Skip to content

Instantly share code, notes, and snippets.

@linj121
Last active September 23, 2024 21:23
Show Gist options
  • Save linj121/7239dc47c13d59b6eadd59ed4f1141a8 to your computer and use it in GitHub Desktop.
Save linj121/7239dc47c13d59b6eadd59ed4f1141a8 to your computer and use it in GitHub Desktop.
Project 3d vertices onto the 2d plane of a 1x1x1 view camera
import matplotlib.pyplot as plt
class Vec2:
x: float
y: float
def __init__(self, x, y):
self.x = x
self.y = y
def __truediv__(self, other):
if (type(other) is int or type(other) is float):
return Vec2(self.x / other, self.y / other)
def __repr__(self):
return self.__str__()
def __str__(self):
return "( x: " + str(self.x) + ", y: " + str(self.y) + " )"
class Vec3:
x: float
y: float
z: float
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __sub__(self, other):
return Vec3(self.x - other.x, self.y - other.y, self.z - other.z)
def __repr__(self):
return self.__str__()
def __str__(self):
return "( x: " + str(self.x) + ", y: " + str(self.y) + ", z: " + str(self.z) + " )"
def getUV(vertices, cameraPos):
uv = dict()
for name, vec3 in vertices.items():
relativeVec = vec3 - cameraPos
uv[name] = Vec2(relativeVec.x, relativeVec.y) / relativeVec.z
return uv
def getUVEdges(uv, edges):
uvEdges = dict()
for edge in edges:
uvEdges[edge] = (uv[edge[0]], uv[edge[1]])
return uvEdges
def drawEdges(uvEdges):
plt.figure(figsize=(6,6))
for line, (vec2A, vec2B) in uvEdges.items():
print(line, vec2A, vec2B)
plt.plot([vec2A.x, vec2B.x], [vec2A.y, vec2B.y], marker='o', label=line)
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("3D View")
plt.legend()
plt.grid(True)
plt.show()
if __name__ == "__main__":
# vertices
data = {
'A': Vec3( 1, 1, 1),
'B': Vec3(-1, 1, 1),
'C': Vec3( 1,-1, 1),
'D': Vec3(-1,-1, 1),
'E': Vec3( 1, 1,-1),
'F': Vec3(-1, 1,-1),
'G': Vec3( 1,-1,-1),
'H': Vec3(-1,-1,-1)
}
# edges
edges = [
'AB', 'CD', 'EF', 'GH',
'AC', 'BD', 'EG', 'FH',
'AE', 'CG', 'BF', 'DH'
]
# camera position
camera = Vec3(2,3,5)
uv = getUV(data, camera)
uvEdges = getUVEdges(uv, edges)
drawEdges(uvEdges)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment