py-materials 3.2.0__tar.gz → 3.3.0__tar.gz

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.
Files changed (59) hide show
  1. {py_materials-3.2.0 → py_materials-3.3.0}/PKG-INFO +1 -1
  2. {py_materials-3.2.0 → py_materials-3.3.0}/pyproject.toml +1 -1
  3. {py_materials-3.2.0 → py_materials-3.3.0}/src/pymat/__init__.py +3 -1
  4. py_materials-3.3.0/src/pymat/search.py +127 -0
  5. {py_materials-3.2.0 → py_materials-3.3.0}/src/pymat/vis/_model.py +38 -0
  6. py_materials-3.3.0/src/pymat/vis/adapters.py +123 -0
  7. py_materials-3.3.0/tests/test_adapters.py +318 -0
  8. {py_materials-3.2.0 → py_materials-3.3.0}/tests/test_e2e_vis.py +33 -0
  9. {py_materials-3.2.0 → py_materials-3.3.0}/tests/test_integration.py +102 -0
  10. py_materials-3.3.0/tests/test_search.py +278 -0
  11. {py_materials-3.2.0 → py_materials-3.3.0}/tests/test_vis.py +5 -2
  12. py_materials-3.2.0/src/pymat/vis/adapters.py +0 -91
  13. py_materials-3.2.0/tests/test_adapters.py +0 -159
  14. {py_materials-3.2.0 → py_materials-3.3.0}/.gitignore +0 -0
  15. {py_materials-3.2.0 → py_materials-3.3.0}/LICENSE +0 -0
  16. {py_materials-3.2.0 → py_materials-3.3.0}/README.md +0 -0
  17. {py_materials-3.2.0 → py_materials-3.3.0}/docs/catalog/README.md +0 -0
  18. {py_materials-3.2.0 → py_materials-3.3.0}/docs/catalog/ceramics/README.md +0 -0
  19. {py_materials-3.2.0 → py_materials-3.3.0}/docs/catalog/electronics/README.md +0 -0
  20. {py_materials-3.2.0 → py_materials-3.3.0}/docs/catalog/gases/README.md +0 -0
  21. {py_materials-3.2.0 → py_materials-3.3.0}/docs/catalog/liquids/README.md +0 -0
  22. {py_materials-3.2.0 → py_materials-3.3.0}/docs/catalog/metals/README.md +0 -0
  23. {py_materials-3.2.0 → py_materials-3.3.0}/docs/catalog/plastics/README.md +0 -0
  24. {py_materials-3.2.0 → py_materials-3.3.0}/docs/catalog/scintillators/README.md +0 -0
  25. {py_materials-3.2.0 → py_materials-3.3.0}/docs/decisions/README.md +0 -0
  26. {py_materials-3.2.0 → py_materials-3.3.0}/mat-rs/data/README.md +0 -0
  27. {py_materials-3.2.0 → py_materials-3.3.0}/src/pymat/core.py +0 -0
  28. {py_materials-3.2.0 → py_materials-3.3.0}/src/pymat/data/ceramics.toml +0 -0
  29. {py_materials-3.2.0 → py_materials-3.3.0}/src/pymat/data/electronics.toml +0 -0
  30. {py_materials-3.2.0 → py_materials-3.3.0}/src/pymat/data/gases.toml +0 -0
  31. {py_materials-3.2.0 → py_materials-3.3.0}/src/pymat/data/liquids.toml +0 -0
  32. {py_materials-3.2.0 → py_materials-3.3.0}/src/pymat/data/metals.toml +0 -0
  33. {py_materials-3.2.0 → py_materials-3.3.0}/src/pymat/data/plastics.toml +0 -0
  34. {py_materials-3.2.0 → py_materials-3.3.0}/src/pymat/data/scintillators.toml +0 -0
  35. {py_materials-3.2.0 → py_materials-3.3.0}/src/pymat/elements.py +0 -0
  36. {py_materials-3.2.0 → py_materials-3.3.0}/src/pymat/enrichers.py +0 -0
  37. {py_materials-3.2.0 → py_materials-3.3.0}/src/pymat/factories.py +0 -0
  38. {py_materials-3.2.0 → py_materials-3.3.0}/src/pymat/loader.py +0 -0
  39. {py_materials-3.2.0 → py_materials-3.3.0}/src/pymat/properties.py +0 -0
  40. {py_materials-3.2.0 → py_materials-3.3.0}/src/pymat/registry.py +0 -0
  41. {py_materials-3.2.0 → py_materials-3.3.0}/src/pymat/units.py +0 -0
  42. {py_materials-3.2.0 → py_materials-3.3.0}/src/pymat/vis/__init__.py +0 -0
  43. {py_materials-3.2.0 → py_materials-3.3.0}/tests/__init__.py +0 -0
  44. {py_materials-3.2.0 → py_materials-3.3.0}/tests/_visual_compare.py +0 -0
  45. {py_materials-3.2.0 → py_materials-3.3.0}/tests/baselines/README.md +0 -0
  46. {py_materials-3.2.0 → py_materials-3.3.0}/tests/conftest.py +0 -0
  47. {py_materials-3.2.0 → py_materials-3.3.0}/tests/material_preview.html +0 -0
  48. {py_materials-3.2.0 → py_materials-3.3.0}/tests/test_apply_to.py +0 -0
  49. {py_materials-3.2.0 → py_materials-3.3.0}/tests/test_catalog.py +0 -0
  50. {py_materials-3.2.0 → py_materials-3.3.0}/tests/test_core.py +0 -0
  51. {py_materials-3.2.0 → py_materials-3.3.0}/tests/test_enrichers.py +0 -0
  52. {py_materials-3.2.0 → py_materials-3.3.0}/tests/test_loader.py +0 -0
  53. {py_materials-3.2.0 → py_materials-3.3.0}/tests/test_properties.py +0 -0
  54. {py_materials-3.2.0 → py_materials-3.3.0}/tests/test_readme_examples.py +0 -0
  55. {py_materials-3.2.0 → py_materials-3.3.0}/tests/test_toml_integrity.py +0 -0
  56. {py_materials-3.2.0 → py_materials-3.3.0}/tests/test_uncertainties.py +0 -0
  57. {py_materials-3.2.0 → py_materials-3.3.0}/tests/test_visual_compare.py +0 -0
  58. {py_materials-3.2.0 → py_materials-3.3.0}/tests/test_visual_regression.py +0 -0
  59. {py_materials-3.2.0 → py_materials-3.3.0}/tests/visual_render.html +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: py-materials
3
- Version: 3.2.0
3
+ Version: 3.3.0
4
4
  Summary: Hierarchical material library for CAD applications with build123d integration
5
5
  Project-URL: Homepage, https://github.com/MorePet/py-mat
6
6
  Project-URL: Repository, https://github.com/MorePet/py-mat
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "py-materials"
7
- version = "3.2.0"
7
+ version = "3.3.0"
8
8
  description = "Hierarchical material library for CAD applications with build123d integration"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -54,9 +54,10 @@ from .properties import (
54
54
  SourcingProperties,
55
55
  ThermalProperties,
56
56
  )
57
+ from .search import search
57
58
  from .units import ureg
58
59
 
59
- __version__ = "3.2.0" # x-release-please-version
60
+ __version__ = "3.3.0" # x-release-please-version
60
61
  __all__ = [
61
62
  "Material",
62
63
  "AllProperties",
@@ -70,6 +71,7 @@ __all__ = [
70
71
  "ureg",
71
72
  "load_toml",
72
73
  "load_category",
74
+ "search",
73
75
  "enrich_from_periodictable",
74
76
  "enrich_from_matproj",
75
77
  "enrich_all",
@@ -0,0 +1,127 @@
1
+ """
2
+ Fuzzy search over the py-mat domain library.
3
+
4
+ ``pymat.search("stainless 316")`` returns a ranked list of ``Material``
5
+ instances whose registry key, name, grade, or hierarchy path matches
6
+ the query tokens. Complements ``pymat.vis.search(...)`` (visual
7
+ catalog): two axes, same verb, no namespace collision.
8
+
9
+ Algorithm: tokenize query on whitespace; every token must match at
10
+ least one weighted target on a candidate Material for it to be
11
+ included. Score is the sum of per-token best-target weights.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from typing import TYPE_CHECKING
17
+
18
+ if TYPE_CHECKING:
19
+ from .core import Material
20
+
21
+
22
+ # Target weights — higher is a stronger match. Order matters: when a
23
+ # query token matches multiple targets on the same Material, the
24
+ # highest-weight hit counts.
25
+ _WEIGHT_KEY = 10 # registry key — "s316L"
26
+ _WEIGHT_NAME = 5 # Material.name — "Stainless Steel 316L"
27
+ _WEIGHT_GRADE = 5 # Material.grade — "316L"
28
+ _WEIGHT_PATH = 3 # hierarchy parent names
29
+
30
+
31
+ def _targets(key: str, material: Material) -> list[tuple[str, int]]:
32
+ """Return (lowered-target-string, weight) pairs for a Material.
33
+
34
+ Hierarchy path walks ``parent`` up; skips the material's own name
35
+ (already covered by the name target) and any None-named parents.
36
+ """
37
+ pairs: list[tuple[str, int]] = [(key.lower(), _WEIGHT_KEY)]
38
+
39
+ if material.name:
40
+ pairs.append((material.name.lower(), _WEIGHT_NAME))
41
+
42
+ grade = getattr(material, "grade", None)
43
+ if grade:
44
+ pairs.append((str(grade).lower(), _WEIGHT_GRADE))
45
+
46
+ # Walk the parent chain; skip the material itself (starts from parent).
47
+ parent = getattr(material, "parent", None)
48
+ while parent is not None:
49
+ if parent.name:
50
+ pairs.append((parent.name.lower(), _WEIGHT_PATH))
51
+ parent = getattr(parent, "parent", None)
52
+
53
+ return pairs
54
+
55
+
56
+ def _score(tokens: list[str], targets: list[tuple[str, int]]) -> int:
57
+ """Score a Material against the query tokens.
58
+
59
+ Every token must substring-match at least one target. Returns 0
60
+ (rejected) if any token misses. Otherwise returns the sum of
61
+ best-per-token weights — so a token matching the high-weight key
62
+ beats a token matching only the low-weight path.
63
+ """
64
+ total = 0
65
+ for token in tokens:
66
+ best = 0
67
+ for target, weight in targets:
68
+ if token in target and weight > best:
69
+ best = weight
70
+ if best == 0:
71
+ return 0 # token didn't match anywhere → reject
72
+ total += best
73
+ return total
74
+
75
+
76
+ def search(query: str, *, limit: int = 10) -> list[Material]:
77
+ """Fuzzy-find Materials in the loaded library by name, key, or grade.
78
+
79
+ Tokenizes ``query`` on whitespace (case-insensitive). Every token
80
+ must match somewhere — registry key, ``Material.name``,
81
+ ``Material.grade``, or a hierarchy parent name — for a Material
82
+ to be included. Ranks by summed match weight; returns at most
83
+ ``limit`` best hits.
84
+
85
+ Returns an empty list for an empty / whitespace-only query.
86
+
87
+ Examples::
88
+
89
+ pymat.search("stainless")
90
+ # → [stainless, s304, s316L, s410, ...]
91
+
92
+ pymat.search("316")
93
+ # → [s316L, s316, ...] — grades match, parent doesn't
94
+
95
+ pymat.search("stainless 316")
96
+ # → [s316L] — all tokens must match, grade wins
97
+
98
+ pymat.search("lyso ce saint")
99
+ # → [prelude420, ...] — deep hierarchy via tokenization
100
+
101
+ Triggers ``load_all()`` on first call so results are exhaustive
102
+ across categories.
103
+ """
104
+ tokens = query.lower().split()
105
+ if not tokens:
106
+ return []
107
+
108
+ # Import lazily to avoid circular import at module load: pymat's
109
+ # __init__.py hasn't finished initializing when this module loads.
110
+ from . import load_all, registry
111
+
112
+ load_all()
113
+ all_materials = registry.list_all()
114
+
115
+ scored: list[tuple[int, int, str, Material]] = []
116
+ for key, material in all_materials.items():
117
+ targets = _targets(key, material)
118
+ s = _score(tokens, targets)
119
+ if s > 0:
120
+ # Tie-break tuple: primary by score DESC (via -s), then by
121
+ # key length ASC (shorter key wins — "s316L" before
122
+ # "electropolished" when both score the same), then by key
123
+ # alphabetical for determinism.
124
+ scored.append((-s, len(key), key, material))
125
+
126
+ scored.sort()
127
+ return [m for _, _, _, m in scored[:limit]]
@@ -406,6 +406,44 @@ class Vis:
406
406
  tex = self.textures.get(channel)
407
407
  return ResolvedChannel(texture=tex, scalar=scalar)
408
408
 
409
+ # ── Adapter sugar (delegate to module-level, method discoverability) ─
410
+
411
+ def to_threejs(self) -> dict[str, Any]:
412
+ """Shorthand for ``pymat.vis.to_threejs(material)`` — method form.
413
+
414
+ Same output as the module-level adapter. Use this when you have
415
+ a ``Vis`` in hand (``material.vis.to_threejs()``); use the
416
+ module-level form (``pymat.vis.to_threejs(material)``) in code
417
+ that's explicitly function-composition oriented.
418
+ """
419
+ from pymat.vis.adapters import to_threejs
420
+
421
+ return to_threejs(self)
422
+
423
+ def to_gltf(self, *, name: str | None = None) -> dict[str, Any]:
424
+ """Shorthand for ``pymat.vis.to_gltf(material)`` — method form.
425
+
426
+ The glTF material node's ``name`` field is populated from
427
+ ``name=`` if given, else left empty (the method has no
428
+ visibility into the owning Material's name; pass it through
429
+ explicitly when calling on a standalone Vis). The module-level
430
+ ``pymat.vis.to_gltf(material)`` reads ``material.name``
431
+ automatically.
432
+ """
433
+ from pymat.vis.adapters import to_gltf
434
+
435
+ return to_gltf(self, name=name)
436
+
437
+ def export_mtlx(self, output_dir: str | Path, *, name: str | None = None) -> Path:
438
+ """Shorthand for ``pymat.vis.export_mtlx(material, out)``.
439
+
440
+ ``name=`` sets the MTLX filename stem. Omitted on a standalone
441
+ Vis → defaults to ``"material"``.
442
+ """
443
+ from pymat.vis.adapters import export_mtlx
444
+
445
+ return export_mtlx(self, Path(output_dir), name=name)
446
+
409
447
  # ── Discovery (py-mat's tag-aware layer over client.search) ─
410
448
 
411
449
  def discover(
@@ -0,0 +1,123 @@
1
+ """
2
+ Output adapters — thin wrappers that map Material to mat-vis's
3
+ generic adapter functions.
4
+
5
+ The actual format logic (Three.js field names, glTF schema,
6
+ MaterialX XML) lives in mat_vis_client.adapters (installed from
7
+ mat-vis-client package). These wrappers extract scalars + textures
8
+ from a ``Material`` (or a standalone ``Vis``) and pass them through.
9
+
10
+ from pymat.vis.adapters import to_threejs, to_gltf, export_mtlx
11
+ result = to_threejs(material) # Material form
12
+ result = to_threejs(material.vis) # Vis form — same output
13
+
14
+ The polymorphism lets ``Vis.to_gltf()`` / ``Vis.to_threejs()`` method
15
+ sugar delegate here without a back-reference from ``Vis`` to its
16
+ owning ``Material``.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from pathlib import Path
22
+ from typing import TYPE_CHECKING, Any, Union
23
+
24
+ from mat_vis_client.adapters import export_mtlx as _export_mtlx
25
+ from mat_vis_client.adapters import to_gltf as _to_gltf
26
+ from mat_vis_client.adapters import to_threejs as _to_threejs
27
+
28
+ if TYPE_CHECKING:
29
+ from pymat.core import _MaterialInternal as Material
30
+ from pymat.vis._model import Vis
31
+
32
+ MaterialOrVis = Union[Material, Vis]
33
+
34
+
35
+ def _rgba_to_hex(rgba: list[float] | tuple[float, ...] | None) -> str | None:
36
+ """Convert [r, g, b, a?] in 0-1 range to '#RRGGBB'. Alpha dropped."""
37
+ if rgba is None:
38
+ return None
39
+ r, g, b = (int(round(max(0.0, min(1.0, c)) * 255)) for c in rgba[:3])
40
+ return f"#{r:02x}{g:02x}{b:02x}"
41
+
42
+
43
+ def _resolve_vis_and_name(obj: MaterialOrVis) -> tuple[Vis, str]:
44
+ """Unwrap a Material (``→ .vis, .name``) or a standalone Vis
45
+ (``→ self, ""``). Duck-typed via the ``.vis`` attribute: anything
46
+ that exposes ``.vis`` is treated as the owning Material."""
47
+ if hasattr(obj, "vis"):
48
+ return obj.vis, getattr(obj, "name", "") or ""
49
+ return obj, "" # assume it's a Vis
50
+
51
+
52
+ def _extract_scalars(obj: MaterialOrVis) -> dict[str, Any]:
53
+ """Extract PBR scalars from material.vis (or a plain Vis).
54
+
55
+ Maps py-mat "metallic" → mat-vis "metalness" and our RGBA
56
+ base_color list → mat-vis's color_hex string (its adapters
57
+ only know how to emit color from the hex form).
58
+ """
59
+ vis, _ = _resolve_vis_and_name(obj)
60
+ return {
61
+ "metalness": vis.get("metallic"),
62
+ "roughness": vis.get("roughness"),
63
+ "color_hex": _rgba_to_hex(vis.get("base_color")),
64
+ "ior": vis.get("ior"),
65
+ "transmission": vis.get("transmission"),
66
+ "clearcoat": vis.get("clearcoat"),
67
+ "emissive": vis.get("emissive"),
68
+ }
69
+
70
+
71
+ def _extract_textures(obj: MaterialOrVis) -> dict[str, bytes]:
72
+ """Extract texture bytes from a Material's Vis (or a plain Vis)."""
73
+ vis, _ = _resolve_vis_and_name(obj)
74
+ if not vis.has_mapping:
75
+ return {}
76
+ return vis.textures
77
+
78
+
79
+ def to_threejs(obj: MaterialOrVis) -> dict[str, Any]:
80
+ """Format as a Three.js MeshPhysicalMaterial-compatible dict.
81
+
82
+ Accepts either a ``Material`` or a standalone ``Vis``. Reads PBR
83
+ scalars and texture maps from ``obj.vis`` (or from ``obj`` itself
84
+ if it's a Vis). Delegates to mat-vis's generic adapter.
85
+ """
86
+ return _to_threejs(_extract_scalars(obj), _extract_textures(obj))
87
+
88
+
89
+ def to_gltf(obj: MaterialOrVis, *, name: str | None = None) -> dict[str, Any]:
90
+ """Format as a glTF pbrMetallicRoughness material dict.
91
+
92
+ Accepts either a ``Material`` (its ``.name`` is used as the glTF
93
+ material ``name`` field) or a standalone ``Vis`` (pass ``name=``
94
+ explicitly to populate the field; empty string otherwise).
95
+ Delegates to mat-vis's generic adapter.
96
+ """
97
+ _, resolved_name = _resolve_vis_and_name(obj)
98
+ result = _to_gltf(_extract_scalars(obj), _extract_textures(obj))
99
+ result["name"] = name if name is not None else resolved_name
100
+ return result
101
+
102
+
103
+ def export_mtlx(
104
+ obj: MaterialOrVis,
105
+ output_dir: Path,
106
+ *,
107
+ name: str | None = None,
108
+ ) -> Path:
109
+ """Export as a MaterialX .mtlx file + PNG textures on disk.
110
+
111
+ Accepts either a ``Material`` (its ``.name`` becomes the filename
112
+ stem) or a standalone ``Vis`` (pass ``name=`` explicitly to name
113
+ the output). Delegates to mat-vis's generic adapter.
114
+ """
115
+ _, resolved_name = _resolve_vis_and_name(obj)
116
+ mat_name = name if name is not None else resolved_name
117
+ safe_name = mat_name.replace(" ", "_").replace("/", "_") or "material"
118
+ return _export_mtlx(
119
+ _extract_scalars(obj),
120
+ _extract_textures(obj),
121
+ output_dir,
122
+ material_name=safe_name,
123
+ )
@@ -0,0 +1,318 @@
1
+ """Tests for pymat.vis.adapters — Material → format wrappers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import tempfile
6
+ from pathlib import Path
7
+
8
+ from pymat import Material
9
+ from pymat.vis.adapters import (
10
+ _extract_scalars,
11
+ _extract_textures,
12
+ _rgba_to_hex,
13
+ export_mtlx,
14
+ to_gltf,
15
+ to_threejs,
16
+ )
17
+
18
+
19
+ def _make_material(with_vis=False):
20
+ """Create a test material with vis scalars."""
21
+ m = Material(name="Test Steel")
22
+ m.vis.metallic = 1.0
23
+ m.vis.roughness = 0.3
24
+ m.vis.base_color = (0.8, 0.8, 0.8, 1.0)
25
+ m.vis.ior = 2.5
26
+ m.vis.transmission = 0.0
27
+ m.vis.clearcoat = 0.0
28
+ m.vis.emissive = (0, 0, 0)
29
+ if with_vis:
30
+ # Identity must be set BEFORE the cache — assigning source /
31
+ # material_id invalidates _textures + _fetched via Vis.__setattr__
32
+ # (3.1.1 cache-invalidation behavior).
33
+ m.vis.source = "ambientcg"
34
+ m.vis.material_id = "Metal032"
35
+ m.vis._textures = {
36
+ "color": b"\x89PNG_color",
37
+ "normal": b"\x89PNG_normal",
38
+ "roughness": b"\x89PNG_roughness",
39
+ }
40
+ m.vis._fetched = True
41
+ return m
42
+
43
+
44
+ class TestExtractScalars:
45
+ def test_from_pbr(self):
46
+ m = _make_material()
47
+ s = _extract_scalars(m)
48
+ assert s["metalness"] == 1.0
49
+ assert s["roughness"] == 0.3
50
+ assert s["ior"] == 2.5
51
+
52
+ def test_vis_wins_over_pbr(self):
53
+ m = _make_material()
54
+ m.vis.roughness = 0.5 # vis override
55
+ s = _extract_scalars(m)
56
+ assert s["roughness"] == 0.5 # vis wins
57
+ assert s["metalness"] == 1.0 # falls back to pbr
58
+
59
+ def test_metallic_mapped_to_metalness(self):
60
+ m = _make_material()
61
+ s = _extract_scalars(m)
62
+ assert "metalness" in s
63
+ assert "metallic" not in s
64
+
65
+ def test_base_color_emitted_as_color_hex(self):
66
+ """mat-vis-client only formats color from color_hex — the extractor
67
+ must convert our RGBA list to '#RRGGBB' or the final Three.js dict
68
+ has no color at all (every material renders as default grey)."""
69
+ m = _make_material()
70
+ m.vis.base_color = (1.0, 0.0, 0.0, 1.0)
71
+ s = _extract_scalars(m)
72
+ assert s["color_hex"] == "#ff0000"
73
+ assert "base_color" not in s # RGBA form must not leak through
74
+
75
+
76
+ class TestRgbaToHex:
77
+ def test_pure_red(self):
78
+ assert _rgba_to_hex([1.0, 0.0, 0.0, 1.0]) == "#ff0000"
79
+
80
+ def test_pure_green(self):
81
+ assert _rgba_to_hex([0.0, 1.0, 0.0]) == "#00ff00" # alpha optional
82
+
83
+ def test_mid_grey(self):
84
+ assert _rgba_to_hex([0.5, 0.5, 0.5]) == "#808080"
85
+
86
+ def test_none_passthrough(self):
87
+ assert _rgba_to_hex(None) is None
88
+
89
+ def test_clamps_out_of_range(self):
90
+ # PBR values can over/undershoot; don't raise, just clamp
91
+ assert _rgba_to_hex([-0.1, 1.5, 0.5]) == "#00ff80"
92
+
93
+ def test_alpha_ignored(self):
94
+ assert _rgba_to_hex([1.0, 1.0, 1.0, 0.3]) == "#ffffff" # alpha stripped
95
+
96
+
97
+ class TestExtractTextures:
98
+ def test_no_vis_returns_empty(self):
99
+ m = _make_material(with_vis=False)
100
+ assert _extract_textures(m) == {}
101
+
102
+ def test_with_vis_returns_textures(self):
103
+ m = _make_material(with_vis=True)
104
+ tex = _extract_textures(m)
105
+ assert "color" in tex
106
+ assert tex["color"] == b"\x89PNG_color"
107
+
108
+
109
+ class TestToThreejs:
110
+ def test_scalar_only(self):
111
+ m = _make_material(with_vis=False)
112
+ d = to_threejs(m)
113
+ assert d["metalness"] == 1.0
114
+ assert d["roughness"] == 0.3
115
+ assert "map" not in d # no textures
116
+
117
+ def test_with_textures(self):
118
+ m = _make_material(with_vis=True)
119
+ d = to_threejs(m)
120
+ assert "map" in d # base64 data URI
121
+ assert d["map"].startswith("data:image/png;base64,")
122
+ assert "normalMap" in d
123
+ assert "roughnessMap" in d
124
+
125
+
126
+ class TestToGltf:
127
+ def test_scalar_only(self):
128
+ m = _make_material(with_vis=False)
129
+ d = to_gltf(m)
130
+ assert d["name"] == "Test Steel"
131
+ assert "pbrMetallicRoughness" in d
132
+ pbr = d["pbrMetallicRoughness"]
133
+ assert pbr["metallicFactor"] == 1.0
134
+ assert pbr["roughnessFactor"] == 0.3
135
+
136
+ def test_with_textures(self):
137
+ m = _make_material(with_vis=True)
138
+ d = to_gltf(m)
139
+ assert d["name"] == "Test Steel"
140
+
141
+
142
+ class TestExportMtlx:
143
+ def test_export_creates_files(self):
144
+ m = _make_material(with_vis=True)
145
+ with tempfile.TemporaryDirectory() as tmp:
146
+ mtlx_path = export_mtlx(m, Path(tmp))
147
+ assert mtlx_path.exists()
148
+ assert mtlx_path.suffix == ".mtlx"
149
+ # Check textures were written as PNG files
150
+ pngs = list(Path(tmp).glob("*.png"))
151
+ assert len(pngs) == 3 # color, normal, roughness
152
+
153
+ def test_export_no_textures(self):
154
+ m = _make_material(with_vis=False)
155
+ with tempfile.TemporaryDirectory() as tmp:
156
+ mtlx_path = export_mtlx(m, Path(tmp))
157
+ assert mtlx_path.exists()
158
+ pngs = list(Path(tmp).glob("*.png"))
159
+ assert len(pngs) == 0 # no textures
160
+
161
+
162
+ class TestAdapterPolymorphism:
163
+ """Adapters accept either a Material or a Vis — same output.
164
+
165
+ This is the property that lets ``Vis.to_gltf()`` method sugar
166
+ delegate to the module-level adapter without a back-reference
167
+ from Vis to its owning Material.
168
+ """
169
+
170
+ def test_to_threejs_material_and_vis_agree(self):
171
+ m = _make_material()
172
+ assert to_threejs(m) == to_threejs(m.vis)
173
+
174
+ def test_to_gltf_material_and_vis_agree_on_pbr(self):
175
+ m = _make_material()
176
+ from_material = to_gltf(m)
177
+ from_vis = to_gltf(m.vis, name=m.name)
178
+ assert from_material == from_vis
179
+
180
+ def test_to_gltf_vis_without_name_leaves_empty_string(self):
181
+ m = _make_material()
182
+ d = to_gltf(m.vis) # no name= kwarg
183
+ assert d["name"] == ""
184
+
185
+ def test_export_mtlx_vis_accepts_name_kwarg(self):
186
+ m = _make_material(with_vis=True)
187
+ with tempfile.TemporaryDirectory() as tmp:
188
+ # Via Vis + explicit name — filename stem must match.
189
+ mtlx_path = export_mtlx(m.vis, Path(tmp), name="Stem")
190
+ assert mtlx_path.exists()
191
+ assert mtlx_path.stem == "Stem", f"expected stem 'Stem', got {mtlx_path.stem!r}"
192
+
193
+ def test_export_mtlx_vis_without_name_falls_back(self):
194
+ """A standalone Vis with no name= kwarg must not crash; the
195
+ default stem is whatever the adapter picks (currently 'material')."""
196
+ from pymat.vis._model import Vis
197
+
198
+ # Construct a Vis fully detached from any Material — this is
199
+ # the path a downstream like mat-vis-client might hit if they
200
+ # adopted the same sugar independently.
201
+ vis = Vis(source=None, material_id=None) # no mapping → no textures
202
+ with tempfile.TemporaryDirectory() as tmp:
203
+ mtlx_path = export_mtlx(vis, Path(tmp))
204
+ assert mtlx_path.exists()
205
+ assert mtlx_path.stem != "", "empty stem would break filesystem writes"
206
+
207
+ def test_resolve_vis_duck_typing_invariant(self):
208
+ """``_resolve_vis_and_name`` distinguishes Material-vs-Vis via
209
+ ``hasattr(obj, "vis")``. If Vis ever grows a ``.vis`` attribute
210
+ (self-reference, alias, anything), the helper would recurse and
211
+ misclassify. Pin that invariant here."""
212
+ from pymat.vis._model import Vis
213
+
214
+ vis = Vis(source="ambientcg", material_id="Metal032")
215
+ assert not hasattr(vis, "vis"), (
216
+ "Vis must not have a .vis attribute — would break the "
217
+ "Material-vs-Vis duck-typing in adapter._resolve_vis_and_name. "
218
+ "If this test starts failing, the helper needs an "
219
+ "isinstance check instead of hasattr."
220
+ )
221
+
222
+ def test_adapter_name_is_keyword_only(self):
223
+ """``to_gltf(obj, name=...)`` must be keyword-only. Positional
224
+ call should be a TypeError — prevents a downstream relying on
225
+ positional ordering that could silently shift on a future
226
+ signature change."""
227
+ import pytest
228
+
229
+ from pymat.vis._model import Vis
230
+
231
+ vis = Vis()
232
+ with pytest.raises(TypeError):
233
+ to_gltf(vis, "positional_name") # type: ignore[misc]
234
+
235
+
236
+ class TestAdapterOnDetachedVis:
237
+ """Full-path tests that construct a Vis without any Material,
238
+ verifying every adapter still works on the raw payload object.
239
+ This is the contract downstreams (including a hypothetical
240
+ mat-vis-client VisAsset) can rely on."""
241
+
242
+ def _detached_vis_with_scalars(self):
243
+ from pymat.vis._model import Vis
244
+
245
+ v = Vis()
246
+ v.metallic = 1.0
247
+ v.roughness = 0.25
248
+ v.base_color = (0.9, 0.9, 0.9, 1.0)
249
+ v.ior = 1.5
250
+ v.transmission = 0.0
251
+ return v
252
+
253
+ def test_to_threejs_on_detached_vis(self):
254
+ v = self._detached_vis_with_scalars()
255
+ d = to_threejs(v)
256
+ assert d["metalness"] == 1.0
257
+ assert d["roughness"] == 0.25
258
+ assert "ior" in d # ior scalar routed through
259
+
260
+ def test_to_gltf_on_detached_vis_empty_name(self):
261
+ v = self._detached_vis_with_scalars()
262
+ d = to_gltf(v)
263
+ assert d["pbrMetallicRoughness"]["metallicFactor"] == 1.0
264
+ assert d["name"] == "" # no owning Material, no name kwarg
265
+
266
+ def test_to_gltf_on_detached_vis_with_name(self):
267
+ v = self._detached_vis_with_scalars()
268
+ d = to_gltf(v, name="Hand-rolled")
269
+ assert d["name"] == "Hand-rolled"
270
+
271
+ def test_vis_method_on_detached_vis(self):
272
+ """The method form must also work on a detached Vis — covers
273
+ the common case of ``Vis().to_gltf(name='...')`` in downstream
274
+ code that constructs Vis without a py-mat Material."""
275
+ v = self._detached_vis_with_scalars()
276
+ assert v.to_gltf(name="X") == to_gltf(v, name="X")
277
+ assert v.to_threejs() == to_threejs(v)
278
+
279
+ def test_method_call_surface_present(self):
280
+ """``m.vis.<TAB>`` must surface the three adapter methods —
281
+ that's the whole point of this sugar."""
282
+ v = self._detached_vis_with_scalars()
283
+ for name in ("to_threejs", "to_gltf", "export_mtlx"):
284
+ attr = getattr(v, name, None)
285
+ assert attr is not None, f"Vis.{name} missing"
286
+ assert callable(attr), f"Vis.{name} not callable"
287
+
288
+
289
+ class TestVisAdapterMethods:
290
+ """Method-form sugar on Vis — discoverability via tab completion.
291
+
292
+ Must be a drop-in shorthand: ``m.vis.to_gltf()`` and
293
+ ``pymat.vis.to_gltf(m)`` must produce the same dict. Same for
294
+ ``to_threejs`` and ``export_mtlx``.
295
+ """
296
+
297
+ def test_vis_to_threejs_matches_module_level(self):
298
+ m = _make_material()
299
+ assert m.vis.to_threejs() == to_threejs(m)
300
+
301
+ def test_vis_to_gltf_matches_module_level_with_name(self):
302
+ m = _make_material()
303
+ assert m.vis.to_gltf(name=m.name) == to_gltf(m)
304
+
305
+ def test_vis_to_gltf_no_name_leaves_empty(self):
306
+ """Vis.to_gltf() without name= produces an empty name field —
307
+ the method can't reach the owning Material without a back-ref,
308
+ so users on a standalone Vis path opt in by passing name="X"."""
309
+ m = _make_material()
310
+ d = m.vis.to_gltf()
311
+ assert d["name"] == ""
312
+
313
+ def test_vis_export_mtlx_delegates(self):
314
+ m = _make_material(with_vis=True)
315
+ with tempfile.TemporaryDirectory() as tmp:
316
+ mtlx_path = m.vis.export_mtlx(Path(tmp), name="ViaMethod")
317
+ assert mtlx_path.exists()
318
+ assert mtlx_path.suffix == ".mtlx"
@@ -220,6 +220,39 @@ class TestEndToEnd:
220
220
  textures = vis.fetch(r["source"], r["id"], tier="128")
221
221
  assert len(textures) >= 0 # may be 0 if 128 tier not available
222
222
 
223
+ def test_mtlx_xml_returns_materialx_string(self):
224
+ """Material.vis.mtlx.xml() returns a MaterialX XML string.
225
+
226
+ Pins the 0.5 method-form (``.xml()`` not property ``.xml``) and
227
+ asserts the content is MaterialX — not an error page or empty
228
+ string. The full ``.export(path)`` package path is covered by
229
+ the adapter test; this test locks the direct ``.xml()`` accessor
230
+ the README + build123d integration docs call out.
231
+ """
232
+ from pymat import Material, vis
233
+
234
+ results = vis.search(category="metal", limit=1)
235
+ if not results:
236
+ pytest.skip("No metal materials in mat-vis index")
237
+
238
+ source = results[0].get("source", "ambientcg")
239
+ mat_id = results[0]["id"]
240
+
241
+ m = Material(name="mtlx xml probe")
242
+ m.vis.source = source
243
+ m.vis.material_id = mat_id
244
+ m.vis.tier = results[0].get("default_tier") or "1k"
245
+
246
+ with _skip_on_upstream_outage():
247
+ xml = m.vis.mtlx.xml()
248
+
249
+ assert isinstance(xml, str), f"expected str, got {type(xml).__name__}"
250
+ lowered = xml.lower()
251
+ assert "<materialx" in lowered or xml.startswith("<?xml"), (
252
+ f"not a MaterialX document; first 200 chars: {xml[:200]!r}"
253
+ )
254
+ assert len(xml) > 200, f"suspiciously short MaterialX doc ({len(xml)} chars)"
255
+
223
256
  def test_resolve_channel(self):
224
257
  """Vis.resolve() returns texture or scalar fallback."""
225
258
  from pymat import Material, vis