xiuminglib.blender package

Submodules

xiuminglib.blender.camera module

xiuminglib.blender.camera.add_camera(xyz=(0, 0, 0), rot_vec_rad=(0, 0, 0), name=None, proj_model='PERSP', f=35, sensor_fit='HORIZONTAL', sensor_width=32, sensor_height=18, clip_start=0.1, clip_end=100)[source]

Adds a camera to the current scene.

Parameters:
  • xyz (tuple, optional) – Location. Defaults to (0, 0, 0).
  • rot_vec_rad (tuple, optional) – Rotations in radians around x, y and z. Defaults to (0, 0, 0).
  • name (str, optional) – Camera object name.
  • proj_model (str, optional) – Camera projection model. Must be 'PERSP', 'ORTHO', or 'PANO'. Defaults to 'PERSP'.
  • f (float, optional) – Focal length in mm. Defaults to 35.
  • sensor_fit (str, optional) – Sensor fit. Must be 'HORIZONTAL' or 'VERTICAL'. See also get_camera_matrix(). Defaults to 'HORIZONTAL'.
  • sensor_width (float, optional) – Sensor width in mm. Defaults to 32.
  • sensor_height (float, optional) – Sensor height in mm. Defaults to 18.
  • clip_start (float, optional) – Near clipping distance. Defaults to 0.1.
  • clip_end (float, optional) – Far clipping distance. Defaults to 100.
Returns:

Camera added.

Return type:

bpy_types.Object

xiuminglib.blender.camera.backproject_to_3d(xys, cam, obj_names=None, world_coords=False)[source]

Backprojects 2D coordinates to 3D.

Since a 2D point could have been projected from any point on a 3D line, this function will return the 3D point at which this line (ray) intersects with an object for the first time.

Parameters:
  • xys (array_like) –

    XY coordinates of length 2 or shape N-by-2, in the following convention:

    (0, 0)
    +------------> (w, 0)
    |           x
    |
    |
    |
    v y (0, h)
    
  • cam (bpy_types.Object) – Camera.
  • obj_names (str or list(str), optional) – Name(s) of object(s) of interest. None means considering all objects.
  • world_coords (bool, optional) – Whether to return world or the object’s local coordinates.
Returns:

  • ray_tos (mathutils.Vector or list(mathutils.Vector)) – Location(s) at which each ray points in the world coordinates, regardless of world_coords. This and the (shared) ray origin (cam.location) determine the rays.
  • xyzs (mathutils.Vector or list(mathutils.Vector)) – Intersection coordinates specified in either the world or the object’s local coordinates, depending on world_coords. None means no intersection.
  • intersect_objnames (str or list(str)) – Name(s) of object(s) responsible for intersections. None means no intersection.
  • intersect_facei (int or list(int)) – Index/indices of the face(s), where the intersection happens.
  • intersect_normals (mathutils.Vector or list(mathutils.Vector)) – Normal vector(s) at the intersection(s) specified in the same space as xyzs.

Return type:

tuple

xiuminglib.blender.camera.correct_sensor_height(cam)[source]

To make render resolutions, sensor size, and pixel aspect ratio comptible.

If render resolutions are \((w_\text{pix}, h_\text{pix})\), sensor sizes are \((w_\text{mm}, h_\text{mm})\), and pixel aspect ratio is \(r\), then \(h_\text{mm}\leftarrow\frac{h_\text{pix}}{w_\text{pix}r}w_\text{mm}\).

Parameters:cam (bpy_types.Object) – Camera.
xiuminglib.blender.camera.easyset(cam, xyz=None, rot_vec_rad=None, name=None, proj_model=None, f=None, sensor_fit=None, sensor_width=None, sensor_height=None)[source]

Sets camera parameters more easily.

See add_camera() for arguments. None will result in no change.

xiuminglib.blender.camera.get_2d_bounding_box(obj, cam)[source]

Gets a 2D bounding box of the object in the camera frame.

This is different from projecting the 3D bounding box to 2D.

Parameters:
  • obj (bpy_types.Object) – Object of interest.
  • cam (bpy_types.Object) – Camera.
Returns:

2D coordinates of the bounding box corners. Of shape 4-by-2. Corners are ordered counterclockwise, following:

(0, 0)
+------------> (w, 0)
|           x
|
|
|
v y (0, h)

Return type:

numpy.ndarray

xiuminglib.blender.camera.get_camera_matrix(cam, keep_disparity=False)[source]

Gets camera matrix, intrinsics, and extrinsics from a camera.

You can ask for a 4-by-4 projection that projects \((x, y, z, 1)\) to \((x, y, 1, d)\), where \(d\) is the disparity, reciprocal of depth.

cam_mat.dot(pts) gives you projections in the following convention:

+------------>
|       proj[:, 0]
|
|
v proj[:, 1]
Parameters:
  • cam (bpy_types.Object) – Camera.
  • keep_disparity (bool, optional) – Whether or not the matrices keep disparity.
Returns:

  • cam_mat (mathutils.Matrix) – Camera matrix, product of intrinsics and extrinsics. 4-by-4 if keep_disparity; else, 3-by-4.
  • int_mat (mathutils.Matrix) – Camera intrinsics. 4-by-4 if keep_disparity; else, 3-by-3.
  • ext_mat (mathutils.Matrix) – Camera extrinsics. 4-by-4 if keep_disparity; else, 3-by-4.

Return type:

tuple

xiuminglib.blender.camera.get_camera_zbuffer(cam, save_to=None, hide=None)[source]

Gets \(z\)-buffer of the camera.

Values are \(z\) components in camera-centered coordinate system, where

  • \(x\) is horizontal;
  • \(y\) is down (to align with the actual pixel coordinates);
  • right-handed: positive \(z\) is look-at direction and means “in front of camera.”

Origin is the camera center, not image plane (one focal length away from origin).

Parameters:
  • cam (bpy_types.Object) – Camera.
  • save_to (str, optional) – Path to which the .exr \(z\)-buffer will be saved. None means don’t save.
  • hide (str or list(str)) – Names of objects to be hidden while rendering this camera’s \(z\)-buffer.
Returns:

Camera \(z\)-buffer.

Return type:

numpy.ndarray

xiuminglib.blender.camera.get_visible_vertices(cam, obj, ignore_occlusion=False, hide=None, method='raycast', perc_eps=1e-06)[source]

Gets vertices that are visible (projected within frame and unoccluded) from camera.

Parameters:
  • cam (bpy_types.Object) – Camera.
  • obj (bpy_types.Object) – Object of interest.
  • ignore_occlusion (bool, optional) – Whether to ignore all occlusion (including self-occlusion). Useful for finding out which vertices fall inside the camera view.
  • hide (str or list(str), optional) – Names of objects to be hidden while rendering this camera’s \(z\)-buffer. No effect if ignore_occlusion.
  • method (str, optional) – Visibility test method: 'raycast' or 'zbuffer'. Ray casting is more robust than comparing the vertex’s depth against \(z\)-buffer (inaccurate when the render resolution is low, or when object’s own depth variation is small compared with its overall depth). The advantage of the \(z\)-buffer, though, is its runtime independent of number of vertices.
  • perc_eps (float, optional) – Threshold for percentage difference between test value \(x\) and true value \(y\). \(x\) is considered equal to \(y\) when \(\frac{|x - y|}{y}\) is smaller. No effect if ignore_occlusion.
Returns:

Indices of vertices that are visible.

Return type:

list

xiuminglib.blender.camera.intrinsics_compatible_with_scene(cam, eps=1e-06)[source]

Checks if camera intrinsic parameters are comptible with the current scene.

Intrinsic parameters include sensor size and pixel aspect ratio, and scene parameters refer to render resolutions and their scale. The entire sensor is assumed active.

Parameters:
  • cam (bpy_types.Object) – Camera object
  • eps (float, optional) – \(\epsilon\) for numerical comparison. Considered equal if \(\frac{|a - b|}{b} < \epsilon\).
Returns:

Check result.

Return type:

bool

xiuminglib.blender.camera.point_camera_to(cam, xyz_target, up=(0, 0, 1))[source]

Points camera to target.

Parameters:
  • cam (bpy_types.Object) – Camera object.
  • xyz_target (array_like) – Target point in world coordinates.
  • up (array_like, optional) – World vector that, when projected, points up in the image plane.

xiuminglib.blender.light module

Add functions in this module usually provide no setter for the lamp’s 3D rotation, because one usually implicitly sets the rotation by pointing the light to an object (and specifying an up vector), by using point_light_to().

xiuminglib.blender.light.add_light_area(xyz=(0, 0, 0), rot_vec_rad=(0, 0, 0), name=None, energy=100, size=0.1)[source]

Adds an area light that emits light rays the lambertian way.

Parameters:
  • xyz (tuple(float), optional) – Location.
  • rot_vec_rad (tuple(float), optional) – Rotations in radians around x, y and z.
  • name (str, optional) – Light name.
  • energy (float, optional) – Light intensity.
  • size (float, optional) – Light size for ray shadow tracing. Use larger values for softer shadows.
Returns:

Light added.

Return type:

bpy_types.Object

xiuminglib.blender.light.add_light_env(env=(1, 1, 1, 1), strength=1, rot_vec_rad=(0, 0, 0), scale=(1, 1, 1))[source]

Adds environment lighting.

Parameters:
  • env (tuple(float) or str, optional) – Environment map. If tuple, it’s RGB or RGBA, each element of which \(\in [0,1]\). Otherwise, it’s the path to an image.
  • strength (float, optional) – Light intensity.
  • rot_vec_rad (tuple(float), optional) – Rotations in radians around x, y and z.
  • scale (tuple(float), optional) – If all changed simultaneously, then no effects.
xiuminglib.blender.light.add_light_point(xyz=(0, 0, 0), name=None, size=0, energy=100)[source]

Adds an omnidirectional point lamp.

Parameters:
  • xyz (tuple(float), optional) – Location.
  • name (str, optional) – Light name.
  • size (float, optional) – Light size; the larger the softer shadows are.
  • energy (float, optional) – Light intensity.
Returns:

Light added.

Return type:

bpy_types.Object

xiuminglib.blender.light.add_light_spot(xyz=(0, 0, 0), name=None, energy=100, shadow_soft_size=0.1, spot_size=0.785, spot_blend=0.15)[source]

Adds a spotlight lamp.

Parameters:
  • xyz (tuple(float), optional) – Location.
  • name (str, optional) – Light name.
  • energy (float, optional) – Light intensity.
  • shadow_soft_size (float, optional) – Light size for raytracing the shadow.
  • spot_size (float, optional) – Angle, in radians, of the spotlight beam.
  • spot_blend (float, optional) – Softness of the spotlight edge.
Returns:

Light added.

Return type:

bpy_types.Object

xiuminglib.blender.light.add_light_sun(xyz=(0, 0, 0), rot_vec_rad=(0, 0, 0), name=None, energy=1, size=0.1)[source]

Adds a sun lamp that emits parallel light rays.

Parameters:
  • xyz (tuple(float), optional) – Location only used to compute light ray direction.
  • rot_vec_rad (tuple(float), optional) – Rotations in radians around x, y and z.
  • name (str, optional) – Light name.
  • energy (float, optional) – Light intensity.
  • size (float, optional) – Light size for ray shadow tracing. Use larger for softer shadows.
Returns:

Light added.

Return type:

bpy_types.Object

xiuminglib.blender.light.point_light_to(light, target)[source]

Points the directional light to a target.

Parameters:
  • light (bpy_types.Object) – Light object.
  • target (tuple(float)) – Target location to which light rays point.

xiuminglib.blender.object module

xiuminglib.blender.object.add_cylinder_between(pt1, pt2, r=0.001, name=None)[source]

Adds a cylinder specified by two end points and radius.

Super useful for visualizing rays in ray tracing while debugging.

Parameters:
  • pt1 (array_like) – World coordinates of point 1.
  • pt2 (array_like) – World coordinates of point 2.
  • r (float, optional) – Cylinder radius.
  • name (str, optional) – Cylinder name.
Returns:

Cylinder added.

Return type:

bpy_types.Object

xiuminglib.blender.object.add_rectangular_plane(center_loc=(0, 0, 0), point_to=(0, 0, 1), size=(2, 2), name=None)[source]

Adds a rectangular plane specified by its center location, dimensions, and where its +z points to.

Parameters:
  • center_loc (array_like, optional) – Plane center location in world coordinates.
  • point_to (array_like, optional) – Point in world coordinates to which plane’s +z points.
  • size (array_like, optional) – Sizes in x and y directions (0 in z).
  • name (str, optional) – Plane name.
Returns:

Plane added.

Return type:

bpy_types.Object

xiuminglib.blender.object.add_sphere(location=(0, 0, 0), scale=1, n_subdiv=2, shade_smooth=False, name=None)[source]

Adds a sphere.

Parameters:
  • location (array_like, optional) – Location of the sphere center.
  • scale (float, optional) – Scale of the sphere.
  • n_subdiv (int, optional) – Control of how round the sphere is.
  • shade_smooth (bool, optional) – Whether to use smooth shading.
  • name (str, optional) – Name of the added sphere.
Returns:

Sphere created.

Return type:

bpy_types.Object

xiuminglib.blender.object.color_vertices(obj, vert_ind, colors)[source]

Colors each vertex of interest with the given color.

Colors are defined for vertex loops, in fact. This function uses the same color for all loops of a vertex. Useful for making a 3D heatmap.

Parameters:
  • obj (bpy_types.Object) – Object.
  • vert_ind (int or list(int)) – Index/indices of vertex/vertices to color.
  • colors (tuple or list(tuple)) – RGB value(s) to paint on vertex/vertices. Values \(\in [0, 1]\). If one tuple, this color will be applied to all vertices. If list of tuples, must be of the same length as vert_ind.
xiuminglib.blender.object.create_mesh(verts, faces, name='new-mesh')[source]

Creates a mesh from vertices and faces.

Parameters:
  • verts (array_like) – Local coordinates of the vertices, of shape N-by-3.
  • faces (list(tuple)) – Faces specified by ordered vertex indices.
  • name (str, optional) – Mesh name.
Returns:

Mesh data created.

Return type:

bpy_types.Mesh

xiuminglib.blender.object.create_object_from_mesh(mesh_data, obj_name='new-obj', location=(0, 0, 0), rotation_euler=(0, 0, 0), scale=(1, 1, 1))[source]

Creates object from mesh data.

Parameters:
  • mesh_data (bpy_types.Mesh) – Mesh data.
  • obj_name (str, optional) – Object name.
  • location (tuple, optional) – Object location in world coordinates.
  • rotation_euler (tuple, optional) – Object rotation in radians.
  • scale (tuple, optional) – Object scale.
Returns:

Object created.

Return type:

bpy_types.Object

xiuminglib.blender.object.export_object(obj_names, model_path, axis_forward=None, axis_up=None)[source]

Exports Blender object(s) to a file.

Parameters:
  • obj_names (str or list(str)) – Object name(s) to export. Must be a single string if output format is .ply.
  • model_path (str) – Output .obj or .ply path.
  • axis_forward (str, optional) – Which direction is forward. For .obj, the default is '-Z', and 'Y' for .ply.
  • axis_up (str, optional) – Which direction is upward. For .obj, the default is 'Y', and 'Z' for .ply.
Writes
  • Exported model file, possibly accompanied by a material file.
xiuminglib.blender.object.get_bmesh(obj)[source]

Gets Blender mesh data from object.

Parameters:obj (bpy_types.Object) – Object.
Returns:Blender mesh data.
Return type:BMesh
xiuminglib.blender.object.get_object(otype, any_ok=False)[source]

Gets the handle of the only (or any) object of the given type.

Parameters:
  • otype (str) – Object type: 'MESH', 'CAMERA', 'LAMP' or any string a_bpy_obj.type may return.
  • any_ok (bool, optional) – Whether it’s ok to grab any object when there exist multiple ones matching the given type. If False, there must be exactly one object of the given type.
Returns:

bpy_types.Object.

xiuminglib.blender.object.import_object(model_path, axis_forward='-Z', axis_up='Y', rot_mat=((1, 0, 0), (0, 1, 0), (0, 0, 1)), trans_vec=(0, 0, 0), scale=1, merge=False, name=None)[source]

Imports external object to current scene, the low-level way.

Parameters:
  • model_path (str) – Path to object to add.
  • axis_forward (str, optional) – Which direction is forward.
  • axis_up (str, optional) – Which direction is upward.
  • rot_mat (array_like, optional) – 3-by-3 rotation matrix preceding translation.
  • trans_vec (array_like, optional) – 3D translation vector following rotation.
  • scale (float, optional) – Scale of the object.
  • merge (bool, optional) – Whether to merge objects into one.
  • name (str, optional) – Object name after import.
Returns:

Imported object(s).

Return type:

bpy_types.Object or list(bpy_types.Object)

xiuminglib.blender.object.raycast(obj_bvhtree, ray_from_objspc, ray_to_objspc)[source]

Casts a ray to an object.

Parameters:
  • obj_bvhtree (mathutils.bvhtree.BVHTree) – Constructed BVH tree of the object.
  • ray_from_objspc (mathutils.Vector) – Ray origin, in object’s local coordinates.
  • ray_to_objspc (mathutils.Vector) – Ray goes through this point, also specified in the object’s local coordinates. Note that the ray doesn’t stop at this point, and this is just for computing the ray direction.
Returns:

  • hit_loc (mathutils.Vector) – Hit location on the object, in the object’s local coordinates. None means no intersection.
  • hit_normal (mathutils.Vector) – Normal of the hit location, also in the object’s local coordinates.
  • hit_fi (int) – Index of the face where the hit happens.
  • ray_dist (float) – Distance that the ray has traveled before hitting the object. If ray_to_objspc is a point on the object surface, then this return value is useful for checking for self occlusion.

Return type:

tuple

xiuminglib.blender.object.remove_objects(name_pattern, regex=False)[source]

Removes object(s) from current scene.

Parameters:
  • name_pattern (str) – Name or name pattern of object(s) to remove.
  • regex (bool, optional) – Whether to interpret name_pattern as a regex.
xiuminglib.blender.object.select_mesh_elements_by_vertices(obj, vert_ind, select_type)[source]

Selects vertices or their associated edges/faces in edit mode.

Parameters:
  • obj (bpy_types.Object) – Object.
  • vert_ind (int or list(int)) – Vertex index/indices.
  • select_type (str) – Type of mesh elements to select: 'vertex', 'edge' or 'face'.
xiuminglib.blender.object.setup_emission_nodetree(obj, texture=(1, 1, 1, 1), strength=1, hide=False)[source]

Sets up an emission node tree for the object.

Parameters:
  • obj (bpy_types.Object) – Object (maybe bundled with texture map).
  • texture (str or tuple, optional) – If string, must be 'bundled' or path to the texture image. If tuple, must be of 4 floats \(\in [0, 1]\) as RGBA values.
  • strength (float, optional) – Emission strength.
  • hide (bool, optional) – Useful for hiding the emissive object (but keeping the light of course).
xiuminglib.blender.object.setup_holdout_nodetree(obj)[source]

Sets up a holdout node tree for the object.

Parameters:obj (bpy_types.Object) – Object bundled with texture map.
xiuminglib.blender.object.setup_retroreflective_nodetree(obj, texture, roughness=0, glossy_weight=0.1)[source]

Sets up a retroreflective texture node tree.

Bundled texture can be an external texture map (carelessly mapped) or a pure color. Mathematically, the BRDF model is a mixture of a diffuse BRDF and a glossy BRDF using incoming light directions as normals.

Parameters:
  • obj (bpy_types.Object) – Object, optionally bundled with texture map.
  • texture (str or tuple) – If string, must be 'bundled' or path to the texture image. If tuple, must be of 4 floats \(\in [0, 1]\) as RGBA values.
  • roughness (float, optional) – Roughness for both the glossy and diffuse shaders.
  • glossy_weight (float, optional) – Mixture weight for the glossy shader.
xiuminglib.blender.object.setup_simple_nodetree(obj, texture, shader_type, roughness=0)[source]

Sets up a simple (diffuse and/or glossy) node tree.

Texture can be an bundled texture map, a path to an external texture map, or simply a pure color. If a path to an external image, and UV coordinates are given (e.g., in the geometry .obj file), then they will be used. If they are not given, texture mapping will be done carelessly, with automatically generated UV coordinates. See private function _make_texture_node() for how this is done.

Parameters:
  • obj (bpy_types.Object) – Object, optionally bundled with texture map.
  • texture (str or tuple) – If string, must be 'bundled' or path to the texture image. If tuple, must be of 4 floats \(\in [0, 1]\) as RGBA values.
  • shader_type (str) – Either 'diffuse' or 'glossy'.
  • roughness (float, optional) – If diffuse, the roughness in Oren-Nayar, 0 gives Lambertian. If glossy, 0 means perfectly reflective.
xiuminglib.blender.object.smart_uv_unwrap(obj, area_weight=0.0)[source]

UV unwrapping using Blender’s smart projection.

A vertex may map to multiple UV locations, but each loop maps to exactly one UV location. If a face uses M vertices, then it has M loops, so a vertex may belong to multiple loops, each of which has one UV location.

Note

If a vertex belongs to no face, it doesn’t get a UV coordinate, so don’t assume you can get a UV for any given vertex index.

Parameters:
  • obj (bpy_types.Object) – Object to UV unwrap.
  • area_weight (float, optional) – Area weight.
Returns:

Dictionary with its keys being the face indices, and values being 2D arrays with four columns containing the corresponding face’s loop indices, vertex indices, \(u\), and \(v\).

UV coordinate convention:

(0, 1)
    ^ v
    |
    |
    |
    |
    +-----------> (1, 0)
(0, 0)        u

Return type:

dict(numpy.ndarray)

xiuminglib.blender.object.subdivide_mesh(obj, n_subdiv=2)[source]

Subdivides mesh of object.

Parameters:
  • obj (bpy_types.Object) – Object whose mesh is to be subdivided.
  • n_subdiv (int, optional) – Number of subdivision levels.

xiuminglib.blender.render module

xiuminglib.blender.render.easyset(w=None, h=None, n_samples=None, ao=None, color_mode=None, file_format=None, color_depth=None, sampling_method=None, n_aa_samples=None)[source]

Sets some of the scene attributes more easily.

Parameters:
  • w (int, optional) – Width of render in pixels.
  • h (int, optional) – Height of render in pixels.
  • n_samples (int, optional) – Number of samples.
  • ao (bool, optional) – Ambient occlusion.
  • color_mode (str, optional) – Color mode of rendering: 'BW', 'RGB', or 'RGBA'.
  • file_format (str, optional) – File format of the render: 'PNG', 'OPEN_EXR', etc.
  • color_depth (str, optional) – Color depth of rendering: '8' or '16' for .png; '16' or '32' for .exr.
  • sampling_method (str, optional) – Method to sample light and materials: 'PATH' or 'BRANCHED_PATH'.
  • n_aa_samples (int, optional) – Number of anti-aliasing samples (used with 'BRANCHED_PATH').
xiuminglib.blender.render.render(outpath, cam=None, obj_names=None, alpha=True, text=None)[source]

Renders current scene with cameras in scene.

Parameters:
  • outpath (str) – Path to save the render to. Should end with either .exr or .png.
  • cam (bpy_types.Object, optional) – Camera through which scene is rendered. If None, use the only camera in scene.
  • obj_names (str or list(str), optional) – Name(s) of object(s) of interest. If None, all objects are of interest and will appear in the render.
  • alpha (bool, optional) – Whether to render the alpha channel.
  • text (dict, optional) –

    What text to be overlaid on image and how, following the format:

    {
        'contents': "Hello World!",
        'bottom_left_corner': (50, 50),
        'font_scale': 1,
        'bgr': (255, 0, 0),
        'thickness': 2,
    }
    
Writes
  • A 32-bit .exr or 16-bit .png image.
xiuminglib.blender.render.render_alpha(outpath, cam=None, obj_names=None, samples=1000)[source]

Renders binary or soft mask of objects from the specified camera.

Parameters:
  • outpath (str) – Path to save the render to. Should end with .png.
  • cam (bpy_types.Object, optional) – Camera through which scene is rendered. If None, there must be just one camera in scene.
  • obj_names (str or list(str), optional) – Name(s) of object(s) of interest. None means all objects.
  • samples (int, optional) – Samples per pixel. \(1\) gives a hard mask, and \(\gt 1\) gives a soft (anti-aliased) mask.
Writes
  • A 16-bit three-channel .png mask, where bright indicates foreground.
xiuminglib.blender.render.render_depth(outprefix, cam=None, obj_names=None, ray_depth=False)[source]

Renders raw depth map in .exr of the specified object(s) from the specified camera.

The EXR data contain an aliased \(z\) map and an anti-aliased alpha map.

Parameters:
  • outprefix (str) – Where to save the .exr maps to, e.g., '~/depth'.
  • cam (bpy_types.Object, optional) – Camera through which scene is rendered. If None, there must be the just one camera in the scene.
  • obj_names (str or list(str), optional) – Name(s) of object(s) of interest. None means all objects.
  • ray_depth (bool, optional) – Whether to render ray or plane depth.
Writes
  • A 32-bit .exr depth map w/o anti-aliasing, located at outprefix + '_z.exr'.
  • A 32-bit .exr alpha map w/ anti-aliasing, located at outprefix + '_a.exr'.

Todo

Ray depth.

xiuminglib.blender.render.render_lighting_passes(outpath, cam=None, obj_names=None, n_samples=None, select=None)[source]

Renders select Cycles’ lighting passes of the specified object(s) from the specified camera.

Data are in a single multi-layer .exr file. See the code below for what channels are rendered.

Parameters:
  • outpath (str) – Where to save the lighting passes to. Should end with .exr.
  • cam (bpy_types.Object, optional) – Camera through which scene is rendered. If None, there must be only one camera in scene.
  • obj_names (str or list(str), optional) – Name(s) of object(s) of interest. None means all objects.
  • n_samples (int, optional) – Number of samples per pixel. Useful when you want a value different than other renderings; None means using the current value.
  • select (list(str), optional) – Render only this list of passes. None means rendering all passes: diffuse_direct, diffuse_indirect, diffuse_color, glossy_direct, glossy_indirect, and glossy_color.
Writes
  • A 32-bit .exr multi-layer image containing the lighting passes.
xiuminglib.blender.render.render_normal(outpath, cam=None, obj_names=None, outpath_refball=None, world_coords=False)[source]

Renders raw normal map in .exr of the specified object(s) from the specified camera.

RGB at each pixel is the (almost unit) normal vector at that location.

Parameters:
  • outpath (str) – The .exr path (so data are raw values, not integer values) we save the normal map to.
  • cam (bpy_types.Object, optional) – Camera through which scene is rendered. If None, there must be only one camera in scene.
  • obj_names (str or list(str), optional) – Name(s) of object(s) of interest. None means all objects.
  • outpath_refball (str, optional) – The .exr path to save the reference ball’s normals to. None means not rendering the reference ball.
  • world_coords (bool, optional) – Whether to render normals in the world or negated camera space.

Warning

TL;DR

If you want camera-space normal maps, you need to negate the normal map after loading it from the .exr file this function writes. Otherwise, those normals live in a space that has all three axes flipped w.r.t. the camera’s local space.

The Details

If you want world-space normals, then easy; I’ll just use Cycles, and the normals are automatically in the world space. If camera-space normals are what you want, I’ll use Blender Internal (BI), but there’s some complication taken care of under the hood.

BI renders normals “in the camera space.” I verified this by keeping my scene intact, but having my camera rotating a bit; indeed, the normal vectors of a cube went from “round values”, such as \((0, 0, 1)\), to “non-round values”, such as \((0.02, 0.03, 0.99)\).

But what precisely is this “camera space” (denoted by \(S\))? Is it really just the camera’s local space? How do we go from \(S\) to the world coordinate system, and possibly to another space therefrom? Here’s my exploration.

I put a camera at the scene center, and had it pointing, head-on, to one face of a default cube (so the camera saw just that face – no other faces). I rendered the normals with BI: the raw RGB value is \((0, 0, −1)\). OK, so the normal vector pointing out of the screen to my eyes is \(S\)’s \(−z\). Hence, \(S\)’s \(+z\) points into the screen.

Then I rotated the cube by just a little, so my camera got to see a little bit of the side faces it couldn’t see before. The normal vector pointing to the left is \((1, 0, 0)\); so the \(+x\) of \(S\) points to the left, tangent to the screen. Similarly, I found out the \(+y\) points downwards, also tangent to the screen.

But wait, the three axes don’t even form a right-handed system; they form a left-handed one! This is so strange. Oh, if we negate all the axes, then we get a right-handed system. Would this negated system be the camera’s local space (as in an object’s local coordinate system)?

It is! After eyeballing the camera’s local space axes, I found they are exactly the flipped axes of \(S\). Therefore, when camera-space normals are asked for, I first render them out using BI, and then have to flip the signs to give the camera-space normals, which you can then transform to other spaces correctly with transformation matrices.

Writes
  • A 32-bit .exr normal map of the object(s) of interest.
  • Another 32-bit .exr normal map of the reference ball, if asked for.
xiuminglib.blender.render.set_cycles(w=None, h=None, n_samples=None, max_bounces=None, min_bounces=None, transp_bg=None, color_mode=None, color_depth=None)[source]

Sets up Cycles as rendering engine.

None means no change.

Parameters:
  • w (int, optional) – Width of render in pixels.
  • h (int, optional) – Height of render in pixels.
  • n_samples (int, optional) – Number of samples.
  • max_bounces (int, optional) – Maximum number of light bounces. Setting max_bounces to 0 for direct lighting only.
  • min_bounces (int, optional) – Minimum number of light bounces.
  • transp_bg (bool, optional) – Whether world background is transparent.
  • color_mode (str, optional) – Color mode: 'BW', 'RGB' or 'RGBA'.
  • color_depth (str, optional) – Color depth: '8' or '16'.

xiuminglib.blender.scene module

xiuminglib.blender.scene.open_blend(inpath)[source]

Opens a .blend file.

Parameters:inpath (str) – E.g., '~/foo.blend'.
xiuminglib.blender.scene.save_blend(outpath=None, delete_overwritten=False)[source]

Saves current scene to a .blend file.

Parameters:
  • outpath (str, optional) – Path to save the scene to, e.g., '~/foo.blend'. None means saving to the current file.
  • delete_overwritten (bool, optional) – Whether to delete or keep as .blend1 the same-name file.
Writes
  • A .blend file.

xiuminglib.blender.util module

xiuminglib.blender.util.cursor_to(loc)[source]

Moves the cursor to the given 3D location.

Useful for inspecting where a 3D point is in the scene, to do which you first use this function, save the scene, and open the scene in GUI.

Parameters:loc (array_like) – 3D coordinates, of length 3.