vs2convert 0.2.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.
vs2convert/__init__.py ADDED
@@ -0,0 +1,10 @@
1
+ """vs2convert - convert Shadertoy, ISF and GLSLSandbox shaders to VS-2 .frag.
2
+
3
+ The library surface lives in :mod:`vs2convert.api`; the command line entry
4
+ point is :func:`vs2convert.cli.main`.
5
+ """
6
+
7
+ from .api import ConversionResult, Rejection, convert
8
+
9
+ __all__ = ["convert", "ConversionResult", "Rejection"]
10
+ __version__ = "0.2.0"
vs2convert/api.py ADDED
@@ -0,0 +1,194 @@
1
+ """The public conversion API.
2
+
3
+ This is the single surface both the CLI and any future front-end call.
4
+ `convert()` never raises on a bad source: a decline is returned as data.
5
+ """
6
+
7
+ from dataclasses import dataclass
8
+ from typing import Dict, List, Optional
9
+
10
+ from .core.detector import check_suitability
11
+ from .core.gates import NON_FORCEABLE
12
+ from .core.generator import ConversionError
13
+ from .core.generator import convert as _convert
14
+ from .validators.validator import run_validation
15
+
16
+ __all__ = ["convert", "ConversionResult", "Rejection"]
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class Rejection:
21
+ """One reason a source was not converted."""
22
+
23
+ stage: str # "detect" | "suitability" | "convert" | "validate"
24
+ gate: str # stable id, from core.gates.GATES
25
+ reason: str # one-line human summary
26
+ detail: str # what the user can do about it
27
+ issue_hint: Optional[str] = None
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class ConversionResult:
32
+ """Everything a caller needs to show or write the outcome."""
33
+
34
+ ok: bool
35
+ frag: Optional[str]
36
+ manifest: Optional[dict]
37
+ params: List[dict]
38
+ warnings: List[str]
39
+ baked: List[str]
40
+ rejections: List[Rejection]
41
+ format: Optional[str]
42
+ source_name: Optional[str]
43
+
44
+
45
+ # What the user can do about each refusal. Kept here, not in the CLI, so a
46
+ # future front-end gives the same advice. Keyed by the stable gate id, so a
47
+ # renamed message cannot silently lose its advice.
48
+ _GATE_ADVICE = {
49
+ "hlsl-milkdrop": "MilkDrop/HLSL cannot be expressed as one VS-2 pass; "
50
+ "port it by hand.",
51
+ "isf-feedback-buffer": "VS-2 has no feedback buffer. Remove the TARGET "
52
+ "input/pass, or convert by hand.",
53
+ "isf-imported-resources": "The .fs ships its own image files, which VS-2 "
54
+ "cannot load. Supply those images from the VS-2 "
55
+ "layer instead.",
56
+ "glsl-texture2d": "Replace texture2D()/tex2D() with texture(imageTex, uv), "
57
+ "or convert by hand.",
58
+ "shadertoy-multi-channel": "VS-2 binds one image. Strip the shader down to "
59
+ "a single channel, or convert by hand.",
60
+ "isf-multiple-image-inputs": "VS-2 binds one image. Use a single TYPE:image "
61
+ "input, or convert by hand.",
62
+ "shadertoy-unrepresentable-channel": "The pass metadata declares a channel "
63
+ "VS-2 has no input for (buffer, "
64
+ "cubemap, keyboard), or an audio "
65
+ "channel with no implemented mapping "
66
+ "(VS-2 has fftTex). Change the "
67
+ "channel to a texture, or convert by "
68
+ "hand.",
69
+ "shadertoy-channel-uncertainty": "Pass the Shadertoy channel declarations "
70
+ "with --meta so the binding can be "
71
+ "confirmed.",
72
+ "engine-var-redeclaration": "Remove the declaration; VS-2 provides "
73
+ "resolution, time, texCoord, color, alpha, "
74
+ "imageTex, imageResolution and fftTex.",
75
+ "too-many-parameters": "VS-2 accepts at most 7 parameters. Remove the "
76
+ "extras, or hard-code their values.",
77
+ "missing-entry-point": "The source has no mainImage()/main(). Check that it "
78
+ "is a complete shader.",
79
+ "isf-parse-failure": "Fix the JSON manifest, or obtain a clean copy of the "
80
+ ".fs.",
81
+ "unsupported-format": "The source is not Shadertoy, ISF or GLSLSandbox.",
82
+ "structural-validation": "The converted body did not pass the structural "
83
+ "validator. Report it with the source; do not "
84
+ "ship the output.",
85
+ "internal-error": "This is a converter bug, not a problem with the source. "
86
+ "Please report it with the full traceback.",
87
+ }
88
+ _DEFAULT_ADVICE = "Adjust the source, or convert it by hand."
89
+
90
+
91
+ def _reject(stage: str, gate: str, reason: str) -> Rejection:
92
+ return Rejection(stage=stage, gate=gate, reason=reason,
93
+ detail=_GATE_ADVICE.get(gate, _DEFAULT_ADVICE))
94
+
95
+
96
+ def _decline(source_name, fmt, warnings, rejections) -> ConversionResult:
97
+ return ConversionResult(
98
+ ok=False,
99
+ frag=None,
100
+ manifest=None,
101
+ params=[],
102
+ warnings=list(warnings),
103
+ baked=[],
104
+ rejections=list(rejections),
105
+ format=fmt,
106
+ source_name=source_name,
107
+ )
108
+
109
+
110
+ def convert(source: str, *, name: Optional[str] = None, force: bool = False,
111
+ meta: Optional[Dict] = None,
112
+ validate: bool = True) -> ConversionResult:
113
+ """Convert a shader source string to a VS-2 `.frag`.
114
+
115
+ Never raises on a bad source: declines come back as `rejections`.
116
+ `ok=True` means the body was produced AND (unless `validate=False`)
117
+ passed the structural validator.
118
+ """
119
+ try:
120
+ return _convert_checked(source, name, force, meta, validate)
121
+ except Exception as exc: # the contract boundary, deliberately broad
122
+ return _decline(
123
+ name, None, [],
124
+ [_reject("convert", "internal-error",
125
+ "conversion failed unexpectedly: %s: %s"
126
+ % (type(exc).__name__, exc))])
127
+
128
+
129
+ def _convert_checked(source, name, force, meta, validate) -> ConversionResult:
130
+ # One call decides: it returns the format and every suitability error,
131
+ # and it re-runs detection internally. Calling detect_format as well
132
+ # would just duplicate the same errors.
133
+ verdict = check_suitability(source)
134
+ fmt = verdict.get("format")
135
+ errors = verdict.get("errors") or []
136
+ gates = verdict.get("error_gates") or []
137
+ warnings = list(verdict.get("warnings") or [])
138
+
139
+ if errors:
140
+ # A non-forceable gate is a fact about the target, not a limitation
141
+ # this tool can override. Forcing one emits a body that does not
142
+ # compile or silently drops an input, so decline even with --force.
143
+ blocked = [g for g in gates if g in NON_FORCEABLE]
144
+ if force and not blocked:
145
+ warnings.append(
146
+ "FORCED past the suitability gate: the output is very likely "
147
+ "broken.")
148
+ else:
149
+ rejections = [_reject("suitability", gate, message)
150
+ for gate, message in zip(gates, errors)]
151
+ return _decline(name, fmt, warnings, rejections)
152
+
153
+ try:
154
+ report = _convert(source, fmt, name or "shader", force=force, meta=meta)
155
+ except ConversionError as exc:
156
+ gate = exc.gate or "internal-error"
157
+ return _decline(name, fmt, warnings,
158
+ [_reject("convert", gate, str(exc))])
159
+
160
+ frag = report["frag"]
161
+ warnings.extend(report.get("warnings") or [])
162
+ baked = list(report.get("baked") or [])
163
+ manifest = report.get("manifest")
164
+ params = list(report.get("params") or [])
165
+
166
+ rejections = []
167
+ if validate:
168
+ try:
169
+ check = run_validation(frag, name or "shader")
170
+ except Exception as exc:
171
+ rejections.append(_reject(
172
+ "validate", "internal-error",
173
+ "validation failed unexpectedly: %s: %s"
174
+ % (type(exc).__name__, exc)))
175
+ else:
176
+ for message in check.get("errors") or []:
177
+ rejections.append(
178
+ _reject("validate", "structural-validation", message))
179
+ warnings.extend(check.get("warnings") or [])
180
+
181
+ if rejections:
182
+ return _decline(name, fmt, warnings, rejections)
183
+
184
+ return ConversionResult(
185
+ ok=True,
186
+ frag=frag,
187
+ manifest=manifest,
188
+ params=params,
189
+ warnings=warnings,
190
+ baked=baked,
191
+ rejections=[],
192
+ format=fmt,
193
+ source_name=name,
194
+ )
vs2convert/cli.py ADDED
@@ -0,0 +1,306 @@
1
+ #!/usr/bin/env python3
2
+ """vs2convert - convert Shadertoy, ISF and GLSLSandbox shaders to VS-2 .frag.
3
+
4
+ A thin shell over :func:`vs2convert.api.convert`: it reads the source, prints
5
+ the verdict, and writes the file. All conversion decisions live in the API.
6
+ """
7
+
8
+ import argparse
9
+ import json
10
+ import re
11
+ import shlex
12
+ import sys
13
+ import textwrap
14
+ from pathlib import Path
15
+ from urllib.parse import urlencode
16
+
17
+ from . import __version__, api
18
+ from .core.detector import detect_format
19
+ from .core.report import Reporter
20
+ from .core.shadertoy_meta import load_meta
21
+
22
+ # Where a declined conversion is reported. Kept in one place: it is printed
23
+ # on every decline, so it must be right.
24
+ ISSUES_URL = "https://github.com/andrewpmiller/vs2convert/issues/new"
25
+
26
+
27
+ def main():
28
+ parser = argparse.ArgumentParser(
29
+ prog="vs2convert",
30
+ description="Convert a Shadertoy, ISF or GLSLSandbox shader to a "
31
+ "VS-2 .frag file.",
32
+ formatter_class=argparse.RawDescriptionHelpFormatter,
33
+ epilog="""Exit codes:
34
+ 0 converted (always validated) and, if requested, rendered
35
+ 1 declined, or the input/metadata could not be read - includes
36
+ validation failure and a failed render check
37
+ 2 render verification unavailable, or bad command-line usage
38
+ 3 the source is not suitable for conversion
39
+ 4 could not write the output (missing directory, write error, would
40
+ overwrite the input)
41
+ 5 --strict, and the conversion was UNVERIFIED
42
+
43
+ Pass metadata:
44
+ --meta FILE explicit JSON file
45
+ <stem>.stmeta.json beside the source (or a lone *.stmeta.json in its dir)
46
+ an inline /*{...}*/ JSON block at the top of the source
47
+ Precedence: --meta, then sidecar, then inline. Only Shadertoy-style
48
+ sources consult it.
49
+
50
+ Examples:
51
+ vs2convert shader.fs # writes shader.frag beside it
52
+ vs2convert shader.fs out.frag --verify
53
+ cat shader.glsl | vs2convert - out.frag # stdin needs an explicit output
54
+ """)
55
+ parser.add_argument("source", metavar="SOURCE",
56
+ help="Shader file, or - to read stdin")
57
+ parser.add_argument("output", nargs="?",
58
+ help="Output .frag (default: <source stem>.frag "
59
+ "beside the input; required with stdin)")
60
+ parser.add_argument("--verify", action="store_true",
61
+ help="Render headlessly and print metrics (needs "
62
+ "vs2convert[render])")
63
+ parser.add_argument("--dry-run", action="store_true",
64
+ help="Print the shader instead of writing it")
65
+ parser.add_argument("--force", action="store_true",
66
+ help="Convert past a capability gate (not past HLSL)")
67
+ parser.add_argument("--meta", metavar="FILE",
68
+ help="Shadertoy pass/channel metadata JSON")
69
+ parser.add_argument("--strict", action="store_true",
70
+ help="Exit 5 if the conversion is only UNVERIFIED")
71
+ parser.add_argument("-v", "--verbose", action="store_true",
72
+ help="Show every step and the full text of each note")
73
+ parser.add_argument("--version", action="version",
74
+ version="%(prog)s " + __version__)
75
+ args = parser.parse_args()
76
+
77
+ # --dry-run's contract is `the shader on stdout`, so the run's own
78
+ # output goes to stderr. Otherwise `vs2convert --dry-run x > out.frag`
79
+ # writes a file whose first lines are the status banner, and that is
80
+ # not valid GLSL.
81
+ r = Reporter(verbose=args.verbose,
82
+ stream=sys.stderr if args.dry_run else None)
83
+
84
+ # --- read -----------------------------------------------------------------
85
+ if args.source == "-":
86
+ source = sys.stdin.read()
87
+ source_path = None
88
+ name = "stdin"
89
+ if not args.output:
90
+ parser.error("OUTPUT is required when reading from stdin")
91
+ r.step("reading stdin")
92
+ else:
93
+ source_path = Path(args.source)
94
+ name = source_path.name
95
+ if not source_path.exists():
96
+ _fail(r, name, "input not found", [str(source_path)],
97
+ "check the path", 1)
98
+ source = source_path.read_text(encoding="utf-8")
99
+ r.step("reading %s" % source_path)
100
+
101
+ # --- metadata -------------------------------------------------------------
102
+ # Pass metadata is a Shadertoy concept. Loading it for every format made
103
+ # an ISF header look like pass metadata and let a stray .stmeta.json
104
+ # abort an ISF conversion.
105
+ meta = None
106
+ try:
107
+ fmt = detect_format(source).get("format")
108
+ except Exception:
109
+ fmt = None
110
+ if fmt in ("Shadertoy", "PlainGLSL"):
111
+ try:
112
+ meta, meta_from = load_meta(
113
+ str(source_path) if source_path else None, source, args.meta)
114
+ except (ValueError, OSError, json.JSONDecodeError) as exc:
115
+ _fail(r, name, "could not read pass metadata", [str(exc)],
116
+ "fix or omit --meta", 1)
117
+ if meta:
118
+ r.step("pass metadata from %s" % meta_from)
119
+ elif args.meta:
120
+ r.note("ignoring --meta: only Shadertoy sources use pass metadata")
121
+
122
+ # --- convert --------------------------------------------------------------
123
+ r.step("converting")
124
+ result = api.convert(source, name=source_path.stem if source_path else "stdin",
125
+ force=args.force, meta=meta)
126
+
127
+ if not result.ok:
128
+ _report_decline(r, name, result, source, sys.argv[1:])
129
+ sys.exit(3 if any(x.stage == "suitability" for x in result.rejections)
130
+ else 1)
131
+
132
+ for item in result.baked:
133
+ r.note("baked: %s" % item)
134
+ for item in result.warnings:
135
+ if item.startswith("UNVERIFIED"):
136
+ r.unverified(_short_unverified(item), _unverified_body(item))
137
+ r.detail(" " + item)
138
+ else:
139
+ r.note(item)
140
+ unverified = [w for w in result.warnings if w.startswith("UNVERIFIED")]
141
+
142
+ # --- output path ----------------------------------------------------------
143
+ if args.output:
144
+ output_path = Path(args.output)
145
+ else:
146
+ output_path = source_path.with_suffix(".frag")
147
+ # The guard must cover an explicit output too: `vs2convert in.fs in.fs`
148
+ # used to overwrite the source and report success.
149
+ if source_path is not None and \
150
+ output_path.resolve() == source_path.resolve():
151
+ _fail(r, name, "refusing to overwrite the input",
152
+ ["the output path is the input file"],
153
+ "pass a different output filename", 4)
154
+
155
+ stats = ["%s \u00b7 %d param%s" % (result.format, len(result.params),
156
+ "" if len(result.params) == 1 else "s")]
157
+ stats.append("validated")
158
+
159
+ # --- render verification --------------------------------------------------
160
+ if args.verify:
161
+ r.step("rendering")
162
+ try:
163
+ from .renderer.pipeline import run_verification
164
+ except ImportError:
165
+ _unavailable(r, name)
166
+ verification = run_verification(result.frag, output_path.stem)
167
+ if not verification["passed"]:
168
+ errs = verification["errors"]
169
+ if any("unavailable" in e for e in errs):
170
+ _unavailable(r, name, errs)
171
+ if any("could not create a GL context" in e for e in errs):
172
+ _unavailable(
173
+ r, name, errs,
174
+ "OpenGL is not working on this machine, so the shader "
175
+ "was not rendered")
176
+ compile_fail = any("compile" in e for e in errs)
177
+ _fail(r, name, "render check failed", _gate_lines(errs),
178
+ ("the output did not compile; this is a converter defect, "
179
+ "not a problem with your source" if compile_fail else
180
+ "it compiled but is not showing anything useful"), 1)
181
+ metrics = verification.get("metrics", {})
182
+ shown = ", ".join(
183
+ "%s %s" % (k, metrics[k])
184
+ for k in ("mean", "std", "alpha", "motion") if k in metrics)
185
+ stats.append("rendered (%s)" % shown if shown else "rendered")
186
+
187
+ # --- strict ---------------------------------------------------------------
188
+ if args.strict and unverified:
189
+ _fail(r, name, "UNVERIFIED under --strict",
190
+ ["the conversion rests on an assumption the tool could not check"],
191
+ "check the shader against its original, or drop --strict", 5)
192
+
193
+ # --- write ----------------------------------------------------------------
194
+ if args.dry_run:
195
+ r.success(name, wrote="(dry run, nothing written)", stats=stats)
196
+ print(file=r.out)
197
+ print(result.frag)
198
+ return 0
199
+
200
+ if not output_path.parent.exists():
201
+ _fail(r, name, "output directory does not exist",
202
+ [str(output_path.parent)], "pass a filename, not a path", 4)
203
+ try:
204
+ output_path.write_text(result.frag, encoding="utf-8")
205
+ except OSError as exc:
206
+ _fail(r, name, "could not write", [str(exc)], None, 4)
207
+
208
+ r.success(name, wrote=output_path.name, stats=stats)
209
+ return 0
210
+
211
+
212
+ def _report_decline(r, name, result, source, argv=None):
213
+ """One `stage/gate: reason` line per rejection, then its advice."""
214
+ code = 3 if any(x.stage == "suitability" for x in result.rejections) else 1
215
+ body = []
216
+ for rejection in result.rejections:
217
+ body.extend(_wrap("%s/%s: %s"
218
+ % (rejection.stage, rejection.gate,
219
+ rejection.reason)))
220
+ body.extend(_wrap(" " + rejection.detail))
221
+ r.failure(name, "declined", body=body,
222
+ action="fix the source, or convert it by hand", exit_code=code)
223
+ print(file=r.out)
224
+ print("Report this with the source: %s"
225
+ % _issue_url(name, result, source, argv), file=r.out)
226
+
227
+
228
+ def _issue_url(name, result, source, argv=None):
229
+ gates = ", ".join(sorted({x.gate for x in result.rejections}))
230
+ title = "Declined: %s (%s)" % (name, gates)
231
+ command = "vs2convert %s" % (shlex.join(argv) if argv else name)
232
+ lines = ["Command: %s" % command, "", "Rejections:"]
233
+ for rejection in result.rejections:
234
+ lines.append("- %s/%s: %s" % (rejection.stage, rejection.gate,
235
+ rejection.reason))
236
+ lines += ["", "Source (truncated):", source[:1500]]
237
+ body = "\n".join(lines)
238
+ return ISSUES_URL + "?" + urlencode({"title": title, "body": body})
239
+
240
+
241
+ def _unavailable(r, name, errs=None, action=None):
242
+ body = [str(e) for e in (errs or ["the render check could not run"])]
243
+ action = action or ("rendering needs moderngl+numpy+Pillow; "
244
+ "install vs2convert[render]")
245
+ r.skipped(name, "converted, but not verified", body=_wrap(body),
246
+ action=action, exit_code=2)
247
+ sys.exit(2)
248
+
249
+
250
+ def _fail(r, name, headline, body=None, action=None, code=1):
251
+ r.failure(name, headline, body=_wrap(body) if body else None,
252
+ action=action, exit_code=code)
253
+ sys.exit(code)
254
+
255
+
256
+ def _gate_lines(items, width=66):
257
+ """Render gate errors one per line. A GLSL compiler dump arrives as one
258
+ long blob and is unreadable when wrapped, so split it on its own line
259
+ breaks first."""
260
+ out = []
261
+ for it in items:
262
+ text = str(it)
263
+ if "ERROR:" in text or len(text) > 200:
264
+ parts = [p.strip() for p in text.replace("====", "\n").split("\n")]
265
+ for part in parts:
266
+ part = part.replace("ERROR: ", "")
267
+ part = re.sub(r"^(GLSL Compiler failed|fragment_shader|=+)$",
268
+ "", part)
269
+ part = part.strip()
270
+ if part:
271
+ out.extend(textwrap.wrap(part, width) or [part])
272
+ else:
273
+ out.extend(textwrap.wrap(text, width) or [text])
274
+ return out
275
+
276
+
277
+ def _wrap(items, width=66):
278
+ """Wrap one message or a list of them to a readable width."""
279
+ if isinstance(items, str):
280
+ items = [items]
281
+ out = []
282
+ for it in items:
283
+ out.extend(textwrap.wrap(str(it), width) or [""])
284
+ return out
285
+
286
+
287
+ def _short_unverified(text):
288
+ """One-line headline for the UNVERIFIED block."""
289
+ if "iChannel" in text:
290
+ return "iChannel assumed to be a plain image"
291
+ return text.split(":")[0][:60].strip()
292
+
293
+
294
+ def _unverified_body(text):
295
+ """Short plain-English consequence. The full text goes to stderr under -v,
296
+ so the default output stays scannable."""
297
+ if "iChannel" in text:
298
+ return ["Shadertoy channels can also be buffers, cubemaps, video or",
299
+ "audio (VS 2 has an audio sampler, fftTex, but no mapping",
300
+ "yet), and only the shader page says which. Check it there,",
301
+ "or add a <name>.stmeta.json beside the .txt."]
302
+ return _wrap([text])
303
+
304
+
305
+ if __name__ == "__main__":
306
+ sys.exit(main())
@@ -0,0 +1,5 @@
1
+ """
2
+ Core conversion modules - bundled rules for VS-2 shader conversion.
3
+
4
+ All rules are self-contained in this package. No external skill files needed.
5
+ """