#!/usr/bin/python """ Convert an OBJ 3D model (with vertex color) to a PLY file, which can be read by the draco_encoder. """ import click @click.command() @click.option('-c', '--float_colors/--int_colors', 'float_colors', default=False, help='pass if RGB colors are floats, not ints, in the obj') @click.option('-u', '--unwind/--wind', 'unwind', default=False, help='pass to reverse winding order on faces (if surface normals are upside down)') @click.option('-y', '--flip_y/--no_flip_y', 'flip_y', default=False, help='flip Y axis') @click.option('-z', '--flip_z/--no_flip_z', 'flip_z', default=False, help='flip Z axis') @click.option('-s', '--swap_xy/--no_swap_xy', 'swap_xy', default=False, help='swap x/y axes so things rotate correctly') @click.option('-z', '--swap_xz/--no_swap_xz', 'swap_xz', default=False, help='swap x/z axes so things rotate correctly') @click.option('-i', '--input_fn', required=True, help='input OBJ filename') @click.option('-o', '--output_fn', help='output PLY filename') @click.pass_context def cli(ctx, float_colors, unwind, flip_y, flip_z, swap_xy, swap_xz, input_fn, output_fn): """ click command for converting OBJ to PLY """ ply_header = """ply format ascii 1.0 element vertex {} property float x property float y property float z property uchar red property uchar green property uchar blue element face {} property list uchar int vertex_index end_header """ if output_fn is None: output_fn = input_fn.replace('.obj', '.ply') with open(input_fn, 'r') as f: i = 0 vertexes = [] faces = [] for line in f.readlines(): N = line.strip().split(' ') if N[0] == 'v': if swap_xy: tmp = N[2] N[2] = N[1] N[1] = tmp if flip_y: N[2] = str(float(N[2]) * -1) if swap_xz: tmp = N[3] N[3] = N[1] N[1] = tmp if flip_z: N[2] = str(float(N[2]) * -1) if float_colors: vertexes.append([ N[1], N[2], N[3], str(int(255 * float(N[4]))), str(int(255 * float(N[5]))), str(int(255 * float(N[6]))), ]) else: vertexes.append(N[1:]) if N[0] == 'f': if unwind: faces.append([ "3", str(int(N[3]) - 1), str(int(N[2]) - 1), str(int(N[1]) - 1), ]) else: faces.append([ "3", str(int(N[1]) - 1), str(int(N[2]) - 1), str(int(N[3]) - 1), ]) with open(output_fn, 'w') as out_file: out_file.write(ply_header.format(len(vertexes), len(faces))) for v in vertexes: out_file.write(" ".join(v) + "\n") for f in faces: out_file.write(" ".join(f) + "\n")