summaryrefslogtreecommitdiff
path: root/megapixels/commands/misc/obj2ply.py
blob: e3e18e54cc2b3c83e6122db33f76facfe88d09ca (plain)
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
#!/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.add_argument('--float_colors', action='store_true', help='pass if RGB colors are floats, not ints, in the obj')
@click.add_argument('--unwind', action='store_true', help='pass to reverse winding order on faces (if surface normals are upside down)')
@click.add_argument('--flip_y', action='store_true', help='flip Y axis')
@click.add_argument('-i', '--input_fn', required=True, help='input OBJ filename')
@click.add_argument('-o', '--output_fn', help='output PLY filename')
@click.pass_context
def cli(ctx, float_colors, unwind, flip_y, 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 flip_y:
          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")