code
stringlengths 1
5.19M
| package
stringlengths 1
81
| path
stringlengths 9
304
| filename
stringlengths 4
145
|
---|---|---|---|
from models_converter.interfaces.writer_interface import WriterInterface
from models_converter.interfaces.parser_interface import ParserInterface
__all__ = [
'WriterInterface',
'ParserInterface'
]
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/interfaces/__init__.py | __init__.py |
from typing import Literal
class Writer:
def __init__(self, endian: Literal['big', 'little'] = 'big'):
self.endian = endian
self.buffer = b''
def write(self, data: bytes) -> None:
self.buffer += data
def writeUInteger(self, integer: int, length: int = 1) -> None:
self.buffer += integer.to_bytes(length, self.endian, signed=False)
def writeInteger(self, integer: int, length: int = 1) -> None:
self.buffer += integer.to_bytes(length, self.endian, signed=True)
def writeUInt64(self, integer: int) -> None:
self.writeUInteger(integer, 8)
def writeInt64(self, integer: int) -> None:
self.writeInteger(integer, 8)
def writeFloat(self, floating: float) -> None:
exponent = 0
sign = 1
if floating == 0:
self.writeUInt32(0)
else:
if floating < 0:
sign = -1
floating = -floating
if floating >= 2 ** -1022:
value = floating
while value < 1:
exponent -= 1
value *= 2
while value >= 2:
exponent += 1
value /= 2
mantissa = floating / 2 ** exponent
exponent += 127
as_integer_bin = '0'
if sign == -1:
as_integer_bin = '1'
as_integer_bin += bin(exponent)[2:].zfill(8)
mantissa_bin = ''
for x in range(24):
bit = '0'
if mantissa >= 1 / 2 ** x:
mantissa -= 1 / 2 ** x
bit = '1'
mantissa_bin += bit
mantissa_bin = mantissa_bin[1:]
as_integer_bin += mantissa_bin
as_integer = int(as_integer_bin, 2)
self.writeUInt32(as_integer)
def writeUInt32(self, integer: int) -> None:
self.writeUInteger(integer, 4)
def writeInt32(self, integer: int) -> None:
self.writeInteger(integer, 4)
def writeNUInt16(self, integer: float) -> None:
self.writeUInt16(round(integer * 65535))
def writeUInt16(self, integer: int) -> None:
self.writeUInteger(integer, 2)
def writeNInt16(self, integer: float) -> None:
self.writeInt16(round(integer * 32512))
def writeInt16(self, integer: int) -> None:
self.writeInteger(integer, 2)
def writeUInt8(self, integer: int) -> None:
self.writeUInteger(integer)
def writeInt8(self, integer: int) -> None:
self.writeInteger(integer)
def writeBool(self, boolean: bool) -> None:
if boolean:
self.writeUInt8(1)
else:
self.writeUInt8(0)
writeUInt = writeUInteger
writeInt = writeInteger
writeULong = writeUInt64
writeLong = writeInt64
writeNUShort = writeNUInt16
writeNShort = writeNInt16
writeUShort = writeUInt16
writeShort = writeInt16
writeUByte = writeUInt8
writeByte = writeInt8
def writeChar(self, string: str) -> None:
for char in list(string):
self.buffer += char.encode('utf-8')
def writeString(self, string: str) -> None:
if string is None:
string = ''
encoded = string.encode('utf-8')
self.writeUShort(len(encoded))
self.buffer += encoded
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/utilities/writer.py | writer.py |
import typing
class Reader:
def __init__(self, buffer: bytes, endian: typing.Literal['big', 'little'] = 'big'):
self.buffer = buffer
self.endian = endian
self.i = 0
def read(self, length: int = 1) -> bytes:
result = self.buffer[self.i:self.i + length]
self.i += length
return result
def readUInteger(self, length: int = 1) -> int:
result = 0
for x in range(length):
byte = self.buffer[self.i]
bit_padding = x * 8
if self.endian == 'big':
bit_padding = (8 * (length - 1)) - bit_padding
result |= byte << bit_padding
self.i += 1
return result
def readInteger(self, length: int = 1) -> int:
integer = self.readUInteger(length)
result = integer
if integer > 2 ** (length * 8) / 2:
result -= 2 ** (length * 8)
return result
def readUInt64(self) -> int:
return self.readUInteger(8)
def readInt64(self) -> int:
return self.readInteger(8)
def readFloat(self) -> float:
as_int = self.readUInt32()
binary = bin(as_int)
binary = binary[2:].zfill(32)
sign = -1 if binary[0] == '1' else 1
exponent = int(binary[1:9], 2) - 127
mantissa_base = binary[9:]
mantissa_bin = '1' + mantissa_base
mantissa = 0
val = 1
if exponent == -127:
if mantissa_base[1] == -1:
return 0
else:
exponent = -126
mantissa_bin = '0' + mantissa_base
for char in mantissa_bin:
mantissa += val * int(char)
val = val / 2
result = sign * 2 ** exponent * mantissa
return result
def readUInt32(self) -> int:
return self.readUInteger(4)
def readInt32(self) -> int:
return self.readInteger(4)
def readNUInt16(self) -> float:
return self.readUInt16() / 65535
def readUInt16(self) -> int:
return self.readUInteger(2)
def readNInt16(self) -> float:
return self.readInt16() / 32512
def readInt16(self) -> int:
return self.readInteger(2)
def readUInt8(self) -> int:
return self.readUInteger()
def readInt8(self) -> int:
return self.readInteger()
def readBool(self) -> bool:
if self.readUInt8() >= 1:
return True
else:
return False
readUInt = readUInteger
readInt = readInteger
readULong = readUInt64
readLong = readInt64
readNUShort = readNUInt16
readNShort = readNInt16
readUShort = readUInt16
readShort = readInt16
readUByte = readUInt8
readByte = readInt8
def readChars(self, length: int = 1) -> str:
return self.read(length).decode('utf-8')
def readString(self) -> str:
length = self.readUShort()
return self.readChars(length)
def tell(self) -> int:
return self.i
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/utilities/reader.py | reader.py |
def remove_prefix(string: str, prefix: str):
if string.startswith(prefix):
return string[len(prefix):]
return string
def remove_suffix(string: str, suffix: str):
if string.endswith(suffix):
return string[:len(string) - len(suffix)]
return string
__all__ = [
'remove_prefix',
'remove_suffix',
'writer',
'reader',
'math',
'matrix'
]
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/utilities/__init__.py | __init__.py |
class Quaternion:
def __init__(self, x: float = 0, y: float = 0, z: float = 0, w: float = 1):
self.x = x
self.y = y
self.z = z
self.w = w
def clone(self):
return Quaternion(self.x, self.y, self.z, self.w)
def __repr__(self):
return f'({self.x:.2f}, {self.y:.2f}, {self.z:.2f}, {self.w:.2f})'
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/utilities/math/quaternion.py | quaternion.py |
class Vector3:
def __init__(self, x: float = 0, y: float = 0, z: float = 0):
self.x = x
self.y = y
self.z = z
def clone(self):
return Vector3(self.x, self.y, self.z)
def __repr__(self):
return f'({self.x:.2f}, {self.y:.2f}, {self.z:.2f})'
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/utilities/math/vector3.py | vector3.py |
from models_converter.utilities.math.quaternion import Quaternion
from models_converter.utilities.math.vector3 import Vector3
__all__ = [
'Quaternion',
'Vector3'
]
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/utilities/math/__init__.py | __init__.py |
from .matrix3x3 import Matrix3x3
from . import Matrix
from ..math import Vector3, Quaternion
class Matrix4x4(Matrix):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.translation_matrix = None
self.rotation_matrix = None
self.scale_matrix = None
def determinant(self):
value1_1 = self.matrix[0][0]
value1_2 = self.matrix[0][1]
value1_3 = self.matrix[0][2]
value1_4 = self.matrix[0][3]
value2_1 = self.matrix[1][0]
value2_2 = self.matrix[1][1]
value2_3 = self.matrix[1][2]
value2_4 = self.matrix[1][3]
value3_1 = self.matrix[2][0]
value3_2 = self.matrix[2][1]
value3_3 = self.matrix[2][2]
value3_4 = self.matrix[2][3]
value4_1 = self.matrix[3][0]
value4_2 = self.matrix[3][1]
value4_3 = self.matrix[3][2]
value4_4 = self.matrix[3][3]
matrix1 = Matrix3x3(matrix=(
(value2_2, value2_3, value2_4),
(value3_2, value3_3, value3_4),
(value4_2, value4_3, value4_4)
))
matrix2 = Matrix3x3(matrix=(
(value2_1, value2_3, value2_4),
(value3_1, value3_3, value3_4),
(value4_1, value4_3, value4_4)
))
matrix3 = Matrix3x3(matrix=(
(value2_1, value2_2, value2_4),
(value3_1, value3_2, value3_4),
(value4_1, value4_2, value4_4)
))
matrix4 = Matrix3x3(matrix=(
(value2_1, value2_2, value2_3),
(value3_1, value3_2, value3_3),
(value4_1, value4_2, value4_3)
))
det = value1_1 * matrix1.determinant()
det -= value1_2 * matrix2.determinant()
det += value1_3 * matrix3.determinant()
det -= value1_4 * matrix4.determinant()
return det
def cofactor(self):
value1_1 = self.matrix[0][0]
value1_2 = self.matrix[0][1]
value1_3 = self.matrix[0][2]
value1_4 = self.matrix[0][3]
value2_1 = self.matrix[1][0]
value2_2 = self.matrix[1][1]
value2_3 = self.matrix[1][2]
value2_4 = self.matrix[1][3]
value3_1 = self.matrix[2][0]
value3_2 = self.matrix[2][1]
value3_3 = self.matrix[2][2]
value3_4 = self.matrix[2][3]
value4_1 = self.matrix[3][0]
value4_2 = self.matrix[3][1]
value4_3 = self.matrix[3][2]
value4_4 = self.matrix[3][3]
matrix1 = Matrix3x3(matrix=(
(value2_2, value2_3, value2_4),
(value3_2, value3_3, value3_4),
(value4_2, value4_3, value4_4)
))
matrix2 = Matrix3x3(matrix=(
(value2_1, value2_3, value2_4),
(value3_1, value3_3, value3_4),
(value4_1, value4_3, value4_4)
))
matrix3 = Matrix3x3(matrix=(
(value2_1, value2_2, value2_4),
(value3_1, value3_2, value3_4),
(value4_1, value4_2, value4_4)
))
matrix4 = Matrix3x3(matrix=(
(value2_1, value2_2, value2_3),
(value3_1, value3_2, value3_3),
(value4_1, value4_2, value4_3)
))
matrix5 = Matrix3x3(matrix=(
(value1_2, value1_3, value1_4),
(value3_2, value3_3, value3_4),
(value4_2, value4_3, value4_4)
))
matrix6 = Matrix3x3(matrix=(
(value1_1, value1_3, value1_4),
(value3_1, value3_3, value3_4),
(value4_1, value4_3, value4_4)
))
matrix7 = Matrix3x3(matrix=(
(value1_1, value1_2, value1_4),
(value3_1, value3_2, value3_4),
(value4_1, value4_2, value4_4)
))
matrix8 = Matrix3x3(matrix=(
(value1_1, value1_2, value1_3),
(value3_1, value3_2, value3_3),
(value4_1, value4_2, value4_3)
))
matrix9 = Matrix3x3(matrix=(
(value1_2, value1_3, value1_4),
(value2_2, value2_3, value2_4),
(value4_2, value4_3, value4_4)
))
matrix10 = Matrix3x3(matrix=(
(value1_1, value1_3, value1_4),
(value2_1, value2_3, value2_4),
(value4_1, value4_3, value4_4)
))
matrix11 = Matrix3x3(matrix=(
(value1_1, value1_2, value1_4),
(value2_1, value2_2, value2_4),
(value4_1, value4_2, value4_4)
))
matrix12 = Matrix3x3(matrix=(
(value1_1, value1_2, value1_3),
(value2_1, value2_2, value2_3),
(value4_1, value4_2, value4_3)
))
matrix13 = Matrix3x3(matrix=(
(value1_2, value1_3, value1_4),
(value2_2, value2_3, value2_4),
(value3_2, value3_3, value3_4)
))
matrix14 = Matrix3x3(matrix=(
(value1_1, value1_3, value1_4),
(value2_1, value2_3, value2_4),
(value3_1, value3_3, value3_4)
))
matrix15 = Matrix3x3(matrix=(
(value1_1, value1_2, value1_4),
(value2_1, value2_2, value2_4),
(value3_1, value3_2, value3_4)
))
matrix16 = Matrix3x3(matrix=(
(value1_1, value1_2, value1_3),
(value2_1, value2_2, value2_3),
(value3_1, value3_2, value3_3)
))
self.matrix = (
(matrix1.determinant(), matrix2.determinant(), matrix3.determinant(), matrix4.determinant()),
(matrix5.determinant(), matrix6.determinant(), matrix7.determinant(), matrix8.determinant()),
(matrix9.determinant(), matrix10.determinant(), matrix11.determinant(), matrix12.determinant()),
(matrix13.determinant(), matrix14.determinant(), matrix15.determinant(), matrix16.determinant())
)
self.find_cofactor()
def put_rotation(self, quaterion: Quaternion):
x, y, z, w = quaterion.x, quaterion.y, quaterion.z, quaterion.w
rotation_matrix = (
(1-2*y**2-2*z**2, 2*x*y-2*z*w, 2*x*z+2*y*w, 0), # x
(2*x*y+2*z*w, 1-2*x**2-2*z**2, 2*y*z-2*x*w, 0), # y
(2*x*z-2*y*w, 2*y*z+2*x*w, 1-2*x**2-2*y**2, 0), # z
(0, 0, 0, 1)
)
self.rotation_matrix = Matrix4x4(matrix=rotation_matrix)
def put_position(self, position: Vector3):
translation_matrix = (
(1, 0, 0, position.x), # x
(0, 1, 0, position.y), # y
(0, 0, 1, position.z), # z
(0, 0, 0, 1)
)
self.translation_matrix = Matrix4x4(matrix=translation_matrix)
def put_scale(self, scale: Vector3):
scale_matrix = (
(scale.x, 0, 0, 0),
(0, scale.y, 0, 0),
(0, 0, scale.z, 0),
(0, 0, 0, 1)
)
self.scale_matrix = Matrix4x4(matrix=scale_matrix)
def get_rotation(self) -> Quaternion:
return Quaternion()
def get_position(self) -> Vector3:
position = Vector3(self.matrix[0][3], self.matrix[1][3], self.matrix[2][3])
self.put_position(position)
return position
def get_scale(self) -> Vector3:
scale = Vector3(1, 1, 1)
self.put_scale(scale)
return scale
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/utilities/matrix/matrix4x4.py | matrix4x4.py |
from . import Matrix
class Matrix2x2(Matrix):
def determinant(self):
value1_1 = self.matrix[0][0]
value1_2 = self.matrix[0][1]
value2_1 = self.matrix[1][0]
value2_2 = self.matrix[1][1]
det = value1_1 * value2_2
det -= value1_2 * value2_1
return det
def cofactor(self):
self.find_cofactor()
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/utilities/matrix/matrix2x2.py | matrix2x2.py |
from .matrix2x2 import Matrix2x2
from . import Matrix
class Matrix3x3(Matrix):
def determinant(self):
value1_1 = self.matrix[0][0]
value1_2 = self.matrix[0][1]
value1_3 = self.matrix[0][2]
value2_1 = self.matrix[1][0]
value2_2 = self.matrix[1][1]
value2_3 = self.matrix[1][2]
value3_1 = self.matrix[2][0]
value3_2 = self.matrix[2][1]
value3_3 = self.matrix[2][2]
matrix1 = Matrix2x2(matrix=(
(value2_2, value2_3),
(value3_2, value3_3)
))
matrix2 = Matrix2x2(matrix=(
(value2_1, value2_3),
(value3_1, value3_3)
))
matrix3 = Matrix2x2(matrix=(
(value2_1, value2_2),
(value3_1, value3_2)
))
det = value1_1 * matrix1.determinant()
det -= value1_2 * matrix2.determinant()
det += value1_3 * matrix3.determinant()
return det
def cofactor(self):
value1_1 = self.matrix[0][0]
value1_2 = self.matrix[0][1]
value1_3 = self.matrix[0][2]
value2_1 = self.matrix[1][0]
value2_2 = self.matrix[1][1]
value2_3 = self.matrix[1][2]
value3_1 = self.matrix[2][0]
value3_2 = self.matrix[2][1]
value3_3 = self.matrix[2][2]
matrix1 = Matrix2x2(matrix=(
(value2_2, value2_3),
(value3_2, value3_3)
))
matrix2 = Matrix2x2(matrix=(
(value2_1, value2_3),
(value3_1, value3_3)
))
matrix3 = Matrix2x2(matrix=(
(value2_1, value2_2),
(value3_1, value3_2)
))
matrix4 = Matrix2x2(matrix=(
(value1_2, value1_3),
(value3_2, value3_3)
))
matrix5 = Matrix2x2(matrix=(
(value1_1, value1_3),
(value3_1, value3_3)
))
matrix6 = Matrix2x2(matrix=(
(value1_1, value1_2),
(value3_1, value3_2)
))
matrix7 = Matrix2x2(matrix=(
(value1_2, value1_3),
(value2_2, value2_3)
))
matrix8 = Matrix2x2(matrix=(
(value1_1, value1_3),
(value2_1, value2_3)
))
matrix9 = Matrix2x2(matrix=(
(value1_1, value1_2),
(value2_1, value2_2)
))
self.matrix = (
(matrix1.determinant(), matrix2.determinant(), matrix3.determinant()),
(matrix4.determinant(), matrix5.determinant(), matrix6.determinant()),
(matrix7.determinant(), matrix8.determinant(), matrix9.determinant())
)
cofactor_matrix = []
for row in range(len(self.matrix)):
new_row = []
for column in range(len(self.matrix[0])):
new_row.append(self.matrix[row][column] * (-1) ** (row + column))
cofactor_matrix.append(new_row)
self.matrix = cofactor_matrix
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/utilities/matrix/matrix3x3.py | matrix3x3.py |
class Matrix:
def __init__(self, **kwargs):
matrix = None
if 'matrix' in kwargs:
matrix = kwargs['matrix']
if 'size' in kwargs:
self.size = kwargs['size']
matrix = self.get_identity_matrix(
self.size
)
else:
self.size = (
len(matrix[0]), # x
len(matrix) # y
)
self.matrix = matrix
def __matmul__(self, other):
if len(self.matrix) != len(other.matrix[0]) or len(self.matrix[0]) != len(other.matrix):
raise TypeError('Матрицы не могут быть перемножены')
else:
multiplied_matrix = []
for row in self.matrix:
matrix_row = []
for column in range(4):
s = 0
for i in range(4):
s += row[i] * other.matrix[i][column]
matrix_row.append(s)
multiplied_matrix.append(matrix_row)
return Matrix(matrix=multiplied_matrix)
def __mul__(self, other: int or float):
multiplied_matrix = []
for row in range(len(self.matrix)):
new_row = []
for column in range(len(self.matrix[0])):
new_row.append(self.matrix[row][column]*other)
multiplied_matrix.append(new_row)
return Matrix(matrix=multiplied_matrix)
def __repr__(self):
return f'{self.__class__.__name__} <{self.matrix}>'
def __str__(self):
return str(self.matrix)
@staticmethod
def get_identity_matrix(size: tuple[int, int]):
matrix = []
for y in range(size[1]):
row = []
for x in range(size[0]):
element = 0
if x == y:
element = 1
row.append(element)
matrix.append(row)
return matrix
def find_cofactor(self):
cofactor_matrix = []
for row in range(len(self.matrix)):
new_row = []
for column in range(len(self.matrix[0])):
new_row.append(self.matrix[row][column] * (-1) ** (row + column))
cofactor_matrix.append(new_row)
self.matrix = cofactor_matrix
def transpose(self):
height = len(self.matrix)
width = len(self.matrix[0])
self.matrix = [[self.matrix[row][col] for row in range(height)] for col in range(width)]
self.matrix = [tuple(row) for row in self.matrix]
self.matrix = tuple(self.matrix)
def determinant(self):
det = 0
return det
def cofactor(self):
pass
def inverse(self):
det = self.determinant()
if det != 0:
self.transpose()
self.cofactor()
self.matrix = self.__mul__(1 / det).matrix
return self
__all__ = [
'matrix2x2',
'matrix3x3',
'matrix4x4'
]
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/utilities/matrix/__init__.py | __init__.py |
__all__ = [
'scw',
'collada',
'wavefront',
'gltf'
]
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/__init__.py | __init__.py |
from typing import List
from models_converter.utilities.math import Quaternion
from models_converter.utilities.math import Vector3
class Node:
class Instance:
class Bind:
def __init__(self, symbol: str = None, target: str = None):
self._symbol = symbol
self._target = target
def get_symbol(self) -> str or None:
return self._symbol
def get_target(self) -> str or None:
return self._target
def __init__(self, *, name: str, instance_type: str):
self._name: str = name
self._type: str = instance_type
self._target: str or None = None
self._binds = []
def __repr__(self) -> str:
return f'{self._name} - {self._type}'
def get_name(self) -> str:
return self._name
def get_type(self) -> str:
return self._type
def get_target(self) -> str:
return self._target
def set_target(self, target: str):
self._target = target
def get_binds(self) -> list:
return self._binds
def add_bind(self, symbol: str, target: str):
self._binds.append(Node.Instance.Bind(symbol, target))
class Frame:
def __init__(self, frame_id: int, position: Vector3 = None, scale: Vector3 = None, rotation: Quaternion = None):
self._id: int = frame_id
self._position: Vector3 = position
self._scale: Vector3 = scale
self._rotation: Quaternion = rotation
def get_id(self) -> int:
return self._id
def get_rotation(self) -> Quaternion:
return self._rotation
def set_rotation(self, rotation: Quaternion):
self._rotation = rotation
def get_position(self) -> Vector3:
return self._position
def set_position(self, position: Vector3):
self._position = position
def get_scale(self) -> Vector3:
return self._scale
def set_scale(self, scale: Vector3):
self._scale = scale
def __init__(self, *, name: str, parent: str):
self.frames_settings = 0
self._name: str = name
self._parent: str or None = parent
self._instances = []
self._frames = []
def __repr__(self) -> str:
result = self._name
if self._parent:
result += " <- " + self._parent
return f'Node({result})'
def get_name(self) -> str:
return self._name
def get_parent(self) -> str or None:
return self._parent
def get_instances(self) -> List[Instance]:
return self._instances
def add_instance(self, instance: Instance):
self._instances.append(instance)
def get_frames(self) -> List[Frame]:
return self._frames
def add_frame(self, frame: Frame):
self._frames.append(frame)
def set_frames(self, frames: List[Frame]):
self._frames.clear()
for frame in frames:
self._frames.append(frame)
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/universal/node.py | node.py |
from typing import List
from models_converter.formats.universal.camera import Camera
from models_converter.formats.universal.geometry import Geometry
from models_converter.formats.universal.node import Node
class Scene:
def __init__(self):
self._frame_rate: int = 30
self._materials = []
self._geometries = []
self._cameras = []
self._nodes = []
def get_materials(self) -> List:
return self._materials
def add_material(self, material):
self._materials.append(material)
def get_geometries(self) -> List[Geometry]:
return self._geometries
def add_geometry(self, geometry: Geometry):
self._geometries.append(geometry)
def get_cameras(self) -> List[Camera]:
return self._cameras
def add_camera(self, camera: Camera):
self._cameras.append(camera)
def get_nodes(self) -> List[Node]:
return self._nodes
def add_node(self, node: Node):
self._nodes.append(node)
def import_nodes(self, animation_scene):
for node in self._nodes:
for animation_node in animation_scene.get_nodes():
if node.get_name() == animation_node.get_name():
node.set_frames(animation_node.get_frames())
break
def get_frame_rate(self) -> int:
return self._frame_rate
def set_frame_rate(self, frame_rate: int):
self._frame_rate = frame_rate
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/universal/scene.py | scene.py |
from models_converter.formats.universal.scene import Scene, Node, Camera, Geometry
__all__ = [
'Scene',
'Node',
'Camera',
'Geometry'
]
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/universal/__init__.py | __init__.py |
from typing import List
class Geometry:
class Vertex:
def __init__(self, *,
name: str,
vertex_type: str,
vertex_index: int,
vertex_scale: float,
points: List[List[float]]):
self._name: str = name
self._type: str = vertex_type
self._index: int = vertex_index
self._scale: float = vertex_scale
self._points: List[List[float]] = points
def get_name(self) -> str:
return self._name
def get_type(self) -> str:
return self._type
def get_index(self) -> int:
return self._index
def get_point_size(self) -> float:
return len(self._points[0])
def get_scale(self) -> float:
return self._scale
def get_points(self) -> List[List[float]]:
return self._points
class Material:
def __init__(self, name: str, triangles: List[List[List[int]]]):
self._name: str = name
self._triangles: List[List[List[int]]] = triangles
def get_name(self) -> str:
return self._name
def get_triangles(self) -> List[List[List[int]]]:
return self._triangles
class Joint:
def __init__(self, name: str, matrix: List[float] or None):
self._name: str = name
self._matrix: List[float] or None = matrix
def get_name(self) -> str:
return self._name
def get_matrix(self) -> List[float]:
return self._matrix
def set_matrix(self, matrix: List[float]):
self._matrix = matrix
class Weight:
def __init__(self, joint_index: int, strength: float):
self._joint_index: int = joint_index
self._strength: float = strength
def get_joint_index(self) -> int:
return self._joint_index
def get_strength(self) -> float:
return self._strength
def __init__(self, *, name: str, group: str = None):
self._name: str = name
self._group: str or None = group
self._vertices: List[Geometry.Vertex] = []
self._materials: List[Geometry.Material] = []
self._bind_matrix: List[float] or None = None
self._joints: List[Geometry.Joint] = []
self._weights: List[Geometry.Weight] = []
def get_name(self) -> str:
return self._name
def get_group(self) -> str or None:
return self._group
def get_vertices(self) -> List[Vertex]:
return self._vertices
def add_vertex(self, vertex: Vertex):
self._vertices.append(vertex)
def get_materials(self) -> List[Material]:
return self._materials
def add_material(self, material: Material):
self._materials.append(material)
def has_controller(self) -> bool:
return self._bind_matrix is not None
def get_bind_matrix(self) -> list:
return self._bind_matrix
def set_controller_bind_matrix(self, matrix: List[float]):
self._bind_matrix = matrix
def get_joints(self) -> List[Joint]:
return self._joints
def add_joint(self, joint: Joint):
self._joints.append(joint)
def get_weights(self) -> List[Weight]:
return self._weights
def add_weight(self, weight: Weight):
self._weights.append(weight)
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/universal/geometry.py | geometry.py |
class Camera:
def __init__(self, *, name: str, fov: float, aspect_ratio: float, near: float, far: float):
self._name: str = name
self._v1: float = 0
self._fov: float = fov
self._aspect_ratio: float = aspect_ratio
self._near: float = near
self._far: float = far
def get_name(self) -> str:
return self._name
def get_v1(self) -> float:
return self._v1
def get_fov(self) -> float:
return self._fov
def get_aspect_ration(self) -> float:
return self._aspect_ratio
def get_near(self) -> float:
return self._near
def get_far(self) -> float:
return self._far
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/universal/camera.py | camera.py |
from .gltf_property import GlTFProperty
class Material(GlTFProperty):
class NormalTextureInfo(GlTFProperty):
def __init__(self):
super().__init__()
self.index = None
self.tex_coord = None # Default: 0
self.scale = None # Default: 1
class OcclusionTextureInfo(GlTFProperty):
def __init__(self):
super().__init__()
self.index = None
self.tex_coord = None # Default: 0
self.strength = None # Default: 1
class PbrMetallicRoughness(GlTFProperty):
def __init__(self):
super().__init__()
self.base_color_factor = None # Default: [1, 1, 1, 1]
self.base_color_texture = None
self.metallic_factor = None # Default: 1
self.roughness_factor = None # Default: 1
self.metallic_roughness_texture = None
def __init__(self):
super().__init__()
self.name = None
self.pbr_metallic_roughness = None
self.normal_texture = None
self.occlusion_texture = None
self.emissive_texture = None
self.emissive_factor = None # Default: [0, 0, 0]
self.alpha_mode = None # Default: 'OPAQUE'
self.alpha_cutoff = None # Default: 0.5
self.double_sided = None # Default: False
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/gltf/material.py | material.py |
from .gltf_property import GlTFProperty
class BufferView(GlTFProperty):
def __init__(self):
super().__init__()
self.buffer = None
self.byte_length = None
self.byte_offset = 0
self.byte_stride = None
self.target = None
self.name = None
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/gltf/buffer_view.py | buffer_view.py |
from .gltf_property import GlTFProperty
class Asset(GlTFProperty):
def __init__(self):
super().__init__()
self.version = None
self.copyright = None
self.generator = None
self.min_version = None
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/gltf/asset.py | asset.py |
from .gltf_property import GlTFProperty
from ...utilities.math import Vector3, Quaternion
from ...utilities.matrix.matrix4x4 import Matrix4x4
class Node(GlTFProperty):
def __init__(self):
super().__init__()
self.camera = None
self.children = None
self.skin = None
self.matrix = Matrix4x4(size=(4, 4))
self.mesh = None
self.rotation = Quaternion() # Default: [0, 0, 0, 1]
self.scale = Vector3(1, 1, 1) # Default: [1, 1, 1]
self.translation = Vector3() # Default: [0, 0, 0]
self.weights = None
self.name = None
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/gltf/node.py | node.py |
from .gltf_property import GlTFProperty
class Mesh(GlTFProperty):
class Primitive(GlTFProperty):
def __init__(self):
super().__init__()
self.attributes = None
self.indices = None
self.material = None
self.mode = None # Default: 4
self.targets = None
def __init__(self):
super().__init__()
self.primitives = self.Primitive
self.weights = None
self.name = None
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/gltf/mesh.py | mesh.py |
class GlTFChunk:
def __init__(self):
self.chunk_length = 0
self.chunk_name = b''
self.data = b''
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/gltf/chunk.py | chunk.py |
from models_converter.formats.gltf import GlTFProperty
class TextureInfo(GlTFProperty):
def __init__(self):
super().__init__()
self.index = None
self.tex_coord = None # Default: 0
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/gltf/texture_info.py | texture_info.py |
from .gltf_property import GlTFProperty
class Scene(GlTFProperty):
def __init__(self):
super().__init__()
self.nodes = None
self.name = None
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/gltf/scene.py | scene.py |
import json
from models_converter.interfaces import WriterInterface
class Writer(WriterInterface):
MAGIC = b'glTF'
def __init__(self):
self.writen = self.MAGIC
self.data = bytes()
self.asset = {"version": "2.0"}
self.scene = 0
self.scenes = [{
"nodes": []
}]
self.nodes = []
self.buffers = []
self.buffer_views = []
self.accessors = []
self.meshes = []
self.materials = []
self.textures = []
self.images = []
self.samplers = []
def add_root_node_index(self, index):
self.scenes[0]["nodes"].append(index)
def add_node(self, node):
self.nodes.append(node)
def add_mesh(self, mesh):
self.meshes.append(mesh)
def add_material(self, material):
self.materials.append(material)
def add_texture(self, texture):
self.textures.append(texture)
def add_image(self, image):
self.images.append(image)
def add_sampler(self, sampler):
self.samplers.append(sampler)
def add_data(self, data):
offset = len(self.data)
self.data += data
return offset
def add_buffer_view(self, buffer_view):
index = len(self.buffer_views)
self.buffer_views.append(buffer_view)
return index
def add_accessor(self, accessor):
index = len(self.accessors)
self.accessors.append(accessor)
return index
def as_dict(self):
return {
"asset": self.asset,
"scene": self.scene,
"scenes": self.scenes,
"nodes": self.nodes,
"buffers": self.buffers,
"bufferViews": self.buffer_views,
"accessors": self.accessors,
"meshes": self.meshes,
"materials": self.materials,
"textures": self.textures,
"images": self.images,
"samplers": self.samplers,
}
def write(self, data: dict):
print(data)
json_data = json.dumps(self.as_dict())
self.buffers.append({
"byteLength": len(self.data)
})
# pad json data with spaces
json_data += " " * (4 - len(json_data) % 4)
# pad binary data with null bytes
self.data += bytes((4 - len(self.data) % 4))
self.writen += (2).to_bytes(4, 'little')
self.writen += (len(json_data) + len(self.data) + 28).to_bytes(4, 'little')
self.writen += len(json_data).to_bytes(4, 'little') + b'JSON' + json_data.encode()
self.writen += len(self.data).to_bytes(4, 'little') + b'BIN\x00' + self.data
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/gltf/writer.py | writer.py |
from .gltf_property import GlTFProperty
class Sampler(GlTFProperty):
def __init__(self):
super().__init__()
self.mag_filter = None
self.min_filter = None
self.wrap_s = None # Default: 10497
self.wrap_t = None # Default: 10497
self.name = None
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/gltf/sampler.py | sampler.py |
from .gltf_property import GlTFProperty
class Animation(GlTFProperty):
class AnimationSampler(GlTFProperty):
def __init__(self):
super().__init__()
self.input = None
self.output = None
self.interpolation = None # Default: 'LINEAR'
class Channel(GlTFProperty):
class Target(GlTFProperty):
def __init__(self):
super().__init__()
self.path = None
self.node = None
def __init__(self):
super().__init__()
self.sampler = None
self.target = self.Target
def __init__(self):
super().__init__()
self.channels = self.Channel
self.samplers = self.AnimationSampler
self.name = None
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/gltf/animation.py | animation.py |
from models_converter.utilities.math import Vector3, Quaternion
from models_converter.utilities.matrix.matrix4x4 import Matrix4x4
def to_camelcase(property_name: str):
words = property_name.split('_')
for word_index in range(len(words)):
word = words[word_index]
if word_index > 0:
word = word.capitalize()
words[word_index] = word
camelcase_name = ''.join(words)
return camelcase_name
def to_lowercase(property_name: str) -> str:
result = ''
for char in property_name:
if char.isupper():
char = f'_{char.lower()}'
result += char
return result
class GlTFProperty:
def __init__(self):
self.extensions = None
self.extras = None
def from_dict(self, dictionary: dict):
if dictionary:
for key, value in dictionary.items():
attribute_name = to_lowercase(key)
value_type = type(value)
attribute_value = getattr(self, attribute_name)
if attribute_value is None or value_type in (int, str, bool):
attribute_value = value
elif type(attribute_value) in (Vector3, Quaternion, Matrix4x4) and type(value) is list:
attribute_value = type(attribute_value)(*value)
elif issubclass(attribute_value, GlTFProperty):
if value_type is list:
value_type = attribute_value
values = []
for item in value:
new_value = value_type()
new_value.from_dict(item)
values.append(new_value)
attribute_value = values
else:
attribute_value = attribute_value()
attribute_value.from_dict(value)
setattr(self, attribute_name, attribute_value)
def to_dict(self) -> dict:
dictionary = {}
for key, value in self.__dict__.items():
if value is not None:
attribute_name = to_camelcase(key)
value_type = type(value)
attribute_value = None
if value_type is list:
attribute_value = []
for item in value:
item_type = type(item)
if issubclass(item_type, GlTFProperty):
item = item.to_dict()
attribute_value.append(item)
elif issubclass(value_type, GlTFProperty):
attribute_value = value.to_dict()
elif attribute_value is None:
attribute_value = value
dictionary[attribute_name] = attribute_value
return dictionary
def __getitem__(self, item):
item = to_lowercase(item)
if hasattr(self, item):
return getattr(self, item)
else:
raise IndexError('The object has no attribute named ' + item)
def __repr__(self) -> str:
return f'<{self.__class__.__name__} ({self.to_dict()})>'
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/gltf/gltf_property.py | gltf_property.py |
from .gltf_property import GlTFProperty
class Texture(GlTFProperty):
def __init__(self):
super().__init__()
self.sampler = None
self.source = None
self.name = None
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/gltf/texture.py | texture.py |
from .gltf_property import GlTFProperty
class Image(GlTFProperty):
def __init__(self):
super().__init__()
self.uri = None
self.mime_type = None
self.buffer_view = None
self.name = None
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/gltf/image.py | image.py |
import json
from models_converter.formats import universal
from models_converter.formats.gltf.chunk import GlTFChunk
from models_converter.formats.gltf.gltf import GlTF
from models_converter.formats.gltf.node import Node
from models_converter.formats.universal import Scene, Geometry
from models_converter.interfaces import ParserInterface
from models_converter.utilities.reader import Reader
class Parser(ParserInterface):
def __init__(self, data: bytes):
self.file_data = data
self.scene = Scene()
self.version = None
self.length = None
self.json_chunk = None
self.bin_chunk = None
self.buffer_views = []
self.accessors = []
self.buffers = []
self.gltf = GlTF()
def parse_bin(self):
reader = Reader(self.bin_chunk.data, 'little')
for buffer in self.gltf.buffers:
parsed_buffer = reader.read(buffer.byte_length)
self.buffers.append(parsed_buffer)
for buffer_view in self.gltf.buffer_views:
reader.__init__(self.buffers[buffer_view.buffer], 'little')
reader.read(buffer_view.byte_offset)
length = buffer_view.byte_length
data = reader.read(length)
self.buffer_views.append(data)
for accessor in self.gltf.accessors:
reader.__init__(self.buffer_views[accessor.buffer_view], 'little')
reader.read(accessor.byte_offset)
types = {
5120: (reader.readByte, 1),
5121: (reader.readUByte, 1),
5122: (reader.readShort, 2),
5123: (reader.readUShort, 2),
5125: (reader.readUInt32, 4),
5126: (reader.readFloat, 4)
}
if accessor.normalized:
types = {
5120: (lambda: max(reader.readByte() / 127, -1.0), 1),
5121: (lambda: reader.readUByte() / 255, 1),
5122: (lambda: max(reader.readShort() / 32767, -1.0), 2),
5123: (lambda: reader.readUShort() / 65535, 2),
5125: (reader.readUInt32, 4),
5126: (reader.readFloat, 4)
}
items_count = {
'SCALAR': 1,
'VEC2': 2,
'VEC3': 3,
'VEC4': 4,
'MAT2': 4,
'MAT3': 9,
'MAT4': 16
}
components_count = items_count[accessor.type]
read_type, bytes_per_element = types[accessor.component_type]
default_stride = bytes_per_element * components_count
stride = self.gltf.buffer_views[accessor.buffer_view].byte_stride or default_stride
elements_per_stride = stride // bytes_per_element
elements_count = accessor.count * elements_per_stride
temp_list = []
for i in range(elements_count):
temp_list.append(read_type())
self.accessors.append([
temp_list[i:i + components_count]
for i in range(0, elements_count, elements_per_stride)
])
def parse(self):
reader = Reader(self.file_data, 'little')
magic = reader.read(4)
if magic != b'glTF':
raise TypeError('Wrong file magic! "676c5446" expected, but given is ' + magic.hex())
self.version = reader.readUInt32()
self.length = reader.readUInt32()
self.json_chunk = GlTFChunk()
self.bin_chunk = GlTFChunk()
self.json_chunk.chunk_length = reader.readUInt32()
self.json_chunk.chunk_name = reader.read(4)
self.json_chunk.data = reader.read(self.json_chunk.chunk_length)
self.bin_chunk.chunk_length = reader.readUInt32()
self.bin_chunk.chunk_name = reader.read(4)
self.bin_chunk.data = reader.read(self.bin_chunk.chunk_length)
self.gltf.from_dict(json.loads(self.json_chunk.data))
self.parse_bin()
scene_id = self.gltf.scene
scene = self.gltf.scenes[scene_id]
for node_id in scene.nodes:
node = self.gltf.nodes[node_id]
self.parse_node(node)
# TODO: animations
# for animation in self.gltf.animations:
# for channel in animation.channels:
# sampler: Animation.AnimationSampler = animation.samplers[channel.sampler]
# input_accessor = self.accessors[sampler.input]
def parse_node(self, gltf_node: Node, parent: str = None):
node_name = gltf_node.name.split('|')[-1]
node = universal.Node(
name=node_name,
parent=parent
)
instance = None
if gltf_node.mesh is not None and type(self.gltf.meshes) is list:
mesh = self.gltf.meshes[gltf_node.mesh]
mesh_name = mesh.name.split('|')
group = 'GEO'
name = mesh_name[0]
if len(mesh_name) > 1:
group = mesh_name[0]
name = mesh_name[1]
geometry = Geometry(name=name, group=group)
if gltf_node.skin is not None:
instance = universal.Node.Instance(name=geometry.get_name(), instance_type='CONT')
geometry.set_controller_bind_matrix([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1])
skin_id = gltf_node.skin
skin = self.gltf.skins[skin_id]
bind_matrices = self.accessors[skin.inverse_bind_matrices]
bind_matrices = [[m[0::4], m[1::4], m[2::4], m[3::4]] for m in bind_matrices]
for matrix_index in range(len(bind_matrices)):
m = bind_matrices[matrix_index]
matrix = m[0]
matrix.extend(m[1])
matrix.extend(m[2])
matrix.extend(m[3])
bind_matrices[matrix_index] = matrix
for joint in skin.joints:
joint_index = skin['joints'].index(joint)
joint_node = self.gltf.nodes[joint]
joint_name = joint_node['name']
matrix = bind_matrices[joint_index]
geometry.add_joint(Geometry.Joint(joint_name, matrix))
else:
instance = universal.Node.Instance(name=geometry.get_name(), instance_type='GEOM')
position_offset = 0
normal_offset = 0
texcoord_offset = 0
for primitive in mesh.primitives:
if primitive.to_dict() != {}:
primitive_index = mesh.primitives.index(primitive)
attributes = primitive.attributes
material_id = primitive.material
polygons_id = primitive.indices
triangles = self.accessors[polygons_id]
material = self.gltf.materials[material_id]
material_name = material.extensions['SC_shader']['name']
instance.add_bind(material_name, material_name)
position = []
normal = []
texcoord = []
joint_ids = 0
for attribute_id in attributes:
attribute = attributes[attribute_id]
points = None
if attribute_id == 'POSITION':
position = self.accessors[attribute]
points = list(map(
lambda point: (
point[0] * gltf_node.scale.x + gltf_node.translation.x,
point[1] * gltf_node.scale.y + gltf_node.translation.y,
point[2] * gltf_node.scale.z + gltf_node.translation.z
),
position
))
elif attribute_id == 'NORMAL':
normal = self.accessors[attribute]
points = list(map(
lambda point: (
point[0] * gltf_node.scale.x,
point[1] * gltf_node.scale.y,
point[2] * gltf_node.scale.z
),
normal
))
elif attribute_id.startswith('TEXCOORD'):
texcoord = self.accessors[attribute]
texcoord = [[item[0], 1 - item[1]] for item in texcoord]
attribute_id = 'TEXCOORD'
points = texcoord
elif attribute_id.startswith('JOINTS'):
joint_ids = self.accessors[attribute]
elif attribute_id.startswith('WEIGHTS'):
weights = self.accessors[attribute]
for x in range(len(joint_ids)):
geometry.add_weight(Geometry.Weight(joint_ids[x][0], weights[x][0] / 255))
geometry.add_weight(Geometry.Weight(joint_ids[x][1], weights[x][1] / 255))
geometry.add_weight(Geometry.Weight(joint_ids[x][2], weights[x][2] / 255))
geometry.add_weight(Geometry.Weight(joint_ids[x][3], weights[x][3] / 255))
if points:
geometry.add_vertex(Geometry.Vertex(
name=f'{attribute_id.lower()}_{primitive_index}',
vertex_type=attribute_id,
vertex_index=len(geometry.get_vertices()),
vertex_scale=1,
points=points
))
triangles = [
[
[
point[0] + normal_offset,
point[0] + position_offset,
point[0] + texcoord_offset
] for point in triangles[x:x + 3]
] for x in range(0, len(triangles), 3)
]
geometry.add_material(Geometry.Material(material_name, triangles))
for attribute_id in attributes:
if attribute_id == 'POSITION':
position_offset += len(position)
elif attribute_id == 'NORMAL':
normal_offset += len(normal)
elif attribute_id.startswith('TEXCOORD'):
texcoord_offset += len(texcoord)
self.scene.add_geometry(geometry)
if instance is not None:
node.add_instance(instance)
self.scene.add_node(node)
node.add_frame(universal.Node.Frame(
0,
gltf_node.translation,
gltf_node.scale,
gltf_node.rotation
))
if gltf_node.children:
for child_id in gltf_node.children:
child = self.gltf.nodes[child_id]
self.parse_node(child, node_name)
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/gltf/parser.py | parser.py |
from .gltf_property import GlTFProperty
class Accessor(GlTFProperty):
class Sparse(GlTFProperty):
class Indices(GlTFProperty):
def __init__(self):
super().__init__()
self.buffer_view = None
self.component_type = None
self.byte_offset = 0
class Values(GlTFProperty):
def __init__(self):
super().__init__()
self.buffer_view = None
self.byte_offset = 0
def __init__(self):
super().__init__()
self.count = None
self.indices = self.Indices
self.values = self.Values
def __init__(self):
super().__init__()
self.component_type = None
self.count = None
self.type = None
self.buffer_view = None
self.byte_offset = 0
self.normalized = False
self.max = None
self.min = None
self.sparse = self.Sparse
self.name = None
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/gltf/accessor.py | accessor.py |
from .accessor import Accessor
from .animation import Animation
from .asset import Asset
from .buffer import Buffer
from .buffer_view import BufferView
from .camera import Camera
from .gltf_property import GlTFProperty
from .image import Image
from .material import Material
from .mesh import Mesh
from .node import Node
from .sampler import Sampler
from .scene import Scene
from .skin import Skin
from .texture import Texture
from .writer import Writer
from .parser import Parser
__all__ = [
'Accessor',
'Animation',
'Asset',
'Buffer',
'BufferView',
'Camera',
'Image',
'Material',
'Mesh',
'Node',
'Sampler',
'Scene',
'Skin',
'Texture',
'Parser',
'Writer'
]
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/gltf/__init__.py | __init__.py |
from .gltf_property import GlTFProperty
class Buffer(GlTFProperty):
def __init__(self):
super().__init__()
self.byte_length = None
self.uri = None
self.name = None
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/gltf/buffer.py | buffer.py |
from .gltf_property import GlTFProperty
from . import *
class GlTF(GlTFProperty):
def __init__(self):
super().__init__()
self.asset = Asset
self.extensions_used = None
self.extensions_required = None
self.accessors = Accessor
self.animations = Animation
self.buffers = Buffer
self.buffer_views = BufferView
self.cameras = Camera
self.images = Image
self.materials = Material
self.meshes = Mesh
self.nodes = Node
self.samplers = Sampler
self.scene = None
self.scenes = Scene
self.skins = Skin
self.textures = Texture
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/gltf/gltf.py | gltf.py |
from .gltf_property import GlTFProperty
class Skin(GlTFProperty):
def __init__(self):
super().__init__()
self.joints = None
self.inverse_bind_matrices = None
self.skeleton = None
self.name = None
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/gltf/skin.py | skin.py |
from .gltf_property import GlTFProperty
class Camera(GlTFProperty):
class Orthographic(GlTFProperty):
def __init__(self):
super().__init__()
self.xmag = None
self.ymag = None
self.zfar = None
self.znear = None
class Perspective(GlTFProperty):
def __init__(self):
super().__init__()
self.yfov = None
self.znear = None
self.aspect_ratio = None
self.zfar = None
def __init__(self):
super().__init__()
self.type = None
self.orthographic = None
self.perspective = None
self.name = None
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/gltf/camera.py | camera.py |
import binascii
from .chunks import *
from ..universal import Scene
from ...interfaces import WriterInterface
class Writer(WriterInterface):
MAGIC = b'SC3D'
def __init__(self):
self.writen = self.MAGIC
def write(self, scene: Scene):
head = HEAD()
head.version = 2
head.frame_rate = 30
head.first_frame = 0
head.last_frame = 0
head.materials_file = 'sc3d/character_materials.scw' if len(scene.get_geometries()) > 0 else None
self._write_chunk(head)
# TODO: materials
for material in scene.get_materials():
mate = MATE(head)
self._write_chunk(mate)
for geometry in scene.get_geometries():
geom = GEOM(head)
geom.geometry = geometry
self._write_chunk(geom)
for camera in scene.get_cameras():
came = CAME(head)
came.camera = camera
self._write_chunk(came)
node = NODE(head)
node.nodes = scene.get_nodes()
self._write_chunk(node)
wend = WEND()
self._write_chunk(wend)
def _write_chunk(self, chunk: Chunk):
chunk.encode()
self.writen += chunk.length.to_bytes(4, 'big') + chunk.chunk_name.encode('utf-8') + chunk.buffer
self.writen += binascii.crc32(chunk.chunk_name.encode('utf-8') + chunk.buffer).to_bytes(4, 'big')
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/scw/writer.py | writer.py |
from ..universal import Scene
from ...interfaces import ParserInterface
from ...utilities.reader import Reader
from .chunks import *
class Parser(ParserInterface):
def __init__(self, file_data: bytes):
self.file_data = file_data
self.scene = Scene()
self.chunks = []
self.header = None
def parse(self):
reader = Reader(self.file_data)
file_magic = reader.read(4)
if file_magic != b'SC3D':
raise TypeError('File Magic isn\'t "SC3D"')
self._split_chunks(reader)
for chunk in self.chunks:
chunk_name = chunk['chunk_name']
chunk_data = chunk['data']
if chunk_name == 'HEAD':
head = HEAD()
head.parse(chunk_data)
self.header = head
elif chunk_name == 'MATE':
mate = MATE(self.header)
mate.parse(chunk_data)
self.scene.add_material(mate)
elif chunk_name == 'GEOM':
geom = GEOM(self.header)
geom.parse(chunk_data)
self.scene.add_geometry(geom.geometry)
elif chunk_name == 'CAME':
came = CAME(self.header)
came.parse(chunk_data)
self.scene.add_camera(came.camera)
elif chunk_name == 'NODE':
node = NODE(self.header)
node.parse(chunk_data)
self.scene.get_nodes().extend(node.nodes)
elif chunk_name == 'WEND':
wend = WEND()
wend.parse(chunk_data)
else:
raise TypeError(f'Unknown chunk: {chunk_name}')
def _split_chunks(self, reader: Reader):
# len(Chunk Length) + len(Chunk Name) + len(Chunk CRC)
while reader.tell() <= len(self.file_data) - 12:
chunk_length = reader.readUInt32()
chunk_name = reader.readChars(4)
chunk_data = reader.read(chunk_length)
chunk_crc = reader.readUInt32()
self.chunks.append({
'chunk_name': chunk_name,
'data': chunk_data,
'crc': chunk_crc
})
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/scw/parser.py | parser.py |
from .writer import Writer
from .parser import Parser
__all__ = [
'Writer',
'Parser'
]
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/scw/__init__.py | __init__.py |
from models_converter.utilities.math import Vector3
from models_converter.utilities.math import Quaternion
from . import Chunk
from ...universal.node import Node
class NODE(Chunk):
def __init__(self, header):
super().__init__(header)
self.chunk_name = 'NODE'
self.nodes = []
def parse(self, buffer: bytes):
super().parse(buffer)
nodes_count = self.readUShort()
for node_index in range(nodes_count):
node = Node(
name=self.readString(),
parent=self.readString()
)
instances_count = self.readUShort()
for x in range(instances_count):
instance = Node.Instance(
instance_type=self.readChars(4),
name=self.readString()
)
if instance.get_type() in ('GEOM', 'CONT'):
materials_count = self.readUShort()
for bind in range(materials_count):
symbol = self.readString()
target = self.readString()
instance.add_bind(symbol, target)
elif instance.get_type() == 'CAME':
instance.set_target(self.readString())
node.add_instance(instance)
frames_count = self.readUShort()
if frames_count > 0:
rotation = Quaternion()
position = Vector3()
scale = Vector3()
node.frames_settings = self.readUByte()
for frame_index in range(frames_count):
frame = Node.Frame(self.readUShort())
if node.frames_settings & 1 or frame_index == 0: # Rotation
rotation.x = self.readNShort()
rotation.y = self.readNShort()
rotation.z = self.readNShort()
rotation.w = self.readNShort()
if node.frames_settings & 2 or frame_index == 0: # Position X
position.x = self.readFloat()
if node.frames_settings & 4 or frame_index == 0: # Position Y
position.y = self.readFloat()
if node.frames_settings & 8 or frame_index == 0: # Position Z
position.z = self.readFloat()
if node.frames_settings & 16 or frame_index == 0: # Scale X
scale.x = self.readFloat()
if node.frames_settings & 32 or frame_index == 0: # Scale Y
scale.y = self.readFloat()
if node.frames_settings & 64 or frame_index == 0: # Scale Z
scale.z = self.readFloat()
frame.set_rotation(rotation.clone())
frame.set_position(position.clone())
frame.set_scale(scale.clone())
node.add_frame(frame)
self.nodes.append(node)
def encode(self):
super().encode()
self.writeUShort(len(self.nodes))
for node in self.nodes:
self.writeString(node.get_name())
self.writeString(node.get_parent())
self.writeUShort(len(node.get_instances()))
for instance in node.get_instances():
self.writeChar(instance.get_type())
self.writeString(instance.get_name())
self.writeUShort(len(instance.get_binds()))
for bind in instance.get_binds():
self.writeString(bind.get_symbol())
self.writeString(bind.get_target())
self._encode_frames(node.get_frames(), node.frames_settings)
self.length = len(self.buffer)
def _encode_frames(self, frames, frames_settings):
self.writeUShort(len(frames))
if len(frames) > 0:
self.writeUByte(frames_settings)
for frame in frames:
self.writeUShort(frame.get_id())
if frames_settings & 128 or frames.index(frame) == 0: # Rotation
rotation = frame.get_rotation()
self.writeNShort(rotation.x)
self.writeNShort(rotation.y)
self.writeNShort(rotation.z)
self.writeNShort(rotation.w)
if frames_settings & 16 or frames.index(frame) == 0: # Position X
self.writeFloat(frame.get_position().x)
if frames_settings & 32 or frames.index(frame) == 0: # Position Y
self.writeFloat(frame.get_position().y)
if frames_settings & 64 or frames.index(frame) == 0: # Position Z
self.writeFloat(frame.get_position().z)
if frames_settings & 2 or frames.index(frame) == 0: # Scale X
self.writeFloat(frame.get_scale().x)
if frames_settings & 4 or frames.index(frame) == 0: # Scale Y
self.writeFloat(frame.get_scale().y)
if frames_settings & 8 or frames.index(frame) == 0: # Scale Z
self.writeFloat(frame.get_scale().z)
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/scw/chunks/node.py | node.py |
from . import Chunk
from ...universal import Geometry
class GEOM(Chunk):
def __init__(self, header):
super().__init__(header)
self.chunk_name = 'GEOM'
self.geometry: Geometry or None = None
def parse(self, buffer: bytes):
super().parse(buffer)
self.geometry = Geometry(
name=self.readString(),
group=self.readString()
)
if self.header.version < 2:
matrix = []
for x in range(4):
temp_list = []
for x1 in range(4):
temp_list.append(self.readFloat())
matrix.append(temp_list)
self._parse_vertices()
self._parse_skin()
self._parse_materials()
def _parse_vertices(self):
vertex_count = self.readUByte()
for x in range(vertex_count):
vertex_type = self.readString()
vertex_index = self.readUByte()
self.readUByte() # sub_index
vertex_stride = self.readUByte()
vertex_scale = self.readFloat()
vertex_count = self.readUInt32()
if vertex_type == 'VERTEX':
vertex_type = 'POSITION'
coordinates = []
for x1 in range(vertex_count):
coordinates_massive = [self.readNShort() for _ in range(vertex_stride)]
if vertex_type == 'TEXCOORD':
coordinates_massive[1::2] = [1 - x for x in coordinates_massive[1::2]]
coordinates.append(coordinates_massive)
self.geometry.add_vertex(Geometry.Vertex(
name=f'{vertex_type.lower()}_0',
vertex_type=vertex_type,
vertex_index=vertex_index,
vertex_scale=vertex_scale,
points=coordinates)
)
def _parse_skin(self):
has_controller = self.readBool()
if has_controller:
self.geometry.set_controller_bind_matrix([self.readFloat() for _ in range(16)])
self._parse_joints()
self._parse_weights()
def _parse_joints(self):
joint_counts = self.readUByte()
for x in range(joint_counts):
joint_name = self.readString()
joint_matrix = [self.readFloat() for _ in range(16)]
self.geometry.add_joint(Geometry.Joint(joint_name, joint_matrix))
def _parse_weights(self):
vertex_weights_count = self.readUInt32()
for x in range(vertex_weights_count):
joint_a = self.readUByte()
joint_b = self.readUByte()
joint_c = self.readUByte()
joint_d = self.readUByte()
weight_a = self.readNUShort()
weight_b = self.readNUShort()
weight_c = self.readNUShort()
weight_d = self.readNUShort()
self.geometry.add_weight(Geometry.Weight(joint_a, weight_a))
self.geometry.add_weight(Geometry.Weight(joint_b, weight_b))
self.geometry.add_weight(Geometry.Weight(joint_c, weight_c))
self.geometry.add_weight(Geometry.Weight(joint_d, weight_d))
def _parse_materials(self):
materials_count = self.readUByte()
for x in range(materials_count):
material_name = self.readString()
self.readString()
triangles_count = self.readUShort()
inputs_count = self.readUByte()
vertex_index_length = self.readUByte()
triangles = []
for x1 in range(triangles_count):
triangles.append([
[
self.readUInteger(vertex_index_length) # Vertex
for _ in range(inputs_count)
] for _ in range(3) # 3 points
])
self.geometry.add_material(Geometry.Material(material_name, triangles))
def encode(self):
super().encode()
self.writeString(self.geometry.get_name())
self.writeString(self.geometry.get_group())
self._encode_vertices(self.geometry.get_vertices())
self._encode_skin()
self._encode_materials()
self.length = len(self.buffer)
def _encode_vertices(self, vertices):
self.writeUByte(len(vertices))
for vertex in vertices:
self.writeString(vertex.get_type())
self.writeUByte(vertex.get_index())
self.writeUByte(0) # sub_index
self.writeUByte(vertex.get_point_size())
self.writeFloat(vertex.get_scale())
self.writeUInt32(len(vertex.get_points()))
for point in vertex.get_points():
if vertex.get_type() == 'TEXCOORD':
point[1::2] = [1 - x for x in point[1::2]]
for coordinate in point:
# coordinate /= vertex['scale']
coordinate *= 32512
self.writeShort(round(coordinate))
def _encode_skin(self):
self.writeBool(self.geometry.has_controller())
if self.geometry.has_controller():
for x in self.geometry.get_bind_matrix():
self.writeFloat(x)
self._encode_joints()
self._encode_weight()
def _encode_joints(self):
if not self.geometry.has_controller():
self.writeUByte(0)
return
self.writeUByte(len(self.geometry.get_joints()))
for joint in self.geometry.get_joints():
self.writeString(joint.get_name())
for x in joint.get_matrix():
self.writeFloat(x)
def _encode_weight(self):
if not self.geometry.has_controller():
self.writeUInt32(0)
return
weights_quads = len(self.geometry.get_weights()) // 4
self.writeUInt32(weights_quads)
for quad_index in range(weights_quads):
quad = self.geometry.get_weights()[quad_index * 4:(quad_index + 1) * 4]
for weight in quad:
self.writeUByte(weight.get_joint_index())
for weight in quad:
self.writeNUShort(weight.get_strength())
def _encode_materials(self):
self.writeUByte(len(self.geometry.get_materials()))
for material in self.geometry.get_materials():
self.writeString(material.get_name())
self.writeString('')
self.writeUShort(len(material.get_triangles()))
# Calculate settings
inputs_count = len(material.get_triangles()[0][0])
maximal_value = 0
for triangle in material.get_triangles():
for point in triangle:
for vertex in point:
if vertex > maximal_value:
maximal_value = vertex
item_length = 1 if maximal_value <= 255 else 2
# Write Settings
self.writeUByte(inputs_count)
self.writeUByte(item_length)
# Write Polygons
for triangle in material.get_triangles():
for point in triangle:
for vertex in point:
self.writeUInteger(vertex, item_length)
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/scw/chunks/geom.py | geom.py |
from ....utilities.reader import Reader
from ....utilities.writer import Writer
class Chunk(Writer, Reader):
def __init__(self, header):
super().__init__()
self.header = header
self.chunk_name = ''
self.buffer = b''
self.length = 0
def parse(self, buffer: bytes):
Reader.__init__(self, buffer, 'big')
def encode(self):
Writer.__init__(self, 'big')
self.length = len(self.buffer)
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/scw/chunks/chunk.py | chunk.py |
from . import Chunk
class HEAD(Chunk):
def __init__(self, header=None):
super().__init__(header)
self.chunk_name = 'HEAD'
self.version: int = 2
self.frame_rate: int = 30
self.first_frame: int = 0
self.last_frame: int = 0
self.materials_file: str or None = None
self.v3: int = 0
def parse(self, buffer: bytes):
super().parse(buffer)
self.version = self.readUShort()
self.frame_rate = self.readUShort()
self.first_frame = self.readUShort()
self.last_frame = self.readUShort()
self.materials_file = self.readString()
if self.version >= 1:
self.v3 = self.readUByte()
def encode(self):
super().encode()
self.version = 2
self.writeUShort(self.version)
self.writeUShort(self.frame_rate)
self.writeUShort(self.first_frame)
self.writeUShort(self.last_frame)
self.writeString(self.materials_file)
if self.version >= 1:
self.writeUByte(0)
self.length = len(self.buffer)
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/scw/chunks/head.py | head.py |
from . import Chunk
class WEND(Chunk):
def __init__(self, header=None):
super().__init__(header)
self.chunk_name = 'WEND'
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/scw/chunks/wend.py | wend.py |
from .chunk import Chunk
from .head import HEAD
from .mate import MATE
from .geom import GEOM
from .came import CAME
from .node import NODE
from .wend import WEND
__all__ = [
'Chunk',
'HEAD',
'MATE',
'GEOM',
'CAME',
'NODE',
'WEND'
]
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/scw/chunks/__init__.py | __init__.py |
from . import Chunk
from ...universal.camera import Camera
class CAME(Chunk):
def __init__(self, header):
super().__init__(header)
self.chunk_name = 'CAME'
self.camera: Camera or None = None
def parse(self, buffer: bytes):
super().parse(buffer)
name = self.readString()
self.readFloat()
fov = self.readFloat()
aspect_ratio = self.readFloat()
near = self.readFloat()
far = self.readFloat()
self.camera = Camera(name=name, fov=fov, aspect_ratio=aspect_ratio, near=near, far=far)
def encode(self):
super().encode()
self.writeString(self.camera.get_name())
self.writeFloat(self.camera.get_v1())
self.writeFloat(self.camera.get_fov())
self.writeFloat(self.camera.get_aspect_ration())
self.writeFloat(self.camera.get_near())
self.writeFloat(self.camera.get_far())
self.length = len(self.buffer)
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/scw/chunks/came.py | came.py |
from . import Chunk
class MATE(Chunk):
def __init__(self, header):
super().__init__(header)
self.chunk_name = 'MATE'
def parse(self, buffer: bytes):
super().parse(buffer)
setattr(self, 'name', self.readString())
setattr(self, 'shader', self.readString())
setattr(self, 'v1', self.readUByte())
setattr(self, 'v2', self.readUByte())
effect = {}
a = self.readUByte()
r = self.readUByte()
g = self.readUByte()
b = self.readUByte()
ambient_color = (r, g, b, a)
effect['ambient'] = ambient_color
use_diffuse_tex = self.readBool()
if use_diffuse_tex:
diffuse_tex = self.readString()
effect['diffuse'] = diffuse_tex
else:
a = self.readUByte()
r = self.readUByte()
g = self.readUByte()
b = self.readUByte()
diffuse_color = (r, g, b, a)
effect['diffuse'] = diffuse_color
use_specular_tex = self.readBool()
if use_specular_tex:
specular_tex = self.readString()
effect['specular'] = specular_tex
else:
a = self.readUByte()
r = self.readUByte()
g = self.readUByte()
b = self.readUByte()
specular_color = (r, g, b, a)
effect['specular'] = specular_color
setattr(self, 'v3', self.readString())
setattr(self, 'v4', self.readString())
use_colorize_tex = self.readBool()
if use_colorize_tex:
colorize_tex = self.readString()
effect['colorize'] = colorize_tex
else:
a = self.readUByte()
r = self.readUByte()
g = self.readUByte()
b = self.readUByte()
colorize_color = (r, g, b, a)
effect['colorize'] = colorize_color
use_emission_tex = self.readBool()
if use_emission_tex:
emission_tex = self.readString()
effect['emission'] = emission_tex
else:
a = self.readUByte()
r = self.readUByte()
g = self.readUByte()
b = self.readUByte()
emission_color = (r, g, b, a)
effect['emission'] = emission_color
setattr(self, 'opacity_texture', self.readString())
setattr(self, 'v5', self.readFloat())
setattr(self, 'v6', self.readFloat())
effect['lightmaps'] = {
'diffuse': self.readString(),
'specular': self.readString()
}
if self.header.version == 2:
setattr(self, 'v7', self.readString())
shader_define_flags = self.readUInt32()
effect['shader_define_flags'] = shader_define_flags
if shader_define_flags & 32768:
self.readFloat()
self.readFloat()
self.readFloat()
self.readFloat()
setattr(self, 'effect', effect)
def encode(self):
super().encode()
self.writeString(getattr(self, 'name'))
self.writeString(getattr(self, 'shader'))
self.writeUByte(4) # getattr(self, 'v1')
self.writeUByte(0) # getattr(self, 'v2')
effect = getattr(self, 'effect')
r, g, b, a = effect['ambient']
self.writeUByte(a)
self.writeUByte(r)
self.writeUByte(g)
self.writeUByte(b)
use_diffuse_tex = type(effect['diffuse']) is str
self.writeBool(use_diffuse_tex)
if use_diffuse_tex:
self.writeString(effect['diffuse'])
else:
r, g, b, a = effect['diffuse']
self.writeUByte(a)
self.writeUByte(r)
self.writeUByte(g)
self.writeUByte(b)
use_specular_tex = type(effect['specular']) is str
self.writeBool(use_specular_tex)
if use_specular_tex:
self.writeString(effect['specular'])
else:
r, g, b, a = effect['specular']
self.writeUByte(a)
self.writeUByte(r)
self.writeUByte(g)
self.writeUByte(b)
self.writeString('.') # getattr(self, 'v3')
self.writeString('') # getattr(self, 'v4')
use_colorize_tex = type(effect['colorize']) is str
self.writeBool(use_colorize_tex)
if use_colorize_tex:
self.writeString(effect['colorize'])
else:
r, g, b, a = effect['colorize']
self.writeUByte(a)
self.writeUByte(r)
self.writeUByte(g)
self.writeUByte(b)
use_emission_tex = type(effect['emission']) is str
self.writeBool(use_emission_tex)
if use_emission_tex:
self.writeString(effect['emission'])
else:
r, g, b, a = effect['emission']
self.writeUByte(a)
self.writeUByte(r)
self.writeUByte(g)
self.writeUByte(b)
self.writeString('') # getattr(self, 'opacity_texture')
self.writeFloat(1) # getattr(self, 'v5')
self.writeFloat(0) # getattr(self, 'v6')
self.writeString(effect['lightmaps']['diffuse'])
self.writeString(effect['lightmaps']['specular'])
if self.header['version'] == 2:
self.writeString('') # getattr(self, 'v7')
self.writeUInt32(effect['shader_define_flags'])
self.length = len(self.buffer)
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/scw/chunks/mate.py | mate.py |
from xml.etree.ElementTree import *
from .collada import Collada
from ..universal import Scene, Node, Geometry
from ...interfaces import WriterInterface
from ...utilities.matrix.matrix4x4 import Matrix4x4
class Writer(WriterInterface):
def __init__(self):
self.writen = None
self.dae = Collada()
self.library_materials = None
self.library_effects = None
self.library_images = None
self.library_geometries = None
self.library_controllers = None
self.library_animations = None
self.library_cameras = None
self.library_visual_scenes = None
def create_libraries(self):
self.library_materials = SubElement(self.dae.root, 'library_materials')
self.library_effects = SubElement(self.dae.root, 'library_effects')
# self.library_images = SubElement(dae.collada, 'library_images')
self.library_geometries = SubElement(self.dae.root, 'library_geometries')
self.library_controllers = SubElement(self.dae.root, 'library_controllers')
self.library_animations = SubElement(self.dae.root, 'library_animations')
# self.library_cameras = SubElement(self.dae.collada, 'library_cameras')
self.library_visual_scenes = SubElement(self.dae.root, 'library_visual_scenes')
def sign(self):
asset = SubElement(self.dae.root, 'asset')
contributor = SubElement(asset, 'contributor')
SubElement(contributor, 'author').text = 'Vorono4ka'
SubElement(contributor, 'authoring_tool').text = 'models_converter (https://github.com/vorono4ka/3d-converter)'
return contributor
def write(self, scene: Scene):
contributor = self.sign()
# if 'version' in data['header']:
# SubElement(contributor, 'comments').text = 'Version: ' + str(data['header']['version'])
self.create_libraries()
# for material in scene.get_materials():
# self.create_material(material)
for geometry in scene.get_geometries():
geometry_name = self.create_geometry(geometry)
if geometry.has_controller():
self.create_controller(geometry_name, geometry)
self.create_scene(scene)
self.writen = tostring(self.dae.root, xml_declaration=True).decode()
def create_material(self, material_data):
material_name = material_data['name']
SubElement(self.library_materials, 'material', id=material_name)
effect_name = f'{material_name}-effect'
material = SubElement(self.library_materials, 'material', id=material_name)
SubElement(material, 'instance_effect', url=f'#{effect_name}')
effect = SubElement(self.library_effects, 'effect', id=effect_name)
profile = SubElement(effect, 'profile_COMMON')
technique = SubElement(profile, 'technique', sid='common')
ambient_data = material_data['effect']['ambient']
diffuse_data = material_data['effect']['diffuse']
emission_data = material_data['effect']['emission']
specular_data = material_data['effect']['specular']
phong = SubElement(technique, 'phong')
if type(ambient_data) is list:
ambient = SubElement(phong, 'ambient')
ambient_data[3] /= 255
ambient_data = [str(item) for item in ambient_data]
SubElement(ambient, 'color').text = ' '.join(ambient_data)
# else:
# SubElement(ambient, 'texture', texture=ambient_data, texcoord='CHANNEL0')
if type(diffuse_data) is list:
diffuse = SubElement(phong, 'diffuse')
diffuse_data[3] /= 255
diffuse_data = [str(item) for item in diffuse_data]
SubElement(diffuse, 'color').text = ' '.join(diffuse_data)
# else:
# SubElement(diffuse, 'texture', texture=diffuse_data, texcoord='CHANNEL0')
if type(emission_data) is list:
emission = SubElement(phong, 'emission')
emission_data[3] /= 255
emission_data = [str(item) for item in emission_data]
SubElement(emission, 'color').text = ' '.join(emission_data)
# else:
# SubElement(emission, 'texture', texture=emission_data, texcoord='CHANNEL0')
if type(specular_data) is list:
specular = SubElement(phong, 'specular')
specular_data[3] /= 255
specular_data = [str(item) for item in specular_data]
SubElement(specular, 'color').text = ' '.join(specular_data)
# else:
# SubElement(specular, 'texture', texture=specular_data, texcoord='CHANNEL0')
def create_geometry(self, geometry: Geometry):
geometry_name = geometry.get_name()
collada_geometry = SubElement(self.library_geometries, 'geometry', id=f'{geometry_name}-geom')
mesh = SubElement(collada_geometry, 'mesh')
for vertex in geometry.get_vertices():
params = []
vertex_type = vertex.get_type()
vertex_name = vertex.get_name()
coordinate = vertex.get_points()
stride = len(coordinate[0])
if vertex_type == 'VERTEX':
vertex_type = 'POSITION'
source_name = f'{geometry_name}-{vertex_name}'
if vertex_type in ['POSITION', 'NORMAL']:
params.append({'name': 'X', 'type': 'float'})
params.append({'name': 'Y', 'type': 'float'})
params.append({'name': 'Z', 'type': 'float'})
elif vertex_type in ['TEXCOORD']:
params.append({'name': 'S', 'type': 'float'})
params.append({'name': 'T', 'type': 'float'})
self.dae.write_source(
mesh,
source_name,
'float_array',
tuple(' '.join(str(sub_item * vertex.get_scale()) for sub_item in item) for item in coordinate),
stride,
params
)
if vertex_type == 'POSITION':
vertices = SubElement(mesh, 'vertices', id=f'{source_name}-vertices')
self.dae.write_input(vertices, 'POSITION', source_name)
for material in geometry.get_materials():
collada_triangles = SubElement(mesh, 'triangles',
count=f'{len(material.get_triangles())}',
material=material.get_name())
inputs_count = len(material.get_triangles()[0][0])
for vertex_index in range(len(geometry.get_vertices())):
if vertex_index == inputs_count:
break
vertex = geometry.get_vertices()[vertex_index]
input_type = vertex.get_type()
if input_type == 'POSITION':
input_type = 'VERTEX'
source_id = f'{geometry_name}-{vertex.get_name()}'
if input_type == 'VERTEX':
source_id = f'{source_id}-vertices'
self.dae.write_input(collada_triangles, input_type, source_id, vertex_index)
polygons = SubElement(collada_triangles, 'p')
formatted_polygons_data = []
for triangle in material.get_triangles():
for point in triangle:
for coordinate in point:
formatted_polygons_data.append(str(coordinate))
polygons.text = ' '.join(formatted_polygons_data)
return geometry_name
def create_controller(self, geometry_name: str, geometry: Geometry):
controller = SubElement(self.library_controllers, 'controller', id=f'{geometry_name}-cont')
skin = SubElement(controller, 'skin', source=f'#{geometry_name}-geom')
SubElement(skin, 'bind_shape_matrix').text = ' '.join(map(str, geometry.get_bind_matrix()))
joints_names_source_id = f'{geometry_name}-joints'
joints_matrices_source_id = f'{geometry_name}-joints-bind-matrices'
weights_source_id = f'{geometry_name}-weights'
self.dae.write_source(
skin,
joints_names_source_id,
'Name_array',
tuple(joint.get_name() for joint in geometry.get_joints()),
1,
[{'name': 'JOINT', 'type': 'name'}]
)
self.dae.write_source(
skin,
joints_matrices_source_id,
'float_array',
tuple(' '.join(map(str, joint.get_matrix())) for joint in geometry.get_joints()),
16,
[{'name': 'TRANSFORM', 'type': 'float4x4'}]
)
vertex_weights = []
unique_weights = []
vcount = [0] * (len(geometry.get_weights()) // 4)
for weight_index in range(len(geometry.get_weights())):
weight = geometry.get_weights()[weight_index]
if weight.get_strength() == 0:
continue
vcount[weight_index // 4] += 1
vertex_weights.append(weight.get_joint_index())
if weight.get_strength() in unique_weights:
vertex_weights.append(unique_weights.index(weight.get_strength()))
else:
unique_weights.append(weight.get_strength())
vertex_weights.append(len(unique_weights) - 1)
self.dae.write_source(
skin,
weights_source_id,
'float_array',
tuple(map(str, unique_weights)),
1,
[{'name': 'WEIGHT', 'type': 'float'}]
)
joints = SubElement(skin, 'joints')
self.dae.write_input(joints, 'JOINT', joints_names_source_id)
self.dae.write_input(joints, 'INV_BIND_MATRIX', joints_matrices_source_id)
collada_vertex_weights = SubElement(skin, 'vertex_weights', count=f'{len(vcount)}')
self.dae.write_input(collada_vertex_weights, 'JOINT', joints_names_source_id, 0)
self.dae.write_input(collada_vertex_weights, 'WEIGHT', weights_source_id, 1)
SubElement(collada_vertex_weights, 'vcount').text = ' '.join(map(str, vcount))
SubElement(collada_vertex_weights, 'v').text = ' '.join(map(str, vertex_weights))
def create_animation(self, node_name, frames, matrix_output, time_input):
animation = SubElement(self.library_animations, 'animation', id=node_name)
self.dae.write_source(
animation,
f'{node_name}-time-input',
'float_array',
time_input,
1,
[{'name': 'TIME', 'type': 'float'}]
)
self.dae.write_source(
animation,
f'{node_name}-matrix-output',
'float_array',
matrix_output,
16,
[{'name': 'TRANSFORM', 'type': 'float4x4'}]
)
self.dae.write_source(
animation,
f'{node_name}-interpolation',
'Name_array',
tuple('LINEAR' for _ in range(len(frames))),
1,
[{'name': 'INTERPOLATION', 'type': 'name'}]
)
sampler = SubElement(animation, 'sampler', id=f'{node_name}-sampler')
self.dae.write_input(
sampler,
'INPUT',
f'{node_name}-time-input'
)
self.dae.write_input(
sampler,
'OUTPUT',
f'{node_name}-matrix-output'
)
self.dae.write_input(
sampler,
'INTERPOLATION',
f'{node_name}-interpolation'
)
SubElement(animation, 'channel',
source=f'#{node_name}-sampler',
target=f'{node_name}/transform')
def create_scene(self, scene: Scene):
visual_scene = SubElement(self.library_visual_scenes, 'visual_scene',
id='3dConverterScene',
name='3d-Converter Scene')
not_joint_nodes = []
node_index = 0
parent_name = None
while node_index < len(not_joint_nodes) or len(not_joint_nodes) == 0:
if len(not_joint_nodes) > 0:
parent_name = not_joint_nodes[node_index]
for _node in scene.get_nodes():
if _node.get_instances() or _node.get_name() == parent_name:
if not (_node.get_name() in not_joint_nodes):
not_joint_nodes.append(_node.get_name())
if not (_node.get_parent() in not_joint_nodes):
not_joint_nodes.append(_node.get_parent())
node_index += 1
for node in scene.get_nodes():
self.create_node(visual_scene, node, scene, not_joint_nodes)
collada_scene = SubElement(self.dae.root, 'scene')
SubElement(collada_scene, 'instance_visual_scene',
url='#3dConverterScene',
name='3d-Converter Scene')
def create_node(self, visual_scene, node: Node, scene: Scene, not_joint_nodes):
parent_name = node.get_parent()
parent = visual_scene
if parent_name != '':
parent = visual_scene.find(f'.//*[@id="{parent_name}"]')
if parent is None:
parent = visual_scene
node_name = node.get_name()
collada_node = SubElement(parent, 'node', id=node.get_name())
for instance in node.get_instances():
bind_material = None
instance_type = instance.get_type()
if instance_type == 'CONT':
instance_controller = SubElement(collada_node, 'instance_controller',
url=f'#{instance.get_name()}-cont')
bind_material = SubElement(instance_controller, 'bind_material')
elif instance_type == 'GEOM':
instance_controller = SubElement(collada_node, 'instance_geometry', url=f'#{instance.get_name()}-geom')
bind_material = SubElement(instance_controller, 'bind_material')
if instance_type in ['GEOM', 'CONT']:
technique_common = SubElement(bind_material, 'technique_common')
for bind in instance.get_binds():
SubElement(technique_common, 'instance_material',
symbol=bind.get_symbol(),
target=f'#{bind.get_target()}')
else:
if not (node.get_name() in not_joint_nodes):
collada_node.attrib['type'] = 'JOINT'
time_input = []
matrix_output = []
for frame_index in range(len(node.get_frames())):
frame = node.get_frames()[frame_index]
frame_id = frame.get_id()
matrix = Matrix4x4(size=(4, 4))
time_input.append(str(frame_id / scene.get_frame_rate()))
matrix.put_rotation(frame.get_rotation())
matrix.put_position(frame.get_position())
matrix.put_scale(frame.get_scale())
matrix = matrix.translation_matrix @ matrix.rotation_matrix @ matrix.scale_matrix
matrix_values = []
for row in matrix.matrix:
for column in row:
matrix_values.append(str(column))
if frame_index == 0:
SubElement(collada_node, 'matrix', sid='transform').text = ' '.join(matrix_values)
matrix_output.append(' '.join(matrix_values))
if len(node.get_frames()) > 1:
self.create_animation(node_name, node.get_frames(), matrix_output, time_input)
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/collada/writer.py | writer.py |
from xml.etree.ElementTree import *
from .collada import NAMESPACE
from ..universal import Node, Scene, Geometry
from ...interfaces import ParserInterface
from ...utilities import remove_suffix
from ...utilities.matrix.matrix4x4 import Matrix4x4
NAMESPACES = {
'collada': NAMESPACE
}
class Parser(ParserInterface):
def __init__(self, file_data):
self.library_materials = None
self.library_effects = None
self.library_geometries = None
self.library_controllers = None
self.instance_scene = None
self.library_scenes = None
self.scene = Scene()
root = fromstring(file_data)
self.find_libraries(root)
self.instance_scene = root.find('./collada:scene', NAMESPACES).find('collada:instance_visual_scene', NAMESPACES)
def find_libraries(self, root):
self.library_materials = root.find('./collada:library_materials', NAMESPACES)
if self.library_materials is None:
self.library_materials = []
self.library_effects = root.find('./collada:library_effects', NAMESPACES)
self.library_geometries = root.find('./collada:library_geometries', NAMESPACES)
self.library_controllers = root.find('./collada:library_controllers', NAMESPACES)
self.library_scenes = root.find('./collada:library_visual_scenes', NAMESPACES)
def parse(self):
self.parse_materials()
scene_url = self.instance_scene.attrib['url'][1:]
scene = self.library_scenes.find(f'collada:visual_scene[@id="{scene_url}"]', NAMESPACES)
self.parse_node(scene.findall('collada:node', NAMESPACES))
self.parse_nodes()
def parse_materials(self):
for material in self.library_materials:
material_name = material.attrib['name']
instance_effect = material.find('collada:instance_effect', NAMESPACES)
if instance_effect is not None:
effect_url = instance_effect.attrib['url'][1:]
effect = self.library_effects.find(f'collada:effect[@id="{effect_url}"]', NAMESPACES)
if effect is not None:
# profile = None
# for item in effect:
# if 'profile' in item.tag:
# profile = item
# technique = profile.find('collada:technique', NAMESPACES)
#
# emission_data = None
# ambient_data = None
# diffuse_data = None
#
# emission = technique[0].find('collada:emission', NAMESPACES)
# ambient = technique[0].find('collada:ambient', NAMESPACES)
# diffuse = technique[0].find('collada:diffuse', NAMESPACES)
#
# if 'color' in emission[0].tag:
# emission_data = [float(item) for item in emission[0].text.split()]
# emission_data[3] *= 255
# elif 'texture' in emission[0].tag:
# # emission_data = emission[0].attrib['texture']
# emission_data = '.'
#
# if 'color' in ambient[0].tag:
# ambient_data = [float(item) for item in ambient[0].text.split()]
# ambient_data[3] *= 255
# elif 'texture' in ambient[0].tag:
# # ambient_data = ambient[0].attrib['texture']
# ambient_data = '.'
#
# if 'color' in diffuse[0].tag:
# diffuse_data = [float(item) for item in diffuse[0].text.split()]
# diffuse_data[3] *= 255
# elif 'texture' in diffuse[0].tag:
# # diffuse_data = diffuse[0].attrib['texture']
# diffuse_data = '.'
material_data = {
'name': material_name,
'shader': 'shader/uber.vsh',
'effect': {
'ambient': [0, 0, 0, 255], # ambient_data,
'diffuse': '.', # diffuse_data,
'specular': '.',
'colorize': [255, 255, 255, 255],
'emission': [0, 0, 0, 255], # emission_data,
'lightmaps': {
'diffuse': 'sc3d/diffuse_lightmap.png',
'specular': 'sc3d/specular_lightmap.png'
},
'shader_define_flags': 3014
}
}
self.scene.add_material(material_data)
def parse_node(self, xml_nodes: list, parent: str = None):
for xml_node in xml_nodes:
if not ('name' in xml_node.attrib):
xml_node.attrib['name'] = xml_node.attrib['id']
node: Node = Node(
name=xml_node.attrib['name'],
parent=parent
)
instance_geometry = xml_node.findall('collada:instance_geometry', NAMESPACES)
instance_controller = xml_node.findall('collada:instance_controller', NAMESPACES)
for xml_instance in [*instance_geometry, *instance_controller]:
if instance_geometry:
instance = Node.Instance(name=xml_instance.attrib['url'][1:], instance_type='GEOM')
elif instance_controller:
instance = Node.Instance(name=xml_instance.attrib['url'][1:], instance_type='CONT')
else:
continue
bind_material = xml_instance.find('collada:bind_material', NAMESPACES)
technique_common = bind_material[0]
for instance_material in technique_common:
instance.add_bind(instance_material.attrib['symbol'], instance_material.attrib['target'][1:])
node.add_instance(instance)
xml_matrix = xml_node.findall('collada:matrix', NAMESPACES)
if xml_matrix:
matrix = xml_matrix[0].text.split()
matrix = [[float(value) for value in matrix[x:x + 4]] for x in range(0, len(matrix), 4)]
matrix = Matrix4x4(matrix=matrix)
scale = matrix.get_scale()
position = matrix.get_position()
rotation = matrix.get_rotation()
node.add_frame(Node.Frame(0, position, scale, rotation))
self.scene.add_node(node)
self.parse_node(xml_node.findall('collada:node', NAMESPACES), node.get_name())
def parse_nodes(self):
nodes = self.scene.get_nodes()
for node_index in range(len(nodes)):
node = nodes[node_index]
for instance in node.get_instances():
controller = None
collada_geometry = None
if instance.get_type() == 'CONT':
controller = self.library_controllers.find(f'collada:controller[@id="{instance.get_name()}"]',
NAMESPACES)
geometry_url = controller[0].attrib['source'][1:]
collada_geometry = self.library_geometries.find(f'collada:geometry[@id="{geometry_url}"]',
NAMESPACES)
elif instance.get_type() == 'GEOM':
collada_geometry = self.library_geometries.find(f'collada:geometry[@id="{instance.get_name()}"]',
NAMESPACES)
if not ('name' in collada_geometry.attrib):
collada_geometry.attrib['name'] = collada_geometry.attrib['id']
instance._name = collada_geometry.attrib['name']
for suffix in ('-skin', '-cont'):
instance._name = remove_suffix(instance.get_name(), suffix)
for suffix in ('-mesh', '-geom'):
instance._name = remove_suffix(instance.get_name(), suffix)
if collada_geometry is not None:
geometry = self.parse_geometry(collada_geometry)
if controller is not None:
self.parse_controller(controller, geometry)
def parse_controller(self, collada_controller, geometry: Geometry):
skin = collada_controller[0]
bind_shape_matrix = skin.find('collada:bind_shape_matrix', NAMESPACES).text
geometry.set_controller_bind_matrix(list(map(float, bind_shape_matrix.split())))
joints = skin.find('collada:joints', NAMESPACES)
joint_inputs = joints.findall('collada:input', NAMESPACES)
for _input in joint_inputs:
# semantic = _input.attrib['semantic']
source_url = _input.attrib['source']
source = skin.find(f'collada:source[@id="{source_url[1:]}"]', NAMESPACES)
accessor = source.find('collada:technique_common/collada:accessor', NAMESPACES)
accessor_stride = int(accessor.attrib['stride'])
accessor_source_url = accessor.attrib['source']
accessor_source = source.find(f'collada:*[@id="{accessor_source_url[1:]}"]', NAMESPACES)
params = accessor.findall('collada:param', NAMESPACES)
for param in params:
param_name = param.attrib['name']
# param_type = param.attrib['type']
source_data = accessor_source.text.split()
if param_name == 'JOINT':
for name in source_data:
geometry.add_joint(Geometry.Joint(name, None))
if param_name == 'TRANSFORM':
for x in range(int(accessor_source.attrib['count']) // int(accessor_stride)):
matrix = []
for y in source_data[x * accessor_stride:(x + 1) * accessor_stride]:
matrix.append(float(y))
geometry.get_joints()[x].set_matrix(matrix)
vertex_weights = skin.find('collada:vertex_weights', NAMESPACES)
vertex_weights_inputs = vertex_weights.findall('collada:input', NAMESPACES)
for _input in vertex_weights_inputs:
semantic = _input.attrib['semantic']
source_url = _input.attrib['source']
source = skin.find(f'collada:source[@id="{source_url[1:]}"]', NAMESPACES)
if semantic == 'WEIGHT':
accessor = source.find('collada:technique_common/collada:accessor', NAMESPACES)
accessor_source_url = accessor.attrib['source']
accessor_source = source.find(f'collada:*[@id="{accessor_source_url[1:]}"]', NAMESPACES)
weights = None
params = accessor.findall('collada:param', NAMESPACES)
for param in params:
param_name = param.attrib['name']
# param_type = param.attrib['type']
if param_name == 'WEIGHT':
weights = [float(x) for x in accessor_source.text.split()]
break
if weights is None:
continue
vcount = vertex_weights.find('collada:vcount', NAMESPACES).text
v = vertex_weights.find('collada:v', NAMESPACES).text
v = map(int, v.split())
for count in map(int, vcount.split()):
for i in range(count):
joint_index = next(v)
strength_index = next(v)
geometry.add_weight(Geometry.Weight(joint_index, weights[strength_index]))
while count < 4:
geometry.add_weight(Geometry.Weight(0, 0))
count += 1
break
def parse_geometry(self, collada_geometry) -> Geometry:
name = collada_geometry.attrib['name']
for suffix in ('-mesh', '-geom'):
name = remove_suffix(name, suffix)
geometry = Geometry(name=name, group='GEO')
mesh = collada_geometry[0]
triangles = mesh.findall('collada:triangles', NAMESPACES)
if triangles:
pass
else:
triangles = mesh.findall('collada:polylist', NAMESPACES)
inputs = triangles[0].findall('collada:input', NAMESPACES)
for _input in inputs:
semantic = _input.attrib['semantic']
source_link = _input.attrib['source'][1:]
source = mesh.find(f'*[@id="{source_link}"]')
if semantic == 'VERTEX':
vertices_input = source[0]
semantic = vertices_input.attrib['semantic']
source_link = vertices_input.attrib['source'][1:]
source = mesh.find(f'*[@id="{source_link}"]')
float_array = source.find('collada:float_array', NAMESPACES)
accessor = source.find('collada:technique_common/collada:accessor', NAMESPACES)
points_temp = [float(floating) for floating in float_array.text.split()]
scale = max(max(points_temp), abs(min(points_temp)))
if scale < 1:
scale = 1
if semantic == 'TEXCOORD':
points_temp[1::2] = [1 - x for x in points_temp[1::2]]
points_temp = [value / scale for value in points_temp]
points = []
for x in range(0, len(points_temp), len(accessor)):
points.append(points_temp[x: x + len(accessor)])
geometry.add_vertex(Geometry.Vertex(
name='',
vertex_type=semantic,
vertex_index=len(geometry.get_vertices()),
vertex_scale=scale,
points=points
))
for triangle in triangles:
triangles_material = triangle.attrib['material']
p = triangle.find('collada:p', NAMESPACES)
triangles_temp = [int(integer) for integer in p.text.split()]
triangles = [
[
triangles_temp[polygon_index + point_index:polygon_index + point_index + 3]
for point_index in range(0, len(inputs) * 3, 3)
] for polygon_index in range(0, len(triangles_temp), len(inputs) * 3)
]
geometry.add_material(Geometry.Material(name=triangles_material, triangles=triangles))
self.scene.add_geometry(geometry)
return geometry
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/collada/parser.py | parser.py |
from xml.etree.ElementTree import *
VERSION = '1.4.1'
NAMESPACE = 'http://www.collada.org/2005/11/COLLADASchema'
class Collada:
def __init__(self):
self.root = Element('COLLADA', version=VERSION, xmlns=NAMESPACE)
@staticmethod
def write_source(parent,
source_id: str,
array_tag: str,
array_data: tuple,
stride: int,
params: list):
source = SubElement(parent, 'source', id=source_id)
array = SubElement(source, array_tag)
array.attrib = {'id': f'{source_id}-array',
'count': f'{len(array_data) * stride}'}
technique_common = SubElement(source, 'technique_common')
accessor = SubElement(technique_common, 'accessor')
accessor.attrib = {'source': f'#{source_id}-array',
'count': f'{len(array_data)}',
'stride': f'{stride}'}
for param_data in params:
param = SubElement(accessor, 'param')
param.attrib = param_data
array.text = ' '.join(array_data)
@staticmethod
def write_input(parent,
semantic: str,
source_id: str,
offset: int = None):
attributes = {
'semantic': semantic,
'source': f'#{source_id}'
}
if offset is not None:
attributes['offset'] = f'{offset}'
_input = SubElement(parent, 'input')
_input.attrib = attributes
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/collada/collada.py | collada.py |
from .writer import Writer
from .parser import Parser
__all__ = [
'Writer',
'Parser'
]
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/collada/__init__.py | __init__.py |
from models_converter.formats.universal import Scene
from models_converter.interfaces import WriterInterface
class Writer(WriterInterface):
def __init__(self):
self.writen = ''
self.temp_vertices_offsets = {
'POSITION': 0,
'TEXCOORD': 0,
'NORMAL': 0
}
self.vertices_offsets = {
'POSITION': 0,
'TEXCOORD': 0,
'NORMAL': 0
}
def write(self, scene: Scene):
for geometry in scene.get_geometries():
for key in self.vertices_offsets.keys():
self.vertices_offsets[key] = self.temp_vertices_offsets[key]
prefix = ''
for vertex in geometry.get_vertices():
if vertex.get_type() == 'POSITION':
prefix = 'v '
elif vertex.get_type() == 'NORMAL':
prefix = 'vn '
elif vertex.get_type() == 'TEXCOORD':
prefix = 'vt '
self.temp_vertices_offsets[vertex.get_type()] += len(vertex.get_points())
for triangle in vertex.get_points():
temp_string = prefix
for point in triangle:
temp_string += str(point * vertex.get_scale()) + ' '
self.writen += f'{temp_string}\n'
self.writen += '\n\n'
for material in geometry.get_materials():
self.writen += f'o {geometry.get_name()}|{material.get_name()}\n\n'
for triangle in material.get_triangles():
temp_string = 'f '
for point in triangle:
temp_list = [
str(point[0] + self.vertices_offsets['POSITION'] + 1), # POSITION
str(point[2] + self.vertices_offsets['TEXCOORD'] + 1), # TEXCOORD
str(point[1] + self.vertices_offsets['NORMAL'] + 1) # NORMAL
]
temp_string += '/'.join(temp_list) + ' '
self.writen += f'{temp_string}\n'
self.writen += '\n\n'
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/wavefront/writer.py | writer.py |
from models_converter.formats.universal import Scene, Node, Geometry
from models_converter.interfaces import ParserInterface
from models_converter.utilities.math import Vector3, Quaternion
class Parser(ParserInterface):
def __init__(self, file_data: bytes or str):
if type(file_data) is bytes:
file_data = file_data.decode()
self.scene = Scene()
self.lines = file_data.split('\n')
self.position_temp, self.position = [], []
self.normals_temp, self.normals = [], []
self.texcoord_temp, self.texcoord = [], []
def parse(self):
triangles = []
geometry_name = None
material = 'character_mat'
position_scale, normals_scale, texcoord_scale = 1, 1, 1
vertices_offsets = {
'POSITION': 0,
'TEXCOORD': 0,
'NORMAL': 0
}
names = [line[2:].split('|')[0]
for line in list(filter(lambda line: line.startswith('o '), self.lines))]
for line_index in range(len(self.lines)):
line = self.lines[line_index]
items = line.split()[1:]
if line.startswith('v '): # POSITION
for item in items:
self.position_temp.append(float(item))
elif line.startswith('vn '): # NORMAL
for item in items:
self.normals_temp.append(float(item))
elif line.startswith('vt '): # TEXCOORD
if len(items) > 2:
items = items[:-1]
for item in items:
self.texcoord_temp.append(float(item))
elif line.startswith('f '):
temp_list = []
if len(items) > 3:
raise ValueError('It is necessary to triangulate the model')
for item in items:
second_temp_list = []
if len(item.split('/')) == 2:
raise ValueError('Model have not normals or texture')
elif len(item.split('/')) == 1:
raise ValueError('Model have not normals and texture')
for x in item.split('/'):
second_temp_list.append(int(x) - 1)
temp_list.append([second_temp_list[0] - vertices_offsets['POSITION'],
second_temp_list[2] - vertices_offsets['TEXCOORD'],
second_temp_list[1] - vertices_offsets['NORMAL']])
triangles.append(temp_list)
elif line.startswith('o '):
geometry_name = items[0]
if '|' in items[0]:
geometry_name, material = items[0].split('|')
if self.position_temp:
self.position = []
position_scale = self._get_vertex_scale(self.position_temp)
for x in range(0, len(self.position_temp), 3):
self.position.append([vertex / position_scale for vertex in self.position_temp[x: x + 3]])
if self.normals_temp:
self.normals = []
normals_scale = self._get_vertex_scale(self.normals_temp)
for x in range(0, len(self.normals_temp), 3):
self.normals.append([vertex / normals_scale for vertex in self.normals_temp[x: x + 3]])
if self.texcoord_temp:
self.texcoord = []
texcoord_scale = self._get_vertex_scale(self.texcoord_temp)
for x in range(0, len(self.texcoord_temp), 2):
self.texcoord.append([vertex / texcoord_scale for vertex in self.texcoord_temp[x: x + 2]])
if not line.startswith('f ') and triangles and geometry_name and \
self.position and self.normals and self.texcoord:
self.position_temp = []
self.normals_temp = []
self.texcoord_temp = []
if len(names) > len(self.scene.get_geometries()) + 1 and \
names[len(self.scene.get_geometries()) + 1] != geometry_name:
vertices_offsets['POSITION'] += len(self.position)
vertices_offsets['TEXCOORD'] += len(self.normals)
vertices_offsets['NORMAL'] += len(self.texcoord)
if not (self.scene.get_geometries() and self.scene.get_geometries()[-1].get_name() == geometry_name):
geometry = Geometry(name=geometry_name, group='GEO')
geometry.add_vertex(Geometry.Vertex(
name='position_0',
vertex_type='POSITION',
vertex_index=0,
vertex_scale=position_scale,
points=self.position
))
geometry.add_vertex(Geometry.Vertex(
name='normal_0',
vertex_type='NORMAL',
vertex_index=1,
vertex_scale=normals_scale,
points=self.normals
))
geometry.add_vertex(Geometry.Vertex(
name='texcoord_0',
vertex_type='TEXCOORD',
vertex_index=2,
vertex_scale=texcoord_scale,
points=self.texcoord
))
self.scene.add_geometry(geometry)
self.scene.get_geometries()[-1].add_material(
Geometry.Material(material, triangles)
)
material = 'character_mat'
triangles = []
for geometry in self.scene.get_geometries():
node = Node(name=geometry.get_name(), parent='')
instance = Node.Instance(name=geometry.get_name(), instance_type='GEOM')
for material in geometry.get_materials():
instance.add_bind(material.get_name(), material.get_name())
node.add_instance(instance)
node.add_frame(Node.Frame(0, Vector3(), Vector3(1, 1, 1), Quaternion()))
self.scene.add_node(node)
@staticmethod
def _get_vertex_scale(vertex_data: list):
vertex_scale = max(max(vertex_data), abs(min(vertex_data)))
if vertex_scale < 1:
vertex_scale = 1
return vertex_scale
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/wavefront/parser.py | parser.py |
from .parser import Parser
from .writer import Writer
__all__ = [
'Writer',
'Parser'
]
| 3d-converter | /3d-converter-0.9.0.tar.gz/3d-converter-0.9.0/models_converter/formats/wavefront/__init__.py | __init__.py |
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
# ##### END GPL LICENSE BLOCK #####
import pygame
from .classes import Mesh, CameraOrtho
def cube():
camera = CameraOrtho((45, 45), (0, 0), 5)
mesh = Mesh(
((-1, -1, -1), (-1, -1, 1), (-1, 1, -1), (-1, 1, 1), (1, -1, -1), (1, -1, 1), (1, 1, -1), (1, 1, 1)),
((3, 7, 5, 1), (1, 5, 4, 0), (0, 4, 6, 2), (6, 2, 3, 7), (5, 7, 6, 4), (1, 3, 2, 0)),
((128, 128, 128), (128, 128, 128), (128, 128, 128), (128, 128, 128), (128, 128, 128), (128, 128, 128))
)
pygame.init()
pygame.display.set_caption("3D Example: Cube")
WINDOW = pygame.display.set_mode((720, 720))
clock = pygame.time.Clock()
dragging = False
drag_start_pos = (0, 0)
view_start_pos = (0, 0)
while True:
clock.tick(60)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
return
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 4:
camera.size /= 1.1
elif event.button == 5:
camera.size *= 1.1
WINDOW.fill((0, 0, 0))
WINDOW.blit(camera.render(mesh, (720, 720)), (0, 0))
if pygame.mouse.get_pressed()[0]:
if dragging:
mouse_pos = pygame.mouse.get_pos()
new_view = (view_start_pos[0] - (mouse_pos[1]-drag_start_pos[1])/5, view_start_pos[1] + (mouse_pos[0]-drag_start_pos[0])/5)
camera.angle = new_view
else:
dragging = True
drag_start_pos = pygame.mouse.get_pos()
view_start_pos = camera.angle[:]
else:
dragging = False | 3d-renderer | /3d_renderer-0.0.6-py3-none-any.whl/renderer/examples.py | examples.py |
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
# ##### END GPL LICENSE BLOCK #####
import pygame
from math import radians, sin, cos
class CameraOrtho:
def __init__(self, angle=(0, 0), shift=(0, 0), size=5):
"""
Initializes camera.
:param angle: Angle of the camera in (latitude, longitude)
:type angle: Tuple[float, float]
:param shift: Shift of camera in (x, y)
:type shift: Tuple[float, float]
:param size: Orthographic size of camera.
:type size: float
"""
self.angle = angle
self.shift = shift
self.size = size
def render(self, mesh, resolution, bg_col=(0, 0, 0, 0)):
"""
Renders mesh as a pygame surface.
:param mesh: Mesh to render.
:type mesh: renderer.Mesh
:param resolution: Resolution to render in (x, y). The Y size will be adjusted, and the X size will be the ortho size.
:type resolution: Tuple[int, int]
:param bg_col: Background color of render in (R, G, B, [A])
:type bg_col: Tuple[int]
"""
surface = pygame.Surface(resolution, pygame.SRCALPHA)
surface.fill(bg_col)
data = mesh.setup_render()
for face in data:
color = face[0]
locs = []
for vert in face[1]:
locs.append(self.project(vert, resolution))
pygame.draw.polygon(surface, color, locs)
return surface
def project(self, vert, res):
size_hor = self.size
size_ver = self.size / res[0] * res[1]
loc_x, loc_y, loc_z = vert
view_ver = radians(self.angle[0])
view_hor = radians(self.angle[1])
px_hor = loc_x*cos(view_hor) + loc_y*sin(view_hor)
px_hor *= res[0] / size_hor
px_hor += res[0] / 2
px_ver = loc_z*sin(view_ver) - loc_x*sin(view_hor)*cos(view_ver) + loc_y*cos(view_hor)*cos(view_ver)
px_ver *= res[1] / size_ver
px_ver += res[1] / 2
return (px_hor, px_ver)
class Mesh:
def __init__(self, verts, faces, colors):
"""
Initializes mesh.
:param verts: Tuple of (x, y, z) locations.
:type verts: Tuple[Tuple[float, float, float]]
:param faces: Tuple of vertex indexes.
:type faces: Tuple[Tuple[int]]
:param colors: Colors (r, g, b) corresponding to each face.
:type colors: Tuple[Tuple[int, int, int]]
"""
self.set_mesh(verts, faces, colors)
def set_mesh(self, verts, faces, colors):
"""
Initializes mesh.
:param verts: Tuple of (x, y, z) locations.
:type verts: Tuple[Tuple[float, float, float]]
:param faces: Tuple of vertex indexes.
:type faces: Tuple[Tuple[int]]
:param colors: Colors (r, g, b) corresponding to each face.
:type colors: Tuple[Tuple[int, int, int]]
"""
self.verts = verts
self.colors = colors
self.faces = []
for face in faces:
self.faces.append([verts[i] for i in face])
def setup_render(self):
"""
Returns a list that the renderer can understand. This should only be called by the renderer.
"""
faces = []
for i, face in enumerate(self.faces):
if len(face) == 3:
faces.append((self.colors[i], face))
else:
curr_color = self.colors[i]
for vert in range(1, len(face)-1):
faces.append((curr_color, (face[0], face[vert], face[vert+1])))
return faces | 3d-renderer | /3d_renderer-0.0.6-py3-none-any.whl/renderer/classes.py | classes.py |
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
# ##### END GPL LICENSE BLOCK #####
from . import examples
from .classes import CameraOrtho, Mesh | 3d-renderer | /3d_renderer-0.0.6-py3-none-any.whl/renderer/__init__.py | __init__.py |
# 3D Video Converter
A simple FFMPEG-based script for converting either two separate stereo videos or an existing 3D video into a wide range of 3D video formats.
## Installation
### Install `3d-video-converter`
From PyPI:
```bash
pip install 3d-video-converter
```
Or from the source on GitHub:
```bash
pip install "3d-video-converter @ git+https://github.com/evoth/3d-video-converter"
```
The package will be installed with the module name `video_converter_3d`.
### Install FFmpeg
This package depends on [ffmpeg-python](https://github.com/kkroening/ffmpeg-python), which means that [FFmpeg](https://ffmpeg.org/) must be installed and accessible via the `$PATH` environment variable. Please follow appropriate installation instructions for your platform.
To check if FFmpeg is installed, run the `ffmpeg` command from the terminal. If it is installed correctly, you should see version and build information.
## Usage examples
Convert a full-width parallel view video to full color red/cyan anaglyph:
```python
from video_converter_3d import convert_3d
convert_3d("video_parallel.mp4", "sbsl", "video_anaglyph.mp4", "arcc")
```
Combine two separate stereo videos into a full-width parallel view video, only keeping audio from the left video:
```python
from video_converter_3d import convert_2d_to_3d
convert_2d_to_3d(
"video_left.mp4",
"video_right.mp4",
True,
False,
"video_parallel.mp4",
"sbsl"
)
```
| 3d-video-converter | /3d-video-converter-0.0.4.tar.gz/3d-video-converter-0.0.4/README.md | README.md |
from setuptools import setup
from pathlib import Path
this_directory = Path(__file__).parent
long_description = (this_directory / "README.md").read_text()
setup(
name="3d-video-converter",
packages=["video_converter_3d"],
version="0.0.4",
author="Ethan Voth",
author_email="ethanvoth7@gmail.com",
url="https://github.com/evoth/3d-video-converter",
description="FFMPEG-based tool for converting either two separate stereo videos or an existing 3D video into a wide range of 3D video formats.",
long_description=long_description,
long_description_content_type="text/markdown",
install_requires=[
"ffmpeg-python",
"opencv-python",
],
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
)
| 3d-video-converter | /3d-video-converter-0.0.4.tar.gz/3d-video-converter-0.0.4/setup.py | setup.py |
from typing import Any, Dict
import ffmpeg
from cv2 import CAP_PROP_FPS, VideoCapture
def convert_3d(
in_video: str,
in_type: str,
out_video: str,
out_type: str,
out_ffmpeg_options: Dict[str, Any] = {"c:v": "libx264", "crf": 18},
) -> None:
"""
Given a 3D video and its type of 3D, converts to a 3D video of a different
type (see https://ffmpeg.org/ffmpeg-filters.html#stereo3d for available
input and output type strings). For example, to convert a full-width
parallel view video to full color red/cyan anaglyph, the `in_type` would be
`"sbsl"` and the `out_type` would be `"arcc"`.
Optionally, export settings can be adjusted
via `out_ffmpeg_options`, which are passed to the ffmpeg-python output
function.
"""
stream = ffmpeg.input(in_video)
audio = stream.audio
if in_type != out_type:
filter_options = {"in": in_type, "out": out_type}
stream = ffmpeg.filter(stream, "stereo3d", **filter_options)
stream = ffmpeg.output(stream, audio, out_video, **out_ffmpeg_options)
ffmpeg.run(stream)
def convert_2d_to_3d(
in_video_left: str,
in_video_right: str,
use_audio_left: bool,
use_audio_right: bool,
out_video: str,
out_type: str,
out_ffmpeg_options: Dict[str, Any] = {"c:v": "libx264", "crf": 18},
offset: float = 0,
overwrite: bool = False,
) -> None:
"""
Given two separate stereo videos of identical dimensions and constant
framerates, combines into a 3D video of the specified type (see
https://ffmpeg.org/ffmpeg-filters.html#stereo3d for available output type
strings). For example, to combine the videos into a full-width parallel view
video, the `out_type` would be `"sbsl"`.
The audio from either or both videos may be used, depending on the value of
`use_audio_left` and `use_audio_right`. If both are `True`, mixes audio down
into mono or stereo, depending on the input files. However, if using audio
from both videos, there may be slight echoing artifacts.
Additionally, the offset between `in_video_left` and `in_video_right` can be
specified by setting `offset` to the number of seconds `in_video_right` is
delayed from `in_video_left` (or vice versa for a negative value).
Optionally, export settings can be adjusted
via `out_ffmpeg_options`, which are passed to the ffmpeg-python output
function. Set `overwrite` to `True` to automatically overwrite files.
"""
# Apply offset by trimming beginning of video that starts earlier
in_options_left = {}
if offset > 0:
in_options_left["ss"] = offset
stream_left = ffmpeg.input(in_video_left, **in_options_left)
in_options_right = {}
if offset < 0:
in_options_right["ss"] = -1 * offset
stream_right = ffmpeg.input(in_video_right, **in_options_right)
# Create parallel view video which can be converted to another type (or
# cross view if the output type is cross view)
if out_type == "sbsr":
stream = ffmpeg.filter(
[stream_right.video, stream_left.video], "hstack", inputs=2, shortest=1
)
else:
stream = ffmpeg.filter(
[stream_left.video, stream_right.video], "hstack", inputs=2, shortest=1
)
# Convert parallel view to another type
if out_type not in ["sbsl", "sbsr"]:
filter_options = {"in": "sbsl", "out": out_type}
stream = ffmpeg.filter(stream, "stereo3d", **filter_options)
# Process audio
if use_audio_left and use_audio_right:
audio = ffmpeg.filter(
[stream_left.audio, stream_right.audio], "amerge", inputs=2
)
out_ffmpeg_options["ac"] = 2
elif use_audio_left:
audio = stream_left.audio
elif use_audio_right:
audio = stream_right.audio
# Get framerate
cap = VideoCapture(in_video_left)
fps = cap.get(CAP_PROP_FPS)
# Configure output
out_ffmpeg_options["fps_mode"] = "cfr"
out_ffmpeg_options["r"] = fps
if use_audio_left or use_audio_right:
stream = ffmpeg.output(stream, audio, out_video, **out_ffmpeg_options)
else:
stream = ffmpeg.output(stream, out_video, **out_ffmpeg_options)
ffmpeg.run(stream, overwrite_output=overwrite)
| 3d-video-converter | /3d-video-converter-0.0.4.tar.gz/3d-video-converter-0.0.4/video_converter_3d/converter.py | converter.py |
from .converter import convert_2d_to_3d, convert_3d
| 3d-video-converter | /3d-video-converter-0.0.4.tar.gz/3d-video-converter-0.0.4/video_converter_3d/__init__.py | __init__.py |
3D Wallet Generator
===================
This project helps you design and export 3D-printable wallets, similar to paper wallets (but they won't die in a flood)
-----------------------------------------------------------------------------------------------------------------------
Everyone who's seriously serious about bitcoin has tried paper wallet
generators. While the idea is great, paper isn't a great medium out of
which to make something that stores significant value. This this in
mind, we set out to make a simple, easy-to-use software that can design
and export 3D-printable wallets, with a variety of configuration
options.
Dependencies
------------
- Python3: this project is designed for Python3, not Python2
- PyBitcoin, ``sudo pip3 install bitcoin`` **(no manual installation required)**
- PyQRCode, ``sudo pip3 install pyqrcode`` **(no manual installation required)**
- OpenSCAD 2015 (or higher), just install from their website, and the
program should find it automatically (submit an issue if it doesn't) - **(manual installation required)**
Features
--------
- Supports a variety of configuration and size options
- Exports wallets as STL
- Export keys as CSV-file for import into other software (for big
batches)
- Set the configuration and let it generate millions of **random**
wallets for you
- Support for other cryptocurrencies, including:
- Bitcoin
- Litecoin
- Dogecoin
- Any other currency (as long as you know the version bit for address generation)
Instructions
------------
1. Install pip
- Windows: download from their website
- Mac: install from MacPorts or Brew
- Linux (Ubuntu/Debian): ``sudo apt-get install python3-pip``
2. Install OpenSCAD
- `Download from their website <http://openscad.org/downloads.html>`_
- Make sure you are running their newest version (or at least OpenSCAD 2015)
- Contact us if you need help.
3. Install our package
- Try: ``sudo pip3 install 3d-wallet-generator``
- If it continues to fail, shoot us an email and we'll try to help.
4. Use our package
- Run ``3dwallet -h`` to see your options
- Try the default settings by running `3dwallet` - it will output five wallets, with the default settings, into a folder in your current directory.
- Play with the other settings and decide how your printer, CNC, etc. likes the different styles.
- Film it or take a picture, and give it to us! We'll add it to our collection!
We recommend you run the Linux version off of a LiveUSB for maximum
security (just as you would with a normal paper wallet).
Miscellaneous
-------------
- If you have any comments, questions, or feature requests, either
submit an issue or contact us at btcspry@bitforwarder.com
- We always accept donations at
**1MF7hKShzq2iSV9ZZ9hEx6ATnHQpFtM7cF!!** Please donate, this project
took a bunch of effort and we want to make sure it was worth it.
To Do / Features Coming Soon
----------------------------
- Add pictures
- Add option to import your own addresses/private keys
- Offset the white in the QR code (instead of just offsetting the
black)
- If you want any of these developed faster, send us a gift to our donation address above.
| 3d-wallet-generator | /3d-wallet-generator-0.2.0.tar.gz/3d-wallet-generator-0.2.0/README.rst | README.rst |
from setuptools import setup
long_description = open('README.rst').read()
setup(
name = '3d-wallet-generator',
packages = ['gen_3dwallet'],
version = '0.2.0',
description = 'A tool to help you design and export 3D-printable bitcoin/cryptocurrency wallets',
long_description=long_description,
author = 'BTC Spry',
author_email = 'btcspry@bitforwarder.com',
url = 'https://github.com/btcspry/3d-wallet-generator',
install_requires=["bitcoin>=1.1.29","PyQrCode>=1.1"],
keywords = ['bitcoin','litecoin','dogecoin','wallet','3d printer','cryptocurrency','altcoin','money'],
classifiers = ["Programming Language :: Python :: 3 :: Only","License :: OSI Approved :: MIT License","Operating System :: OS Independent","Intended Audience :: End Users/Desktop","Environment :: Console","Development Status :: 4 - Beta","Topic :: Utilities"],
entry_points={
'console_scripts': [
'3dwallet = gen_3dwallet.base:main',
],
},
)
| 3d-wallet-generator | /3d-wallet-generator-0.2.0.tar.gz/3d-wallet-generator-0.2.0/setup.py | setup.py |
#!/usr/bin/python3
try:
import qr_tools as qrTools # Module for this project
except:
import gen_3dwallet.qr_tools as qrTools
try:
import TextGenerator as textGen # Module for this project
except:
import gen_3dwallet.TextGenerator as textGen
import bitcoin # sudo pip3 install bitcoin
import argparse
import time
import math
import sys
import os
import distutils.spawn
def parse_args():
parser = argparse.ArgumentParser(description='Generate an STL file of a 3D-printable bitcoin, litecoin, dogecoin, or other type of coin.', formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('-ve', '--version', dest='versionByte', type=int, default=0, help='Version Bit of the address (for other altcoins).\nBitcoin: 0 (Default)\n Litecoin: 48\n Dogecoin: 30')
parser.add_argument('-ct', '--coin-title', dest='coinTitle', type=str, default="Bitcoin", help='Title of the coin, used for design purposes \n(Default: Bitcoin)')
parser.add_argument('-ls', '--layout-style', dest='layoutStyle', type=int, default=1, help="Layout style of the wallet.\n1) Address on the Front, Private Key on the Back (Default)\n2) Private Key Only\n3) Address Only (don't forget to export the Private Keys after)")
parser.add_argument('-wi', '--width', dest='walletWidth', type=float, default=54.0, help='The width of the wallet in mm. The length is calculated automatically. Default option is approximately standard credit card legnth and width. \n(Default: 54.0)')
parser.add_argument('-he', '--height', dest='walletHeight', type=float, default=8.0, help='The height of the wallet in mm. \n(Default: 8)')
parser.add_argument('-bo', '--black-offset', dest='blackOffset', type=int, default=-30, help='The percentage of the height that the black part of the QR code, and the text, will be raised or lowered by.\nNegative number for lowered, positive for raised. Option must be greater than -90. \n(Default: -20)')
parser.add_argument('-ec', '--qr-error-correction', dest='errorCorrection', type=str, default="M", help='The percentage of the QR codes that can be destroyed before they are irrecoverable\nL) 7 percent\nM) 15 percent (Default)\nQ) 25 percent\nH) 30 percent')
parser.add_argument('-dc', '--disable-round-corners', dest='roundCorners', action='store_false', help="Round the coners (four short edges) of the wallet. \n(Default: disabled)")
parser.add_argument('-co', '--copies', dest='copies', type=int, default=5, help='The number of wallets to generate. These will all be unique and randomly-generate wallets (not copies). \n(Default: 5)')
parser.add_argument('-sd', '--openscad-exe', dest='scadExe', type=str, default="openscad", help='The location and filename of the command line tools for OpenSCAD (leave as default if it is installed as a command [ie. Linux])\nIn most cases on Windows and Mac, the executable will be found automatically.')
parser.add_argument('-o', '--stl-folder', dest='outputSTLFolder', type=str, default="./WalletsOut/", help='The output folder to export the STL files into\n(Default: ./WalletsOut/)')
parser.add_argument('-oc', '--scad-folder', dest='outputSCADFolder', type=str, default='', help='The output folder to store the SCAD generation files in (optional, only used for debugging)\n(Default: disabled)')
parser.add_argument('-ea', '--export-address-csv', dest='exportAddressCSV', type=str, default='', help='The output CSV file to export the address list to (optional)\n(Default: disabled)')
parser.add_argument('-ep', '--export-privkey-csv', dest='exportPrivkeyCSV', type=str, default='', help='The output CSV file to export the private key list to (optional)\n(Default: disabled)')
parser.add_argument('-eap', '--export-address-privkey-csv', dest='exportAPCSV', type=str, default='', help='The output CSV file to export the address and private key list to, in the format of "address,privkey" (optional)\n(Default: disabled)')
parser.add_argument('-epa', '--export-privkey-address-csv', dest='exportPACSV', type=str, default='', help='The output CSV file to export the address and private key list to, in the format of "privkey,address" (optional)\n(Default: disabled)')
return parser.parse_args()
def main():
args = parse_args()
# Set DEBUG variable for testing purposes (changing styling)
# If true, prints the SCAD to the terminal and then breaks after first generation
DEBUG = False
# Generate the addresses
if args.copies < 1:
print("Please enter a valid number of copies (-co flag), and try again.")
sys.exit()
else: # Use an else statement here just in case we add the option to import a CSV file with the keys (generated somewhere else)
walletDataList = []
for i in range(args.copies):
thisData = {}
# Generate the addresses with keys
thisData["privateKey"] = bitcoin.main.random_key() # Secure: uses random library, time library and proprietary function
thisData["wif"] = bitcoin.encode_privkey(thisData["privateKey"], "wif", args.versionByte)
thisData["address"] = bitcoin.privkey_to_address(thisData["privateKey"], args.versionByte)
# Generate the QR codes
if args.errorCorrection.upper() not in ["L","M","Q","H"]:
print("Please select a valid QR Error Correction value (L, M, Q, or H).")
sys.exit()
thisData["wifQR"] = qrTools.getQRArray(thisData["wif"], args.errorCorrection.upper())
thisData["addressQR"] = qrTools.getQRArray(thisData["address"], args.errorCorrection.upper())
# Reverse them or else they appear backwards (unknown reason)
thisData["wifQR"] = list(reversed(thisData["wifQR"]))
thisData["addressQR"] = list(reversed(thisData["addressQR"]))
# Append ALL the wallet information, just in case we want to do something with it later
walletDataList.append(thisData)
# Validate other args and set some constants
walletWidth = args.walletWidth
walletHeight = args.walletHeight
if args.layoutStyle == 1 or args.layoutStyle == 2 or args.layoutStyle == 3:
walletLength = walletWidth*1.6 # Approximately the same ratio as a credit card
else:
print("Please choose a valid layout style option.")
sys.exit()
if args.blackOffset < -90.0:
print("Please ensure that --black-offset (-bo flag) is set correctly, and is greater than -90.")
sys.exit()
textDepth = (args.blackOffset/100) * walletHeight
# Check the openscad command
scadExe = args.scadExe
if args.scadExe == "openscad" and not distutils.spawn.find_executable("openscad"):
if os.path.isfile("/Applications/OpenSCAD.app/Contents/MacOS/OpenSCAD"):
print("Info: OpenSCAD found in Applications folder on Mac")
scadExe = "/Applications/OpenSCAD.app/Contents/MacOS/OpenSCAD"
elif os.path.isfile("%PROGRAMFILES%\OpenSCAD\openscad.exe"):
print("Info: OpenSCAD found in Program Files on Windows")
scadExe = "%PROGRAMFILES%\OpenSCAD\openscad.exe"
elif os.path.isfile("%PROGRAMFILES(x86)%\OpenSCAD\openscad.exe"):
print("Info: OpenSCAD found in Program Files (x86) on Windows")
scadExe = "%PROGRAMFILES(x86)%\OpenSCAD\openscad.exe"
if not distutils.spawn.find_executable(scadExe):
print("Please install OpenSCAD or specify the location of it with --openscad-exe.")
sys.exit()
# Set the master SCAD variable
masterSCAD = "// SCAD Code Generated By 3DGen.py - 3D Wallet Generator\n\n" # The beginning of the wallet are identical
scadOutputs = [] # Generated from loop for each wallet (different addresses)
# Include some modules at the beginning
masterSCAD += "// Import some modules\n"
masterSCAD += """
$fn=100;
module createMeniscus(h,radius)difference(){translate([radius/2+0.1,radius/2+0.1,0]){cube([radius+0.2,radius+0.1,h+0.2],center=true);}cylinder(h=h+0.2,r=radius,center=true);}
module roundCornersCube(x,y,z)translate([x/2,y/2,z/2]){difference(){r=((x+y)/2)*0.052;cube([x,y,z],center=true);translate([x/2-r,y/2-r]){rotate(0){createMeniscus(z,r);}}translate([-x/2+r,y/2-r]){rotate(90){createMeniscus(z,r);}}translate([-x/2+r,-y/2+r]){rotate(180){createMeniscus(z,r);}}translate([x/2-r,-y/2+r]){rotate(270){createMeniscus(z,r);}}}}
""" # The rounding corners modules for creating a rounded rectangle
masterSCAD += "\n"
# Draw the main prism
if args.roundCorners:
mainCube = "roundCornersCube(" + str(walletLength) + "," + str(walletWidth) + "," + str(walletHeight) + ");"
else:
mainCube = "cube([" + str(walletLength) + "," + str(walletWidth) + "," + str(walletHeight) + "]);"
mainCube += "\n\n"
# Init a variable to keep all the additive/subtractive parts
finalParts = []
# Init variables to keep the CSV output data in
addressOut = []
privkeyOut = []
APOut = []
PAOut = []
# Set a counter for naming the files
filenameCounter = 1
# Break into the loop for each wallet
for data in walletDataList:
# 'data' = wif, address, wifQR, addressQR
# Generate the texts
addressLine1 = data["address"][:math.ceil(len(data["address"])/2.0)]
addressLine2 = data["address"][math.ceil(len(data["address"])/2.0):]
wifLine1 = data["wif"][:17]
wifLine2 = data["wif"][17:34]
wifLine3 = data["wif"][34:]
addressLine1Dots = textGen.getArray(addressLine1)
addressLine2Dots = textGen.getArray(addressLine2)
privkeyLine1Dots = textGen.getArray(wifLine1)
privkeyLine2Dots = textGen.getArray(wifLine2)
privkeyLine3Dots = textGen.getArray(wifLine3)
bigTitle = textGen.getArray("3D " + args.coinTitle + " Wallet")
addressTitle = textGen.getArray("Address")
privkeyTitle = textGen.getArray("Private Key")
# Create the big title union so that it can be sized and moved
bigTitleUnion = ""
for rowIndex in range(len(bigTitle)):
row = bigTitle[rowIndex]
for colIndex in range(len(row)):
if row[colIndex] == '1':
translateHeight = walletHeight if textDepth>0 else walletHeight+textDepth
bigTitleUnion += "translate([colIndex,rowIndex,translateHeight]){cube([1,1,textDepth]);}".replace('colIndex',str(colIndex)).replace('rowIndex',str(rowIndex)).replace('textDepth',str(abs(textDepth))).replace('translateHeight',str(translateHeight))
# Translate the title to where it goes
bigTitleFinal = "translate([(1/17)*length,(14/17)*width,0]){resize([(15/17)*length,0,0],auto=[true,true,false]){bigTitleUnion}}".replace('length',str(walletLength)).replace('width',str(walletWidth)).replace('bigTitleUnion',bigTitleUnion)
finalParts.append(bigTitleFinal+"\n\n")
if args.layoutStyle == 1:
# Need to copy it on to the backside as well - rotate then move it, and then create a union of the two titles (front and back)
bigTitle2 = "translate([length,0,height]){rotate(180,v=[0,1,0]){bigTitleFinal}}".replace('length',str(walletLength)).replace('height',str(walletHeight)).replace('bigTitleFinal',bigTitleFinal).replace('translateHeight',str(translateHeight))
finalParts.append(bigTitle2+"\n\n")
# Draw the word "Address" on the front, and draw on the actual address
if args.layoutStyle == 1 or args.layoutStyle == 3:
# Draw the address on the front
addressParts = []
# Create the address title union and size/move it
addressTitleUnion = "union(){"
for rowIndex in range(len(addressTitle)):
row = addressTitle[rowIndex]
for colIndex in range(len(row)):
if row[colIndex] == '1':
translateHeight = walletHeight if textDepth>0 else walletHeight+textDepth
addressTitleUnion += "translate([colIndex,rowIndex,translateHeight]){cube([1,1,textDepth]);}".replace('colIndex',str(colIndex)).replace('rowIndex',str(rowIndex)).replace('textDepth',str(abs(textDepth))).replace('translateHeight',str(translateHeight))
addressTitleUnion += "}"
addressTitleFinal = "translate([(10/17)*length,(6/11)*width,0]){resize([0,(4/55)*width,0],auto=[true,true,false]){addressTitleUnion}}\n\n".replace('length',str(walletLength)).replace('width',str(walletWidth)).replace('addressTitleUnion',addressTitleUnion)
addressParts.append(addressTitleFinal)
# Create the first line of the address
addressLine1Union = "union(){"
for rowIndex in range(len(addressLine1Dots)):
row = addressLine1Dots[rowIndex]
for colIndex in range(len(row)):
if row[colIndex] == '1':
translateHeight = walletHeight if textDepth>0 else walletHeight+textDepth
addressLine1Union += "translate([colIndex,rowIndex,translateHeight]){cube([1,1,textDepth]);}".replace('colIndex',str(colIndex)).replace('rowIndex',str(rowIndex)).replace('textDepth',str(abs(textDepth))).replace('translateHeight',str(translateHeight))
addressLine1Union += "}"
addressLine1Final = "translate([(8.2/17)*length,(5/11)*width,0]){resize([0,(3/55)*width,0],auto=[true,true,false]){addressLine1Union}}\n\n".replace('length',str(walletLength)).replace('width',str(walletWidth)).replace('addressLine1Union',addressLine1Union)
addressParts.append(addressLine1Final)
# Create the second line of the address
addressLine2Union = "union(){"
for rowIndex in range(len(addressLine2Dots)):
row = addressLine2Dots[rowIndex]
for colIndex in range(len(row)):
if row[colIndex] == '1':
translateHeight = walletHeight if textDepth>0 else walletHeight+textDepth
addressLine2Union += "translate([colIndex,rowIndex,translateHeight]){cube([1,1,textDepth]);}".replace('colIndex',str(colIndex)).replace('rowIndex',str(rowIndex)).replace('textDepth',str(abs(textDepth))).replace('translateHeight',str(translateHeight))
addressLine2Union += "}"
addressLine2Final = "translate([(8.2/17)*length,(4.1/11)*width,0]){resize([0,(3/55)*width,0],auto=[true,true,false]){addressLine2Union}}\n\n".replace('length',str(walletLength)).replace('width',str(walletWidth)).replace('addressLine2Union',addressLine2Union)
addressParts.append(addressLine2Final)
# Create the QR code
addressQRUnion = "union(){"
for rowIndex in range(len(data["addressQR"])):
row = data["addressQR"][rowIndex]
for colIndex in range(len(row)):
if row[colIndex] == 0:
translateHeight = walletHeight if textDepth>0 else walletHeight+textDepth
addressQRUnion += "translate([colIndex,rowIndex,translateHeight]){cube([1,1,textDepth]);}".replace('colIndex',str(colIndex)).replace('rowIndex',str(rowIndex)).replace('textDepth',str(abs(textDepth))).replace('translateHeight',str(translateHeight))
addressQRUnion += "}"
addressQRFinal = "translate([(0.6/17)*length,(0.6/11)*width,0]){resize([0,(8/12)*width,0],auto=[true,true,false]){addressQRUnion}}\n\n".replace('length',str(walletLength)).replace('width',str(walletWidth)).replace('addressQRUnion',addressQRUnion)
addressParts.append(addressQRFinal)
finalParts.extend(addressParts)
# Draw all the things having to do with the private key
if args.layoutStyle == 1 or args.layoutStyle == 2:
privkeyParts = []
# Create the privkey title union and size/move it
privkeyTitleUnion = "union(){"
for rowIndex in range(len(privkeyTitle)):
row = privkeyTitle[rowIndex]
for colIndex in range(len(row)):
if row[colIndex] == '1':
translateHeight = walletHeight if textDepth>0 else walletHeight+textDepth
privkeyTitleUnion += "translate([colIndex,rowIndex,translateHeight]){cube([1,1,textDepth]);}".replace('colIndex',str(colIndex)).replace('rowIndex',str(rowIndex)).replace('textDepth',str(abs(textDepth))).replace('translateHeight',str(translateHeight))
privkeyTitleUnion += "}"
privkeyTitleFinal = "translate([(8.7/17)*length,(7/11)*width,0]){resize([0,(4/55)*width,0],auto=[true,true,false]){privkeyTitleUnion}}\n\n".replace('length',str(walletLength)).replace('width',str(walletWidth)).replace('privkeyTitleUnion',privkeyTitleUnion)
privkeyParts.append(privkeyTitleFinal)
# Create the first line of the privkey
privkeyLine1Union = "union(){"
for rowIndex in range(len(privkeyLine1Dots)):
row = privkeyLine1Dots[rowIndex]
for colIndex in range(len(row)):
if row[colIndex] == '1':
translateHeight = walletHeight if textDepth>0 else walletHeight+textDepth
privkeyLine1Union += "translate([colIndex,rowIndex,translateHeight]){cube([1,1,textDepth]);}".replace('colIndex',str(colIndex)).replace('rowIndex',str(rowIndex)).replace('textDepth',str(abs(textDepth))).replace('translateHeight',str(translateHeight))
privkeyLine1Union += "}"
privkeyLine1Final = "translate([(8.2/17)*length,(6/11)*width,0]){resize([0,(3/55)*width,0],auto=[true,true,false]){privkeyLine1Union}}\n\n".replace('length',str(walletLength)).replace('width',str(walletWidth)).replace('privkeyLine1Union',privkeyLine1Union)
privkeyParts.append(privkeyLine1Final)
# Create the second line of the privkey
privkeyLine2Union = "union(){"
for rowIndex in range(len(privkeyLine2Dots)):
row = privkeyLine2Dots[rowIndex]
for colIndex in range(len(row)):
if row[colIndex] == '1':
translateHeight = walletHeight if textDepth>0 else walletHeight+textDepth
privkeyLine2Union += "translate([colIndex,rowIndex,translateHeight]){cube([1,1,textDepth]);}".replace('colIndex',str(colIndex)).replace('rowIndex',str(rowIndex)).replace('textDepth',str(abs(textDepth))).replace('translateHeight',str(translateHeight))
privkeyLine2Union += "}"
privkeyLine2Final = "translate([(8.2/17)*length,(5.1/11)*width,0]){resize([0,(3/55)*width,0],auto=[true,true,false]){privkeyLine2Union}}\n\n".replace('length',str(walletLength)).replace('width',str(walletWidth)).replace('privkeyLine2Union',privkeyLine2Union)
privkeyParts.append(privkeyLine2Final)
# Create the third line of the privkey
privkeyLine3Union = "union(){"
for rowIndex in range(len(privkeyLine3Dots)):
row = privkeyLine3Dots[rowIndex]
for colIndex in range(len(row)):
if row[colIndex] == '1':
translateHeight = walletHeight if textDepth>0 else walletHeight+textDepth
privkeyLine3Union += "translate([colIndex,rowIndex,translateHeight]){cube([1,1,textDepth]);}".replace('colIndex',str(colIndex)).replace('rowIndex',str(rowIndex)).replace('textDepth',str(abs(textDepth))).replace('translateHeight',str(translateHeight))
privkeyLine3Union += "}"
privkeyLine3Final = "translate([(8.2/17)*length,(4.2/11)*width,0]){resize([0,(3/55)*width,0],auto=[true,true,false]){privkeyLine3Union}}\n\n".replace('length',str(walletLength)).replace('width',str(walletWidth)).replace('privkeyLine3Union',privkeyLine3Union)
privkeyParts.append(privkeyLine3Final)
# Create the QR code
privkeyQRUnion = "union(){"
for rowIndex in range(len(data["wifQR"])):
row = data["wifQR"][rowIndex]
for colIndex in range(len(row)):
if row[colIndex] == 0:
translateHeight = walletHeight if textDepth>0 else walletHeight+textDepth
privkeyQRUnion += "translate([colIndex,rowIndex,translateHeight]){cube([1,1,textDepth]);}".replace('colIndex',str(colIndex)).replace('rowIndex',str(rowIndex)).replace('textDepth',str(abs(textDepth))).replace('translateHeight',str(translateHeight))
privkeyQRUnion += "}"
privkeyQRFinal = "translate([(0.6/17)*length,(0.6/11)*width,0]){resize([0,(8/12)*width,0],auto=[true,true,false]){privkeyQRUnion}}\n\n".replace('length',str(walletLength)).replace('width',str(walletWidth)).replace('privkeyQRUnion',privkeyQRUnion)
privkeyParts.append(privkeyQRFinal)
if args.layoutStyle == 2:
# Just add it all to the finalParts
finalParts.extend(privkeyParts)
elif args.layoutStyle == 1:
# Rotate it all and then add it to the finalParts
privkeyPartsNew = []
for part in privkeyParts:
privkeyPartsNew.append("translate([length,0,height]){rotate(180,v=[0,1,0]){part}}".replace('length',str(walletLength)).replace('height',str(walletHeight)).replace('part',part).replace('translateHeight',str(translateHeight)))
finalParts.extend(privkeyPartsNew)
# Put it all together
finalSCAD = masterSCAD
if textDepth < 0:
finalSCAD += "difference() {\n\n"
else:
finalSCAD += "union() {\n\n"
finalSCAD += mainCube
finalSCAD += "".join(finalParts)
finalSCAD += "}"
if DEBUG:
print(finalSCAD)
break
if args.outputSCADFolder:
try:
os.makedirs(args.outputSCADFolder)
except FileExistsError:
pass
scadOutFile = open(args.outputSCADFolder + '/wallet' + str(filenameCounter) + '.scad','w')
scadOutFile.write(finalSCAD)
scadOutFile.close()
# Log some info
print("Status: Done generating data for wallet #" + str(filenameCounter) + "...Starting generating STL file")
if args.outputSTLFolder:
try:
os.makedirs(args.outputSTLFolder)
except FileExistsError:
pass
scadOutFile = open('temp.scad','w')
scadOutFile.write(finalSCAD)
scadOutFile.close()
os.system(scadExe + " -o " + args.outputSTLFolder + "/wallet" + str(filenameCounter) + ".stl temp.scad")
try:
os.remove('temp.scad')
except:
pass
else:
print("Please provide a folder to output the STL files.")
# Update the CSV file variables
addressOut.append(data["address"])
privkeyOut.append(data["wif"])
APOut.append(data["address"] + "," + data["wif"])
PAOut.append(data["wif"] + "," + data["address"])
# Print some more stats
print("Status: Done generating STL file (" + str(round(filenameCounter/args.copies*100)) + "% done)")
filenameCounter += 1
# Export the CSV files
if args.exportAddressCSV:
csvFile = open(args.exportAddressCSV,'a')
csvFile.write(','.join(addressOut))
csvFile.close()
if args.exportPrivkeyCSV:
csvFile = open(args.exportPrivkeyCSV,'a')
csvFile.write(','.join(privkeyOut))
csvFile.close()
if args.exportAPCSV:
csvFile = open(args.exportAPCSV,'a')
csvFile.write('\n'.join(exportAPCSV))
csvFile.close()
if args.exportPACSV:
csvFile = open(args.exportPACSV,'a')
csvFile.write('\n'.join(exportPACSV))
csvFile.close()
| 3d-wallet-generator | /3d-wallet-generator-0.2.0.tar.gz/3d-wallet-generator-0.2.0/gen_3dwallet/base.py | base.py |
#!/usr/bin/python3
# Character list matches up with the character table, which is decoded by the binary decoder
chars = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}"
# Character table defining 5x7 characters (adapted from table of dot matrix display codes)
characterTable = [[ 0, 0, 0, 0, 0, 0, 0],
[ 4, 0, 4, 4, 4, 4, 4],
[ 0, 0, 0, 0,10,10,10],
[10,10,31,10,31,10,10],
[ 4,30, 5,14,20,15, 4],
[ 3,19, 8, 4, 2,25,24],
[13,18,21, 8,20,18,12],
[ 0, 0, 0, 0, 8, 4,12],
[ 2, 4, 8, 8, 8, 4, 2],
[ 8, 4, 2, 2, 2, 4, 8],
[ 0, 4,21,14,21, 4, 0],
[ 0, 4, 4,31, 4, 4, 0],
[ 8, 4,12, 0, 0, 0, 0],
[ 0, 0, 0,31, 0, 0, 0],
[12,12, 0, 0, 0, 0, 0],
[ 0,16, 8, 4, 2, 1, 0],
[14,17,25,21,19,17,14],
[14, 4, 4, 4, 4,12, 4],
[31, 8, 4, 2, 1,17,14],
[14,17, 1, 2, 4, 2,31],
[ 2, 2,31,18,10, 6, 2],
[14,17, 1, 1,30,16,31],
[14,17,17,30,16, 8, 6],
[ 8, 8, 8, 4, 2, 1,31],
[14,17,17,14,17,17,14],
[12, 2, 1,15,17,17,14],
[ 0,12,12, 0,12,12, 0],
[ 8, 4,12, 0,12,12, 0],
[ 2, 4, 8,16, 8, 4, 2],
[ 0, 0,31, 0,31, 0, 0],
[16, 8, 4, 2, 4, 8,16],
[ 4, 0, 4, 2, 1,17,14],
[14,21,21,13, 1,17,14],
[17,17,31,17,17,17,14],
[30,17,17,30,17,17,30],
[14,17,16,16,16,17,14],
[30,17,17,17,17,17,30],
[31,16,16,30,16,16,31],
[16,16,16,30,16,16,31],
[15,17,17,23,16,17,14],
[17,17,17,31,17,17,17],
[14, 4, 4, 4, 4, 4,14],
[12,18, 2, 2, 2, 2, 7],
[17,18,20,24,20,18,17],
[31,16,16,16,16,16,16],
[17,17,17,21,21,27,17],
[17,17,19,21,25,17,17],
[14,17,17,17,17,17,14],
[16,16,16,30,17,17,30],
[13,18,21,17,17,17,14],
[17,18,20,30,17,17,30],
[30, 1, 1,14,16,16,15],
[ 4, 4, 4, 4, 4, 4,31],
[14,17,17,17,17,17,17],
[ 4,10,17,17,17,17,17],
[10,21,21,21,17,17,17],
[17,17,10, 4,10,17,17],
[ 4, 4, 4,10,17,17,17],
[31,16, 8, 4, 2, 1,31],
[14, 8, 8, 8, 8, 8,14],
[ 0, 1, 2, 4, 8,16, 0],
[14, 2, 2, 2, 2, 2,14],
[ 0, 0, 0, 0,17,10, 4],
[31, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 2, 4, 8],
[15,17,15, 1,14, 0, 0],
[30,17,17,25,22,16,16],
[14,17,16,16,14, 0, 0],
[15,17,17,19,13, 1, 1],
[14,16,31,17,14, 0, 0],
[ 8, 8, 8,28, 8, 9, 6],
[14, 1,15,17,15, 0, 0],
[17,17,17,25,22,16,16],
[14, 4, 4, 4,12, 0, 4],
[12,18, 2, 2, 2, 6, 2],
[18,20,24,20,18,16,16],
[14, 4, 4, 4, 4, 4,12],
[17,17,21,21,26, 0, 0],
[17,17,17,25,22, 0, 0],
[14,17,17,17,14, 0, 0],
[16,16,30,17,30, 0, 0],
[ 1, 1,15,19,13, 0, 0],
[16,16,16,25,22, 0, 0],
[30, 1,14,16,15, 0, 0],
[ 6, 9, 8, 8,28, 8, 8],
[13,19,17,17,17, 0, 0],
[ 4,10,17,17,17, 0, 0],
[10,21,21,17,17, 0, 0],
[17,10, 4,10,17, 0, 0],
[14, 1,15,17,17, 0, 0],
[31, 8, 4, 2,31, 0, 0],
[ 2, 4, 4, 8, 4, 4, 2],
[ 4, 4, 4, 4, 4, 4, 4],
[ 8, 4, 4, 2, 4, 4, 8]]
# Binary decode table
decTable = ["00000", "00001", "00010", "00011", "00100", "00101",
"00110", "00111", "01000", "01001", "01010", "01011",
"01100", "01101", "01110", "01111", "10000", "10001",
"10010", "10011", "10100", "10101", "10110", "10111",
"11000", "11001", "11010", "11011", "11100", "11101",
"11110", "11111"]
def getArray(text):
outArray = [""]*7 # Initialize the empty rows
for thisChar in text:
index = chars.index(thisChar)
thisDec = characterTable[index]
for rowIndex in range(len(thisDec)):
outArray[rowIndex] += (decTable[thisDec[rowIndex]])+"0" # Add onto the current row in outArray based on the decode table at this decimal value (thisDec[rowIndex] = thisRow), adding a 0 for spacing at the end
return outArray
| 3d-wallet-generator | /3d-wallet-generator-0.2.0.tar.gz/3d-wallet-generator-0.2.0/gen_3dwallet/TextGenerator.py | TextGenerator.py |
#!/usr/bin/python3
import pyqrcode # sudo pip3 install pyqrcode
def getQRArray(text, errorCorrection):
""" Takes in text and errorCorrection (letter), returns 2D array of the QR code"""
# White is True (1)
# Black is False (0)
# ECC: L7, M15, Q25, H30
# Create the object
qr = pyqrcode.create(text, error=errorCorrection)
# Get the terminal representation and split by lines (get rid of top and bottom white spaces)
plainOut = qr.terminal().split("\n")[5:-5]
# Initialize the output 2D list
out = []
for line in plainOut:
thisOut = []
for char in line:
if char == u'7':
# This is white
thisOut.append(1)
elif char == u'4':
# This is black, it's part of the u'49'
thisOut.append(0)
# Finally add everything to the output, stipping whitespaces at start and end
out.append(thisOut[4:-4])
# Everything is done, return the qr code list
return out | 3d-wallet-generator | /3d-wallet-generator-0.2.0.tar.gz/3d-wallet-generator-0.2.0/gen_3dwallet/qr_tools.py | qr_tools.py |
# Welcome to **3D** - the package for Python game design
3D is a project designed to make programming 3D games as easy as possible.
3D gives developers an easy way to build great games and 3D renders using nothing but Python.
> **Note**: 3D is imported using `import g`, not `import 3d`!
| 3d | /3d-0.1.1.tar.gz/3d-0.1.1/README.md | README.md |
class Window:
pass
| 3d | /3d-0.1.1.tar.gz/3d-0.1.1/g/window.py | window.py |
from g.window import Window | 3d | /3d-0.1.1.tar.gz/3d-0.1.1/g/__init__.py | __init__.py |
# 3DRenderPy
This is an implementation of a ray tracer based on Jamis Buck's The Ray Tracer Challenge. It supports several primitives:
1. Sphere
2. Plane
3. Cube
4. Cylinder
5. Cone
6. Group
7. Triangle and Somooth Triangle
8. CSG
Installation:
```
pip install 3DRenderPy
``` | 3dRenderPy | /3dRenderPy-0.0.5.tar.gz/3dRenderPy-0.0.5/README.md | README.md |
import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="3dRenderPy",
version="0.0.5",
author="Ulysses Lynne",
author_email="yufeilin@bennington.edu",
description="This is an implementation of a ray tracer based on Jamis Buck's The Ray Tracer Challenge. It supports several primitives.",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/woes-lynne/3DRenderPy",
project_urls={
"Bug Tracker": "https://github.com/woes-lynne/3DRenderPy/issues",
},
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
package_dir={"": "src"},
packages=setuptools.find_packages(where="src"),
python_requires=">=3.6",
install_requires=[
"numpy>=1.19.5",
"Pillow>=5.1.0"
]
)
| 3dRenderPy | /3dRenderPy-0.0.5.tar.gz/3dRenderPy-0.0.5/setup.py | setup.py |
from RenderPy.Tuple import Tuple
from RenderPy.Intersection import Intersection
from RenderPy.Ray import Ray
# ---------------------
"""
Computation class helps to save all necessary results takes place after we obtain an intersection object
It contains the following elements:
1. t: a scalar, the intersection is t units away from the origin of the ray
2. object: a class inheriting Shape, indicating the shape that has the intersection
3. point: a Tuple, the intersection point
4. eyev: a Tuple, the eye vector
5. normalv: a Tuple, the normal at the point
6. inside: a Bool, indicates whether the intersection is inside or outside the shape
7. reflectv: a Tuple, the reflected vector
8. n1: a float, a refractivity index
9. n2: a float, a refractivity index
Computation class contains the following functions:
__init__
__str__
schlick
"""
# ---------------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/ComputationTest.py
--- OR ----
python3 -m nose -v ../test/ComputationTest.py
--- OR ----
python -m nose -v ../test/ComputationTest.py
---------------------------------------------------
"""
class Computation():
t = 0
shape = None
point = Tuple()
eyev = Tuple()
normalv = Tuple()
inside = False
# ---------------------
"""
Set up the computation object
---- Inputs: --------
* intersection: an Intersection
* ray: a Ray
* xs: an Intersection Array, containing all intersections from the world
---- Outputs: --------
* comp: a Computation
"""
# ---------------------
def __init__(self, intersection: "Intersection", ray: "Ray", xs=[]):
self.t = intersection.t
self.shape = intersection.shape
self.point = ray.position(self.t)
self.eyev = ~ray.direction
self.normalv = self.shape.normalAt(self.point, hit=intersection)
if self.normalv.dot(self.eyev) < 0:
self.inside = True
self.normalv = ~self.normalv
self.overPoint = self.point + self.normalv * 0.00001
self.underPoint = self.point - self.normalv * 0.00001
# reflectivity
self.reflectv = ray.direction.reflectV(self.normalv)
# refractivity
containers = []
for i in xs:
if i == intersection:
if len(containers) == 0:
self.n1 = 1
else:
self.n1 = containers[-1].material.refractiveIndex
if i.shape in containers:
containers.remove(i.shape)
else:
containers.append(i.shape)
if i == intersection:
if len(containers) == 0:
self.n2 = 1
else:
self.n2 = containers[-1].material.refractiveIndex
break
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/ComputationTest.py:test_init
--- OR ----
python3 -m nose -v ../test/ComputationTest.py:test_init
--- OR ----
python -m nose -v ../test/ComputationTest.py:test_init
---------------------------------------------------
"""
# ---------------------
"""
Define the output format for Computation class
"""
# ---------------------
def __str__(self):
return "T: " + str(self.t) + "\n" + "Object: "+str(self.shape)+"\n" + "Point: "+str(self.point) + "\n" + "Eye: "+str(self.eyev) + "\n" + "Normal: "+str(self.normalv) + + "\n" + "Over Point: "+str(self.overPoint) + "\n" + "Under Point: "+str(self.underPoint) + "\n" + "Reflect Vector: "+str(self.reflectv) + "\n" + "n1: "+str(self.n1) + "\n" + "n2: "+str(self.n2)
# ---------------------
"""
Schlick implements the Fresnel effect to determine the reflectance
---- Outputs: --------
* num: a float, the reflectance of the ray
"""
# ---------------------
def schlick(self):
cos = self.eyev.dot(self.normalv)
if self.n1 > self.n2:
n = self.n1/self.n2
sin2T = n * n * (1-cos*cos)
if sin2T > 1:
return 1
cosT = (1-sin2T)
cos = cosT
r0 = (self.n1-self.n2)/(self.n1 + self.n2)
r0 = r0 * r0
return r0 + (1-r0)*((1-cos) ** 5)
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/ComputationTest.py:test_schlick
--- OR ----
python3 -m nose -v ../test/ComputationTest.py:test_schlick
--- OR ----
python -m nose -v ../test/ComputationTest.py:test_schlick
---------------------------------------------------
"""
| 3dRenderPy | /3dRenderPy-0.0.5.tar.gz/3dRenderPy-0.0.5/src/RenderPy/Computation.py | Computation.py |
from RenderPy.Sphere import Sphere
from RenderPy.Color import Color
from RenderPy.Matrix import Matrix
from RenderPy.Light import Light
from RenderPy.Tuple import Tuple
from RenderPy.Ray import Ray
from RenderPy.Computation import Computation
from RenderPy.Material import Material
from RenderPy.Intersection import Intersection
# ---------------------
"""
World class contains all the lights and shapes in a scene.
It contains the following 2 elements:
1. lights: an array of Lights
2. shapes: an array of Shapes
World class contains the following functions:
__init__
defaultWorld
intersectWorld
shadeHit
reflectedColor
colorAt
isShadowed
"""
# ---------------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/WorldTest.py
--- OR ----
python3 -m nose -v ../test/WorldTest.py
--- OR ----
python -m nose -v ../test/WorldTest.py
---------------------------------------------------
"""
class World():
# ---------------------
"""
World class takes in 2 input
lights is an array of Lights
shapes is an array of Shapes
"""
# ---------------------
def __init__(self, lights=[], shapes=[]):
self.lights = lights
self.shapes = shapes
# ---------------------
"""
defaultWorld renders a default world
containing two sphere, one is larger than the other, with the same center
the light is also default
Note: if you want to change material, remember to initialize a new instance, don't change in place
"""
# ---------------------
@staticmethod
def defaultWorld():
light = Light(Tuple.point(-10, 10, -10), Color(1, 1, 1))
s1 = Sphere()
s1.material = Material(color=Color(0.8, 1.0, 0.6),
diffuse=0.7, specular=0.2)
s2 = Sphere()
s2.material = Material(color=Color(1, 1, 1))
s2.transform = Matrix.scaling(0.5, 0.5, 0.5)
return World([light], [s1, s2])
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/WorldTest.py:test_defaultWorld
--- OR ----
python3 -m nose -v ../test/WorldTest.py:test_defaultWorld
--- OR ----
python -m nose -v ../test/WorldTest.py:test_defaultWorld
---------------------------------------------------
"""
# ---------------------
"""
Intersect world sets up the intersection of all objects in the world and the given ray
Then, sort the intersections by their t value
---- Inputs: --------
* ray: a Ray
---- Outputs: --------
* count: a scalar, the number of intersections
* results: a tuple, all intersections are listed
"""
# ---------------------
def intersectWorld(self, ray: "Ray"):
total = 0
result = []
for s in self.shapes:
count, intersects = s.intersect(ray)
if count != 0:
total += count
result += intersects
result.sort(key=lambda x: x.t)
return total, result
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/WorldTest.py:test_intersectWorld
--- OR ----
python3 -m nose -v ../test/WorldTest.py:test_intersectWorld
--- OR ----
python -m nose -v ../test/WorldTest.py:test_intersectWorld
---------------------------------------------------
"""
# ---------------------
"""
shadeHit helps to calculate the shading on each different object
---- Inputs: --------
* computation: a Computation
* remaining: an Integer, indicating the number of recursion left
---- Outputs: --------
* color: a Color, the final representation on the object
"""
# ---------------------
def shadeHit(self, computation: "Computation", remaining=1):
col = Color(0, 0, 0)
for l in self.lights:
inShadow = self.isShadowed(l, computation.overPoint)
col += computation.shape.material.lighting(
l, computation.overPoint, computation.eyev, computation.normalv, inShadow, computation.shape.transform)
reflected = self.reflectedColor(computation, remaining)
refracted = self.refractedColor(computation, remaining)
mat = computation.shape.material
if mat.reflective > 0 and mat.transparency > 0:
reflectance = computation.schlick()
return col + reflected * reflectance + refracted * (1-reflectance)
return col + reflected + refracted
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/WorldTest.py:test_shadeHit
--- OR ----
python3 -m nose -v ../test/WorldTest.py:test_shadeHit
--- OR ----
python -m nose -v ../test/WorldTest.py:test_shadeHit
---------------------------------------------------
"""
# ---------------------
"""
colorAt helps to calculate the final color on the object
---- Inputs: --------
* ray: a Ray
* remaining: an Integer, indicates the number of recursion left
---- Outputs: --------
* color: a Color, the final color on the object
"""
# ---------------------
def colorAt(self, ray: "Ray", remaining=1):
count, xs = self.intersectWorld(ray)
h = Intersection.hit(xs)
if count == 0:
return Color(0, 0, 0)
comp = Computation(h, ray, xs)
return self.shadeHit(comp, remaining)
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/WorldTest.py:test_colorAt
--- OR ----
python3 -m nose -v ../test/WorldTest.py:test_colorAt
--- OR ----
python -m nose -v ../test/WorldTest.py:test_colorAt
---------------------------------------------------
"""
# ---------------------
"""
isShadowed helps to determine whehter the shape is in shadow
---- Inputs: --------
* l: a Light, indicating the light we want to use to calculate shadow
* point: a Point, a point on the shape
---- Outputs: --------
* inShadow: a Bool, indicating whether the shape is in shadow
"""
# ---------------------
def isShadowed(self, l: "Light", point: "Tuple"):
v = l.position - point
distance = v.magnitude()
direction = v.normalize()
r = Ray(point, direction)
count, inters = self.intersectWorld(r)
h = Intersection.hit(inters)
return h != Intersection() and h.t < distance
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/WorldTest.py:test_isShadowed
--- OR ----
python3 -m nose -v ../test/WorldTest.py:test_isShadowed
--- OR ----
python -m nose -v ../test/WorldTest.py:test_isShadowed
---------------------------------------------------
"""
# ---------------------
"""
reflectedColor helps to determine the relfected color based on intersection
---- Inputs: --------
* comp: a Computation, contain all information of intersection
* remaining: an Integer, indicate the number of recursion left
---- Outputs: --------
* col: a Color, the reflected Color
"""
# ---------------------
def reflectedColor(self, comp: "Computation", remaining=1):
if remaining <= 0:
return Color()
r = comp.shape.material.reflective
if r == 0:
return Color()
reflectRay = Ray(comp.overPoint, comp.reflectv)
color = self.colorAt(reflectRay)
return color * r
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/WorldTest.py:test_refelctedColor
--- OR ----
python3 -m nose -v ../test/WorldTest.py:test_refelctedColor
--- OR ----
python -m nose -v ../test/WorldTest.py:test_refelctedColor
---------------------------------------------------
"""
# ---------------------
"""
refractedColor helps to determine the refracted color based on intersection
---- Inputs: --------
* comp: a Computation, contain all information of intersection
* remaining: an Integer, indicate the number of recursion left
---- Outputs: --------
* col: a Color, the reflected Color
"""
# ---------------------
def refractedColor(self, comp: "Computation", remaining=1):
if comp.shape.material.transparency == 0 or remaining == 0:
return Color()
nRatio = comp.n1/comp.n2
cosI = comp.eyev.dot(comp.normalv)
sin2T = nRatio * nRatio * (1-cosI*cosI)
if sin2T > 1:
return Color()
cosT = (1-sin2T) ** 0.5
direction = comp.normalv * (nRatio * cosI - cosT) - comp.eyev * nRatio
refractRay = Ray(comp.underPoint, direction)
return self.colorAt(refractRay, remaining - 1) * comp.shape.material.transparency
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/WorldTest.py:test_refractedColor
--- OR ----
python3 -m nose -v ../test/WorldTest.py:test_refractedColor
--- OR ----
python -m nose -v ../test/WorldTest.py:test_refractedColor
---------------------------------------------------
"""
| 3dRenderPy | /3dRenderPy-0.0.5.tar.gz/3dRenderPy-0.0.5/src/RenderPy/World.py | World.py |
import numpy as np
# ---------------------
"""
Color class describes colors based on r,g,b from 0 to 1, if there are exceptions it will be handled in the canvas class while output the image
Each color contains 3 elements: r,g,b in a numpy array
r,g,b are all float value
r: red, g: green, b: blue
Color class contains the following functions:
__init__
__str__
__eq__
__add__
__sub__
__mul__
"""
# ---------------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/ColorTest.py
--- OR ----
python3 -m nose -v ../test/ColorTest.py
--- OR ----
python -m nose -v ../test/ColorTest.py
---------------------------------------------------
"""
class Color():
# ---------------------
"""
Color class takes in a group of three numbers or a numpy array
arr[0] is r, arr[1] is g, arr[2] is b
"""
# ---------------------
def __init__(self, r: float = None, g: float = None, b: float = None, arr: np.array = None):
if r == g == b == None:
try:
if arr.size != 0:
self.arr = arr
self.r = arr[0]
self.g = arr[1]
self.b = arr[2]
except:
self.r = 0
self.g = 0
self.b = 0
self.arr = np.array([0, 0, 0])
else:
self.r = r
self.g = g
self.b = b
self.arr = np.array([r, g, b])
# ---------------------
"""
Define the output format for Color class
"""
# ---------------------
def __str__(self):
return "({0},{1},{2})".format(self.r, self.g, self.b)
# ---------------------
"""
Define equivalence of two Color instances
This is based on numpy allclose function with absolute tolerance 0.00001
"""
# ---------------------
def __eq__(self, color2: "Color"):
return np.allclose(self.arr, color2.arr, atol=0.0001)
# ---------------------
"""
Define the sum between two Colors
---- Inputs: --------
* color2: A Color
---- Outputs: --------
* Color: the sum of two Colors
"""
# ---------------------
def __add__(self, color2: "Color"):
return Color(arr=self.arr + color2.arr)
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/ColorTest.py:test_add
--- OR ----
python3 -m nose -v ../test/ColorTest.py:test_add
--- OR ----
python -m nose -v ../test/ColorTest.py:test_add
---------------------------------------------------
"""
# ---------------------
"""
Define the difference between two Colors
---- Inputs: --------
* color2: A Color
---- Outputs: --------
* Color: the difference of two Colors
"""
# ---------------------
def __sub__(self, color2: "Color"):
return Color(arr=self.arr - color2.arr)
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/ColorTest.py:test_subtract
--- OR ----
python3 -m nose -v ../test/ColorTest.py:test_subtract
--- OR ----
python -m nose -v ../test/ColorTest.py:test_subtract
---------------------------------------------------
"""
# ---------------------
"""
Define the product of a Color and a scalar or another Color
Multiplying scalar is to create a new color
Multiplying two colors together is to blend these colors
The order is not interchangeable for color * scalar
But interchangeable for color * color
---- Inputs: --------
* multi: A scalar or a Color
---- Outputs: --------
* Tuple: the product of a Color and a scalar or another Color
"""
# ---------------------
def __mul__(self, multi):
if type(multi) == float or type(multi) == int:
return Color(arr=self.arr * multi)
return Color(arr=self.arr*multi.arr)
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/ColorTest.py:test_multi
--- OR ----
python3 -m nose -v ../test/ColorTest.py:test_multi
--- OR ----
python -m nose -v ../test/ColorTest.py:test_multi
---------------------------------------------------
"""
| 3dRenderPy | /3dRenderPy-0.0.5.tar.gz/3dRenderPy-0.0.5/src/RenderPy/Color.py | Color.py |
import numpy as np
from RenderPy.Tuple import Tuple
from RenderPy.Color import Color
# ---------------------
"""
Light class describes the light in the world.
Each light contains 2 elements: position and intensity
position: a Tuple, the origin where light locates
intensity: a Color, the color of the light
Light class contains the following functions:
__init__
__str__
__eq__
"""
# ---------------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/LightTest.py
--- OR ----
python3 -m nose -v ../test/LightTest.py
--- OR ----
python -m nose -v ../test/LightTest.py
---------------------------------------------------
"""
class Light():
# ---------------------
"""
Light takes in two parameters: position and intensity
position is a Tuple
intensity is a Color
"""
# ---------------------
def __init__(self, position: "Tuple" = None, intensity: "Color" = None):
if not position and not intensity:
self.position = Tuple.point(0, 0, 0)
self.intensity = Color()
else:
self.position = position
self.intensity = intensity
# ---------------------
"""
Define the output format for Light class
"""
# ---------------------
def __str__(self):
return "Position: " + str(self.position) + " Color: " + str(self.intensity)
# ---------------------
"""
Define equivalence of two Light instances
"""
# ---------------------
def __eq__(self, light2: "Light"):
return self.intensity == light2.intensity and self.position == light2.position
| 3dRenderPy | /3dRenderPy-0.0.5.tar.gz/3dRenderPy-0.0.5/src/RenderPy/Light.py | Light.py |
import numpy as np
from RenderPy.Matrix import Matrix
from RenderPy.Tuple import Tuple
from RenderPy.Ray import Ray
from RenderPy.Canvas import Canvas
from RenderPy.World import World
# ---------------------
"""
Camera class helps to set up a camera in the scene and this would define the angle and distance we will be looking at the scene.
Each camera contains 7 elements:
hsize: a float, define the horizontal size of the canvas in pixels
vsize: a float, define the vertical size of the canvas in pixels
fieldOfView: a float, the radian angle describes how much the camera could see
transform: a Matrix, describe the transform matrix of the camera
halfWidth: a float, define the view on half of the width
halfHeight: a float, define the view on half of the height
pixelSize: a float define the size of a pixel in the scene
Camera class contains the following functions:
__init__
__eq__
rayForPixel
"""
# ---------------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/CameraTest.py
--- OR ----
python3 -m nose -v ../test/CameraTest.py
--- OR ----
python -m nose -v ../test/CameraTest.py
---------------------------------------------------
"""
class Camera():
# ---------------------
"""
Camera class takes in three numbers
hsize is horizontal size, vsize is vertical size, fieldOfView is the field of view of the camera
"""
# ---------------------
def __init__(self, hsize: float, vsize: float, fieldOfView: float):
self.hsize = hsize
self.vsize = vsize
self.fieldOfView = fieldOfView
self.transform = Matrix(matrix=np.eye(4))
# In this part we calculate pixelSize
halfView = np.tan(fieldOfView/2)
# determine whether it is a horizontal or vertical view
aspect = hsize/vsize
if aspect >= 1:
self.halfWidth = halfView
self.halfHeight = halfView/aspect
else:
self.halfWidth = halfView * aspect
self.halfHeight = halfView
self.pixelSize = self.halfWidth * 2/self.hsize
# ---------------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/CameraTest.py:test_init
--- OR ----
python3 -m nose -v ../test/CameraTest.py:test_init
--- OR ----
python -m nose -v ../test/CameraTest.py:test_init
---------------------------------------------------
"""
# ---------------------
"""
Define equivalence of two Canvas instances
"""
# ---------------------
def __eq__(self, camera2: "Camera"):
return self.fieldOfView == camera2.fieldOfView and self.transform == camera2.transform and self.hsize == camera2.hsize and self.vsize == camera2.vsize
# ---------------------
"""
rayForPixel takes in the x and y coordinate and get the ray on that point
---- Inputs: --------
* px: a float, x coordinate
* py: a float, y coordinate
---- Outputs: --------
* ray: a ray on that pixel point
"""
# ---------------------
def rayForPixel(self, px: float, py: float):
xOffset = (px+0.5) * self.pixelSize
yOffset = (py+0.5) * self.pixelSize
wx = self.halfWidth - xOffset
wy = self.halfHeight - yOffset
pixel = ~self.transform * Tuple.point(wx, wy, -1)
origin = ~self.transform * Tuple.point(0, 0, 0)
direction = (pixel-origin).normalize()
return Ray(origin, direction)
# ---------------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/CameraTest.py:test_rayForPixel
--- OR ----
python3 -m nose -v ../test/CameraTest.py:test_rayForPixel
--- OR ----
python -m nose -v ../test/CameraTest.py:test_rayForPixel
---------------------------------------------------
"""
# ---------------------
"""
render generates the image
---- Inputs: --------
* world: a World containing all shapes and lights
---- Outputs: --------
* image: a Canvas containing the calculated values
"""
# ---------------------
def render(self, world: "World"):
image = Canvas(self.hsize, self.vsize)
for y in range(self.vsize):
for x in range(self.hsize):
ray = self.rayForPixel(x, y)
color = world.colorAt(ray)
image.writePixel(x, y, color)
return image
# ---------------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/CameraTest.py:test_render
--- OR ----
python3 -m nose -v ../test/CameraTest.py:test_render
--- OR ----
python -m nose -v ../test/CameraTest.py:test_render
---------------------------------------------------
"""
| 3dRenderPy | /3dRenderPy-0.0.5.tar.gz/3dRenderPy-0.0.5/src/RenderPy/Camera.py | Camera.py |
import numpy as np
# ---------------------
"""
Tuple class describes the tuple we use to build a 3D renderer
This class is a base class for points and vectors
Each tuple contain 4 elements: x,y,z,w in a numpy array
x,y,z,w are all float value
x: x-coordinate, y: y-coordinate, z: z-coordinate
w = 0 indicate a vector, w = 1 indicate a point
Tuple class contains the following functions:
__init__
__str__
__eq__
__add__
__sub__
__mul__
__truediv__
__invert__
point
vector
magnitude
dot
cross
reflectV
"""
# ---------------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/TupleTest.py
--- OR ----
python3 -m nose -v ../test/TupleTest.py
--- OR ----
python -m nose -v ../test/TupleTest.py
---------------------------------------------------
"""
class Tuple():
# ---------------------
"""
Tuple class takes in a group of 4 numbers or a numpy array
arr[0] is x, arr[1] is y, arr[2] is z, arr[3] is w
We support two ways of input:
Give four double: x,y,z,w
Or
Given a numpy array
"""
# ---------------------
def __init__(self, x: float = None, y: float = None, z: float = None, w: float = None, arr: np.array = None):
if x == y == z == w == None:
try:
if arr.size != 0:
self.x = arr[0]
self.y = arr[1]
self.z = arr[2]
self.w = arr[3]
self.arr = arr
except:
self.x = 0
self.y = 0
self.z = 0
self.w = 0
self.arr = np.array([0, 0, 0, 0])
else:
self.x = x
self.y = y
self.z = z
self.w = w
self.arr = np.array([x, y, z, w])
# ---------------------
"""
Define the output format for Tuple class
"""
# ---------------------
def __str__(self):
return "({0},{1},{2},{3})".format(self.x, self.y, self.z, self.w)
# ---------------------
"""
Define equivalence of two Tuple instances
This is based on numpy allclose function with absolute tolerance 0.00001
"""
# ---------------------
def __eq__(self, tuple2: "Tuple"):
if tuple2 == None:
return False
return np.allclose(self.arr, tuple2.arr, atol=0.0001)
# ---------------------
"""
Define the sum between two Tuples
Works for both points and vector
---- Inputs: --------
* tuple2: A Tuple
---- Outputs: --------
* Tuple: the sum of two tuples
"""
# ---------------------
def __add__(self, tuple2: "Tuple"):
return Tuple(arr=(self.arr + tuple2.arr))
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/TupleTest.py:test_add
--- OR ----
python3 -m nose -v ../test/TupleTest.py:test_add
--- OR ----
python -m nose -v ../test/TupleTest.py:test_add
---------------------------------------------------
"""
# ---------------------
"""
Define the difference between two Tuples
Works for both points and vector
---- Inputs: --------
* tuple2: A Tuple
---- Outputs: --------
* Tuple: the difference of two tuples
"""
# ---------------------
def __sub__(self, tuple2: "Tuple"):
return Tuple(arr=(self.arr - tuple2.arr))
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/TupleTest.py:test_subtract
--- OR ----
python3 -m nose -v ../test/TupleTest.py:test_subtract
--- OR ----
python -m nose -v ../test/TupleTest.py:test_subtract
---------------------------------------------------
"""
# ---------------------
"""
Define the product of a Tuple and a scalar
This is used for finding the point lies scalar times further in the direction of the given vector
The order is not interchangeable, must be tuple * scalar
Works vector only
---- Inputs: --------
* scalar: A scalar
---- Outputs: --------
* Tuple: the product of a Tuple and a scalar
"""
# ---------------------
def __mul__(self, scalar: float):
return Tuple(arr=self.arr * scalar)
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/TupleTest.py:test_multiScalar
--- OR ----
python3 -m nose -v ../test/TupleTest.py:test_multiScalar
--- OR ----
python -m nose -v ../test/TupleTest.py:test_multiScalar
---------------------------------------------------
"""
# ---------------------
"""
Define the division of a Tuple and a scalar
The order is not interchangeable, must be tuple / scalar
Works for vector only
---- Inputs: --------
* scalar: A scalar
---- Outputs: --------
* Tuple: the product of a Tuple and a scalar
"""
# ---------------------
def __truediv__(self, scalar: float):
return Tuple(arr=self.arr / scalar)
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/TupleTest.py:test_divScalar
--- OR ----
python3 -m nose -v ../test/TupleTest.py:test_divScalar
--- OR ----
python -m nose -v ../test/TupleTest.py:test_divScalar
---------------------------------------------------
"""
# ---------------------
"""
Negate multiply each element in the array by -1
Works for both point and vector
---- Outputs: --------
* Tuple: the negated tuple
"""
# ---------------------
def __invert__(self):
return Tuple(arr=-self.arr)
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/TupleTest.py:test_negate
--- OR ----
python3 -m nose -v ../test/TupleTest.py:test_negate
--- OR ----
python -m nose -v ../test/TupleTest.py:test_negate
---------------------------------------------------
"""
# ---------------------
"""
Point is a Tuple having w=1
point is a static method
---- Inputs: --------
* x: x-coordinate
* y: y-coordinate
* z: z-coordinate
---- Outputs: --------
* Tuple: a Point
"""
# ---------------------
@staticmethod
def point(x: float, y: float, z: float):
return Tuple(x, y, z, 1)
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/TupleTest.py:test_point
--- OR ----
python3 -m nose -v ../test/TupleTest.py:test_point
--- OR ----
python -m nose -v ../test/TupleTest.py:test_point
---------------------------------------------------
"""
# ---------------------
"""
Vector is a Tuple having w=0
vector is a static method
---- Inputs: --------
* x: x-coordinate
* y: y-coordinate
* z: z-coordinate
---- Outputs: --------
* Tuple: a Point
"""
# ---------------------
@staticmethod
def vector(x: float, y: float, z: float):
return Tuple(x, y, z, 0)
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/TupleTest.py:test_vector
--- OR ----
python3 -m nose -v ../test/TupleTest.py:test_vector
--- OR ----
python -m nose -v ../test/TupleTest.py:test_vector
---------------------------------------------------
"""
# ---------------------
"""
Magnituude is used for discovering the distance represented by a vector
Magnitude is calculated based on Pythagoras' theorem
Works for vector only
---- Outputs: --------
* magnitude: a scalar
"""
# ---------------------
def magnitude(self):
return np.sqrt(sum(self.arr**2))
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/TupleTest.py:test_magnitude
--- OR ----
python3 -m nose -v ../test/TupleTest.py:test_magnitude
--- OR ----
python -m nose -v ../test/TupleTest.py:test_magnitude
---------------------------------------------------
"""
# ---------------------
"""
Normalize is used to converting a vector to a unit vector to make sure the rays are calculated standardly
Works for vector only
---- Outputs: --------
* normalizedVector: a Tuple
"""
# ---------------------
def normalize(self):
if self.magnitude() == 0:
return self
return self/self.magnitude()
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/TupleTest.py:test_magnitude
--- OR ----
python3 -m nose -v ../test/TupleTest.py:test_magnitude
--- OR ----
python -m nose -v ../test/TupleTest.py:test_magnitude
---------------------------------------------------
"""
# ---------------------
"""
Dot product is a standard way to understand the angle between two vectors, the smaller the result, the larger the angle
It is widely used to find intersactions of rays and objects.
Works for vector only
---- Inputs: --------
* tuple2: a Tuple
---- Outputs: --------
* dotProduct: a scalar
"""
# ---------------------
def dot(self, tuple2: "Tuple"):
return float(self.arr@tuple2.arr)
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/TupleTest.py:test_dot
--- OR ----
python3 -m nose -v ../test/TupleTest.py:test_dot
--- OR ----
python -m nose -v ../test/TupleTest.py:test_dot
---------------------------------------------------
"""
# ---------------------
"""
Cross product is a standard way to find a third vector perpendicular to the existing two vectors.
However, given the vector has directions, and can be pointing the opposite direction
If we have the cross product order changed then we would have the result vector pointing to the opposite direction
Works for vector only
---- Inputs: --------
* tuple2: a Tuple
---- Outputs: --------
* crossProduct: a Tuple perpendicular to the given two vectors
"""
# ---------------------
def cross(self, tuple2: "Tuple"):
crossP = np.cross(self.arr[:-1], tuple2.arr[:-1])
return Tuple.vector(crossP[0], crossP[1], crossP[2])
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/TupleTest.py:test_cross
--- OR ----
python3 -m nose -v ../test/TupleTest.py:test_cross
--- OR ----
python -m nose -v ../test/TupleTest.py:test_cross
---------------------------------------------------
"""
# ---------------------
"""
reflectV is used to calculate the reflected vector based on the original input
and the calculated normal vector
Works for vector only
---- Inputs: --------
* normal: a Tuple, the normal vector
---- Outputs: --------
* crossProduct: a Tuple perpendicular to the given two vectors
"""
# ---------------------
def reflectV(self, normal: "Tuple"):
return self - normal * 2 * self.dot(normal)
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/TupleTest.py:test_reflectV
--- OR ----
python3 -m nose -v ../test/TupleTest.py:test_reflectV
--- OR ----
python -m nose -v ../test/TupleTest.py:test_reflectV
---------------------------------------------------
"""
| 3dRenderPy | /3dRenderPy-0.0.5.tar.gz/3dRenderPy-0.0.5/src/RenderPy/Tuple.py | Tuple.py |
from RenderPy.Tuple import Tuple
from RenderPy.Matrix import Matrix
# ---------------------
"""
Ray class helps to describe the ray in the picture
Each ray contains 2 elements: origin and direction
origin, direction are both Tuple value
origin: the start point of the ray, direction: the moving direction of the ray
Ray class contains the following functions:
__init__
__str__
__eq__
position
"""
# ---------------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/RayTest.py
--- OR ----
python3 -m nose -v ../test/RayTest.py
--- OR ----
python -m nose -v ../test/RayTest.py
---------------------------------------------------
"""
class Ray():
# ---------------------
"""
Ray class takes in two Tuples
origin is the origin of the ray, a point
direction is the direction of the ray, a vector
"""
# ---------------------
def __init__(self, origin: "Tuple" = Tuple(), direction: "Tuple" = Tuple()):
self.origin = origin
self.direction = direction
# ---------------------
"""
Define the output format for Ray class
"""
# ---------------------
def __str__(self):
return "origin: " + str(self.origin) + " direction: " + str(self.direction)
# ---------------------
"""
Define equivalence of two Ray instances
"""
# ---------------------
def __eq__(self, ray2: "Ray"):
return self.direction == ray2.direction and self.origin == ray2.origin
# ---------------------
"""
Define the final point based on the given direction and origin of the ray
---- Inputs: --------
* lambda: a float
---- Outputs: --------
* Tuple: the point on the line that is t units away from origin
"""
# ---------------------
def position(self, t: float):
return self.origin + self.direction * t
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/RayTest.py:test_position
--- OR ----
python3 -m nose -v ../test/RayTest.py:test_position
--- OR ----
python -m nose -v ../test/RayTest.py:test_position
---------------------------------------------------
"""
# ---------------------
"""
Helps to find the new ray after a transformation
---- Inputs: --------
* matrix: a transformation matrix
---- Outputs: --------
* Ray: the new transformed ray
"""
# ---------------------
def transform(self, matrix: "Matrix"):
return Ray(origin=matrix*self.origin, direction=matrix*self.direction)
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/RayTest.py:test_transform
--- OR ----
python3 -m nose -v ../test/RayTest.py:test_transform
--- OR ----
python -m nose -v ../test/RayTest.py:test_transform
---------------------------------------------------
"""
| 3dRenderPy | /3dRenderPy-0.0.5.tar.gz/3dRenderPy-0.0.5/src/RenderPy/Ray.py | Ray.py |
from RenderPy.Tuple import Tuple
# ---------------------
"""
Intersection class helps to save a intersection point of the shape and the ray
It contains two elements: t, object
t: a scalar recording the intersection is t unit apart from the ray's origin
shape: the shape used to be intersected with the given ray
Intersection class contains the following functions:
__init__
__eq__
hit
"""
# ---------------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/IntersectionTest.py
--- OR ----
python3 -m nose -v ../test/IntersectionTest.py
--- OR ----
python -m nose -v ../test/IntersectionTest.py
---------------------------------------------------
"""
class Intersection():
# ---------------------
"""
Intersection class takes in no input
t is the intersection point
shape is the shape used to make calculation
"""
# ---------------------
def __init__(self, t: float = None, shape=None, u=None, v=None):
self.t = t
self.shape = shape
self.u = u
self.v = v
# ---------------------
"""
Define equivalence of two Intersection instances
"""
# ---------------------
def __eq__(self, i2: "Intersection"):
if i2 == None:
return False
return self.t == i2.t and self.shape == i2.shape and self.u == i2.u and self.v == i2.v
# ---------------------
"""
Define the print format of Intersection instances
"""
# ---------------------
def __str__(self):
return "t:" + str(self.t) + "\n" + "shape:" + str(self.shape)+"\n" + "u:" + str(self.u) + "\n" + "v:" + str(self.v) + "\n"
# ---------------------
"""
Find the intersection with the smallest t-value, ignore those negative values
---- Inputs: --------
* xs: a list of intersections
---- Outputs: --------
* results: the intersection with the smallest non-negative t-value or empty Intersection instance
"""
# ---------------------
@staticmethod
def hit(xs):
xs = [i for i in xs if i.t >= 0]
if len(xs) == 0:
return Intersection()
return min(xs, key=lambda x: x.t)
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/IntersectionTest.py:test_hit
--- OR ----
python3 -m nose -v ../test/IntersectionTest.py:test_hit
--- OR ----
python -m nose -v ../test/IntersectionTest.py:test_hit
---------------------------------------------------
"""
| 3dRenderPy | /3dRenderPy-0.0.5.tar.gz/3dRenderPy-0.0.5/src/RenderPy/Intersection.py | Intersection.py |
import re
from RenderPy.Tuple import Tuple
from RenderPy.Group import Group
from RenderPy.Triangle import Triangle
# ---------------------
"""
ObjParser class helps to parse .obj files into images and render them with triangles or smooth triangles.
It contains the following variable:
1. vertices: a list, a collection of different vertices.
2. normals: a list, a collection of different normals
3. textures: a list, a collection of different textures
4. defaultGroup: a Group, the shape that contains all triangles
Intersection class contains the following functions:
__init__
__eq__
hit
"""
# ---------------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/ObjParserTest.py
--- OR ----
python3 -m nose -v ../test/ObjParserTest.py
--- OR ----
python -m nose -v ../test/ObjParserTest.py
---------------------------------------------------
"""
class ObjParser():
# ---------------------
"""
ObjParser class takes in no input
"""
# ---------------------
def __init__(self):
self.vertices = []
self.normals = []
self.textures = []
self.defaultGroup = Group()
self.cur = self.defaultGroup
self.subGroups = {}
# ---------------------
"""
Define equivalence of two ObjParser instances
"""
# ---------------------
def __eq__(self, p2: "ObjParser"):
if len(self.vertices) != len(p2.vertices):
return False
for i in range(len(self.vertices)):
if self.vertices[i] != p2.vertices[i]:
return False
if len(self.normals) != len(p2.normals):
return False
for i in range(len(self.normals)):
if self.normals[i] != p2.normals[i]:
return False
if len(self.textures) != len(p2.textures):
return False
for i in range(len(self.textures)):
if self.textures[i] != p2.textures[i]:
return False
return self.defaultGroup == p2.defaultGroup
# ---------------------
"""
parse reads in the obj file and holds everything in a group.
---- Inputs: --------
* path: a string, the path of the obj file
---- Outputs: --------
no output, all conversion will happen within the instance
"""
# ---------------------
def parse(self, path: str):
f = open(path, "r")
lines = f.readlines()
for l in lines:
self.convertLine(l)
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/ObjParserTest.py:test_parse
--- OR ----
python3 -m nose -v ../test/ObjParserTest.py:test_parse
--- OR ----
python -m nose -v ../test/ObjParserTest.py:test_parse
---------------------------------------------------
"""
# ---------------------
"""
convertLine tests whether a line is qualified and converts it into the formats we want.
---- Inputs: --------
* line: a string
---- Outputs: --------
no output, all conversion will happen within the instance
"""
# ---------------------
def convertLine(self, line: str):
# Here we use compile regex to help match the pattern of the phrases we want
# v is vector
# vt tecture, used in smooth triangle
# vn normal
rv = re.compile("(v|vn|vt) ([-+]?[0-9]+[\.]?[0-9]* ?){3}")
# f 1 2 3
rf1 = re.compile("f (\d+ ?){3,}")
# the two following type of fs are for smooth triangle
# f v1//vn1 1//2 1//3 1//4
rf2 = re.compile("f (\d+\/\/\d+ ?){3,}")
# f v1/vt1/vn1 1/2/3 1/3/4 1/4/5
rf3 = re.compile("f (\d+\/\d+\/\d+ ?){3,}")
rg = re.compile("g \w+")
if rv.match(line):
line = line.split(" ")
if line[0] == "v":
self.vertices.append(Tuple.point(
float(line[1]), float(line[2]), float(line[3])))
elif line[0] == "vn":
self.normals.append(Tuple.vector(
float(line[1]), float(line[2]), float(line[3])))
elif line[0] == "vt":
self.textures.append(Tuple.vector(
float(line[1]), float(line[2]), float(line[3])))
elif rf1.match(line):
line = line.split(" ")
head = int(line[1])-1
line = line[1:]
for i in range(1, len(line)-1):
t = Triangle(self.vertices[head],
self.vertices[int(line[i])-1],
self.vertices[int(line[i+1])-1])
self.cur.addChild(t)
elif rg.match(line):
line = line.split(" ")
groupName = line[1][:-1]
self.subGroups[groupName] = Group()
self.defaultGroup.addChild(self.subGroups[groupName])
self.cur = self.subGroups[groupName]
# ignore for now, this is for smooth triangle
elif rf2.match(line):
line = line.split(" ")
line = line[1:]
vert = []
norm = []
for l in line:
l = l.split("//")
vert.append(int(l[0])-1)
norm.append(int(l[1])-1)
for i in range(1, len(vert)-1):
t = Triangle(self.vertices[int(vert[0])],
self.vertices[int(vert[i])],
self.vertices[int(vert[i+1])],
self.normals[int(norm[0])],
self.normals[int(norm[i])],
self.normals[int(norm[i+1])])
self.cur.addChild(t)
elif rf3.match(line):
line = line.split(" ")
line = line[1:]
vert = []
norm = []
for l in line:
l = l.split("/")
vert.append(int(l[0])-1)
norm.append(int(l[2])-1)
for i in range(1, len(vert)-1):
t = Triangle(self.vertices[int(vert[0])],
self.vertices[int(vert[i])],
self.vertices[int(vert[i+1])],
self.normals[int(norm[0])],
self.normals[int(norm[i])],
self.normals[int(norm[i+1])])
self.cur.addChild(t)
# -----------------
"""
Make sure you are on ~/src
this is tested within the parser function
"""
| 3dRenderPy | /3dRenderPy-0.0.5.tar.gz/3dRenderPy-0.0.5/src/RenderPy/ObjParser.py | ObjParser.py |
import numpy as np
from RenderPy.Color import Color
from RenderPy.Matrix import Matrix
from RenderPy.Tuple import Tuple
from RenderPy.Intersection import Intersection
# ---------------------
"""
Pattern class helps to establish the patterns that would show up on the shape
It contains a transform matrix and two colors to match up the colors, but could be expanded later.
1. transform: a Matrix, a transform matrix.
2. c1: a Color, one color in the pattern
3. c2: a Color, one color in the pattern
4. patternType: a String, indicates the type of pattern used in the material
Currently we only support 4 types of patterns:
stripe, gradient, ring and checker, we will support more in the future
Pattern class contains the following functions:
__init__
__eq__
__str__
patternAtObject
stripe
gradient
ring
checker
"""
# ---------------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/PatternTest.py
--- OR ----
python3 -m nose -v ../test/PatternTest.py
--- OR ----
python -m nose -v ../test/PatternTest.py
---------------------------------------------------
"""
class Pattern():
# ---------------------
"""
Pattern class takes in two colors and a transform matrix and a string indicating the pattern type
"""
# ---------------------
def __init__(self, c1: "Color", c2: "Color", transform: "Matrix" = None, patternType: str = "stripe"):
self.c1 = c1
self.c2 = c2
if transform != None:
self.transform = transform
else:
self.transform = Matrix(matrix=np.eye(4))
self.patternType = patternType
# ---------------------
"""
Define equivalence of two Sphere instances
"""
# ---------------------
def __eq__(self, pattern2: "Pattern"):
return pattern2.c1 == self.c1 and pattern2.c2 == self.c2 and pattern2.transform == self.transform
# ---------------------
"""
Define the string of pattern
"""
# ---------------------
def __str__(self):
return "Color1: " + str(self.c1) + "\nColor2: " + str(self.c2) + "\nTransfrom Matrix: \n" + str(self.transform) + "\nPattern Type: " + self.patternType
# ---------------------
"""
Stripe pattern looks like ababab across the main axis
---- Inputs: --------
* point: a Point
* objTransform: a Matrix, the transform matrix of the object
---- Outputs: --------
* color: a Color, the color at the point
"""
# ---------------------
def patternAtObject(self, point: "Tuple", objTransform: "Matrix"):
objPoint = ~objTransform * point
patternPoint = ~self.transform*objPoint
if self.patternType == "stripe":
return self.stripe(patternPoint)
elif self.patternType == "gradient":
return self.gradient(patternPoint)
elif self.patternType == "ring":
return self.ring(patternPoint)
elif self.patternType == "checker":
return self.checker(patternPoint)
else:
return Color(patternPoint.x, patternPoint.y, patternPoint.z)
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/PatternTest.py:test_patternAtObject
--- OR ----
python3 -m nose -v ../test/PatternTest.py:test_patternAtObject
--- OR ----
python -m nose -v ../test/PatternTest.py:test_patternAtObject
---------------------------------------------------
"""
# ---------------------
"""
Stripe pattern looks like ababab across the main axis
---- Inputs: --------
* point: a Point
---- Outputs: --------
* color: a Color, the color at the point
"""
# ---------------------
def stripe(self, point: "Tuple"):
return self.c1 if np.floor(point.x) % 2 == 0 else self.c2
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/PatternTest.py:test_stripe
--- OR ----
python3 -m nose -v ../test/PatternTest.py:test_stripe
--- OR ----
python -m nose -v ../test/PatternTest.py:test_stripe
---------------------------------------------------
"""
# ---------------------
"""
Gradient pattern looks like a->b incrementally across the main axis
---- Inputs: --------
* point: a Point
---- Outputs: --------
* color: a Color, the color at the point
"""
# ---------------------
def gradient(self, point: "Tuple"):
distance = self.c2-self.c1
fraction = float(point.x - np.floor(point.x))
return self.c1 + distance * fraction
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/PatternTest.py:test_gradient
--- OR ----
python3 -m nose -v ../test/PatternTest.py:test_gradient
--- OR ----
python -m nose -v ../test/PatternTest.py:test_gradient
---------------------------------------------------
"""
# ---------------------
"""
Ring pattern looks like ababab along x-axis and z-axis and in a circle
---- Inputs: --------
* point: a Point
---- Outputs: --------
* color: a Color, the color at the point
"""
# ---------------------
def ring(self, point: "Tuple"):
if np.floor((point.x**2 + point.z**2)) % 2 == 0:
return self.c1
return self.c2
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/PatternTest.py:test_ring
--- OR ----
python3 -m nose -v ../test/PatternTest.py:test_ring
--- OR ----
python -m nose -v ../test/PatternTest.py:test_ring
---------------------------------------------------
"""
# ---------------------
"""
3D Checker pattern looks like ababab along x-axis and y-axis and in a square but does not influence z-axis
---- Inputs: --------
* point: a Point
---- Outputs: --------
* color: a Color, the color at the point
"""
# ---------------------
def checker(self, point: "Tuple"):
if (np.floor(np.array([point.x, point.y, point.z])).sum()) % 2 == 0:
return self.c1
return self.c2
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/PatternTest.py:test_checker
--- OR ----
python3 -m nose -v ../test/PatternTest.py:test_checker
--- OR ----
python -m nose -v ../test/PatternTest.py:test_checker
---------------------------------------------------
"""
| 3dRenderPy | /3dRenderPy-0.0.5.tar.gz/3dRenderPy-0.0.5/src/RenderPy/Pattern.py | Pattern.py |
import numpy as np
from RenderPy.Shape import Shape
from RenderPy.Tuple import Tuple
from RenderPy.Intersection import Intersection
# ---------------------
"""
Group class helps to describe a collection of multiple shapes and they would be transformed together
It inherits all elements from shape
The group's normal is calculated within each sub shapes.
It has an array of shapes
Group class contains the following functions:
__init__
localIntersect
"""
# ---------------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/GroupTest.py
--- OR ----
python3 -m nose -v ../test/GroupTest.py
--- OR ----
python -m nose -v ../test/GroupTest.py
---------------------------------------------------
"""
class Group(Shape):
# ---------------------
"""
Group class takes in no input
"""
# ---------------------
def __init__(self, objs=None):
super().__init__()
if objs == None:
self.objects = []
else:
for i in objs:
i.parent = self
self.objects = objs
# ---------------------
"""
Define equivalence of two Cube instances
"""
# ---------------------
def __eq__(self, group2: "Group"):
if type(group2).__name__ != "Group":
return False
if len(self.objects) != len(group2.objects):
return False
for i in range(len(self.objects)):
if self.objects[i] != group2.objects[i]:
return False
return True
# ---------------------
"""
Add child addas a shape to the object array of the group
---- Inputs: --------
* shape: a Shape, that is any form like sphere, cube, cylinder or cone
"""
# ---------------------
def addChild(self, shape):
shape.parent = self
self.objects.append(shape)
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/GroupTest.py:test_addChild
--- OR ----
python3 -m nose -v ../test/GroupTest.py:test_addChild
--- OR ----
python -m nose -v ../test/GroupTest.py:test_addChild
---------------------------------------------------
"""
# ---------------------
"""
Find the intersection between the ray and the cube
---- Inputs: --------
* ray: a Ray
---- Outputs: --------
* count: a scalar, the number of intersections
* results: a tuple, all intersections are listed
"""
# ---------------------
def localIntersect(self, ray: "Ray"):
xs = []
c = 0
for i in self.objects:
count, result = i.intersect(ray)
c += count
xs += result
xs = sorted(xs, key=lambda x: x.t)
return c, xs
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/GroupTest.py:test_intersect
--- OR ----
python3 -m nose -v ../test/GroupTest.py:test_intersect
--- OR ----
python -m nose -v ../test/GroupTest.py:test_intersect
---------------------------------------------------
"""
| 3dRenderPy | /3dRenderPy-0.0.5.tar.gz/3dRenderPy-0.0.5/src/RenderPy/Group.py | Group.py |
import numpy as np
from RenderPy.Shape import Shape
from RenderPy.Tuple import Tuple
from RenderPy.Intersection import Intersection
# ---------------------
"""
Triangle class helps to describe a triangle in the world,
it is established based on the input point values.
It could be used to form a large shape by different combinations.
It is useful for reading obj files
It inherits all elements from shape
Here, we combine the definition of smooth triangle and triangle together.
If you input n1,n2 and n3 for a triangle, it would be a smooth triangle.
Cone class contains the following functions:
__init__
localIntersect
localNormalAt
"""
# ---------------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/TriangleTest.py
--- OR ----
python3 -m nose -v ../test/TriangleTest.py
--- OR ----
python -m nose -v ../test/TriangleTest.py
---------------------------------------------------
"""
class Triangle(Shape):
# ---------------------
"""
Triangle class takes in three points to describe the three corners of the triangle
"""
# ---------------------
def __init__(self, p1: "Tuple", p2: "Tuple", p3: "Tuple", n1: "Tuple" = None, n2: "Tuple" = None, n3: "Tuple" = None):
super().__init__()
self.p1 = p1
self.p2 = p2
self.p3 = p3
self.e1 = p2-p1
self.e2 = p3-p1
self.n1 = n1
self.n2 = n2
self.n3 = n3
self.normal = (self.e2.cross(self.e1)).normalize()
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/TriangleTest.py:test_init
--- OR ----
python3 -m nose -v ../test/TriangleTest.py:test_init
--- OR ----
python -m nose -v ../test/TriangleTest.py:test_init
---------------------------------------------------
"""
# ---------------------
"""
Define equivalence of two Triangle instances
"""
# ---------------------
def __eq__(self, t2: "Triangle"):
if type(t2).__name__ != "Triangle":
return False
return self.material == t2.material and self.transform == t2.transform and t2.p1 == self.p1 and t2.p2 == self.p2 and t2.p3 == self.p3
# ---------------------
"""
Define print format for triangle instances
"""
# ---------------------
def __str__(self):
result = "p1:"+str(self.p1)+"\n" + "p2:" + \
str(self.p2)+"\n"+"p3:"+str(self.p3)+"\n"
if self.n1 != None:
result += "n1:"+str(self.n1) + "\n" + "n2: " + \
str(self.n2) + "\n" + "n3: "+str(self.n3) + "\n"
return result
# ---------------------
"""
Find the intersection between the ray and the cube
---- Inputs: --------
* ray: a Ray
---- Outputs: --------
* count: a scalar, the number of intersections
* results: a tuple, all intersections are listed
"""
# ---------------------
def localIntersect(self, ray: "Ray"):
de2 = ray.direction.cross(self.e2)
det = self.e1.dot(de2)
if abs(det) < 0.00001:
return 0, []
f = 1/det
op1 = ray.origin-self.p1
u = op1.dot(de2) * f
if u < 0 or u > 1:
return 0, []
oe1 = op1.cross(self.e1)
v = ray.direction.dot(oe1)*f
if v < 0 or (u+v) > 1:
return 0, []
t = self.e2.dot(oe1)
if self.n1 != None:
return 1, [Intersection(t, self, u, v), ]
return 1, [Intersection(t, self), ]
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/TriangleTest.py:test_intersect
--- OR ----
python3 -m nose -v ../test/TriangleTest.py:test_intersect
--- OR ----
python -m nose -v ../test/TriangleTest.py:test_intersect
---------------------------------------------------
"""
# ---------------------
"""
Find the normal at a certain point of the Cube
---- Inputs: --------
* point: a Tuple, indicating a point on the Cube
---- Outputs: --------
* vector: the normal vector
"""
# ---------------------
def localNormalAt(self, point: "Tuple", **kwargs):
if "hit" not in kwargs:
return self.normal
hit = kwargs["hit"]
return self.n2 * hit.u + self.n3 * hit.v + self.n1 * (1-hit.u-hit.v)
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/TriangleTest.py:test_normalAt
--- OR ----
python3 -m nose -v ../test/TriangleTest.py:test_normalAt
--- OR ----
python -m nose -v ../test/TriangleTest.py:test_normalAt
---------------------------------------------------
"""
| 3dRenderPy | /3dRenderPy-0.0.5.tar.gz/3dRenderPy-0.0.5/src/RenderPy/Triangle.py | Triangle.py |
import numpy as np
from RenderPy.Shape import Shape
from RenderPy.Tuple import Tuple
from RenderPy.Intersection import Intersection
# ---------------------
"""
Cube class helps to describe a cube with a center at point(0,0,0)
It inherits all elements from shape
Cube class contains the following functions:
__init__
localIntersect
localNormalAt
"""
# ---------------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/CubeTest.py
--- OR ----
python3 -m nose -v ../test/CubeTest.py
--- OR ----
python -m nose -v ../test/CubeTest.py
---------------------------------------------------
"""
class Cube(Shape):
# ---------------------
"""
Cube class takes in no input
"""
# ---------------------
def __init__(self):
super().__init__()
# ---------------------
"""
Define equivalence of two Cube instances
"""
# ---------------------
def __eq__(self, cube2: "Cube"):
if type(cube2).__name__ != "Cube":
return False
return self.material == cube2.material and self.transform == cube2.transform
# ---------------------
"""
Find the intersection between the ray and the cube
---- Inputs: --------
* ray: a Ray
---- Outputs: --------
* count: a scalar, the number of intersections
* results: a tuple, all intersections are listed
"""
# ---------------------
def localIntersect(self, ray: "Ray"):
def checkAxis(origin, direction):
tminNumerator = (-1-origin)
tmaxNumerator = (1-origin)
if abs(direction) >= 0.00001:
tmin = tminNumerator/direction
tmax = tmaxNumerator/direction
else:
tmin = tminNumerator * float(np.Infinity)
tmax = tmaxNumerator * float(np.Infinity)
if tmin > tmax:
tmin, tmax = tmax, tmin
return tmin, tmax
xtmin, xtmax = checkAxis(ray.origin.x, ray.direction.x)
ytmin, ytmax = checkAxis(ray.origin.y, ray.direction.y)
ztmin, ztmax = checkAxis(ray.origin.z, ray.direction.z)
tmin = max(xtmin, ytmin, ztmin)
tmax = min(xtmax, ytmax, ztmax)
if tmin > tmax:
return 0, []
return 2, [Intersection(tmin, self), Intersection(tmax, self)]
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/CubeTest.py:test_intersect
--- OR ----
python3 -m nose -v ../test/CubeTest.py:test_intersect
--- OR ----
python -m nose -v ../test/CubeTest.py:test_intersect
---------------------------------------------------
"""
# ---------------------
"""
Find the normal at a certain point of the Cube
---- Inputs: --------
* point: a Tuple, indicating a point on the Cube
---- Outputs: --------
* vector: the normal vector
"""
# ---------------------
def localNormalAt(self, point: "Tuple"):
maxc = max(abs(point.x), abs(point.y), abs(point.z))
if maxc - abs(point.x) <= 0.0001:
return Tuple.vector(point.x, 0, 0)
elif maxc - abs(point.y) <= 0.0001:
return Tuple.vector(0, point.y, 0)
return Tuple.vector(0, 0, point.z)
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/CubeTest.py:test_normalAt
--- OR ----
python3 -m nose -v ../test/CubeTest.py:test_normalAt
--- OR ----
python -m nose -v ../test/CubeTest.py:test_normalAt
---------------------------------------------------
"""
| 3dRenderPy | /3dRenderPy-0.0.5.tar.gz/3dRenderPy-0.0.5/src/RenderPy/Cube.py | Cube.py |
from RenderPy.Shape import Shape
from RenderPy.Tuple import Tuple
from RenderPy.Intersection import Intersection
# ---------------------
"""
Plane class helps to describe a plane with a center at point(0,0,0)
It inherits all elements from shape
Plane class contains the following functions:
__init__
localIntersect
localNormalAt
"""
# ---------------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/PlaneTest.py
--- OR ----
python3 -m nose -v ../test/PlaneTest.py
--- OR ----
python -m nose -v ../test/PlaneTest.py
---------------------------------------------------
"""
class Plane(Shape):
# ---------------------
"""
Plane class takes in no input
"""
# ---------------------
def __init__(self):
super().__init__()
# ---------------------
"""
Define equivalence of two Plane instances
"""
# ---------------------
def __eq__(self, plane2: "Plane"):
if type(plane2).__name__ != "Plane":
return False
return self.material == plane2.material and self.transform == plane2.transform
# ---------------------
"""
Find the intersection between the ray and the plane
---- Inputs: --------
* ray: a Ray
---- Outputs: --------
* count: a scalar, the number of intersections
* results: a tuple, all intersections are listed
"""
# ---------------------
def localIntersect(self, ray: "Ray"):
if abs(ray.direction.y) < 0.00001:
return 0, ()
return 1, [Intersection(-ray.origin.y/ray.direction.y, self), ]
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/PlaneTest.py:test_intersect
--- OR ----
python3 -m nose -v ../test/PlaneTest.py:test_intersect
--- OR ----
python -m nose -v ../test/PlaneTest.py:test_intersect
---------------------------------------------------
"""
# ---------------------
"""
Find the normal at a certain point of the Plane
---- Inputs: --------
* point: a Tuple, indicating a point on the Plane
* hit: an Intersection, just follow the definition of shape localNormalAt
---- Outputs: --------
* vector: the normal vector
"""
# ---------------------
def localNormalAt(self, point: "Tuple"):
return Tuple.vector(0, 1, 0)
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/PlaneTest.py:test_normalAt
--- OR ----
python3 -m nose -v ../test/PlaneTest.py:test_normalAt
--- OR ----
python -m nose -v ../test/PlaneTest.py:test_normalAt
---------------------------------------------------
"""
| 3dRenderPy | /3dRenderPy-0.0.5.tar.gz/3dRenderPy-0.0.5/src/RenderPy/Plane.py | Plane.py |
import numpy as np
from RenderPy.Shape import Shape
from RenderPy.Tuple import Tuple
from RenderPy.Intersection import Intersection
# ---------------------
"""
Cylinder class helps to describe a cylinder with a center at point(0,0,0)
It inherits all elements from shape
Cylinder class contains the following functions:
__init__
localIntersect
localNormalAt
"""
# ---------------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/CylinderTest.py
--- OR ----
python3 -m nose -v ../test/CylinderTest.py
--- OR ----
python -m nose -v ../test/CylinderTest.py
---------------------------------------------------
"""
class Cylinder(Shape):
# ---------------------
"""
Cylinder class takes in a minimum and a maximum to describe the height of a cylinder
"""
# ---------------------
def __init__(self, minimum=float("-inf"), maximum=float("inf"), closed=False):
super().__init__()
self.minimum = minimum
self.maximum = maximum
self.closed = closed
# ---------------------
"""
Define equivalence of two Cylinder instances
"""
# ---------------------
def __eq__(self, cylinder2: "Cylinder"):
if type(cylinder2).__name__ != "Cylinder":
return False
return self.material == cylinder2.material and self.transform == cylinder2.transform
# ---------------------
"""
Find the intersection between the ray and the cube
---- Inputs: --------
* ray: a Ray
---- Outputs: --------
* count: a scalar, the number of intersections
* results: a tuple, all intersections are listed
"""
# ---------------------
def localIntersect(self, ray: "Ray"):
def checkCaps(t):
x = ray.origin.x + t*ray.direction.x
z = ray.origin.z + t*ray.direction.z
return (x*x + z*z) <= 1
def intersectCap(xs):
if not self.closed or abs(ray.direction.y) < 0.00001:
return len(xs), xs
t = (self.minimum - ray.origin.y)/ray.direction.y
if checkCaps(t):
xs.append(Intersection(t, self))
t = (self.maximum - ray.origin.y)/ray.direction.y
if checkCaps(t):
xs.append(Intersection(t, self))
return len(xs), xs
xs = []
a = ray.direction.x ** 2 + ray.direction.z**2
if a < 0.0001:
return intersectCap(xs)
b = 2*ray.origin.x*ray.direction.x + 2*ray.origin.z*ray.direction.z
c = ray.origin.x**2 + ray.origin.z**2 - 1
disc = b*b-4*a*c
if disc < 0:
return 0, ()
t0 = (-b-disc**0.5)/(2*a)
t1 = (-b+disc**0.5)/(2*a)
if t0 > t1:
t0, t1 = t1, t0
y0 = ray.origin.y + t0*ray.direction.y
if self.minimum < y0 < self.maximum:
xs.append(Intersection(t0, self))
y1 = ray.origin.y + t1*ray.direction.y
if self.minimum < y1 < self.maximum:
xs.append(Intersection(t1, self))
return intersectCap(xs)
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/CylinderTest.py:test_intersect
--- OR ----
python3 -m nose -v ../test/CylinderTest.py:test_intersect
--- OR ----
python -m nose -v ../test/CylinderTest.py:test_intersect
---------------------------------------------------
"""
# ---------------------
"""
Find the normal at a certain point of the Cube
---- Inputs: --------
* point: a Tuple, indicating a point on the Cube
---- Outputs: --------
* vector: the normal vector
"""
# ---------------------
def localNormalAt(self, point: "Tuple"):
dist = point.x * point.x + point.z * point.z
if dist < 1 and point.y >= self.maximum-0.00001:
return Tuple.vector(0, 1, 0)
elif dist < 1 and point.y <= self.minimum + 0.00001:
return Tuple.vector(0, -1, 0)
return Tuple.vector(point.x, 0, point.z)
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/CylinderTest.py:test_normalAt
--- OR ----
python3 -m nose -v ../test/CylinderTest.py:test_normalAt
--- OR ----
python -m nose -v ../test/CylinderTest.py:test_normalAt
---------------------------------------------------
"""
| 3dRenderPy | /3dRenderPy-0.0.5.tar.gz/3dRenderPy-0.0.5/src/RenderPy/Cylinder.py | Cylinder.py |
import numpy as np
from RenderPy.Shape import Shape
from RenderPy.Tuple import Tuple
from RenderPy.Intersection import Intersection
# ---------------------
"""
Cone class helps to describe a cone with a center at point(0,0,0)
It inherits all elements from shape
Cone class contains the following functions:
__init__
localIntersect
localNormalAt
"""
# ---------------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/ConeTest.py
--- OR ----
python3 -m nose -v ../test/ConeTest.py
--- OR ----
python -m nose -v ../test/ConeTest.py
---------------------------------------------------
"""
class Cone(Shape):
# ---------------------
"""
Cone class takes in a minimum and a maximum to describe the height of a cone
"""
# ---------------------
def __init__(self, minimum=float("-inf"), maximum=float("inf"), closed=False):
super().__init__()
self.minimum = minimum
self.maximum = maximum
self.closed = closed
# ---------------------
"""
Define equivalence of two Cube instances
"""
# ---------------------
def __eq__(self, cone2: "Cone"):
if type(cone2).__name__ != "Cone":
return False
return self.material == cone2.material and self.transform == cone2.transform
# ---------------------
"""
Find the intersection between the ray and the cube
---- Inputs: --------
* ray: a Ray
---- Outputs: --------
* count: a scalar, the number of intersections
* results: a tuple, all intersections are listed
"""
# ---------------------
def localIntersect(self, ray: "Ray"):
def checkCaps(t):
x = ray.origin.x + t*ray.direction.x
z = ray.origin.z + t*ray.direction.z
yVal = max(self.maximum, self.minimum)
return (x*x + z*z) <= yVal * yVal
def intersectCap(xs):
if not self.closed or abs(ray.direction.y) < 0.00001:
return len(xs), xs
t = (self.minimum - ray.origin.y)/ray.direction.y
if checkCaps(t):
xs.append(Intersection(t, self))
t = (self.maximum - ray.origin.y)/ray.direction.y
if checkCaps(t):
xs.append(Intersection(t, self))
return len(xs), xs
xs = []
a = ray.direction.x ** 2 + ray.direction.z**2 - ray.direction.y ** 2
b = 2*ray.origin.x*ray.direction.x + 2*ray.origin.z * \
ray.direction.z - 2 * ray.origin.y * ray.direction.y
c = ray.origin.x**2 + ray.origin.z**2 - ray.origin.y**2
if abs(a) < 0.00001 and abs(b) < 0.00001:
return intersectCap(xs)
elif abs(a) < 0.00001:
xs.append(Intersection(-c/(2*b), self))
else:
disc = b*b-4*a*c
if disc < 0:
return 0, ()
t0 = (-b-disc**0.5)/(2*a)
t1 = (-b+disc**0.5)/(2*a)
if t0 > t1:
t0, t1 = t1, t0
y0 = ray.origin.y + t0*ray.direction.y
if self.minimum < y0 < self.maximum:
xs.append(Intersection(t0, self))
y1 = ray.origin.y + t1*ray.direction.y
if self.minimum < y1 < self.maximum:
xs.append(Intersection(t1, self))
return intersectCap(xs)
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/ConeTest.py:test_intersect
--- OR ----
python3 -m nose -v ../test/ConeTest.py:test_intersect
--- OR ----
python -m nose -v ../test/ConeTest.py:test_intersect
---------------------------------------------------
"""
# ---------------------
"""
Find the normal at a certain point of the Cube
---- Inputs: --------
* point: a Tuple, indicating a point on the Cube
---- Outputs: --------
* vector: the normal vector
"""
# ---------------------
def localNormalAt(self, point: "Tuple"):
dist = point.x * point.x + point.z * point.z
if dist < 1 and point.y >= self.maximum-0.00001:
return Tuple.vector(0, 1, 0)
elif dist < 1 and point.y <= self.minimum + 0.00001:
return Tuple.vector(0, -1, 0)
y = dist ** 0.5
if point.y > 0:
y = -y
return Tuple.vector(point.x, y, point.z)
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/ConeTest.py:test_normalAt
--- OR ----
python3 -m nose -v ../test/ConeTest.py:test_normalAt
--- OR ----
python -m nose -v ../test/ConeTest.py:test_normalAt
---------------------------------------------------
"""
| 3dRenderPy | /3dRenderPy-0.0.5.tar.gz/3dRenderPy-0.0.5/src/RenderPy/Cone.py | Cone.py |
import numpy as np
from RenderPy.Tuple import Tuple
from RenderPy.Color import Color
from RenderPy.Light import Light
from RenderPy.Pattern import Pattern
from RenderPy.Matrix import Matrix
# ---------------------
"""
Material class describes the material of a shape based on the Phong Reflection Model
Each material contains 5 elements:
1. color: a Color, the color of the material
2. ambient: a float, describe the ambient color of the material
3. diffuse: a float, describe the diffuse color of the material
4. specular: a float, describe the specular color of the material
5. shininess: a float, describe the shineness of the material
6. pattern: a Pattern, describe the pattern of the material
7. reflective: a float, indicates the reflectivity of the material
Material class contains the following functions:
__init__
__str__
__eq__
lighting
"""
# ---------------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/MaterialTest.py
--- OR ----
python3 -m nose -v ../test/MaterialTest.py
--- OR ----
python -m nose -v ../test/MaterialTest.py
---------------------------------------------------
"""
class Material():
# ---------------------
"""
Material takes in nine parameters
"""
# ---------------------
def __init__(self, color: "Color" = Color(1, 1, 1), ambient: float = 0.1, diffuse: float = 0.9, specular: float = 0.9, shininess: float = 200, pattern: "Pattern" = None, reflective: float = 0, transparency: float = 0, refractiveIndex: float = 1):
self.color = color
self.ambient = ambient
self.diffuse = diffuse
self.specular = specular
self.shininess = shininess
self.pattern = pattern
self.reflective = reflective
self.transparency = transparency
self.refractiveIndex = refractiveIndex
# ---------------------
"""
Define the output format for Material class
"""
# ---------------------
def __str__(self):
return "Color: " + str(self.color) + "\nAmbient: " + str(self.ambient) + "\nDiffuse: " + str(self.diffuse) + "\nSpecular: " + str(self.specular) + "\nShininess: " + str(self.shininess)+"\nPattern: \n"+str(self.pattern)+"\nReflective: "+str(self.reflective)+"\nTransparency: "+str(self.transparency)+"\nRefractive Index: "+str(self.refractiveIndex)
# ---------------------
"""
Define equivalence of two Material instances
"""
# ---------------------
def __eq__(self, material2: "Light"):
return self.color == material2.color and self.ambient == material2.ambient and self.diffuse == material2.diffuse and self.specular == material2.specular and self.shininess == material2.shininess and self.pattern == material2.pattern
# ---------------------
"""
Get the final color when the shape is shined by a light
---- Inputs: --------
* light: a Light
* point: a Tuple, the place where we are looking at for the light and shape intersection
* eyev: a Tuple, the position of our eye
* normalv: a Tuple, the normal vector
* inShadow: a bool, indicate whether there is a shadow
* transform: a Matrix, the transform matrix of the shape, used for calculating pattern
---- Outputs: --------
* count: a scalar, the number of intersections
* results: a tuple, all intersections are listed
"""
# ---------------------
def lighting(self, light: "Light", point: "Tuple", eyev: "Tuple", normalv: "Tuple", inShadow: bool = False, transform: "Matrix" = Matrix(matrix=np.eye(4))):
if self.pattern is not None:
self.color = self.pattern.patternAtObject(point, transform)
effectiveColor = self.color * light.intensity
lightV = (light.position-point).normalize()
ambient = effectiveColor * self.ambient
if inShadow:
return ambient
lightDotNormal = lightV.dot(normalv)
# calculate diffuse and specular
if lightDotNormal < 0:
diffuse = Color(0, 0, 0)
specular = Color(0, 0, 0)
else:
diffuse = effectiveColor * self.diffuse * lightDotNormal
reflect = ~lightV.reflectV(normalv)
reflectDotEye = reflect.dot(eyev)
if reflectDotEye == 0:
specular = Color(0, 0, 0)
else:
factor = reflectDotEye**self.shininess
specular = light.intensity * self.specular * factor
return ambient + diffuse + specular
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/MaterialTest.py:test_lighting
--- OR ----
python3 -m nose -v ../test/MaterialTest.py:test_lighting
--- OR ----
python -m nose -v ../test/MaterialTest.py:test_lighting
---------------------------------------------------
"""
| 3dRenderPy | /3dRenderPy-0.0.5.tar.gz/3dRenderPy-0.0.5/src/RenderPy/Material.py | Material.py |
from RenderPy.Shape import Shape
from RenderPy.Tuple import Tuple
from RenderPy.Material import Material
from RenderPy.Intersection import Intersection
# ---------------------
"""
Sphere class helps to describe a sphere with a center at point(0,0,0)
It inherits all elements from shape
It contains a center element
center: a Tuple marks the center of the sphere
Sphere class contains the following functions:
__init__
localIntersect
localNormalAt
glassSphere
"""
# ---------------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/SphereTest.py
--- OR ----
python3 -m nose -v ../test/SphereTest.py
--- OR ----
python -m nose -v ../test/SphereTest.py
---------------------------------------------------
"""
class Sphere(Shape):
# ---------------------
"""
Sphere class takes in no input
center is the center point of sphere
"""
# ---------------------
def __init__(self):
super().__init__()
# ---------------------
"""
Define equivalence of two Sphere instances
"""
# ---------------------
def __eq__(self, sphere2: "Sphere"):
if type(sphere2).__name__ != "Sphere":
return False
return self.center == sphere2.center and self.material == sphere2.material and self.transform == sphere2.transform
# ---------------------
"""
Find the intersection between the ray and the sphere
---- Inputs: --------
* ray: a Ray
---- Outputs: --------
* count: a scalar, the number of intersections
* results: a tuple, all intersections are listed
"""
# ---------------------
def localIntersect(self, ray: "Ray"):
sphereToRay = ray.origin-self.center
a = ray.direction.dot(ray.direction)
b = 2 * ray.direction.dot(sphereToRay)
c = sphereToRay.dot(sphereToRay) - 1
discriminant = b*b - 4*a*c
if discriminant < 0:
return 0, []
elif discriminant == 0:
return 1, [Intersection((-b-discriminant**0.5)/(2*a), self), ]
t1 = (-b-discriminant**0.5)/(2*a)
t1 = Intersection(t1, self)
t2 = (-b+discriminant**0.5)/(2*a)
t2 = Intersection(t2, self)
return 2, [t1, t2]
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/SphereTest.py:test_intersect
--- OR ----
python3 -m nose -v ../test/SphereTest.py:test_intersect
--- OR ----
python -m nose -v ../test/SphereTest.py:test_intersect
---------------------------------------------------
"""
# ---------------------
"""
Find the normal at a certain point of the sphere
---- Inputs: --------
* point: a Tuple, indicating a point on the sphere
---- Outputs: --------
* vector: the normal vector
"""
# ---------------------
def localNormalAt(self, point: "Tuple"):
return point-self.center
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/SphereTest.py:test_normalAt
--- OR ----
python3 -m nose -v ../test/SphereTest.py:test_normalAt
--- OR ----
python -m nose -v ../test/SphereTest.py:test_normalAt
---------------------------------------------------
"""
# ---------------------
"""
glassSphere method creates a glass sphere with transparency of 1 and refractive index 1.5
---- Outputs: --------
* s: a Sphere
"""
# ---------------------
@staticmethod
def glassSphere():
s = Sphere()
s.material = Material(transparency=1, refractiveIndex=1.5)
return s
| 3dRenderPy | /3dRenderPy-0.0.5.tar.gz/3dRenderPy-0.0.5/src/RenderPy/Sphere.py | Sphere.py |
import numpy as np
from RenderPy.Shape import Shape
from RenderPy.Tuple import Tuple
from RenderPy.Intersection import Intersection
# ---------------------
"""
CSG class helps to describe a shape that is built by some combinations of two shapes
The combinations it supports are union, intersection and difference
It inherits all elements from shape
This files contains two parts:
includes function
CSG class
CSG class contains the following functions:
__init__
intersectionAllowed
filterIntersection
localIntersect
"""
# ---------------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/CSGTest.py
--- OR ----
python3 -m nose -v ../test/CSGTest.py
--- OR ----
python -m nose -v ../test/CSGTest.py
---------------------------------------------------
"""
# ---------------------
"""
includes check whehter shape1 includes shape2
---- Inputs: --------
* s1: a Shape, shape1
* s2: a Shape, shape2
---- Outputs: --------
* includes: a bool, whether shape1 includes shape2
"""
# ---------------------
def includes(s1, s2):
if type(s1).__name__ == "CSG":
return s1.left.includes(s2) or s1.right.includes(s2)
if type(s1).__name__ == "Group":
for i in s1.objects:
if i.includes(s2):
return True
return False
return s1 == s2
# -----------------
"""
Make sure you are on ~/src
this is tested within filterIntersection in CSG class
"""
class CSG(Shape):
# ---------------------
"""
Cube class takes in no input
"""
# ---------------------
def __init__(self, shape1, shape2, operation: "str"):
super().__init__()
self.left = shape1
self.right = shape2
self.operation = operation
shape1.parent = self
shape2.parent = self
# ---------------------
"""
Define equivalence of two Cube instances
"""
# ---------------------
def __eq__(self, csg2: "CSG"):
if type(csg2).__name__ != "CSG":
return False
return self.s1 == csg2.s1 and self.s2 == csg2.s2 and self.operation == csg2.operation
# ---------------------
"""
Intersection allowed helps to determine whehter there is a intersection
---- Inputs: --------
* lhit: a boolean, indicate whether there is a left hit
* inl: a boolean, indicate whether there is a inner left hit
* inr: a boolean, indicates whether there is a inner right hit
---- Outputs: --------
* allowed: a boolean, indicates whether the intersection is allowed
"""
# ---------------------
def intersectionAllowed(self, lhit: bool, inl: bool, inr: bool):
if self.operation == "union":
return (lhit and not inr) or (not lhit and not inl)
elif self.operation == "intersect":
return (lhit and inr) or (not lhit and inl)
elif self.operation == "difference":
return (lhit and not inr) or (not lhit and inl)
return False
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/CubeTest.py:test_intersectionAllowed
--- OR ----
python3 -m nose -v ../test/CubeTest.py:test_intersectionAllowed
--- OR ----
python -m nose -v ../test/CubeTest.py:test_intersectionAllowed
---------------------------------------------------
"""
# ---------------------
"""
filterIntersection helps to find the valid intersections based on intersectionAllowed
---- Inputs: --------
* xs: a list of Intersections
---- Outputs: --------
* result: a list of Intersections
"""
# ---------------------
def filterIntersection(self, xs):
inl = False
inr = False
result = []
for i in xs:
lhit = includes(self.left, i.shape)
tmp = self.intersectionAllowed(lhit, inl, inr)
if self.intersectionAllowed(lhit, inl, inr):
result.append(i)
if lhit:
inl = not inl
else:
inr = not inr
return result
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/CubeTest.py:test_filterIntersection
--- OR ----
python3 -m nose -v ../test/CubeTest.py:test_filterIntersection
--- OR ----
python -m nose -v ../test/CubeTest.py:test_filterIntersection
---------------------------------------------------
"""
# ---------------------
"""
Find the intersection between the ray and the cube
---- Inputs: --------
* ray: a Ray
---- Outputs: --------
* count: a scalar, the number of intersections
* results: a tuple, all intersections are listed
"""
# ---------------------
def localIntersect(self, ray: "Ray"):
countLeft, leftXs = self.left.intersect(ray)
countRight, rightXs = self.right.intersect(ray)
xs = leftXs + rightXs
xs = sorted(xs, key=lambda x: x.t)
result = self.filterIntersection(xs)
return len(result), result
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/CubeTest.py:test_intersect
--- OR ----
python3 -m nose -v ../test/CubeTest.py:test_intersect
--- OR ----
python -m nose -v ../test/CubeTest.py:test_intersect
---------------------------------------------------
"""
| 3dRenderPy | /3dRenderPy-0.0.5.tar.gz/3dRenderPy-0.0.5/src/RenderPy/CSG.py | CSG.py |
import abc
import numpy as np
from RenderPy.Tuple import Tuple
from RenderPy.Matrix import Matrix
from RenderPy.Ray import Ray
from RenderPy.Material import Material
# ---------------------
"""
Shape class is a parent class containing all necessary compnents of a shape.
Sphere and all other specific classes inherits it.
It contains the following elements:
1. transform: a Matrix, recording the transform matrix
2. material: a Material, recording the material of the shape
3. parent: a Shape, the parent of a shape in a group
Shape class contains the following functions:
__init__
__str__
intersect
localIntersect: an abstract method, would be implemented by other classes
normalAt
localNormalAt: an abstract method, would be implemented by other classes
"""
# ---------------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/ShapeTest.py
--- OR ----
python3 -m nose -v ../test/ShapeTest.py
--- OR ----
python -m nose -v ../test/ShapeTest.py
---------------------------------------------------
"""
class Shape():
# ---------------------
"""
Shape class takes in no input
"""
# ---------------------
def __init__(self):
self.center = Tuple.point(0, 0, 0)
self.material = Material()
self.transform = Matrix(matrix=np.eye(4))
self.parent = None
# ---------------------
"""
Define the output format for Shape class
"""
# ---------------------
def __str__(self):
return "The transform matrix is: \n" + str(self.transform) + "\n" + "The material is as the following: \n" + str(self.material) + "\n"
# ---------------------
"""
Find the intersection between the ray and the shape with the world axis
---- Inputs: --------
* ray: a Ray with world axis
---- Outputs: --------
* count: a scalar, the number of intersections
* results: a tuple, all intersections are listed
"""
# ---------------------
def intersect(self, ray: "Ray"):
localRay = ray.transform(~self.transform)
return self.localIntersect(localRay)
# ---------------------
"""
Make sure you are on ~/src
use the test of each different shape's intersect function
"""
# ---------------------
"""
Find the intersection with the shape as the main axis and center at the origin
---- Inputs: --------
* ray: a Ray with sphere axis
---- Outputs: --------
* count: a scalar, the number of intersections
* results: a tuple, all intersections are listed
"""
# ---------------------
@abc.abstractmethod
def localIntersect(self, ray: "Ray"):
raise NotImplementedError
# ---------------------
"""
Make sure you are on ~/src
this will be tested by all of the intersect function
"""
# ---------------------
"""
Find the normal between the ray and the shape with the world axis
---- Inputs: --------
* ray: a Ray with world axis
---- Outputs: --------
* count: a scalar, the number of intersections
* results: a tuple, all intersections are listed
"""
# ---------------------
def normalAt(self, point: "Tuple", **kwargs):
localPoint = self.worldToObject(point)
if "hit" in kwargs:
localNormal = self.localNormalAt(localPoint, hit=kwargs["hit"])
else:
localNormal = self.localNormalAt(localPoint)
return self.normalToWorld(localNormal)
# ---------------------
"""
Make sure you are on ~/src
use the test of each different shape's normalAt function
also, we have a specific test for group normal at the following:
---------------------------------------------------
nosetests -v ../test/ShapeTest.py:test_normalAt
--- OR ----
python3 -m nose -v ../test/ShapeTest.py:test_normalAt
--- OR ----
python -m nose -v ../test/ShapeTest.py:test_normalAt
---------------------------------------------------
"""
# ---------------------
"""
Find the normal with the shape as the main axis and center at the origin
---- Inputs: --------
* ray: a Ray with sphere axis
---- Outputs: --------
* count: a scalar, the number of intersections
* results: a tuple, all intersections are listed
"""
# ---------------------
@abc.abstractmethod
def localNormalAt(self, point: "Tuple", **kwargs):
raise NotImplementedError
# ---------------------
"""
Make sure you are on ~/src
this will be tested with all of normalAt function
"""
# ---------------------
"""
World to object converts the normal at the point of the shape to the shape axis
---- Inputs: --------
* point: a Tuple, indicating a point on the Shape
---- Outputs: --------
* point: a Tuple, the converted point
"""
# ---------------------
def worldToObject(self, point: "Tuple"):
if self.parent != None:
point = self.parent.worldToObject(point)
return ~self.transform * point
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/GroupTest.py:test_worldToObject
--- OR ----
python3 -m nose -v ../test/GroupTest.py:test_worldToObject
--- OR ----
python -m nose -v ../test/GroupTest.py:test_worldToObject
---------------------------------------------------
"""
# ---------------------
"""
Normal to World converts the normal at the point of the shape to the world axis
---- Inputs: --------
* nromal: a Tuple, indicating a point on the Shape
---- Outputs: --------
* normal: a Tuple, the converted normal vector
"""
# ---------------------
def normalToWorld(self, normal: "Tuple"):
normal = (~self.transform).transpose() * normal
normal.w = 0
normal.arr[3] = 0
normal = normal.normalize()
if self.parent != None:
normal = self.parent.normalToWorld(normal)
return normal
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/GroupTest.py:test_normalToWorld
--- OR ----
python3 -m nose -v ../test/GroupTest.py:test_normalToWorld
--- OR ----
python -m nose -v ../test/GroupTest.py:test_normalToWorld
---------------------------------------------------
"""
| 3dRenderPy | /3dRenderPy-0.0.5.tar.gz/3dRenderPy-0.0.5/src/RenderPy/Shape.py | Shape.py |
import os
import numpy as np
from PIL import Image
from RenderPy.Color import Color
# ---------------------
"""
Canvas class helps to describe a set of pixel in grids that help generate images.
Each canvas contains 2 elements: weight ,height
width, height are all float value
width: defining the number of columns, height: defining the number of rows
Canvas class contains the following functions:
__init__
__eq__
pixelAt
writePixel
canvasToPPM
canvasToPNG
saveImage
"""
# ---------------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/CanvasTest.py
--- OR ----
python3 -m nose -v ../test/CanvasTest.py
--- OR ----
python -m nose -v ../test/CanvasTest.py
---------------------------------------------------
"""
class Canvas():
# ---------------------
"""
Canvas class takes in two numbers
w is width, h is height
"""
# ---------------------
def __init__(self, w: int, h: int):
self.width = w
self.height = h
self.canv = [[Color() for _ in range(w)] for _ in range(h)]
# ---------------------
"""
Define equivalence of two Canvas instances
"""
# ---------------------
def __eq__(self, canvas2: "Canvas"):
if self.width == canvas2.width and self.height == canvas2.height:
for i in range(self.height):
for j in range(self.width):
if self.canv[i][j] != canvas2.canv[i][j]:
return False
return True
return False
# ---------------------
"""
Get the color of a given pixel
---- Inputs: --------
* cl: A float indicating the column number of where the pixel is at
* rw: A float indicating the row number of where the pixel is at
---- Outputs: --------
* Color: the color at the pixel
"""
# ---------------------
def pixelAt(self, cl: int, rw: int):
return self.canv[rw][cl]
# ---------------------
"""
Change the color of a given pixel
---- Inputs: --------
* cl: A float indicating the column number of where the pixel is at
* rw: A float indicating the row number of where the pixel is at
* color: A Color wanted to be at the pixel
"""
# ---------------------
def writePixel(self, cl: int, rw: int, color: "Color"):
self.canv[rw][cl] = color
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/CanvasTest.py:test_writePixel
--- OR ----
python3 -m nose -v ../test/CanvasTest.py:test_writePixel
--- OR ----
python -m nose -v ../test/CanvasTest.py:test_writePixel
---------------------------------------------------
"""
# ---------------------
"""
Convert the canvas to ppm formatted images
Generally existing PPM softwares accept a line more than 70 characters,
but there are some needs to have each line having less than or equal to 70 characters
We also need a new line at the end of the string
---- Outputs: --------
* result: A string containing the final ppm file
"""
# ---------------------
def canvasToPPM(self):
result = "P3\n"+str(self.width) + " " + str(self.height) + "\n255\n"
for row in self.canv:
temp = ""
for pix in row:
# providing a conversion from 0 to 1 to 255 scale
# if greater than 1, we read it as 1
# if smaller than 0, we read it as 0
def setColor(color):
if color >= 1:
return 255
elif color <= 0:
return 0
else:
return int(round(color * 255, 0))
red = str(setColor(pix.r))
green = str(setColor(pix.g))
blue = str(setColor(pix.b))
# for each color, if the existing line adding 1 to 3 characters
# we cut it off and strip the last space and add a new line
# so that we fulfill the 70 character requirment and do not cut off a color
if len(temp) + len(red) > 70:
result += temp[:-1] + "\n"
temp = ""
temp += red + " "
if len(temp) + len(green) > 70:
result += temp[:-1] + "\n"
temp = ""
temp += green + " "
if len(temp) + len(blue) > 70:
result += temp[:-1] + "\n"
temp = ""
temp += blue + " "
temp = temp[:-1] + "\n"
result += temp
return result
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/CanvasTest.py:test_canvasToPPM
--- OR ----
python3 -m nose -v ../test/CanvasTest.py:test_canvasToPPM
--- OR ----
python -m nose -v ../test/CanvasTest.py:test_canvasToPPM
---------------------------------------------------
"""
# ---------------------
"""
Convert the canvas to a numpy array in order to call PIL.image to convert it to png image
---- Outputs: --------
* result: A numpy array of size (h,w,3)
"""
# ---------------------
def canvasToPNG(self):
result = []
for rw in range(self.height):
row = []
for cl in range(self.width):
cur = np.rint(self.pixelAt(cl, rw).arr*255)
if cur[0] > 255:
cur[0] = 255
elif cur[0] < 0:
cur[0] = 0
if cur[1] > 255:
cur[1] = 255
elif cur[1] < 0:
cur[1] = 0
if cur[2] > 255:
cur[2] = 255
elif cur[2] < 0:
cur[2] = 0
row.append(cur)
result.append(row)
result = np.array(result)
result = result.astype(np.uint8)
return result
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/CanvasTest.py:test_canvasToPNG
--- OR ----
python3 -m nose -v ../test/CanvasTest.py:test_canvasToPNG
--- OR ----
python -m nose -v ../test/CanvasTest.py:test_canvasToPNG
---------------------------------------------------
"""
# ---------------------
"""
Save the result string from canvasToPPM to ppm file
---- Inputs: --------
* filename: A string indicating the file name you want for the image
* directory: default is the images folder, or a specefic one of your choice
"""
# ---------------------
def saveImage(self, filename: str, directory: str = "../images/", fileType="png"):
if not os.path.isdir(directory):
os.mkdir(directory)
path = directory + filename + "." + fileType
if fileType == "ppm":
result = self.canvasToPPM()
f = open(path, "w")
f.write(result)
f.close()
else:
result = self.canvasToPNG()
img = Image.fromarray(result, 'RGB')
img.save(path)
print(
filename + " written successfully, please take a look at folder " + directory)
# -----------------
"""
Go to your chosen folder to see whether the image is what you want!
"""
| 3dRenderPy | /3dRenderPy-0.0.5.tar.gz/3dRenderPy-0.0.5/src/RenderPy/Canvas.py | Canvas.py |
import math
import numpy as np
from RenderPy.Tuple import Tuple
# ---------------------
"""
Matrix class helps to describe a set of elements.
Each matrix contains 3 elements: weight ,height, matrix
width, height are all float value
width: defining the number of columns, height: defining the number of rows
matrix: defining a numpy matrix containing necessary numbers
Note: matrix class contains several transformation matrices.
In order to chain them, we need to have the last operation matrix multiply the previous matrix
Matrix class contains the following functions:
__init__
__str__
__eq__
__mul__
__invert__
identity
determinant
translation
scaling
rotateX
rotateY
rotateZ
shearing
viewTransform
"""
# ---------------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/MatrixTest.py
--- OR ----
python3 -m nose -v ../test/MatrixTest.py
--- OR ----
python -m nose -v ../test/MatrixTest.py
---------------------------------------------------
"""
class Matrix():
# ---------------------
"""
Matrix class takes in two numbers
w is width, h is height, matrix is a matrix
"""
# ---------------------
def __init__(self, w: int = None, h: int = None, matrix: np.ndarray = None):
if w == h == None:
try:
if matrix.size != 0:
self.matrix = matrix
self.width = matrix.shape[1]
self.height = matrix.shape[0]
except:
self.width = 0
self.height = 0
self.matrix = np.zeros((1, 1))
else:
self.width = w
self.height = h
self.matrix = np.zeros((h, w))
# ---------------------
"""
Define the output format for Matrix class
"""
# ---------------------
def __str__(self):
return str(self.matrix)
# ---------------------
"""
Define equivalence of two Matrix instances
This is based on numpy allclose function with absolute tolerance 0.00001
"""
# ---------------------
def __eq__(self, matrix2: "Matrix"):
return np.allclose(self.matrix, matrix2.matrix, atol=0.0001)
# ---------------------
"""
Define the multiplication between two Matrix (Cross product)
This helps to perform transformations
Define the multiplication between matrix and vector
Define the multiplication between matrix and scalar
Order matters, it is not interchangable
---- Inputs: --------
* value: A Matrix or a Tuple or a float
---- Outputs: --------
* Matrix: the result from matrix multiplication or a tuple from matrix and tuple multiplication or a matrix from matrix and scalar multiplication
"""
# ---------------------
def __mul__(self, value):
if type(value) == float:
return Matrix(matrix=self.matrix*value)
elif type(value).__name__ == "Tuple":
return Tuple(arr=np.matmul(self.matrix, value.arr))
return Matrix(matrix=np.matmul(self.matrix, value.matrix))
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/MatrixTest.py:test_mul
--- OR ----
python3 -m nose -v ../test/MatrixTest.py:test_mul
--- OR ----
python -m nose -v ../test/MatrixTest.py:test_mul
---------------------------------------------------
"""
# ---------------------
"""
This calculates the inversion of a matrix
---- Outputs: --------
* Matrix: the inverse of the matrix
"""
# ---------------------
def __invert__(self):
return Matrix(matrix=np.linalg.inv(self.matrix))
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/MatrixTest.py:test_inversion
--- OR ----
python3 -m nose -v ../test/MatrixTest.py:test_inversion
--- OR ----
python -m nose -v ../test/MatrixTest.py:test_inversion
---------------------------------------------------
"""
# ---------------------
"""
Define the identity based on the matrix's shape
---- Outputs: --------
* Matrix: the identity matrix
"""
# ---------------------
def identity(self):
return Matrix(matrix=np.eye(self.height))
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/MatrixTest.py:test_identity
--- OR ----
python3 -m nose -v ../test/MatrixTest.py:test_identity
--- OR ----
python -m nose -v ../test/MatrixTest.py:test_identity
---------------------------------------------------
"""
# ---------------------
"""
Obtain the transposed matrix of the original one
Transpose means flipping the matrix over the left diagonal
---- Outputs: --------
* Matrix: the transposed matrix
"""
# ---------------------
def transpose(self):
return Matrix(matrix=self.matrix.T)
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/MatrixTest.py:test_transpose
--- OR ----
python3 -m nose -v ../test/MatrixTest.py:test_transpose
--- OR ----
python -m nose -v ../test/MatrixTest.py:test_transpose
---------------------------------------------------
"""
# ---------------------
"""
Obtain the determinant of the matrix
It is used to determine whether this matrix has an inversion
---- Outputs: --------
* result: a scalar, the determinant
"""
# ---------------------
def determinant(self):
return np.linalg.det(self.matrix)
# -----------------
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/MatrixTest.py:test_deter
--- OR ----
python3 -m nose -v ../test/MatrixTest.py:test_deter
--- OR ----
python -m nose -v ../test/MatrixTest.py:test_deter
---------------------------------------------------
"""
# ---------------------
"""
Translation matrix helps to transform a point to a desired location
However, it does not work for vectors
Inverse of the translation matrix means working on the opposite direction
translation is a static method
---- Inputs: --------
* x: the amount wants to transform on x-axis
* y: the amount wants to transform on y-axis
* z: the amount wants to transform on z-axis
---- Outputs: --------
* Matrix: the translation matrix
"""
# ---------------------
@staticmethod
def translation(x: float, y: float, z: float):
m = np.eye(4)
m[0, 3] = x
m[1, 3] = y
m[2, 3] = z
return Matrix(matrix=m)
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/MatrixTest.py:test_translation
--- OR ----
python3 -m nose -v ../test/MatrixTest.py:test_translation
--- OR ----
python -m nose -v ../test/MatrixTest.py:test_translation
---------------------------------------------------
"""
# ---------------------
"""
Scale matrix helps to transform the size of an object
Inverse of the scaling matrix means scaling by the inverse of the input
scaling is a static method
---- Inputs: --------
* x: the amount wants to be scaled on x-axis
* y: the amount wants to be scaled on y-axis
* z: the amount wants to be scaled on z-axis
---- Outputs: --------
* Matrix: the scaling matrix
"""
# ---------------------
@staticmethod
def scaling(x: float, y: float, z: float):
m = np.eye(4)
m[0, 0] = x
m[1, 1] = y
m[2, 2] = z
return Matrix(matrix=m)
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/MatrixTest.py:test_scaling
--- OR ----
python3 -m nose -v ../test/MatrixTest.py:test_scaling
--- OR ----
python -m nose -v ../test/MatrixTest.py:test_scaling
---------------------------------------------------
"""
# ---------------------
"""
RotateX matrix helps to rotate the object according to x-axis
Inverse of the matrix means rotating at an opposite direction
rotateX is a static method
---- Inputs: --------
* angle: the rotate angle in radian
---- Outputs: --------
* Matrix: the rotation matrix
"""
# ---------------------
@staticmethod
def rotateX(theta: float):
m = np.eye(4)
m[1, 1] = math.cos(theta)
m[1, 2] = -math.sin(theta)
m[2, 1] = math.sin(theta)
m[2, 2] = math.cos(theta)
return Matrix(matrix=m)
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/MatrixTest.py:test_rotateX
--- OR ----
python3 -m nose -v ../test/MatrixTest.py:test_rotateX
--- OR ----
python -m nose -v ../test/MatrixTest.py:test_rotateX
---------------------------------------------------
"""
# ---------------------
"""
RotateY matrix helps to rotate the object according to y-axis
Inverse of the matrix means rotating at an opposite direction
rotateY is a static method
---- Inputs: --------
* angle: the rotate angle in radian
---- Outputs: --------
* Matrix: the rotation matrix
"""
# ---------------------
@staticmethod
def rotateY(theta: float):
m = np.eye(4)
m[0, 0] = math.cos(theta)
m[0, 2] = math.sin(theta)
m[2, 0] = -math.sin(theta)
m[2, 2] = math.cos(theta)
return Matrix(matrix=m)
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/MatrixTest.py:test_rotateY
--- OR ----
python3 -m nose -v ../test/MatrixTest.py:test_rotateY
--- OR ----
python -m nose -v ../test/MatrixTest.py:test_rotateY
---------------------------------------------------
"""
# ---------------------
"""
RotateZ matrix helps to rotate the object according to z-axis
Inverse of the matrix means rotating at an opposite direction
rotateZ is a static method
---- Inputs: --------
* angle: the rotate angle in radian
---- Outputs: --------
* Matrix: the rotation matrix
"""
# ---------------------
@staticmethod
def rotateZ(theta: float):
m = np.eye(4)
m[0, 0] = math.cos(theta)
m[0, 1] = -math.sin(theta)
m[1, 0] = math.sin(theta)
m[1, 1] = math.cos(theta)
return Matrix(matrix=m)
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/MatrixTest.py:test_rotateY
--- OR ----
python3 -m nose -v ../test/MatrixTest.py:test_rotateY
--- OR ----
python -m nose -v ../test/MatrixTest.py:test_rotateY
---------------------------------------------------
"""
# ---------------------
"""
Shearing matrix helps to slant a straight line.
X-coordinates would change in proportion to Y-axis and Z-axis,
Y-coordinates changes in proportion to X-axis and Z-axis,
Z-coordinates changes in proportion to X-axis and Y-axis.
Inverse of the matrix means shifting the line on an opposite direction
shearing is a static method
---- Inputs: --------
* xy: a float, the change of X-coordinates in proportion to Y-axis
* xz: a float, the change of X-coordinates in proportion to Z-axis
* yx: a float, the change of Y-coordinates in proportion to X-axis
* yz: a float, the change of Y-coordinates in proportion to Z-axis
* zx: a float, the change of Z-coordinates in proportion to X-axis
* zy: a float, the change of Z-coordinates in proportion to Y-axis
---- Outputs: --------
* Matrix: the rotation matrix
"""
# ---------------------
@staticmethod
def shearing(xy: float, xz: float, yx: float, yz: float, zx: float, zy: float):
m = np.eye(4)
m[0, 1] = xy
m[0, 2] = xz
m[1, 0] = yx
m[1, 2] = yz
m[2, 0] = zx
m[2, 1] = zy
return Matrix(matrix=m)
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/MatrixTest.py:test_shearing
--- OR ----
python3 -m nose -v ../test/MatrixTest.py:test_shearing
--- OR ----
python -m nose -v ../test/MatrixTest.py:test_shearing
---------------------------------------------------
"""
# ---------------------
"""
View transformation matrix helps to transform the camera
Inverse of the view transform matrix means undo the transformation on the camera
viewTransformation is a static method
---- Inputs: --------
* fromV: a Point, indicating where the eye is in the scene
* toV: a Point, indicating the direction the eye is looking at the scene
* upV: a Vector, indicating which direction is up in the scene
---- Outputs: --------
* Matrix: the view transformation matrix
"""
# ---------------------
@staticmethod
def viewTransformation(fromV: "Tuple", toV: "Tuple", upV: "Tuple"):
forward = (toV-fromV).normalize()
upn = upV.normalize()
left = forward.cross(upn)
trueUp = left.cross(forward)
orientation = Matrix(matrix=np.array([
[left.x, left.y, left.z, 0],
[trueUp.x, trueUp.y, trueUp.z, 0],
[-forward.x, -forward.y, -forward.z, 0],
[0, 0, 0, 1]
]))
return orientation*Matrix.translation(-fromV.x, -fromV.y, -fromV.z)
"""
Make sure you are on ~/src
---------------------------------------------------
nosetests -v ../test/MatrixTest.py:test_viewTransformation
--- OR ----
python3 -m nose -v ../test/MatrixTest.py:test_viewTransformation
--- OR ----
python -m nose -v ../test/MatrixTest.py:test_viewTransformation
---------------------------------------------------
"""
| 3dRenderPy | /3dRenderPy-0.0.5.tar.gz/3dRenderPy-0.0.5/src/RenderPy/Matrix.py | Matrix.py |
# 3debt
Try to figure out what dependencies you're missing to start upgrading your project to Python 3
## Installation
pip install -g 3debt
## Usage
3debt requirements.txt
| 3debt | /3debt-0.0.6.tar.gz/3debt-0.0.6/README.rst | README.rst |
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='3debt',
version='0.0.6',
description='Python 3 dependency checker',
long_description=long_description,
url='https://github.com/akoskaaa/3debt',
author='Akos Hochrein',
author_email='hoch.akos@gmail.com',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Software Development :: Build Tools',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
],
packages=find_packages(exclude=['contrib', 'docs', 'tests', 'scripts']),
install_requires=[
'argparse',
'requests'
],
entry_points={
'console_scripts': [
'3debt=src:run',
],
},
)
| 3debt | /3debt-0.0.6.tar.gz/3debt-0.0.6/setup.py | setup.py |
import requests
def is_ok_on_pypi(package_name, package_version=None):
response = requests.get('https://pypi.python.org/pypi/{package_name}/{package_version}'.format(
package_name=package_name,
package_version='' if package_version is None else package_version
))
return 'Python :: 3' in response.content
| 3debt | /3debt-0.0.6.tar.gz/3debt-0.0.6/src/evaluators.py | evaluators.py |
from evaluators import is_ok_on_pypi
class DependencyParser(object):
def __init__(self, ignored_prefixes=None, verbose=False):
self.ignored_prefixes = ignored_prefixes
self.verbose = verbose
def parse_file(self, filename):
with open(filename, 'r') as f:
for line in f.readlines():
self.parse_line(line.strip())
def parse_line(self, line):
if not len(line) or line.startswith('#'):
return
if any([line.startswith(prefix) for prefix in self.ignored_prefixes]):
return
package_info = line.split('==')
package_name = package_info[0]
package_version = package_info[1] if 2 == len(package_info) else None
pypi_looks_good = is_ok_on_pypi(package_name, package_version)
if not pypi_looks_good or self.verbose:
print('{indicator}-{package_name}@{package_version}'.format(
indicator='OK' if pypi_looks_good else 'NO',
package_name=package_name,
package_version=package_version
))
| 3debt | /3debt-0.0.6.tar.gz/3debt-0.0.6/src/parser.py | parser.py |
import argparse
from parser import DependencyParser
argument_parser = argparse.ArgumentParser(description="""
Get information if your dependent packages are Python 3 compatible yet
""".strip())
argument_parser.add_argument('-v', '--verbose',
help="Display information about all packages in the requirements file",
action='store_true', default=False
)
argument_parser.add_argument('--ignore',
help="Prefixes of packages that you\'d like to ignore while parsing the file",
nargs='*', default=[]
)
argument_parser.add_argument('filename',
help="Name of the file that contains the dependencies",
)
def run():
args = argument_parser.parse_args()
dependency_parser = DependencyParser(args.ignore, args.verbose)
dependency_parser.parse_file(args.filename)
| 3debt | /3debt-0.0.6.tar.gz/3debt-0.0.6/src/__init__.py | __init__.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.