unityripper 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,293 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+ from typing import Any, Sequence
5
+
6
+ from ..materials import MaterialData, TextureBinding
7
+ from ..mathutil import Mat4, IDENTITY, det3, scale_matrix, transform_normal, transform_point
8
+ from ..scene import MeshAsset, MeshData, RendererModel
9
+ from ..textures import TextureStore
10
+ from ..util import format_size, log, sanitize_filename
11
+ from .common import (
12
+ ExportOptions,
13
+ compute_normals,
14
+ flatten_triangles,
15
+ material_key,
16
+ material_stem,
17
+ needs_winding_reverse,
18
+ renderer_stem,
19
+ srgb_tuple,
20
+ texture_relpath,
21
+ usable_normals,
22
+ )
23
+
24
+ Float = float
25
+
26
+ class ObjExporter:
27
+ def __init__(self, output_dir: Path, textures: TextureStore, options: ExportOptions):
28
+ self.output_dir = output_dir
29
+ self.obj_dir = output_dir / "obj"
30
+ self.textures = textures
31
+ self.options = options
32
+
33
+ def _texture_path(self, binding: TextureBinding | None, hint: str, role: str, from_dir: Path) -> str | None:
34
+ if binding is None or binding.texture is None:
35
+ return None
36
+ asset = self.textures.save(binding.texture, hint=hint, role=role)
37
+ if asset is None:
38
+ return None
39
+ return texture_relpath(asset.file, from_dir)
40
+
41
+ def _write_material_block(self, lines: list[str], name: str, material: MaterialData, from_dir: Path) -> None:
42
+ lines.append(f"newmtl {name}\n")
43
+ r, g, b = srgb_tuple(material.base_color)
44
+ lines.append(f"Kd {r:.6f} {g:.6f} {b:.6f}\n")
45
+ alpha = 1.0 if material.alpha_mode == "OPAQUE" else material.base_color[3]
46
+ lines.append(f"d {alpha:.6f}\n")
47
+ spec = max(0.0, min(1.0, 1.0 - material.roughness))
48
+ lines.append(f"Ns {spec * 900.0 + 10.0:.1f}\n")
49
+ lines.append("illum 2\n")
50
+ if material.emission_color and max(material.emission_color) > 0.001:
51
+ er, eg, eb = srgb_tuple(material.emission_color)
52
+ lines.append(f"Ke {er:.6f} {eg:.6f} {eb:.6f}\n")
53
+
54
+ hint = material.name or "material"
55
+ albedo = self._texture_path(material.albedo, f"{hint}_albedo", "albedo", from_dir)
56
+ if albedo:
57
+ scale = material.albedo.scale
58
+ offset = material.albedo.offset
59
+ options = ""
60
+ if scale != (1.0, 1.0) or offset != (0.0, 0.0):
61
+ options = f"-s {scale[0]:.6f} {scale[1]:.6f} -o {offset[0]:.6f} {offset[1]:.6f} "
62
+ lines.append(f"map_Kd {options}{albedo}\n")
63
+
64
+ normal = self._texture_path(material.normal, f"{hint}_normal", "normal", from_dir)
65
+ if normal:
66
+ lines.append(f"map_Bump {normal}\n")
67
+
68
+ emission = self._texture_path(material.emission_map, f"{hint}_emission", "albedo", from_dir)
69
+ if emission:
70
+ lines.append(f"map_Ke {emission}\n")
71
+ lines.append("\n")
72
+
73
+ def _write_mtl(self, mtl_path: Path, materials: Sequence[MaterialData], prefix: str) -> list[str]:
74
+ lines: list[str] = [f"# UnityModelRipper\n"]
75
+ names: list[str] = []
76
+ used: set[str] = set()
77
+ for i, material in enumerate(materials):
78
+ name = material_stem(i, material, prefix)
79
+ base = name
80
+ n = 2
81
+ while name in used:
82
+ name = f"{base}_{n}"
83
+ n += 1
84
+ used.add(name)
85
+ names.append(name)
86
+ self._write_material_block(lines, name, material, mtl_path.parent)
87
+ mtl_path.write_text("".join(lines), encoding="utf-8")
88
+ return names
89
+
90
+ def _write_geometry(
91
+ self,
92
+ lines: list[str],
93
+ mesh: MeshData,
94
+ materials: Sequence[MaterialData],
95
+ material_names: Sequence[str] | None,
96
+ world: Mat4,
97
+ vertex_offset: int,
98
+ uv_offset: int,
99
+ normal_offset: int,
100
+ group_name: str,
101
+ ) -> tuple[int, int, int]:
102
+ positions = [transform_point(world, v) for v in mesh.vertices]
103
+ if self.options.mirror_x:
104
+ positions = [(-p[0], p[1], p[2]) for p in positions]
105
+ if self.options.scale != 1.0:
106
+ s = self.options.scale
107
+ positions = [(p[0] * s, p[1] * s, p[2] * s) for p in positions]
108
+
109
+ normals = usable_normals(mesh)
110
+ if normals is not None:
111
+ normals = [transform_normal(world, n) for n in normals]
112
+ if self.options.mirror_x:
113
+ normals = [(-n[0], n[1], n[2]) for n in normals]
114
+ else:
115
+ normals = compute_normals(mesh.vertices, flatten_triangles(mesh))
116
+ normals = [transform_normal(world, n) for n in normals]
117
+ if self.options.mirror_x:
118
+ normals = [(-n[0], n[1], n[2]) for n in normals]
119
+
120
+ uvs = mesh.uvs
121
+ lines.extend(f"v {p[0]:.6f} {p[1]:.6f} {p[2]:.6f}\n" for p in positions)
122
+ if uvs:
123
+ lines.extend(f"vt {uv[0]:.6f} {uv[1]:.6f}\n" for uv in uvs)
124
+ lines.extend(f"vn {n[0]:.6f} {n[1]:.6f} {n[2]:.6f}\n" for n in normals)
125
+
126
+ reverse = needs_winding_reverse(det3(world), self.options.mirror_x)
127
+ for sub_index, tris in enumerate(mesh.triangles):
128
+ if not tris:
129
+ continue
130
+ suffix = f"_{sub_index}" if len(mesh.triangles) > 1 else ""
131
+ lines.append(f"g {group_name}{suffix}\n")
132
+ if material_names:
133
+ mat_index = min(sub_index, len(material_names) - 1)
134
+ lines.append(f"usemtl {material_names[mat_index]}\n")
135
+ for tri in tris:
136
+ a, b, c = tri
137
+ if reverse:
138
+ b, c = c, b
139
+ va = vertex_offset + a + 1
140
+ vb = vertex_offset + b + 1
141
+ vc = vertex_offset + c + 1
142
+ if uvs:
143
+ ta = uv_offset + a + 1
144
+ tb = uv_offset + b + 1
145
+ tc = uv_offset + c + 1
146
+ if normals:
147
+ na = normal_offset + a + 1
148
+ nb = normal_offset + b + 1
149
+ nc = normal_offset + c + 1
150
+ lines.append(f"f {va}/{ta}/{na} {vb}/{tb}/{nb} {vc}/{tc}/{nc}\n")
151
+ else:
152
+ lines.append(f"f {va}/{ta} {vb}/{tb} {vc}/{tc}\n")
153
+ elif normals:
154
+ na = normal_offset + a + 1
155
+ nb = normal_offset + b + 1
156
+ nc = normal_offset + c + 1
157
+ lines.append(f"f {va}//{na} {vb}//{nb} {vc}//{nc}\n")
158
+ else:
159
+ lines.append(f"f {va} {vb} {vc}\n")
160
+ return len(positions), (len(uvs) if uvs else 0), len(normals)
161
+
162
+ def export_assets(self, assets: Sequence[MeshAsset]) -> list[tuple[str, Path]]:
163
+ self.obj_dir.mkdir(parents=True, exist_ok=True)
164
+ written: list[tuple[str, Path]] = []
165
+ used: set[str] = set()
166
+ for asset in assets:
167
+ stem = sanitize_filename(asset.name, "model")
168
+ candidate = stem
169
+ n = 2
170
+ while candidate.lower() in used:
171
+ candidate = f"{stem}_{n}"
172
+ n += 1
173
+ used.add(candidate.lower())
174
+ try:
175
+ written.append((asset.name, self._export_asset(asset, candidate)))
176
+ except Exception as exc:
177
+ log.warning("OBJ export failed for %s: %s: %s", asset.name, type(exc).__name__, exc)
178
+ return written
179
+
180
+ def _export_asset(self, asset: MeshAsset, stem: str) -> Path:
181
+ mesh = asset.mesh
182
+ materials = list(asset.materials) or [MaterialData(key=None, name="Default")]
183
+ obj_path = self.obj_dir / f"{stem}.obj"
184
+ mtl_path = obj_path.with_suffix(".mtl")
185
+
186
+ lines = [f"# UnityModelRipper - {asset.name}\n", f"# mesh: {mesh.name}\n"]
187
+ material_names: list[str] | None = None
188
+ if materials:
189
+ material_names = self._write_mtl(mtl_path, materials, prefix="m")
190
+ lines.append(f"mtllib {mtl_path.name}\n")
191
+
192
+ self._write_geometry(
193
+ lines,
194
+ mesh,
195
+ materials,
196
+ material_names,
197
+ asset.matrix if asset.matrix != IDENTITY else scale_matrix(asset.scale),
198
+ 0,
199
+ 0,
200
+ 0,
201
+ sanitize_filename(mesh.name or asset.name, "model"),
202
+ )
203
+ obj_path.write_text("".join(lines), encoding="utf-8")
204
+ log.info("OBJ %s (%s)", obj_path.name, format_size(obj_path.stat().st_size))
205
+ return obj_path
206
+
207
+ def export_scene(self, models: Sequence[RendererModel], name: str = "scene") -> Path:
208
+ self.obj_dir.mkdir(parents=True, exist_ok=True)
209
+ obj_path = self.obj_dir / f"{sanitize_filename(name, 'scene')}.obj"
210
+ mtl_path = obj_path.with_suffix(".mtl")
211
+
212
+ materials: list[MaterialData] = []
213
+ material_names: list[str] = []
214
+ material_index: dict[tuple, int] = {}
215
+ for model in models:
216
+ for material in model.materials:
217
+ key = material_key(material)
218
+ if key not in material_index:
219
+ material_index[key] = len(materials)
220
+ materials.append(material)
221
+
222
+ if materials:
223
+ material_names = self._write_mtl(mtl_path, materials, prefix="mat")
224
+ lines = [f"# UnityModelRipper - {name}\n"]
225
+ if materials:
226
+ lines.append(f"mtllib {mtl_path.name}\n")
227
+
228
+ vertex_offset = uv_offset = normal_offset = 0
229
+ for model in models:
230
+ if model.mesh is None:
231
+ continue
232
+ sub_names = []
233
+ for material in model.materials:
234
+ idx = material_index.get(material_key(material), 0)
235
+ sub_names.append(material_names[idx] if material_names else "")
236
+ before_v, before_uv, before_n = vertex_offset, uv_offset, normal_offset
237
+ dv, du, dn = self._write_geometry(
238
+ lines,
239
+ model.mesh,
240
+ model.materials,
241
+ sub_names,
242
+ model.world,
243
+ vertex_offset,
244
+ uv_offset,
245
+ normal_offset,
246
+ sanitize_filename(model.path or model.name, "object"),
247
+ )
248
+ vertex_offset += dv
249
+ uv_offset += du
250
+ normal_offset += dn
251
+ if (vertex_offset, uv_offset, normal_offset) == (before_v, before_uv, before_n):
252
+ continue
253
+
254
+ obj_path.write_text("".join(lines), encoding="utf-8")
255
+ log.info("OBJ scene %s (%s)", obj_path.name, format_size(obj_path.stat().st_size))
256
+ return obj_path
257
+
258
+ def export_scene_split(self, models: Sequence[RendererModel]) -> list[tuple[RendererModel, Path]]:
259
+ self.obj_dir.mkdir(parents=True, exist_ok=True)
260
+ written: list[tuple[RendererModel, Path]] = []
261
+ used: set[str] = set()
262
+ for model in models:
263
+ if model.mesh is None:
264
+ continue
265
+ stem = renderer_stem(model)
266
+ candidate = stem
267
+ n = 2
268
+ while candidate.lower() in used:
269
+ candidate = f"{stem}_{n}"
270
+ n += 1
271
+ used.add(candidate.lower())
272
+
273
+ materials = list(model.materials) or [MaterialData(key=None, name="Default")]
274
+ obj_path = self.obj_dir / f"{candidate}.obj"
275
+ mtl_path = obj_path.with_suffix(".mtl")
276
+ lines = [f"# UnityModelRipper - {model.path or model.name}\n", f"# mesh: {model.mesh.name}\n"]
277
+ material_names = self._write_mtl(mtl_path, materials, prefix="m")
278
+ lines.append(f"mtllib {mtl_path.name}\n")
279
+ self._write_geometry(
280
+ lines,
281
+ model.mesh,
282
+ materials,
283
+ material_names,
284
+ model.world,
285
+ 0,
286
+ 0,
287
+ 0,
288
+ sanitize_filename(model.path or model.name or model.mesh.name, "object"),
289
+ )
290
+ obj_path.write_text("".join(lines), encoding="utf-8")
291
+ written.append((model, obj_path))
292
+ log.info("OBJ scene split into %d file(s)", len(written))
293
+ return written
@@ -0,0 +1,230 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from typing import Any
5
+
6
+ from .util import log, object_identity
7
+
8
+ ALBEDO_SLOTS = (
9
+ "_BaseMap", "_MainTex", "_AlbedoMap", "_Albedo", "_Diffuse", "_DiffuseMap",
10
+ "_BaseColorMap", "_Atlas", "_Tex", "_Texture", "_MainTexture",
11
+ )
12
+ NORMAL_SLOTS = ("_BumpMap", "_NormalMap", "_NormalTex", "_DetailNormalMap")
13
+ METALLIC_SLOTS = ("_MetallicGlossMap", "_MetallicMap", "_MaskMap", "_SpecGlossMap")
14
+ OCCLUSION_SLOTS = ("_OcclusionMap", "_Occlusion", "_AO")
15
+ EMISSION_SLOTS = ("_EmissionMap", "_EmissiveMap", "_Emission")
16
+ COLOR_SLOTS = ("_BaseColor", "_Color", "_TintColor", "_MainColor", "_AlbedoColor", "_Tint")
17
+ METALLIC_FLOATS = ("_Metallic",)
18
+ SMOOTHNESS_FLOATS = ("_Glossiness", "_Smoothness")
19
+ ROUGHNESS_FLOATS = ("_Roughness",)
20
+
21
+ @dataclass
22
+ class TextureBinding:
23
+ slot: str
24
+ texture: Any
25
+ scale: tuple[float, float] = (1.0, 1.0)
26
+ offset: tuple[float, float] = (0.0, 0.0)
27
+
28
+ @dataclass
29
+ class MaterialData:
30
+ key: tuple[str, int] | None
31
+ name: str
32
+ shader: str = ""
33
+ albedo: TextureBinding | None = None
34
+ normal: TextureBinding | None = None
35
+ metallic_map: TextureBinding | None = None
36
+ occlusion: TextureBinding | None = None
37
+ emission_map: TextureBinding | None = None
38
+ base_color: tuple[float, float, float, float] = (1.0, 1.0, 1.0, 1.0)
39
+ emission_color: tuple[float, float, float] = (0.0, 0.0, 0.0)
40
+ metallic: float = 0.0
41
+ roughness: float = 0.5
42
+ alpha_mode: str = "OPAQUE"
43
+ alpha_cutoff: float = 0.5
44
+ double_sided: bool = False
45
+ unlit: bool = False
46
+ render_queue: int = 0
47
+ floats: dict[str, float] = field(default_factory=dict)
48
+ colors: dict[str, tuple[float, float, float, float]] = field(default_factory=dict)
49
+
50
+ @property
51
+ def has_albedo(self) -> bool:
52
+ return self.albedo is not None and self.albedo.texture is not None
53
+
54
+ def _pairs(value: Any):
55
+ if not value:
56
+ return
57
+ if isinstance(value, dict):
58
+ yield from value.items()
59
+ return
60
+ for item in value:
61
+ try:
62
+ if isinstance(item, (tuple, list)) and len(item) == 2:
63
+ yield item[0], item[1]
64
+ else:
65
+ yield item[0], item[1]
66
+ except Exception:
67
+ continue
68
+
69
+ def _as_float(value: Any, default: float = 0.0) -> float:
70
+ try:
71
+ return float(value)
72
+ except Exception:
73
+ return default
74
+
75
+ def _color_tuple(value: Any) -> tuple[float, float, float, float]:
76
+ try:
77
+ return (float(value.r), float(value.g), float(value.b), float(value.a))
78
+ except Exception:
79
+ pass
80
+ try:
81
+ packed = int(value.rgba)
82
+ return (
83
+ ((packed >> 24) & 0xFF) / 255.0,
84
+ ((packed >> 16) & 0xFF) / 255.0,
85
+ ((packed >> 8) & 0xFF) / 255.0,
86
+ (packed & 0xFF) / 255.0,
87
+ )
88
+ except Exception:
89
+ return (1.0, 1.0, 1.0, 1.0)
90
+
91
+ def _texture_binding(value: Any, slot: str) -> TextureBinding | None:
92
+ texture = getattr(value, "m_Texture", None)
93
+ if texture is None or not getattr(texture, "m_PathID", 0):
94
+ return None
95
+ scale = getattr(value, "m_Scale", None)
96
+ offset = getattr(value, "m_Offset", None)
97
+ sx = _as_float(getattr(scale, "x", 1.0), 1.0)
98
+ sy = _as_float(getattr(scale, "y", 1.0), 1.0)
99
+ ox = _as_float(getattr(offset, "x", 0.0), 0.0)
100
+ oy = _as_float(getattr(offset, "y", 0.0), 0.0)
101
+ return TextureBinding(slot=slot, texture=texture, scale=(sx, sy), offset=(ox, oy))
102
+
103
+ def _pick(mapping: dict[str, Any], names: tuple[str, ...]) -> tuple[str, Any] | None:
104
+ lowered = {k.lower(): (k, v) for k, v in mapping.items()}
105
+ for name in names:
106
+ hit = lowered.get(name.lower())
107
+ if hit is not None:
108
+ return hit
109
+ return None
110
+
111
+ def _shader_name(material: Any) -> str:
112
+ shader_ptr = getattr(material, "m_Shader", None)
113
+ if shader_ptr is None or not getattr(shader_ptr, "m_PathID", 0):
114
+ return ""
115
+ try:
116
+ shader = shader_ptr.read()
117
+ parsed = getattr(shader, "m_ParsedForm", None)
118
+ return str(getattr(parsed, "m_Name", "") or getattr(shader, "m_Name", "") or "")
119
+ except Exception:
120
+ return ""
121
+
122
+ def read_material(obj: Any, base_path: str | None = None) -> MaterialData:
123
+ material = obj.read()
124
+ name = str(getattr(material, "m_Name", "material") or "material")
125
+ props = getattr(material, "m_SavedProperties", None)
126
+ texenvs: dict[str, Any] = {}
127
+ floats: dict[str, float] = {}
128
+ colors: dict[str, tuple[float, float, float, float]] = {}
129
+
130
+ if props is not None:
131
+ for slot, value in _pairs(getattr(props, "m_TexEnvs", None)):
132
+ if value is not None:
133
+ texenvs[str(slot)] = value
134
+ for key, value in _pairs(getattr(props, "m_Floats", None)):
135
+ floats[str(key)] = _as_float(value)
136
+ for key, value in _pairs(getattr(props, "m_Colors", None)):
137
+ colors[str(key)] = _color_tuple(value)
138
+
139
+ shader = _shader_name(material)
140
+
141
+ def tex(names: tuple[str, ...]) -> TextureBinding | None:
142
+ hit = _pick(texenvs, names)
143
+ if hit is None:
144
+ return None
145
+ slot, value = hit
146
+ return _texture_binding(value, slot)
147
+
148
+ albedo = tex(ALBEDO_SLOTS)
149
+ normal = tex(NORMAL_SLOTS)
150
+ metallic_map = tex(METALLIC_SLOTS)
151
+ occlusion = tex(OCCLUSION_SLOTS)
152
+ emission_map = tex(EMISSION_SLOTS)
153
+
154
+ base_color = (1.0, 1.0, 1.0, 1.0)
155
+ color_hit = _pick(colors, COLOR_SLOTS)
156
+ if color_hit is not None:
157
+ base_color = color_hit[1]
158
+
159
+ emission = (0.0, 0.0, 0.0)
160
+ emission_hit = _pick(colors, ("_EmissionColor", "_EmissiveColor"))
161
+ if emission_hit is not None:
162
+ emission = emission_hit[1][:3]
163
+
164
+ metallic = 0.0
165
+ metallic_hit = _pick(floats, METALLIC_FLOATS)
166
+ if metallic_hit is not None:
167
+ metallic = max(0.0, min(1.0, metallic_hit[1]))
168
+
169
+ roughness = 0.5
170
+ roughness_hit = _pick(floats, ROUGHNESS_FLOATS)
171
+ if roughness_hit is not None:
172
+ roughness = max(0.0, min(1.0, roughness_hit[1]))
173
+ else:
174
+ smoothness_hit = _pick(floats, SMOOTHNESS_FLOATS)
175
+ if smoothness_hit is not None:
176
+ roughness = max(0.0, min(1.0, 1.0 - smoothness_hit[1]))
177
+
178
+ alpha_mode = "OPAQUE"
179
+ cutoff = 0.5
180
+ mode_hit = _pick(floats, ("_Mode",))
181
+ alpha_clip_hit = _pick(floats, ("_AlphaClip",))
182
+ surface_hit = _pick(floats, ("_Surface",))
183
+ cull_hit = _pick(floats, ("_Cull",))
184
+ cutoff_hit = _pick(floats, ("_Cutoff", "_AlphaCutoff"))
185
+ if cutoff_hit is not None:
186
+ cutoff = max(0.0, min(1.0, cutoff_hit[1]))
187
+
188
+ mode = int(mode_hit[1]) if mode_hit is not None else None
189
+ if mode_hit is not None and mode in (2, 3):
190
+ alpha_mode = "BLEND"
191
+ elif alpha_clip_hit is not None and alpha_clip_hit[1] >= 0.5:
192
+ alpha_mode = "MASK"
193
+ elif surface_hit is not None and int(surface_hit[1]) == 1:
194
+ alpha_mode = "BLEND"
195
+ elif mode_hit is not None and mode == 1:
196
+ alpha_mode = "MASK"
197
+
198
+ render_queue = int(_as_float(getattr(material, "m_CustomRenderQueue", 0)))
199
+ if alpha_mode == "OPAQUE" and render_queue >= 3000:
200
+ alpha_mode = "BLEND"
201
+ elif alpha_mode == "OPAQUE" and 2450 <= render_queue < 3000:
202
+ alpha_mode = "MASK"
203
+
204
+ double_sided = cull_hit is not None and int(cull_hit[1]) == 0
205
+ shader_lower = shader.lower()
206
+ unlit = "unlit" in shader_lower or "sprite" in shader_lower or shader_lower.startswith("ui/")
207
+
208
+ data = MaterialData(
209
+ key=object_identity(obj, base_path),
210
+ name=name,
211
+ shader=shader,
212
+ albedo=albedo,
213
+ normal=normal,
214
+ metallic_map=metallic_map,
215
+ occlusion=occlusion,
216
+ emission_map=emission_map,
217
+ base_color=base_color,
218
+ emission_color=emission,
219
+ metallic=metallic,
220
+ roughness=roughness,
221
+ alpha_mode=alpha_mode,
222
+ alpha_cutoff=cutoff,
223
+ double_sided=double_sided,
224
+ unlit=unlit,
225
+ render_queue=render_queue,
226
+ floats=floats,
227
+ colors=colors,
228
+ )
229
+ log.debug("material %s shader=%s", name, shader)
230
+ return data
@@ -0,0 +1,133 @@
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ from typing import Iterable, Sequence
5
+
6
+ Vec2 = tuple[float, float]
7
+ Vec3 = tuple[float, float, float]
8
+ Vec4 = tuple[float, float, float, float]
9
+ Mat4 = tuple[float, ...]
10
+ Mat3 = tuple[float, ...]
11
+
12
+ IDENTITY: Mat4 = (1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0)
13
+
14
+ def scale_matrix(scale: float) -> Mat4:
15
+ return (scale, 0.0, 0.0, 0.0, 0.0, scale, 0.0, 0.0, 0.0, 0.0, scale, 0.0, 0.0, 0.0, 0.0, 1.0)
16
+
17
+ def quat_to_mat3(x: float, y: float, z: float, w: float) -> Mat3:
18
+ xx, yy, zz = x * x, y * y, z * z
19
+ xy, xz, yz = x * y, x * z, y * z
20
+ wx, wy, wz = w * x, w * y, w * z
21
+ return (
22
+ 1.0 - 2.0 * (yy + zz), 2.0 * (xy - wz), 2.0 * (xz + wy),
23
+ 2.0 * (xy + wz), 1.0 - 2.0 * (xx + zz), 2.0 * (yz - wx),
24
+ 2.0 * (xz - wy), 2.0 * (yz + wx), 1.0 - 2.0 * (xx + yy),
25
+ )
26
+
27
+ def trs_matrix(position: Sequence[float], rotation: Sequence[float], scale: Sequence[float]) -> Mat4:
28
+ px, py, pz = float(position[0]), float(position[1]), float(position[2])
29
+ qx, qy, qz, qw = (float(rotation[0]), float(rotation[1]), float(rotation[2]), float(rotation[3]))
30
+ sx, sy, sz = float(scale[0]), float(scale[1]), float(scale[2])
31
+ r = quat_to_mat3(qx, qy, qz, qw)
32
+ return (
33
+ r[0] * sx, r[1] * sy, r[2] * sz, px,
34
+ r[3] * sx, r[4] * sy, r[5] * sz, py,
35
+ r[6] * sx, r[7] * sy, r[8] * sz, pz,
36
+ 0.0, 0.0, 0.0, 1.0,
37
+ )
38
+
39
+ def mat_mul(a: Mat4, b: Mat4) -> Mat4:
40
+ return (
41
+ a[0] * b[0] + a[1] * b[4] + a[2] * b[8] + a[3] * b[12],
42
+ a[0] * b[1] + a[1] * b[5] + a[2] * b[9] + a[3] * b[13],
43
+ a[0] * b[2] + a[1] * b[6] + a[2] * b[10] + a[3] * b[14],
44
+ a[0] * b[3] + a[1] * b[7] + a[2] * b[11] + a[3] * b[15],
45
+ a[4] * b[0] + a[5] * b[4] + a[6] * b[8] + a[7] * b[12],
46
+ a[4] * b[1] + a[5] * b[5] + a[6] * b[9] + a[7] * b[13],
47
+ a[4] * b[2] + a[5] * b[6] + a[6] * b[10] + a[7] * b[14],
48
+ a[4] * b[3] + a[5] * b[7] + a[6] * b[11] + a[7] * b[15],
49
+ a[8] * b[0] + a[9] * b[4] + a[10] * b[8] + a[11] * b[12],
50
+ a[8] * b[1] + a[9] * b[5] + a[10] * b[9] + a[11] * b[13],
51
+ a[8] * b[2] + a[9] * b[6] + a[10] * b[10] + a[11] * b[14],
52
+ a[8] * b[3] + a[9] * b[7] + a[10] * b[11] + a[11] * b[15],
53
+ a[12] * b[0] + a[13] * b[4] + a[14] * b[8] + a[15] * b[12],
54
+ a[12] * b[1] + a[13] * b[5] + a[14] * b[9] + a[15] * b[13],
55
+ a[12] * b[2] + a[13] * b[6] + a[14] * b[10] + a[15] * b[14],
56
+ a[12] * b[3] + a[13] * b[7] + a[14] * b[11] + a[15] * b[15],
57
+ )
58
+
59
+ def transform_point(m: Mat4, p: Sequence[float]) -> Vec3:
60
+ x, y, z = float(p[0]), float(p[1]), float(p[2])
61
+ return (
62
+ m[0] * x + m[1] * y + m[2] * z + m[3],
63
+ m[4] * x + m[5] * y + m[6] * z + m[7],
64
+ m[8] * x + m[9] * y + m[10] * z + m[11],
65
+ )
66
+
67
+ def transform_vector(m: Mat4, v: Sequence[float]) -> Vec3:
68
+ x, y, z = float(v[0]), float(v[1]), float(v[2])
69
+ return (
70
+ m[0] * x + m[1] * y + m[2] * z,
71
+ m[4] * x + m[5] * y + m[6] * z,
72
+ m[8] * x + m[9] * y + m[10] * z,
73
+ )
74
+
75
+ def det3(m: Mat4) -> float:
76
+ return (
77
+ m[0] * (m[5] * m[10] - m[6] * m[9])
78
+ - m[1] * (m[4] * m[10] - m[6] * m[8])
79
+ + m[2] * (m[4] * m[9] - m[5] * m[8])
80
+ )
81
+
82
+ def inverse_transpose3(m: Mat4) -> Mat3:
83
+ a, b, c = m[0], m[1], m[2]
84
+ d, e, f = m[4], m[5], m[6]
85
+ g, h, i = m[8], m[9], m[10]
86
+ det = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g)
87
+ if abs(det) < 1e-12:
88
+ return (1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0)
89
+ inv_det = 1.0 / det
90
+ return (
91
+ (e * i - f * h) * inv_det, (c * h - b * i) * inv_det, (b * f - c * e) * inv_det,
92
+ (f * g - d * i) * inv_det, (a * i - c * g) * inv_det, (c * d - a * f) * inv_det,
93
+ (d * h - e * g) * inv_det, (b * g - a * h) * inv_det, (a * e - b * d) * inv_det,
94
+ )
95
+
96
+ def transform_normal(m: Mat4, n: Sequence[float]) -> Vec3:
97
+ nm = inverse_transpose3(m)
98
+ x, y, z = float(n[0]), float(n[1]), float(n[2])
99
+ rx = nm[0] * x + nm[1] * y + nm[2] * z
100
+ ry = nm[3] * x + nm[4] * y + nm[5] * z
101
+ rz = nm[6] * x + nm[7] * y + nm[8] * z
102
+ length = math.sqrt(rx * rx + ry * ry + rz * rz)
103
+ if length < 1e-12:
104
+ return (0.0, 0.0, 0.0)
105
+ return (rx / length, ry / length, rz / length)
106
+
107
+ def normalize3(v: Sequence[float]) -> Vec3:
108
+ x, y, z = float(v[0]), float(v[1]), float(v[2])
109
+ length = math.sqrt(x * x + y * y + z * z)
110
+ if length < 1e-12:
111
+ return (0.0, 0.0, 0.0)
112
+ return (x / length, y / length, z / length)
113
+
114
+ def mirror_x_point(p: Sequence[float]) -> Vec3:
115
+ return (-float(p[0]), float(p[1]), float(p[2]))
116
+
117
+ def mirror_x_normal(n: Sequence[float]) -> Vec3:
118
+ return (-float(n[0]), float(n[1]), float(n[2]))
119
+
120
+ def matrix_from_unity(m: object) -> Mat4:
121
+ return tuple(float(getattr(m, f"e{r}{c}")) for r in range(4) for c in range(4))
122
+
123
+ def mat4_to_gltf(m: Mat4) -> list[float]:
124
+ return [m[0], m[4], m[8], m[12], m[1], m[5], m[9], m[13], m[2], m[6], m[10], m[14], m[3], m[7], m[11], m[15]]
125
+
126
+ def iter_floats(values: Iterable[float]) -> list[float]:
127
+ out: list[float] = []
128
+ for v in values:
129
+ f = float(v)
130
+ if not math.isfinite(f):
131
+ f = 0.0
132
+ out.append(f)
133
+ return out