obja/decimate.py

68 lines
2.0 KiB
Python
Raw Normal View History

2021-07-22 15:19:40 +02:00
#!/usr/bin/env python
import obja
import numpy as np
import sys
class Decimater(obja.Model):
"""
A simple class that decimates a 3D model stupidly.
"""
def __init__(self):
super().__init__()
self.deleted_faces = set()
def contract(self, output):
"""
Decimates the model stupidly, and write the resulting obja in output.
"""
operations = []
2021-09-27 14:01:01 +02:00
for (vertex_index, vertex) in enumerate(self.vertices):
operations.append(('ev', vertex_index, vertex + 0.25))
2021-07-22 15:19:40 +02:00
# Iterate through the vertex
for (vertex_index, vertex) in enumerate(self.vertices):
2021-09-27 14:01:01 +02:00
# Iterate through the faces
2021-07-22 15:19:40 +02:00
for (face_index, face) in enumerate(self.faces):
2021-09-27 14:01:01 +02:00
# Delete any face related to this vertex
2021-07-22 15:19:40 +02:00
if face_index not in self.deleted_faces:
2021-09-27 14:01:01 +02:00
if vertex_index in [face.a,face.b,face.c]:
self.deleted_faces.add(face_index)
# Add the instruction to operations stack
operations.append(('face', face_index, face))
2021-07-22 15:19:40 +02:00
# Delete the vertex
operations.append(('vertex', vertex_index, vertex))
# To rebuild the model, run operations in reverse order
operations.reverse()
2021-09-27 14:01:01 +02:00
# Write the result in output file
output_model = obja.Output(output, random_color=True)
2021-07-22 15:19:40 +02:00
for (ty, index, value) in operations:
if ty == "vertex":
output_model.add_vertex(index, value)
2021-09-27 14:01:01 +02:00
elif ty == "face":
output_model.add_face(index, value)
2021-07-22 15:19:40 +02:00
else:
2021-09-27 14:01:01 +02:00
output_model.edit_vertex(index, value)
2021-07-22 15:19:40 +02:00
def main():
"""
Runs the program on the model given as parameter.
"""
np.seterr(invalid = 'raise')
model = Decimater()
model.parse_file('exemple/suzanne.obj')
with open('exemple/suzanne.obja', 'w') as output:
model.contract(output)
if __name__ == '__main__':
main()