obj_to_rust.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #!/usr/bin/python
  2. import sys
  3. COLOR = "[0., 1., 1., 1.]"
  4. class Obj:
  5. def __init__(self, name):
  6. self.name = name
  7. self.v = []
  8. self.f = []
  9. def push_vert(self, args):
  10. assert len(args) == 3
  11. (x, y, z) = [float(v) for v in args]
  12. assert y == 0
  13. vert = (x, z)
  14. self.v.append(vert)
  15. def push_face(self, args):
  16. idxs = [arg.split("/")[0] for arg in args]
  17. assert len(idxs) == 3
  18. idxs = [int(idx) - 1 for idx in idxs]
  19. for idx in idxs:
  20. assert idx < len(self.v)
  21. self.f.extend(idxs)
  22. def parse_obj(fname):
  23. objs = []
  24. obj = None
  25. for line in open(fname):
  26. line = line.rstrip("\n")
  27. if line[0] == '#':
  28. continue
  29. line = line.split(" ")
  30. cmd = line[0]
  31. args = line[1:]
  32. match cmd:
  33. case 'o':
  34. if obj is not None:
  35. objs.append(obj)
  36. name = args[0]
  37. #print(f"New object {name}")
  38. obj = Obj(name)
  39. continue
  40. case 'v':
  41. obj.push_vert(args)
  42. case 'f':
  43. obj.push_face(args)
  44. case _:
  45. #print(f"Skipping {cmd}: {args}")
  46. pass
  47. if obj is not None:
  48. objs.append(obj)
  49. return objs
  50. def output(obj):
  51. name = obj.name
  52. print("use crate::ui::{VectorShape, ShapeVertex};")
  53. print(f"pub fn create_{name}() -> VectorShape {{")
  54. print(" VectorShape {")
  55. print(" verts: vec![")
  56. for (x, y) in obj.v:
  57. print(f" ShapeVertex::from_xy({x}, {y}, {COLOR}),")
  58. print(" ],")
  59. indices = ", ".join([str(f) for f in obj.f])
  60. print(f" indices: vec![{indices}]")
  61. print(" }")
  62. print("}")
  63. def main(argv):
  64. if len(argv) != 2:
  65. print("obj_to_rust OBJFILE", file=sys.stderr)
  66. return -1
  67. objs = parse_obj(argv[1])
  68. for obj in objs:
  69. output(obj)
  70. return 0
  71. if __name__ == "__main__":
  72. sys.exit(main(sys.argv))