merge ws/tex
This commit is contained in:
commit
93a5afbe65
63 files changed
+11009
-3
No files matched your search
@@ -5,17 +5,28 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
|
||||
|
||||
| Category | Format | Extensions | Read | Write | Capabilities | Test |
|
||||
|---|---|---|---|---|---|---|
|
||||
| image | ani | .ani | yes | yes | alpha: true, animation: true, frames: true | `tests/image/ani.luau` |
|
||||
| image | bmp | .bmp .dib | yes | yes | alpha: true, depths: 1, 2, 4, 8, 16, 24, 32, rle: true | `tests/image/bmp.luau` |
|
||||
| image | dds | .dds | yes | yes | alpha: true, float: true, mipmaps: true, cubemap: true, compressed: "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7" | `tests/image/dds.luau` |
|
||||
| image | exr | .exr | yes | yes | alpha: true, float: true, hdr: true, depths: 16, 32, multipart: true, tiled: true | `tests/image/exr.luau` |
|
||||
| image | gif | .gif | yes | yes | animation: true, alpha: true, palette: true, depths: 1, 2, 4, 8 | `tests/image/gif.luau` |
|
||||
| image | hdr | .hdr .pic .rgbe | yes | yes | alpha: false, float: true, depths: 32 | `tests/image/hdr.luau` |
|
||||
| image | icns | .icns | yes | yes | alpha: true, frames: true, depths: 1, 24, 32 | `tests/image/icns.luau` |
|
||||
| image | ico | .ico .cur | yes | yes | alpha: true, frames: true, depths: 1, 4, 8, 16, 24, 32 | `tests/image/ico.luau` |
|
||||
| image | ilbm | .iff .ilbm .lbm .pbm | yes | yes | alpha: true, palette: true, depths: 1, 2, 3, 4, 5, 6, 7, 8, 24, 32 | `tests/image/ilbm.luau` |
|
||||
| image | jpeg | .jpg .jpeg .jpe .jfif | yes | yes | lossy: true, alpha: false, depths: 8, 12, progressive: true, arithmetic: true | `tests/image/jpeg.luau` |
|
||||
| image | ktx | .ktx2 .ktx | yes | yes | alpha: true, float: true, mipmaps: true, cubemap: true, compressed: "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7", "etc1", "etc2", "eac" | `tests/image/ktx.luau` |
|
||||
| image | pcx | .pcx .pcc .dcx | yes | yes | alpha: true, palette: true, depths: 1, 2, 4, 8, 24, 32 | `tests/image/pcx.luau` |
|
||||
| image | png | .png .apng | yes | yes | animation: true, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` |
|
||||
| image | pnm | .pnm .pbm .pgm .ppm .pam .pfm | yes | yes | alpha: true, depths: 1, 8, 16, 32, float: true | `tests/image/pnm.luau` |
|
||||
| image | qoi | .qoi | yes | yes | alpha: true, depths: 8 | `tests/image/qoi.luau` |
|
||||
| image | sgi | .sgi .rgb .rgba .bw .int .inta | yes | yes | alpha: true, depths: 8, 16 | `tests/image/sgi.luau` |
|
||||
| image | sunras | .ras .sun .rs .im1 .im8 .im24 .im32 | yes | yes | alpha: true, palette: true, depths: 1, 8, 24, 32 | `tests/image/sunras.luau` |
|
||||
| image | tga | .tga .icb .vda .vst .tpic | yes | yes | alpha: true, palette: true, depths: 8, 15, 16, 24, 32 | `tests/image/tga.luau` |
|
||||
| image | tiff | .tif .tiff | yes | yes | alpha: true, pages: true, depths: 1, 2, 4, 8, 16, 32, float: true | `tests/image/tiff.luau` |
|
||||
| image | webp | .webp | yes | yes | animation: true, alpha: true, lossy: true, lossless: true, depths: 8 | `tests/image/webp.luau` |
|
||||
| image | xbm | .xbm .bm | yes | yes | depths: 1 | `tests/image/xbm.luau` |
|
||||
| image | xpm | .xpm .pm | yes | yes | alpha: true, palette: true, depths: 8 | `tests/image/xpm.luau` |
|
||||
| audio | aac | .aac .adts | yes | - | codecs: "aac", streaming: true | `tests/audio/aac.luau` |
|
||||
| audio | aiff | .aiff .aif .aifc .afc | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, lossy: false | `tests/audio/aiff.luau` |
|
||||
| audio | au | .au .snd | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, lossy: false | `tests/audio/au.luau` |
|
||||
@@ -91,6 +102,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
|
||||
| vector | svg | .svg | yes | yes | rasterize: true, text: false | `tests/vector/svg.luau` |
|
||||
| vector | tiled | .tmx .tmj .tsx .tsj | yes | yes | tilesets: true, infinite: true | `tests/vector/tiled.luau` |
|
||||
| layered | aseprite | .aseprite .ase | yes | yes | layers: true, groups: true, animation: true, depths: 8, 16, 32 | `tests/layered/aseprite.luau` |
|
||||
| layered | ora | .ora | yes | yes | layers: true, groups: true, depths: 8 | `tests/layered/ora.luau` |
|
||||
| layered | psd | .psd .psb | yes | yes | layers: true, groups: true, depths: 1, 8, 16, 32 | `tests/layered/psd.luau` |
|
||||
| subtitle | ass | .ass .ssa | yes | yes | styles: true | `tests/subtitle/ass.luau` |
|
||||
| subtitle | srt | .srt | yes | yes | styles: false | `tests/subtitle/srt.luau` |
|
||||
@@ -137,12 +149,17 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain:
|
||||
- codecs/font/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177): the outlines of OpenType fonts
|
||||
- codecs/font/TrueType: the sfnt font container (TrueType .ttf, OpenType .otf with CFF outlines, collections .ttc) parsed
|
||||
- **image**
|
||||
- codecs/image/Bcn: the BCn block-compressed texture codecs, shared by the texture formats (DDS, KTX, VTF, BLP, ...):
|
||||
- codecs/image/Blend: layer compositing on rgba8 buffers (straight alpha): source-over with the separable and non-separable
|
||||
- codecs/image/Dct: the 8x8 DCTs JPEG, Motion-JPEG and MPEG-1 share (native; never throws).
|
||||
- codecs/image/Etc: the Ericsson / Khronos block texture codecs, decode only: ETC1, ETC2 RGB (with the T, H and planar
|
||||
- codecs/image/Half: IEEE 754 binary16 ("half") <-> number, for the float texel formats (DDS / KTX R16F..., BC6H,
|
||||
- codecs/image/Jpeg: the JPEG codec (ITU T.81) on byte ranges: image/jpeg is a thin format over it, and the Motion-JPEG
|
||||
- codecs/image/Pixels: row loops between packed pixel layouts and rgba8 (native), shared by the bitmap formats (BMP,
|
||||
- codecs/image/Quantize: palette quantization of rgba8 pixels. A codec (layer 1): image/gif (and later any palette
|
||||
- codecs/image/Raster: an antialiased scanline rasterizer for paths of lines, quadratic and cubic Béziers, under an affine
|
||||
- codecs/image/Texel: uncompressed GPU texel formats -> the standard pixel formats, shared by the texture containers
|
||||
- codecs/image/Texture: one entry point over the texture pixel codecs for the texture containers (DDS, KTX, VTF, ...):
|
||||
- codecs/image/Vp8: the VP8 video codec (RFC 6386), decode only. A codec (layer 1): image/webp uses it for lossy frames, the
|
||||
- codecs/image/Vp8L: WebP lossless (VP8L, "WebP Lossless Bitstream Specification", RFC 9649 section 3). A codec (layer 1):
|
||||
- codecs/image/Yuv: planar 4:2:0 Y'CbCr <-> rgba8 for the video codecs and writers (native; never throws). BT.601 or
|
||||
|
||||
@@ -207,6 +207,42 @@ Read and write unless noted; see [FORMATS.md](../FORMATS.md) for depths and deta
|
||||
| TIFF | pages | yes | 1..32-bit, float |
|
||||
| BMP, TGA, QOI, ICO / CUR, PNM / PAM / PFM | ICO entries | yes | |
|
||||
| HDR | | no | float (`native` gives rgbaf32) |
|
||||
| DDS, KTX / KTX2 | faces / layers / slices | yes | GPU textures: BC1..BC7, ETC / EAC, every uncompressed layout; mips in `meta.mipmaps` |
|
||||
| OpenEXR | parts (`opts.part`) | yes | half / float / uint, NONE / RLE / ZIPS / ZIP / PIZ, tiles; writes NONE / ZIPS / ZIP |
|
||||
| PCX, SGI, Sun Raster, IFF ILBM / PBM, XPM, XBM | | yes (XBM 1-bit) | old paint / workstation formats; ILBM reads HAM and EHB |
|
||||
| ICNS, ANI | ICNS sizes / ANI steps | yes | PNG / ICO entries through the api hooks |
|
||||
|
||||
### Textures and HDR (DDS, KTX, EXR)
|
||||
|
||||
DDS and KTX files hold GPU textures: block-compressed (BC1..BC7, ETC1 / ETC2 / EAC) or plain texel layouts, with mip
|
||||
levels, cube faces and array layers. The image is the first surface; `img.frames` lists every face / layer / depth
|
||||
slice when there is more than one (`meta.layout` is `"2d"`, `"cube"`, `"array"` or `"volume"`), and with `opts.mips` the
|
||||
smaller levels of the first surface go to `meta.mipmaps`. Float and 16-bit sources keep their values with
|
||||
`opts.native` (`rgbaf32` / `rgba16`); otherwise they are clamped into `rgba8`. Writers pick the stored layout with
|
||||
`pixelFormat` (`format` is the file format): DDS writes `rgba8`, `bgra8`, `bc1`, `bc3`, `bc4`, `bc5`, `rgba16`,
|
||||
`rgba16f`, `rgba32f`; KTX2 writes the uncompressed ones.
|
||||
|
||||
```luau
|
||||
local img = assert(F.ops.image.new(64, 64))
|
||||
assert(F.ops.image.fill(img, 200, 120, 40, 255))
|
||||
local dds = assert(F.save(img, nil, { format = "dds", pixelFormat = "bc1", mips = true }))
|
||||
local tex = assert(F.load(dds, { mips = true }))
|
||||
assert(tex.meta.source.pixelFormat == "bc1" and #tex.meta.mipmaps == 6)
|
||||
local ktx = assert(F.save(img, nil, { format = "ktx", mips = true, zlib = 6 })) -- KTX2, ZLIB-supercompressed
|
||||
assert(F.detect(ktx) == "ktx")
|
||||
```
|
||||
|
||||
OpenEXR loads as linear floats with `opts.native` (`rgbaf32`); the default `rgba8` goes through the same 1 / 2.2
|
||||
display curve as Radiance HDR. `opts.part` picks a part of a multipart file, `opts.layer` reads `<layer>.R` / `.G` / ...
|
||||
|
||||
```luau
|
||||
local hdr = assert(F.ops.image.new(8, 8, "rgbaf32"))
|
||||
assert(F.ops.image.fill(hdr, 4, 2, 0.5, 1)) -- floats may exceed 1
|
||||
local exr = assert(F.save(hdr, nil, { format = "exr", compression = "zip", pixelType = "half" }))
|
||||
local linear = assert(F.load(exr, { native = true }))
|
||||
assert(linear.format == "rgbaf32" and math.abs(buffer.readf32(linear.pixels, 0) - 4) < 1e-3)
|
||||
assert(F.load(exr).format == "rgba8") -- the display conversion
|
||||
```
|
||||
|
||||
An animated image also opens as a video (`F.video.open(gifBytes)`), and saves to a video format
|
||||
(`F.convert(gifBytes, "avi")`): see [video.md](video.md).
|
||||
|
||||
+25
-3
@@ -1,8 +1,8 @@
|
||||
# Layered images (PSD, Aseprite)
|
||||
# Layered images (PSD, Aseprite, OpenRaster)
|
||||
|
||||
Photoshop documents and Aseprite sprites load as a `Layered`: a canvas size and a tree of layers, each with its own
|
||||
Photoshop documents, Aseprite sprites and OpenRaster files load as a `Layered`: a canvas size and a tree of layers, each with its own
|
||||
rgba8 [Image](image.md), position, opacity, blend mode and visibility. `F.ops.layers.flatten` composites the tree
|
||||
into one Image; `F.save` writes PSD or Aseprite, layers included. Aseprite animations also carry every frame's tree.
|
||||
into one Image; `F.save` writes PSD, Aseprite or OpenRaster, layers included. Aseprite animations also carry every frame's tree.
|
||||
|
||||
```luau
|
||||
local doc = assert(F.layered.load(psdBytes))
|
||||
@@ -230,6 +230,28 @@ assert(#back.frames == 4 and back.frames[3].layers[1].x == 3)
|
||||
|---|---|---|---|
|
||||
| PSD / PSB | 1 / 8 / 16 / 32-bit, every colour mode, layers, groups, masks, clipping | 8-bit RGB | adjustment, type and smart-object layers keep only their pixels; no layer effects |
|
||||
| Aseprite | RGBA, grayscale, indexed; frames, linked cels, tags, palette, user data | yes | tilemap layers are skipped (`meta.skipped`); slices not kept |
|
||||
| OpenRaster (ORA) | the stack tree (nested stacks = groups), offsets, opacity, visibility, svg composite-ops | yes | layers are PNGs through the api hooks; `meta.composite` = mergedimage.png |
|
||||
|
||||
### OpenRaster
|
||||
|
||||
An `.ora` file is a zip of PNG layers and a `stack.xml` tree (the format GIMP, Krita and MyPaint exchange). It loads
|
||||
like the others; nested `<stack>`s become groups (`isolation="auto"` is the `"passThrough"` blend). Saving writes every
|
||||
layer, the flattened `mergedimage.png` and a thumbnail.
|
||||
|
||||
```luau
|
||||
local doc = F.Types.Layered.new(32, 24)
|
||||
local base = assert(F.ops.image.new(32, 24))
|
||||
assert(F.ops.image.fill(base, 30, 60, 200, 255))
|
||||
local dot = assert(F.ops.image.new(8, 8))
|
||||
assert(F.ops.image.fill(dot, 255, 255, 0, 255))
|
||||
local top = F.Types.Layered.layer("dot", dot, 12, 8)
|
||||
top.blend, top.opacity = "screen", 0.5
|
||||
doc.layers = { F.Types.Layered.layer("base", base), top }
|
||||
local ora = assert(F.save(doc, nil, { format = "ora" }))
|
||||
local back = assert(F.layered.load(ora))
|
||||
assert(#back.layers == 2 and back.layers[2].blend == "screen" and back.layers[2].x == 12)
|
||||
assert(back.meta.composite.width == 32) -- mergedimage.png
|
||||
```
|
||||
|
||||
See [FORMATS.md](../FORMATS.md) for the capability matrix.
|
||||
|
||||
|
||||
@@ -44,6 +44,8 @@
|
||||
| `tests/gen/h264_jvt` (downloaded at fixture time, not committed) | ITU-T H.264.1 / JVT conformance bitstreams (itu.int) | ITU-T test data |
|
||||
| `src/Formats/model/ldraw/Colors.luau` (the built-in colour table) | the !COLOUR list of LDConfig.ldr (LDraw.org Parts Library, UPDATE 2025-05-20), reformatted | CC BY 2.0 / CC BY 4.0: [LDRAW_COLOURS.txt](LDRAW_COLOURS.txt) |
|
||||
| `tests/gen/ldraw_*` (read at fixture time from the nix store, not committed) | LDraw.org Parts Library parts and sample models (complete.zip, as packaged for nixpkgs' LeoCAD) | CC BY 2.0 / CC BY 4.0, test data |
|
||||
| `src/Formats/codecs/image/Bcn/Decode.luau` (the BC1..BC7 block decoders and the BPTC tables; changed to follow the D3D11 rules) | Pillow 12 `src/libImaging/BcnDecode.c` | CC0 1.0: [pillow-bcn-CC0.txt](pillow-bcn-CC0.txt) |
|
||||
| `src/Formats/image/exr/Piz.luau`, `src/Formats/image/exr/Codec.luau` (the PIZ Huffman / wavelet / LUT steps and the ZIP / RLE byte predictor, re-implemented in Luau after the OpenEXR algorithms) | OpenEXR 3.x (ImfPizCompressor, ImfHuf, ImfWav, ImfZip, ImfRle) | BSD-3-Clause: [openexr-LICENSE.md](openexr-LICENSE.md) |
|
||||
|
||||
Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this
|
||||
folder (see docs/STYLE.md, "Absorbing an existing repo").
|
||||
@@ -0,0 +1,11 @@
|
||||
Copyright (c) Contributors to the OpenEXR Project. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
||||
|
||||
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
@@ -0,0 +1,134 @@
|
||||
Pillow src/libImaging/BcnDecode.c (https://github.com/python-pillow/Pillow), file header:
|
||||
|
||||
/*
|
||||
* The Python Imaging Library
|
||||
*
|
||||
* decoder for DXTn-compressed data
|
||||
*
|
||||
* Format documentation:
|
||||
* https://web.archive.org/web/20170802060935/http://oss.sgi.com/projects/ogl-sample/registry/EXT/texture_compression_s3tc.txt
|
||||
*
|
||||
* The contents of this file are in the public domain (CC0)
|
||||
* Full text of the CC0 license:
|
||||
* https://creativecommons.org/publicdomain/zero/1.0/
|
||||
*/
|
||||
|
||||
The full CC0 1.0 text follows.
|
||||
|
||||
CC0 1.0 Universal
|
||||
|
||||
Statement of Purpose
|
||||
|
||||
The laws of most jurisdictions throughout the world automatically confer
|
||||
exclusive Copyright and Related Rights (defined below) upon the creator and
|
||||
subsequent owner(s) (each and all, an "owner") of an original work of
|
||||
authorship and/or a database (each, a "Work").
|
||||
|
||||
Certain owners wish to permanently relinquish those rights to a Work for the
|
||||
purpose of contributing to a commons of creative, cultural and scientific
|
||||
works ("Commons") that the public can reliably and without fear of later
|
||||
claims of infringement build upon, modify, incorporate in other works, reuse
|
||||
and redistribute as freely as possible in any form whatsoever and for any
|
||||
purposes, including without limitation commercial purposes. These owners may
|
||||
contribute to the Commons to promote the ideal of a free culture and the
|
||||
further production of creative, cultural and scientific works, or to gain
|
||||
reputation or greater distribution for their Work in part through the use and
|
||||
efforts of others.
|
||||
|
||||
For these and/or other purposes and motivations, and without any expectation
|
||||
of additional consideration or compensation, the person associating CC0 with a
|
||||
Work (the "Affirmer"), to the extent that he or she is an owner of Copyright
|
||||
and Related Rights in the Work, voluntarily elects to apply CC0 to the Work
|
||||
and publicly distribute the Work under its terms, with knowledge of his or her
|
||||
Copyright and Related Rights in the Work and the meaning and intended legal
|
||||
effect of CC0 on those rights.
|
||||
|
||||
1. Copyright and Related Rights. A Work made available under CC0 may be
|
||||
protected by copyright and related or neighboring rights ("Copyright and
|
||||
Related Rights"). Copyright and Related Rights include, but are not limited
|
||||
to, the following:
|
||||
|
||||
i. the right to reproduce, adapt, distribute, perform, display, communicate,
|
||||
and translate a Work;
|
||||
|
||||
ii. moral rights retained by the original author(s) and/or performer(s);
|
||||
|
||||
iii. publicity and privacy rights pertaining to a person's image or likeness
|
||||
depicted in a Work;
|
||||
|
||||
iv. rights protecting against unfair competition in regards to a Work,
|
||||
subject to the limitations in paragraph 4(a), below;
|
||||
|
||||
v. rights protecting the extraction, dissemination, use and reuse of data in
|
||||
a Work;
|
||||
|
||||
vi. database rights (such as those arising under Directive 96/9/EC of the
|
||||
European Parliament and of the Council of 11 March 1996 on the legal
|
||||
protection of databases, and under any national implementation thereof,
|
||||
including any amended or successor version of such directive); and
|
||||
|
||||
vii. other similar, equivalent or corresponding rights throughout the world
|
||||
based on applicable law or treaty, and any national implementations thereof.
|
||||
|
||||
2. Waiver. To the greatest extent permitted by, but not in contravention of,
|
||||
applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and
|
||||
unconditionally waives, abandons, and surrenders all of Affirmer's Copyright
|
||||
and Related Rights and associated claims and causes of action, whether now
|
||||
known or unknown (including existing as well as future claims and causes of
|
||||
action), in the Work (i) in all territories worldwide, (ii) for the maximum
|
||||
duration provided by applicable law or treaty (including future time
|
||||
extensions), (iii) in any current or future medium and for any number of
|
||||
copies, and (iv) for any purpose whatsoever, including without limitation
|
||||
commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes
|
||||
the Waiver for the benefit of each member of the public at large and to the
|
||||
detriment of Affirmer's heirs and successors, fully intending that such Waiver
|
||||
shall not be subject to revocation, rescission, cancellation, termination, or
|
||||
any other legal or equitable action to disrupt the quiet enjoyment of the Work
|
||||
by the public as contemplated by Affirmer's express Statement of Purpose.
|
||||
|
||||
3. Public License Fallback. Should any part of the Waiver for any reason be
|
||||
judged legally invalid or ineffective under applicable law, then the Waiver
|
||||
shall be preserved to the maximum extent permitted taking into account
|
||||
Affirmer's express Statement of Purpose. In addition, to the extent the Waiver
|
||||
is so judged Affirmer hereby grants to each affected person a royalty-free,
|
||||
non transferable, non sublicensable, non exclusive, irrevocable and
|
||||
unconditional license to exercise Affirmer's Copyright and Related Rights in
|
||||
the Work (i) in all territories worldwide, (ii) for the maximum duration
|
||||
provided by applicable law or treaty (including future time extensions), (iii)
|
||||
in any current or future medium and for any number of copies, and (iv) for any
|
||||
purpose whatsoever, including without limitation commercial, advertising or
|
||||
promotional purposes (the "License"). The License shall be deemed effective as
|
||||
of the date CC0 was applied by Affirmer to the Work. Should any part of the
|
||||
License for any reason be judged legally invalid or ineffective under
|
||||
applicable law, such partial invalidity or ineffectiveness shall not
|
||||
invalidate the remainder of the License, and in such case Affirmer hereby
|
||||
affirms that he or she will not (i) exercise any of his or her remaining
|
||||
Copyright and Related Rights in the Work or (ii) assert any associated claims
|
||||
and causes of action with respect to the Work, in either case contrary to
|
||||
Affirmer's express Statement of Purpose.
|
||||
|
||||
4. Limitations and Disclaimers.
|
||||
|
||||
a. No trademark or patent rights held by Affirmer are waived, abandoned,
|
||||
surrendered, licensed or otherwise affected by this document.
|
||||
|
||||
b. Affirmer offers the Work as-is and makes no representations or warranties
|
||||
of any kind concerning the Work, express, implied, statutory or otherwise,
|
||||
including without limitation warranties of title, merchantability, fitness
|
||||
for a particular purpose, non infringement, or the absence of latent or
|
||||
other defects, accuracy, or the present or absence of errors, whether or not
|
||||
discoverable, all to the greatest extent permissible under applicable law.
|
||||
|
||||
c. Affirmer disclaims responsibility for clearing rights of other persons
|
||||
that may apply to the Work or any use thereof, including without limitation
|
||||
any person's Copyright and Related Rights in the Work. Further, Affirmer
|
||||
disclaims responsibility for obtaining any necessary consents, permissions
|
||||
or other rights required for any use of the Work.
|
||||
|
||||
d. Affirmer understands and acknowledges that Creative Commons is not a
|
||||
party to this document and has no duty or obligation with respect to this
|
||||
CC0 or use of the Work.
|
||||
|
||||
For more information, please see
|
||||
<http://creativecommons.org/publicdomain/zero/1.0/>
|
||||
|
||||
@@ -14,6 +14,18 @@ export type Entry = {
|
||||
}
|
||||
|
||||
local list: { Entry } = {
|
||||
{
|
||||
name = "ani",
|
||||
category = "image",
|
||||
path = "image/ani",
|
||||
extensions = { "ani" },
|
||||
mime = { "application/x-navi-animation" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Riff" },
|
||||
caps = { decode = true, encode = true, alpha = true, animation = true, frames = true },
|
||||
load = function()
|
||||
return require("@formats/image/ani")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "bmp",
|
||||
category = "image",
|
||||
@@ -26,6 +38,30 @@ local list: { Entry } = {
|
||||
return require("@formats/image/bmp")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "dds",
|
||||
category = "image",
|
||||
path = "image/dds",
|
||||
extensions = { "dds" },
|
||||
mime = { "image/vnd-ms.dds", "image/x-dds" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Bcn", "codecs/image/Texel", "codecs/image/Texture" },
|
||||
caps = { decode = true, encode = true, alpha = true, float = true, mipmaps = true, cubemap = true, compressed = { "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7" } },
|
||||
load = function()
|
||||
return require("@formats/image/dds")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "exr",
|
||||
category = "image",
|
||||
path = "image/exr",
|
||||
extensions = { "exr" },
|
||||
mime = { "image/x-exr", "image/aces" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Half", "codecs/compress/Deflate" },
|
||||
caps = { decode = true, encode = true, alpha = true, float = true, hdr = true, depths = { 16, 32 }, multipart = true, tiled = true },
|
||||
load = function()
|
||||
return require("@formats/image/exr")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "gif",
|
||||
category = "image",
|
||||
@@ -50,6 +86,18 @@ local list: { Entry } = {
|
||||
return require("@formats/image/hdr")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "icns",
|
||||
category = "image",
|
||||
path = "image/icns",
|
||||
extensions = { "icns" },
|
||||
mime = { "image/icns", "image/x-icns" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "containers/Chunks" },
|
||||
caps = { decode = true, encode = true, alpha = true, frames = true, depths = { 1, 24, 32 } },
|
||||
load = function()
|
||||
return require("@formats/image/icns")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "ico",
|
||||
category = "image",
|
||||
@@ -62,6 +110,18 @@ local list: { Entry } = {
|
||||
return require("@formats/image/ico")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "ilbm",
|
||||
category = "image",
|
||||
path = "image/ilbm",
|
||||
extensions = { "iff", "ilbm", "lbm", "pbm" },
|
||||
mime = { "image/x-ilbm", "image/x-iff" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/compress/PackBits", "codecs/image/Pixels" },
|
||||
caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 2, 3, 4, 5, 6, 7, 8, 24, 32 } },
|
||||
load = function()
|
||||
return require("@formats/image/ilbm")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "jpeg",
|
||||
category = "image",
|
||||
@@ -74,6 +134,30 @@ local list: { Entry } = {
|
||||
return require("@formats/image/jpeg")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "ktx",
|
||||
category = "image",
|
||||
path = "image/ktx",
|
||||
extensions = { "ktx2", "ktx" },
|
||||
mime = { "image/ktx2", "image/ktx" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/compress/Deflate", "codecs/compress/Zstd", "codecs/image/Texel", "codecs/image/Texture" },
|
||||
caps = { decode = true, encode = true, alpha = true, float = true, mipmaps = true, cubemap = true, compressed = { "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7", "etc1", "etc2", "eac" } },
|
||||
load = function()
|
||||
return require("@formats/image/ktx")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "pcx",
|
||||
category = "image",
|
||||
path = "image/pcx",
|
||||
extensions = { "pcx", "pcc", "dcx" },
|
||||
mime = { "image/vnd.zbrush.pcx", "image/x-pcx" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Pixels" },
|
||||
caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 2, 4, 8, 24, 32 } },
|
||||
load = function()
|
||||
return require("@formats/image/pcx")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "png",
|
||||
category = "image",
|
||||
@@ -110,6 +194,30 @@ local list: { Entry } = {
|
||||
return require("@formats/image/qoi")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "sgi",
|
||||
category = "image",
|
||||
path = "image/sgi",
|
||||
extensions = { "sgi", "rgb", "rgba", "bw", "int", "inta" },
|
||||
mime = { "image/sgi", "image/x-rgb" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" },
|
||||
caps = { decode = true, encode = true, alpha = true, depths = { 8, 16 } },
|
||||
load = function()
|
||||
return require("@formats/image/sgi")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "sunras",
|
||||
category = "image",
|
||||
path = "image/sunras",
|
||||
extensions = { "ras", "sun", "rs", "im1", "im8", "im24", "im32" },
|
||||
mime = { "image/x-sun-raster", "image/x-cmu-raster" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Pixels" },
|
||||
caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 8, 24, 32 } },
|
||||
load = function()
|
||||
return require("@formats/image/sunras")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "tga",
|
||||
category = "image",
|
||||
@@ -146,6 +254,30 @@ local list: { Entry } = {
|
||||
return require("@formats/image/webp")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "xbm",
|
||||
category = "image",
|
||||
path = "image/xbm",
|
||||
extensions = { "xbm", "bm" },
|
||||
mime = { "image/x-xbitmap", "image/x-xbm" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" },
|
||||
caps = { decode = true, encode = true, depths = { 1 } },
|
||||
load = function()
|
||||
return require("@formats/image/xbm")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "xpm",
|
||||
category = "image",
|
||||
path = "image/xpm",
|
||||
extensions = { "xpm", "pm" },
|
||||
mime = { "image/x-xpixmap", "image/x-xpm" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" },
|
||||
caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 8 } },
|
||||
load = function()
|
||||
return require("@formats/image/xpm")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "aac",
|
||||
category = "audio",
|
||||
@@ -1046,6 +1178,18 @@ local list: { Entry } = {
|
||||
return require("@formats/layered/aseprite")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "ora",
|
||||
category = "layered",
|
||||
path = "layered/ora",
|
||||
extensions = { "ora" },
|
||||
mime = { "image/openraster" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Zip", "codecs/text/Xml", "codecs/image/Blend" },
|
||||
caps = { decode = true, encode = true, layers = true, groups = true, depths = { 8 } },
|
||||
load = function()
|
||||
return require("@formats/layered/ora")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "psd",
|
||||
category = "layered",
|
||||
|
||||
@@ -0,0 +1,498 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/image/Bcn/Decode: the BC1..BC7 block decoders (S3TC / DXT1-5, RGTC, BPTC). Ported from Pillow's
|
||||
-- src/libImaging/BcnDecode.c (CC0, licenses/pillow-bcn-CC0.txt) and changed to follow the D3D11 functional spec where
|
||||
-- Pillow does not: BC6H interpolation rounds ((a * (64 - w) + b * w + 32) >> 6), BC6H keeps its float values (no 8-bit
|
||||
-- clamp), BC7's reserved mode 8 and BC6H's reserved modes decode to transparent / zero, BC4 / BC5 SNORM interpolate
|
||||
-- the signed values (-128 reads as -127). Each decoder writes one 4x4 block into a 64-byte (rgba8) or 256-byte
|
||||
-- (rgbaf32) scratch block; the caller clips it into the image. Never throws: the caller checks the source size.
|
||||
local Half = require("@formats/codecs/image/Half")
|
||||
|
||||
local Decode = {}
|
||||
|
||||
local readu8, readu16, readu32, writeu8, writeu32, writef32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32, buffer.writef32
|
||||
local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift
|
||||
local HALF = Half.TABLE
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ BC1 / BC2 / BC3
|
||||
local pal = buffer.create(16) -- 4 rgba8 colours
|
||||
|
||||
local function c565(c: number): (number, number, number)
|
||||
local r = rshift(band(c, 0xF800), 8)
|
||||
local g = rshift(band(c, 0x7E0), 3)
|
||||
local b = lshift(band(c, 0x1F), 3)
|
||||
return bor(r, rshift(r, 5)), bor(g, rshift(g, 6)), bor(b, rshift(b, 5))
|
||||
end
|
||||
|
||||
-- the BC1 colour block at p into blk (64 bytes); fourColour = BC2 / BC3 (always the 4-colour palette)
|
||||
local function colour(src: buffer, p: number, blk: buffer, fourColour: boolean)
|
||||
local c0, c1 = readu16(src, p), readu16(src, p + 2)
|
||||
local r0, g0, b0 = c565(c0)
|
||||
local r1, g1, b1 = c565(c1)
|
||||
writeu32(pal, 0, r0 + g0 * 256 + b0 * 65536 + 0xFF000000)
|
||||
writeu32(pal, 4, r1 + g1 * 256 + b1 * 65536 + 0xFF000000)
|
||||
if c0 > c1 or fourColour then
|
||||
writeu32(pal, 8, (2 * r0 + r1) // 3 + ((2 * g0 + g1) // 3) * 256 + ((2 * b0 + b1) // 3) * 65536 + 0xFF000000)
|
||||
writeu32(pal, 12, (r0 + 2 * r1) // 3 + ((g0 + 2 * g1) // 3) * 256 + ((b0 + 2 * b1) // 3) * 65536 + 0xFF000000)
|
||||
else
|
||||
writeu32(pal, 8, (r0 + r1) // 2 + ((g0 + g1) // 2) * 256 + ((b0 + b1) // 2) * 65536 + 0xFF000000)
|
||||
writeu32(pal, 12, 0)
|
||||
end
|
||||
local idx = readu32(src, p + 4)
|
||||
for i = 0, 15 do
|
||||
writeu32(blk, i * 4, readu32(pal, band(rshift(idx, i * 2), 3) * 4))
|
||||
end
|
||||
end
|
||||
|
||||
-- the 8 values of a BC3 alpha / BC4 block (unsigned) into vals
|
||||
local vals = table.create(8, 0)
|
||||
local function ramp8(a0: number, a1: number)
|
||||
vals[1], vals[2] = a0, a1
|
||||
if a0 > a1 then
|
||||
for i = 1, 6 do
|
||||
vals[i + 2] = ((7 - i) * a0 + i * a1) // 7
|
||||
end
|
||||
else
|
||||
for i = 1, 4 do
|
||||
vals[i + 2] = ((5 - i) * a0 + i * a1) // 5
|
||||
end
|
||||
vals[7], vals[8] = 0, 255
|
||||
end
|
||||
end
|
||||
|
||||
-- signed (SNORM) ramp, values -127..127 rounded to the nearest integer, biased by 128 into 1..255
|
||||
local function ramp8s(u0: number, u1: number)
|
||||
local s0: number = math.max(if u0 >= 128 then u0 - 256 else u0, -127)
|
||||
local s1: number = math.max(if u1 >= 128 then u1 - 256 else u1, -127)
|
||||
vals[1], vals[2] = s0 + 128, s1 + 128
|
||||
if s0 > s1 then
|
||||
for i = 1, 6 do
|
||||
vals[i + 2] = math.floor(((7 - i) * s0 + i * s1) / 7 + 0.5) + 128
|
||||
end
|
||||
else
|
||||
for i = 1, 4 do
|
||||
vals[i + 2] = math.floor(((5 - i) * s0 + i * s1) / 5 + 0.5) + 128
|
||||
end
|
||||
vals[7], vals[8] = 1, 255
|
||||
end
|
||||
end
|
||||
|
||||
-- one 8-byte BC3 alpha / BC4 block at p into byte `channel` of every blk pixel (and the next ones when spread)
|
||||
local function single(src: buffer, p: number, blk: buffer, channel: number, signed: boolean, spread: boolean)
|
||||
if signed then
|
||||
ramp8s(readu8(src, p), readu8(src, p + 1))
|
||||
else
|
||||
ramp8(readu8(src, p), readu8(src, p + 1))
|
||||
end
|
||||
local lo = readu8(src, p + 2) + readu8(src, p + 3) * 256 + readu8(src, p + 4) * 65536
|
||||
local hi = readu8(src, p + 5) + readu8(src, p + 6) * 256 + readu8(src, p + 7) * 65536
|
||||
for i = 0, 15 do
|
||||
local sel = if i < 8 then band(rshift(lo, i * 3), 7) else band(rshift(hi, (i - 8) * 3), 7)
|
||||
local v = vals[sel + 1]
|
||||
local o = i * 4
|
||||
if spread then
|
||||
writeu32(blk, o, v + v * 256 + v * 65536 + 0xFF000000)
|
||||
else
|
||||
writeu8(blk, o + channel, v)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function Decode.bc1(src: buffer, p: number, blk: buffer)
|
||||
colour(src, p, blk, false)
|
||||
end
|
||||
|
||||
function Decode.bc2(src: buffer, p: number, blk: buffer)
|
||||
colour(src, p + 8, blk, true)
|
||||
for i = 0, 15 do
|
||||
local a = band(rshift(readu8(src, p + rshift(i, 1)), band(i, 1) * 4), 15)
|
||||
writeu8(blk, i * 4 + 3, a * 17)
|
||||
end
|
||||
end
|
||||
|
||||
function Decode.bc3(src: buffer, p: number, blk: buffer)
|
||||
colour(src, p + 8, blk, true)
|
||||
single(src, p, blk, 3, false, false)
|
||||
end
|
||||
|
||||
function Decode.bc4(src: buffer, p: number, blk: buffer)
|
||||
single(src, p, blk, 0, false, true)
|
||||
end
|
||||
|
||||
function Decode.bc4s(src: buffer, p: number, blk: buffer)
|
||||
single(src, p, blk, 0, true, true)
|
||||
end
|
||||
|
||||
local function bc5(src: buffer, p: number, blk: buffer, signed: boolean)
|
||||
for i = 0, 15 do
|
||||
writeu32(blk, i * 4, 0xFF000000)
|
||||
end
|
||||
single(src, p, blk, 0, signed, false)
|
||||
single(src, p + 8, blk, 1, signed, false)
|
||||
end
|
||||
function Decode.bc5(src: buffer, p: number, blk: buffer)
|
||||
bc5(src, p, blk, false)
|
||||
end
|
||||
function Decode.bc5s(src: buffer, p: number, blk: buffer)
|
||||
bc5(src, p, blk, true)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ BPTC tables
|
||||
-- partition tables (BC7 Table.P2 1 bit per pixel, Table.P3 2 bits per pixel) and the anchor indices
|
||||
local SI2 = {
|
||||
0xcccc, 0x8888, 0xeeee, 0xecc8, 0xc880, 0xfeec, 0xfec8, 0xec80, 0xc800, 0xffec, 0xfe80, 0xe800, 0xffe8, 0xff00, 0xfff0, 0xf000,
|
||||
0xf710, 0x008e, 0x7100, 0x08ce, 0x008c, 0x7310, 0x3100, 0x8cce, 0x088c, 0x3110, 0x6666, 0x366c, 0x17e8, 0x0ff0, 0x718e, 0x399c,
|
||||
0xaaaa, 0xf0f0, 0x5a5a, 0x33cc, 0x3c3c, 0x55aa, 0x9696, 0xa55a, 0x73ce, 0x13c8, 0x324c, 0x3bdc, 0x6996, 0xc33c, 0x9966, 0x0660,
|
||||
0x0272, 0x04e4, 0x4e40, 0x2720, 0xc936, 0x936c, 0x39c6, 0x639c, 0x9336, 0x9cc6, 0x817e, 0xe718, 0xccf0, 0x0fcc, 0x7744, 0xee22,
|
||||
}
|
||||
local SI3 = {
|
||||
0xaa685050, 0x6a5a5040, 0x5a5a4200, 0x5450a0a8, 0xa5a50000, 0xa0a05050, 0x5555a0a0, 0x5a5a5050, 0xaa550000, 0xaa555500,
|
||||
0xaaaa5500, 0x90909090, 0x94949494, 0xa4a4a4a4, 0xa9a59450, 0x2a0a4250, 0xa5945040, 0x0a425054, 0xa5a5a500, 0x55a0a0a0,
|
||||
0xa8a85454, 0x6a6a4040, 0xa4a45000, 0x1a1a0500, 0x0050a4a4, 0xaaa59090, 0x14696914, 0x69691400, 0xa08585a0, 0xaa821414,
|
||||
0x50a4a450, 0x6a5a0200, 0xa9a58000, 0x5090a0a8, 0xa8a09050, 0x24242424, 0x00aa5500, 0x24924924, 0x24499224, 0x50a50a50,
|
||||
0x500aa550, 0xaaaa4444, 0x66660000, 0xa5a0a5a0, 0x50a050a0, 0x69286928, 0x44aaaa44, 0x66666600, 0xaa444444, 0x54a854a8,
|
||||
0x95809580, 0x96969600, 0xa85454a8, 0x80959580, 0xaa141414, 0x96960000, 0xaaaa1414, 0xa05050a0, 0xa0a5a5a0, 0x96000000,
|
||||
0x40804080, 0xa9a8a9a8, 0xaaaaaa44, 0x2a4a5254,
|
||||
}
|
||||
local AI0 = {
|
||||
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 2, 8, 2, 2, 8, 8, 15, 2, 8, 2, 2, 8, 8, 2, 2,
|
||||
15, 15, 6, 8, 2, 8, 15, 15, 2, 8, 2, 2, 2, 15, 15, 6, 6, 2, 6, 8, 15, 15, 2, 2, 15, 15, 15, 15, 15, 2, 2, 15,
|
||||
}
|
||||
local AI1 = {
|
||||
3, 3, 15, 15, 8, 3, 15, 15, 8, 8, 6, 6, 6, 5, 3, 3, 3, 3, 8, 15, 3, 3, 6, 10, 5, 8, 8, 6, 8, 5, 15, 15,
|
||||
8, 15, 3, 5, 6, 10, 8, 15, 15, 3, 15, 5, 15, 15, 15, 15, 3, 15, 5, 5, 5, 8, 5, 10, 5, 10, 8, 13, 15, 12, 3, 3,
|
||||
}
|
||||
local AI2 = {
|
||||
15, 8, 8, 3, 15, 15, 3, 8, 15, 15, 15, 15, 15, 15, 15, 8, 15, 8, 15, 3, 15, 8, 15, 8, 3, 15, 6, 10, 15, 15, 10, 8,
|
||||
15, 3, 15, 10, 10, 8, 9, 10, 6, 15, 8, 15, 3, 6, 6, 8, 15, 3, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 3, 15, 15, 8,
|
||||
}
|
||||
local W2 = { [0] = 0, 21, 43, 64 }
|
||||
local W3 = { [0] = 0, 9, 18, 27, 37, 46, 55, 64 }
|
||||
local W4 = { [0] = 0, 4, 9, 13, 17, 21, 26, 30, 34, 38, 43, 47, 51, 55, 60, 64 }
|
||||
local WEIGHTS = { [2] = W2, [3] = W3, [4] = W4 }
|
||||
Decode.SI2, Decode.SI3, Decode.AI0, Decode.AI1, Decode.AI2, Decode.WEIGHTS = SI2, SI3, AI0, AI1, AI2, WEIGHTS
|
||||
|
||||
local function subset(ns: number, part: number, i: number): number
|
||||
if ns == 2 then
|
||||
return band(rshift(SI2[part + 1], i), 1)
|
||||
elseif ns == 3 then
|
||||
return band(rshift(SI3[part + 1], 2 * i), 3)
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- the 128-bit block as four u32 words: bits(at, n) for n <= 16
|
||||
local w0, w1, w2, w3 = 0, 0, 0, 0
|
||||
local function load(src: buffer, p: number)
|
||||
w0, w1, w2, w3 = readu32(src, p), readu32(src, p + 4), readu32(src, p + 8), readu32(src, p + 12)
|
||||
end
|
||||
local function word(i: number): number
|
||||
return if i == 0 then w0 elseif i == 1 then w1 elseif i == 2 then w2 else w3
|
||||
end
|
||||
local function bits(at: number, n: number): number
|
||||
if n == 0 then
|
||||
return 0
|
||||
end
|
||||
local wi, sh = rshift(at, 5), band(at, 31)
|
||||
local v = rshift(word(wi), sh)
|
||||
if sh + n > 32 and wi < 3 then
|
||||
v = bor(v, lshift(word(wi + 1), 32 - sh))
|
||||
end
|
||||
return band(v, lshift(1, n) - 1)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ BC7
|
||||
-- ns, pb, rb, isb, cb, ab, epb, spb, ib, ib2
|
||||
local MODES7 = {
|
||||
{ 3, 4, 0, 0, 4, 0, 1, 0, 3, 0 },
|
||||
{ 2, 6, 0, 0, 6, 0, 0, 1, 3, 0 },
|
||||
{ 3, 6, 0, 0, 5, 0, 0, 0, 2, 0 },
|
||||
{ 2, 6, 0, 0, 7, 0, 1, 0, 2, 0 },
|
||||
{ 1, 0, 2, 1, 5, 6, 0, 0, 2, 3 },
|
||||
{ 1, 0, 2, 0, 7, 8, 0, 0, 2, 2 },
|
||||
{ 1, 0, 0, 0, 7, 7, 1, 0, 4, 0 },
|
||||
{ 2, 6, 0, 0, 5, 5, 1, 0, 2, 0 },
|
||||
}
|
||||
local er, eg, eb, ea = table.create(6, 0), table.create(6, 0), table.create(6, 0), table.create(6, 0)
|
||||
|
||||
local function expand(v: number, n: number): number
|
||||
v = band(lshift(v, 8 - n), 255)
|
||||
return bor(v, rshift(v, n))
|
||||
end
|
||||
|
||||
function Decode.bc7(src: buffer, p: number, blk: buffer)
|
||||
local m0 = readu8(src, p)
|
||||
if m0 == 0 then
|
||||
buffer.fill(blk, 0, 0, 64)
|
||||
return
|
||||
end
|
||||
load(src, p)
|
||||
local mode = 0
|
||||
while band(m0, lshift(1, mode)) == 0 do
|
||||
mode += 1
|
||||
end
|
||||
local info = MODES7[mode + 1]
|
||||
local ns, pb, rb, isb, cb, ab, epb, spb, ib, ib2 = info[1], info[2], info[3], info[4], info[5], info[6], info[7], info[8], info[9], info[10]
|
||||
local bit = mode + 1
|
||||
local part = bits(bit, pb)
|
||||
bit += pb
|
||||
local rot = bits(bit, rb)
|
||||
bit += rb
|
||||
local sel = bits(bit, isb)
|
||||
bit += isb
|
||||
local nep = ns * 2
|
||||
for i = 1, nep do
|
||||
er[i] = bits(bit, cb)
|
||||
bit += cb
|
||||
end
|
||||
for i = 1, nep do
|
||||
eg[i] = bits(bit, cb)
|
||||
bit += cb
|
||||
end
|
||||
for i = 1, nep do
|
||||
eb[i] = bits(bit, cb)
|
||||
bit += cb
|
||||
end
|
||||
for i = 1, nep do
|
||||
if ab > 0 then
|
||||
ea[i] = bits(bit, ab)
|
||||
bit += ab
|
||||
else
|
||||
ea[i] = 255
|
||||
end
|
||||
end
|
||||
if epb == 1 then
|
||||
cb += 1
|
||||
if ab > 0 then
|
||||
ab += 1
|
||||
end
|
||||
for i = 1, nep do
|
||||
local v = bits(bit, 1)
|
||||
bit += 1
|
||||
er[i], eg[i], eb[i] = er[i] * 2 + v, eg[i] * 2 + v, eb[i] * 2 + v
|
||||
if ab > 0 then
|
||||
ea[i] = ea[i] * 2 + v
|
||||
end
|
||||
end
|
||||
end
|
||||
if spb == 1 then
|
||||
cb += 1
|
||||
if ab > 0 then
|
||||
ab += 1
|
||||
end
|
||||
for i = 1, nep, 2 do
|
||||
local v = bits(bit, 1)
|
||||
bit += 1
|
||||
for j = i, i + 1 do
|
||||
er[j], eg[j], eb[j] = er[j] * 2 + v, eg[j] * 2 + v, eb[j] * 2 + v
|
||||
if ab > 0 then
|
||||
ea[j] = ea[j] * 2 + v
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
for i = 1, nep do
|
||||
er[i], eg[i], eb[i] = expand(er[i], cb), expand(eg[i], cb), expand(eb[i], cb)
|
||||
if ab > 0 then
|
||||
ea[i] = expand(ea[i], ab)
|
||||
end
|
||||
end
|
||||
local cw = WEIGHTS[ib]
|
||||
local aw = if ab > 0 and ib2 > 0 then WEIGHTS[ib2] else cw
|
||||
local cbit = bit
|
||||
local abit = cbit + 16 * ib - ns
|
||||
local a1 = if ns == 2 then AI0[part + 1] elseif ns == 3 then AI1[part + 1] else -1
|
||||
local a2 = if ns == 3 then AI2[part + 1] else -1
|
||||
for i = 0, 15 do
|
||||
local s = subset(ns, part, i) * 2 + 1
|
||||
local n = ib
|
||||
if i == 0 or i == a1 or i == a2 then
|
||||
n -= 1
|
||||
end
|
||||
local i0 = bits(cbit, n)
|
||||
cbit += n
|
||||
local wc, wa
|
||||
if ab > 0 and ib2 > 0 then
|
||||
local n2 = if i == 0 then ib2 - 1 else ib2
|
||||
local i1 = bits(abit, n2)
|
||||
abit += n2
|
||||
if sel == 1 then
|
||||
wc, wa = aw[i1], cw[i0]
|
||||
else
|
||||
wc, wa = cw[i0], aw[i1]
|
||||
end
|
||||
else
|
||||
wc, wa = cw[i0], cw[i0]
|
||||
end
|
||||
local tc, ta = 64 - wc, 64 - wa
|
||||
local r = rshift(tc * er[s] + wc * er[s + 1] + 32, 6)
|
||||
local g = rshift(tc * eg[s] + wc * eg[s + 1] + 32, 6)
|
||||
local b = rshift(tc * eb[s] + wc * eb[s + 1] + 32, 6)
|
||||
local a = rshift(ta * ea[s] + wa * ea[s + 1] + 32, 6)
|
||||
if rot == 1 then
|
||||
r, a = a, r
|
||||
elseif rot == 2 then
|
||||
g, a = a, g
|
||||
elseif rot == 3 then
|
||||
b, a = a, b
|
||||
end
|
||||
writeu32(blk, i * 4, r + g * 256 + b * 65536 + a * 16777216)
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ BC6H
|
||||
-- ns, transformed, pb, epb, rb, gb, bb
|
||||
local MODES6 = {
|
||||
{ 2, 1, 5, 10, 5, 5, 5 },
|
||||
{ 2, 1, 5, 7, 6, 6, 6 },
|
||||
{ 2, 1, 5, 11, 5, 4, 4 },
|
||||
{ 2, 1, 5, 11, 4, 5, 4 },
|
||||
{ 2, 1, 5, 11, 4, 4, 5 },
|
||||
{ 2, 1, 5, 9, 5, 5, 5 },
|
||||
{ 2, 1, 5, 8, 6, 5, 5 },
|
||||
{ 2, 1, 5, 8, 5, 6, 5 },
|
||||
{ 2, 1, 5, 8, 5, 5, 6 },
|
||||
{ 2, 0, 5, 6, 6, 6, 6 },
|
||||
{ 1, 0, 0, 10, 10, 10, 10 },
|
||||
{ 1, 1, 0, 11, 9, 9, 9 },
|
||||
{ 1, 1, 0, 12, 8, 8, 8 },
|
||||
{ 1, 1, 0, 16, 4, 4, 4 },
|
||||
}
|
||||
-- Table.F: for each endpoint bit in stream order, endpoint * 16 + bit (endpoints r0 g0 b0 r1 g1 b1 r2 ... b3)
|
||||
local PACK6 = {
|
||||
{ 116, 132, 180, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 176, 160, 161, 162, 163, 80, 81, 82, 83, 84, 177, 128, 129, 130, 131, 96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179 },
|
||||
{ 117, 164, 165, 0, 1, 2, 3, 4, 5, 6, 176, 177, 132, 16, 17, 18, 19, 20, 21, 22, 133, 178, 116, 32, 33, 34, 35, 36, 37, 38, 179, 181, 180, 48, 49, 50, 51, 52, 53, 112, 113, 114, 115, 64, 65, 66, 67, 68, 69, 160, 161, 162, 163, 80, 81, 82, 83, 84, 85, 128, 129, 130, 131, 96, 97, 98, 99, 100, 101, 144, 145, 146, 147, 148, 149 },
|
||||
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 10, 112, 113, 114, 115, 64, 65, 66, 67, 26, 176, 160, 161, 162, 163, 80, 81, 82, 83, 42, 177, 128, 129, 130, 131, 96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179 },
|
||||
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 10, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 26, 160, 161, 162, 163, 80, 81, 82, 83, 42, 177, 128, 129, 130, 131, 96, 97, 98, 99, 176, 178, 144, 145, 146, 147, 116, 179 },
|
||||
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 10, 132, 112, 113, 114, 115, 64, 65, 66, 67, 26, 176, 160, 161, 162, 163, 80, 81, 82, 83, 84, 42, 128, 129, 130, 131, 96, 97, 98, 99, 177, 178, 144, 145, 146, 147, 180, 179 },
|
||||
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 132, 16, 17, 18, 19, 20, 21, 22, 23, 24, 116, 32, 33, 34, 35, 36, 37, 38, 39, 40, 180, 48, 49, 50, 51, 52, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 176, 160, 161, 162, 163, 80, 81, 82, 83, 84, 177, 128, 129, 130, 131, 96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179 },
|
||||
{ 0, 1, 2, 3, 4, 5, 6, 7, 164, 132, 16, 17, 18, 19, 20, 21, 22, 23, 178, 116, 32, 33, 34, 35, 36, 37, 38, 39, 179, 180, 48, 49, 50, 51, 52, 53, 112, 113, 114, 115, 64, 65, 66, 67, 68, 176, 160, 161, 162, 163, 80, 81, 82, 83, 84, 177, 128, 129, 130, 131, 96, 97, 98, 99, 100, 101, 144, 145, 146, 147, 148, 149 },
|
||||
{ 0, 1, 2, 3, 4, 5, 6, 7, 176, 132, 16, 17, 18, 19, 20, 21, 22, 23, 117, 116, 32, 33, 34, 35, 36, 37, 38, 39, 165, 180, 48, 49, 50, 51, 52, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 69, 160, 161, 162, 163, 80, 81, 82, 83, 84, 177, 128, 129, 130, 131, 96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179 },
|
||||
{ 0, 1, 2, 3, 4, 5, 6, 7, 177, 132, 16, 17, 18, 19, 20, 21, 22, 23, 133, 116, 32, 33, 34, 35, 36, 37, 38, 39, 181, 180, 48, 49, 50, 51, 52, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 176, 160, 161, 162, 163, 80, 81, 82, 83, 84, 85, 128, 129, 130, 131, 96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179 },
|
||||
{ 0, 1, 2, 3, 4, 5, 164, 176, 177, 132, 16, 17, 18, 19, 20, 21, 117, 133, 178, 116, 32, 33, 34, 35, 36, 37, 165, 179, 181, 180, 48, 49, 50, 51, 52, 53, 112, 113, 114, 115, 64, 65, 66, 67, 68, 69, 160, 161, 162, 163, 80, 81, 82, 83, 84, 85, 128, 129, 130, 131, 96, 97, 98, 99, 100, 101, 144, 145, 146, 147, 148, 149 },
|
||||
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89 },
|
||||
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 53, 54, 55, 56, 10, 64, 65, 66, 67, 68, 69, 70, 71, 72, 26, 80, 81, 82, 83, 84, 85, 86, 87, 88, 42 },
|
||||
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 53, 54, 55, 11, 10, 64, 65, 66, 67, 68, 69, 70, 71, 27, 26, 80, 81, 82, 83, 84, 85, 86, 87, 43, 42 },
|
||||
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 15, 14, 13, 12, 11, 10, 64, 65, 66, 67, 31, 30, 29, 28, 27, 26, 80, 81, 82, 83, 47, 46, 45, 44, 43, 42 },
|
||||
}
|
||||
local ep = table.create(12, 0)
|
||||
local uq = table.create(12, 0)
|
||||
|
||||
local function signExtend(v: number, n: number): number
|
||||
v = band(v, lshift(1, n) - 1)
|
||||
return if v >= lshift(1, n - 1) then v - lshift(1, n) else v
|
||||
end
|
||||
|
||||
local function unquantize(x: number, n: number, signed: boolean): number
|
||||
if not signed then
|
||||
if n >= 15 or x == 0 then
|
||||
return x
|
||||
elseif x == lshift(1, n) - 1 then
|
||||
return 0xFFFF
|
||||
end
|
||||
return rshift(x * 32768 + 0x4000, n - 1)
|
||||
end
|
||||
if n >= 16 then
|
||||
return x
|
||||
end
|
||||
local neg = x < 0
|
||||
if neg then
|
||||
x = -x
|
||||
end
|
||||
if x ~= 0 then
|
||||
if x >= lshift(1, n - 1) - 1 then
|
||||
x = 0x7FFF
|
||||
else
|
||||
x = rshift(x * 32768 + 0x4000, n - 1)
|
||||
end
|
||||
end
|
||||
return if neg then -x else x
|
||||
end
|
||||
|
||||
local function finish(v: number, signed: boolean): number
|
||||
if signed then
|
||||
if v < 0 then
|
||||
return -HALF[(-v * 31) // 32]
|
||||
end
|
||||
return HALF[(v * 31) // 32]
|
||||
end
|
||||
return HALF[(v * 31) // 64]
|
||||
end
|
||||
|
||||
-- one BC6H block into blk as rgbaf32 (256 bytes, alpha 1)
|
||||
function Decode.bc6h(src: buffer, p: number, blk: buffer, signed: boolean)
|
||||
load(src, p)
|
||||
local m = band(w0, 31)
|
||||
local mode, bit, epbits, ib
|
||||
local low = band(m, 3)
|
||||
if low < 2 then
|
||||
mode, bit, epbits, ib = low, 2, 75, 3
|
||||
elseif low == 2 then
|
||||
mode, bit, epbits, ib = 2 + rshift(m, 2), 5, 72, 3
|
||||
else
|
||||
mode, bit, epbits, ib = 10 + rshift(m, 2), 5, 60, 4
|
||||
end
|
||||
if mode >= 14 then
|
||||
for i = 0, 15 do
|
||||
local o = i * 16
|
||||
writef32(blk, o, 0)
|
||||
writef32(blk, o + 4, 0)
|
||||
writef32(blk, o + 8, 0)
|
||||
writef32(blk, o + 12, 1)
|
||||
end
|
||||
return
|
||||
end
|
||||
local info = MODES6[mode + 1]
|
||||
local ns, tr, pb, epb, rbits, gbits, bbits = info[1], info[2], info[3], info[4], info[5], info[6], info[7]
|
||||
local nep = if ns == 2 then 12 else 6
|
||||
for i = 1, 12 do
|
||||
ep[i] = 0
|
||||
end
|
||||
local pack = PACK6[mode + 1]
|
||||
for i = 1, epbits do
|
||||
local d = pack[i]
|
||||
local e = rshift(d, 4) + 1
|
||||
ep[e] = bor(ep[e], lshift(bits(bit + i - 1, 1), band(d, 15)))
|
||||
end
|
||||
bit += epbits
|
||||
local part = bits(bit, pb)
|
||||
bit += pb
|
||||
local mask = lshift(1, epb) - 1
|
||||
if signed then
|
||||
ep[1], ep[2], ep[3] = signExtend(ep[1], epb), signExtend(ep[2], epb), signExtend(ep[3], epb)
|
||||
end
|
||||
if signed or tr == 1 then
|
||||
for i = 4, nep, 3 do
|
||||
ep[i], ep[i + 1], ep[i + 2] = signExtend(ep[i], rbits), signExtend(ep[i + 1], gbits), signExtend(ep[i + 2], bbits)
|
||||
end
|
||||
end
|
||||
if tr == 1 then
|
||||
for i = 4, nep, 3 do
|
||||
for c = 0, 2 do
|
||||
local v = band(ep[i + c] + ep[1 + c], mask)
|
||||
ep[i + c] = if signed then signExtend(v, epb) else v
|
||||
end
|
||||
end
|
||||
end
|
||||
for i = 1, nep do
|
||||
uq[i] = unquantize(ep[i], epb, signed)
|
||||
end
|
||||
local w = WEIGHTS[ib]
|
||||
local a1 = if ns == 2 then AI0[part + 1] else -1
|
||||
for i = 0, 15 do
|
||||
local s = subset(ns, part, i) * 6 + 1
|
||||
local n = if i == 0 or i == a1 then ib - 1 else ib
|
||||
local wt = w[bits(bit, n)]
|
||||
bit += n
|
||||
local t = 64 - wt
|
||||
local o = i * 16
|
||||
-- floor((a * t + b * w + 32) / 64): the products may be negative (signed) - // floors like >> would
|
||||
writef32(blk, o, finish((uq[s] * t + uq[s + 3] * wt + 32) // 64, signed))
|
||||
writef32(blk, o + 4, finish((uq[s + 1] * t + uq[s + 4] * wt + 32) // 64, signed))
|
||||
writef32(blk, o + 8, finish((uq[s + 2] * t + uq[s + 5] * wt + 32) // 64, signed))
|
||||
writef32(blk, o + 12, 1)
|
||||
end
|
||||
end
|
||||
|
||||
return Decode
|
||||
@@ -0,0 +1,442 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/image/Bcn/Encode: BC1 / BC3 / BC4 / BC5 block encoders (new in formats-luau; the approach follows stb_dxt by
|
||||
-- Fabian Giesen / Sean Barrett, public domain: the principal axis of the block's colours by power iteration, the
|
||||
-- extreme pixels along it as endpoints, then least-squares refinement of the endpoints for the chosen indices, keeping
|
||||
-- the best; single-colour blocks use exact endpoint tables). Indices are chosen against the palette exactly as
|
||||
-- Bcn/Decode rebuilds it. BC4 / BC5 channels try both the 8-value and the 6-value (+ 0 / 255) ramps. Never throws.
|
||||
local Encode = {}
|
||||
|
||||
local readu8, writeu8, writeu16, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu16, buffer.writeu32
|
||||
local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift
|
||||
|
||||
local function exp5(v: number): number
|
||||
return bor(lshift(v, 3), rshift(v, 2))
|
||||
end
|
||||
local function exp6(v: number): number
|
||||
return bor(lshift(v, 2), rshift(v, 4))
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ single colours
|
||||
-- OM[k][v + 1] = e0 * 256 + e1 (quantized) whose colour-2 value (4-colour: (2 e0 + e1) // 3; 3-colour: (e0 + e1)
|
||||
-- // 2) is closest to v; k = 1 / 2 for 5-bit (4 / 3 colour), 3 / 4 for 6-bit
|
||||
local OM: { { number } }? = nil
|
||||
local function singleTables(): { { number } }
|
||||
local om = OM
|
||||
if om then
|
||||
return om
|
||||
end
|
||||
local t: { { number } } = {}
|
||||
for k = 1, 4 do
|
||||
local bitsN = if k <= 2 then 5 else 6
|
||||
local maxq = lshift(1, bitsN) - 1
|
||||
local exp: (number) -> number = if bitsN == 5 then exp5 else exp6
|
||||
local best = table.create(256, 1e9)
|
||||
local pick = table.create(256, 0)
|
||||
for a = 0, maxq do
|
||||
local ea = exp(a)
|
||||
for b = 0, maxq do
|
||||
local eb = exp(b)
|
||||
local v: number = if k % 2 == 1 then (2 * ea + eb) // 3 else (ea + eb) // 2
|
||||
-- prefer endpoints close to each other (less error if the colour shifts)
|
||||
local e = math.abs(ea - eb) * 0.01
|
||||
for target = math.max(0, v - 8), math.min(255, v + 8) do
|
||||
local err = (target - v) ^ 2 + e
|
||||
if err < best[target + 1] then
|
||||
best[target + 1] = err
|
||||
pick[target + 1] = a * 256 + b
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
t[k] = pick
|
||||
end
|
||||
OM = t
|
||||
return t
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ BC1 colour
|
||||
local R, G, B, A = table.create(16, 0), table.create(16, 0), table.create(16, 0), table.create(16, 0)
|
||||
local USE = table.create(16, true)
|
||||
local PR, PG, PB = table.create(4, 0), table.create(4, 0), table.create(4, 0)
|
||||
local IDX = table.create(16, 0)
|
||||
local BEST = table.create(16, 0)
|
||||
|
||||
local function palette(c0: number, c1: number, four: boolean)
|
||||
local r0, g0, b0 = exp5(rshift(c0, 11)), exp6(band(rshift(c0, 5), 63)), exp5(band(c0, 31))
|
||||
local r1, g1, b1 = exp5(rshift(c1, 11)), exp6(band(rshift(c1, 5), 63)), exp5(band(c1, 31))
|
||||
PR[1], PG[1], PB[1] = r0, g0, b0
|
||||
PR[2], PG[2], PB[2] = r1, g1, b1
|
||||
if four then
|
||||
PR[3], PG[3], PB[3] = (2 * r0 + r1) // 3, (2 * g0 + g1) // 3, (2 * b0 + b1) // 3
|
||||
PR[4], PG[4], PB[4] = (r0 + 2 * r1) // 3, (g0 + 2 * g1) // 3, (b0 + 2 * b1) // 3
|
||||
else
|
||||
PR[3], PG[3], PB[3] = (r0 + r1) // 2, (g0 + g1) // 2, (b0 + b1) // 2
|
||||
PR[4], PG[4], PB[4] = 0, 0, 0
|
||||
end
|
||||
end
|
||||
|
||||
-- indices for the palette into IDX (0-based); returns the squared error of the used pixels
|
||||
local function assign(four: boolean): number
|
||||
local n = if four then 4 else 3
|
||||
local total = 0
|
||||
for i = 1, 16 do
|
||||
if USE[i] then
|
||||
local r, g, b = R[i], G[i], B[i]
|
||||
local bi, be = 0, math.huge
|
||||
for k = 1, n do
|
||||
local dr, dg, db = r - PR[k], g - PG[k], b - PB[k]
|
||||
local e = dr * dr + dg * dg + db * db
|
||||
if e < be then
|
||||
be, bi = e, k - 1
|
||||
end
|
||||
end
|
||||
IDX[i] = bi
|
||||
total += be
|
||||
else
|
||||
IDX[i] = 3
|
||||
end
|
||||
end
|
||||
return total
|
||||
end
|
||||
|
||||
local function q565(r: number, g: number, b: number): number
|
||||
local qr = math.clamp(math.floor(r * 31 / 255 + 0.5), 0, 31)
|
||||
local qg = math.clamp(math.floor(g * 63 / 255 + 0.5), 0, 63)
|
||||
local qb = math.clamp(math.floor(b * 31 / 255 + 0.5), 0, 31)
|
||||
return qr * 2048 + qg * 32 + qb
|
||||
end
|
||||
|
||||
-- the endpoint weights of index k (the e0 share)
|
||||
local W4 = { 1, 0, 2 / 3, 1 / 3 }
|
||||
local W3 = { 1, 0, 0.5, 0 }
|
||||
|
||||
-- least squares endpoints for the current IDX: c0, c1 or nil when degenerate
|
||||
local function refine(four: boolean): (number?, number?)
|
||||
local W = if four then W4 else W3
|
||||
local aa, bb, ab = 0, 0, 0
|
||||
local ar, ag, ab_, br, bg, bb_ = 0, 0, 0, 0, 0, 0
|
||||
for i = 1, 16 do
|
||||
if USE[i] then
|
||||
local w = W[IDX[i] + 1]
|
||||
local v = 1 - w
|
||||
aa += w * w
|
||||
bb += v * v
|
||||
ab += w * v
|
||||
ar += w * R[i]
|
||||
ag += w * G[i]
|
||||
ab_ += w * B[i]
|
||||
br += v * R[i]
|
||||
bg += v * G[i]
|
||||
bb_ += v * B[i]
|
||||
end
|
||||
end
|
||||
local det = aa * bb - ab * ab
|
||||
if math.abs(det) < 1e-9 then
|
||||
return nil, nil
|
||||
end
|
||||
local f = 1 / det
|
||||
local r0, g0, b0 = (ar * bb - br * ab) * f, (ag * bb - bg * ab) * f, (ab_ * bb - bb_ * ab) * f
|
||||
local r1, g1, b1 = (br * aa - ar * ab) * f, (bg * aa - ag * ab) * f, (bb_ * aa - ab_ * ab) * f
|
||||
return q565(r0, g0, b0), q565(r1, g1, b1)
|
||||
end
|
||||
|
||||
-- encodes R / G / B (USE marks the pixels that count) as a BC1 colour block at out[o]; four = 4-colour mode
|
||||
-- (opaque), else the 3-colour mode with index 3 for the unused (transparent) pixels
|
||||
local function colourBlock(out: buffer, o: number, four: boolean)
|
||||
local n, mr, mg, mb = 0, 0, 0, 0
|
||||
for i = 1, 16 do
|
||||
if USE[i] then
|
||||
n += 1
|
||||
mr += R[i]
|
||||
mg += G[i]
|
||||
mb += B[i]
|
||||
end
|
||||
end
|
||||
if n == 0 then
|
||||
writeu16(out, o, 0)
|
||||
writeu16(out, o + 2, 0)
|
||||
writeu32(out, o + 4, 0xFFFFFFFF)
|
||||
return
|
||||
end
|
||||
mr, mg, mb = mr / n, mg / n, mb / n
|
||||
local crr, cgg, cbb, crg, crb, cgb = 0, 0, 0, 0, 0, 0
|
||||
local same = true
|
||||
local fr, fg, fb = -1, -1, -1
|
||||
for i = 1, 16 do
|
||||
if USE[i] then
|
||||
if fr < 0 then
|
||||
fr, fg, fb = R[i], G[i], B[i]
|
||||
elseif R[i] ~= fr or G[i] ~= fg or B[i] ~= fb then
|
||||
same = false
|
||||
end
|
||||
local dr, dg, db = R[i] - mr, G[i] - mg, B[i] - mb
|
||||
crr += dr * dr
|
||||
cgg += dg * dg
|
||||
cbb += db * db
|
||||
crg += dr * dg
|
||||
crb += dr * db
|
||||
cgb += dg * db
|
||||
end
|
||||
end
|
||||
local c0, c1
|
||||
if same then
|
||||
local t = singleTables()
|
||||
local k = if four then 0 else 1
|
||||
local pr, pg, pb = t[1 + k][fr + 1], t[3 + k][fg + 1], t[1 + k][fb + 1]
|
||||
c0 = rshift(pr, 8) * 2048 + rshift(pg, 8) * 32 + rshift(pb, 8)
|
||||
c1 = band(pr, 255) * 2048 + band(pg, 255) * 32 + band(pb, 255)
|
||||
local i2 = 2
|
||||
if c0 == c1 then
|
||||
i2 = 0
|
||||
end
|
||||
-- index 2 everywhere (or 0 for an exact endpoint); order fixed below
|
||||
for i = 1, 16 do
|
||||
IDX[i] = if USE[i] then i2 else 3
|
||||
end
|
||||
else
|
||||
-- principal axis
|
||||
local vr, vg, vb = 1, 1, 1
|
||||
for _ = 1, 8 do
|
||||
local nr = crr * vr + crg * vg + crb * vb
|
||||
local ng = crg * vr + cgg * vg + cgb * vb
|
||||
local nb = crb * vr + cgb * vg + cbb * vb
|
||||
local m = math.max(math.abs(nr), math.abs(ng), math.abs(nb))
|
||||
if m < 1e-9 then
|
||||
break
|
||||
end
|
||||
vr, vg, vb = nr / m, ng / m, nb / m
|
||||
end
|
||||
local lo, hi, li, hi_ = math.huge, -math.huge, 1, 1
|
||||
for i = 1, 16 do
|
||||
if USE[i] then
|
||||
local d = R[i] * vr + G[i] * vg + B[i] * vb
|
||||
if d < lo then
|
||||
lo, li = d, i
|
||||
end
|
||||
if d > hi then
|
||||
hi, hi_ = d, i
|
||||
end
|
||||
end
|
||||
end
|
||||
c0 = q565(R[hi_], G[hi_], B[hi_])
|
||||
c1 = q565(R[li], G[li], B[li])
|
||||
palette(c0, c1, four)
|
||||
local err = assign(four)
|
||||
for i = 1, 16 do
|
||||
BEST[i] = IDX[i]
|
||||
end
|
||||
for _ = 1, 2 do
|
||||
local n0, n1 = refine(four)
|
||||
if not n0 or not n1 then
|
||||
break
|
||||
end
|
||||
palette(n0, n1, four)
|
||||
local e2 = assign(four)
|
||||
if e2 < err then
|
||||
err, c0, c1 = e2, n0, n1
|
||||
for i = 1, 16 do
|
||||
BEST[i] = IDX[i]
|
||||
end
|
||||
else
|
||||
break
|
||||
end
|
||||
end
|
||||
for i = 1, 16 do
|
||||
IDX[i] = BEST[i]
|
||||
end
|
||||
end
|
||||
-- the mode is set by the endpoint order: 4-colour c0 > c1, 3-colour c0 <= c1
|
||||
if four then
|
||||
if c0 < c1 then
|
||||
c0, c1 = c1, c0
|
||||
for i = 1, 16 do
|
||||
local v = IDX[i]
|
||||
IDX[i] = if v == 0 then 1 elseif v == 1 then 0 elseif v == 2 then 3 else 2
|
||||
end
|
||||
elseif c0 == c1 then
|
||||
for i = 1, 16 do
|
||||
IDX[i] = 0
|
||||
end
|
||||
end
|
||||
elseif c0 > c1 then
|
||||
c0, c1 = c1, c0
|
||||
for i = 1, 16 do
|
||||
local v = IDX[i]
|
||||
IDX[i] = if v == 0 then 1 elseif v == 1 then 0 else v
|
||||
end
|
||||
end
|
||||
writeu16(out, o, c0)
|
||||
writeu16(out, o + 2, c1)
|
||||
local bitsv = 0
|
||||
for i = 16, 1, -1 do
|
||||
bitsv = bitsv * 4 + IDX[i]
|
||||
end
|
||||
writeu32(out, o + 4, bitsv)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ BC4 channel
|
||||
local V = table.create(16, 0)
|
||||
local RAMP = table.create(8, 0)
|
||||
local SEL = table.create(16, 0)
|
||||
local SELB = table.create(16, 0)
|
||||
|
||||
local function ramp(a0: number, a1: number)
|
||||
RAMP[1], RAMP[2] = a0, a1
|
||||
if a0 > a1 then
|
||||
for i = 1, 6 do
|
||||
RAMP[i + 2] = ((7 - i) * a0 + i * a1) // 7
|
||||
end
|
||||
else
|
||||
for i = 1, 4 do
|
||||
RAMP[i + 2] = ((5 - i) * a0 + i * a1) // 5
|
||||
end
|
||||
RAMP[7], RAMP[8] = 0, 255
|
||||
end
|
||||
end
|
||||
|
||||
local function pick(): number
|
||||
local total = 0
|
||||
for i = 1, 16 do
|
||||
local v = V[i]
|
||||
local bi, be = 0, math.huge
|
||||
for k = 1, 8 do
|
||||
local d = v - RAMP[k]
|
||||
local e = d * d
|
||||
if e < be then
|
||||
be, bi = e, k - 1
|
||||
end
|
||||
end
|
||||
SEL[i] = bi
|
||||
total += be
|
||||
end
|
||||
return total
|
||||
end
|
||||
|
||||
-- encodes V[1..16] (0..255) as an 8-byte BC4 block at out[o]
|
||||
local function channelBlock(out: buffer, o: number)
|
||||
local lo, hi = 255, 0
|
||||
local lo2, hi2 = 255, 0
|
||||
for i = 1, 16 do
|
||||
local v = V[i]
|
||||
lo, hi = math.min(lo, v), math.max(hi, v)
|
||||
if v > 0 and v < 255 then
|
||||
lo2, hi2 = math.min(lo2, v), math.max(hi2, v)
|
||||
end
|
||||
end
|
||||
local a0, a1
|
||||
if lo == hi then
|
||||
a0, a1 = lo, lo
|
||||
ramp(a0, a1)
|
||||
pick()
|
||||
else
|
||||
-- 8-value ramp, then a few nudged endpoints
|
||||
local bestErr, b0, b1 = math.huge, hi, lo
|
||||
for d0 = 0, 1 do
|
||||
for d1 = 0, 1 do
|
||||
local x0, x1 = hi - d0, lo + d1
|
||||
if x0 > x1 then
|
||||
ramp(x0, x1)
|
||||
local e = pick()
|
||||
if e < bestErr then
|
||||
bestErr, b0, b1 = e, x0, x1
|
||||
for i = 1, 16 do
|
||||
SELB[i] = SEL[i]
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
-- 6-value ramp with the 0 / 255 extremes
|
||||
if lo2 > hi2 then
|
||||
lo2, hi2 = lo, lo
|
||||
end
|
||||
ramp(lo2, hi2)
|
||||
local e = pick()
|
||||
if e < bestErr then
|
||||
bestErr, b0, b1 = e, lo2, hi2
|
||||
for i = 1, 16 do
|
||||
SELB[i] = SEL[i]
|
||||
end
|
||||
end
|
||||
a0, a1 = b0, b1
|
||||
for i = 1, 16 do
|
||||
SEL[i] = SELB[i]
|
||||
end
|
||||
end
|
||||
writeu8(out, o, a0)
|
||||
writeu8(out, o + 1, a1)
|
||||
local lo24, hi24 = 0, 0
|
||||
for i = 8, 1, -1 do
|
||||
lo24 = lo24 * 8 + SEL[i]
|
||||
hi24 = hi24 * 8 + SEL[i + 8]
|
||||
end
|
||||
writeu8(out, o + 2, band(lo24, 255))
|
||||
writeu8(out, o + 3, band(rshift(lo24, 8), 255))
|
||||
writeu8(out, o + 4, rshift(lo24, 16))
|
||||
writeu8(out, o + 5, band(hi24, 255))
|
||||
writeu8(out, o + 6, band(rshift(hi24, 8), 255))
|
||||
writeu8(out, o + 7, rshift(hi24, 16))
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ whole images
|
||||
-- the 4x4 block at bx, by of an rgba8 image into R / G / B / A (edge pixels repeat)
|
||||
local function gather(px: buffer, w: number, h: number, bx: number, by: number)
|
||||
for y = 0, 3 do
|
||||
local sy = math.min(by * 4 + y, h - 1)
|
||||
for x = 0, 3 do
|
||||
local sx = math.min(bx * 4 + x, w - 1)
|
||||
local s = (sy * w + sx) * 4
|
||||
local i = y * 4 + x + 1
|
||||
R[i], G[i], B[i], A[i] = readu8(px, s), readu8(px, s + 1), readu8(px, s + 2), readu8(px, s + 3)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- encode(kind, rgba8 pixels, w, h, alphaThreshold) -> the block data (kind = bc1 / bc3 / bc4 / bc5)
|
||||
function Encode.run(kind: string, px: buffer, w: number, h: number, threshold: number): buffer
|
||||
local bw, bh = (w + 3) // 4, (h + 3) // 4
|
||||
local bytes = if kind == "bc1" or kind == "bc4" then 8 else 16
|
||||
local out = buffer.create(bw * bh * bytes)
|
||||
local o = 0
|
||||
for by = 0, bh - 1 do
|
||||
for bx = 0, bw - 1 do
|
||||
gather(px, w, h, bx, by)
|
||||
if kind == "bc1" then
|
||||
local any = false
|
||||
for i = 1, 16 do
|
||||
local u = A[i] >= threshold
|
||||
USE[i] = u
|
||||
any = any or not u
|
||||
end
|
||||
colourBlock(out, o, not any)
|
||||
elseif kind == "bc3" then
|
||||
for i = 1, 16 do
|
||||
USE[i] = true
|
||||
V[i] = A[i]
|
||||
end
|
||||
channelBlock(out, o)
|
||||
colourBlock(out, o + 8, true)
|
||||
elseif kind == "bc4" then
|
||||
for i = 1, 16 do
|
||||
V[i] = R[i]
|
||||
end
|
||||
channelBlock(out, o)
|
||||
else
|
||||
for i = 1, 16 do
|
||||
V[i] = R[i]
|
||||
end
|
||||
channelBlock(out, o)
|
||||
for i = 1, 16 do
|
||||
V[i] = G[i]
|
||||
end
|
||||
channelBlock(out, o + 8)
|
||||
end
|
||||
o += bytes
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
return Encode
|
||||
@@ -0,0 +1,121 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/image/Bcn: the BCn block-compressed texture codecs, shared by the texture formats (DDS, KTX, VTF, BLP, ...):
|
||||
-- decode of BC1 (DXT1, with the 3-colour + transparent mode), BC2 (DXT3), BC3 (DXT5), BC4 / BC5 (RGTC / ATI1 / ATI2,
|
||||
-- UNORM and SNORM), BC6H (UF16 / SF16, to rgbaf32) and BC7 (all 8 modes); encode of BC1 / BC3 / BC4 / BC5 (UNORM).
|
||||
-- Decoders ported from Pillow's BcnDecode.c (CC0) with the D3D11 rules; encoders new (stb_dxt-style). Never throws.
|
||||
--
|
||||
-- local px, err = Bcn.decode("bc7", buf, offset, w, h) -- rgba8 pixels (rgbaf32 for bc6h / bc6hs)
|
||||
-- local blocks = Bcn.encode("bc1", rgba8Pixels, w, h) -- the block data (row-major blocks)
|
||||
-- Bcn.size("bc3", w, h) -- bytes of a w x h image (whole 4x4 blocks)
|
||||
--
|
||||
-- Channels: BC4 decodes to grey (r = g = b, opaque), BC5 to red + green (blue 0, opaque); SNORM values are biased by
|
||||
-- 128 into rgba8 (-127 -> 1, 0 -> 128, 127 -> 255). BC1 / BC3 / BC5 encode reads R / G (BC4: R), BC1 alpha below
|
||||
-- opts.alphaThreshold (default 128) selects the transparent 3-colour mode.
|
||||
local Decode = require("@formats/codecs/image/Bcn/Decode")
|
||||
local Encode = require("@formats/codecs/image/Bcn/Encode")
|
||||
|
||||
local Bcn = {}
|
||||
|
||||
-- kind -> bytes per 4x4 block
|
||||
Bcn.BLOCK = table.freeze({ bc1 = 8, bc2 = 16, bc3 = 16, bc4 = 8, bc4s = 8, bc5 = 16, bc5s = 16, bc6h = 16, bc6hs = 16, bc7 = 16 }) :: { [string]: number }
|
||||
-- kinds that decode to rgbaf32
|
||||
Bcn.FLOAT = table.freeze({ bc6h = true, bc6hs = true }) :: { [string]: boolean }
|
||||
|
||||
local readu32, writeu32 = buffer.readu32, buffer.writeu32
|
||||
|
||||
local BLOCKS: { [string]: (buffer, number, buffer) -> () } = {
|
||||
bc1 = Decode.bc1,
|
||||
bc2 = Decode.bc2,
|
||||
bc3 = Decode.bc3,
|
||||
bc4 = Decode.bc4,
|
||||
bc4s = Decode.bc4s,
|
||||
bc5 = Decode.bc5,
|
||||
bc5s = Decode.bc5s,
|
||||
bc7 = Decode.bc7,
|
||||
bc6h = function(src: buffer, p: number, blk: buffer)
|
||||
Decode.bc6h(src, p, blk, false)
|
||||
end,
|
||||
bc6hs = function(src: buffer, p: number, blk: buffer)
|
||||
Decode.bc6h(src, p, blk, true)
|
||||
end,
|
||||
}
|
||||
|
||||
-- size(kind, w, h) -> bytes of the block data (nil for an unknown kind)
|
||||
function Bcn.size(kind: string, w: number, h: number): number?
|
||||
local b = Bcn.BLOCK[kind]
|
||||
if not b then
|
||||
return nil
|
||||
end
|
||||
return ((w + 3) // 4) * ((h + 3) // 4) * b
|
||||
end
|
||||
|
||||
-- decode(kind, src, offset, w, h, out?, outOffset?) -> pixels (rgba8, or rgbaf32 for BC6H) | nil, message.
|
||||
-- out (optional) receives the pixels at outOffset (default 0) instead of a new buffer.
|
||||
function Bcn.decode(kind: string, src: buffer, offset: number, w: number, h: number, out: buffer?, outOffset: number?): (buffer?, string?)
|
||||
local fn = BLOCKS[kind]
|
||||
if not fn then
|
||||
return nil, "unsupported: unknown block format " .. tostring(kind)
|
||||
end
|
||||
if w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 then
|
||||
return nil, "bad image size"
|
||||
end
|
||||
local need = Bcn.size(kind, w, h) :: number
|
||||
if offset < 0 or offset + need > buffer.len(src) then
|
||||
return nil, "truncated: block data runs past the end"
|
||||
end
|
||||
local float = Bcn.FLOAT[kind] == true
|
||||
local bpp = if float then 16 else 4
|
||||
local oo = outOffset or 0
|
||||
local dst = out or buffer.create(w * h * bpp)
|
||||
if oo + w * h * bpp > buffer.len(dst) then
|
||||
return nil, "output buffer too small"
|
||||
end
|
||||
local bytes = Bcn.BLOCK[kind]
|
||||
local blk = buffer.create(16 * bpp)
|
||||
local bw, bh = (w + 3) // 4, (h + 3) // 4
|
||||
local p = offset
|
||||
local rowBytes = w * bpp
|
||||
for by = 0, bh - 1 do
|
||||
local rows = math.min(4, h - by * 4)
|
||||
for bx = 0, bw - 1 do
|
||||
fn(src, p, blk)
|
||||
p += bytes
|
||||
local cols = math.min(4, w - bx * 4)
|
||||
local base = oo + (by * 4) * rowBytes + bx * 4 * bpp
|
||||
if cols == 4 and not float then
|
||||
for y = 0, rows - 1 do
|
||||
local d, s = base + y * rowBytes, y * 16
|
||||
writeu32(dst, d, readu32(blk, s))
|
||||
writeu32(dst, d + 4, readu32(blk, s + 4))
|
||||
writeu32(dst, d + 8, readu32(blk, s + 8))
|
||||
writeu32(dst, d + 12, readu32(blk, s + 12))
|
||||
end
|
||||
else
|
||||
for y = 0, rows - 1 do
|
||||
buffer.copy(dst, base + y * rowBytes, blk, y * 4 * bpp, cols * bpp)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return dst, nil
|
||||
end
|
||||
|
||||
export type EncodeOptions = {
|
||||
alphaThreshold: number?, -- BC1: alpha below this is transparent (default 128; 0 = always opaque)
|
||||
}
|
||||
|
||||
-- encode(kind, pixels, w, h, opts?) -> block data | nil, message. pixels: rgba8, w x h; kind = bc1 / bc3 / bc4 / bc5.
|
||||
function Bcn.encode(kind: string, px: buffer, w: number, h: number, opts: EncodeOptions?): (buffer?, string?)
|
||||
if kind ~= "bc1" and kind ~= "bc3" and kind ~= "bc4" and kind ~= "bc5" then
|
||||
return nil, "unsupported: no encoder for " .. tostring(kind)
|
||||
end
|
||||
if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(px) < w * h * 4 then
|
||||
return nil, "needs w x h rgba8 pixels"
|
||||
end
|
||||
local t = opts and opts.alphaThreshold or 128
|
||||
return Encode.run(kind, px, w, h, t), nil
|
||||
end
|
||||
|
||||
return Bcn
|
||||
@@ -0,0 +1,315 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/image/Etc: the Ericsson / Khronos block texture codecs, decode only: ETC1, ETC2 RGB (with the T, H and planar
|
||||
-- modes), ETC2 RGBA (an EAC alpha block + ETC2 colour), ETC2 RGB A1 (punch-through alpha) and EAC R11 / RG11
|
||||
-- (unsigned and signed). Written from the Khronos Data Format Specification 1.3, section 21 (ETC1 / ETC2 / EAC); new
|
||||
-- in formats-luau. Shared by the texture formats (KTX, PVR, ...). Never throws: the caller gets a message instead.
|
||||
--
|
||||
-- local px, err = Etc.decode("etc2_rgba", buf, offset, w, h) -- rgba8 pixels
|
||||
-- local px16 = Etc.decode("eac_rg11", buf, offset, w, h, nil, 0, true) -- rgba16 (EAC keeps its 11 bits)
|
||||
-- Etc.size("etc1", w, h) -- bytes of the block data
|
||||
--
|
||||
-- Kinds: etc1, etc2_rgb, etc2_rgba, etc2_rgba1, eac_r11, eac_r11s, eac_rg11, eac_rg11s. R11 decodes to grey (r = g = b),
|
||||
-- RG11 to red + green (blue 0); signed values are biased (-1 -> 1, 0 -> 128, +1 -> 255; rgba16: 0 / 32768 / 65535).
|
||||
local Etc = {}
|
||||
|
||||
Etc.BLOCK = table.freeze({ etc1 = 8, etc2_rgb = 8, etc2_rgba = 16, etc2_rgba1 = 8, eac_r11 = 8, eac_r11s = 8, eac_rg11 = 16, eac_rg11s = 16 }) :: { [string]: number }
|
||||
|
||||
local readu8, readu32, writeu8, writeu16, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu16, buffer.writeu32
|
||||
local band, rshift, byteswap = bit32.band, bit32.rshift, bit32.byteswap
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ tables
|
||||
local MOD = { -- the ETC1 intensity modifiers per table: index (msb * 2 + lsb) -> a, b, -a, -b
|
||||
{ 2, 8, -2, -8 },
|
||||
{ 5, 17, -5, -17 },
|
||||
{ 9, 29, -9, -29 },
|
||||
{ 13, 42, -13, -42 },
|
||||
{ 18, 60, -18, -60 },
|
||||
{ 24, 80, -24, -80 },
|
||||
{ 33, 106, -33, -106 },
|
||||
{ 47, 183, -47, -183 },
|
||||
}
|
||||
local DIST = { 3, 6, 11, 16, 23, 32, 41, 64 } -- T / H mode distances
|
||||
local EAC = {
|
||||
{ -3, -6, -9, -15, 2, 5, 8, 14 },
|
||||
{ -3, -7, -10, -13, 2, 6, 9, 12 },
|
||||
{ -2, -5, -8, -13, 1, 4, 7, 12 },
|
||||
{ -2, -4, -6, -13, 1, 3, 5, 12 },
|
||||
{ -3, -6, -8, -12, 2, 5, 7, 11 },
|
||||
{ -3, -7, -9, -11, 2, 6, 8, 10 },
|
||||
{ -4, -7, -8, -11, 3, 6, 7, 10 },
|
||||
{ -3, -5, -8, -11, 2, 4, 7, 10 },
|
||||
{ -2, -6, -8, -10, 1, 5, 7, 9 },
|
||||
{ -2, -5, -8, -10, 1, 4, 7, 9 },
|
||||
{ -2, -4, -8, -10, 1, 3, 7, 9 },
|
||||
{ -2, -5, -7, -10, 1, 4, 6, 9 },
|
||||
{ -3, -4, -7, -10, 2, 3, 6, 9 },
|
||||
{ -1, -2, -3, -10, 0, 1, 2, 9 },
|
||||
{ -4, -6, -8, -9, 3, 5, 7, 8 },
|
||||
{ -3, -5, -7, -9, 2, 4, 6, 8 },
|
||||
}
|
||||
|
||||
local function clamp8(v: number): number
|
||||
return if v < 0 then 0 elseif v > 255 then 255 else v
|
||||
end
|
||||
local function rgb(r: number, g: number, b: number): number
|
||||
return clamp8(r) + clamp8(g) * 256 + clamp8(b) * 65536 + 0xFF000000
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ colour blocks
|
||||
-- blk: 16 u32 rgba8 pixels in raster order (y * 4 + x)
|
||||
local P = table.create(4, 0) -- T / H paint colours (rgba8 u32)
|
||||
|
||||
local function be32(src: buffer, p: number): number
|
||||
return byteswap(readu32(src, p))
|
||||
end
|
||||
|
||||
-- the 2-bit pixel index of pixel i (column-major: i = x * 4 + y)
|
||||
local function pix(lo: number, i: number): number
|
||||
return band(rshift(lo, i + 15), 2) + band(rshift(lo, i), 1)
|
||||
end
|
||||
|
||||
-- ETC1 / ETC2 colour block at p into blk. etc2: T / H / planar modes; punch: the RGB A1 variant (bit 33 = opaque).
|
||||
local function colour(src: buffer, p: number, blk: buffer, etc2: boolean, punch: boolean)
|
||||
local hi, lo = be32(src, p), be32(src, p + 4)
|
||||
local diffBit = band(rshift(hi, 1), 1)
|
||||
local flip = band(hi, 1)
|
||||
local opaque = not punch or diffBit == 1
|
||||
local r1, g1, b1, r2, g2, b2
|
||||
if not punch and diffBit == 0 then
|
||||
r1, r2 = band(rshift(hi, 28), 15) * 17, band(rshift(hi, 24), 15) * 17
|
||||
g1, g2 = band(rshift(hi, 20), 15) * 17, band(rshift(hi, 16), 15) * 17
|
||||
b1, b2 = band(rshift(hi, 12), 15) * 17, band(rshift(hi, 8), 15) * 17
|
||||
else
|
||||
local R, G, B = band(rshift(hi, 27), 31), band(rshift(hi, 19), 31), band(rshift(hi, 11), 31)
|
||||
local dR, dG, dB = band(rshift(hi, 24), 7), band(rshift(hi, 16), 7), band(rshift(hi, 8), 7)
|
||||
if dR >= 4 then
|
||||
dR -= 8
|
||||
end
|
||||
if dG >= 4 then
|
||||
dG -= 8
|
||||
end
|
||||
if dB >= 4 then
|
||||
dB -= 8
|
||||
end
|
||||
local R2, G2, B2 = R + dR, G + dG, B + dB
|
||||
if etc2 and (R2 < 0 or R2 > 31) then
|
||||
-- T mode
|
||||
local ra = band(rshift(hi, 27), 3) * 4 + band(rshift(hi, 24), 3)
|
||||
local c1r, c1g, c1b = ra * 17, band(rshift(hi, 20), 15) * 17, band(rshift(hi, 16), 15) * 17
|
||||
local c2r, c2g, c2b = band(rshift(hi, 12), 15) * 17, band(rshift(hi, 8), 15) * 17, band(rshift(hi, 4), 15) * 17
|
||||
local d = DIST[band(rshift(hi, 2), 3) * 2 + band(hi, 1) + 1]
|
||||
P[1] = rgb(c1r, c1g, c1b)
|
||||
P[2] = rgb(c2r + d, c2g + d, c2b + d)
|
||||
P[3] = rgb(c2r, c2g, c2b)
|
||||
P[4] = rgb(c2r - d, c2g - d, c2b - d)
|
||||
elseif etc2 and (G2 < 0 or G2 > 31) then
|
||||
-- H mode
|
||||
local q1r = band(rshift(hi, 27), 15)
|
||||
local q1g = band(rshift(hi, 24), 7) * 2 + band(rshift(hi, 20), 1)
|
||||
local q1b = band(rshift(hi, 19), 1) * 8 + band(rshift(hi, 15), 7)
|
||||
local q2r, q2g, q2b = band(rshift(hi, 11), 15), band(rshift(hi, 7), 15), band(rshift(hi, 3), 15)
|
||||
local order = if q1r * 256 + q1g * 16 + q1b >= q2r * 256 + q2g * 16 + q2b then 1 else 0
|
||||
local d = DIST[band(rshift(hi, 2), 1) * 4 + band(hi, 1) * 2 + order + 1]
|
||||
local c1r, c1g, c1b, c2r, c2g, c2b = q1r * 17, q1g * 17, q1b * 17, q2r * 17, q2g * 17, q2b * 17
|
||||
P[1] = rgb(c1r + d, c1g + d, c1b + d)
|
||||
P[2] = rgb(c1r - d, c1g - d, c1b - d)
|
||||
P[3] = rgb(c2r + d, c2g + d, c2b + d)
|
||||
P[4] = rgb(c2r - d, c2g - d, c2b - d)
|
||||
elseif etc2 and (B2 < 0 or B2 > 31) then
|
||||
-- planar (always opaque)
|
||||
local ro = band(rshift(hi, 25), 63)
|
||||
local go = band(rshift(hi, 24), 1) * 64 + band(rshift(hi, 17), 63)
|
||||
local bo = band(rshift(hi, 16), 1) * 32 + band(rshift(hi, 11), 3) * 8 + band(rshift(hi, 7), 7)
|
||||
local rh = band(rshift(hi, 2), 31) * 2 + band(hi, 1)
|
||||
local gh, bh = band(rshift(lo, 25), 127), band(rshift(lo, 19), 63)
|
||||
local rv, gv, bv = band(rshift(lo, 13), 63), band(rshift(lo, 6), 127), band(lo, 63)
|
||||
ro, rh, rv = ro * 4 + rshift(ro, 4), rh * 4 + rshift(rh, 4), rv * 4 + rshift(rv, 4)
|
||||
go, gh, gv = go * 2 + rshift(go, 6), gh * 2 + rshift(gh, 6), gv * 2 + rshift(gv, 6)
|
||||
bo, bh, bv = bo * 4 + rshift(bo, 4), bh * 4 + rshift(bh, 4), bv * 4 + rshift(bv, 4)
|
||||
for y = 0, 3 do
|
||||
for x = 0, 3 do
|
||||
local r = (x * (rh - ro) + y * (rv - ro) + 4 * ro + 2) // 4
|
||||
local g = (x * (gh - go) + y * (gv - go) + 4 * go + 2) // 4
|
||||
local b = (x * (bh - bo) + y * (bv - bo) + 4 * bo + 2) // 4
|
||||
writeu32(blk, (y * 4 + x) * 4, rgb(r, g, b))
|
||||
end
|
||||
end
|
||||
return
|
||||
else
|
||||
r1, g1, b1 = R * 8 + rshift(R, 2), G * 8 + rshift(G, 2), B * 8 + rshift(B, 2)
|
||||
r2, g2, b2 = R2 * 8 + rshift(R2, 2), G2 * 8 + rshift(G2, 2), B2 * 8 + rshift(B2, 2)
|
||||
end
|
||||
if not r1 then
|
||||
-- T / H: the paint colours by index
|
||||
for i = 0, 15 do
|
||||
local x, y = rshift(i, 2), band(i, 3)
|
||||
local idx = pix(lo, i)
|
||||
local c = if not opaque and idx == 2 then 0 else P[idx + 1]
|
||||
writeu32(blk, (y * 4 + x) * 4, c)
|
||||
end
|
||||
return
|
||||
end
|
||||
end
|
||||
local t1, t2 = MOD[band(rshift(hi, 5), 7) + 1], MOD[band(rshift(hi, 2), 7) + 1]
|
||||
for i = 0, 15 do
|
||||
local x, y = rshift(i, 2), band(i, 3)
|
||||
local second = if flip == 0 then x >= 2 else y >= 2
|
||||
local idx = pix(lo, i)
|
||||
local c
|
||||
if not opaque and idx == 2 then
|
||||
c = 0
|
||||
else
|
||||
local m = if second then t2[idx + 1] else t1[idx + 1]
|
||||
if not opaque and idx == 0 then
|
||||
m = 0
|
||||
end
|
||||
if second then
|
||||
c = rgb((r2 :: number) + m, (g2 :: number) + m, (b2 :: number) + m)
|
||||
else
|
||||
c = rgb((r1 :: number) + m, (g1 :: number) + m, (b1 :: number) + m)
|
||||
end
|
||||
end
|
||||
writeu32(blk, (y * 4 + x) * 4, c)
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ EAC
|
||||
local VALS = table.create(16, 0)
|
||||
|
||||
-- the 16 values of the EAC block at p into VALS (raster order): mode "alpha" (8-bit), "u11" / "s11" (11-bit)
|
||||
local function eac(src: buffer, p: number, mode: string)
|
||||
local base = readu8(src, p)
|
||||
local b1 = readu8(src, p + 1)
|
||||
local mult, tab = rshift(b1, 4), EAC[band(b1, 15) + 1]
|
||||
-- 48 index bits, pixel 0 (column-major) first: bytes 2..7 big-endian, as 24 + 24 bits
|
||||
local hiIdx = readu8(src, p + 2) * 65536 + readu8(src, p + 3) * 256 + readu8(src, p + 4)
|
||||
local loIdx = readu8(src, p + 5) * 65536 + readu8(src, p + 6) * 256 + readu8(src, p + 7)
|
||||
if mode == "s11" then
|
||||
if base >= 128 then
|
||||
base -= 256
|
||||
end
|
||||
if base == -128 then
|
||||
base = -127
|
||||
end
|
||||
end
|
||||
for i = 0, 15 do
|
||||
local idx = if i < 8 then band(rshift(hiIdx, 21 - i * 3), 7) else band(rshift(loIdx, 21 - (i - 8) * 3), 7)
|
||||
local m = tab[idx + 1]
|
||||
local v
|
||||
if mode == "alpha" then
|
||||
v = clamp8(base + m * mult)
|
||||
elseif mode == "u11" then
|
||||
v = if mult == 0 then base * 8 + 4 + m else base * 8 + 4 + m * mult * 8
|
||||
v = if v < 0 then 0 elseif v > 2047 then 2047 else v
|
||||
else
|
||||
v = if mult == 0 then base * 8 + m else base * 8 + m * mult * 8
|
||||
v = if v < -1023 then -1023 elseif v > 1023 then 1023 else v
|
||||
end
|
||||
VALS[band(i, 3) * 4 + rshift(i, 2) + 1] = v
|
||||
end
|
||||
end
|
||||
|
||||
-- 11-bit values -> 8 / 16 bits
|
||||
local function to8(v: number, signed: boolean): number
|
||||
if signed then
|
||||
return math.floor(v * 127 / 1023 + 0.5) + 128
|
||||
end
|
||||
return math.floor(v * 255 / 2047 + 0.5)
|
||||
end
|
||||
local function to16(v: number, signed: boolean): number
|
||||
if signed then
|
||||
return math.floor((v + 1023) * 65535 / 2046 + 0.5)
|
||||
end
|
||||
return v * 32 + rshift(v, 6)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- size(kind, w, h) -> bytes of the block data | nil for an unknown kind
|
||||
function Etc.size(kind: string, w: number, h: number): number?
|
||||
local b = Etc.BLOCK[kind]
|
||||
return if b then ((w + 3) // 4) * ((h + 3) // 4) * b else nil
|
||||
end
|
||||
|
||||
-- decode(kind, src, offset, w, h, out?, outOffset?, wide?) -> pixels | nil, message. rgba8, or rgba16 for the EAC
|
||||
-- kinds when wide is true.
|
||||
function Etc.decode(kind: string, src: buffer, offset: number, w: number, h: number, out: buffer?, outOffset: number?, wide: boolean?): (buffer?, string?)
|
||||
local bytes = Etc.BLOCK[kind]
|
||||
if not bytes then
|
||||
return nil, "unsupported: unknown block format " .. tostring(kind)
|
||||
end
|
||||
if w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 then
|
||||
return nil, "bad image size"
|
||||
end
|
||||
local need = Etc.size(kind, w, h) :: number
|
||||
if offset < 0 or offset + need > buffer.len(src) then
|
||||
return nil, "truncated: block data runs past the end"
|
||||
end
|
||||
local isEac = string.sub(kind, 1, 3) == "eac"
|
||||
local w16 = isEac and wide == true
|
||||
local bpp = if w16 then 8 else 4
|
||||
local oo = outOffset or 0
|
||||
local dst = out or buffer.create(w * h * bpp)
|
||||
if oo + w * h * bpp > buffer.len(dst) then
|
||||
return nil, "output buffer too small"
|
||||
end
|
||||
local signed = kind == "eac_r11s" or kind == "eac_rg11s"
|
||||
local two = kind == "eac_rg11" or kind == "eac_rg11s"
|
||||
local mode11 = if signed then "s11" else "u11"
|
||||
local etc2 = kind ~= "etc1"
|
||||
local punch = kind == "etc2_rgba1"
|
||||
local blk = buffer.create(16 * bpp)
|
||||
local bw, bh = (w + 3) // 4, (h + 3) // 4
|
||||
local p = offset
|
||||
local rowBytes = w * bpp
|
||||
for by = 0, bh - 1 do
|
||||
local rows = math.min(4, h - by * 4)
|
||||
for bx = 0, bw - 1 do
|
||||
if isEac then
|
||||
eac(src, p, mode11)
|
||||
for i = 0, 15 do
|
||||
local v = VALS[i + 1]
|
||||
if w16 then
|
||||
local q = to16(v, signed)
|
||||
writeu16(blk, i * 8, q)
|
||||
writeu16(blk, i * 8 + 2, if two then 0 else q)
|
||||
writeu16(blk, i * 8 + 4, if two then 0 else q)
|
||||
writeu16(blk, i * 8 + 6, 65535)
|
||||
else
|
||||
local q = to8(v, signed)
|
||||
writeu32(blk, i * 4, if two then q + 0xFF000000 else q + q * 256 + q * 65536 + 0xFF000000)
|
||||
end
|
||||
end
|
||||
if two then
|
||||
eac(src, p + 8, mode11)
|
||||
for i = 0, 15 do
|
||||
local v = VALS[i + 1]
|
||||
if w16 then
|
||||
writeu16(blk, i * 8 + 2, to16(v, signed))
|
||||
else
|
||||
writeu8(blk, i * 4 + 1, to8(v, signed))
|
||||
end
|
||||
end
|
||||
end
|
||||
elseif kind == "etc2_rgba" then
|
||||
colour(src, p + 8, blk, true, false)
|
||||
eac(src, p, "alpha")
|
||||
for i = 0, 15 do
|
||||
writeu8(blk, i * 4 + 3, VALS[i + 1])
|
||||
end
|
||||
else
|
||||
colour(src, p, blk, etc2, punch)
|
||||
end
|
||||
p += bytes
|
||||
local cols = math.min(4, w - bx * 4)
|
||||
local base = oo + (by * 4) * rowBytes + bx * 4 * bpp
|
||||
for y = 0, rows - 1 do
|
||||
buffer.copy(dst, base + y * rowBytes, blk, y * 4 * bpp, cols * bpp)
|
||||
end
|
||||
end
|
||||
end
|
||||
return dst, nil
|
||||
end
|
||||
|
||||
return Etc
|
||||
@@ -0,0 +1,74 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/image/Half: IEEE 754 binary16 ("half") <-> number, for the float texel formats (DDS / KTX R16F..., BC6H,
|
||||
-- OpenEXR HALF channels). New in formats-luau. Never throws.
|
||||
--
|
||||
-- local f = Half.TABLE[h] -- the number of every half bit pattern 0..65535 (a 65536-entry table)
|
||||
-- local f = Half.toFloat(h) -- the same, computed
|
||||
-- local h = Half.fromFloat(f) -- round to nearest even; overflow -> infinity, NaN -> a quiet NaN
|
||||
local Half = {}
|
||||
|
||||
local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift
|
||||
|
||||
-- toFloat(h) -> number (h a 16-bit pattern)
|
||||
local function toFloat(h: number): number
|
||||
local s = if h >= 32768 then -1 else 1
|
||||
local e = band(rshift(h, 10), 31)
|
||||
local m = band(h, 1023)
|
||||
if e == 0 then
|
||||
return s * m * 2 ^ -24
|
||||
elseif e == 31 then
|
||||
return if m == 0 then s * math.huge else 0 / 0
|
||||
end
|
||||
return s * (1024 + m) * 2 ^ (e - 25)
|
||||
end
|
||||
Half.toFloat = toFloat
|
||||
|
||||
local TABLE: { [number]: number } = table.create(65536, 0)
|
||||
for h = 0, 65535 do
|
||||
TABLE[h] = toFloat(h)
|
||||
end
|
||||
Half.TABLE = TABLE
|
||||
|
||||
local scratch = buffer.create(4)
|
||||
|
||||
-- fromFloat(f) -> the nearest half bit pattern (ties to even)
|
||||
function Half.fromFloat(f: number): number
|
||||
if f ~= f then
|
||||
return 0x7E00
|
||||
end
|
||||
buffer.writef32(scratch, 0, f)
|
||||
local x = buffer.readu32(scratch, 0)
|
||||
local sign = band(rshift(x, 16), 0x8000)
|
||||
local e = band(rshift(x, 23), 0xFF)
|
||||
local m = band(x, 0x7FFFFF)
|
||||
if e == 255 then
|
||||
return bor(sign, 0x7C00)
|
||||
end
|
||||
local ne = e - 112
|
||||
if ne >= 31 then
|
||||
return bor(sign, 0x7C00)
|
||||
elseif ne <= 0 then
|
||||
if ne < -10 then
|
||||
return sign
|
||||
end
|
||||
m = bor(m, 0x800000)
|
||||
local shift = 14 - ne
|
||||
local hm = rshift(m, shift)
|
||||
local rem = band(m, lshift(1, shift) - 1)
|
||||
local halfway = lshift(1, shift - 1)
|
||||
if rem > halfway or (rem == halfway and band(hm, 1) == 1) then
|
||||
hm += 1
|
||||
end
|
||||
return sign + hm
|
||||
end
|
||||
local hm = rshift(m, 13)
|
||||
local rem = band(m, 0x1FFF)
|
||||
if rem > 0x1000 or (rem == 0x1000 and band(hm, 1) == 1) then
|
||||
hm += 1 -- a carry out of the mantissa bumps the exponent (up to infinity), as it should
|
||||
end
|
||||
return sign + ne * 1024 + hm
|
||||
end
|
||||
|
||||
return Half
|
||||
@@ -0,0 +1,398 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/image/Texel: uncompressed GPU texel formats -> the standard pixel formats, shared by the texture containers
|
||||
-- (DDS's DXGI and legacy bit-mask formats, KTX's Vulkan / OpenGL formats, ...). New in formats-luau. Formats are named
|
||||
-- lower case, channels from the lowest address / bit up (DXGI order): r8, rg8, rgb8, bgr8, rgba8, bgra8, bgrx8, a8,
|
||||
-- l8, la8, r16, rgba16, *s (snorm), *ui / *i (integers), *f (half / float: r16f ... rgba32f), and the packed ones:
|
||||
-- b5g6r5, r5g6b5, b5g5r5a1, a1b5g5r5, b4g4r4a4, a4b4g4r4, a4r4g4b4, rgb10a2, bgr10a2, r11g11b10f, rgb9e5; any other
|
||||
-- bit-mask layout through Texel.masked(bytes, rMask, gMask, bMask, aMask, luminance?). Never throws.
|
||||
--
|
||||
-- local px, fmt = Texel.decode("bgra8", buf, offset, w, h) -- rgba8 pixels
|
||||
-- local px, fmt = Texel.decode("rgba16f", buf, offset, w, h, true) -- native: rgbaf32 (float) / rgba16 (16-bit)
|
||||
-- local desc = Texel.masked(2, 0xF800, 0x07E0, 0x001F, 0) -- a descriptor, accepted by decode
|
||||
--
|
||||
-- Channels: one-channel formats (r*, l*) are grey (r = g = b), two-channel ones red + green; missing alpha is opaque.
|
||||
-- rgba8 output: unorm rescaled with rounding, snorm biased (8-bit: s + 128), floats clamped to 0..1, integers clamped
|
||||
-- to 0..255. Native output: rgba8 when every channel fits 8 bits unsigned, rgba16 for 9..16-bit unorm, else rgbaf32
|
||||
-- (snorm -> -1..1, integers as their values).
|
||||
local Half = require("@formats/codecs/image/Half")
|
||||
|
||||
local Texel = {}
|
||||
|
||||
export type Channel = { c: string, shift: number, bits: number } -- packed channels (c = r g b a l)
|
||||
export type Desc = {
|
||||
bytes: number, -- per texel
|
||||
kind: "array" | "packed" | "r11g11b10f" | "rgb9e5" | "pair" | "ayuv",
|
||||
size: number?, -- array: bytes per component (1, 2, 4)
|
||||
type: string?, -- array: unorm / snorm / uint / sint / float
|
||||
order: string?, -- array: the components in memory (r g b a l x); pair: the 4 bytes of 2 pixels (yuyv, uyvy, rgbg, grgb)
|
||||
channels: { Channel }?, -- packed: unorm fields of a little-endian 16 / 32-bit word
|
||||
}
|
||||
|
||||
local readu8, readu16, readu32, readi8, readi16, readi32, readf32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi8, buffer.readi16, buffer.readi32, buffer.readf32
|
||||
local writeu8, writeu16, writeu32, writef32 = buffer.writeu8, buffer.writeu16, buffer.writeu32, buffer.writef32
|
||||
local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift
|
||||
local HALF = Half.TABLE
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ formats
|
||||
local FORMATS: { [string]: Desc } = {}
|
||||
local function array(name: string, size: number, typ: string, order: string)
|
||||
FORMATS[name] = { bytes = size * #order, kind = "array", size = size, type = typ, order = order }
|
||||
end
|
||||
for _, o in { "r", "rg", "rgb", "rgba" } do
|
||||
array(o .. "8", 1, "unorm", o)
|
||||
array(o .. "8s", 1, "snorm", o)
|
||||
array(o .. "8ui", 1, "uint", o)
|
||||
array(o .. "8i", 1, "sint", o)
|
||||
array(o .. "16", 2, "unorm", o)
|
||||
array(o .. "16s", 2, "snorm", o)
|
||||
array(o .. "16ui", 2, "uint", o)
|
||||
array(o .. "16i", 2, "sint", o)
|
||||
array(o .. "16f", 2, "float", o)
|
||||
array(o .. "32ui", 4, "uint", o)
|
||||
array(o .. "32i", 4, "sint", o)
|
||||
array(o .. "32f", 4, "float", o)
|
||||
end
|
||||
array("bgr8", 1, "unorm", "bgr")
|
||||
array("bgra8", 1, "unorm", "bgra")
|
||||
array("bgrx8", 1, "unorm", "bgrx")
|
||||
array("rgbx8", 1, "unorm", "rgbx")
|
||||
array("a8", 1, "unorm", "a")
|
||||
array("l8", 1, "unorm", "l")
|
||||
array("la8", 1, "unorm", "la")
|
||||
array("l16", 2, "unorm", "l")
|
||||
array("la16", 2, "unorm", "la")
|
||||
array("a16", 2, "unorm", "a")
|
||||
|
||||
local function packed(name: string, bytes: number, spec: { any })
|
||||
local ch: { Channel } = {}
|
||||
for i = 1, #spec, 3 do
|
||||
table.insert(ch, { c = spec[i], shift = spec[i + 1], bits = spec[i + 2] })
|
||||
end
|
||||
FORMATS[name] = { bytes = bytes, kind = "packed", channels = ch }
|
||||
end
|
||||
packed("b5g6r5", 2, { "b", 0, 5, "g", 5, 6, "r", 11, 5 })
|
||||
packed("r5g6b5", 2, { "r", 0, 5, "g", 5, 6, "b", 11, 5 })
|
||||
packed("b5g5r5a1", 2, { "b", 0, 5, "g", 5, 5, "r", 10, 5, "a", 15, 1 })
|
||||
packed("b5g5r5x1", 2, { "b", 0, 5, "g", 5, 5, "r", 10, 5 })
|
||||
packed("a1b5g5r5", 2, { "a", 0, 1, "b", 1, 5, "g", 6, 5, "r", 11, 5 })
|
||||
packed("a1r5g5b5", 2, { "a", 0, 1, "r", 1, 5, "g", 6, 5, "b", 11, 5 })
|
||||
packed("b4g4r4a4", 2, { "b", 0, 4, "g", 4, 4, "r", 8, 4, "a", 12, 4 })
|
||||
packed("r4g4b4a4", 2, { "r", 0, 4, "g", 4, 4, "b", 8, 4, "a", 12, 4 })
|
||||
packed("a4b4g4r4", 2, { "a", 0, 4, "b", 4, 4, "g", 8, 4, "r", 12, 4 })
|
||||
packed("a4r4g4b4", 2, { "a", 0, 4, "r", 4, 4, "g", 8, 4, "b", 12, 4 })
|
||||
packed("rgb10a2", 4, { "r", 0, 10, "g", 10, 10, "b", 20, 10, "a", 30, 2 })
|
||||
packed("bgr10a2", 4, { "b", 0, 10, "g", 10, 10, "r", 20, 10, "a", 30, 2 })
|
||||
packed("r3g3b2", 1, { "b", 0, 2, "g", 2, 3, "r", 5, 3 })
|
||||
FORMATS.r11g11b10f = { bytes = 4, kind = "r11g11b10f" }
|
||||
FORMATS.rgb9e5 = { bytes = 4, kind = "rgb9e5" }
|
||||
-- 4:2:2 pairs (2 pixels in 4 bytes; bytes = per pixel) and 4:4:4 AYUV (bytes V U Y A); Y'CbCr is BT.601 limited range
|
||||
FORMATS.yuy2 = { bytes = 2, kind = "pair", order = "yuyv" }
|
||||
FORMATS.uyvy = { bytes = 2, kind = "pair", order = "uyvy" }
|
||||
FORMATS.rgbg = { bytes = 2, kind = "pair", order = "rgbg" }
|
||||
FORMATS.grgb = { bytes = 2, kind = "pair", order = "grgb" }
|
||||
FORMATS.ayuv = { bytes = 4, kind = "ayuv" }
|
||||
Texel.FORMATS = FORMATS
|
||||
|
||||
-- masked(bytes, r, g, b, a, luminance?) -> a packed descriptor from bit masks (DDS legacy pixel formats); luminance:
|
||||
-- the r mask is a luminance channel
|
||||
function Texel.masked(bytes: number, r: number, g: number, b: number, a: number, luminance: boolean?): Desc?
|
||||
if bytes < 1 or bytes > 4 then
|
||||
return nil
|
||||
end
|
||||
local ch: { Channel } = {}
|
||||
for i, m in { r, g, b, a } do
|
||||
if m ~= 0 then
|
||||
local shift = 0
|
||||
while band(m, lshift(1, shift)) == 0 and shift < 31 do
|
||||
shift += 1
|
||||
end
|
||||
local bits = 0
|
||||
while shift + bits < 32 and band(m, lshift(1, shift + bits)) ~= 0 do
|
||||
bits += 1
|
||||
end
|
||||
local name = if i == 1 then (if luminance then "l" else "r") elseif i == 2 then "g" elseif i == 3 then "b" else "a"
|
||||
table.insert(ch, { c = name, shift = shift, bits = bits })
|
||||
end
|
||||
end
|
||||
if #ch == 0 then
|
||||
return nil
|
||||
end
|
||||
return { bytes = bytes, kind = "packed", channels = ch }
|
||||
end
|
||||
|
||||
-- size(fmt, w, h) -> bytes (rows tightly packed) | nil
|
||||
function Texel.size(fmt: string | Desc, w: number, h: number): number?
|
||||
local d = if type(fmt) == "string" then FORMATS[fmt] else fmt
|
||||
if not d then
|
||||
return nil
|
||||
end
|
||||
return if d.kind == "pair" then ((w + 1) // 2) * 4 * h else d.bytes * w * h
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ helpers
|
||||
-- the native output of a descriptor: rgba8 / rgba16 / rgbaf32
|
||||
local function nativeOf(d: Desc): string
|
||||
if d.kind == "array" then
|
||||
local t, s = d.type, d.size :: number
|
||||
if t == "float" or t == "snorm" or t == "sint" or (t == "uint" and s > 1) then
|
||||
return "rgbaf32"
|
||||
end
|
||||
return if s == 1 then "rgba8" else "rgba16"
|
||||
elseif d.kind == "packed" then
|
||||
local wide = false
|
||||
for _, c in d.channels :: { Channel } do
|
||||
wide = wide or c.bits > 8
|
||||
end
|
||||
return if wide then "rgba16" else "rgba8"
|
||||
end
|
||||
return "rgbaf32"
|
||||
end
|
||||
Texel.nativeOf = nativeOf
|
||||
|
||||
local function uf11(v: number): number
|
||||
local e, m = rshift(v, 6), band(v, 63)
|
||||
if e == 0 then
|
||||
return m / 64 * 2 ^ -14
|
||||
elseif e == 31 then
|
||||
return if m == 0 then math.huge else 0 / 0
|
||||
end
|
||||
return (1 + m / 64) * 2 ^ (e - 15)
|
||||
end
|
||||
local function uf10(v: number): number
|
||||
local e, m = rshift(v, 5), band(v, 31)
|
||||
if e == 0 then
|
||||
return m / 32 * 2 ^ -14
|
||||
elseif e == 31 then
|
||||
return if m == 0 then math.huge else 0 / 0
|
||||
end
|
||||
return (1 + m / 32) * 2 ^ (e - 15)
|
||||
end
|
||||
|
||||
-- one component at q of an array format -> a float (native meaning) and its rgba8 byte
|
||||
local function component(src: buffer, q: number, size: number, typ: string): (number, number)
|
||||
if typ == "unorm" then
|
||||
if size == 1 then
|
||||
local v = readu8(src, q)
|
||||
return v / 255, v
|
||||
elseif size == 2 then
|
||||
local v = readu16(src, q)
|
||||
return v / 65535, (v * 255 + 32767) // 65535
|
||||
end
|
||||
local v = readu32(src, q)
|
||||
return v / 4294967295, math.floor(v / 4294967295 * 255 + 0.5)
|
||||
elseif typ == "snorm" then
|
||||
if size == 1 then
|
||||
local v = math.max(readi8(src, q), -127)
|
||||
return v / 127, v + 128
|
||||
elseif size == 2 then
|
||||
local v = math.max(readi16(src, q), -32767)
|
||||
return v / 32767, math.floor(v * 127 / 32767 + 0.5) + 128
|
||||
end
|
||||
local v = math.max(readi32(src, q), -2147483647)
|
||||
return v / 2147483647, math.floor(v * 127 / 2147483647 + 0.5) + 128
|
||||
elseif typ == "float" then
|
||||
local f = if size == 2 then HALF[readu16(src, q)] else readf32(src, q)
|
||||
local c = if f ~= f then 0 elseif f < 0 then 0 elseif f > 1 then 1 else f
|
||||
return f, math.floor(c * 255 + 0.5)
|
||||
elseif typ == "uint" then
|
||||
local v = if size == 1 then readu8(src, q) elseif size == 2 then readu16(src, q) else readu32(src, q)
|
||||
return v, math.min(v, 255)
|
||||
end
|
||||
local v = if size == 1 then readi8(src, q) elseif size == 2 then readi16(src, q) else readi32(src, q)
|
||||
return v, math.clamp(v, 0, 255)
|
||||
end
|
||||
|
||||
-- BT.601 limited-range Y'CbCr -> an rgba8 u32
|
||||
local function ycc(y: number, u: number, v: number, a: number): number
|
||||
local c, d, e = 1.164 * (y - 16), u - 128, v - 128
|
||||
local r = math.clamp(math.floor(c + 1.596 * e + 0.5), 0, 255)
|
||||
local g = math.clamp(math.floor(c - 0.392 * d - 0.813 * e + 0.5), 0, 255)
|
||||
local b = math.clamp(math.floor(c + 2.017 * d + 0.5), 0, 255)
|
||||
return r + g * 256 + b * 65536 + a * 16777216
|
||||
end
|
||||
|
||||
-- the 4:2:2 pair formats and AYUV -> rgba8 (out is always rgba8: 8-bit sources)
|
||||
local function yuv(d: Desc, src: buffer, offset: number, w: number, h: number, pitch: number, dst: buffer): buffer
|
||||
local n = 0
|
||||
local order = d.order or ""
|
||||
for y = 0, h - 1 do
|
||||
local s = offset + y * pitch
|
||||
for x = 0, w - 1 do
|
||||
if d.kind == "ayuv" then
|
||||
local q = s + x * 4
|
||||
writeu32(dst, n, ycc(readu8(src, q + 2), readu8(src, q + 1), readu8(src, q), readu8(src, q + 3)))
|
||||
else
|
||||
local q = s + (x // 2) * 4
|
||||
local b0, b1, b2, b3 = readu8(src, q), readu8(src, q + 1), readu8(src, q + 2), readu8(src, q + 3)
|
||||
local odd = x % 2 == 1
|
||||
if order == "yuyv" then
|
||||
writeu32(dst, n, ycc(if odd then b2 else b0, b1, b3, 255))
|
||||
elseif order == "uyvy" then
|
||||
writeu32(dst, n, ycc(if odd then b3 else b1, b0, b2, 255))
|
||||
elseif order == "rgbg" then
|
||||
writeu32(dst, n, b0 + (if odd then b3 else b1) * 256 + b2 * 65536 + 0xFF000000)
|
||||
else
|
||||
writeu32(dst, n, b1 + (if odd then b2 else b0) * 256 + b3 * 65536 + 0xFF000000)
|
||||
end
|
||||
end
|
||||
n += 4
|
||||
end
|
||||
end
|
||||
return dst
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- decode(fmt, src, offset, w, h, native?, rowPitch?) -> pixels, pixel format ("rgba8" / "rgba16" / "rgbaf32") | nil,
|
||||
-- message. rowPitch: bytes per source row (default tight).
|
||||
function Texel.decode(fmt: string | Desc, src: buffer, offset: number, w: number, h: number, native: boolean?, rowPitch: number?): (buffer?, string)
|
||||
local d = if type(fmt) == "string" then FORMATS[fmt] else fmt
|
||||
if not d then
|
||||
return nil, "unsupported: unknown texel format " .. tostring(fmt)
|
||||
end
|
||||
local tb = d.bytes
|
||||
local rowBytes = if d.kind == "pair" then ((w + 1) // 2) * 4 else tb * w
|
||||
local pitch = rowPitch or rowBytes
|
||||
if w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or pitch < rowBytes then
|
||||
return nil, "bad image size"
|
||||
end
|
||||
if offset < 0 or offset + pitch * (h - 1) + rowBytes > buffer.len(src) then
|
||||
return nil, "truncated: texel data runs past the end"
|
||||
end
|
||||
local out = if native and d.kind ~= "pair" and d.kind ~= "ayuv" then nativeOf(d) else "rgba8"
|
||||
local bpp = if out == "rgba8" then 4 elseif out == "rgba16" then 8 else 16
|
||||
local dst = buffer.create(w * h * bpp)
|
||||
local n = 0
|
||||
if d.kind == "array" then
|
||||
local order, size, typ = d.order :: string, d.size :: number, d.type :: string
|
||||
-- fast paths
|
||||
if size == 1 and typ == "unorm" and out == "rgba8" and (order == "rgba" or order == "bgra" or order == "bgrx" or order == "rgbx") then
|
||||
local swap = order == "bgra" or order == "bgrx"
|
||||
local opaque = order == "bgrx" or order == "rgbx"
|
||||
for y = 0, h - 1 do
|
||||
local s = offset + y * pitch
|
||||
for x = 0, w - 1 do
|
||||
local v = readu32(src, s + x * 4)
|
||||
if swap then
|
||||
v = band(v, 0xFF00FF00) + band(rshift(v, 16), 0xFF) + lshift(band(v, 0xFF), 16)
|
||||
end
|
||||
if opaque then
|
||||
v = band(v, 0xFFFFFF) + 0xFF000000
|
||||
end
|
||||
writeu32(dst, n, v)
|
||||
n += 4
|
||||
end
|
||||
end
|
||||
return dst, out
|
||||
end
|
||||
local nc = #order
|
||||
local map = table.create(nc, 0) -- component -> output channel 0..3, 4 = grey, -1 = skip
|
||||
for i = 1, nc do
|
||||
local c = string.sub(order, i, i)
|
||||
map[i] = if c == "r" then (if nc == 1 then 4 else 0) elseif c == "g" then 1 elseif c == "b" then 2 elseif c == "a" then 3 elseif c == "l" then 4 else -1
|
||||
end
|
||||
local f = table.create(4, 0)
|
||||
local q8 = table.create(4, 0)
|
||||
for y = 0, h - 1 do
|
||||
local s = offset + y * pitch
|
||||
for _ = 0, w - 1 do
|
||||
f[1], f[2], f[3], f[4] = 0, 0, 0, 1
|
||||
q8[1], q8[2], q8[3], q8[4] = 0, 0, 0, 255
|
||||
for i = 1, nc do
|
||||
local m = map[i]
|
||||
if m >= 0 then
|
||||
local fv, bv = component(src, s, size, typ)
|
||||
if m == 4 then
|
||||
f[1], f[2], f[3] = fv, fv, fv
|
||||
q8[1], q8[2], q8[3] = bv, bv, bv
|
||||
else
|
||||
f[m + 1], q8[m + 1] = fv, bv
|
||||
end
|
||||
end
|
||||
s += size
|
||||
end
|
||||
if out == "rgba8" then
|
||||
writeu32(dst, n, q8[1] + q8[2] * 256 + q8[3] * 65536 + q8[4] * 16777216)
|
||||
elseif out == "rgba16" then
|
||||
for c = 0, 3 do
|
||||
writeu16(dst, n + c * 2, math.floor(math.clamp(f[c + 1], 0, 1) * 65535 + 0.5))
|
||||
end
|
||||
else
|
||||
for c = 0, 3 do
|
||||
writef32(dst, n + c * 4, f[c + 1])
|
||||
end
|
||||
end
|
||||
n += bpp
|
||||
end
|
||||
end
|
||||
return dst, out
|
||||
elseif d.kind == "packed" then
|
||||
local chs = d.channels :: { Channel }
|
||||
for y = 0, h - 1 do
|
||||
local s = offset + y * pitch
|
||||
for _ = 0, w - 1 do
|
||||
local v = if tb == 1 then readu8(src, s) elseif tb == 2 then readu16(src, s) elseif tb == 3 then readu16(src, s) + readu8(src, s + 2) * 65536 else readu32(src, s)
|
||||
s += tb
|
||||
local r, g, b, a = 0, 0, 0, 1
|
||||
for _, c in chs do
|
||||
local maxv = lshift(1, c.bits) - 1
|
||||
local x = band(rshift(v, c.shift), maxv) / (if c.bits >= 32 then 4294967295 else maxv)
|
||||
local k = c.c
|
||||
if k == "r" then
|
||||
r = x
|
||||
elseif k == "g" then
|
||||
g = x
|
||||
elseif k == "b" then
|
||||
b = x
|
||||
elseif k == "a" then
|
||||
a = x
|
||||
else
|
||||
r, g, b = x, x, x
|
||||
end
|
||||
end
|
||||
if out == "rgba8" then
|
||||
writeu32(dst, n, math.floor(r * 255 + 0.5) + math.floor(g * 255 + 0.5) * 256 + math.floor(b * 255 + 0.5) * 65536 + math.floor(a * 255 + 0.5) * 16777216)
|
||||
else
|
||||
writeu16(dst, n, math.floor(r * 65535 + 0.5))
|
||||
writeu16(dst, n + 2, math.floor(g * 65535 + 0.5))
|
||||
writeu16(dst, n + 4, math.floor(b * 65535 + 0.5))
|
||||
writeu16(dst, n + 6, math.floor(a * 65535 + 0.5))
|
||||
end
|
||||
n += bpp
|
||||
end
|
||||
end
|
||||
return dst, out
|
||||
end
|
||||
if d.kind == "pair" or d.kind == "ayuv" then
|
||||
return yuv(d, src, offset, w, h, pitch, dst), out
|
||||
end
|
||||
-- shared-exponent / packed floats
|
||||
local nine = d.kind == "rgb9e5"
|
||||
for y = 0, h - 1 do
|
||||
local s = offset + y * pitch
|
||||
for _ = 0, w - 1 do
|
||||
local v = readu32(src, s)
|
||||
s += 4
|
||||
local sc = if nine then 2 ^ (rshift(v, 27) - 24) else 0
|
||||
local r: number = if nine then band(v, 511) * sc else uf11(band(v, 2047))
|
||||
local g: number = if nine then band(rshift(v, 9), 511) * sc else uf11(band(rshift(v, 11), 2047))
|
||||
local b: number = if nine then band(rshift(v, 18), 511) * sc else uf10(rshift(v, 22))
|
||||
if out == "rgba8" then
|
||||
local function q(x: number): number
|
||||
return if x ~= x or x <= 0 then 0 elseif x >= 1 then 255 else math.floor(x * 255 + 0.5)
|
||||
end
|
||||
writeu32(dst, n, q(r) + q(g) * 256 + q(b) * 65536 + 0xFF000000)
|
||||
else
|
||||
writef32(dst, n, r)
|
||||
writef32(dst, n + 4, g)
|
||||
writef32(dst, n + 8, b)
|
||||
writef32(dst, n + 12, 1)
|
||||
end
|
||||
n += bpp
|
||||
end
|
||||
end
|
||||
return dst, out
|
||||
end
|
||||
|
||||
return Texel
|
||||
@@ -0,0 +1,162 @@
|
||||
--!strict
|
||||
-- codecs/image/Texture: one entry point over the texture pixel codecs for the texture containers (DDS, KTX, VTF, ...):
|
||||
-- a format name is a BCn kind (codecs/image/Bcn), an ETC / EAC kind (codecs/image/Etc) or a texel format
|
||||
-- (codecs/image/Texel); decode / size dispatch on it, surfaces() assembles mip levels / faces / layers into one
|
||||
-- Types.Image, halve() makes the next mip level of an image for writers. New in formats-luau. Never throws.
|
||||
--
|
||||
-- local px, pf = Texture.decode("bc7", buf, offset, w, h, native) -- pixels + their pixel format
|
||||
-- Texture.size("etc2_rgb", w, h) -- bytes of one surface
|
||||
-- local img = Texture.image(px, pf, w, h) -- a Types.Image around them
|
||||
-- local smaller = Texture.halve(img) -- box-filtered next mip level
|
||||
local Types = require("@formats/Types")
|
||||
local Bcn = require("@formats/codecs/image/Bcn")
|
||||
local Etc = require("@formats/codecs/image/Etc")
|
||||
local Texel = require("@formats/codecs/image/Texel")
|
||||
local Half = require("@formats/codecs/image/Half")
|
||||
|
||||
local Texture = {}
|
||||
|
||||
-- known(name) -> "bcn" | "etc" | "texel" | nil
|
||||
function Texture.known(name: string): string?
|
||||
if Bcn.BLOCK[name] then
|
||||
return "bcn"
|
||||
elseif Etc.BLOCK[name] then
|
||||
return "etc"
|
||||
elseif Texel.FORMATS[name] then
|
||||
return "texel"
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- size(name, w, h) -> bytes of a w x h surface | nil
|
||||
function Texture.size(name: string, w: number, h: number): number?
|
||||
return Bcn.size(name, w, h) or Etc.size(name, w, h) or Texel.size(name, w, h)
|
||||
end
|
||||
|
||||
-- block(name) -> block width, height, bytes (1, 1, texel bytes for texel formats) | nil
|
||||
function Texture.block(name: string): (number?, number?, number?)
|
||||
local b = Bcn.BLOCK[name] or Etc.BLOCK[name]
|
||||
if b then
|
||||
return 4, 4, b
|
||||
end
|
||||
local d = Texel.FORMATS[name]
|
||||
if d then
|
||||
return 1, 1, d.bytes
|
||||
end
|
||||
return nil, nil, nil
|
||||
end
|
||||
|
||||
-- decode(name, src, offset, w, h, native?) -> pixels, pixel format | nil, message. Without native the result is
|
||||
-- rgba8 (BC6H and float texels clamped to 0..1); native keeps rgbaf32 (BC6H, floats) / rgba16 (EAC, 16-bit unorm).
|
||||
function Texture.decode(name: string, src: buffer, offset: number, w: number, h: number, native: boolean?): (buffer?, string)
|
||||
if Bcn.BLOCK[name] then
|
||||
local px, err = Bcn.decode(name, src, offset, w, h)
|
||||
if not px then
|
||||
return nil, err or "bad block data"
|
||||
end
|
||||
if Bcn.FLOAT[name] then
|
||||
if native then
|
||||
return px, "rgbaf32"
|
||||
end
|
||||
local out = buffer.create(w * h * 4)
|
||||
for i = 0, w * h - 1 do
|
||||
for c = 0, 3 do
|
||||
local v = buffer.readf32(px, i * 16 + c * 4)
|
||||
buffer.writeu8(out, i * 4 + c, if v ~= v or v <= 0 then 0 elseif v >= 1 then 255 else math.floor(v * 255 + 0.5))
|
||||
end
|
||||
end
|
||||
return out, "rgba8"
|
||||
end
|
||||
return px, "rgba8"
|
||||
elseif Etc.BLOCK[name] then
|
||||
local wide = native == true and string.sub(name, 1, 3) == "eac"
|
||||
local px, err = Etc.decode(name, src, offset, w, h, nil, 0, wide)
|
||||
if not px then
|
||||
return nil, err or "bad block data"
|
||||
end
|
||||
return px, if wide then "rgba16" else "rgba8"
|
||||
end
|
||||
return Texel.decode(name, src, offset, w, h, native)
|
||||
end
|
||||
|
||||
-- image(pixels, pixel format, w, h) -> Types.Image
|
||||
function Texture.image(px: buffer, pf: string, w: number, h: number): Types.Image
|
||||
local img = Types.Image.new(0, 0, pf :: any)
|
||||
img.width, img.height, img.pixels = w, h, px
|
||||
return img
|
||||
end
|
||||
|
||||
export type Surface = { level: number, layer: number, face: number, slice: number, image: Types.Image }
|
||||
|
||||
-- assemble(surfaces, layout) -> the Image of the first surface with img.frames = every level-0 surface (faces /
|
||||
-- layers / depth slices in order, when more than one) and img.meta.mipmaps = the smaller levels of the first surface
|
||||
function Texture.assemble(list: { Surface }, layout: string): Types.Image?
|
||||
local first: Types.Image? = nil
|
||||
local frames: { Types.Frame } = {}
|
||||
local mips: { Types.Image } = {}
|
||||
for _, s in list do
|
||||
if s.level == 0 then
|
||||
first = first or s.image
|
||||
local fr: Types.Frame = { image = s.image, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" }
|
||||
table.insert(frames, fr)
|
||||
elseif s.layer == 0 and s.face == 0 and s.slice == 0 then
|
||||
mips[s.level] = s.image
|
||||
end
|
||||
end
|
||||
if not first then
|
||||
return nil
|
||||
end
|
||||
local img = Texture.image(first.pixels, first.format, first.width, first.height)
|
||||
if #frames > 1 then
|
||||
img.frames = frames
|
||||
end
|
||||
if #mips > 0 then
|
||||
img.meta.mipmaps = mips
|
||||
end
|
||||
img.meta.layout = layout
|
||||
return img
|
||||
end
|
||||
|
||||
-- halve(img) -> the next mip level (each dimension halved, at least 1; 2 x 2 box filter), same pixel format
|
||||
-- (rgba8 / rgba16 / rgbaf32)
|
||||
function Texture.halve(img: Types.Image): Types.Image
|
||||
local w, h = img.width, img.height
|
||||
local nw, nh = math.max(1, w // 2), math.max(1, h // 2)
|
||||
local fmt = img.format
|
||||
local out = Types.Image.new(nw, nh, fmt)
|
||||
local src, dst = img.pixels, out.pixels
|
||||
local cs = if fmt == "rgba8" then 1 elseif fmt == "rgba16" then 2 else 4
|
||||
local function get(x: number, y: number, c: number): number
|
||||
local o = ((math.min(y, h - 1) * w + math.min(x, w - 1)) * 4 + c) * cs
|
||||
return if cs == 1 then buffer.readu8(src, o) elseif cs == 2 then buffer.readu16(src, o) else buffer.readf32(src, o)
|
||||
end
|
||||
for y = 0, nh - 1 do
|
||||
for x = 0, nw - 1 do
|
||||
for c = 0, 3 do
|
||||
local x0, y0 = x * 2, y * 2
|
||||
local v = (get(x0, y0, c) + get(x0 + 1, y0, c) + get(x0, y0 + 1, c) + get(x0 + 1, y0 + 1, c)) / 4
|
||||
local o = ((y * nw + x) * 4 + c) * cs
|
||||
if cs == 1 then
|
||||
buffer.writeu8(dst, o, math.floor(v + 0.5))
|
||||
elseif cs == 2 then
|
||||
buffer.writeu16(dst, o, math.floor(v + 0.5))
|
||||
else
|
||||
buffer.writef32(dst, o, v)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- toHalf(rgbaf32 pixels, n) -> rgba16f texels (for writers)
|
||||
function Texture.toHalf(px: buffer, n: number): buffer
|
||||
local out = buffer.create(n * 8)
|
||||
local from = Half.fromFloat
|
||||
for i = 0, n * 4 - 1 do
|
||||
buffer.writeu16(out, i * 2, from(buffer.readf32(px, i * 4)))
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
return Texture
|
||||
@@ -0,0 +1,183 @@
|
||||
--!strict
|
||||
-- image/ani: Windows animated cursors (RIFF "ACON": the anih header, rate / seq chunks, LIST fram of icon chunks;
|
||||
-- containers/Riff; new code). Decode: every step of the animation as img.frames (the seq order when there is one,
|
||||
-- each step's rate or the default iDispRate in jiffies of 1/60 s as the delay), the icon chunks (ICO / CUR files)
|
||||
-- through the api hook opts.decodeImage (F.load passes it; without it: UNSUPPORTED), the hotspots of CUR frames
|
||||
-- (frame image meta.hotspot), INFO title / author (meta.text). The image is the first step; img.loops = 0 (cursors
|
||||
-- loop forever). Encode: img.frames (or the image) through opts.encodeImage(frame, "ico") as icon chunks, with a
|
||||
-- rate chunk when the delays differ. Not supported: raw (non-icon) frame bitmaps (AF_ICON clear: UNSUPPORTED).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Riff = require("@formats/containers/Riff")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Ani = {
|
||||
name = "ani",
|
||||
category = "image",
|
||||
extensions = { "ani" },
|
||||
mime = { "application/x-navi-animation" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Riff" },
|
||||
caps = { decode = true, encode = true, alpha = true, animation = true, frames = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, -- decodes the ICO / CUR frames (the api passes one)
|
||||
maxFrames: number?, -- refuse more steps (default 10000)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, -- writes the ICO / CUR frames (the api passes one)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Ani.sniff(r: Bytes.Reader): number
|
||||
return if r:peek(4) == "RIFF" and r:peek(4, 8) == "ACON" then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Ani.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
||||
local f, ferr = Riff.read(r)
|
||||
if not f then
|
||||
return nil, ferr
|
||||
end
|
||||
if f.form ~= "ACON" then
|
||||
return nil, Err.new(Err.CORRUPT, "not an ACON form", r.base + 8)
|
||||
end
|
||||
local anih = Riff.find(f, "anih")
|
||||
if not anih or anih.avail < 36 then
|
||||
return nil, Err.new(Err.CORRUPT, "missing anih header", r.base + 12)
|
||||
end
|
||||
local a = anih.offset
|
||||
local nFrames, nSteps = Riff.u32(f, a + 4), Riff.u32(f, a + 8)
|
||||
local dispRate, flags = Riff.u32(f, a + 28), Riff.u32(f, a + 32)
|
||||
local maxFrames = opts and opts.maxFrames or 10000
|
||||
if nSteps == 0 then
|
||||
nSteps = nFrames
|
||||
end
|
||||
if nFrames > maxFrames or nSteps > maxFrames then
|
||||
return nil, Err.new(Err.LIMIT, "too many frames", a + 4)
|
||||
end
|
||||
if bit32.band(flags, 1) == 0 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "raw frame bitmaps (AF_ICON clear)", a + 32)
|
||||
end
|
||||
local decodeImage = opts and opts.decodeImage
|
||||
if not decodeImage then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "icon frames need the decodeImage hook")
|
||||
end
|
||||
-- the icon chunks
|
||||
local icons: { Types.Image } = {}
|
||||
for _, c in f.chunks do
|
||||
if c.id == "LIST" and Riff.listType(f, c) == "fram" then
|
||||
for _, ic in Riff.list(f, c) do
|
||||
if ic.id == "icon" then
|
||||
local sub = buffer.create(ic.avail)
|
||||
buffer.copy(sub, 0, f.buf, ic.offset, ic.avail)
|
||||
local ok, im, ierr = pcall(decodeImage, sub)
|
||||
if not ok or not im then
|
||||
return nil, Err.new(Err.CORRUPT, "frame " .. (#icons + 1) .. ": " .. tostring(if ok then ierr else im), ic.offset)
|
||||
end
|
||||
table.insert(icons, im :: Types.Image)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if #icons == 0 then
|
||||
return nil, Err.new(Err.TRUNCATED, "no icon frames")
|
||||
end
|
||||
local rate = Riff.find(f, "rate")
|
||||
local seq = Riff.find(f, "seq ")
|
||||
local frames: { Types.Frame } = {}
|
||||
for s = 0, nSteps - 1 do
|
||||
local idx = s
|
||||
if seq and seq.avail >= (s + 1) * 4 then
|
||||
idx = Riff.u32(f, seq.offset + s * 4)
|
||||
end
|
||||
local im = icons[idx + 1]
|
||||
if not im then
|
||||
if s >= #icons and not seq then
|
||||
break -- fewer icons than steps: keep what is there
|
||||
end
|
||||
return nil, Err.new(Err.CORRUPT, "step " .. s .. " names frame " .. idx)
|
||||
end
|
||||
local jiffies = dispRate
|
||||
if rate and rate.avail >= (s + 1) * 4 then
|
||||
jiffies = Riff.u32(f, rate.offset + s * 4)
|
||||
end
|
||||
table.insert(frames, { image = im, delay = jiffies / 60, x = 0, y = 0, dispose = "background", blend = "source" } :: Types.Frame)
|
||||
end
|
||||
local first = frames[1].image
|
||||
local img = Types.Image.new(0, 0, first.format)
|
||||
img.width, img.height, img.pixels = first.width, first.height, first.pixels
|
||||
img.frames = frames
|
||||
img.loops = 0
|
||||
img.meta.hotspot = first.meta.hotspot
|
||||
local text: { [string]: string } = {}
|
||||
for _, c in f.chunks do
|
||||
if c.id == "LIST" and Riff.listType(f, c) == "INFO" then
|
||||
for _, it in Riff.list(f, c) do
|
||||
local key = if it.id == "INAM" then "title" elseif it.id == "IART" then "author" else nil
|
||||
if key then
|
||||
text[key] = (string.gsub(buffer.readstring(f.buf, it.offset, it.avail), "%z+$", ""))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if next(text) then
|
||||
img.meta.text = text
|
||||
end
|
||||
img.meta.source = { format = "ani", frames = #icons, steps = #frames, sequence = seq ~= nil, rate = dispRate }
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Ani.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(img) ~= "table" or type(img.pixels) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "needs an Image")
|
||||
end
|
||||
local encodeImage = opts and opts.encodeImage
|
||||
if not encodeImage then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "icon frames need the encodeImage hook")
|
||||
end
|
||||
local frames: { Types.Frame } = if type(img.frames) == "table" and #img.frames > 0 then img.frames else { { image = img, delay = 1 / 6, x = 0, y = 0, dispose = "background", blend = "source" } :: Types.Frame }
|
||||
local w = Riff.writer("ACON")
|
||||
local jiffies: { number } = {}
|
||||
local same = true
|
||||
for i, fr in frames do
|
||||
jiffies[i] = math.max(1, math.floor((fr.delay or 0) * 60 + 0.5))
|
||||
same = same and jiffies[i] == jiffies[1]
|
||||
end
|
||||
local head = Bytes.writer(36)
|
||||
head:u32le(36)
|
||||
head:u32le(#frames)
|
||||
head:u32le(#frames)
|
||||
head:u32le(0)
|
||||
head:u32le(0)
|
||||
head:u32le(0)
|
||||
head:u32le(0)
|
||||
head:u32le(jiffies[1])
|
||||
head:u32le(1)
|
||||
w:chunk("anih", head:finish())
|
||||
if not same then
|
||||
local rw = Bytes.writer(#frames * 4)
|
||||
for _, j in jiffies do
|
||||
rw:u32le(j)
|
||||
end
|
||||
w:chunk("rate", rw:finish())
|
||||
end
|
||||
local items = {}
|
||||
for i, fr in frames do
|
||||
local im = fr.image
|
||||
local ok, data, err = pcall(encodeImage, im, "ico")
|
||||
if not ok or not data then
|
||||
return nil, Err.new(Err.ARG, "frame " .. i .. ": " .. tostring(if ok then err else data))
|
||||
end
|
||||
table.insert(items, { "icon", data })
|
||||
end
|
||||
w:list("fram", items)
|
||||
return w:finish()
|
||||
end
|
||||
|
||||
return Ani
|
||||
@@ -0,0 +1,497 @@
|
||||
--!strict
|
||||
-- image/dds: DirectDraw Surface (Microsoft "DDS" programming guide: DDS_HEADER, DDS_PIXELFORMAT, DDS_HEADER_DXT10; new
|
||||
-- code). Decode: every DXGI format with a pixel layout (BC1..BC7 through codecs/image/Bcn; the uncompressed UNORM /
|
||||
-- SNORM / UINT / SINT / FLOAT / packed / shared-exponent ones and YUY2 / AYUV / RGBG through codecs/image/Texel), the
|
||||
-- legacy FourCC codes (DXT1..DXT5, ATI1 / BC4U / BC4S, ATI2 / BC5U / BC5S, RXGB, YUY2 / UYVY / RGBG / GRGB, the
|
||||
-- D3DFMT float / 16-bit numbers) and legacy bit-mask RGB / luminance / alpha formats; mip chains, cube maps (all six
|
||||
-- faces or a subset), texture arrays (DX10 arraySize) and volume textures. The first surface is the image; when there
|
||||
-- are more (faces, layers, depth slices) img.frames lists every one of them (meta.layout = "2d" / "cube" / "array" /
|
||||
-- "volume", meta.faces), and with opts.mips the smaller levels of the first surface go to img.meta.mipmaps. rgba8 by
|
||||
-- default (BC6H and float formats clamped to 0..1); opts.native keeps rgbaf32 / rgba16 where the source has more.
|
||||
-- Encode: rgba8 as uncompressed (R8G8B8A8 / B8G8R8A8), BC1 / BC3 / BC4 / BC5 (legacy FourCC headers), rgba16 / rgbaf32
|
||||
-- as DX10 R16G16B16A16_UNORM / R32G32B32A32_FLOAT / R16G16B16A16_FLOAT; optional mip chains (box filter) and the
|
||||
-- frames as a texture array or a cube map. Not supported: planar video formats (NV12, P010, ...), palettes (P8),
|
||||
-- 1-bit R1_UNORM, the depth-stencil formats with stencil channels, BC encoders other than 1 / 3 / 4 / 5.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Sniff = require("@formats/core/Sniff")
|
||||
local Types = require("@formats/Types")
|
||||
local Bcn = require("@formats/codecs/image/Bcn")
|
||||
local Texel = require("@formats/codecs/image/Texel")
|
||||
local Texture = require("@formats/codecs/image/Texture")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Dds = {
|
||||
name = "dds",
|
||||
category = "image",
|
||||
extensions = { "dds" },
|
||||
mime = { "image/vnd-ms.dds", "image/x-dds" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Bcn", "codecs/image/Texel", "codecs/image/Texture" },
|
||||
caps = { decode = true, encode = true, alpha = true, float = true, mipmaps = true, cubemap = true, compressed = { "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7" } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
native: boolean?, -- keep rgbaf32 / rgba16 for float / 16-bit / BC6H sources (default false: rgba8)
|
||||
mips: boolean?, -- decode the smaller mip levels of the first surface into img.meta.mipmaps (default false)
|
||||
surfaces: boolean?, -- decode every face / layer / slice into img.frames (default true)
|
||||
maxPixels: number?, -- refuse larger images (default 2^26, counted over every decoded surface)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
pixelFormat: ("rgba8" | "bgra8" | "bc1" | "bc3" | "bc4" | "bc5" | "rgba16" | "rgba16f" | "rgba32f")?, -- default:
|
||||
-- rgba8 for rgba8 images, rgba16 / rgba32f for rgba16 / rgbaf32 ones
|
||||
mips: boolean?, -- write a full mip chain (default false)
|
||||
dx10: boolean?, -- always write the DX10 header (default: only when the format needs it, or for arrays)
|
||||
cube: boolean?, -- write img.frames (6) as a cube map (default: when img.meta.layout == "cube")
|
||||
alphaThreshold: number?, -- BC1: alpha below this is transparent (default 128)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
-- DXGI_FORMAT -> texture format name, sRGB
|
||||
local DXGI: { [number]: string } = {
|
||||
[1] = "rgba32f", [2] = "rgba32f", [3] = "rgba32ui", [4] = "rgba32i",
|
||||
[5] = "rgb32f", [6] = "rgb32f", [7] = "rgb32ui", [8] = "rgb32i",
|
||||
[9] = "rgba16", [10] = "rgba16f", [11] = "rgba16", [12] = "rgba16ui", [13] = "rgba16s", [14] = "rgba16i",
|
||||
[15] = "rg32f", [16] = "rg32f", [17] = "rg32ui", [18] = "rg32i",
|
||||
[23] = "rgb10a2", [24] = "rgb10a2", [26] = "r11g11b10f",
|
||||
[27] = "rgba8", [28] = "rgba8", [29] = "rgba8", [30] = "rgba8ui", [31] = "rgba8s", [32] = "rgba8i",
|
||||
[33] = "rg16", [34] = "rg16f", [35] = "rg16", [36] = "rg16ui", [37] = "rg16s", [38] = "rg16i",
|
||||
[39] = "r32f", [40] = "r32f", [41] = "r32f", [42] = "r32ui", [43] = "r32i",
|
||||
[48] = "rg8", [49] = "rg8", [50] = "rg8ui", [51] = "rg8s", [52] = "rg8i",
|
||||
[53] = "r16", [54] = "r16f", [55] = "r16", [56] = "r16", [57] = "r16ui", [58] = "r16s", [59] = "r16i",
|
||||
[60] = "r8", [61] = "r8", [62] = "r8ui", [63] = "r8s", [64] = "r8i", [65] = "a8",
|
||||
[67] = "rgb9e5", [68] = "rgbg", [69] = "grgb",
|
||||
[70] = "bc1", [71] = "bc1", [72] = "bc1", [73] = "bc2", [74] = "bc2", [75] = "bc2", [76] = "bc3", [77] = "bc3", [78] = "bc3",
|
||||
[79] = "bc4", [80] = "bc4", [81] = "bc4s", [82] = "bc5", [83] = "bc5", [84] = "bc5s",
|
||||
[85] = "b5g6r5", [86] = "b5g5r5a1", [87] = "bgra8", [88] = "bgrx8", [90] = "bgra8", [91] = "bgra8", [92] = "bgrx8", [93] = "bgrx8",
|
||||
[94] = "bc6h", [95] = "bc6h", [96] = "bc6hs", [97] = "bc7", [98] = "bc7", [99] = "bc7",
|
||||
[100] = "ayuv", [107] = "yuy2", [115] = "b4g4r4a4", [191] = "a4b4g4r4",
|
||||
}
|
||||
local SRGB = { [29] = true, [72] = true, [75] = true, [78] = true, [91] = true, [93] = true, [99] = true }
|
||||
-- legacy FourCC codes (strings and D3DFMT numbers)
|
||||
local FOURCC: { [string]: string } = {
|
||||
DXT1 = "bc1", DXT2 = "bc2", DXT3 = "bc2", DXT4 = "bc3", DXT5 = "bc3", RXGB = "bc3",
|
||||
ATI1 = "bc4", BC4U = "bc4", BC4S = "bc4s", ATI2 = "bc5", BC5U = "bc5", BC5S = "bc5s",
|
||||
YUY2 = "yuy2", UYVY = "uyvy", RGBG = "rgbg", GRGB = "grgb",
|
||||
}
|
||||
local D3DFMT: { [number]: string } = {
|
||||
[36] = "rgba16", [110] = "rgba16s", [111] = "r16f", [112] = "rg16f", [113] = "rgba16f",
|
||||
[114] = "r32f", [115] = "rg32f", [116] = "rgba32f", [117] = "rg8s", [60] = "rg8s", [63] = "rgba8s", [64] = "rg16s",
|
||||
}
|
||||
local FACES = { "+x", "-x", "+y", "-y", "+z", "-z" }
|
||||
local MAGIC = "DDS "
|
||||
|
||||
local DDSD_MIPMAPCOUNT, DDSD_DEPTH = 0x20000, 0x800000
|
||||
local DDPF_ALPHAPIXELS, DDPF_ALPHA, DDPF_FOURCC, DDPF_RGB, DDPF_LUMINANCE, DDPF_BUMPDUDV = 0x1, 0x2, 0x4, 0x40, 0x20000, 0x80000
|
||||
local CAPS2_CUBEMAP, CAPS2_VOLUME = 0x200, 0x200000
|
||||
local MISC_CUBE = 0x4
|
||||
|
||||
local band = bit32.band
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Dds.sniff(r: Bytes.Reader): number
|
||||
return math.max(Sniff.magic(r, MAGIC .. "\124\0\0\0"), Sniff.magic(r, MAGIC, 0, 0.6))
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
export type Info = {
|
||||
width: number,
|
||||
height: number,
|
||||
depth: number,
|
||||
mips: number,
|
||||
format: string, -- the texture format name (codecs/image/Texture)
|
||||
layout: string, -- "2d" | "cube" | "array" | "volume"
|
||||
layers: number,
|
||||
faces: { string }, -- cube faces present (in file order), else { }
|
||||
srgb: boolean,
|
||||
dxgi: number?,
|
||||
fourcc: string?,
|
||||
dataOffset: number, -- relative to the file start
|
||||
alphaMode: number?,
|
||||
premultiplied: boolean?,
|
||||
masked: Texel.Desc?, -- legacy bit-mask formats (format = "masked" unless the masks have a name)
|
||||
}
|
||||
|
||||
local function u32(b: buffer, o: number): number
|
||||
return buffer.readu32(b, o)
|
||||
end
|
||||
|
||||
-- info(r) -> Info | nil, Err (the headers only)
|
||||
function Dds.info(r: Bytes.Reader): (Info?, Err.Err?)
|
||||
local b, o, n = r.buf, r.base, r.limit - r.base
|
||||
if n < 128 or buffer.readstring(b, o, 4) ~= MAGIC then
|
||||
return nil, Err.new(if n < 128 and n >= 4 and buffer.readstring(b, o, 4) == MAGIC then Err.TRUNCATED else Err.CORRUPT, "not a DDS file", o)
|
||||
end
|
||||
if u32(b, o + 4) ~= 124 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad header size " .. u32(b, o + 4), o + 4)
|
||||
end
|
||||
local flags = u32(b, o + 8)
|
||||
local h, w = u32(b, o + 12), u32(b, o + 16)
|
||||
local depth = u32(b, o + 24)
|
||||
local mips = u32(b, o + 28)
|
||||
local pfFlags, fourccNum = u32(b, o + 80), u32(b, o + 84)
|
||||
local bitCount = u32(b, o + 88)
|
||||
local rm, gm, bm, am = u32(b, o + 92), u32(b, o + 96), u32(b, o + 100), u32(b, o + 104)
|
||||
local caps2 = u32(b, o + 112)
|
||||
if w == 0 or h == 0 or w > 65536 or h > 65536 then
|
||||
return nil, Err.new(Err.CORRUPT, string.format("bad size %d x %d", w, h), o + 12)
|
||||
end
|
||||
if band(flags, DDSD_MIPMAPCOUNT) == 0 and mips > 1 and band(u32(b, o + 108), 0x400000) == 0 then
|
||||
mips = 1 -- a count without the flag or the caps bit: some writers leave garbage
|
||||
end
|
||||
mips = math.max(1, mips)
|
||||
local maxMips = 1
|
||||
do
|
||||
local m = math.max(w, h, depth)
|
||||
while m > 1 do
|
||||
m //= 2
|
||||
maxMips += 1
|
||||
end
|
||||
end
|
||||
if mips > maxMips then
|
||||
return nil, Err.new(Err.CORRUPT, "more mip levels than the size allows", o + 28)
|
||||
end
|
||||
local info: Info = {
|
||||
width = w,
|
||||
height = h,
|
||||
depth = 1,
|
||||
mips = mips,
|
||||
format = "",
|
||||
layout = "2d",
|
||||
layers = 1,
|
||||
faces = {},
|
||||
srgb = false,
|
||||
dataOffset = 128,
|
||||
}
|
||||
local volume = band(caps2, CAPS2_VOLUME) ~= 0 or band(flags, DDSD_DEPTH) ~= 0 and depth > 1
|
||||
if band(pfFlags, DDPF_FOURCC) ~= 0 then
|
||||
local fourcc = buffer.readstring(b, o + 84, 4)
|
||||
if fourcc == "DX10" then
|
||||
if n < 148 then
|
||||
return nil, Err.new(Err.TRUNCATED, "missing DX10 header", o + 128)
|
||||
end
|
||||
local dxgi, dim, misc, arr, misc2 = u32(b, o + 128), u32(b, o + 132), u32(b, o + 136), u32(b, o + 140), u32(b, o + 144)
|
||||
info.dxgi = dxgi
|
||||
info.dataOffset = 148
|
||||
local name = DXGI[dxgi]
|
||||
if not name then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "DXGI format " .. dxgi, o + 128)
|
||||
end
|
||||
info.format = name
|
||||
info.srgb = SRGB[dxgi] == true
|
||||
info.alphaMode = band(misc2, 7)
|
||||
info.premultiplied = band(misc2, 7) == 2
|
||||
info.layers = math.max(1, arr)
|
||||
if info.layers > 4096 then
|
||||
return nil, Err.new(Err.CORRUPT, "array size " .. arr, o + 140)
|
||||
end
|
||||
if dim == 4 then
|
||||
volume = true
|
||||
elseif dim ~= 2 and dim ~= 3 and dim ~= 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad resource dimension " .. dim, o + 132)
|
||||
else
|
||||
volume = false
|
||||
end
|
||||
if band(misc, MISC_CUBE) ~= 0 then
|
||||
info.layout = "cube"
|
||||
info.faces = table.clone(FACES)
|
||||
elseif info.layers > 1 then
|
||||
info.layout = "array"
|
||||
end
|
||||
else
|
||||
info.fourcc = fourcc
|
||||
local name = FOURCC[fourcc] or D3DFMT[fourccNum]
|
||||
if not name then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "FourCC " .. string.format("%q", fourcc), o + 84)
|
||||
end
|
||||
info.format = name
|
||||
info.premultiplied = fourcc == "DXT2" or fourcc == "DXT4"
|
||||
end
|
||||
elseif band(pfFlags, DDPF_RGB + DDPF_LUMINANCE + DDPF_ALPHA + DDPF_BUMPDUDV + 0x200) ~= 0 then
|
||||
local bytes = bitCount // 8
|
||||
if bitCount % 8 ~= 0 or bytes < 1 or bytes > 4 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, bitCount .. "-bit pixels", o + 88)
|
||||
end
|
||||
local lum = band(pfFlags, DDPF_LUMINANCE) ~= 0
|
||||
local alphaOnly = band(pfFlags, DDPF_ALPHA) ~= 0 and band(pfFlags, DDPF_RGB + DDPF_LUMINANCE) == 0
|
||||
local a = if band(pfFlags, DDPF_ALPHAPIXELS + DDPF_ALPHA) ~= 0 then am else 0
|
||||
local d
|
||||
if alphaOnly then
|
||||
d = Texel.masked(bytes, 0, 0, 0, if am ~= 0 then am else 0xFF)
|
||||
elseif band(pfFlags, DDPF_BUMPDUDV) ~= 0 then
|
||||
d = nil -- signed bump maps: handled by the D3DFMT names when they come as FourCC
|
||||
else
|
||||
d = Texel.masked(bytes, rm, if lum then 0 else gm, if lum then 0 else bm, a, lum)
|
||||
end
|
||||
if not d then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "pixel format masks", o + 92)
|
||||
end
|
||||
-- the common masks map onto named texel formats (fast paths, sane names)
|
||||
local key = string.format("%d:%x:%x:%x:%x:%s", bitCount, rm, gm, bm, a, tostring(lum))
|
||||
local named = ({
|
||||
["32:ff:ff00:ff0000:ff000000:false"] = "rgba8",
|
||||
["32:ff0000:ff00:ff:ff000000:false"] = "bgra8",
|
||||
["32:ff0000:ff00:ff:0:false"] = "bgrx8",
|
||||
["32:ff:ff00:ff0000:0:false"] = "rgbx8",
|
||||
["24:ff0000:ff00:ff:0:false"] = "bgr8",
|
||||
["24:ff:ff00:ff0000:0:false"] = "rgb8",
|
||||
["8:ff:0:0:0:true"] = "l8",
|
||||
["16:ffff:0:0:0:true"] = "l16",
|
||||
} :: { [string]: string })[key]
|
||||
info.format = named or "masked"
|
||||
info.masked = d
|
||||
else
|
||||
return nil, Err.new(Err.UNSUPPORTED, string.format("pixel format flags 0x%x", pfFlags), o + 80)
|
||||
end
|
||||
if volume then
|
||||
info.layout = "volume"
|
||||
info.depth = math.max(1, depth)
|
||||
if info.depth > 2048 then
|
||||
return nil, Err.new(Err.CORRUPT, "depth " .. depth, o + 24)
|
||||
end
|
||||
elseif band(caps2, CAPS2_CUBEMAP) ~= 0 and not info.dxgi then
|
||||
info.layout = "cube"
|
||||
for i, f in FACES do
|
||||
if band(caps2, bit32.lshift(0x400, i - 1)) ~= 0 then
|
||||
table.insert(info.faces, f)
|
||||
end
|
||||
end
|
||||
if #info.faces == 0 then
|
||||
info.faces = table.clone(FACES)
|
||||
end
|
||||
end
|
||||
return info, nil
|
||||
end
|
||||
|
||||
-- the bytes of one surface of format f
|
||||
local function surfaceSize(info: any, w: number, h: number): number
|
||||
if info.format == "masked" then
|
||||
return (info.masked :: Texel.Desc).bytes * w * h
|
||||
end
|
||||
return Texture.size(info.format, w, h) :: number
|
||||
end
|
||||
|
||||
function Dds.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
||||
local info, ierr = Dds.info(r)
|
||||
if not info then
|
||||
return nil, ierr
|
||||
end
|
||||
local native = opts and opts.native or false
|
||||
local wantMips = opts and opts.mips or false
|
||||
local wantAll = not (opts and opts.surfaces == false)
|
||||
local maxPixels = opts and opts.maxPixels or 2 ^ 26
|
||||
local b, base = r.buf, r.base
|
||||
local p = base + info.dataOffset
|
||||
local limit = r.limit
|
||||
local count = if info.layout == "cube" then #info.faces * info.layers else info.layers
|
||||
local list: { Texture.Surface } = {}
|
||||
local pixels = 0
|
||||
local stop = false
|
||||
for layer = 0, count - 1 do
|
||||
local w, h, d = info.width, info.height, info.depth
|
||||
for level = 0, info.mips - 1 do
|
||||
local size = surfaceSize(info, w, h)
|
||||
for slice = 0, d - 1 do
|
||||
local want = (level == 0 and (wantAll or (layer == 0 and slice == 0))) or (wantMips and layer == 0 and slice == 0)
|
||||
if want then
|
||||
if p + size > limit then
|
||||
if level > 0 or layer > 0 or slice > 0 then
|
||||
stop = true -- a cut mip chain / later surface: keep what decoded
|
||||
break
|
||||
end
|
||||
return nil, Err.new(Err.TRUNCATED, "surface data runs past the end", p)
|
||||
end
|
||||
pixels += w * h
|
||||
if pixels > maxPixels then
|
||||
return nil, Err.new(Err.LIMIT, string.format("over the %d pixel limit", maxPixels))
|
||||
end
|
||||
local px, pf
|
||||
if info.format == "masked" then
|
||||
px, pf = Texel.decode(info.masked :: Texel.Desc, b, p, w, h, native)
|
||||
else
|
||||
px, pf = Texture.decode(info.format, b, p, w, h, native)
|
||||
end
|
||||
if not px then
|
||||
return nil, Err.from(pf, p)
|
||||
end
|
||||
local face = if info.layout == "cube" then layer % #info.faces else 0
|
||||
table.insert(list, { level = level, layer = layer, face = face, slice = slice, image = Texture.image(px, pf, w, h) })
|
||||
end
|
||||
p += size
|
||||
end
|
||||
if stop then
|
||||
break
|
||||
end
|
||||
w, h, d = math.max(1, w // 2), math.max(1, h // 2), math.max(1, d // 2)
|
||||
end
|
||||
if stop then
|
||||
break
|
||||
end
|
||||
end
|
||||
local img = Texture.assemble(list, info.layout)
|
||||
if not img then
|
||||
return nil, Err.new(Err.TRUNCATED, "no surface data", base + info.dataOffset)
|
||||
end
|
||||
if info.layout == "cube" then
|
||||
img.meta.faces = info.faces
|
||||
end
|
||||
if info.srgb then
|
||||
img.meta.colorSpace = "srgb"
|
||||
elseif string.find(info.format, "f$") or info.format == "bc6h" or info.format == "bc6hs" or info.format == "rgb9e5" then
|
||||
img.meta.colorSpace = "linear"
|
||||
end
|
||||
img.meta.source = {
|
||||
format = "dds",
|
||||
pixelFormat = info.format,
|
||||
dxgi = info.dxgi,
|
||||
fourcc = info.fourcc,
|
||||
mips = info.mips,
|
||||
layers = info.layers,
|
||||
depth = info.depth,
|
||||
premultiplied = info.premultiplied,
|
||||
}
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
local BYTES_PF: { [string]: number } = { rgba8 = 4, bgra8 = 4, rgba16 = 8, rgba16f = 8, rgba32f = 16 }
|
||||
local DX10_OUT: { [string]: number } = { rgba8 = 28, bgra8 = 87, bc1 = 71, bc3 = 77, bc4 = 80, bc5 = 83, rgba16 = 11, rgba16f = 10, rgba32f = 2 }
|
||||
|
||||
-- the surface bytes of one image in format f
|
||||
local function surface(img: Types.Image, f: string, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local w, h, px = img.width, img.height, img.pixels
|
||||
if f == "bc1" or f == "bc3" or f == "bc4" or f == "bc5" then
|
||||
local blocks, err = Bcn.encode(f, px, w, h, opts and { alphaThreshold = opts.alphaThreshold } or nil)
|
||||
if not blocks then
|
||||
return nil, Err.new(Err.ARG, tostring(err))
|
||||
end
|
||||
return blocks, nil
|
||||
elseif f == "bgra8" then
|
||||
local out = buffer.create(w * h * 4)
|
||||
for i = 0, w * h - 1 do
|
||||
local v = buffer.readu32(px, i * 4)
|
||||
buffer.writeu32(out, i * 4, band(v, 0xFF00FF00) + band(bit32.rshift(v, 16), 0xFF) + bit32.lshift(band(v, 0xFF), 16))
|
||||
end
|
||||
return out, nil
|
||||
elseif f == "rgba16f" then
|
||||
return Texture.toHalf(px, w * h), nil
|
||||
end
|
||||
local out = buffer.create(w * h * (BYTES_PF[f] :: number))
|
||||
buffer.copy(out, 0, px, 0, buffer.len(out))
|
||||
return out, nil
|
||||
end
|
||||
|
||||
local function writeHeader(out: Bytes.Writer, w: number, h: number, f: string, mips: number, dx10: boolean, layers: number, cube: boolean)
|
||||
local blockFmt = f == "bc1" or f == "bc3" or f == "bc4" or f == "bc5"
|
||||
out:string(MAGIC)
|
||||
out:u32le(124)
|
||||
local flags = 0x1007 + (if mips > 1 then DDSD_MIPMAPCOUNT else 0) + (if blockFmt then 0x80000 else 0x8)
|
||||
out:u32le(flags)
|
||||
out:u32le(h)
|
||||
out:u32le(w)
|
||||
out:u32le(if blockFmt then Texture.size(f, w, h) :: number else w * (BYTES_PF[f] :: number))
|
||||
out:u32le(0)
|
||||
out:u32le(if mips > 1 then mips else 0)
|
||||
out:fill(0, 44)
|
||||
-- DDS_PIXELFORMAT
|
||||
out:u32le(32)
|
||||
if dx10 then
|
||||
out:u32le(DDPF_FOURCC)
|
||||
out:string("DX10")
|
||||
out:fill(0, 20)
|
||||
elseif blockFmt then
|
||||
out:u32le(DDPF_FOURCC)
|
||||
out:string(({ bc1 = "DXT1", bc3 = "DXT5", bc4 = "ATI1", bc5 = "ATI2" } :: { [string]: string })[f])
|
||||
out:fill(0, 20)
|
||||
else
|
||||
out:u32le(DDPF_RGB + DDPF_ALPHAPIXELS)
|
||||
out:u32le(0)
|
||||
out:u32le(32)
|
||||
if f == "bgra8" then
|
||||
out:u32le(0xFF0000)
|
||||
out:u32le(0xFF00)
|
||||
out:u32le(0xFF)
|
||||
else
|
||||
out:u32le(0xFF)
|
||||
out:u32le(0xFF00)
|
||||
out:u32le(0xFF0000)
|
||||
end
|
||||
out:u32le(0xFF000000)
|
||||
end
|
||||
out:u32le(0x1000 + (if mips > 1 then 0x400008 else 0) + (if cube then 0x8 else 0))
|
||||
out:u32le(if cube then 0xFE00 else 0)
|
||||
out:fill(0, 12)
|
||||
if dx10 then
|
||||
out:u32le(DX10_OUT[f])
|
||||
out:u32le(3)
|
||||
out:u32le(if cube then MISC_CUBE else 0)
|
||||
out:u32le(if cube then layers // 6 else layers)
|
||||
out:u32le(0)
|
||||
end
|
||||
end
|
||||
|
||||
function Dds.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "number" or img.width < 1 or img.height < 1 then
|
||||
return nil, Err.new(Err.ARG, "needs an Image")
|
||||
end
|
||||
local pf = img.format
|
||||
if pf ~= "rgba8" and pf ~= "rgba16" and pf ~= "rgbaf32" then
|
||||
return nil, Err.new(Err.ARG, "needs an rgba8, rgba16 or rgbaf32 Image (got " .. tostring(pf) .. ")")
|
||||
end
|
||||
local f: string = (opts and opts.pixelFormat) or (if pf == "rgba8" then "rgba8" elseif pf == "rgba16" then "rgba16" else "rgba32f")
|
||||
if not DX10_OUT[f] then
|
||||
return nil, Err.new(Err.ARG, "unknown pixelFormat " .. tostring(f))
|
||||
end
|
||||
local needs = if f == "rgba16" then "rgba16" elseif f == "rgba16f" or f == "rgba32f" then "rgbaf32" else "rgba8"
|
||||
if pf ~= needs then
|
||||
return nil, Err.new(Err.ARG, string.format("pixelFormat %s needs an %s Image", f, needs))
|
||||
end
|
||||
-- surfaces: the frames (array / cube faces) or the image
|
||||
local images: { Types.Image } = { img }
|
||||
if img.frames and #img.frames > 1 then
|
||||
images = {}
|
||||
for i, fr in img.frames do
|
||||
local fi = fr.image
|
||||
if type(fi) ~= "table" or fi.width ~= img.width or fi.height ~= img.height or fi.format ~= pf then
|
||||
return nil, Err.new(Err.ARG, "frame " .. i .. ": every surface needs the image's size and pixel format")
|
||||
end
|
||||
images[i] = fi
|
||||
end
|
||||
end
|
||||
local cube = if opts and opts.cube ~= nil then opts.cube else (img.meta and img.meta.layout == "cube")
|
||||
if cube and #images % 6 ~= 0 then
|
||||
return nil, Err.new(Err.ARG, "a cube map needs 6 faces per layer")
|
||||
end
|
||||
local dx10 = (opts and opts.dx10) or f == "rgba16" or f == "rgba16f" or f == "rgba32f" or (#images > 1 and not (cube and #images == 6))
|
||||
local mips = 1
|
||||
if opts and opts.mips then
|
||||
local m = math.max(img.width, img.height)
|
||||
while m > 1 do
|
||||
m //= 2
|
||||
mips += 1
|
||||
end
|
||||
end
|
||||
local out = Bytes.writer(img.width * img.height * 4 * #images + 200)
|
||||
writeHeader(out, img.width, img.height, f, mips, dx10, #images, cube == true)
|
||||
for _, im in images do
|
||||
local level = im
|
||||
for m = 1, mips do
|
||||
local data, err = surface(level, f, opts)
|
||||
if not data then
|
||||
return nil, err
|
||||
end
|
||||
out:bytes(data)
|
||||
if m < mips then
|
||||
level = Texture.halve(level)
|
||||
end
|
||||
end
|
||||
end
|
||||
return out:finish(), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
Dds.DXGI = DXGI
|
||||
|
||||
return Dds
|
||||
@@ -0,0 +1,117 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- image/exr/Codec: the OpenEXR byte-level codecs (from the OpenEXR file layout document and ImfZip / ImfRle, BSD-3-
|
||||
-- Clause): RLE and ZIP / ZIPS decode (run lengths or zlib, then the delta predictor and the two-half byte interleave),
|
||||
-- ZIP encode, and the per-line channel sample conversion to floats. Never throws.
|
||||
local Deflate = require("@formats/codecs/compress/Deflate")
|
||||
local Half = require("@formats/codecs/image/Half")
|
||||
|
||||
local Codec = {}
|
||||
|
||||
local readu8, writeu8, readi8, readu16, readu32, readf32, writef32 = buffer.readu8, buffer.writeu8, buffer.readi8, buffer.readu16, buffer.readu32, buffer.readf32, buffer.writef32
|
||||
local HALF = Half.TABLE
|
||||
|
||||
-- undoes the predictor and the interleave of t (n bytes) -> a new buffer
|
||||
local function reconstruct(t: buffer, n: number): buffer
|
||||
local prev = if n > 0 then readu8(t, 0) else 0
|
||||
for i = 1, n - 1 do
|
||||
prev = (prev + readu8(t, i) - 128) % 256
|
||||
writeu8(t, i, prev)
|
||||
end
|
||||
local out = buffer.create(n)
|
||||
local half = (n + 1) // 2
|
||||
for i = 0, half - 1 do
|
||||
writeu8(out, i * 2, readu8(t, i))
|
||||
end
|
||||
for i = 0, n - half - 1 do
|
||||
writeu8(out, i * 2 + 1, readu8(t, half + i))
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- rle(src, p, n, outSize) -> the raw block | nil, message
|
||||
function Codec.rle(src: buffer, p: number, n: number, outSize: number): (buffer?, string?)
|
||||
local t = buffer.create(outSize)
|
||||
local o, stop = 0, p + n
|
||||
while p < stop do
|
||||
local c = readi8(src, p)
|
||||
p += 1
|
||||
if c < 0 then
|
||||
local cnt = -c
|
||||
if p + cnt > stop or o + cnt > outSize then
|
||||
return nil, "bad RLE run"
|
||||
end
|
||||
buffer.copy(t, o, src, p, cnt)
|
||||
p += cnt
|
||||
o += cnt
|
||||
else
|
||||
if p >= stop or o + c + 1 > outSize then
|
||||
return nil, "bad RLE run"
|
||||
end
|
||||
buffer.fill(t, o, readu8(src, p), c + 1)
|
||||
p += 1
|
||||
o += c + 1
|
||||
end
|
||||
end
|
||||
if o ~= outSize then
|
||||
return nil, "RLE data too short"
|
||||
end
|
||||
return reconstruct(t, outSize), nil
|
||||
end
|
||||
|
||||
-- zip(src, p, n, outSize) -> the raw block | nil, message (ZIP and ZIPS)
|
||||
function Codec.unzip(src: buffer, p: number, n: number, outSize: number): (buffer?, string?)
|
||||
local t, err = Deflate.zlib(src, p, n, outSize)
|
||||
if not t then
|
||||
return nil, tostring(err)
|
||||
end
|
||||
if buffer.len(t) ~= outSize then
|
||||
return nil, "zlib block has the wrong size"
|
||||
end
|
||||
return reconstruct(t, outSize), nil
|
||||
end
|
||||
|
||||
-- zipEncode(raw, level) -> the compressed block (interleave, predictor, zlib)
|
||||
function Codec.zip(raw: buffer, level: number): buffer
|
||||
local n = buffer.len(raw)
|
||||
local t = buffer.create(n)
|
||||
local half = (n + 1) // 2
|
||||
for i = 0, n - 1 do
|
||||
local v = readu8(raw, i)
|
||||
if i % 2 == 0 then
|
||||
writeu8(t, i // 2, v)
|
||||
else
|
||||
writeu8(t, half + i // 2, v)
|
||||
end
|
||||
end
|
||||
local prev = if n > 0 then readu8(t, 0) else 0
|
||||
for i = 1, n - 1 do
|
||||
local v = readu8(t, i)
|
||||
writeu8(t, i, (v - prev + 384) % 256)
|
||||
prev = v
|
||||
end
|
||||
return Deflate.zlibCompress(t, { level = level }) :: buffer
|
||||
end
|
||||
|
||||
-- samples(src, p, count, kind, dst, d, step) -> reads count samples of kind (0 uint, 1 half, 2 float) at p into
|
||||
-- dst (f32) at byte offset d, step bytes apart; returns the source offset after them
|
||||
function Codec.samples(src: buffer, p: number, count: number, kind: number, dst: buffer, d: number, step: number): number
|
||||
if kind == 1 then
|
||||
for i = 0, count - 1 do
|
||||
writef32(dst, d + i * step, HALF[readu16(src, p + i * 2)])
|
||||
end
|
||||
return p + count * 2
|
||||
elseif kind == 2 then
|
||||
for i = 0, count - 1 do
|
||||
writef32(dst, d + i * step, readf32(src, p + i * 4))
|
||||
end
|
||||
else
|
||||
for i = 0, count - 1 do
|
||||
writef32(dst, d + i * step, readu32(src, p + i * 4))
|
||||
end
|
||||
end
|
||||
return p + count * 4
|
||||
end
|
||||
|
||||
return Codec
|
||||
@@ -0,0 +1,367 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- image/exr/Piz: OpenEXR's PIZ decompressor (written from the OpenEXR 3.x sources' algorithm description: ImfPizCompressor
|
||||
-- / ImfHuf / ImfWav, BSD-3-Clause, licenses/openexr-LICENSE.md): the range bitmap and its reverse LUT, the Huffman
|
||||
-- stream (packed code lengths, canonical codes, the run-length symbol), the 2-D Haar wavelet (14- and 16-bit
|
||||
-- variants) per channel plane, then the planes rearranged into scanlines. Never throws: nil, message on bad data.
|
||||
local Piz = {}
|
||||
|
||||
local readu8, readu16, writeu16, readu32 = buffer.readu8, buffer.readu16, buffer.writeu16, buffer.readu32
|
||||
local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift
|
||||
|
||||
local USHORT_RANGE, BITMAP_SIZE = 65536, 8192
|
||||
local HUF_ENCSIZE = 65537
|
||||
local DECBITS = 14
|
||||
local SHORT_ZEROCODE_RUN, LONG_ZEROCODE_RUN, SHORTEST_LONG_RUN = 59, 63, 6
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ Huffman
|
||||
-- the canonical code table: lengths[i] and codes[i] for symbols im..iM (1-based tables: symbol s at s + 1)
|
||||
local function unpackTable(src: buffer, p: number, limit: number, im: number, iM: number, len: { number }): number?
|
||||
local c, lc = 0, 0
|
||||
local function bits(n: number): number?
|
||||
while lc < n do
|
||||
if p >= limit then
|
||||
return nil
|
||||
end
|
||||
c = c * 256 + readu8(src, p)
|
||||
p += 1
|
||||
lc += 8
|
||||
end
|
||||
lc -= n
|
||||
local v = c // 2 ^ lc
|
||||
c -= v * 2 ^ lc
|
||||
return v
|
||||
end
|
||||
local i = im
|
||||
while i <= iM do
|
||||
local l = bits(6)
|
||||
if not l then
|
||||
return nil
|
||||
end
|
||||
if l == LONG_ZEROCODE_RUN then
|
||||
local z = bits(8)
|
||||
if not z then
|
||||
return nil
|
||||
end
|
||||
z += SHORTEST_LONG_RUN
|
||||
if i + z > iM + 1 then
|
||||
return nil
|
||||
end
|
||||
for k = i, i + z - 1 do
|
||||
len[k + 1] = 0
|
||||
end
|
||||
i += z
|
||||
elseif l >= SHORT_ZEROCODE_RUN then
|
||||
local z = l - SHORT_ZEROCODE_RUN + 2
|
||||
if i + z > iM + 1 then
|
||||
return nil
|
||||
end
|
||||
for k = i, i + z - 1 do
|
||||
len[k + 1] = 0
|
||||
end
|
||||
i += z
|
||||
else
|
||||
len[i + 1] = l
|
||||
i += 1
|
||||
end
|
||||
end
|
||||
return p
|
||||
end
|
||||
|
||||
-- hufUncompress: nRaw u16 values from [p, p + n) into out (a buffer of u16) | nil, message
|
||||
local function huffman(src: buffer, p: number, n: number, out: buffer, nRaw: number): string?
|
||||
if n == 0 then
|
||||
return if nRaw == 0 then nil else "empty Huffman data"
|
||||
end
|
||||
if n < 20 then
|
||||
return "truncated Huffman header"
|
||||
end
|
||||
local im, iM, nBits = readu32(src, p), readu32(src, p + 4), readu32(src, p + 12)
|
||||
if im >= HUF_ENCSIZE or iM >= HUF_ENCSIZE or im > iM then
|
||||
return "bad Huffman symbol range"
|
||||
end
|
||||
local limit = p + n
|
||||
local len = table.create(HUF_ENCSIZE, 0)
|
||||
local q = unpackTable(src, p + 20, limit, im, iM, len)
|
||||
if not q then
|
||||
return "bad Huffman table"
|
||||
end
|
||||
if q + (nBits + 7) // 8 > limit then
|
||||
return "truncated Huffman data"
|
||||
end
|
||||
-- canonical codes (OpenEXR's order: longest codes get the smallest values)
|
||||
local count = table.create(59, 0)
|
||||
for s = im, iM do
|
||||
local l = len[s + 1]
|
||||
if l > 58 then
|
||||
return "bad Huffman code length"
|
||||
end
|
||||
count[l + 1] += 1
|
||||
end
|
||||
local start = table.create(59, 0)
|
||||
local c = 0
|
||||
for l = 58, 1, -1 do
|
||||
local nc = (c + count[l + 1]) // 2
|
||||
start[l + 1] = c
|
||||
c = nc
|
||||
end
|
||||
local fast = buffer.create(lshift(1, DECBITS) * 4) -- (symbol + 1) * 64 + length; 0 = long or invalid
|
||||
local long: { [number]: { [number]: number } } = {}
|
||||
local maxLong = 0
|
||||
for s = im, iM do
|
||||
local l = len[s + 1]
|
||||
if l > 0 then
|
||||
local code = start[l + 1]
|
||||
start[l + 1] = code + 1
|
||||
if l <= DECBITS then
|
||||
local base = code * 2 ^ (DECBITS - l)
|
||||
local v = (s + 1) * 64 + l
|
||||
for k = base, base + 2 ^ (DECBITS - l) - 1 do
|
||||
if k < lshift(1, DECBITS) then
|
||||
buffer.writeu32(fast, k * 4, v)
|
||||
end
|
||||
end
|
||||
else
|
||||
if l > 52 then
|
||||
return "unsupported: Huffman code longer than 52 bits"
|
||||
end
|
||||
local t = long[l]
|
||||
if not t then
|
||||
t = {}
|
||||
long[l] = t
|
||||
end
|
||||
t[code] = s
|
||||
maxLong = math.max(maxLong, l)
|
||||
end
|
||||
end
|
||||
end
|
||||
-- decode MSB-first from a zero-padded copy
|
||||
local nbytes = (nBits + 7) // 8
|
||||
local data = buffer.create(nbytes + 8)
|
||||
buffer.copy(data, 0, src, q, nbytes)
|
||||
local bp = 0
|
||||
local o = 0
|
||||
local rlc = iM
|
||||
local mask = lshift(1, DECBITS) - 1
|
||||
while bp < nBits do
|
||||
local byte = rshift(bp, 3)
|
||||
local w = bit32.byteswap(readu32(data, byte))
|
||||
local peek = band(rshift(w, 32 - DECBITS - band(bp, 7)), mask)
|
||||
local e = readu32(fast, peek * 4)
|
||||
local sym: number, l: number = 0, 0
|
||||
if e ~= 0 then
|
||||
sym = e // 64 - 1
|
||||
l = band(e, 63)
|
||||
else
|
||||
-- a long code: bit by bit from length 15
|
||||
sym = -1
|
||||
local code = 0
|
||||
for k = 0, maxLong - 1 do
|
||||
local bitAt = bp + k
|
||||
code = code * 2 + band(rshift(readu8(data, rshift(bitAt, 3)), 7 - band(bitAt, 7)), 1)
|
||||
if k + 1 > DECBITS then
|
||||
local t = long[k + 1]
|
||||
local found: number? = if t then t[code] else nil
|
||||
if found then
|
||||
sym = found
|
||||
l = k + 1
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
if sym < 0 then
|
||||
return "invalid Huffman code"
|
||||
end
|
||||
end
|
||||
bp += l
|
||||
if bp > nBits then
|
||||
return "Huffman code past the end of the data"
|
||||
end
|
||||
if sym == rlc then
|
||||
if bp + 8 > nBits then
|
||||
return "truncated run length"
|
||||
end
|
||||
local b2 = bit32.byteswap(readu32(data, rshift(bp, 3)))
|
||||
local cs = band(rshift(b2, 24 - band(bp, 7)), 255)
|
||||
bp += 8
|
||||
if o + cs > nRaw then
|
||||
return "too much Huffman data"
|
||||
end
|
||||
if o == 0 then
|
||||
return "run length at the start"
|
||||
end
|
||||
local s = readu16(out, (o - 1) * 2)
|
||||
for _ = 1, cs do
|
||||
writeu16(out, o * 2, s)
|
||||
o += 1
|
||||
end
|
||||
else
|
||||
if o >= nRaw then
|
||||
return "too much Huffman data"
|
||||
end
|
||||
writeu16(out, o * 2, sym)
|
||||
o += 1
|
||||
end
|
||||
end
|
||||
if o ~= nRaw then
|
||||
return "not enough Huffman data"
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ wavelet
|
||||
-- the inverse 2-D Haar wavelet over n x ny u16 values at element offset base, strides ox / oy (in elements)
|
||||
local function wav2Decode(t: buffer, base: number, nx: number, ox: number, ny: number, oy: number, mx: number)
|
||||
local w14 = mx < 16384
|
||||
local n = math.min(nx, ny)
|
||||
local p = 1
|
||||
while p <= n do
|
||||
p *= 2
|
||||
end
|
||||
p //= 2
|
||||
local p2 = p
|
||||
p //= 2
|
||||
local function dec(l: number, h: number): (number, number)
|
||||
if w14 then
|
||||
local ls = if l >= 32768 then l - 65536 else l
|
||||
local hs = if h >= 32768 then h - 65536 else h
|
||||
local ai = ls + hs % 2 + hs // 2
|
||||
return ai % 65536, (ai - hs) % 65536
|
||||
end
|
||||
local bb = (l - rshift(h, 1)) % 65536
|
||||
return (h + bb - 32768) % 65536, bb
|
||||
end
|
||||
while p >= 1 do
|
||||
local oy1, oy2, ox1, ox2 = oy * p, oy * p2, ox * p, ox * p2
|
||||
local py = base
|
||||
local ey = base + oy * (ny - p2)
|
||||
while py <= ey do
|
||||
local px = py
|
||||
local ex = py + ox * (nx - p2)
|
||||
while px <= ex do
|
||||
local p01 = px + ox1
|
||||
local p10 = px + oy1
|
||||
local p11 = p10 + ox1
|
||||
local i00, i10 = dec(readu16(t, px * 2), readu16(t, p10 * 2))
|
||||
local i01, i11 = dec(readu16(t, p01 * 2), readu16(t, p11 * 2))
|
||||
local a, b = dec(i00, i01)
|
||||
writeu16(t, px * 2, a)
|
||||
writeu16(t, p01 * 2, b)
|
||||
local c, d = dec(i10, i11)
|
||||
writeu16(t, p10 * 2, c)
|
||||
writeu16(t, p11 * 2, d)
|
||||
px += ox2
|
||||
end
|
||||
if band(nx, p) ~= 0 then
|
||||
local p10 = px + oy1
|
||||
local a, b = dec(readu16(t, px * 2), readu16(t, p10 * 2))
|
||||
writeu16(t, px * 2, a)
|
||||
writeu16(t, p10 * 2, b)
|
||||
end
|
||||
py += oy2
|
||||
end
|
||||
if band(ny, p) ~= 0 then
|
||||
local px = py
|
||||
local ex = py + ox * (nx - p2)
|
||||
while px <= ex do
|
||||
local p01 = px + ox1
|
||||
local a, b = dec(readu16(t, px * 2), readu16(t, p01 * 2))
|
||||
writeu16(t, px * 2, a)
|
||||
writeu16(t, p01 * 2, b)
|
||||
px += ox2
|
||||
end
|
||||
end
|
||||
p2 = p
|
||||
p //= 2
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
export type Chan = { nx: number, ny: number, size: number, ys: number }
|
||||
|
||||
-- decode(src, p, n, chans, minY, maxY, outSize) -> the uncompressed block (scanline order) | nil, message.
|
||||
-- chans: per channel (sorted order) its sample counts nx / ny in the block, size (1 = half, 2 = float / uint) and
|
||||
-- ySampling.
|
||||
function Piz.decode(src: buffer, p: number, n: number, chans: { Chan }, minY: number, maxY: number, outSize: number): (buffer?, string?)
|
||||
local total = 0
|
||||
for _, c in chans do
|
||||
total += c.nx * c.ny * c.size
|
||||
end
|
||||
if total * 2 ~= outSize then
|
||||
return nil, "PIZ block size mismatch"
|
||||
end
|
||||
local out = buffer.create(outSize)
|
||||
if total == 0 then
|
||||
return out, nil
|
||||
end
|
||||
local limit = p + n
|
||||
if p + 4 > limit then
|
||||
return nil, "truncated PIZ header"
|
||||
end
|
||||
local minNZ, maxNZ = readu16(src, p), readu16(src, p + 2)
|
||||
p += 4
|
||||
if maxNZ >= BITMAP_SIZE then
|
||||
return nil, "bad PIZ bitmap range"
|
||||
end
|
||||
local bitmap = buffer.create(BITMAP_SIZE)
|
||||
if minNZ <= maxNZ then
|
||||
local cnt = maxNZ - minNZ + 1
|
||||
if p + cnt > limit then
|
||||
return nil, "truncated PIZ bitmap"
|
||||
end
|
||||
buffer.copy(bitmap, minNZ, src, p, cnt)
|
||||
p += cnt
|
||||
end
|
||||
-- reverse LUT
|
||||
local lut = buffer.create(USHORT_RANGE * 2)
|
||||
local k = 0
|
||||
for i = 0, USHORT_RANGE - 1 do
|
||||
if i == 0 or band(readu8(bitmap, rshift(i, 3)), lshift(1, band(i, 7))) ~= 0 then
|
||||
writeu16(lut, k * 2, i)
|
||||
k += 1
|
||||
end
|
||||
end
|
||||
local maxValue = k - 1
|
||||
if p + 4 > limit then
|
||||
return nil, "truncated PIZ length"
|
||||
end
|
||||
local length = readu32(src, p)
|
||||
p += 4
|
||||
if length > limit - p then
|
||||
return nil, "truncated PIZ data"
|
||||
end
|
||||
local tmp = buffer.create(total * 2)
|
||||
local herr = huffman(src, p, length, tmp, total)
|
||||
if herr then
|
||||
return nil, herr
|
||||
end
|
||||
local starts = table.create(#chans, 0)
|
||||
local at = 0
|
||||
for i, c in chans do
|
||||
starts[i] = at
|
||||
for j = 0, c.size - 1 do
|
||||
wav2Decode(tmp, at + j, c.nx, c.size, c.ny, c.nx * c.size, maxValue)
|
||||
end
|
||||
at += c.nx * c.ny * c.size
|
||||
end
|
||||
for i = 0, total - 1 do
|
||||
writeu16(tmp, i * 2, readu16(lut, readu16(tmp, i * 2) * 2))
|
||||
end
|
||||
-- planes -> scanlines
|
||||
local o = 0
|
||||
local cursor = table.clone(starts)
|
||||
for y = minY, maxY do
|
||||
for i, c in chans do
|
||||
if y % c.ys == 0 then
|
||||
local cnt = c.nx * c.size
|
||||
buffer.copy(out, o, tmp, cursor[i] * 2, cnt * 2)
|
||||
cursor[i] += cnt
|
||||
o += cnt * 2
|
||||
end
|
||||
end
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
return Piz
|
||||
@@ -0,0 +1,782 @@
|
||||
--!strict
|
||||
-- image/exr: OpenEXR (the OpenEXR file layout and technical introduction documents, openexr.com; new code, the PIZ
|
||||
-- decoder written after OpenEXR's algorithm, BSD-3-Clause: licenses/openexr-LICENSE.md). Decode: single-part and
|
||||
-- multipart files (opts.part: 1-based index or part name; meta.source.parts lists them), scanline and tiled parts
|
||||
-- (one level, mip-map and rip-map levels: level 0, plus the mip-map levels into img.meta.mipmaps with opts.mips),
|
||||
-- compression NONE / RLE / ZIPS / ZIP / PIZ, HALF / FLOAT / UINT channels, x / y subsampled channels (nearest), any
|
||||
-- line order, broken offset tables (rebuilt from the chunks of single-part files). R / G / B / A map to the image
|
||||
-- (opts.layer = "diffuse" reads diffuse.R ...); a Y-only image is grey; every channel name is in meta.source.channels.
|
||||
-- The image is the data window (meta.dataWindow / meta.displayWindow keep both boxes). opts.native gives the linear
|
||||
-- rgbaf32 values; the default rgba8 is a display conversion like image/hdr's: round(clamp(v, 0, 1) ^ (1 / 2.2) * 255)
|
||||
-- for colour, round(clamp(a, 0, 1) * 255) for alpha.
|
||||
-- Encode: rgbaf32 (or rgba8 through the inverse curve) as a scanline file, HALF (default) or FLOAT channels, A only
|
||||
-- when some alpha is not 1, compression NONE, ZIPS or ZIP (default). Not supported: deep data, PXR24 / B44 / B44A /
|
||||
-- DWAA / DWAB / HTJ2K / ZSTD compression (UNSUPPORTED naming the method), RY / BY chroma (the Y channel is used).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Sniff = require("@formats/core/Sniff")
|
||||
local Types = require("@formats/Types")
|
||||
local Half = require("@formats/codecs/image/Half")
|
||||
local Codec = require("@formats/image/exr/Codec")
|
||||
local Piz = require("@formats/image/exr/Piz")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Exr = {
|
||||
name = "exr",
|
||||
category = "image",
|
||||
extensions = { "exr" },
|
||||
mime = { "image/x-exr", "image/aces" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Half", "codecs/compress/Deflate" },
|
||||
caps = { decode = true, encode = true, alpha = true, float = true, hdr = true, depths = { 16, 32 }, multipart = true, tiled = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
native: boolean?, -- linear rgbaf32 (default false: rgba8 through a 1 / 2.2 display gamma)
|
||||
part: (number | string)?, -- multipart files: the part to read (1-based index or name; default 1)
|
||||
layer: string?, -- read <layer>.R / .G / .B / .A instead of R / G / B / A
|
||||
mips: boolean?, -- tiled mip-map parts: decode the smaller levels into img.meta.mipmaps (default false)
|
||||
maxPixels: number?, -- refuse larger images (default 2^26)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
compression: ("none" | "zips" | "zip")?, -- default "zip"
|
||||
pixelType: ("half" | "float")?, -- default "half"
|
||||
alpha: boolean?, -- write A (default: when some alpha is not 1)
|
||||
level: number?, -- zlib level 1..9 (default 6)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local MAGIC = "\118\47\49\1"
|
||||
local COMPRESSION: { [number]: string } = { [0] = "none", "rle", "zips", "zip", "piz", "pxr24", "b44", "b44a", "dwaa", "dwab", "htj2k256", "htj2k32", "zstd" }
|
||||
local LINES: { [number]: number } = { [0] = 1, 1, 1, 16, 32, 16, 32, 32, 32, 256 }
|
||||
local GAMMA = 1 / 2.2
|
||||
|
||||
local readu8, readu32, readi32, readf32, readstring = buffer.readu8, buffer.readu32, buffer.readi32, buffer.readf32, buffer.readstring
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Exr.sniff(r: Bytes.Reader): number
|
||||
return Sniff.magic(r, MAGIC)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
type Channel = { name: string, kind: number, linear: boolean, xs: number, ys: number }
|
||||
type Part = {
|
||||
attrs: { [string]: any },
|
||||
channels: { Channel },
|
||||
compression: number,
|
||||
box: { number }, -- data window xMin, yMin, xMax, yMax
|
||||
display: { number },
|
||||
tiled: boolean,
|
||||
tiles: { number }?, -- xSize, ySize, mode, rounding
|
||||
name: string?,
|
||||
type: string?,
|
||||
chunks: number,
|
||||
offsets: { number },
|
||||
}
|
||||
|
||||
local function cstr(b: buffer, p: number, limit: number, max: number): (string?, number)
|
||||
local q = p
|
||||
while q < limit and q - p <= max do
|
||||
if readu8(b, q) == 0 then
|
||||
return readstring(b, p, q - p), q + 1
|
||||
end
|
||||
q += 1
|
||||
end
|
||||
return nil, q
|
||||
end
|
||||
|
||||
local function f32(b: buffer, o: number): number
|
||||
return readf32(b, o)
|
||||
end
|
||||
|
||||
-- one attribute value of a known type
|
||||
local function value(b: buffer, p: number, size: number, typ: string): any
|
||||
if typ == "chlist" then
|
||||
local list: { Channel } = {}
|
||||
local q, stop = p, p + size
|
||||
while q < stop and readu8(b, q) ~= 0 do
|
||||
local name, nq = cstr(b, q, stop, 255)
|
||||
if not name or nq + 16 > stop then
|
||||
return nil
|
||||
end
|
||||
table.insert(list, { name = name, kind = readi32(b, nq), linear = readu8(b, nq + 4) ~= 0, xs = readi32(b, nq + 8), ys = readi32(b, nq + 12) })
|
||||
q = nq + 16
|
||||
end
|
||||
return list
|
||||
elseif typ == "compression" or typ == "lineOrder" or typ == "envmap" or typ == "deepImageState" then
|
||||
return if size >= 1 then readu8(b, p) else nil
|
||||
elseif typ == "box2i" then
|
||||
return if size >= 16 then { readi32(b, p), readi32(b, p + 4), readi32(b, p + 8), readi32(b, p + 12) } else nil
|
||||
elseif typ == "box2f" then
|
||||
return if size >= 16 then { f32(b, p), f32(b, p + 4), f32(b, p + 8), f32(b, p + 12) } else nil
|
||||
elseif typ == "v2i" then
|
||||
return if size >= 8 then { readi32(b, p), readi32(b, p + 4) } else nil
|
||||
elseif typ == "v2f" then
|
||||
return if size >= 8 then { f32(b, p), f32(b, p + 4) } else nil
|
||||
elseif typ == "v3f" then
|
||||
return if size >= 12 then { f32(b, p), f32(b, p + 4), f32(b, p + 8) } else nil
|
||||
elseif typ == "float" then
|
||||
return if size >= 4 then f32(b, p) else nil
|
||||
elseif typ == "double" then
|
||||
return if size >= 8 then buffer.readf64(b, p) else nil
|
||||
elseif typ == "int" then
|
||||
return if size >= 4 then readi32(b, p) else nil
|
||||
elseif typ == "string" then
|
||||
return readstring(b, p, size)
|
||||
elseif typ == "tiledesc" then
|
||||
if size < 9 then
|
||||
return nil
|
||||
end
|
||||
local m = readu8(b, p + 8)
|
||||
return { readu32(b, p), readu32(b, p + 4), m % 16, m // 16 }
|
||||
elseif typ == "chromaticities" then
|
||||
if size < 32 then
|
||||
return nil
|
||||
end
|
||||
local t = {}
|
||||
for i = 0, 7 do
|
||||
t[i + 1] = f32(b, p + i * 4)
|
||||
end
|
||||
return t
|
||||
end
|
||||
local raw = buffer.create(size)
|
||||
buffer.copy(raw, 0, b, p, size)
|
||||
return raw
|
||||
end
|
||||
|
||||
-- the attributes of one header from p -> attrs, the offset after its terminating NUL | nil, Err
|
||||
local function header(b: buffer, p: number, limit: number): ({ [string]: any }?, number, Err.Err?)
|
||||
local attrs: { [string]: any } = {}
|
||||
local types: { [string]: string } = {}
|
||||
while true do
|
||||
if p >= limit then
|
||||
return nil, p, Err.new(Err.TRUNCATED, "header runs past the end", p)
|
||||
end
|
||||
if readu8(b, p) == 0 then
|
||||
attrs._types = types
|
||||
return attrs, p + 1, nil
|
||||
end
|
||||
local name, q = cstr(b, p, limit, 255)
|
||||
if not name then
|
||||
return nil, p, Err.new(Err.CORRUPT, "bad attribute name", p)
|
||||
end
|
||||
local typ, q2 = cstr(b, q, limit, 255)
|
||||
if not typ then
|
||||
return nil, p, Err.new(Err.CORRUPT, "bad attribute type", q)
|
||||
end
|
||||
if q2 + 4 > limit then
|
||||
return nil, p, Err.new(Err.TRUNCATED, "attribute size runs past the end", q2)
|
||||
end
|
||||
local size = readi32(b, q2)
|
||||
if size < 0 or q2 + 4 + size > limit then
|
||||
return nil, p, Err.new(Err.TRUNCATED, "attribute " .. name .. " runs past the end", q2)
|
||||
end
|
||||
attrs[name] = value(b, q2 + 4, size, typ)
|
||||
types[name] = typ
|
||||
p = q2 + 4 + size
|
||||
end
|
||||
end
|
||||
|
||||
-- level sizes of a tiled part
|
||||
local function levelSize(n: number, l: number, roundUp: boolean): number
|
||||
local d = 2 ^ l
|
||||
return math.max(1, if roundUp then math.ceil(n / d) else n // d)
|
||||
end
|
||||
local function levelCount(w: number, h: number, mode: number, roundUp: boolean): (number, number)
|
||||
local function count(n: number): number
|
||||
local c = 1
|
||||
while levelSize(n, c - 1, roundUp) > 1 do
|
||||
c += 1
|
||||
end
|
||||
return c
|
||||
end
|
||||
if mode == 0 then
|
||||
return 1, 1
|
||||
elseif mode == 1 then
|
||||
local c = count(math.max(w, h))
|
||||
return c, c
|
||||
end
|
||||
return count(w), count(h)
|
||||
end
|
||||
|
||||
-- chunk count of a part (single-part files: computed)
|
||||
local function chunkCount(pt: Part): number
|
||||
local w, h = pt.box[3] - pt.box[1] + 1, pt.box[4] - pt.box[2] + 1
|
||||
if not pt.tiled then
|
||||
return (h + LINES[pt.compression] - 1) // LINES[pt.compression]
|
||||
end
|
||||
local t = pt.tiles :: { number }
|
||||
local tx, ty, mode, roundUp = t[1], t[2], t[3], t[4] == 1
|
||||
local lx, ly = levelCount(w, h, mode, roundUp)
|
||||
local n = 0
|
||||
if mode == 2 then
|
||||
for y = 0, ly - 1 do
|
||||
for x = 0, lx - 1 do
|
||||
n += math.ceil(levelSize(w, x, roundUp) / tx) * math.ceil(levelSize(h, y, roundUp) / ty)
|
||||
end
|
||||
end
|
||||
else
|
||||
for l = 0, lx - 1 do
|
||||
n += math.ceil(levelSize(w, l, roundUp) / tx) * math.ceil(levelSize(h, l, roundUp) / ty)
|
||||
end
|
||||
end
|
||||
return n
|
||||
end
|
||||
|
||||
export type Info = { multipart: boolean, tiled: boolean, deep: boolean, parts: { Part }, dataStart: number }
|
||||
|
||||
local function parse(r: Bytes.Reader): (Info?, Err.Err?)
|
||||
local b, base, limit = r.buf, r.base, r.limit
|
||||
if limit - base < 8 or readstring(b, base, 4) ~= MAGIC then
|
||||
return nil, Err.new(Err.CORRUPT, "not an OpenEXR file", base)
|
||||
end
|
||||
local ver = readu32(b, base + 4)
|
||||
if ver % 256 ~= 2 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "version " .. ver % 256, base + 4)
|
||||
end
|
||||
local flags = ver // 256
|
||||
local tiledFlag, deep, multi = bit32.band(flags, 2) ~= 0, bit32.band(flags, 8) ~= 0, bit32.band(flags, 16) ~= 0
|
||||
local info: Info = { multipart = multi, tiled = tiledFlag, deep = deep, parts = {}, dataStart = 0 }
|
||||
local p = base + 8
|
||||
repeat
|
||||
local attrs, q, herr = header(b, p, limit)
|
||||
if not attrs then
|
||||
return nil, herr
|
||||
end
|
||||
p = q
|
||||
local chans = attrs.channels
|
||||
local box = attrs.dataWindow
|
||||
if type(chans) ~= "table" or type(box) ~= "table" or type(attrs.compression) ~= "number" then
|
||||
return nil, Err.new(Err.CORRUPT, "missing channels / dataWindow / compression", p)
|
||||
end
|
||||
local typ = attrs.type
|
||||
local pt: Part = {
|
||||
attrs = attrs,
|
||||
channels = chans,
|
||||
compression = attrs.compression,
|
||||
box = box,
|
||||
display = attrs.displayWindow or box,
|
||||
tiled = if typ then (typ == "tiledimage" or typ == "deeptile") else tiledFlag,
|
||||
tiles = attrs.tiles,
|
||||
name = attrs.name,
|
||||
type = typ,
|
||||
chunks = 0,
|
||||
offsets = {},
|
||||
}
|
||||
if pt.tiled and type(pt.tiles) ~= "table" then
|
||||
return nil, Err.new(Err.CORRUPT, "tiled part without tiles", p)
|
||||
end
|
||||
if box[3] < box[1] or box[4] < box[2] or box[3] - box[1] >= 2 ^ 24 or box[4] - box[2] >= 2 ^ 24 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad data window", p)
|
||||
end
|
||||
if pt.tiled and ((pt.tiles :: any)[1] < 1 or (pt.tiles :: any)[2] < 1) then
|
||||
return nil, Err.new(Err.CORRUPT, "bad tile size", p)
|
||||
end
|
||||
for _, c in chans do
|
||||
if c.xs < 1 or c.ys < 1 or c.kind < 0 or c.kind > 2 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad channel " .. c.name, p)
|
||||
end
|
||||
end
|
||||
table.insert(info.parts, pt)
|
||||
if #info.parts > 4096 then
|
||||
return nil, Err.new(Err.LIMIT, "too many parts", p)
|
||||
end
|
||||
until not multi or (p < limit and readu8(b, p) == 0)
|
||||
if multi then
|
||||
p += 1
|
||||
end
|
||||
-- offset tables
|
||||
for _, pt in info.parts do
|
||||
local n = if type(pt.attrs.chunkCount) == "number" then pt.attrs.chunkCount else (if LINES[pt.compression] then chunkCount(pt) else 0)
|
||||
if n < 0 or n > 2 ^ 24 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad chunk count", p)
|
||||
end
|
||||
pt.chunks = n
|
||||
if p + n * 8 > limit then
|
||||
return nil, Err.new(Err.TRUNCATED, "offset table runs past the end", p)
|
||||
end
|
||||
for i = 0, n - 1 do
|
||||
pt.offsets[i + 1] = readu32(b, p + i * 8) + readu32(b, p + i * 8 + 4) * 4294967296
|
||||
end
|
||||
p += n * 8
|
||||
end
|
||||
info.dataStart = p - base
|
||||
return info, nil
|
||||
end
|
||||
|
||||
-- info(r) -> { multipart, tiled, deep, parts = { { name, type, attrs, channels, compression, box, ... } } } | nil, Err
|
||||
function Exr.info(r: Bytes.Reader): (Info?, Err.Err?)
|
||||
return parse(r)
|
||||
end
|
||||
|
||||
-- bytes of a sample kind
|
||||
local SIZE = { [0] = 4, 2, 4 }
|
||||
|
||||
-- number of multiples of s in [a, b]
|
||||
local function samples(a: number, b: number, s: number): number
|
||||
return b // s - (a - 1) // s
|
||||
end
|
||||
|
||||
type Target = { [number]: number } -- channel index -> output component (0..3, 4 = grey)
|
||||
|
||||
local function newPlane(pw: number, ph: number): buffer
|
||||
local px = buffer.create(pw * ph * 16)
|
||||
for i = 0, pw * ph - 1 do
|
||||
buffer.writef32(px, i * 16 + 12, 1)
|
||||
end
|
||||
return px
|
||||
end
|
||||
-- one decompressed block: the lines y0..y1 (absolute), columns x0..x0 + bw - 1 of plane (pw wide, origin ox, oy)
|
||||
local function block(part: Part, target: Target, data: buffer, dp: number, y0: number, y1: number, x0: number, bw: number, plane: buffer, pw: number, ph: number, ox: number, oy: number): Err.Err?
|
||||
local p = dp
|
||||
for y = y0, y1 do
|
||||
for i, c in part.channels do
|
||||
if y % c.ys == 0 then
|
||||
local nx = if c.xs == 1 then bw else samples(x0, x0 + bw - 1, c.xs)
|
||||
local sz = SIZE[c.kind]
|
||||
if p + nx * sz > buffer.len(data) then
|
||||
return Err.new(Err.CORRUPT, "block too short")
|
||||
end
|
||||
local k = target[i]
|
||||
if k ~= nil then
|
||||
local row = y - oy
|
||||
if c.xs == 1 and c.ys == 1 and k < 4 then
|
||||
Codec.samples(data, p, nx, c.kind, plane, (row * pw + (x0 - ox)) * 16 + k * 4, 16)
|
||||
else
|
||||
local tmp = buffer.create(nx * 4)
|
||||
Codec.samples(data, p, nx, c.kind, tmp, 0, 4)
|
||||
local first = (x0 + c.xs - 1) // c.xs * c.xs
|
||||
for s = 0, nx - 1 do
|
||||
local v = buffer.readf32(tmp, s * 4)
|
||||
local sx = first + s * c.xs
|
||||
for yy = row, math.min(row + c.ys - 1, ph - 1) do
|
||||
for xx = sx - ox, math.min(sx - ox + c.xs - 1, pw - 1) do
|
||||
local o = (yy * pw + xx) * 16
|
||||
if k == 4 then
|
||||
buffer.writef32(plane, o, v)
|
||||
buffer.writef32(plane, o + 4, v)
|
||||
buffer.writef32(plane, o + 8, v)
|
||||
else
|
||||
buffer.writef32(plane, o + k * 4, v)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
p += nx * sz
|
||||
end
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- the raw bytes of a block (uncompressed size raw)
|
||||
local function unpack(b: buffer, comp: number, part: Part, p: number, size: number, raw: number, y0: number, y1: number, x0: number, bw: number): (buffer?, number, Err.Err?)
|
||||
if size == raw or comp == 0 then
|
||||
if size < raw then
|
||||
return nil, 0, Err.new(Err.CORRUPT, "short uncompressed block", p)
|
||||
end
|
||||
return b, p, nil
|
||||
end
|
||||
local out, err
|
||||
if comp == 1 then
|
||||
out, err = Codec.rle(b, p, size, raw)
|
||||
elseif comp == 2 or comp == 3 then
|
||||
out, err = Codec.unzip(b, p, size, raw)
|
||||
else
|
||||
local chans: { Piz.Chan } = {}
|
||||
for i, c in part.channels do
|
||||
chans[i] = { nx = samples(x0, x0 + bw - 1, c.xs), ny = samples(y0, y1, c.ys), size = SIZE[c.kind] // 2, ys = c.ys }
|
||||
end
|
||||
out, err = Piz.decode(b, p, size, chans, y0, y1, raw)
|
||||
end
|
||||
if not out then
|
||||
return nil, 0, Err.from(err, p)
|
||||
end
|
||||
return out, 0, nil
|
||||
end
|
||||
|
||||
local function rawSize(part: Part, y0: number, y1: number, x0: number, bw: number): number
|
||||
local n = 0
|
||||
for y = y0, y1 do
|
||||
for _, c in part.channels do
|
||||
if y % c.ys == 0 then
|
||||
n += samples(x0, x0 + bw - 1, c.xs) * SIZE[c.kind]
|
||||
end
|
||||
end
|
||||
end
|
||||
return n
|
||||
end
|
||||
|
||||
function Exr.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
||||
local info, perr = parse(r)
|
||||
if not info then
|
||||
return nil, perr
|
||||
end
|
||||
local b, base, limit = r.buf, r.base, r.limit
|
||||
local want = opts and opts.part or 1
|
||||
local pt: Part? = nil
|
||||
local partIndex = 0
|
||||
for i, p in info.parts do
|
||||
if (type(want) == "number" and i == want) or (type(want) == "string" and p.name == want) then
|
||||
pt, partIndex = p, i
|
||||
end
|
||||
end
|
||||
if not pt then
|
||||
return nil, Err.new(Err.ARG, "no part " .. tostring(want))
|
||||
end
|
||||
local part = pt :: Part
|
||||
if info.deep or (part.type and string.find(part.type, "deep")) then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "deep data")
|
||||
end
|
||||
local comp: number = part.compression
|
||||
if comp > 4 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "compression " .. (COMPRESSION[comp] or tostring(comp)))
|
||||
end
|
||||
local box = part.box
|
||||
local xMin, yMin, xMax, yMax = box[1], box[2], box[3], box[4]
|
||||
local w, h = xMax - xMin + 1, yMax - yMin + 1
|
||||
local maxPixels = opts and opts.maxPixels or 2 ^ 26
|
||||
if w * h > maxPixels then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
|
||||
end
|
||||
-- channel -> output component
|
||||
local prefix = if opts and opts.layer then opts.layer .. "." else ""
|
||||
local target: Target = {}
|
||||
local hasRgb = false
|
||||
for i, c in part.channels do
|
||||
local n = c.name
|
||||
if string.sub(n, 1, #prefix) == prefix then
|
||||
local s = string.sub(n, #prefix + 1)
|
||||
local k = if s == "R" or s == "r" then 0 elseif s == "G" or s == "g" then 1 elseif s == "B" or s == "b" then 2 elseif s == "A" or s == "a" then 3 else nil
|
||||
if k then
|
||||
target[i] = k
|
||||
hasRgb = hasRgb or k < 3
|
||||
end
|
||||
end
|
||||
end
|
||||
if not hasRgb then
|
||||
for i, c in part.channels do
|
||||
if c.name == prefix .. "Y" then
|
||||
target[i] = 4
|
||||
end
|
||||
end
|
||||
end
|
||||
local multi = info.multipart
|
||||
-- offsets: single-part tables with holes are rebuilt from the chunk sequence
|
||||
local offsets = part.offsets
|
||||
local bad = false
|
||||
for _, o in offsets do
|
||||
if o < info.dataStart or base + o + 8 > limit then
|
||||
bad = true
|
||||
break
|
||||
end
|
||||
end
|
||||
if bad then
|
||||
-- rebuild from the chunk sequence (every part's chunks follow the tables; multipart chunks name their part)
|
||||
offsets = {}
|
||||
local p = base + info.dataStart
|
||||
local total = 0
|
||||
for _, q in info.parts do
|
||||
total += q.chunks
|
||||
end
|
||||
for _ = 1, total do
|
||||
local pi = 1
|
||||
local at = p
|
||||
if multi then
|
||||
if p + 4 > limit then
|
||||
break
|
||||
end
|
||||
pi = readi32(b, p) + 1
|
||||
p += 4
|
||||
end
|
||||
local q = info.parts[pi]
|
||||
if not q then
|
||||
break
|
||||
end
|
||||
local head = if q.tiled then 20 else 8
|
||||
if p + head > limit then
|
||||
break
|
||||
end
|
||||
local size = readi32(b, p + head - 4)
|
||||
if size < 0 then
|
||||
break
|
||||
end
|
||||
if pi == partIndex then
|
||||
table.insert(offsets, at - base)
|
||||
end
|
||||
p += head + size
|
||||
end
|
||||
end
|
||||
|
||||
local planes: { [number]: buffer } = { [0] = newPlane(w, h) } -- level -> rgbaf32 pixels
|
||||
local tiles = part.tiles
|
||||
local roundUp = tiles ~= nil and tiles[4] == 1
|
||||
local wantMips = opts and opts.mips and tiles ~= nil and tiles[3] == 1
|
||||
|
||||
local lpb = LINES[comp]
|
||||
for ci, off in offsets do
|
||||
local p = base + off
|
||||
if multi then
|
||||
if p + 4 > limit then
|
||||
return nil, Err.new(Err.TRUNCATED, "chunk past the end", p)
|
||||
end
|
||||
if readi32(b, p) ~= partIndex - 1 then
|
||||
return nil, Err.new(Err.CORRUPT, "chunk of another part in this part's table", p)
|
||||
end
|
||||
p += 4
|
||||
end
|
||||
if part.tiled then
|
||||
if p + 20 > limit then
|
||||
return nil, Err.new(Err.TRUNCATED, "tile header past the end", p)
|
||||
end
|
||||
local tx, ty, lx, ly, size = readi32(b, p), readi32(b, p + 4), readi32(b, p + 8), readi32(b, p + 12), readi32(b, p + 16)
|
||||
p += 20
|
||||
local t = tiles :: { number }
|
||||
local level = if lx == 0 and ly == 0 then 0 elseif wantMips and lx == ly then lx else -1
|
||||
if level >= 0 then
|
||||
local lw, lh = levelSize(w, level, roundUp), levelSize(h, level, roundUp)
|
||||
local x0, y0 = tx * t[1], ty * t[2]
|
||||
if tx < 0 or ty < 0 or x0 >= lw or y0 >= lh then
|
||||
return nil, Err.new(Err.CORRUPT, "tile outside the image", p)
|
||||
end
|
||||
if size < 0 or p + size > limit then
|
||||
return nil, Err.new(Err.TRUNCATED, "tile data past the end", p)
|
||||
end
|
||||
local bw, bh = math.min(t[1], lw - x0), math.min(t[2], lh - y0)
|
||||
local plane = planes[level]
|
||||
if not plane then
|
||||
plane = newPlane(lw, lh)
|
||||
planes[level] = plane
|
||||
end
|
||||
-- tile coordinates are relative to the level's data window origin
|
||||
local ax, ay = xMin + x0, yMin + y0
|
||||
local raw = rawSize(part, ay, ay + bh - 1, ax, bw)
|
||||
local data, dp, uerr = unpack(b, comp, part, p, size, raw, ay, ay + bh - 1, ax, bw)
|
||||
if not data then
|
||||
return nil, uerr
|
||||
end
|
||||
local berr = block(part, target, data, dp, ay, ay + bh - 1, ax, bw, plane, lw, lh, xMin, yMin)
|
||||
if berr then
|
||||
return nil, berr
|
||||
end
|
||||
end
|
||||
else
|
||||
if p + 8 > limit then
|
||||
return nil, Err.new(Err.TRUNCATED, "chunk header past the end", p)
|
||||
end
|
||||
local y, size = readi32(b, p), readi32(b, p + 4)
|
||||
p += 8
|
||||
if y < yMin or y > yMax or (y - yMin) % lpb ~= 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad scanline block y " .. y, p - 8)
|
||||
end
|
||||
if size < 0 or p + size > limit then
|
||||
if ci > 1 then
|
||||
break -- a cut file: keep the lines that decoded (meta.truncated)
|
||||
end
|
||||
return nil, Err.new(Err.TRUNCATED, "block data past the end", p)
|
||||
end
|
||||
local y1 = math.min(y + lpb - 1, yMax)
|
||||
local raw = rawSize(part, y, y1, xMin, w)
|
||||
local data, dp, uerr = unpack(b, comp, part, p, size, raw, y, y1, xMin, w)
|
||||
if not data then
|
||||
return nil, uerr
|
||||
end
|
||||
local berr = block(part, target, data, dp, y, y1, xMin, w, planes[0], w, h, xMin, yMin)
|
||||
if berr then
|
||||
return nil, berr
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local native = opts and opts.native
|
||||
local function finish(px: buffer, pw: number, ph: number): Types.Image
|
||||
if native then
|
||||
local img = Types.Image.new(0, 0, "rgbaf32")
|
||||
img.width, img.height, img.pixels = pw, ph, px
|
||||
return img
|
||||
end
|
||||
local img = Types.Image.new(pw, ph, "rgba8")
|
||||
local o = img.pixels
|
||||
for i = 0, pw * ph - 1 do
|
||||
for c = 0, 3 do
|
||||
local v = buffer.readf32(px, i * 16 + c * 4)
|
||||
v = if v ~= v or v <= 0 then 0 elseif v >= 1 then 1 else v
|
||||
buffer.writeu8(o, i * 4 + c, math.floor((if c < 3 then v ^ GAMMA else v) * 255 + 0.5))
|
||||
end
|
||||
end
|
||||
return img
|
||||
end
|
||||
local img = finish(planes[0], w, h)
|
||||
if wantMips then
|
||||
local mips = {}
|
||||
local l = 1
|
||||
while planes[l] do
|
||||
mips[l] = finish(planes[l], levelSize(w, l, roundUp), levelSize(h, l, roundUp))
|
||||
l += 1
|
||||
end
|
||||
if #mips > 0 then
|
||||
img.meta.mipmaps = mips
|
||||
end
|
||||
end
|
||||
local names, parts = {}, {}
|
||||
for i, c in part.channels do
|
||||
names[i] = c.name
|
||||
end
|
||||
for i, p in info.parts do
|
||||
parts[i] = { name = p.name or "", type = p.type or (if p.tiled then "tiledimage" else "scanlineimage") }
|
||||
end
|
||||
img.meta.colorSpace = "linear"
|
||||
img.meta.dataWindow = { x = xMin, y = yMin, width = w, height = h }
|
||||
local dw = part.display
|
||||
img.meta.displayWindow = { x = dw[1], y = dw[2], width = dw[3] - dw[1] + 1, height = dw[4] - dw[2] + 1 }
|
||||
local attrs = {}
|
||||
for k, v in part.attrs do
|
||||
if k ~= "_types" and (type(v) == "string" or type(v) == "number") then
|
||||
attrs[k] = v
|
||||
end
|
||||
end
|
||||
img.meta.attributes = attrs
|
||||
local kinds = {}
|
||||
for i, c in part.channels do
|
||||
kinds[i] = ({ [0] = "uint", "half", "float" })[c.kind]
|
||||
end
|
||||
img.meta.source = {
|
||||
format = "exr",
|
||||
compression = COMPRESSION[comp],
|
||||
channels = names,
|
||||
pixelTypes = kinds,
|
||||
part = partIndex,
|
||||
parts = parts,
|
||||
tiled = part.tiled,
|
||||
lineOrder = part.attrs.lineOrder,
|
||||
bitDepth = if kinds[1] == "half" then 16 else 32,
|
||||
}
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
local function attr(w: Bytes.Writer, name: string, typ: string, data: buffer)
|
||||
w:cstring(name)
|
||||
w:cstring(typ)
|
||||
w:u32le(buffer.len(data))
|
||||
w:bytes(data)
|
||||
end
|
||||
|
||||
function Exr.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(img) ~= "table" or type(img.pixels) ~= "buffer" or (img.format ~= "rgbaf32" and img.format ~= "rgba8") then
|
||||
return nil, Err.new(Err.ARG, "needs an rgbaf32 or rgba8 Image")
|
||||
end
|
||||
local w, h = img.width, img.height
|
||||
if type(w) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 then
|
||||
return nil, Err.new(Err.ARG, "bad image size")
|
||||
end
|
||||
local compName = opts and opts.compression or "zip"
|
||||
local comp = if compName == "none" then 0 elseif compName == "zips" then 2 elseif compName == "zip" then 3 else nil
|
||||
if not comp then
|
||||
return nil, Err.new(Err.ARG, "compression must be none, zips or zip")
|
||||
end
|
||||
local ptype = opts and opts.pixelType or "half"
|
||||
if ptype ~= "half" and ptype ~= "float" then
|
||||
return nil, Err.new(Err.ARG, "pixelType must be half or float")
|
||||
end
|
||||
local level = opts and opts.level or 6
|
||||
-- the float values
|
||||
local n = w * h
|
||||
local fl = buffer.create(n * 16)
|
||||
if img.format == "rgbaf32" then
|
||||
buffer.copy(fl, 0, img.pixels, 0, n * 16)
|
||||
else
|
||||
for i = 0, n * 4 - 1 do
|
||||
local v = buffer.readu8(img.pixels, i) / 255
|
||||
buffer.writef32(fl, i * 4, if i % 4 < 3 then v ^ 2.2 else v)
|
||||
end
|
||||
end
|
||||
local alpha = opts and opts.alpha
|
||||
if alpha == nil then
|
||||
alpha = false
|
||||
for i = 0, n - 1 do
|
||||
if buffer.readf32(fl, i * 16 + 12) ~= 1 then
|
||||
alpha = true
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
local chans = if alpha then { { "A", 3 }, { "B", 2 }, { "G", 1 }, { "R", 0 } } else { { "B", 2 }, { "G", 1 }, { "R", 0 } }
|
||||
local kind = if ptype == "half" then 1 else 2
|
||||
local sz = if kind == 1 then 2 else 4
|
||||
local lpb = LINES[comp]
|
||||
local nblocks = (h + lpb - 1) // lpb
|
||||
-- header
|
||||
local hw = Bytes.writer(512)
|
||||
hw:string(MAGIC)
|
||||
hw:u32le(2)
|
||||
local cl = Bytes.writer()
|
||||
for _, c in chans do
|
||||
cl:cstring(c[1])
|
||||
cl:u32le(kind)
|
||||
cl:u8(0)
|
||||
cl:fill(0, 3)
|
||||
cl:u32le(1)
|
||||
cl:u32le(1)
|
||||
end
|
||||
cl:u8(0)
|
||||
attr(hw, "channels", "chlist", cl:finish())
|
||||
attr(hw, "compression", "compression", buffer.fromstring(string.char(comp)))
|
||||
local bw = Bytes.writer(16)
|
||||
bw:u32le(0)
|
||||
bw:u32le(0)
|
||||
bw:u32le(w - 1)
|
||||
bw:u32le(h - 1)
|
||||
local boxb = bw:finish()
|
||||
attr(hw, "dataWindow", "box2i", boxb)
|
||||
attr(hw, "displayWindow", "box2i", boxb)
|
||||
attr(hw, "lineOrder", "lineOrder", buffer.fromstring("\0"))
|
||||
local fw = Bytes.writer(4)
|
||||
fw:f32le(1)
|
||||
attr(hw, "pixelAspectRatio", "float", fw:finish())
|
||||
attr(hw, "screenWindowCenter", "v2f", buffer.create(8))
|
||||
attr(hw, "screenWindowWidth", "float", fw:finish())
|
||||
hw:u8(0)
|
||||
local tableAt = hw:tell()
|
||||
hw:fill(0, nblocks * 8)
|
||||
local from = Half.fromFloat
|
||||
for bi = 0, nblocks - 1 do
|
||||
local y0 = bi * lpb
|
||||
local y1 = math.min(y0 + lpb - 1, h - 1)
|
||||
local raw = buffer.create((y1 - y0 + 1) * #chans * w * sz)
|
||||
local o = 0
|
||||
for y = y0, y1 do
|
||||
for _, c in chans do
|
||||
local k = c[2]
|
||||
for x = 0, w - 1 do
|
||||
local v = buffer.readf32(fl, ((y * w + x) * 4 + k) * 4)
|
||||
if kind == 1 then
|
||||
buffer.writeu16(raw, o, from(v))
|
||||
else
|
||||
buffer.writef32(raw, o, v)
|
||||
end
|
||||
o += sz
|
||||
end
|
||||
end
|
||||
end
|
||||
local data = raw
|
||||
if comp ~= 0 then
|
||||
local z = Codec.zip(raw, level)
|
||||
if buffer.len(z) < buffer.len(raw) then
|
||||
data = z
|
||||
end
|
||||
end
|
||||
local at = hw:tell()
|
||||
hw:setU32le(tableAt + bi * 8, at)
|
||||
hw:u32le(y0)
|
||||
hw:u32le(buffer.len(data))
|
||||
hw:bytes(data)
|
||||
end
|
||||
return hw:finish(), nil
|
||||
end
|
||||
|
||||
return Exr
|
||||
@@ -0,0 +1,337 @@
|
||||
--!strict
|
||||
-- image/icns: Apple Icon Image files (the icns resource type; new code; chunks through containers/Chunks). Decode:
|
||||
-- the legacy RGB entries is32 / il32 / ih32 / it32 (the icns RLE, or raw) with their s8mk / l8mk / h8mk / t8mk alpha
|
||||
-- masks, ic04 / ic05 ARGB entries, the 1-bit ics# / ICN# / ich# / icm# icons with their masks, and PNG entries in any
|
||||
-- type (icp4 .. ic14) through the api hook opts.decodeImage. JPEG 2000 entries are skipped (meta.skipped lists them),
|
||||
-- like 4 / 8-bit palette entries and nested dark-mode / TOC chunks. The image is the largest entry; img.frames lists
|
||||
-- every decoded entry (each with meta.source = { type = "ic07", ... }); a file of JPEG 2000 entries only returns
|
||||
-- UNSUPPORTED. Encode: the image and every img.frames image (square, 16 .. 1024): PNG entries through opts.encodeImage
|
||||
-- (icp4 / icp5 / icp6 / ic07 / ic08 / ic09 / ic10), or without the hook (or opts.legacy) the RLE entries for 16 / 32 /
|
||||
-- 48 / 128 with masks.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Sniff = require("@formats/core/Sniff")
|
||||
local Types = require("@formats/Types")
|
||||
local Chunks = require("@formats/containers/Chunks")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Icns = {
|
||||
name = "icns",
|
||||
category = "image",
|
||||
extensions = { "icns" },
|
||||
mime = { "image/icns", "image/x-icns" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "containers/Chunks" },
|
||||
caps = { decode = true, encode = true, alpha = true, frames = true, depths = { 1, 24, 32 } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, -- decodes PNG entries (the api passes one)
|
||||
maxPixels: number?, -- refuse entries larger than this (default 2^22)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, -- writes PNG entries (the api passes one)
|
||||
legacy: boolean?, -- RLE entries (16 / 32 / 48 / 128) even when encodeImage is there (default false)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local RGB: { [string]: { any } } = { is32 = { 16, "s8mk" }, il32 = { 32, "l8mk" }, ih32 = { 48, "h8mk" }, it32 = { 128, "t8mk" } }
|
||||
local MASKS: { [string]: boolean } = { s8mk = true, l8mk = true, h8mk = true, t8mk = true }
|
||||
local ARGB: { [string]: number } = { ic04 = 16, ic05 = 32 }
|
||||
local MONO: { [string]: { number } } = { ["ics#"] = { 16, 16 }, ["ICN#"] = { 32, 32 }, ["ich#"] = { 48, 48 }, ["icm#"] = { 16, 12 } }
|
||||
local PNG_TYPES: { [number]: string } = { [16] = "icp4", [32] = "icp5", [64] = "icp6", [128] = "ic07", [256] = "ic08", [512] = "ic09", [1024] = "ic10" }
|
||||
local LEGACY: { [number]: { string } } = { [16] = { "is32", "s8mk" }, [32] = { "il32", "l8mk" }, [48] = { "ih32", "h8mk" }, [128] = { "it32", "t8mk" } }
|
||||
local LAYOUT: Chunks.Layout = {
|
||||
bigEndian = true,
|
||||
resize = function(_id: string, declared: number): number?
|
||||
return math.max(0, declared - 8)
|
||||
end,
|
||||
}
|
||||
|
||||
local readu8 = buffer.readu8
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Icns.sniff(r: Bytes.Reader): number
|
||||
return Sniff.magic(r, "icns")
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- the icns RLE of n channels of count bytes each from [p, stop) into out at channel offsets (interleaved, step 4)
|
||||
local function unrle(b: buffer, p: number, stop: number, out: buffer, channels: { number }, count: number): boolean
|
||||
for _, ch in channels do
|
||||
local i = 0
|
||||
while i < count do
|
||||
if p >= stop then
|
||||
return false
|
||||
end
|
||||
local c = readu8(b, p)
|
||||
p += 1
|
||||
if c >= 128 then
|
||||
local n = c - 125
|
||||
if p >= stop then
|
||||
return false
|
||||
end
|
||||
local v = readu8(b, p)
|
||||
p += 1
|
||||
for _ = 1, math.min(n, count - i) do
|
||||
buffer.writeu8(out, i * 4 + ch, v)
|
||||
i += 1
|
||||
end
|
||||
else
|
||||
local n = c + 1
|
||||
if p + n > stop then
|
||||
return false
|
||||
end
|
||||
for k = 0, math.min(n, count - i) - 1 do
|
||||
buffer.writeu8(out, (i + k) * 4 + ch, readu8(b, p + k))
|
||||
end
|
||||
i += math.min(n, count - i)
|
||||
p += n
|
||||
end
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
local function isPng(b: buffer, p: number, n: number): boolean
|
||||
return n >= 8 and buffer.readstring(b, p, 8) == "\137PNG\r\n\26\n"
|
||||
end
|
||||
local function isJp2(b: buffer, p: number, n: number): boolean
|
||||
return n >= 12 and (buffer.readstring(b, p, 12) == "\0\0\0\12jP \r\n\135\n" or buffer.readstring(b, p, 4) == "\255\79\255\81")
|
||||
end
|
||||
|
||||
function Icns.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
||||
local b, o, limit = r.buf, r.base, r.limit
|
||||
if limit - o < 8 or buffer.readstring(b, o, 4) ~= "icns" then
|
||||
return nil, Err.new(Err.CORRUPT, "not an icns file", o)
|
||||
end
|
||||
local total = bit32.byteswap(buffer.readu32(b, o + 4))
|
||||
local stop = math.min(limit, o + math.max(total, 8))
|
||||
local list = Chunks.walk(b, o + 8, stop, LAYOUT)
|
||||
local decodeImage = opts and opts.decodeImage
|
||||
local maxPixels = opts and opts.maxPixels or 2 ^ 22
|
||||
local masks: { [string]: Chunks.Chunk } = {}
|
||||
for _, c in list do
|
||||
if MASKS[c.id] then
|
||||
masks[c.id] = c
|
||||
end
|
||||
end
|
||||
local frames: { Types.Frame } = {}
|
||||
local skipped: { string } = {}
|
||||
local function add(im: Types.Image, typ: string, extra: { [string]: any }?)
|
||||
local src: { [string]: any } = { format = "icns", type = typ }
|
||||
if extra then
|
||||
for k, v in extra do
|
||||
src[k] = v
|
||||
end
|
||||
end
|
||||
im.meta.source = src :: any
|
||||
table.insert(frames, { image = im, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" } :: Types.Frame)
|
||||
end
|
||||
for _, c in list do
|
||||
local id, p, n = c.id, c.offset, c.avail
|
||||
if c.truncated then
|
||||
table.insert(skipped, id .. " (truncated)")
|
||||
elseif RGB[id] then
|
||||
local size = RGB[id][1]
|
||||
local im = Types.Image.new(size, size, "rgba8")
|
||||
local px = im.pixels
|
||||
local q = if id == "it32" then p + 4 else p
|
||||
local count = size * size
|
||||
local ok
|
||||
if n == count * 3 then
|
||||
for i = 0, count - 1 do
|
||||
for k = 0, 2 do
|
||||
buffer.writeu8(px, i * 4 + k, readu8(b, p + k * count + i))
|
||||
end
|
||||
end
|
||||
ok = true
|
||||
else
|
||||
ok = unrle(b, q, p + n, px, { 0, 1, 2 }, count)
|
||||
end
|
||||
local m = masks[RGB[id][2]]
|
||||
for i = 0, count - 1 do
|
||||
buffer.writeu8(px, i * 4 + 3, if m and m.avail >= count then readu8(b, m.offset + i) else 255)
|
||||
end
|
||||
if ok then
|
||||
add(im, id, { bitDepth = 24, mask = m ~= nil })
|
||||
else
|
||||
table.insert(skipped, id .. " (bad RLE)")
|
||||
end
|
||||
elseif ARGB[id] and n >= 4 and buffer.readstring(b, p, 4) == "ARGB" then
|
||||
local size = ARGB[id]
|
||||
local im = Types.Image.new(size, size, "rgba8")
|
||||
if unrle(b, p + 4, p + n, im.pixels, { 3, 0, 1, 2 }, size * size) then
|
||||
add(im, id, { bitDepth = 32 })
|
||||
else
|
||||
table.insert(skipped, id .. " (bad RLE)")
|
||||
end
|
||||
elseif MONO[id] then
|
||||
local w, h = MONO[id][1], MONO[id][2]
|
||||
local bytes = w * h // 8
|
||||
if n >= bytes * 2 then
|
||||
local im = Types.Image.new(w, h, "rgba8")
|
||||
for i = 0, w * h - 1 do
|
||||
local bit = bit32.band(bit32.rshift(readu8(b, p + bit32.rshift(i, 3)), 7 - bit32.band(i, 7)), 1)
|
||||
local mbit = bit32.band(bit32.rshift(readu8(b, p + bytes + bit32.rshift(i, 3)), 7 - bit32.band(i, 7)), 1)
|
||||
buffer.writeu32(im.pixels, i * 4, (if bit == 1 then 0 else 0xFFFFFF) + mbit * 0xFF000000)
|
||||
end
|
||||
add(im, id, { bitDepth = 1 })
|
||||
end
|
||||
elseif isPng(b, p, n) then
|
||||
if decodeImage then
|
||||
local sub = buffer.create(n)
|
||||
buffer.copy(sub, 0, b, p, n)
|
||||
local okc, im, ierr = pcall(decodeImage, sub)
|
||||
if okc and im then
|
||||
if im.width * im.height <= maxPixels then
|
||||
add(im :: Types.Image, id, { png = true })
|
||||
else
|
||||
table.insert(skipped, id .. " (over maxPixels)")
|
||||
end
|
||||
else
|
||||
table.insert(skipped, id .. " (PNG: " .. tostring(if okc then ierr else im) .. ")")
|
||||
end
|
||||
else
|
||||
table.insert(skipped, id .. " (PNG: no decodeImage hook)")
|
||||
end
|
||||
elseif isJp2(b, p, n) then
|
||||
table.insert(skipped, id .. " (JPEG 2000)")
|
||||
elseif not MASKS[id] and id ~= "TOC " and id ~= "icnV" and id ~= "name" and id ~= "info" then
|
||||
table.insert(skipped, id)
|
||||
end
|
||||
end
|
||||
if #frames == 0 then
|
||||
if #skipped > 0 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "no decodable entry (" .. table.concat(skipped, ", ") .. ")")
|
||||
end
|
||||
return nil, Err.new(Err.CORRUPT, "no icon entries", o + 8)
|
||||
end
|
||||
local main = frames[1].image
|
||||
for _, f in frames do
|
||||
if f.image.width * f.image.height > main.width * main.height then
|
||||
main = f.image
|
||||
end
|
||||
end
|
||||
local img = Types.Image.new(0, 0, "rgba8")
|
||||
img.width, img.height, img.pixels = main.width, main.height, main.pixels
|
||||
if #frames > 1 then
|
||||
img.frames = frames
|
||||
end
|
||||
if #skipped > 0 then
|
||||
img.meta.skipped = skipped
|
||||
end
|
||||
img.meta.source = { format = "icns", type = main.meta.source and main.meta.source.type, entries = #frames }
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- the icns RLE of one channel (count bytes, step 4 from ch) into w
|
||||
local function rle(w: Bytes.Writer, px: buffer, ch: number, count: number)
|
||||
local i = 0
|
||||
while i < count do
|
||||
local v = readu8(px, i * 4 + ch)
|
||||
local run = 1
|
||||
while i + run < count and run < 130 and readu8(px, (i + run) * 4 + ch) == v do
|
||||
run += 1
|
||||
end
|
||||
if run >= 3 then
|
||||
w:u8(run + 125)
|
||||
w:u8(v)
|
||||
i += run
|
||||
else
|
||||
local lit = 0
|
||||
while i + lit < count and lit < 128 do
|
||||
local a = readu8(px, (i + lit) * 4 + ch)
|
||||
if i + lit + 2 < count and readu8(px, (i + lit + 1) * 4 + ch) == a and readu8(px, (i + lit + 2) * 4 + ch) == a then
|
||||
break
|
||||
end
|
||||
lit += 1
|
||||
end
|
||||
lit = math.max(lit, 1)
|
||||
w:u8(lit - 1)
|
||||
for k = 0, lit - 1 do
|
||||
w:u8(readu8(px, (i + k) * 4 + ch))
|
||||
end
|
||||
i += lit
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function Icns.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(img) ~= "table" or type(img.pixels) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "needs an Image")
|
||||
end
|
||||
local images: { Types.Image } = {}
|
||||
local seen: { [number]: boolean } = {}
|
||||
local function take(im: Types.Image): Err.Err?
|
||||
if type(im) ~= "table" or im.format ~= "rgba8" or im.width ~= im.height then
|
||||
return Err.new(Err.ARG, "icons are square rgba8 images")
|
||||
end
|
||||
if not seen[im.width] then
|
||||
seen[im.width] = true
|
||||
table.insert(images, im)
|
||||
end
|
||||
return nil
|
||||
end
|
||||
local e = take(img)
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
if type(img.frames) == "table" then
|
||||
for _, f in img.frames do
|
||||
local fe = take(f.image)
|
||||
if fe then
|
||||
return nil, fe
|
||||
end
|
||||
end
|
||||
end
|
||||
table.sort(images, function(a: Types.Image, c: Types.Image): boolean
|
||||
return a.width < c.width
|
||||
end)
|
||||
local encodeImage = opts and opts.encodeImage
|
||||
local legacy = (opts and opts.legacy) or encodeImage == nil
|
||||
local body = Bytes.writer()
|
||||
local function chunk(id: string, data: buffer)
|
||||
body:string(id)
|
||||
body:u32be(buffer.len(data) + 8)
|
||||
body:bytes(data)
|
||||
end
|
||||
for _, im in images do
|
||||
local s = im.width
|
||||
if legacy and LEGACY[s] then
|
||||
local types = LEGACY[s]
|
||||
local w = Bytes.writer()
|
||||
if s == 128 then
|
||||
w:u32be(0)
|
||||
end
|
||||
for ch = 0, 2 do
|
||||
rle(w, im.pixels, ch, s * s)
|
||||
end
|
||||
chunk(types[1], w:finish())
|
||||
local m = buffer.create(s * s)
|
||||
for i = 0, s * s - 1 do
|
||||
buffer.writeu8(m, i, readu8(im.pixels, i * 4 + 3))
|
||||
end
|
||||
chunk(types[2], m)
|
||||
elseif encodeImage and PNG_TYPES[s] then
|
||||
local ok, png, perr = pcall(encodeImage, im, "png")
|
||||
if not ok or not png then
|
||||
return nil, Err.new(Err.ARG, "PNG entry " .. s .. ": " .. tostring(if ok then perr else png))
|
||||
end
|
||||
chunk(PNG_TYPES[s], png :: buffer)
|
||||
else
|
||||
return nil, Err.new(Err.ARG, string.format("no icns entry for %d x %d%s", s, s, if encodeImage then "" else " without an encodeImage hook (16 / 32 / 48 / 128 only)"))
|
||||
end
|
||||
end
|
||||
local data = body:finish()
|
||||
local out = Bytes.writer(buffer.len(data) + 8)
|
||||
out:string("icns")
|
||||
out:u32be(buffer.len(data) + 8)
|
||||
out:bytes(data)
|
||||
return out:finish(), nil
|
||||
end
|
||||
|
||||
return Icns
|
||||
@@ -0,0 +1,324 @@
|
||||
--!strict
|
||||
-- image/ilbm: IFF ILBM and PBM pictures (EA IFF 85 "ILBM" standard, the Amiga ROM Kernel Manual; new code; chunks
|
||||
-- through containers/Chunks, ByteRun1 through codecs/compress/PackBits). Decode: planar ILBM with 1..8 planes and a
|
||||
-- CMAP (grey without one), EHB (extra half-brite, CAMG 0x80), HAM6 / HAM8 (CAMG 0x800), deep 24 / 32-plane RGB(A),
|
||||
-- chunky PBM (8-bit, Deluxe Paint), masking 1 (a mask plane) and 2 (a transparent colour index), uncompressed or
|
||||
-- ByteRun1 bodies; opts.adjustColors scales 4-bit OCS palettes (all low nibbles zero) to 8 bits; NAME / ANNO / AUTH
|
||||
-- text (meta.text). HAM channel values replicate their bits (4-bit v -> v * 17; ilbmtoppm shifts: v * 16). Encode: rgba8 as a planar ILBM: up to 256 opaque colours with a CMAP and the fewest planes, else
|
||||
-- 24 planes (32 with alpha), ByteRun1 (default) or uncompressed. Not supported: animations (ANIM), the rarer
|
||||
-- encodings (RGBN / RGB8 / ACBM / DEEP chunks: UNSUPPORTED), SHAM / PCHG palette changes (ignored).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Chunks = require("@formats/containers/Chunks")
|
||||
local PackBits = require("@formats/codecs/compress/PackBits")
|
||||
local Pixels = require("@formats/codecs/image/Pixels")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Ilbm = {
|
||||
name = "ilbm",
|
||||
category = "image",
|
||||
extensions = { "iff", "ilbm", "lbm", "pbm" },
|
||||
mime = { "image/x-ilbm", "image/x-iff" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/compress/PackBits", "codecs/image/Pixels" },
|
||||
caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 2, 3, 4, 5, 6, 7, 8, 24, 32 } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
adjustColors: boolean?, -- scale 4-bit OCS palettes (every low nibble 0) to 8 bits (default false)
|
||||
maxPixels: number?, -- refuse larger images (default 2^26)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
compress: boolean?, -- ByteRun1 (default true)
|
||||
}
|
||||
|
||||
local readu8, readu16 = buffer.readu8, buffer.readu16
|
||||
local function be16(b: buffer, o: number): number
|
||||
return bit32.rshift(bit32.byteswap(readu16(b, o)), 16)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Ilbm.sniff(r: Bytes.Reader): number
|
||||
if r:peek(4) ~= "FORM" then
|
||||
return 0
|
||||
end
|
||||
local t = r:peek(4, 8)
|
||||
return if t == "ILBM" or t == "PBM " then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Ilbm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
||||
local b, o, limit = r.buf, r.base, r.limit
|
||||
if limit - o < 12 or buffer.readstring(b, o, 4) ~= "FORM" then
|
||||
return nil, Err.new(Err.CORRUPT, "not an IFF FORM", o)
|
||||
end
|
||||
local form = buffer.readstring(b, o + 8, 4)
|
||||
if form ~= "ILBM" and form ~= "PBM " then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "FORM " .. form, o + 8)
|
||||
end
|
||||
local chunky = form == "PBM "
|
||||
local list = Chunks.walk(b, o + 12, math.min(limit, o + 8 + bit32.byteswap(buffer.readu32(b, o + 4))), Chunks.IFF)
|
||||
local bmhd, cmap, body = Chunks.find(list, "BMHD"), Chunks.find(list, "CMAP"), Chunks.find(list, "BODY")
|
||||
if not bmhd or bmhd.avail < 20 then
|
||||
return nil, Err.new(Err.CORRUPT, "missing BMHD", o + 12)
|
||||
end
|
||||
if not body then
|
||||
return nil, Err.new(Err.TRUNCATED, "missing BODY", o + 12)
|
||||
end
|
||||
local q = bmhd.offset
|
||||
local w, h = be16(b, q), be16(b, q + 2)
|
||||
local planes, masking, comp = readu8(b, q + 8), readu8(b, q + 9), readu8(b, q + 10)
|
||||
local trans = be16(b, q + 12)
|
||||
if w == 0 or h == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad size", q)
|
||||
end
|
||||
if comp > 1 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "compression " .. comp, q + 10)
|
||||
end
|
||||
if not (planes >= 1 and planes <= 8 or planes == 24 or planes == 32) or (chunky and planes ~= 8) then
|
||||
return nil, Err.new(Err.UNSUPPORTED, planes .. " planes", q + 8)
|
||||
end
|
||||
local maxPixels = opts and opts.maxPixels or 2 ^ 26
|
||||
if w * h > maxPixels then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
|
||||
end
|
||||
local camg = 0
|
||||
local c = Chunks.find(list, "CAMG")
|
||||
if c and c.avail >= 4 then
|
||||
camg = bit32.byteswap(buffer.readu32(b, c.offset))
|
||||
end
|
||||
local ham = bit32.band(camg, 0x800) ~= 0 and (planes == 6 or planes == 8)
|
||||
local ehb = bit32.band(camg, 0x80) ~= 0 and planes == 6 and not ham
|
||||
-- palette
|
||||
local pal = buffer.create(1024)
|
||||
local ncol = 0
|
||||
if cmap then
|
||||
ncol = math.min(256, cmap.avail // 3)
|
||||
local low = true
|
||||
for i = 0, ncol * 3 - 1 do
|
||||
low = low and bit32.band(readu8(b, cmap.offset + i), 15) == 0
|
||||
end
|
||||
local adjust = low and opts and opts.adjustColors
|
||||
for i = 0, ncol - 1 do
|
||||
local function ch(k: number): number
|
||||
local v = readu8(b, cmap.offset + i * 3 + k)
|
||||
return if adjust then v + bit32.rshift(v, 4) else v
|
||||
end
|
||||
buffer.writeu32(pal, i * 4, ch(0) + ch(1) * 256 + ch(2) * 65536 + 0xFF000000)
|
||||
end
|
||||
end
|
||||
if ncol == 0 and planes <= 8 then
|
||||
local n = bit32.lshift(1, planes)
|
||||
for i = 0, n - 1 do
|
||||
local g = (i * 255) // math.max(1, n - 1)
|
||||
buffer.writeu32(pal, i * 4, g * 0x10101 + 0xFF000000)
|
||||
end
|
||||
ncol = n
|
||||
end
|
||||
if ehb then
|
||||
for i = 0, 31 do
|
||||
local v = buffer.readu32(pal, i * 4)
|
||||
local rr, gg, bb = bit32.band(v, 255), bit32.band(bit32.rshift(v, 8), 255), bit32.band(bit32.rshift(v, 16), 255)
|
||||
buffer.writeu32(pal, (32 + i) * 4, bit32.rshift(rr, 1) + bit32.rshift(gg, 1) * 256 + bit32.rshift(bb, 1) * 65536 + 0xFF000000)
|
||||
end
|
||||
end
|
||||
-- the body, decompressed
|
||||
local rowBytes = if chunky then w + w % 2 else ((w + 15) // 16) * 2
|
||||
local total = if chunky then rowBytes * h else rowBytes * (planes + (if masking == 1 then 1 else 0)) * h
|
||||
local raw = buffer.create(total)
|
||||
local truncated
|
||||
if comp == 1 then
|
||||
local written = PackBits.decode(b, body.offset, body.offset + body.avail, raw, 0, total)
|
||||
truncated = written < total
|
||||
else
|
||||
local n = math.min(total, body.avail)
|
||||
buffer.copy(raw, 0, b, body.offset, n)
|
||||
truncated = n < total
|
||||
end
|
||||
local img = Types.Image.new(w, h, "rgba8")
|
||||
local px = img.pixels
|
||||
if chunky then
|
||||
Pixels.indexed(raw, 0, rowBytes, 8, px, w, h, true, pal)
|
||||
if masking == 2 then
|
||||
for i = 0, w * h - 1 do
|
||||
local y, x = i // w, i % w
|
||||
if readu8(raw, y * rowBytes + x) == trans then
|
||||
buffer.writeu32(px, i * 4, 0)
|
||||
end
|
||||
end
|
||||
end
|
||||
else
|
||||
local stride = rowBytes * (planes + (if masking == 1 then 1 else 0))
|
||||
local deep = planes >= 24
|
||||
local bits = planes - 2
|
||||
for y = 0, h - 1 do
|
||||
local row = y * stride
|
||||
local pr: number, pg: number, pb: number = 0, 0, 0
|
||||
if ham then
|
||||
local v = buffer.readu32(pal, 0)
|
||||
pr = bit32.band(v, 255)
|
||||
pg = bit32.band(bit32.rshift(v, 8), 255)
|
||||
pb = bit32.band(bit32.rshift(v, 16), 255)
|
||||
end
|
||||
for x = 0, w - 1 do
|
||||
local byteAt, shift = bit32.rshift(x, 3), 7 - bit32.band(x, 7)
|
||||
local idx = 0
|
||||
for k = 0, planes - 1 do
|
||||
idx += bit32.band(bit32.rshift(readu8(raw, row + k * rowBytes + byteAt), shift), 1) * 2 ^ k
|
||||
end
|
||||
local out: number
|
||||
if deep then
|
||||
local a = if planes == 32 then bit32.rshift(idx, 24) % 256 else 255
|
||||
out = bit32.band(idx, 0xFFFFFF) + a * 16777216
|
||||
elseif ham then
|
||||
local ctl = bit32.rshift(idx, bits)
|
||||
local val = bit32.band(idx, bit32.lshift(1, bits) - 1)
|
||||
local v8 = if bits == 4 then val * 17 else val * 4 + bit32.rshift(val, 4)
|
||||
if ctl == 0 then
|
||||
local v = buffer.readu32(pal, val * 4)
|
||||
pr = bit32.band(v, 255)
|
||||
pg = bit32.band(bit32.rshift(v, 8), 255)
|
||||
pb = bit32.band(bit32.rshift(v, 16), 255)
|
||||
elseif ctl == 1 then
|
||||
pb = v8
|
||||
elseif ctl == 2 then
|
||||
pr = v8
|
||||
else
|
||||
pg = v8
|
||||
end
|
||||
out = pr + pg * 256 + pb * 65536 + 0xFF000000
|
||||
else
|
||||
out = buffer.readu32(pal, bit32.band(idx, 255) * 4)
|
||||
if masking == 2 and idx == trans then
|
||||
out = 0
|
||||
end
|
||||
end
|
||||
if masking == 1 then
|
||||
local m = bit32.band(bit32.rshift(readu8(raw, row + planes * rowBytes + byteAt), shift), 1)
|
||||
if m == 0 then
|
||||
out = 0
|
||||
end
|
||||
end
|
||||
buffer.writeu32(px, (y * w + x) * 4, out)
|
||||
end
|
||||
end
|
||||
end
|
||||
if ncol > 0 and planes <= 8 and not ham then
|
||||
local plist: { { number } } = {}
|
||||
for i = 0, (if ehb then 64 else ncol) - 1 do
|
||||
local v = buffer.readu32(pal, i * 4)
|
||||
plist[i + 1] = { bit32.band(v, 255), bit32.band(bit32.rshift(v, 8), 255), bit32.band(bit32.rshift(v, 16), 255), 255 }
|
||||
end
|
||||
img.meta.palette = plist
|
||||
end
|
||||
local text: { [string]: string } = {}
|
||||
for _, ch in list do
|
||||
if ch.id == "NAME" or ch.id == "ANNO" or ch.id == "AUTH" or ch.id == "(c) " then
|
||||
local s = buffer.readstring(b, ch.offset, ch.avail)
|
||||
local key = string.gsub(ch.id, "[^%w]", "")
|
||||
text[string.lower(key)] = (string.gsub(s, "%z+$", ""))
|
||||
end
|
||||
end
|
||||
if next(text) then
|
||||
img.meta.text = text
|
||||
end
|
||||
if truncated then
|
||||
img.meta.truncated = true
|
||||
end
|
||||
img.meta.source = { format = "ilbm", form = form, planes = planes, bitDepth = planes, ham = ham, ehb = ehb, masking = masking, compression = comp, camg = camg }
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Ilbm.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "needs an rgba8 Image")
|
||||
end
|
||||
local w, h = img.width, img.height
|
||||
if w < 1 or h < 1 or w > 65535 or h > 65535 then
|
||||
return nil, Err.new(Err.ARG, "size must be 1..65535")
|
||||
end
|
||||
local px = img.pixels
|
||||
local cols, alpha = Pixels.colours(px, w * h, 256)
|
||||
local usePal = not alpha and #cols <= 256
|
||||
local planes = if usePal then 1 elseif alpha then 32 else 24
|
||||
if usePal then
|
||||
while bit32.lshift(1, planes) < #cols do
|
||||
planes += 1
|
||||
end
|
||||
end
|
||||
local compress = not (opts and opts.compress == false)
|
||||
local index: { [number]: number } = {}
|
||||
for i, cv in cols do
|
||||
index[cv] = i - 1
|
||||
end
|
||||
local rowBytes = ((w + 15) // 16) * 2
|
||||
local body = Bytes.writer(rowBytes * planes * h)
|
||||
local row = buffer.create(rowBytes)
|
||||
for y = 0, h - 1 do
|
||||
for k = 0, planes - 1 do
|
||||
buffer.fill(row, 0, 0, rowBytes)
|
||||
for x = 0, w - 1 do
|
||||
local v = buffer.readu32(px, (y * w + x) * 4)
|
||||
local idx = if usePal then (index[bit32.band(v, 0xFFFFFF)] or 0) else v
|
||||
if bit32.band(bit32.rshift(idx, k), 1) == 1 then
|
||||
local at = bit32.rshift(x, 3)
|
||||
buffer.writeu8(row, at, bit32.bor(readu8(row, at), bit32.rshift(0x80, bit32.band(x, 7))))
|
||||
end
|
||||
end
|
||||
if compress then
|
||||
body:bytes(PackBits.encode(row, 0, rowBytes))
|
||||
else
|
||||
body:bytes(row)
|
||||
end
|
||||
end
|
||||
end
|
||||
local bodyData = body:finish()
|
||||
local out = Bytes.writer(buffer.len(bodyData) + 900)
|
||||
out:string("FORM")
|
||||
out:u32be(0)
|
||||
out:string("ILBM")
|
||||
out:string("BMHD")
|
||||
out:u32be(20)
|
||||
out:u16be(w)
|
||||
out:u16be(h)
|
||||
out:u16be(0)
|
||||
out:u16be(0)
|
||||
out:u8(planes)
|
||||
out:u8(0)
|
||||
out:u8(if compress then 1 else 0)
|
||||
out:u8(0)
|
||||
out:u16be(0)
|
||||
out:u8(1)
|
||||
out:u8(1)
|
||||
out:u16be(w)
|
||||
out:u16be(h)
|
||||
if usePal then
|
||||
local n = bit32.lshift(1, planes)
|
||||
out:string("CMAP")
|
||||
out:u32be(n * 3)
|
||||
for i = 1, n do
|
||||
local cv = cols[i] or 0
|
||||
out:u8(bit32.band(cv, 255))
|
||||
out:u8(bit32.band(bit32.rshift(cv, 8), 255))
|
||||
out:u8(bit32.rshift(cv, 16))
|
||||
end
|
||||
if (n * 3) % 2 == 1 then
|
||||
out:u8(0)
|
||||
end
|
||||
end
|
||||
out:string("BODY")
|
||||
out:u32be(buffer.len(bodyData))
|
||||
out:bytes(bodyData)
|
||||
if buffer.len(bodyData) % 2 == 1 then
|
||||
out:u8(0)
|
||||
end
|
||||
local res = out:finish()
|
||||
buffer.writeu32(res, 4, bit32.byteswap(buffer.len(res) - 8))
|
||||
return res, nil
|
||||
end
|
||||
|
||||
return Ilbm
|
||||
@@ -0,0 +1,672 @@
|
||||
--!strict
|
||||
-- image/ktx: Khronos texture containers (KTX 1.1 and KTX 2.0 specifications; new code). Decode: KTX1 (OpenGL
|
||||
-- glInternalFormat / glFormat + glType: the S3TC / RGTC / BPTC / ETC1 / ETC2 / EAC compressed formats and the
|
||||
-- uncompressed ones with 4-byte row alignment; big-endian files) and KTX2 (VkFormat: BCn, ETC2 / EAC and every
|
||||
-- uncompressed format codecs/image/Texel knows; Zstandard (codecs/compress/Zstd) and ZLIB supercompression); mip
|
||||
-- levels, cube maps, arrays and 3D textures, the key / value data (meta.keyValue) and KTXorientation (T=u rows are
|
||||
-- flipped). Like image/dds: the first surface is the image, img.frames lists every face / layer / slice when there is
|
||||
-- more than one (meta.layout), opts.mips decodes the smaller levels into img.meta.mipmaps; rgba8 unless opts.native.
|
||||
-- Encode: KTX2, uncompressed: rgba8 (R8G8B8A8_UNORM, or _SRGB when meta.colorSpace is "srgb"), rgba16
|
||||
-- (R16G16B16A16_UNORM), rgbaf32 (R32G32B32A32_SFLOAT or R16G16B16A16_SFLOAT), with a full DFD, optional mip chain,
|
||||
-- frames as layers or cube faces, optional ZLIB supercompression. Not supported: Basis Universal (BasisLZ / ETC1S and
|
||||
-- UASTC: UNSUPPORTED), ASTC and PVRTC, writing KTX1 or Zstandard.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Sniff = require("@formats/core/Sniff")
|
||||
local Types = require("@formats/Types")
|
||||
local Deflate = require("@formats/codecs/compress/Deflate")
|
||||
local Zstd = require("@formats/codecs/compress/Zstd")
|
||||
local Texel = require("@formats/codecs/image/Texel")
|
||||
local Texture = require("@formats/codecs/image/Texture")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Ktx = {
|
||||
name = "ktx",
|
||||
category = "image",
|
||||
extensions = { "ktx2", "ktx" },
|
||||
mime = { "image/ktx2", "image/ktx" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/compress/Deflate", "codecs/compress/Zstd", "codecs/image/Texel", "codecs/image/Texture" },
|
||||
caps = { decode = true, encode = true, alpha = true, float = true, mipmaps = true, cubemap = true, compressed = { "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7", "etc1", "etc2", "eac" } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
native: boolean?, -- keep rgbaf32 / rgba16 for float / 16-bit / BC6H / EAC sources (default false: rgba8)
|
||||
mips: boolean?, -- decode the smaller mip levels of the first surface into img.meta.mipmaps (default false)
|
||||
surfaces: boolean?, -- decode every face / layer / slice into img.frames (default true)
|
||||
maxPixels: number?, -- refuse larger images (default 2^26, over every decoded surface)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
pixelFormat: ("rgba8" | "rgba16" | "rgba16f" | "rgba32f")?, -- default: the image's own (rgbaf32 -> rgba32f)
|
||||
srgb: boolean?, -- rgba8 as R8G8B8A8_SRGB (default: meta.colorSpace == "srgb")
|
||||
mips: boolean?, -- a full mip chain (box filter; default false)
|
||||
cube: boolean?, -- img.frames as cube faces (default: meta.layout == "cube")
|
||||
zlib: number?, -- ZLIB-supercompress every level at this level 1..9 (default none)
|
||||
keyValue: { [string]: string }?, -- extra key / value pairs (KTXwriter is always written)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local ID1 = "\171KTX 11\187\r\n\26\n"
|
||||
local ID2 = "\171KTX 20\187\r\n\26\n"
|
||||
|
||||
-- VkFormat -> texture format name
|
||||
local VK: { [number]: string } = {
|
||||
[2] = "a4b4g4r4", [3] = "a4r4g4b4", [4] = "b5g6r5", [5] = "r5g6b5", [6] = "a1b5g5r5", [7] = "a1r5g5b5", [8] = "b5g5r5a1",
|
||||
[9] = "r8", [10] = "r8s", [13] = "r8ui", [14] = "r8i", [15] = "r8",
|
||||
[16] = "rg8", [17] = "rg8s", [20] = "rg8ui", [21] = "rg8i", [22] = "rg8",
|
||||
[23] = "rgb8", [24] = "rgb8s", [27] = "rgb8ui", [28] = "rgb8i", [29] = "rgb8",
|
||||
[30] = "bgr8", [36] = "bgr8",
|
||||
[37] = "rgba8", [38] = "rgba8s", [41] = "rgba8ui", [42] = "rgba8i", [43] = "rgba8",
|
||||
[44] = "bgra8", [50] = "bgra8",
|
||||
[58] = "bgr10a2", [64] = "rgb10a2",
|
||||
[70] = "r16", [71] = "r16s", [74] = "r16ui", [75] = "r16i", [76] = "r16f",
|
||||
[77] = "rg16", [78] = "rg16s", [81] = "rg16ui", [82] = "rg16i", [83] = "rg16f",
|
||||
[84] = "rgb16", [85] = "rgb16s", [88] = "rgb16ui", [89] = "rgb16i", [90] = "rgb16f",
|
||||
[91] = "rgba16", [92] = "rgba16s", [95] = "rgba16ui", [96] = "rgba16i", [97] = "rgba16f",
|
||||
[98] = "r32ui", [99] = "r32i", [100] = "r32f", [101] = "rg32ui", [102] = "rg32i", [103] = "rg32f",
|
||||
[104] = "rgb32ui", [105] = "rgb32i", [106] = "rgb32f", [107] = "rgba32ui", [108] = "rgba32i", [109] = "rgba32f",
|
||||
[122] = "r11g11b10f", [123] = "rgb9e5", [124] = "r16", [126] = "r32f",
|
||||
[131] = "bc1", [132] = "bc1", [133] = "bc1", [134] = "bc1", [135] = "bc2", [136] = "bc2", [137] = "bc3", [138] = "bc3",
|
||||
[139] = "bc4", [140] = "bc4s", [141] = "bc5", [142] = "bc5s", [143] = "bc6h", [144] = "bc6hs", [145] = "bc7", [146] = "bc7",
|
||||
[147] = "etc2_rgb", [148] = "etc2_rgb", [149] = "etc2_rgba1", [150] = "etc2_rgba1", [151] = "etc2_rgba", [152] = "etc2_rgba",
|
||||
[153] = "eac_r11", [154] = "eac_r11s", [155] = "eac_rg11", [156] = "eac_rg11s",
|
||||
}
|
||||
local VK_SRGB = { [15] = true, [22] = true, [29] = true, [36] = true, [43] = true, [50] = true, [132] = true, [134] = true, [136] = true, [138] = true, [146] = true, [148] = true, [150] = true, [152] = true }
|
||||
local VK_OPAQUE = { [131] = true, [132] = true } -- BC1 RGB: the 3-colour mode's index 3 is opaque black
|
||||
-- OpenGL compressed internal formats
|
||||
local GL_COMPRESSED: { [number]: string } = {
|
||||
[0x83F0] = "bc1", [0x83F1] = "bc1", [0x83F2] = "bc2", [0x83F3] = "bc3",
|
||||
[0x8C4C] = "bc1", [0x8C4D] = "bc1", [0x8C4E] = "bc2", [0x8C4F] = "bc3",
|
||||
[0x8DBB] = "bc4", [0x8DBC] = "bc4s", [0x8DBD] = "bc5", [0x8DBE] = "bc5s",
|
||||
[0x8E8C] = "bc7", [0x8E8D] = "bc7", [0x8E8E] = "bc6hs", [0x8E8F] = "bc6h",
|
||||
[0x8D64] = "etc1", [0x9274] = "etc2_rgb", [0x9275] = "etc2_rgb", [0x9276] = "etc2_rgba1", [0x9277] = "etc2_rgba1",
|
||||
[0x9278] = "etc2_rgba", [0x9279] = "etc2_rgba", [0x9270] = "eac_r11", [0x9271] = "eac_r11s", [0x9272] = "eac_rg11", [0x9273] = "eac_rg11s",
|
||||
}
|
||||
local GL_SRGB = { [0x8C4C] = true, [0x8C4D] = true, [0x8C4E] = true, [0x8C4F] = true, [0x8E8D] = true, [0x9275] = true, [0x9277] = true, [0x9279] = true, [0x8C41] = true, [0x8C43] = true }
|
||||
local GL_OPAQUE = { [0x83F0] = true, [0x8C4C] = true }
|
||||
-- glFormat -> channel order; glType -> bit size, Texel suffix
|
||||
local GL_ORDER: { [number]: string } = {
|
||||
[0x1903] = "r", [0x8227] = "rg", [0x1907] = "rgb", [0x1908] = "rgba", [0x80E0] = "bgr", [0x80E1] = "bgra",
|
||||
[0x1909] = "l", [0x190A] = "la", [0x1906] = "a",
|
||||
[0x8D94] = "r", [0x8228] = "rg", [0x8D98] = "rgb", [0x8D99] = "rgba", -- the _INTEGER formats
|
||||
}
|
||||
local GL_INTEGER = { [0x8D94] = true, [0x8228] = true, [0x8D98] = true, [0x8D99] = true }
|
||||
local GL_PACKED: { [number]: string } = {
|
||||
[0x8363] = "b5g6r5", [0x8033] = "a4b4g4r4", [0x8034] = "a1b5g5r5", [0x8368] = "rgb10a2", [0x8C3B] = "r11g11b10f", [0x8C3E] = "rgb9e5",
|
||||
}
|
||||
local GL_TYPES: { [number]: { any } } = {
|
||||
[0x1401] = { 8, "", "ui" }, [0x1400] = { 8, "s", "i" }, [0x1403] = { 16, "", "ui" }, [0x1402] = { 16, "s", "i" },
|
||||
[0x1405] = { 32, "ui", "ui" }, [0x1404] = { 32, "i", "i" }, [0x140B] = { 16, "f", "f" }, [0x1406] = { 32, "f", "f" },
|
||||
}
|
||||
local FACES = { "+x", "-x", "+y", "-y", "+z", "-z" }
|
||||
|
||||
local readu32, readstring = buffer.readu32, buffer.readstring
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Ktx.sniff(r: Bytes.Reader): number
|
||||
return math.max(Sniff.magic(r, ID2), Sniff.magic(r, ID1))
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
export type Info = {
|
||||
version: number, -- 1 or 2
|
||||
width: number,
|
||||
height: number,
|
||||
depth: number, -- 1 for 2D
|
||||
layers: number,
|
||||
faces: number,
|
||||
levels: number,
|
||||
format: string?, -- the texture format name (nil when unsupported: see unsupported)
|
||||
unsupported: string?,
|
||||
srgb: boolean,
|
||||
opaque: boolean, -- BC1 RGB
|
||||
vkFormat: number?,
|
||||
glInternalFormat: number?,
|
||||
supercompression: number?,
|
||||
keyValue: { [string]: string },
|
||||
bigEndian: boolean?,
|
||||
typeSize: number,
|
||||
dataOffset: number, -- KTX1: the first imageSize field (relative to the file)
|
||||
levelIndex: { { offset: number, length: number, uncompressed: number } }?, -- KTX2
|
||||
}
|
||||
|
||||
local function u64(b: buffer, o: number): number
|
||||
return readu32(b, o) + readu32(b, o + 4) * 4294967296
|
||||
end
|
||||
|
||||
-- key / value pairs from [p, stop): u32 length, key NUL value, padding to 4
|
||||
local function keyValues(b: buffer, p: number, stop: number, be: boolean): { [string]: string }
|
||||
local kv: { [string]: string } = {}
|
||||
while p + 4 <= stop do
|
||||
local n = readu32(b, p)
|
||||
if be then
|
||||
n = bit32.byteswap(n)
|
||||
end
|
||||
p += 4
|
||||
if n > stop - p then
|
||||
break
|
||||
end
|
||||
local s = readstring(b, p, n)
|
||||
local z = string.find(s, "\0", 1, true)
|
||||
if z then
|
||||
local v = string.sub(s, z + 1)
|
||||
if string.sub(v, -1) == "\0" then
|
||||
v = string.sub(v, 1, -2)
|
||||
end
|
||||
kv[string.sub(s, 1, z - 1)] = v
|
||||
end
|
||||
p += n + (3 - (n + 3) % 4)
|
||||
end
|
||||
return kv
|
||||
end
|
||||
|
||||
local function info1(r: Bytes.Reader): (Info?, Err.Err?)
|
||||
local b, o, n = r.buf, r.base, r.limit - r.base
|
||||
if n < 64 then
|
||||
return nil, Err.new(Err.TRUNCATED, "short KTX1 header", o)
|
||||
end
|
||||
local e = readu32(b, o + 12)
|
||||
local be = e == 0x01020304
|
||||
if not be and e ~= 0x04030201 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad endianness field", o + 12)
|
||||
end
|
||||
local function f(i: number): number
|
||||
local v = readu32(b, o + 16 + i * 4)
|
||||
return if be then bit32.byteswap(v) else v
|
||||
end
|
||||
local glType, typeSize, glFormat, internal = f(0), f(1), f(2), f(3)
|
||||
local w, h, d, arr, faces, levels, kvBytes = f(5), f(6), f(7), f(8), f(9), f(10), f(11)
|
||||
if w == 0 or w > 65536 or h > 65536 or d > 2048 or arr > 4096 or (faces ~= 1 and faces ~= 6) or levels > 32 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad KTX1 header", o + 16)
|
||||
end
|
||||
if 64 + kvBytes > n then
|
||||
return nil, Err.new(Err.TRUNCATED, "key / value data runs past the end", o + 64)
|
||||
end
|
||||
local info: Info = {
|
||||
version = 1,
|
||||
width = w,
|
||||
height = math.max(1, h),
|
||||
depth = math.max(1, d),
|
||||
layers = math.max(1, arr),
|
||||
faces = faces,
|
||||
levels = math.max(1, levels),
|
||||
srgb = GL_SRGB[internal] == true,
|
||||
opaque = GL_OPAQUE[internal] == true,
|
||||
glInternalFormat = internal,
|
||||
keyValue = keyValues(b, o + 64, o + 64 + kvBytes, be),
|
||||
bigEndian = be,
|
||||
typeSize = typeSize,
|
||||
dataOffset = 64 + kvBytes,
|
||||
}
|
||||
if glType == 0 then
|
||||
info.format = GL_COMPRESSED[internal]
|
||||
if not info.format then
|
||||
info.unsupported = string.format("compressed glInternalFormat 0x%04X", internal)
|
||||
end
|
||||
else
|
||||
local name = GL_PACKED[glType]
|
||||
if not name then
|
||||
local order = GL_ORDER[glFormat]
|
||||
local int = GL_INTEGER[glFormat] == true
|
||||
-- glType -> component bits, Texel suffix (normalized / integer)
|
||||
local t = GL_TYPES[glType]
|
||||
local size: number? = t and t[1]
|
||||
local suffix: string = if t then (if int then t[3] else t[2]) else ""
|
||||
if order and size then
|
||||
name = order .. tostring(size) .. suffix
|
||||
end
|
||||
end
|
||||
if name and Texel.FORMATS[name] then
|
||||
info.format = name
|
||||
else
|
||||
info.unsupported = string.format("glFormat 0x%04X / glType 0x%04X", glFormat, glType)
|
||||
end
|
||||
end
|
||||
return info, nil
|
||||
end
|
||||
|
||||
local function info2(r: Bytes.Reader): (Info?, Err.Err?)
|
||||
local b, o, n = r.buf, r.base, r.limit - r.base
|
||||
if n < 80 then
|
||||
return nil, Err.new(Err.TRUNCATED, "short KTX2 header", o)
|
||||
end
|
||||
local vk, typeSize = readu32(b, o + 12), readu32(b, o + 16)
|
||||
local w, h, d = readu32(b, o + 20), readu32(b, o + 24), readu32(b, o + 28)
|
||||
local layers, faces, levels, scheme = readu32(b, o + 32), readu32(b, o + 36), readu32(b, o + 40), readu32(b, o + 44)
|
||||
if w == 0 or w > 65536 or h > 65536 or d > 2048 or layers > 4096 or (faces ~= 1 and faces ~= 6) or levels > 32 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad KTX2 header", o + 20)
|
||||
end
|
||||
local nl = math.max(1, levels)
|
||||
if 80 + nl * 24 > n then
|
||||
return nil, Err.new(Err.TRUNCATED, "level index runs past the end", o + 80)
|
||||
end
|
||||
local dfdOff, dfdLen, kvOff, kvLen = readu32(b, o + 48), readu32(b, o + 52), readu32(b, o + 56), readu32(b, o + 60)
|
||||
local info: Info = {
|
||||
version = 2,
|
||||
width = w,
|
||||
height = math.max(1, h),
|
||||
depth = math.max(1, d),
|
||||
layers = math.max(1, layers),
|
||||
faces = faces,
|
||||
levels = nl,
|
||||
srgb = VK_SRGB[vk] == true,
|
||||
opaque = VK_OPAQUE[vk] == true,
|
||||
vkFormat = vk,
|
||||
supercompression = scheme,
|
||||
keyValue = if kvLen > 0 and kvOff + kvLen <= n then keyValues(b, o + kvOff, o + kvOff + kvLen, false) else {},
|
||||
typeSize = typeSize,
|
||||
dataOffset = 0,
|
||||
levelIndex = {},
|
||||
}
|
||||
for i = 0, nl - 1 do
|
||||
local q = o + 80 + i * 24
|
||||
table.insert(info.levelIndex :: any, { offset = u64(b, q), length = u64(b, q + 8), uncompressed = u64(b, q + 16) })
|
||||
end
|
||||
-- the colour model of the DFD tells Basis Universal apart
|
||||
local model = -1
|
||||
if dfdLen >= 16 and dfdOff + dfdLen <= n then
|
||||
model = buffer.readu8(b, o + dfdOff + 12)
|
||||
if buffer.readu8(b, o + dfdOff + 14) == 2 then
|
||||
info.srgb = true
|
||||
end
|
||||
end
|
||||
if scheme == 1 or model == 163 then
|
||||
info.unsupported = "Basis Universal ETC1S / BasisLZ"
|
||||
elseif model == 166 then
|
||||
info.unsupported = "Basis Universal UASTC"
|
||||
elseif scheme > 3 then
|
||||
info.unsupported = "supercompression scheme " .. scheme
|
||||
elseif vk == 0 then
|
||||
info.unsupported = "VK_FORMAT_UNDEFINED"
|
||||
else
|
||||
info.format = VK[vk]
|
||||
if not info.format then
|
||||
info.unsupported = "VkFormat " .. vk .. (if vk >= 157 and vk <= 184 or vk >= 1000066000 then " (ASTC)" else "")
|
||||
end
|
||||
end
|
||||
return info, nil
|
||||
end
|
||||
|
||||
-- info(r) -> Info | nil, Err (the headers only)
|
||||
function Ktx.info(r: Bytes.Reader): (Info?, Err.Err?)
|
||||
local id = r:peek(12)
|
||||
if id == ID2 then
|
||||
return info2(r)
|
||||
elseif id == ID1 then
|
||||
return info1(r)
|
||||
end
|
||||
return nil, Err.new(Err.CORRUPT, "not a KTX file", r.base)
|
||||
end
|
||||
|
||||
-- reverses the bytes of every typeSize-wide element of a big-endian KTX1 image
|
||||
local function swapped(b: buffer, p: number, n: number, size: number): buffer
|
||||
local out = buffer.create(n)
|
||||
buffer.copy(out, 0, b, p, n)
|
||||
for i = 0, n - size, size do
|
||||
if size == 2 then
|
||||
buffer.writeu16(out, i, bit32.rshift(bit32.byteswap(buffer.readu16(out, i)), 16))
|
||||
else
|
||||
buffer.writeu32(out, i, bit32.byteswap(buffer.readu32(out, i)))
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- flips the rows of a decoded surface (KTXorientation T=u)
|
||||
local function flip(img: Types.Image)
|
||||
local row = img.width * (Types.BPP[img.format] or 4)
|
||||
local px = img.pixels
|
||||
local tmp = buffer.create(row)
|
||||
for y = 0, img.height // 2 - 1 do
|
||||
local a, z = y * row, (img.height - 1 - y) * row
|
||||
buffer.copy(tmp, 0, px, a, row)
|
||||
buffer.copy(px, a, px, z, row)
|
||||
buffer.copy(px, z, tmp, 0, row)
|
||||
end
|
||||
end
|
||||
|
||||
function Ktx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
||||
local info, ierr = Ktx.info(r)
|
||||
if not info then
|
||||
return nil, ierr
|
||||
end
|
||||
local fmt = info.format
|
||||
if not fmt then
|
||||
return nil, Err.new(Err.UNSUPPORTED, info.unsupported or "format")
|
||||
end
|
||||
local native = opts and opts.native or false
|
||||
local wantMips = opts and opts.mips or false
|
||||
local wantAll = not (opts and opts.surfaces == false)
|
||||
local maxPixels = opts and opts.maxPixels or 2 ^ 26
|
||||
local b, base, limit = r.buf, r.base, r.limit
|
||||
local bw, bh, bbytes = Texture.block(fmt)
|
||||
local blockFmt = bw == 4
|
||||
local orient = info.keyValue.KTXorientation or ""
|
||||
local up = string.find(orient, "T=u", 1, true) ~= nil or (info.version == 2 and string.sub(orient, 2, 2) == "u")
|
||||
local list: { Texture.Surface } = {}
|
||||
local pixels = 0
|
||||
local count = info.layers * info.faces
|
||||
local p = base + info.dataOffset
|
||||
local w, h, d = info.width, info.height, info.depth
|
||||
for level = 0, info.levels - 1 do
|
||||
local want = level == 0 or wantMips
|
||||
-- the level's data: buf, offset, the image stride and row pitch
|
||||
local lb, lp = b, 0
|
||||
local rowPitch: number? = nil
|
||||
local imgSize = Texture.size(fmt, w, h) :: number
|
||||
local stride = imgSize
|
||||
if info.version == 1 then
|
||||
if p + 4 > limit then
|
||||
if level == 0 then
|
||||
return nil, Err.new(Err.TRUNCATED, "missing level 0", p)
|
||||
end
|
||||
break
|
||||
end
|
||||
local declared = readu32(b, p)
|
||||
if info.bigEndian then
|
||||
declared = bit32.byteswap(declared)
|
||||
end
|
||||
p += 4
|
||||
if not blockFmt then
|
||||
local tight = (bbytes :: number) * w
|
||||
rowPitch = tight + (3 - (tight + 3) % 4)
|
||||
imgSize = (rowPitch :: number) * h
|
||||
end
|
||||
stride = imgSize + (3 - (imgSize + 3) % 4) -- cube padding
|
||||
local total = stride * count * d
|
||||
if declared < imgSize * (if info.faces == 6 and info.layers == 1 then 1 else count * d) and level == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "imageSize too small for the format", p - 4)
|
||||
end
|
||||
if p + total > limit then
|
||||
if level == 0 then
|
||||
return nil, Err.new(Err.TRUNCATED, "level 0 data runs past the end", p)
|
||||
end
|
||||
break
|
||||
end
|
||||
lp = p
|
||||
p += total
|
||||
p += 3 - (total + 3) % 4
|
||||
if info.bigEndian and info.typeSize > 1 and want then
|
||||
lb, lp = swapped(b, lp, total, info.typeSize), 0
|
||||
end
|
||||
else
|
||||
local li = (info.levelIndex :: any)[level + 1]
|
||||
local off, len = base + li.offset, li.length
|
||||
if off + len > limit or li.offset < 80 then
|
||||
if level == 0 then
|
||||
return nil, Err.new(Err.TRUNCATED, "level 0 data runs past the end", off)
|
||||
end
|
||||
break
|
||||
end
|
||||
local expect = imgSize * count * d
|
||||
if want then
|
||||
local scheme = info.supercompression
|
||||
if scheme == 2 or scheme == 3 then
|
||||
if li.uncompressed < expect or li.uncompressed > 2 ^ 31 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad uncompressed level size", base + 80 + level * 24)
|
||||
end
|
||||
local out, zerr
|
||||
if scheme == 2 then
|
||||
out, zerr = Zstd.decompress(b, off, len, { maxBytes = li.uncompressed })
|
||||
else
|
||||
out, zerr = Deflate.zlib(b, off, len, li.uncompressed)
|
||||
end
|
||||
if not out then
|
||||
return nil, Err.wrap(zerr)
|
||||
end
|
||||
lb, lp = out, 0
|
||||
else
|
||||
lb, lp = b, off
|
||||
end
|
||||
if lp + expect > buffer.len(lb) then
|
||||
return nil, Err.new(Err.TRUNCATED, "level " .. level .. " is too small", off)
|
||||
end
|
||||
end
|
||||
end
|
||||
if want then
|
||||
for layer = 0, count - 1 do
|
||||
for slice = 0, d - 1 do
|
||||
if level == 0 and not wantAll and (layer > 0 or slice > 0) then
|
||||
continue
|
||||
end
|
||||
if level > 0 and (layer > 0 or slice > 0) then
|
||||
continue
|
||||
end
|
||||
pixels += w * h
|
||||
if pixels > maxPixels then
|
||||
return nil, Err.new(Err.LIMIT, string.format("over the %d pixel limit", maxPixels))
|
||||
end
|
||||
local at = lp + (layer * d + slice) * stride
|
||||
local px, pf
|
||||
if rowPitch then
|
||||
px, pf = Texel.decode(fmt, lb, at, w, h, native, rowPitch)
|
||||
else
|
||||
px, pf = Texture.decode(fmt, lb, at, w, h, native)
|
||||
end
|
||||
if not px then
|
||||
return nil, Err.from(pf, at)
|
||||
end
|
||||
local im = Texture.image(px, pf, w, h)
|
||||
if info.opaque then
|
||||
for i = 0, w * h - 1 do
|
||||
buffer.writeu8(px, i * 4 + 3, 255)
|
||||
end
|
||||
end
|
||||
if up then
|
||||
flip(im)
|
||||
end
|
||||
table.insert(list, { level = level, layer = layer, face = layer % info.faces, slice = slice, image = im })
|
||||
end
|
||||
end
|
||||
end
|
||||
w, h, d = math.max(1, w // 2), math.max(1, h // 2), math.max(1, d // 2)
|
||||
end
|
||||
local layout = if info.depth > 1 then "volume" elseif info.faces == 6 then "cube" elseif info.layers > 1 then "array" else "2d"
|
||||
local img = Texture.assemble(list, layout)
|
||||
if not img then
|
||||
return nil, Err.new(Err.TRUNCATED, "no image data")
|
||||
end
|
||||
if info.faces == 6 then
|
||||
img.meta.faces = table.clone(FACES)
|
||||
end
|
||||
if info.srgb then
|
||||
img.meta.colorSpace = "srgb"
|
||||
elseif string.find(fmt, "f$") or fmt == "bc6h" or fmt == "bc6hs" or fmt == "rgb9e5" then
|
||||
img.meta.colorSpace = "linear"
|
||||
end
|
||||
img.meta.keyValue = info.keyValue
|
||||
img.meta.source = {
|
||||
format = "ktx",
|
||||
version = info.version,
|
||||
pixelFormat = fmt,
|
||||
vkFormat = info.vkFormat,
|
||||
glInternalFormat = info.glInternalFormat,
|
||||
supercompression = info.supercompression,
|
||||
mips = info.levels,
|
||||
layers = info.layers,
|
||||
depth = info.depth,
|
||||
}
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- format -> VkFormat, bytes per texel, component bytes, kind
|
||||
local OUT: { [string]: { number } } = {
|
||||
rgba8 = { 37, 4, 1 },
|
||||
rgba16 = { 91, 8, 2 },
|
||||
rgba16f = { 97, 8, 2 },
|
||||
rgba32f = { 109, 16, 4 },
|
||||
}
|
||||
|
||||
-- the DFD: one basic descriptor block with four samples (R G B A)
|
||||
local function dfd(f: string, srgb: boolean): buffer
|
||||
local spec = OUT[f]
|
||||
local texel, comp = spec[2], spec[3]
|
||||
local float = f == "rgba16f" or f == "rgba32f"
|
||||
local w = Bytes.writer(92)
|
||||
local blockSize = 24 + 16 * 4
|
||||
w:u32le(4 + blockSize)
|
||||
w:u32le(0) -- vendor 0, descriptor type 0
|
||||
w:u32le(2 + blockSize * 65536) -- version 2, block size
|
||||
w:u8(1) -- colour model RGBSDA
|
||||
w:u8(1) -- primaries BT.709
|
||||
w:u8(if srgb then 2 else 1) -- transfer: sRGB / linear
|
||||
w:u8(0) -- straight alpha
|
||||
w:u32le(0) -- texel block 1 x 1 x 1 x 1
|
||||
w:u32le(texel) -- bytesPlane0
|
||||
w:u32le(0)
|
||||
for c = 0, 3 do
|
||||
local channel = if c == 3 then 15 else c
|
||||
local qual = (if float then 0xC0 else 0) + (if srgb and c == 3 then 0x10 else 0)
|
||||
w:u16le(c * comp * 8)
|
||||
w:u8(comp * 8 - 1)
|
||||
w:u8(channel + qual)
|
||||
w:u32le(0) -- sample position
|
||||
if float then
|
||||
w:u32le(0xBF800000)
|
||||
w:u32le(0x3F800000)
|
||||
else
|
||||
w:u32le(0)
|
||||
w:u32le(if comp == 1 then 255 else 65535)
|
||||
end
|
||||
end
|
||||
return w:finish()
|
||||
end
|
||||
|
||||
function Ktx.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "number" or img.width < 1 or img.height < 1 then
|
||||
return nil, Err.new(Err.ARG, "needs an Image")
|
||||
end
|
||||
local pf = img.format
|
||||
if pf ~= "rgba8" and pf ~= "rgba16" and pf ~= "rgbaf32" then
|
||||
return nil, Err.new(Err.ARG, "needs an rgba8, rgba16 or rgbaf32 Image (got " .. tostring(pf) .. ")")
|
||||
end
|
||||
local f: string = (opts and opts.pixelFormat) or (if pf == "rgbaf32" then "rgba32f" else pf)
|
||||
local spec = OUT[f]
|
||||
if not spec then
|
||||
return nil, Err.new(Err.ARG, "unknown pixelFormat " .. tostring(f))
|
||||
end
|
||||
local needs = if f == "rgba16f" or f == "rgba32f" then "rgbaf32" else f
|
||||
if pf ~= needs then
|
||||
return nil, Err.new(Err.ARG, string.format("pixelFormat %s needs an %s Image", f, needs))
|
||||
end
|
||||
local srgb = f == "rgba8" and (if opts and opts.srgb ~= nil then opts.srgb else (img.meta and img.meta.colorSpace == "srgb"))
|
||||
local images: { Types.Image } = { img }
|
||||
if img.frames and #img.frames > 1 then
|
||||
images = {}
|
||||
for i, fr in img.frames do
|
||||
local fi = fr.image
|
||||
if type(fi) ~= "table" or fi.width ~= img.width or fi.height ~= img.height or fi.format ~= pf then
|
||||
return nil, Err.new(Err.ARG, "frame " .. i .. ": every surface needs the image's size and pixel format")
|
||||
end
|
||||
images[i] = fi
|
||||
end
|
||||
end
|
||||
local cube = if opts and opts.cube ~= nil then opts.cube else (img.meta and img.meta.layout == "cube")
|
||||
if cube and (#images % 6 ~= 0 or img.width ~= img.height) then
|
||||
return nil, Err.new(Err.ARG, "a cube map needs 6 square faces per layer")
|
||||
end
|
||||
local faces = if cube then 6 else 1
|
||||
local layers = #images // faces
|
||||
local levels = 1
|
||||
if opts and opts.mips then
|
||||
local m = math.max(img.width, img.height)
|
||||
while m > 1 do
|
||||
m //= 2
|
||||
levels += 1
|
||||
end
|
||||
end
|
||||
local zl = opts and opts.zlib
|
||||
if zl ~= nil and (type(zl) ~= "number" or zl < 1 or zl > 9) then
|
||||
return nil, Err.new(Err.ARG, "zlib level must be 1..9")
|
||||
end
|
||||
-- level data: the images of every layer / face per level
|
||||
local levelData: { buffer } = {}
|
||||
local raw: { number } = {}
|
||||
local cur = table.clone(images)
|
||||
for lv = 1, levels do
|
||||
local w = Bytes.writer()
|
||||
for i, im in cur do
|
||||
local data = if f == "rgba16f" then Texture.toHalf(im.pixels, im.width * im.height) else im.pixels
|
||||
w:bytes(data, 0, im.width * im.height * spec[2])
|
||||
if lv < levels then
|
||||
cur[i] = Texture.halve(im)
|
||||
end
|
||||
end
|
||||
local lb = w:finish()
|
||||
raw[lv] = buffer.len(lb)
|
||||
if zl then
|
||||
lb = Deflate.zlibCompress(lb, { level = zl }) :: buffer
|
||||
end
|
||||
levelData[lv] = lb
|
||||
end
|
||||
-- key / value data
|
||||
local kvw = Bytes.writer()
|
||||
local pairs_: { { string } } = { { "KTXwriter", "formats-luau" } }
|
||||
if opts and opts.keyValue then
|
||||
for k, v in opts.keyValue do
|
||||
if k ~= "KTXwriter" then
|
||||
table.insert(pairs_, { k, v })
|
||||
end
|
||||
end
|
||||
end
|
||||
table.sort(pairs_, function(a: { string }, c: { string }): boolean
|
||||
return a[1] < c[1]
|
||||
end)
|
||||
for _, kv in pairs_ do
|
||||
local n = #kv[1] + 1 + #kv[2] + 1
|
||||
kvw:u32le(n)
|
||||
kvw:string(kv[1])
|
||||
kvw:u8(0)
|
||||
kvw:string(kv[2])
|
||||
kvw:u8(0)
|
||||
kvw:fill(0, 3 - (n + 3) % 4)
|
||||
end
|
||||
local kvd = kvw:finish()
|
||||
local d = dfd(f, srgb == true)
|
||||
local dfdOff = 80 + levels * 24
|
||||
local kvOff = dfdOff + buffer.len(d)
|
||||
local dataStart = kvOff + buffer.len(kvd)
|
||||
local align = if zl then 1 else (if spec[2] % 4 == 0 then spec[2] else 4)
|
||||
-- smallest level first
|
||||
local offsets: { number } = {}
|
||||
local p = dataStart
|
||||
for lv = levels, 1, -1 do
|
||||
p += (align - p % align) % align
|
||||
offsets[lv] = p
|
||||
p += buffer.len(levelData[lv])
|
||||
end
|
||||
local out = Bytes.writer(p)
|
||||
out:string(ID2)
|
||||
out:u32le(if f == "rgba8" and srgb then 43 else spec[1])
|
||||
out:u32le(spec[3])
|
||||
out:u32le(img.width)
|
||||
out:u32le(img.height)
|
||||
out:u32le(0)
|
||||
out:u32le(if layers > 1 then layers else 0)
|
||||
out:u32le(faces)
|
||||
out:u32le(levels)
|
||||
out:u32le(if zl then 3 else 0)
|
||||
out:u32le(dfdOff)
|
||||
out:u32le(buffer.len(d))
|
||||
out:u32le(kvOff)
|
||||
out:u32le(buffer.len(kvd))
|
||||
out:u64le(0)
|
||||
out:u64le(0)
|
||||
for lv = 1, levels do
|
||||
out:u64le(offsets[lv])
|
||||
out:u64le(buffer.len(levelData[lv]))
|
||||
out:u64le(raw[lv])
|
||||
end
|
||||
out:bytes(d)
|
||||
out:bytes(kvd)
|
||||
for lv = levels, 1, -1 do
|
||||
out:fill(0, offsets[lv] - out:tell())
|
||||
out:bytes(levelData[lv])
|
||||
end
|
||||
return out:finish(), nil
|
||||
end
|
||||
|
||||
return Ktx
|
||||
@@ -0,0 +1,266 @@
|
||||
--!strict
|
||||
-- image/pcx: ZSoft PC Paintbrush (the ZSoft "Technical Reference Manual" PCX header and RLE; new code). Decode: 1-bit
|
||||
-- monochrome, 1-bit x 2..4 planes (EGA, the header palette), 2 / 4-bit packed (the header palette), 8-bit with the
|
||||
-- 256-colour palette at the end (grey when it is missing), 8-bit x 3 / 4 planes (RGB / RGBA); RLE (runs may cross
|
||||
-- scan lines) and the rare uncompressed encoding; the window (xMin / yMin) and DPI (meta.dpi). Encode: rgba8 as
|
||||
-- 8-bit palette (up to 256 opaque colours), 24-bit (3 planes) or 32-bit (4 planes, when there is alpha), RLE.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Pixels = require("@formats/codecs/image/Pixels")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Pcx = {
|
||||
name = "pcx",
|
||||
category = "image",
|
||||
extensions = { "pcx", "pcc", "dcx" },
|
||||
mime = { "image/vnd.zbrush.pcx", "image/x-pcx" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Pixels" },
|
||||
caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 2, 4, 8, 24, 32 } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
maxPixels: number?, -- refuse larger images (default 2^26)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
palette: boolean?, -- 8-bit palette when possible (default true); false: always 24 / 32-bit planes
|
||||
}
|
||||
|
||||
local readu8, readu16 = buffer.readu8, buffer.readu16
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Pcx.sniff(r: Bytes.Reader): number
|
||||
if r:size() < 128 then
|
||||
return 0
|
||||
end
|
||||
local m, v, e, bpp = r:peekU8(0), r:peekU8(1), r:peekU8(2), r:peekU8(3)
|
||||
if m ~= 10 or (v ~= 0 and v ~= 2 and v ~= 3 and v ~= 4 and v ~= 5) or e > 1 then
|
||||
return 0
|
||||
end
|
||||
return if bpp == 1 or bpp == 2 or bpp == 4 or bpp == 8 then 0.8 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Pcx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
||||
local b, o, limit = r.buf, r.base, r.limit
|
||||
if limit - o < 128 then
|
||||
return nil, Err.new(Err.TRUNCATED, "short header", o)
|
||||
end
|
||||
if readu8(b, o) ~= 10 then
|
||||
return nil, Err.new(Err.CORRUPT, "not a PCX file", o)
|
||||
end
|
||||
local version, enc, bpp = readu8(b, o + 1), readu8(b, o + 2), readu8(b, o + 3)
|
||||
local x0, y0, x1, y1 = readu16(b, o + 4), readu16(b, o + 6), readu16(b, o + 8), readu16(b, o + 10)
|
||||
local planes, bpl = readu8(b, o + 65), readu16(b, o + 66)
|
||||
local w, h = x1 - x0 + 1, y1 - y0 + 1
|
||||
if x1 < x0 or y1 < y0 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad window", o + 4)
|
||||
end
|
||||
local maxPixels = opts and opts.maxPixels or 2 ^ 26
|
||||
if w * h > maxPixels then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
|
||||
end
|
||||
local kind
|
||||
if bpp == 8 and planes == 1 then
|
||||
kind = "pal8"
|
||||
elseif bpp == 8 and (planes == 3 or planes == 4) then
|
||||
kind = "rgb"
|
||||
elseif bpp == 1 and planes >= 1 and planes <= 4 then
|
||||
kind = "planar"
|
||||
elseif (bpp == 2 or bpp == 4) and planes == 1 then
|
||||
kind = "packed"
|
||||
else
|
||||
return nil, Err.new(Err.UNSUPPORTED, string.format("%d bits x %d planes", bpp, planes), o + 3)
|
||||
end
|
||||
if bpl * 8 < w * bpp then
|
||||
return nil, Err.new(Err.CORRUPT, "bytes per line too small", o + 66)
|
||||
end
|
||||
-- the scan lines (planes after each other per line), RLE across lines
|
||||
local total = bpl * planes * h
|
||||
local raw = buffer.create(total)
|
||||
local p, q = o + 128, 0
|
||||
local truncated = false
|
||||
if enc == 1 then
|
||||
while q < total do
|
||||
if p >= limit then
|
||||
truncated = true
|
||||
break
|
||||
end
|
||||
local c = readu8(b, p)
|
||||
p += 1
|
||||
if c >= 0xC0 then
|
||||
if p >= limit then
|
||||
truncated = true
|
||||
break
|
||||
end
|
||||
local n = math.min(c - 0xC0, total - q)
|
||||
buffer.fill(raw, q, readu8(b, p), n)
|
||||
p += 1
|
||||
q += n
|
||||
else
|
||||
buffer.writeu8(raw, q, c)
|
||||
q += 1
|
||||
end
|
||||
end
|
||||
else
|
||||
local n = math.min(total, limit - p)
|
||||
buffer.copy(raw, 0, b, p, n)
|
||||
p += n
|
||||
truncated = n < total
|
||||
end
|
||||
-- palettes
|
||||
local pal = buffer.create(1024)
|
||||
local function setPal(i: number, rr: number, gg: number, bb: number)
|
||||
buffer.writeu32(pal, i * 4, rr + gg * 256 + bb * 65536 + 0xFF000000)
|
||||
end
|
||||
if kind == "pal8" then
|
||||
local at = limit - 769
|
||||
if at >= p and readu8(b, at) == 12 then
|
||||
for i = 0, 255 do
|
||||
setPal(i, readu8(b, at + 1 + i * 3), readu8(b, at + 2 + i * 3), readu8(b, at + 3 + i * 3))
|
||||
end
|
||||
else
|
||||
for i = 0, 255 do
|
||||
setPal(i, i, i, i)
|
||||
end
|
||||
end
|
||||
elseif kind == "planar" and planes == 1 then
|
||||
setPal(0, 0, 0, 0)
|
||||
setPal(1, 255, 255, 255)
|
||||
else
|
||||
for i = 0, 15 do
|
||||
setPal(i, readu8(b, o + 16 + i * 3), readu8(b, o + 17 + i * 3), readu8(b, o + 18 + i * 3))
|
||||
end
|
||||
end
|
||||
local img = Types.Image.new(w, h, "rgba8")
|
||||
local px = img.pixels
|
||||
if kind == "pal8" or kind == "packed" then
|
||||
Pixels.indexed(raw, 0, bpl, bpp, px, w, h, true, pal)
|
||||
elseif kind == "planar" then
|
||||
for y = 0, h - 1 do
|
||||
local row = y * bpl * planes
|
||||
for x = 0, w - 1 do
|
||||
local idx = 0
|
||||
for pl = 0, planes - 1 do
|
||||
local byte = readu8(raw, row + pl * bpl + bit32.rshift(x, 3))
|
||||
idx += bit32.band(bit32.rshift(byte, 7 - bit32.band(x, 7)), 1) * bit32.lshift(1, pl)
|
||||
end
|
||||
buffer.writeu32(px, (y * w + x) * 4, buffer.readu32(pal, idx * 4))
|
||||
end
|
||||
end
|
||||
else
|
||||
for y = 0, h - 1 do
|
||||
local row = y * bpl * planes
|
||||
for x = 0, w - 1 do
|
||||
local d = (y * w + x) * 4
|
||||
buffer.writeu8(px, d, readu8(raw, row + x))
|
||||
buffer.writeu8(px, d + 1, readu8(raw, row + bpl + x))
|
||||
buffer.writeu8(px, d + 2, readu8(raw, row + 2 * bpl + x))
|
||||
buffer.writeu8(px, d + 3, if planes == 4 then readu8(raw, row + 3 * bpl + x) else 255)
|
||||
end
|
||||
end
|
||||
end
|
||||
if kind == "pal8" or kind == "packed" or (kind == "planar" and planes > 1) then
|
||||
local list: { { number } } = {}
|
||||
for i = 0, (if kind == "pal8" then 256 else bit32.lshift(1, bpp * planes)) - 1 do
|
||||
local v = buffer.readu32(pal, i * 4)
|
||||
list[i + 1] = { bit32.band(v, 255), bit32.band(bit32.rshift(v, 8), 255), bit32.band(bit32.rshift(v, 16), 255), 255 }
|
||||
end
|
||||
img.meta.palette = list
|
||||
end
|
||||
local hd, vd = readu16(b, o + 12), readu16(b, o + 14)
|
||||
if hd > 0 and vd > 0 then
|
||||
img.meta.dpi = { x = hd, y = vd }
|
||||
end
|
||||
if truncated then
|
||||
img.meta.truncated = true
|
||||
end
|
||||
img.meta.source = { format = "pcx", version = version, bitDepth = bpp * planes, planes = planes, x = x0, y = y0, rle = enc == 1 }
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- RLE of one plane row into w
|
||||
local function rleRow(out: Bytes.Writer, src: buffer, p: number, n: number)
|
||||
local i = 0
|
||||
while i < n do
|
||||
local v = readu8(src, p + i)
|
||||
local run = 1
|
||||
while i + run < n and run < 63 and readu8(src, p + i + run) == v do
|
||||
run += 1
|
||||
end
|
||||
if run > 1 or v >= 0xC0 then
|
||||
out:u8(0xC0 + run)
|
||||
end
|
||||
out:u8(v)
|
||||
i += run
|
||||
end
|
||||
end
|
||||
|
||||
function Pcx.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "needs an rgba8 Image")
|
||||
end
|
||||
local w, h = img.width, img.height
|
||||
if w < 1 or h < 1 or w > 65535 or h > 65535 then
|
||||
return nil, Err.new(Err.ARG, "size must be 1..65535")
|
||||
end
|
||||
local px = img.pixels
|
||||
local cols, alpha = Pixels.colours(px, w * h, 256)
|
||||
local usePal = not alpha and #cols <= 256 and not (opts and opts.palette == false)
|
||||
local planes = if usePal then 1 elseif alpha then 4 else 3
|
||||
local bpl = w + w % 2
|
||||
local out = Bytes.writer(128 + w * h * planes + 800)
|
||||
out:u8(10)
|
||||
out:u8(5)
|
||||
out:u8(1)
|
||||
out:u8(8)
|
||||
out:u16le(0)
|
||||
out:u16le(0)
|
||||
out:u16le(w - 1)
|
||||
out:u16le(h - 1)
|
||||
local dpi = img.meta and img.meta.dpi
|
||||
out:u16le(if dpi then math.floor(dpi.x + 0.5) else 72)
|
||||
out:u16le(if dpi then math.floor(dpi.y + 0.5) else 72)
|
||||
out:fill(0, 48)
|
||||
out:u8(0)
|
||||
out:u8(planes)
|
||||
out:u16le(bpl)
|
||||
out:u16le(1)
|
||||
out:fill(0, 58)
|
||||
local row = buffer.create(bpl)
|
||||
local index: { [number]: number } = {}
|
||||
for i, c in cols do
|
||||
index[c] = i - 1
|
||||
end
|
||||
for y = 0, h - 1 do
|
||||
for pl = 0, planes - 1 do
|
||||
for x = 0, w - 1 do
|
||||
local s = (y * w + x) * 4
|
||||
local v
|
||||
if usePal then
|
||||
v = index[bit32.band(buffer.readu32(px, s), 0xFFFFFF)] or 0
|
||||
else
|
||||
v = readu8(px, s + pl)
|
||||
end
|
||||
buffer.writeu8(row, x, v)
|
||||
end
|
||||
rleRow(out, row, 0, bpl)
|
||||
end
|
||||
end
|
||||
if usePal then
|
||||
out:u8(12)
|
||||
for i = 0, 255 do
|
||||
local c = cols[i + 1] or 0
|
||||
out:u8(bit32.band(c, 255))
|
||||
out:u8(bit32.band(bit32.rshift(c, 8), 255))
|
||||
out:u8(bit32.rshift(c, 16))
|
||||
end
|
||||
end
|
||||
return out:finish(), nil
|
||||
end
|
||||
|
||||
return Pcx
|
||||
@@ -0,0 +1,286 @@
|
||||
--!strict
|
||||
-- image/sgi: Silicon Graphics image files (.rgb / .sgi / .bw / .rgba; Paul Haeberli's "The SGI Image File Format"
|
||||
-- 1.00; new code). Decode: verbatim and RLE storage, 1 and 2 bytes per channel, 1 (grey), 2 (grey + alpha), 3 (RGB)
|
||||
-- and 4 (RGBA) channels, dimension 1 / 2 / 3, rows bottom-up; rgba8 (2-byte channels keep their high byte), or rgba16
|
||||
-- with opts.native for 2-byte files; the image name (meta.text.name). Encode: rgba8 as RGB (or RGBA when there is
|
||||
-- alpha), RLE (default) or verbatim; rgba16 as 2-byte channels. Not supported: the obsolete dithered / screen /
|
||||
-- colour-map files (colormap field 1..3: UNSUPPORTED).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Sniff = require("@formats/core/Sniff")
|
||||
local Types = require("@formats/Types")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Sgi = {
|
||||
name = "sgi",
|
||||
category = "image",
|
||||
extensions = { "sgi", "rgb", "rgba", "bw", "int", "inta" },
|
||||
mime = { "image/sgi", "image/x-rgb" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" },
|
||||
caps = { decode = true, encode = true, alpha = true, depths = { 8, 16 } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
native: boolean?, -- rgba16 for 2-byte files (default false: rgba8)
|
||||
maxPixels: number?, -- refuse larger images (default 2^26)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
rle: boolean?, -- RLE storage (default true)
|
||||
name: string?, -- the image name (up to 79 bytes; default meta.text.name)
|
||||
}
|
||||
|
||||
local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32
|
||||
local function be16(b: buffer, o: number): number
|
||||
return bit32.rshift(bit32.byteswap(readu16(b, o)), 16)
|
||||
end
|
||||
local function be32(b: buffer, o: number): number
|
||||
return bit32.byteswap(readu32(b, o))
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Sgi.sniff(r: Bytes.Reader): number
|
||||
if Sniff.magic(r, "\1\218") == 0 or r:size() < 512 then
|
||||
return 0
|
||||
end
|
||||
local st, bpc = r:peekU8(2), r:peekU8(3)
|
||||
return if st <= 1 and (bpc == 1 or bpc == 2) then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Sgi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
||||
local b, o, limit = r.buf, r.base, r.limit
|
||||
if limit - o < 512 then
|
||||
return nil, Err.new(Err.TRUNCATED, "short header", o)
|
||||
end
|
||||
if be16(b, o) ~= 474 then
|
||||
return nil, Err.new(Err.CORRUPT, "not an SGI image", o)
|
||||
end
|
||||
local rle, bpc, dim = readu8(b, o + 2), readu8(b, o + 3), be16(b, o + 4)
|
||||
local w, h, z = be16(b, o + 6), be16(b, o + 8), be16(b, o + 10)
|
||||
if dim == 1 then
|
||||
h, z = 1, 1
|
||||
elseif dim == 2 then
|
||||
z = 1
|
||||
end
|
||||
if rle > 1 or (bpc ~= 1 and bpc ~= 2) or dim < 1 or dim > 3 or w == 0 or h == 0 or z == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad header", o + 2)
|
||||
end
|
||||
if z > 4 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, z .. " channels", o + 10)
|
||||
end
|
||||
local cmap = be32(b, o + 104)
|
||||
if cmap ~= 0 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "colormap type " .. cmap, o + 104)
|
||||
end
|
||||
local maxPixels = opts and opts.maxPixels or 2 ^ 26
|
||||
if w * h > maxPixels then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
|
||||
end
|
||||
-- channel planes as 16-bit samples (8-bit values scaled * 257)
|
||||
local plane = buffer.create(w * h * z * 2)
|
||||
local truncated = false
|
||||
local function put(c: number, row: number, x: number, v: number)
|
||||
buffer.writeu16(plane, ((c * h + row) * w + x) * 2, if bpc == 1 then v * 257 else v)
|
||||
end
|
||||
if rle == 0 then
|
||||
local need = w * h * z * bpc
|
||||
local p = o + 512
|
||||
local avail = math.min(need, limit - p)
|
||||
truncated = avail < need
|
||||
for i = 0, avail // bpc - 1 do
|
||||
local v = if bpc == 1 then readu8(b, p + i) else be16(b, p + i * 2)
|
||||
buffer.writeu16(plane, i * 2, if bpc == 1 then v * 257 else v)
|
||||
end
|
||||
else
|
||||
local n = h * z
|
||||
if o + 512 + n * 8 > limit then
|
||||
return nil, Err.new(Err.TRUNCATED, "RLE tables run past the end", o + 512)
|
||||
end
|
||||
for c = 0, z - 1 do
|
||||
for row = 0, h - 1 do
|
||||
local i = c * h + row
|
||||
local start, len = be32(b, o + 512 + i * 4), be32(b, o + 512 + n * 4 + i * 4)
|
||||
local p = o + start
|
||||
local stop = math.min(limit, p + len)
|
||||
local x = 0
|
||||
while x < w and p + bpc <= stop do
|
||||
local cnt = if bpc == 1 then readu8(b, p) else be16(b, p)
|
||||
p += bpc
|
||||
local count = bit32.band(cnt, 0x7F)
|
||||
if count == 0 then
|
||||
break
|
||||
end
|
||||
if bit32.band(cnt, 0x80) ~= 0 then
|
||||
for _ = 1, count do
|
||||
if x >= w or p + bpc > stop then
|
||||
break
|
||||
end
|
||||
put(c, row, x, if bpc == 1 then readu8(b, p) else be16(b, p))
|
||||
p += bpc
|
||||
x += 1
|
||||
end
|
||||
else
|
||||
if p + bpc > stop then
|
||||
break
|
||||
end
|
||||
local v = if bpc == 1 then readu8(b, p) else be16(b, p)
|
||||
p += bpc
|
||||
for _ = 1, count do
|
||||
if x >= w then
|
||||
break
|
||||
end
|
||||
put(c, row, x, v)
|
||||
x += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
if x < w then
|
||||
truncated = true
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
local wide = opts and opts.native and bpc == 2
|
||||
local img = Types.Image.new(w, h, if wide then "rgba16" else "rgba8")
|
||||
local px = img.pixels
|
||||
for y = 0, h - 1 do
|
||||
local row = h - 1 - y
|
||||
for x = 0, w - 1 do
|
||||
local function s(c: number): number
|
||||
return buffer.readu16(plane, ((c * h + row) * w + x) * 2)
|
||||
end
|
||||
local rr: number = s(0)
|
||||
local gg: number = if z >= 3 then s(1) else rr
|
||||
local bb: number = if z >= 3 then s(2) else rr
|
||||
local aa: number = if z == 2 then s(1) elseif z == 4 then s(3) else 65535
|
||||
local d = (y * w + x)
|
||||
if wide then
|
||||
buffer.writeu16(px, d * 8, rr)
|
||||
buffer.writeu16(px, d * 8 + 2, gg)
|
||||
buffer.writeu16(px, d * 8 + 4, bb)
|
||||
buffer.writeu16(px, d * 8 + 6, aa)
|
||||
else
|
||||
buffer.writeu32(px, d * 4, bit32.rshift(rr, 8) + bit32.rshift(gg, 8) * 256 + bit32.rshift(bb, 8) * 65536 + bit32.rshift(aa, 8) * 16777216)
|
||||
end
|
||||
end
|
||||
end
|
||||
local name = buffer.readstring(b, o + 24, 80)
|
||||
local zpos = string.find(name, "\0", 1, true)
|
||||
name = if zpos then string.sub(name, 1, zpos - 1) else name
|
||||
if name ~= "" then
|
||||
img.meta.text = { name = name }
|
||||
end
|
||||
if truncated then
|
||||
img.meta.truncated = true
|
||||
end
|
||||
img.meta.source = { format = "sgi", bitDepth = bpc * 8, channels = z, rle = rle == 1, dimension = dim }
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Sgi.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(img) ~= "table" or (img.format ~= "rgba8" and img.format ~= "rgba16") or type(img.pixels) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "needs an rgba8 or rgba16 Image")
|
||||
end
|
||||
local w, h = img.width, img.height
|
||||
if w < 1 or h < 1 or w > 65535 or h > 65535 then
|
||||
return nil, Err.new(Err.ARG, "size must be 1..65535")
|
||||
end
|
||||
local wide = img.format == "rgba16"
|
||||
local bpc = if wide then 2 else 1
|
||||
local px = img.pixels
|
||||
local function sample(x: number, y: number, c: number): number
|
||||
local i = (y * w + x) * 4 + c
|
||||
return if wide then buffer.readu16(px, i * 2) else readu8(px, i)
|
||||
end
|
||||
local z = 3
|
||||
for i = 0, w * h - 1 do
|
||||
if (if wide then buffer.readu16(px, i * 8 + 6) < 65535 else readu8(px, i * 4 + 3) < 255) then
|
||||
z = 4
|
||||
break
|
||||
end
|
||||
end
|
||||
local rle = not (opts and opts.rle == false)
|
||||
local out = Bytes.writer(512 + w * h * z * bpc + h * z * 8)
|
||||
out:u16be(474)
|
||||
out:u8(if rle then 1 else 0)
|
||||
out:u8(bpc)
|
||||
out:u16be(3)
|
||||
out:u16be(w)
|
||||
out:u16be(h)
|
||||
out:u16be(z)
|
||||
out:u32be(0)
|
||||
out:u32be(if wide then 65535 else 255)
|
||||
out:u32be(0)
|
||||
local name = (opts and opts.name) or (img.meta and img.meta.text and img.meta.text.name) or ""
|
||||
name = string.sub(name, 1, 79)
|
||||
out:string(name)
|
||||
out:fill(0, 80 - #name)
|
||||
out:u32be(0)
|
||||
out:fill(0, 404)
|
||||
local function put(v: number)
|
||||
if wide then
|
||||
out:u16be(v)
|
||||
else
|
||||
out:u8(v)
|
||||
end
|
||||
end
|
||||
if not rle then
|
||||
for c = 0, z - 1 do
|
||||
for row = 0, h - 1 do
|
||||
local y = h - 1 - row
|
||||
for x = 0, w - 1 do
|
||||
put(sample(x, y, c))
|
||||
end
|
||||
end
|
||||
end
|
||||
return out:finish(), nil
|
||||
end
|
||||
local tables = out:tell()
|
||||
out:fill(0, h * z * 8)
|
||||
for c = 0, z - 1 do
|
||||
for row = 0, h - 1 do
|
||||
local y = h - 1 - row
|
||||
local start = out:tell()
|
||||
local x = 0
|
||||
while x < w do
|
||||
-- a run of equal samples (>= 3) or literals up to the next run
|
||||
local v = sample(x, y, c)
|
||||
local run = 1
|
||||
while x + run < w and run < 127 and sample(x + run, y, c) == v do
|
||||
run += 1
|
||||
end
|
||||
if run >= 3 then
|
||||
put(run)
|
||||
put(v)
|
||||
x += run
|
||||
else
|
||||
local lit = 0
|
||||
while x + lit < w and lit < 127 do
|
||||
local a = sample(x + lit, y, c)
|
||||
if x + lit + 2 < w and sample(x + lit + 1, y, c) == a and sample(x + lit + 2, y, c) == a then
|
||||
break
|
||||
end
|
||||
lit += 1
|
||||
end
|
||||
lit = math.max(lit, 1)
|
||||
put(0x80 + lit)
|
||||
for k = 0, lit - 1 do
|
||||
put(sample(x + k, y, c))
|
||||
end
|
||||
x += lit
|
||||
end
|
||||
end
|
||||
put(0)
|
||||
local i = c * h + row
|
||||
out:setU32be(tables + i * 4, start)
|
||||
out:setU32be(tables + h * z * 4 + i * 4, out:tell() - start)
|
||||
end
|
||||
end
|
||||
return out:finish(), nil
|
||||
end
|
||||
|
||||
return Sgi
|
||||
@@ -0,0 +1,247 @@
|
||||
--!strict
|
||||
-- image/sunras: Sun Raster (rasterfile(5), SunOS <rasterfile.h>; new code). Decode: 1-bit (0 = white without a colour
|
||||
-- map), 8-bit (grey or the RGB colour map), 24-bit and 32-bit pixels in BGR / XBGR order (RT_STANDARD, RT_OLD,
|
||||
-- RT_BYTE_ENCODED) or RGB / XRGB order (RT_FORMAT_RGB), the byte-encoded RLE (0x80 escapes), 16-bit row padding; in
|
||||
-- 32-bit files the X byte is alpha when it is not all zero. Encode: rgba8 as 24-bit (opaque) or 32-bit (alpha in the
|
||||
-- X byte) BGR, RT_BYTE_ENCODED (default) or RT_STANDARD. Not supported: RT_FORMAT_TIFF / RT_FORMAT_IFF (UNSUPPORTED),
|
||||
-- raw colour maps (RMT_RAW is ignored).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Sniff = require("@formats/core/Sniff")
|
||||
local Types = require("@formats/Types")
|
||||
local Pixels = require("@formats/codecs/image/Pixels")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Sunras = {
|
||||
name = "sunras",
|
||||
category = "image",
|
||||
extensions = { "ras", "sun", "rs", "im1", "im8", "im24", "im32" },
|
||||
mime = { "image/x-sun-raster", "image/x-cmu-raster" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Pixels" },
|
||||
caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 8, 24, 32 } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
maxPixels: number?, -- refuse larger images (default 2^26)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
rle: boolean?, -- RT_BYTE_ENCODED (default true); false: RT_STANDARD
|
||||
}
|
||||
|
||||
local MAGIC = "\89\166\106\149"
|
||||
local readu8, readu32 = buffer.readu8, buffer.readu32
|
||||
local function be32(b: buffer, o: number): number
|
||||
return bit32.byteswap(readu32(b, o))
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Sunras.sniff(r: Bytes.Reader): number
|
||||
return Sniff.magic(r, MAGIC)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Sunras.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
||||
local b, o, limit = r.buf, r.base, r.limit
|
||||
if limit - o < 32 then
|
||||
return nil, Err.new(Err.TRUNCATED, "short header", o)
|
||||
end
|
||||
if buffer.readstring(b, o, 4) ~= MAGIC then
|
||||
return nil, Err.new(Err.CORRUPT, "not a Sun raster", o)
|
||||
end
|
||||
local w, h, depth, typ, maptype, maplen = be32(b, o + 4), be32(b, o + 8), be32(b, o + 12), be32(b, o + 20), be32(b, o + 24), be32(b, o + 28)
|
||||
if w == 0 or h == 0 or w > 65536 or h > 65536 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad size", o + 4)
|
||||
end
|
||||
if depth ~= 1 and depth ~= 8 and depth ~= 24 and depth ~= 32 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, depth .. "-bit pixels", o + 12)
|
||||
end
|
||||
if typ == 4 or typ == 5 or typ > 5 and typ ~= 0xFFFF then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "raster type " .. typ, o + 20)
|
||||
end
|
||||
local maxPixels = opts and opts.maxPixels or 2 ^ 26
|
||||
if w * h > maxPixels then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
|
||||
end
|
||||
local p = o + 32
|
||||
if p + maplen > limit then
|
||||
return nil, Err.new(Err.TRUNCATED, "colour map runs past the end", p)
|
||||
end
|
||||
local pal = buffer.create(1024)
|
||||
local ncol = 0
|
||||
if maptype == 1 and maplen > 0 then
|
||||
ncol = math.min(256, maplen // 3)
|
||||
for i = 0, ncol - 1 do
|
||||
buffer.writeu32(pal, i * 4, readu8(b, p + i) + readu8(b, p + ncol + i) * 256 + readu8(b, p + 2 * ncol + i) * 65536 + 0xFF000000)
|
||||
end
|
||||
elseif depth == 1 then
|
||||
buffer.writeu32(pal, 0, 0xFFFFFFFF)
|
||||
buffer.writeu32(pal, 4, 0xFF000000)
|
||||
else
|
||||
for i = 0, 255 do
|
||||
buffer.writeu32(pal, i * 4, i * 0x10101 + 0xFF000000)
|
||||
end
|
||||
end
|
||||
p += maplen
|
||||
local stride = ((w * depth + 15) // 16) * 2
|
||||
local total = stride * h
|
||||
local raw = buffer.create(total + 4)
|
||||
local truncated = false
|
||||
if typ == 2 then
|
||||
local q = 0
|
||||
while q < total and p < limit do
|
||||
local c = readu8(b, p)
|
||||
p += 1
|
||||
if c ~= 0x80 then
|
||||
buffer.writeu8(raw, q, c)
|
||||
q += 1
|
||||
else
|
||||
if p >= limit then
|
||||
break
|
||||
end
|
||||
local n = readu8(b, p)
|
||||
p += 1
|
||||
if n == 0 then
|
||||
buffer.writeu8(raw, q, 0x80)
|
||||
q += 1
|
||||
else
|
||||
if p >= limit then
|
||||
break
|
||||
end
|
||||
local cnt = math.min(n + 1, total - q)
|
||||
buffer.fill(raw, q, readu8(b, p), cnt)
|
||||
p += 1
|
||||
q += cnt
|
||||
end
|
||||
end
|
||||
end
|
||||
truncated = q < total
|
||||
else
|
||||
local n = math.min(total, limit - p)
|
||||
buffer.copy(raw, 0, b, p, n)
|
||||
truncated = n < total
|
||||
end
|
||||
local img = Types.Image.new(w, h, "rgba8")
|
||||
local px = img.pixels
|
||||
if depth <= 8 then
|
||||
Pixels.indexed(raw, 0, stride, depth, px, w, h, true, pal)
|
||||
else
|
||||
local rgb = typ == 3
|
||||
local bytes = depth // 8
|
||||
local alpha = false
|
||||
if bytes == 4 then
|
||||
for y = 0, h - 1 do
|
||||
for x = 0, w - 1 do
|
||||
if readu8(raw, y * stride + x * 4) ~= 0 then
|
||||
alpha = true
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
for y = 0, h - 1 do
|
||||
for x = 0, w - 1 do
|
||||
local s = y * stride + x * bytes
|
||||
local a = 255
|
||||
if bytes == 4 then
|
||||
a = if alpha then readu8(raw, s) else 255
|
||||
s += 1
|
||||
end
|
||||
local c0, c1, c2 = readu8(raw, s), readu8(raw, s + 1), readu8(raw, s + 2)
|
||||
local rr, bb = if rgb then c0 else c2, if rgb then c2 else c0
|
||||
buffer.writeu32(px, (y * w + x) * 4, rr + c1 * 256 + bb * 65536 + a * 16777216)
|
||||
end
|
||||
end
|
||||
end
|
||||
if ncol > 0 then
|
||||
local list: { { number } } = {}
|
||||
for i = 0, ncol - 1 do
|
||||
local v = buffer.readu32(pal, i * 4)
|
||||
list[i + 1] = { bit32.band(v, 255), bit32.band(bit32.rshift(v, 8), 255), bit32.band(bit32.rshift(v, 16), 255), 255 }
|
||||
end
|
||||
img.meta.palette = list
|
||||
end
|
||||
if truncated then
|
||||
img.meta.truncated = true
|
||||
end
|
||||
img.meta.source = { format = "sunras", bitDepth = depth, type = typ, rle = typ == 2 }
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Sunras.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "needs an rgba8 Image")
|
||||
end
|
||||
local w, h = img.width, img.height
|
||||
if w < 1 or h < 1 then
|
||||
return nil, Err.new(Err.ARG, "bad size")
|
||||
end
|
||||
local px = img.pixels
|
||||
local alpha = false
|
||||
for i = 0, w * h - 1 do
|
||||
if readu8(px, i * 4 + 3) < 255 then
|
||||
alpha = true
|
||||
break
|
||||
end
|
||||
end
|
||||
local depth = if alpha then 32 else 24
|
||||
local bytes = depth // 8
|
||||
local stride = ((w * depth + 15) // 16) * 2
|
||||
local raw = buffer.create(stride * h)
|
||||
for y = 0, h - 1 do
|
||||
for x = 0, w - 1 do
|
||||
local s, d = (y * w + x) * 4, y * stride + x * bytes
|
||||
if alpha then
|
||||
buffer.writeu8(raw, d, readu8(px, s + 3))
|
||||
d += 1
|
||||
end
|
||||
buffer.writeu8(raw, d, readu8(px, s + 2))
|
||||
buffer.writeu8(raw, d + 1, readu8(px, s + 1))
|
||||
buffer.writeu8(raw, d + 2, readu8(px, s))
|
||||
end
|
||||
end
|
||||
local rle = not (opts and opts.rle == false)
|
||||
local body = raw
|
||||
if rle then
|
||||
local wr = Bytes.writer(stride * h)
|
||||
local i, n = 0, stride * h
|
||||
while i < n do
|
||||
local v = readu8(raw, i)
|
||||
local run = 1
|
||||
while i + run < n and run < 256 and readu8(raw, i + run) == v do
|
||||
run += 1
|
||||
end
|
||||
if run >= 3 or v == 0x80 then
|
||||
if run == 1 then
|
||||
wr:u8(0x80)
|
||||
wr:u8(0)
|
||||
else
|
||||
wr:u8(0x80)
|
||||
wr:u8(run - 1)
|
||||
wr:u8(v)
|
||||
end
|
||||
else
|
||||
for _ = 1, run do
|
||||
wr:u8(v)
|
||||
end
|
||||
end
|
||||
i += run
|
||||
end
|
||||
body = wr:finish()
|
||||
end
|
||||
local out = Bytes.writer(32 + buffer.len(body))
|
||||
out:string(MAGIC)
|
||||
out:u32be(w)
|
||||
out:u32be(h)
|
||||
out:u32be(depth)
|
||||
out:u32be(buffer.len(body))
|
||||
out:u32be(if rle then 2 else 1)
|
||||
out:u32be(0)
|
||||
out:u32be(0)
|
||||
out:bytes(body)
|
||||
return out:finish(), nil
|
||||
end
|
||||
|
||||
return Sunras
|
||||
@@ -0,0 +1,162 @@
|
||||
--!strict
|
||||
-- image/xbm: X BitMap (X11 bitmap(1) C source; X10 16-bit variant; new code). Decode: the #define _width / _height
|
||||
-- (and _x_hot / _y_hot: meta.hotspot), the char / short bits array in hex, decimal or octal, LSB first, set bits black,
|
||||
-- clear bits white (opts.transparent: clear bits transparent instead). Encode: rgba8 thresholded (luminance below
|
||||
-- opts.threshold, default 128, and alpha >= 128 is black), X11 format, opts.name (default "image").
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Sniff = require("@formats/core/Sniff")
|
||||
local Types = require("@formats/Types")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Xbm = {
|
||||
name = "xbm",
|
||||
category = "image",
|
||||
extensions = { "xbm", "bm" },
|
||||
mime = { "image/x-xbitmap", "image/x-xbm" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" },
|
||||
caps = { decode = true, encode = true, depths = { 1 } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
transparent: boolean?, -- clear bits transparent (default false: white)
|
||||
maxPixels: number?, -- refuse larger images (default 2^26)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
name: string?, -- the C identifier prefix (default "image"; an extension is dropped, other characters become _)
|
||||
threshold: number?, -- luminance below this is black (default 128)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Xbm.sniff(r: Bytes.Reader): number
|
||||
local s = Sniff.text(r, 256, true)
|
||||
if string.match(s, "^#define%s+[%w_]*_?width%s+%d+") or string.match(s, "^/%*.-%*/%s*#define%s+[%w_]*width%s+%d+") then
|
||||
return 0.9
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Xbm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
||||
local n = r.limit - r.base
|
||||
if n > 2 ^ 26 then
|
||||
return nil, Err.new(Err.LIMIT, "file too large")
|
||||
end
|
||||
local s = buffer.readstring(r.buf, r.base, n)
|
||||
local w = tonumber(string.match(s, "#define%s+[%w_]-_?width%s+(%d+)"))
|
||||
local h = tonumber(string.match(s, "#define%s+[%w_]-_?height%s+(%d+)"))
|
||||
if not w or not h or w < 1 or h < 1 then
|
||||
return nil, Err.new(Err.CORRUPT, "missing width / height defines")
|
||||
end
|
||||
local maxPixels = opts and opts.maxPixels or 2 ^ 26
|
||||
if w * h > maxPixels then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
|
||||
end
|
||||
local brace = string.find(s, "{", 1, true)
|
||||
if not brace then
|
||||
return nil, Err.new(Err.CORRUPT, "missing bits array")
|
||||
end
|
||||
local decl = string.sub(s, 1, brace)
|
||||
local short = string.find(decl, "short", 1, true) ~= nil
|
||||
local unit = if short then 16 else 8
|
||||
local per = (w + unit - 1) // unit
|
||||
local want = per * h
|
||||
local img = Types.Image.new(w, h, "rgba8")
|
||||
local px = img.pixels
|
||||
local clear = if opts and opts.transparent then 0x00FFFFFF else 0xFFFFFFFF
|
||||
local got = 0
|
||||
local body = string.gsub(string.sub(s, brace + 1), "/%*.-%*/", " ")
|
||||
for tok in string.gmatch(body, "[%w]+") do
|
||||
if got >= want then
|
||||
break
|
||||
end
|
||||
local v
|
||||
if string.match(tok, "^0[xX]%x+$") then
|
||||
v = tonumber(string.sub(tok, 3), 16)
|
||||
elseif string.match(tok, "^0%d+$") then
|
||||
v = tonumber(tok, 8)
|
||||
elseif string.match(tok, "^%d+$") then
|
||||
v = tonumber(tok)
|
||||
end
|
||||
if v then
|
||||
local y, cx = got // per, (got % per) * unit
|
||||
for k = 0, unit - 1 do
|
||||
local x = cx + k
|
||||
if x < w then
|
||||
buffer.writeu32(px, (y * w + x) * 4, if bit32.band(bit32.rshift(v, k), 1) == 1 then 0xFF000000 else clear)
|
||||
end
|
||||
end
|
||||
got += 1
|
||||
end
|
||||
end
|
||||
if got < want then
|
||||
for i = got * unit, want * unit - 1 do
|
||||
local y, x = i // (per * unit), i % (per * unit)
|
||||
if x < w then
|
||||
buffer.writeu32(px, (y * w + x) * 4, clear)
|
||||
end
|
||||
end
|
||||
img.meta.truncated = true
|
||||
end
|
||||
local hx = tonumber(string.match(s, "#define%s+[%w_]-_?x_hot%s+(%d+)"))
|
||||
local hy = tonumber(string.match(s, "#define%s+[%w_]-_?y_hot%s+(%d+)"))
|
||||
if hx and hy then
|
||||
img.meta.hotspot = { x = hx, y = hy }
|
||||
end
|
||||
local name = string.match(s, "#define%s+([%w_]-)_?width%s")
|
||||
img.meta.source = { format = "xbm", bitDepth = 1, name = name, x10 = short }
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Xbm.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "needs an rgba8 Image")
|
||||
end
|
||||
local w, h = img.width, img.height
|
||||
if w < 1 or h < 1 then
|
||||
return nil, Err.new(Err.ARG, "bad size")
|
||||
end
|
||||
-- a C identifier from opts.name (F.save passes the file name: "out.xbm" -> out)
|
||||
local name = string.gsub(string.gsub(opts and opts.name or "image", "%.[^.]*$", ""), "[^%w_]", "_")
|
||||
if name == "" or string.match(name, "^%d") then
|
||||
name = "_" .. name
|
||||
end
|
||||
local th = opts and opts.threshold or 128
|
||||
local px = img.pixels
|
||||
local parts = {
|
||||
string.format("#define %s_width %d\n#define %s_height %d\n", name, w, name, h),
|
||||
}
|
||||
local hs: { x: number, y: number }? = img.meta and img.meta.hotspot
|
||||
if hs then
|
||||
table.insert(parts, string.format("#define %s_x_hot %d\n#define %s_y_hot %d\n", name, hs.x, name, hs.y))
|
||||
end
|
||||
table.insert(parts, string.format("static unsigned char %s_bits[] = {\n", name))
|
||||
local per = (w + 7) // 8
|
||||
local bytes = {}
|
||||
for y = 0, h - 1 do
|
||||
for bx = 0, per - 1 do
|
||||
local v = 0
|
||||
for k = 0, 7 do
|
||||
local x = bx * 8 + k
|
||||
if x < w then
|
||||
local o = (y * w + x) * 4
|
||||
local lum = 0.299 * buffer.readu8(px, o) + 0.587 * buffer.readu8(px, o + 1) + 0.114 * buffer.readu8(px, o + 2)
|
||||
if lum < th and buffer.readu8(px, o + 3) >= 128 then
|
||||
v += bit32.lshift(1, k)
|
||||
end
|
||||
end
|
||||
end
|
||||
table.insert(bytes, string.format("0x%02x", v))
|
||||
end
|
||||
end
|
||||
for i = 1, #bytes, 12 do
|
||||
table.insert(parts, " " .. table.concat(bytes, ", ", i, math.min(i + 11, #bytes)) .. (if i + 11 < #bytes then ",\n" else " };\n"))
|
||||
end
|
||||
return buffer.fromstring(table.concat(parts)), nil
|
||||
end
|
||||
|
||||
return Xbm
|
||||
@@ -0,0 +1,57 @@
|
||||
--!strict
|
||||
-- image/xpm/Names: colour names for XPM colour tables: the CSS Color 4 named colours (which come from X11), with X11's
|
||||
-- own values where the two differ (gray / grey, green, maroon, purple), and X11's grey0 .. grey100 / gray0 .. gray100.
|
||||
-- lookup(name) takes a lower-case name without spaces and returns R + G * 256 + B * 65536, or nil.
|
||||
local Names = {}
|
||||
|
||||
local HEX: { [string]: number } = {
|
||||
aliceblue = 0xF0F8FF, antiquewhite = 0xFAEBD7, aqua = 0x00FFFF, aquamarine = 0x7FFFD4, azure = 0xF0FFFF,
|
||||
beige = 0xF5F5DC, bisque = 0xFFE4C4, black = 0x000000, blanchedalmond = 0xFFEBCD, blue = 0x0000FF,
|
||||
blueviolet = 0x8A2BE2, brown = 0xA52A2A, burlywood = 0xDEB887, cadetblue = 0x5F9EA0, chartreuse = 0x7FFF00,
|
||||
chocolate = 0xD2691E, coral = 0xFF7F50, cornflowerblue = 0x6495ED, cornsilk = 0xFFF8DC, crimson = 0xDC143C,
|
||||
cyan = 0x00FFFF, darkblue = 0x00008B, darkcyan = 0x008B8B, darkgoldenrod = 0xB8860B, darkgray = 0xA9A9A9,
|
||||
darkgreen = 0x006400, darkgrey = 0xA9A9A9, darkkhaki = 0xBDB76B, darkmagenta = 0x8B008B, darkolivegreen = 0x556B2F,
|
||||
darkorange = 0xFF8C00, darkorchid = 0x9932CC, darkred = 0x8B0000, darksalmon = 0xE9967A, darkseagreen = 0x8FBC8F,
|
||||
darkslateblue = 0x483D8B, darkslategray = 0x2F4F4F, darkslategrey = 0x2F4F4F, darkturquoise = 0x00CED1,
|
||||
darkviolet = 0x9400D3, deeppink = 0xFF1493, deepskyblue = 0x00BFFF, dimgray = 0x696969, dimgrey = 0x696969,
|
||||
dodgerblue = 0x1E90FF, firebrick = 0xB22222, floralwhite = 0xFFFAF0, forestgreen = 0x228B22, fuchsia = 0xFF00FF,
|
||||
gainsboro = 0xDCDCDC, ghostwhite = 0xF8F8FF, gold = 0xFFD700, goldenrod = 0xDAA520, gray = 0xBEBEBE,
|
||||
green = 0x00FF00, greenyellow = 0xADFF2F, grey = 0xBEBEBE, honeydew = 0xF0FFF0, hotpink = 0xFF69B4,
|
||||
indianred = 0xCD5C5C, indigo = 0x4B0082, ivory = 0xFFFFF0, khaki = 0xF0E68C, lavender = 0xE6E6FA,
|
||||
lavenderblush = 0xFFF0F5, lawngreen = 0x7CFC00, lemonchiffon = 0xFFFACD, lightblue = 0xADD8E6, lightcoral = 0xF08080,
|
||||
lightcyan = 0xE0FFFF, lightgoldenrodyellow = 0xFAFAD2, lightgray = 0xD3D3D3, lightgreen = 0x90EE90,
|
||||
lightgrey = 0xD3D3D3, lightpink = 0xFFB6C1, lightsalmon = 0xFFA07A, lightseagreen = 0x20B2AA, lightskyblue = 0x87CEFA,
|
||||
lightslategray = 0x778899, lightslategrey = 0x778899, lightsteelblue = 0xB0C4DE, lightyellow = 0xFFFFE0,
|
||||
lime = 0x00FF00, limegreen = 0x32CD32, linen = 0xFAF0E6, magenta = 0xFF00FF, maroon = 0xB03060,
|
||||
mediumaquamarine = 0x66CDAA, mediumblue = 0x0000CD, mediumorchid = 0xBA55D3, mediumpurple = 0x9370DB,
|
||||
mediumseagreen = 0x3CB371, mediumslateblue = 0x7B68EE, mediumspringgreen = 0x00FA9A, mediumturquoise = 0x48D1CC,
|
||||
mediumvioletred = 0xC71585, midnightblue = 0x191970, mintcream = 0xF5FFFA, mistyrose = 0xFFE4E1, moccasin = 0xFFE4B5,
|
||||
navajowhite = 0xFFDEAD, navy = 0x000080, navyblue = 0x000080, oldlace = 0xFDF5E6, olive = 0x808000, olivedrab = 0x6B8E23,
|
||||
orange = 0xFFA500, orangered = 0xFF4500, orchid = 0xDA70D6, palegoldenrod = 0xEEE8AA, palegreen = 0x98FB98,
|
||||
paleturquoise = 0xAFEEEE, palevioletred = 0xDB7093, papayawhip = 0xFFEFD5, peachpuff = 0xFFDAB9, peru = 0xCD853F,
|
||||
pink = 0xFFC0CB, plum = 0xDDA0DD, powderblue = 0xB0E0E6, purple = 0xA020F0, rebeccapurple = 0x663399, red = 0xFF0000,
|
||||
rosybrown = 0xBC8F8F, royalblue = 0x4169E1, saddlebrown = 0x8B4513, salmon = 0xFA8072, sandybrown = 0xF4A460,
|
||||
seagreen = 0x2E8B57, seashell = 0xFFF5EE, sienna = 0xA0522D, silver = 0xC0C0C0, skyblue = 0x87CEEB,
|
||||
slateblue = 0x6A5ACD, slategray = 0x708090, slategrey = 0x708090, snow = 0xFFFAFA, springgreen = 0x00FF7F,
|
||||
steelblue = 0x4682B4, tan = 0xD2B48C, teal = 0x008080, thistle = 0xD8BFD8, tomato = 0xFF6347, turquoise = 0x40E0D0,
|
||||
violet = 0xEE82EE, wheat = 0xF5DEB3, white = 0xFFFFFF, whitesmoke = 0xF5F5F5, yellow = 0xFFFF00, yellowgreen = 0x9ACD32,
|
||||
}
|
||||
|
||||
-- lookup(name) -> R + G * 256 + B * 65536 | nil (name: lower case, no spaces)
|
||||
function Names.lookup(name: string): number?
|
||||
local v = HEX[name]
|
||||
if v then
|
||||
return bit32.rshift(v, 16) + bit32.band(v, 0xFF00) + bit32.band(v, 0xFF) * 65536
|
||||
end
|
||||
local n = string.match(name, "^gr[ae]y(%d+)$")
|
||||
if n then
|
||||
local k = tonumber(n) :: number
|
||||
if k <= 100 then
|
||||
local g = math.floor(k * 255 / 100 + 0.49)
|
||||
return g * 0x10101
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
return Names
|
||||
@@ -0,0 +1,272 @@
|
||||
--!strict
|
||||
-- image/xpm: X PixMap (XPM 3 C source and the XPM 2 plain form; the "XPM Manual" by Arnaud Le Hors; new code). Decode:
|
||||
-- the values line (width, height, colours, chars per pixel, hotspot: meta.hotspot), colour lines with the c / g / g4 /
|
||||
-- m / s keys (c preferred, then g, g4, m), #RGB / #RRGGBB / #RRRGGGBBB / #RRRRGGGGBBBB, None (transparent) and colour
|
||||
-- names (image/xpm/Names: the CSS / X11 names and grey0..100; an unknown name is black and listed in
|
||||
-- meta.unknownColours), the extensions section skipped. Encode: rgba8 as XPM 3 with hex colours, alpha < 128 as None,
|
||||
-- the fewest chars per pixel; opts.name (default "image").
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Sniff = require("@formats/core/Sniff")
|
||||
local Types = require("@formats/Types")
|
||||
local Names = require("@formats/image/xpm/Names")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Xpm = {
|
||||
name = "xpm",
|
||||
category = "image",
|
||||
extensions = { "xpm", "pm" },
|
||||
mime = { "image/x-xpixmap", "image/x-xpm" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" },
|
||||
caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 8 } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
maxPixels: number?, -- refuse larger images (default 2^26)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
name: string?, -- the C identifier (default "image"; an extension is dropped, other characters become _)
|
||||
}
|
||||
|
||||
-- the characters of pixel codes (printable ASCII without '"' and '\')
|
||||
local CODE_CHARS = " .XoO+@#$%&*=-;:>,<1234567890qwertyuipasdfghjklzxcvbnmMNBVCZASDFGHJKLPIUYTREWQ!~^/()_`'][{}|"
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Xpm.sniff(r: Bytes.Reader): number
|
||||
local s = Sniff.text(r, 64, true)
|
||||
if string.sub(s, 1, 9) == "/* XPM */" or string.sub(s, 1, 6) == "! XPM2" then
|
||||
return 1
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- colour value -> rgba8 u32, or nil for an unknown name
|
||||
local function colour(v: string): number?
|
||||
local l = string.lower(v)
|
||||
if l == "none" or l == "transparent" then
|
||||
return 0
|
||||
end
|
||||
if string.sub(v, 1, 1) == "#" then
|
||||
local hex = string.sub(v, 2)
|
||||
local n = #hex
|
||||
if n % 3 ~= 0 or n == 0 or n > 12 or not string.match(hex, "^%x+$") then
|
||||
return nil
|
||||
end
|
||||
local k = n // 3
|
||||
local mx = 16 ^ k - 1
|
||||
local c = 0
|
||||
for i = 0, 2 do
|
||||
local x = tonumber(string.sub(hex, i * k + 1, i * k + k), 16) :: number
|
||||
c += math.floor(x * 255 / mx + 0.5) * 256 ^ i
|
||||
end
|
||||
return c + 0xFF000000
|
||||
end
|
||||
local rgb = Names.lookup(l)
|
||||
return if rgb then rgb + 0xFF000000 else nil
|
||||
end
|
||||
|
||||
-- the strings of the file: C string literals (XPM 3) or plain lines (XPM 2)
|
||||
local function strings(s: string): { string }
|
||||
local out = {}
|
||||
if string.sub(Sniff.dropBom(s), 1, 6) == "! XPM2" then
|
||||
local first = true
|
||||
for line in string.gmatch(s, "[^\n]+") do
|
||||
if first then
|
||||
first = false
|
||||
else
|
||||
table.insert(out, (string.gsub(line, "\r$", "")))
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
local i, n = 1, #s
|
||||
while i <= n do
|
||||
local c = string.sub(s, i, i)
|
||||
if c == "/" and string.sub(s, i + 1, i + 1) == "*" then
|
||||
local e = string.find(s, "*/", i + 2, true)
|
||||
i = if e then e + 2 else n + 1
|
||||
elseif c == '"' then
|
||||
local parts = {}
|
||||
local j = i + 1
|
||||
while j <= n do
|
||||
local d = string.sub(s, j, j)
|
||||
if d == "\\" then
|
||||
table.insert(parts, string.sub(s, j + 1, j + 1))
|
||||
j += 2
|
||||
elseif d == '"' then
|
||||
break
|
||||
else
|
||||
local e = string.find(s, '["\\]', j)
|
||||
local stop = (e or n + 1) - 1
|
||||
table.insert(parts, string.sub(s, j, stop))
|
||||
j = stop + 1
|
||||
end
|
||||
end
|
||||
table.insert(out, table.concat(parts))
|
||||
i = j + 1
|
||||
else
|
||||
i += 1
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local KEYS = { c = true, m = true, g4 = true, g = true, s = true }
|
||||
|
||||
function Xpm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
|
||||
local n = r.limit - r.base
|
||||
if n > 2 ^ 27 then
|
||||
return nil, Err.new(Err.LIMIT, "file too large")
|
||||
end
|
||||
local list = strings(buffer.readstring(r.buf, r.base, n))
|
||||
if #list == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "no XPM strings")
|
||||
end
|
||||
local vals: { number } = {}
|
||||
for tok in string.gmatch(list[1], "%S+") do
|
||||
table.insert(vals, tonumber(tok) or -1)
|
||||
end
|
||||
local w: number, h: number, nc: number, cpp: number = vals[1] or -1, vals[2] or -1, vals[3] or -1, vals[4] or -1
|
||||
if w < 1 or h < 1 or nc < 1 or cpp < 1 or cpp > 8 or w % 1 ~= 0 or h % 1 ~= 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad values line")
|
||||
end
|
||||
local maxPixels = opts and opts.maxPixels or 2 ^ 26
|
||||
if w * h > maxPixels or nc > 2 ^ 24 then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
|
||||
end
|
||||
if #list < 1 + nc then
|
||||
return nil, Err.new(Err.TRUNCATED, "colour table runs past the end")
|
||||
end
|
||||
local map: { [string]: number } = {}
|
||||
local unknown: { string } = {}
|
||||
local palette: { { number } } = {}
|
||||
for i = 1, nc do
|
||||
local line = list[1 + i]
|
||||
local code = string.sub(line, 1, cpp)
|
||||
local rest = string.sub(line, cpp + 1)
|
||||
local found: { [string]: string } = {}
|
||||
local key: string? = nil
|
||||
local acc = {}
|
||||
for tok in string.gmatch(rest, "%S+") do
|
||||
if KEYS[tok] and (key == nil or #acc > 0) then
|
||||
if key then
|
||||
found[key] = table.concat(acc, " ")
|
||||
end
|
||||
key, acc = tok, {}
|
||||
else
|
||||
table.insert(acc, tok)
|
||||
end
|
||||
end
|
||||
if key then
|
||||
found[key] = table.concat(acc, " ")
|
||||
end
|
||||
local v = found.c or found.g or found.g4 or found.m
|
||||
local c = if v then colour(v) else nil
|
||||
if v and not c then
|
||||
c = colour((string.gsub(v, " ", "")))
|
||||
end
|
||||
local cv: number = c or 0xFF000000
|
||||
if not c then
|
||||
table.insert(unknown, v or "")
|
||||
end
|
||||
c = cv
|
||||
map[code] = cv
|
||||
palette[i] = { bit32.band(cv, 255), bit32.band(bit32.rshift(cv, 8), 255), bit32.band(bit32.rshift(cv, 16), 255), bit32.rshift(cv, 24) }
|
||||
end
|
||||
local img = Types.Image.new(w, h, "rgba8")
|
||||
local px = img.pixels
|
||||
local truncated = false
|
||||
for y = 0, h - 1 do
|
||||
local row = list[2 + nc + y]
|
||||
if not row then
|
||||
truncated = true
|
||||
break
|
||||
end
|
||||
for x = 0, w - 1 do
|
||||
local c = map[string.sub(row, x * cpp + 1, x * cpp + cpp)]
|
||||
buffer.writeu32(px, (y * w + x) * 4, c or 0)
|
||||
end
|
||||
end
|
||||
if #vals >= 6 and vals[5] >= 0 and vals[6] >= 0 then
|
||||
img.meta.hotspot = { x = vals[5], y = vals[6] }
|
||||
end
|
||||
if #unknown > 0 then
|
||||
img.meta.unknownColours = unknown
|
||||
end
|
||||
if truncated then
|
||||
img.meta.truncated = true
|
||||
end
|
||||
img.meta.palette = palette
|
||||
img.meta.source = { format = "xpm", colours = nc, charsPerPixel = cpp }
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Xpm.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then
|
||||
return nil, Err.new(Err.ARG, "needs an rgba8 Image")
|
||||
end
|
||||
local w, h = img.width, img.height
|
||||
if w < 1 or h < 1 then
|
||||
return nil, Err.new(Err.ARG, "bad size")
|
||||
end
|
||||
-- a C identifier from opts.name (F.save passes the file name: "out.xbm" -> out)
|
||||
local name = string.gsub(string.gsub(opts and opts.name or "image", "%.[^.]*$", ""), "[^%w_]", "_")
|
||||
if name == "" or string.match(name, "^%d") then
|
||||
name = "_" .. name
|
||||
end
|
||||
local px = img.pixels
|
||||
local index: { [number]: number } = {}
|
||||
local order: { number } = {}
|
||||
local keys = table.create(w * h, 0)
|
||||
for i = 0, w * h - 1 do
|
||||
local v = buffer.readu32(px, i * 4)
|
||||
local k = if v < 0x80000000 then -1 else bit32.band(v, 0xFFFFFF)
|
||||
if not index[k] then
|
||||
table.insert(order, k)
|
||||
index[k] = #order
|
||||
end
|
||||
keys[i + 1] = index[k]
|
||||
end
|
||||
local nchars = #CODE_CHARS
|
||||
local cpp = 1
|
||||
while nchars ^ cpp < #order do
|
||||
cpp += 1
|
||||
end
|
||||
local codes: { string } = {}
|
||||
for i = 1, #order do
|
||||
local v, s = i - 1, ""
|
||||
for _ = 1, cpp do
|
||||
local d = v % nchars
|
||||
s ..= string.sub(CODE_CHARS, d + 1, d + 1)
|
||||
v //= nchars
|
||||
end
|
||||
codes[i] = s
|
||||
end
|
||||
local parts = { "/* XPM */\n", string.format("static char *%s[] = {\n", name) }
|
||||
local hs: { x: number, y: number }? = img.meta and img.meta.hotspot
|
||||
if hs then
|
||||
table.insert(parts, string.format('"%d %d %d %d %d %d",\n', w, h, #order, cpp, hs.x, hs.y))
|
||||
else
|
||||
table.insert(parts, string.format('"%d %d %d %d",\n', w, h, #order, cpp))
|
||||
end
|
||||
for i, k in order do
|
||||
local col = if k < 0 then "None" else string.format("#%02X%02X%02X", bit32.band(k, 255), bit32.band(bit32.rshift(k, 8), 255), bit32.rshift(k, 16))
|
||||
table.insert(parts, string.format('"%s c %s",\n', codes[i], col))
|
||||
end
|
||||
for y = 0, h - 1 do
|
||||
local row = table.create(w, "")
|
||||
for x = 0, w - 1 do
|
||||
row[x + 1] = codes[keys[y * w + x + 1]]
|
||||
end
|
||||
table.insert(parts, '"' .. table.concat(row) .. '"' .. (if y < h - 1 then ",\n" else "\n"))
|
||||
end
|
||||
table.insert(parts, "};\n")
|
||||
return buffer.fromstring(table.concat(parts)), nil
|
||||
end
|
||||
|
||||
return Xpm
|
||||
@@ -0,0 +1,293 @@
|
||||
--!strict
|
||||
-- layered/ora: OpenRaster (the OpenRaster 0.0.6 specification, freedesktop.org; new code): a zip (containers/Zip) with
|
||||
-- a stored "mimetype" first, stack.xml (codecs/text/Xml), PNG layers, mergedimage.png and Thumbnails/thumbnail.png.
|
||||
-- Decode: the stack tree (nested <stack> = groups: isolation="auto" is passThrough; <layer> name / src / x / y /
|
||||
-- opacity / visibility / composite-op, svg:* ops mapped to the codecs/image/Blend names, unknown ones kept as written),
|
||||
-- layers bottom to top as Types.Layered, the PNGs through the api hook opts.decodeImage (F.load passes it; without it:
|
||||
-- UNSUPPORTED), mergedimage.png as meta.composite, the resolution (meta.dpi). Encode: a Layered (rgba8 layers, groups)
|
||||
-- with every layer, the merged image (codecs/image/Blend flattens the tree, or opts.composite) and a thumbnail (up to
|
||||
-- 256 px, nearest) as PNGs through opts.encodeImage. Not supported: non-PNG layer sources, the <text> / <filter> /
|
||||
-- <selection> elements (ignored).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Zip = require("@formats/containers/Zip")
|
||||
local Xml = require("@formats/codecs/text/Xml")
|
||||
local Blend = require("@formats/codecs/image/Blend")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Ora = {
|
||||
name = "ora",
|
||||
category = "layered",
|
||||
extensions = { "ora" },
|
||||
mime = { "image/openraster" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Zip", "codecs/text/Xml", "codecs/image/Blend" },
|
||||
caps = { decode = true, encode = true, layers = true, groups = true, depths = { 8 } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, -- decodes the PNG layers (the api passes one)
|
||||
composite: boolean?, -- decode mergedimage.png into meta.composite (default true)
|
||||
maxLayers: number?, -- default 10000
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, -- writes the PNGs (the api passes one)
|
||||
composite: Types.Image?, -- the merged image (default: the layers flattened with codecs/image/Blend)
|
||||
thumbnail: boolean?, -- write Thumbnails/thumbnail.png (default true)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local MIME = "image/openraster"
|
||||
local OPS: { [string]: string } = {
|
||||
["svg:src-over"] = "normal", ["svg:multiply"] = "multiply", ["svg:screen"] = "screen", ["svg:overlay"] = "overlay",
|
||||
["svg:darken"] = "darken", ["svg:lighten"] = "lighten", ["svg:color-dodge"] = "colorDodge", ["svg:color-burn"] = "colorBurn",
|
||||
["svg:hard-light"] = "hardLight", ["svg:soft-light"] = "softLight", ["svg:difference"] = "difference",
|
||||
["svg:exclusion"] = "exclusion", ["svg:hue"] = "hue", ["svg:saturation"] = "saturation", ["svg:color"] = "color",
|
||||
["svg:luminosity"] = "luminosity", ["svg:plus"] = "linearDodge",
|
||||
}
|
||||
local BACK: { [string]: string } = {}
|
||||
for k, v in OPS do
|
||||
BACK[v] = k
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Ora.sniff(r: Bytes.Reader): number
|
||||
-- a zip whose first (stored) entry is "mimetype" holding image/openraster
|
||||
if r:peek(4) == "PK\3\4" and r:peek(8, 30) == "mimetype" and r:peek(#MIME, 38) == MIME then
|
||||
return 1
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function num(v: any, default: number): number
|
||||
local n = tonumber(v)
|
||||
return if n and n == n then n else default
|
||||
end
|
||||
|
||||
function Ora.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Layered?, Err.Err?)
|
||||
local zip, zerr = Zip.open(r)
|
||||
if not zip then
|
||||
return nil, zerr
|
||||
end
|
||||
local mt = zip:readString("mimetype")
|
||||
if mt and string.gsub(mt, "%s+$", "") ~= MIME then
|
||||
return nil, Err.new(Err.CORRUPT, "mimetype is not " .. MIME)
|
||||
end
|
||||
local stackText, serr = zip:readString("stack.xml")
|
||||
if not stackText then
|
||||
return nil, serr or Err.new(Err.CORRUPT, "missing stack.xml")
|
||||
end
|
||||
local doc, xerr = Xml.decode(stackText)
|
||||
if not doc then
|
||||
return nil, xerr
|
||||
end
|
||||
local root = doc.root
|
||||
if not root or root.name ~= "image" then
|
||||
return nil, Err.new(Err.CORRUPT, "stack.xml has no <image> root")
|
||||
end
|
||||
local decodeImage = opts and opts.decodeImage
|
||||
if not decodeImage then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "PNG layers need the decodeImage hook")
|
||||
end
|
||||
local W, H = num(root.attrs.w, 0), num(root.attrs.h, 0)
|
||||
if W < 1 or H < 1 or W > 65536 or H > 65536 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad image size")
|
||||
end
|
||||
local maxLayers = opts and opts.maxLayers or 10000
|
||||
local count = 0
|
||||
local function png(path: string): (Types.Image?, Err.Err?)
|
||||
local data, derr = zip:read(path)
|
||||
if not data then
|
||||
return nil, derr or Err.new(Err.CORRUPT, "missing " .. path)
|
||||
end
|
||||
local ok, img, ierr = pcall(decodeImage, data)
|
||||
if not ok or not img then
|
||||
return nil, Err.new(Err.CORRUPT, path .. ": " .. tostring(if ok then ierr else img))
|
||||
end
|
||||
return img, nil
|
||||
end
|
||||
-- a <stack>'s children, top first in the file -> bottom to top
|
||||
local function stack(node: any, ox: number, oy: number): ({ Types.Layer }?, Err.Err?)
|
||||
local out: { Types.Layer } = {}
|
||||
for _, ch in node.children do
|
||||
if type(ch) ~= "table" then
|
||||
continue
|
||||
end
|
||||
local a = ch.attrs or {}
|
||||
local visible = a.visibility ~= "hidden"
|
||||
local op = a["composite-op"] or "svg:src-over"
|
||||
local blend = OPS[op] or op
|
||||
local x, y = ox + num(a.x, 0), oy + num(a.y, 0)
|
||||
count += 1
|
||||
if count > maxLayers then
|
||||
return nil, Err.new(Err.LIMIT, "too many layers")
|
||||
end
|
||||
if ch.name == "layer" then
|
||||
local src = a.src
|
||||
if type(src) ~= "string" then
|
||||
continue
|
||||
end
|
||||
if string.lower(string.sub(src, -4)) ~= ".png" then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "layer source " .. src)
|
||||
end
|
||||
local img, perr = png(src)
|
||||
if not img then
|
||||
return nil, perr
|
||||
end
|
||||
local layer = Types.Layered.layer(a.name or src, img :: Types.Image, x, y)
|
||||
layer.opacity = math.clamp(num(a.opacity, 1), 0, 1)
|
||||
layer.visible = visible
|
||||
layer.blend = blend
|
||||
table.insert(out, 1, layer)
|
||||
elseif ch.name == "stack" then
|
||||
local kids, kerr = stack(ch, x, y)
|
||||
if not kids then
|
||||
return nil, kerr
|
||||
end
|
||||
local g = Types.Layered.group(a.name or "group", kids :: { Types.Layer })
|
||||
g.opacity = math.clamp(num(a.opacity, 1), 0, 1)
|
||||
g.visible = visible
|
||||
g.blend = if a.isolation == "isolate" then (if blend == "normal" then "normal" else blend) else "passThrough"
|
||||
table.insert(out, 1, g)
|
||||
end
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
local top = Xml.child(root, "stack")
|
||||
if not top then
|
||||
return nil, Err.new(Err.CORRUPT, "stack.xml has no <stack>")
|
||||
end
|
||||
local layers, lerr = stack(top, 0, 0)
|
||||
if not layers then
|
||||
return nil, lerr
|
||||
end
|
||||
local doc2 = Types.Layered.new(W, H)
|
||||
doc2.layers = layers :: { Types.Layer }
|
||||
if not (opts and opts.composite == false) and zip:find("mergedimage.png") then
|
||||
doc2.meta.composite = png("mergedimage.png")
|
||||
end
|
||||
local xr, yr = tonumber(root.attrs.xres), tonumber(root.attrs.yres)
|
||||
if xr and yr then
|
||||
doc2.meta.dpi = { x = xr, y = yr }
|
||||
end
|
||||
doc2.meta.source = { format = "ora", version = root.attrs.version, layers = count }
|
||||
return doc2, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- nearest-neighbour downscale to fit max x max
|
||||
local function thumbnail(img: Types.Image, max: number): Types.Image
|
||||
local w, h = img.width, img.height
|
||||
local s = math.min(1, max / math.max(w, h))
|
||||
local tw, th = math.max(1, math.floor(w * s)), math.max(1, math.floor(h * s))
|
||||
local t = Types.Image.new(tw, th, "rgba8")
|
||||
for y = 0, th - 1 do
|
||||
local sy = math.min(h - 1, math.floor(y / s))
|
||||
for x = 0, tw - 1 do
|
||||
local sx = math.min(w - 1, math.floor(x / s))
|
||||
buffer.writeu32(t.pixels, (y * tw + x) * 4, buffer.readu32(img.pixels, (sy * w + sx) * 4))
|
||||
end
|
||||
end
|
||||
return t
|
||||
end
|
||||
|
||||
function Ora.encode(doc: Types.Layered, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(doc) ~= "table" or type(doc.layers) ~= "table" or type(doc.width) ~= "number" or doc.width < 1 or doc.height < 1 then
|
||||
return nil, Err.new(Err.ARG, "needs a Layered document")
|
||||
end
|
||||
local encodeImage = opts and opts.encodeImage
|
||||
if not encodeImage then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "PNG layers need the encodeImage hook")
|
||||
end
|
||||
local W, H = doc.width, doc.height
|
||||
local zw = Zip.writer()
|
||||
zw:add("mimetype", MIME, { method = "store" })
|
||||
local files: { { any } } = {}
|
||||
local n = 0
|
||||
local function png(img: Types.Image, label: string): (buffer?, Err.Err?)
|
||||
if type(img) ~= "table" or img.format ~= "rgba8" then
|
||||
return nil, Err.new(Err.ARG, label .. ": layers need rgba8 images")
|
||||
end
|
||||
local ok, data, err = pcall(encodeImage, img, "png")
|
||||
if not ok or not data then
|
||||
return nil, Err.new(Err.ARG, label .. ": " .. tostring(if ok then err else data))
|
||||
end
|
||||
return data, nil
|
||||
end
|
||||
-- layers bottom to top -> xml children top first
|
||||
local function stack(layers: { Types.Layer }): ({ any }?, Err.Err?)
|
||||
local kids = {}
|
||||
for i = #layers, 1, -1 do
|
||||
local l = layers[i]
|
||||
local attrs: { [string]: string } = {
|
||||
name = l.name or "",
|
||||
opacity = string.format("%.6g", l.opacity or 1),
|
||||
visibility = if l.visible == false then "hidden" else "visible",
|
||||
}
|
||||
if l.children then
|
||||
attrs.isolation = if l.blend == "passThrough" then "auto" else "isolate"
|
||||
if l.blend ~= "passThrough" then
|
||||
attrs["composite-op"] = BACK[l.blend] or l.blend
|
||||
end
|
||||
local sub, serr = stack(l.children)
|
||||
if not sub then
|
||||
return nil, serr
|
||||
end
|
||||
table.insert(kids, Xml.element("stack", attrs, sub))
|
||||
else
|
||||
n += 1
|
||||
local path = string.format("data/layer%03d.png", n)
|
||||
local data, perr = png(l.image, "layer " .. tostring(l.name))
|
||||
if not data then
|
||||
return nil, perr
|
||||
end
|
||||
table.insert(files, { path, data })
|
||||
attrs.src = path
|
||||
attrs.x = tostring(math.floor(l.x or 0))
|
||||
attrs.y = tostring(math.floor(l.y or 0))
|
||||
attrs["composite-op"] = BACK[l.blend or "normal"] or l.blend or "svg:src-over"
|
||||
table.insert(kids, Xml.element("layer", attrs))
|
||||
end
|
||||
end
|
||||
return kids, nil
|
||||
end
|
||||
local kids, kerr = stack(doc.layers)
|
||||
if not kids then
|
||||
return nil, kerr
|
||||
end
|
||||
local rootAttrs: { [string]: string } = { version = "0.0.6", w = tostring(W), h = tostring(H) }
|
||||
local dpi = doc.meta and doc.meta.dpi
|
||||
if dpi then
|
||||
rootAttrs.xres, rootAttrs.yres = tostring(dpi.x), tostring(dpi.y)
|
||||
end
|
||||
local xml = Xml.encode(Xml.document(Xml.element("image", rootAttrs, { Xml.element("stack", {}, kids :: any) })), { indent = 1 })
|
||||
zw:add("stack.xml", xml :: string)
|
||||
for _, f in files do
|
||||
zw:add(f[1], f[2], { method = "store" })
|
||||
end
|
||||
local merged = opts and opts.composite
|
||||
if not merged then
|
||||
local m = Types.Image.new(W, H, "rgba8")
|
||||
Blend.flatten(doc.layers, m.pixels, W, H, false)
|
||||
merged = m
|
||||
end
|
||||
local mdata, merr = png(merged :: Types.Image, "mergedimage")
|
||||
if not mdata then
|
||||
return nil, merr
|
||||
end
|
||||
zw:add("mergedimage.png", mdata, { method = "store" })
|
||||
if not (opts and opts.thumbnail == false) then
|
||||
local tdata, terr = png(thumbnail(merged :: Types.Image, 256), "thumbnail")
|
||||
if not tdata then
|
||||
return nil, terr
|
||||
end
|
||||
zw:add("Thumbnails/thumbnail.png", tdata, { method = "store" })
|
||||
end
|
||||
return zw:finish()
|
||||
end
|
||||
|
||||
return Ora
|
||||
@@ -0,0 +1,241 @@
|
||||
-- codecs/image/Bcn tests: random BC1..BC7 blocks (every BC7 and BC6H mode, the BC1 3-colour mode, odd sizes) against
|
||||
-- Pillow's and Godot's (bcdec) decodes; BC6H floats against Godot; the encoders (BC1 / BC3 / BC4 / BC5) within reach
|
||||
-- of Pillow's encoder PSNR, exact on flat blocks; argument errors; the fuzz no-throw pass. Fixtures: tools/fixtures/bcn.py.
|
||||
local T = require("@tests/T")
|
||||
local Bcn = require("@formats/codecs/image/Bcn")
|
||||
local Half = require("@formats/codecs/image/Half")
|
||||
local Fx = require("@tests/gen/bcn")
|
||||
|
||||
local t = T.suite("bcn")
|
||||
|
||||
-- the largest per-byte difference between two rgba8 buffers (channels: which of r, g, b, a count)
|
||||
local function maxDiff(a: buffer, b: buffer, n: number, channels: { number }): (number, number)
|
||||
local worst, at = 0, -1
|
||||
for i = 0, n - 1 do
|
||||
for _, c in channels do
|
||||
local d = math.abs(buffer.readu8(a, i * 4 + c) - buffer.readu8(b, i * 4 + c))
|
||||
if d > worst then
|
||||
worst, at = d, i
|
||||
end
|
||||
end
|
||||
end
|
||||
return worst, at
|
||||
end
|
||||
|
||||
local RGBA, RGB, RG, R = { 0, 1, 2, 3 }, { 0, 1, 2 }, { 0, 1 }, { 0 }
|
||||
-- which channels each reference defines, and the allowed difference to it
|
||||
local PILLOW: { [string]: { any } } = {
|
||||
bc1 = { RGBA, 0 },
|
||||
bc2 = { RGBA, 0 },
|
||||
bc3 = { RGBA, 0 },
|
||||
bc4 = { RGB, 0 },
|
||||
bc5 = { RG, 0 },
|
||||
bc5s = { RG, 1 }, -- Pillow interpolates the biased unsigned values with truncation
|
||||
bc7 = { RGBA, 0 },
|
||||
}
|
||||
|
||||
local stats = { pillow = 0, godot = 0 }
|
||||
for _, c in Fx.cases do
|
||||
local src = buffer.fromstring(c.data)
|
||||
local px, err = Bcn.decode(c.kind, src, 0, c.w, c.h)
|
||||
t:check(px, c.name .. ": " .. tostring(err))
|
||||
local n = c.w * c.h
|
||||
if Bcn.FLOAT[c.kind] then
|
||||
t:eq(buffer.len(px), n * 16, c.name .. ": rgbaf32 size")
|
||||
-- Godot (bcdec) floats: exact half values
|
||||
local g = buffer.fromstring(c.godot)
|
||||
local worst = 0
|
||||
for i = 0, n - 1 do
|
||||
for ch = 0, 2 do
|
||||
local a, b = buffer.readf32(px, i * 16 + ch * 4), buffer.readf32(g, i * 16 + ch * 4)
|
||||
local d = math.abs(a - b) / math.max(math.abs(b), 1e-3)
|
||||
worst = math.max(worst, d)
|
||||
end
|
||||
end
|
||||
t:check(worst < 1e-3, string.format("%s: relative error %g against Godot", c.name, worst))
|
||||
stats.godot += 1
|
||||
-- Pillow: 8-bit truncation of the clamped float (and no rounding term in its interpolation): within 1. Its
|
||||
-- signed BC6H differs from bcdec and the spec (negative endpoints), so only BC6H UF16 is compared.
|
||||
local p = buffer.fromstring(c.pillow)
|
||||
local w2 = 0
|
||||
for i = 0, n - 1 do
|
||||
for ch = 0, 2 do
|
||||
local v = math.clamp(buffer.readf32(px, i * 16 + ch * 4), 0, 1)
|
||||
w2 = math.max(w2, math.abs(math.floor(v * 255) - buffer.readu8(p, i * 4 + ch)))
|
||||
end
|
||||
end
|
||||
if c.kind == "bc6h" then
|
||||
t:check(w2 <= 1, string.format("%s: %d off Pillow", c.name, w2))
|
||||
stats.pillow += 1
|
||||
end
|
||||
else
|
||||
t:eq(buffer.len(px), n * 4, c.name .. ": rgba8 size")
|
||||
local ref = PILLOW[c.kind]
|
||||
local d, at = maxDiff(px, buffer.fromstring(c.pillow), n, ref[1])
|
||||
t:check(d <= ref[2], string.format("%s: %d off Pillow at pixel %d", c.name, d, at))
|
||||
stats.pillow += 1
|
||||
if c.godot then
|
||||
local chans = if c.kind == "bc4" then R elseif c.kind == "bc5" then RG else RGBA
|
||||
local dg, atg = maxDiff(px, buffer.fromstring(c.godot), n, chans)
|
||||
-- bcdec rounds some interpolated values where Pillow truncates: within 1
|
||||
t:check(dg <= 1, string.format("%s: %d off Godot at pixel %d", c.name, dg, atg))
|
||||
stats.godot += 1
|
||||
end
|
||||
end
|
||||
-- into a bigger buffer at an offset, from an offset
|
||||
local big = buffer.create(buffer.len(src) + 5)
|
||||
buffer.copy(big, 5, src)
|
||||
local bpp = if Bcn.FLOAT[c.kind] then 16 else 4
|
||||
local out = buffer.create(n * bpp + 8)
|
||||
local px2 = Bcn.decode(c.kind, big, 5, c.w, c.h, out, 8)
|
||||
t:check(px2 == out and buffer.readstring(out, 8, n * bpp) == buffer.readstring(px, 0, n * bpp), c.name .. ": offsets")
|
||||
end
|
||||
t:note("%d block images decoded: %d Pillow, %d Godot comparisons", #Fx.cases, stats.pillow, stats.godot)
|
||||
|
||||
-- BC4 SNORM = the red channel of BC5 SNORM
|
||||
do
|
||||
for _, c in Fx.cases do
|
||||
if c.kind == "bc5s" then
|
||||
local src = buffer.fromstring(c.data)
|
||||
local nb = buffer.len(src) // 16
|
||||
local b4 = buffer.create(nb * 8)
|
||||
for i = 0, nb - 1 do
|
||||
buffer.copy(b4, i * 8, src, i * 16, 8)
|
||||
end
|
||||
local p4 = Bcn.decode("bc4s", b4, 0, c.w, c.h) :: buffer
|
||||
local p5 = Bcn.decode("bc5s", src, 0, c.w, c.h) :: buffer
|
||||
local ok = true
|
||||
for i = 0, c.w * c.h - 1 do
|
||||
ok = ok and buffer.readu8(p4, i * 4) == buffer.readu8(p5, i * 4) and buffer.readu8(p4, i * 4 + 1) == buffer.readu8(p5, i * 4)
|
||||
end
|
||||
t:check(ok, c.name .. ": bc4s = bc5s red")
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- encoders
|
||||
local function psnr(a: buffer, b: buffer, n: number, channels: { number }): number
|
||||
local se = 0
|
||||
for i = 0, n - 1 do
|
||||
for _, c in channels do
|
||||
local d = buffer.readu8(a, i * 4 + c) - buffer.readu8(b, i * 4 + c)
|
||||
se += d * d
|
||||
end
|
||||
end
|
||||
return if se == 0 then 99 else 10 * math.log10(255 * 255 * n * #channels / se)
|
||||
end
|
||||
|
||||
for _, e in Fx.enc do
|
||||
local px = buffer.fromstring(e.rgba)
|
||||
local n = e.w * e.h
|
||||
for _, k in { { "bc1", RGB }, { "bc3", RGBA }, { "bc5", RG }, { "bc4", R } } do
|
||||
local kind, ch = k[1], k[2]
|
||||
local blocks, err = Bcn.encode(kind, px, e.w, e.h)
|
||||
t:check(blocks, kind .. " encode: " .. tostring(err))
|
||||
t:eq(buffer.len(blocks), Bcn.size(kind, e.w, e.h), e.name .. " " .. kind .. ": size")
|
||||
local back = Bcn.decode(kind, blocks, 0, e.w, e.h) :: buffer
|
||||
local p = psnr(px, back, n, ch)
|
||||
local base = e.psnr[kind]
|
||||
if base then
|
||||
t:check(p >= base - 0.5, string.format("%s %s: PSNR %.2f dB, Pillow %.2f dB", e.name, kind, p, base))
|
||||
t:note("%s %s: %.2f dB (Pillow %.2f dB)", e.name, kind, p, base)
|
||||
else
|
||||
t:check(p >= 35, string.format("%s %s: PSNR %.2f dB", e.name, kind, p))
|
||||
end
|
||||
if kind == "bc1" then
|
||||
-- the transparent pixels survive (3-colour mode)
|
||||
local bad = 0
|
||||
for i = 0, n - 1 do
|
||||
local a = buffer.readu8(px, i * 4 + 3)
|
||||
if (a >= 128) ~= (buffer.readu8(back, i * 4 + 3) == 255) then
|
||||
bad += 1
|
||||
end
|
||||
end
|
||||
t:eq(bad, 0, e.name .. " bc1: alpha mask")
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- flat colours are exact through the single-colour tables (BC1 4-colour and 3-colour, BC4)
|
||||
do
|
||||
local rand = T.rng(3)
|
||||
local worst = 0
|
||||
for _ = 1, 200 do
|
||||
local r, g, b = rand(256), rand(256), rand(256)
|
||||
local px = buffer.create(64)
|
||||
for i = 0, 15 do
|
||||
buffer.writeu32(px, i * 4, r + g * 256 + b * 65536 + (if i == 5 then 0 else 255) * 16777216)
|
||||
end
|
||||
for _, opaque in { true, false } do
|
||||
if opaque then
|
||||
buffer.writeu8(px, 23, 255)
|
||||
else
|
||||
buffer.writeu8(px, 23, 0)
|
||||
end
|
||||
local back = Bcn.decode("bc1", Bcn.encode("bc1", px, 4, 4) :: buffer, 0, 4, 4) :: buffer
|
||||
for i = 0, 15 do
|
||||
if opaque or i ~= 5 then
|
||||
for c = 0, 2 do
|
||||
worst = math.max(worst, math.abs(buffer.readu8(back, i * 4 + c) - buffer.readu8(px, i * 4 + c)))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
-- 5 / 6-bit endpoints reach every 8-bit value within 1 (4-colour) / 2 (3-colour midpoints)
|
||||
t:check(worst <= 2, "flat bc1 colours within " .. worst)
|
||||
local px = buffer.create(64)
|
||||
for v = 0, 255, 5 do
|
||||
for i = 0, 15 do
|
||||
buffer.writeu32(px, i * 4, v + 0xFF000000)
|
||||
end
|
||||
local back = Bcn.decode("bc4", Bcn.encode("bc4", px, 4, 4) :: buffer, 0, 4, 4) :: buffer
|
||||
t:eq(buffer.readu8(back, 0), v, "flat bc4 " .. v)
|
||||
end
|
||||
end
|
||||
|
||||
-- Half
|
||||
do
|
||||
t:eq(Half.fromFloat(1), 0x3C00, "half 1")
|
||||
t:eq(Half.fromFloat(-2), 0xC000, "half -2")
|
||||
t:eq(Half.fromFloat(65504), 0x7BFF, "half max")
|
||||
t:eq(Half.fromFloat(1e6), 0x7C00, "half overflow")
|
||||
t:eq(Half.fromFloat(2 ^ -24), 1, "half smallest subnormal")
|
||||
t:eq(Half.fromFloat(0 / 0), 0x7E00, "half NaN")
|
||||
local ok = true
|
||||
for h = 0, 65535 do
|
||||
local f = Half.TABLE[h]
|
||||
if f == f and Half.fromFloat(f) ~= h and not (h == 0x8000) then
|
||||
ok = false
|
||||
end
|
||||
end
|
||||
t:check(ok, "half round trip of every pattern")
|
||||
end
|
||||
|
||||
-- errors
|
||||
do
|
||||
local _, e1 = Bcn.decode("bc9", buffer.create(8), 0, 4, 4)
|
||||
t:check(e1 and string.find(e1, "unsupported") ~= nil, "unknown kind")
|
||||
local _, e2 = Bcn.decode("bc1", buffer.create(7), 0, 4, 4)
|
||||
t:check(e2 and string.find(e2, "truncated") ~= nil, "short data")
|
||||
local _, e3 = Bcn.encode("bc7", buffer.create(64), 4, 4)
|
||||
t:check(e3 ~= nil, "no bc7 encoder")
|
||||
local _, e4 = Bcn.encode("bc1", buffer.create(10), 4, 4)
|
||||
t:check(e4 ~= nil, "short pixels")
|
||||
end
|
||||
|
||||
-- fuzz: random block data of every kind and size
|
||||
local samples = {}
|
||||
for _, c in Fx.cases do
|
||||
table.insert(samples, buffer.fromstring(c.data))
|
||||
end
|
||||
for _, kind in { "bc1", "bc2", "bc3", "bc4", "bc4s", "bc5", "bc5s", "bc6h", "bc6hs", "bc7" } do
|
||||
t:fuzz("decode " .. kind, function(b: buffer)
|
||||
local n = buffer.len(b) // Bcn.BLOCK[kind]
|
||||
if n < 1 then
|
||||
return Bcn.decode(kind, b, 0, 4, 4)
|
||||
end
|
||||
return Bcn.decode(kind, b, 0, 4 * n - 1, 3)
|
||||
end, samples, { mutations = 2 })
|
||||
end
|
||||
t:done()
|
||||
@@ -0,0 +1,129 @@
|
||||
-- codecs/image/Etc tests: random ETC1 / ETC2 (every mode: individual, differential, T, H, planar; RGB A1 opaque and
|
||||
-- transparent; RGBA with EAC alpha) and EAC R11 / RG11 (unsigned, signed, multiplier 0) blocks against Godot 4's
|
||||
-- decode (etcpak); odd sizes; the 16-bit EAC output; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/etc.py.
|
||||
local T = require("@tests/T")
|
||||
local Etc = require("@formats/codecs/image/Etc")
|
||||
local Fx = require("@tests/gen/etc")
|
||||
|
||||
local t = T.suite("etc")
|
||||
|
||||
local function maxDiff(a: buffer, b: buffer, n: number, channels: { number }): (number, number)
|
||||
local worst, at = 0, -1
|
||||
for i = 0, n - 1 do
|
||||
for _, c in channels do
|
||||
local d = math.abs(buffer.readu8(a, i * 4 + c) - buffer.readu8(b, i * 4 + c))
|
||||
if d > worst then
|
||||
worst, at = d, i
|
||||
end
|
||||
end
|
||||
end
|
||||
return worst, at
|
||||
end
|
||||
|
||||
local worstEac = 0
|
||||
for _, c in Fx do
|
||||
local src = buffer.fromstring(c.data)
|
||||
local px, err = Etc.decode(c.kind, src, 0, c.w, c.h)
|
||||
t:check(px, c.name .. ": " .. tostring(err))
|
||||
local n = c.w * c.h
|
||||
t:eq(buffer.len(px), n * 4, c.name .. ": size")
|
||||
local eacKind = string.sub(c.kind, 1, 3) == "eac"
|
||||
if c.spec then
|
||||
-- signed EAC against the spec rule (values -1023..1023), biased into 8 bits
|
||||
local two = c.kind == "eac_rg11s"
|
||||
local bad = 0
|
||||
for i = 0, n - 1 do
|
||||
for ch = 0, if two then 1 else 0 do
|
||||
local want = math.floor(c.spec[i * 2 + ch + 1] * 127 / 1023 + 0.5) + 128
|
||||
if buffer.readu8(px, i * 4 + ch) ~= want then
|
||||
bad += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
t:eq(bad, 0, c.name .. ": against the spec values")
|
||||
elseif c.kind == "etc2_rgba1" then
|
||||
-- Godot decoded the blocks as ETC2 RGB: opaque blocks match it; transparent ones have index 2 transparent
|
||||
-- black and indexes 1 / 3 unchanged (index 0 drops its modifier in the differential mode); planar is opaque
|
||||
local g = buffer.fromstring(c.godot)
|
||||
local bw = (c.w + 3) // 4
|
||||
local bad = 0
|
||||
for y = 0, c.h - 1 do
|
||||
for x = 0, c.w - 1 do
|
||||
local bo = ((y // 4) * bw + x // 4) * 8
|
||||
local hi = bit32.byteswap(buffer.readu32(src, bo))
|
||||
local lo = bit32.byteswap(buffer.readu32(src, bo + 4))
|
||||
local i = (x % 4) * 4 + y % 4
|
||||
local idx = bit32.band(bit32.rshift(lo, i + 15), 2) + bit32.band(bit32.rshift(lo, i), 1)
|
||||
local opaque = bit32.band(hi, 2) ~= 0
|
||||
local function ch(v: number, at: number): number
|
||||
v = bit32.band(bit32.rshift(hi, at), 31) + (function(d: number): number
|
||||
return if d >= 4 then d - 8 else d
|
||||
end)(bit32.band(bit32.rshift(hi, at - 3), 7))
|
||||
return v
|
||||
end
|
||||
local r2, g2, b2 = ch(0, 27), ch(0, 19), ch(0, 11)
|
||||
local planar = r2 >= 0 and r2 <= 31 and g2 >= 0 and g2 <= 31 and (b2 < 0 or b2 > 31)
|
||||
local diff = r2 >= 0 and r2 <= 31 and g2 >= 0 and g2 <= 31 and b2 >= 0 and b2 <= 31
|
||||
local o = (y * c.w + x) * 4
|
||||
local mine, ref = buffer.readu32(px, o), buffer.readu32(g, o)
|
||||
if opaque or planar then
|
||||
bad += if mine == ref then 0 else 1
|
||||
elseif idx == 2 then
|
||||
bad += if mine == 0 then 0 else 1
|
||||
elseif idx ~= 0 or not diff then
|
||||
bad += if mine == ref then 0 else 1
|
||||
end
|
||||
end
|
||||
end
|
||||
t:eq(bad, 0, c.name .. ": punch-through rules over Godot's ETC2 RGB decode")
|
||||
else
|
||||
local g = buffer.fromstring(c.godot)
|
||||
local chans = if c.kind == "eac_r11" then { 0 } elseif eacKind then { 0, 1 } else { 0, 1, 2, 3 }
|
||||
local d, at = maxDiff(px, g, n, chans)
|
||||
if eacKind then
|
||||
-- Godot keeps EAC as 16-bit / half floats and converts to 8 bits with its own rounding
|
||||
worstEac = math.max(worstEac, d)
|
||||
t:check(d <= 1, string.format("%s: %d off Godot at pixel %d", c.name, d, at))
|
||||
else
|
||||
t:check(d == 0, string.format("%s: %d off Godot at pixel %d", c.name, d, at))
|
||||
end
|
||||
end
|
||||
-- 16-bit EAC agrees with the 8-bit output
|
||||
if eacKind then
|
||||
local p16 = Etc.decode(c.kind, src, 0, c.w, c.h, nil, 0, true) :: buffer
|
||||
t:eq(buffer.len(p16), n * 8, c.name .. ": rgba16 size")
|
||||
local ok = true
|
||||
for i = 0, n - 1 do
|
||||
local v16 = buffer.readu16(p16, i * 8)
|
||||
ok = ok and math.abs(math.floor(v16 / 257 + 0.5) - buffer.readu8(px, i * 4)) <= 1
|
||||
end
|
||||
t:check(ok, c.name .. ": rgba16 ~ rgba8")
|
||||
end
|
||||
-- from / into offsets
|
||||
local big = buffer.create(buffer.len(src) + 3)
|
||||
buffer.copy(big, 3, src)
|
||||
local out = buffer.create(n * 4 + 4)
|
||||
Etc.decode(c.kind, big, 3, c.w, c.h, out, 4)
|
||||
t:check(buffer.readstring(out, 4, n * 4) == buffer.tostring(px), c.name .. ": offsets")
|
||||
end
|
||||
t:note("%d block images match Godot (EAC within %d)", #Fx, worstEac)
|
||||
|
||||
do
|
||||
local _, e1 = Etc.decode("etc3", buffer.create(8), 0, 4, 4)
|
||||
t:check(e1 and string.find(e1, "unsupported") ~= nil, "unknown kind")
|
||||
local _, e2 = Etc.decode("etc2_rgba", buffer.create(8), 0, 4, 4)
|
||||
t:check(e2 and string.find(e2, "truncated") ~= nil, "short data")
|
||||
t:eq(Etc.size("etc2_rgba", 5, 5), 64, "size")
|
||||
end
|
||||
|
||||
local samples = {}
|
||||
for _, c in Fx do
|
||||
table.insert(samples, buffer.fromstring(c.data))
|
||||
end
|
||||
for kind in Etc.BLOCK do
|
||||
t:fuzz("decode " .. kind, function(b: buffer)
|
||||
local n = buffer.len(b) // Etc.BLOCK[kind]
|
||||
return Etc.decode(kind, b, 0, math.max(1, 4 * n - 2), 4)
|
||||
end, samples, { mutations = 2 })
|
||||
end
|
||||
t:done()
|
||||
@@ -0,0 +1,78 @@
|
||||
-- tests/image/_raster: the shared checks of the simple raster formats' tests (pcx, sgi, sunras, xbm, xpm, ilbm, icns,
|
||||
-- ani): decode every case against its reference rgba8 pixels, round-trip images through the encoder, fuzz samples.
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
|
||||
local R = {}
|
||||
|
||||
local function maxDiff(a: buffer, b: buffer, n: number): (number, number)
|
||||
local worst, at = 0, -1
|
||||
for i = 0, n * 4 - 1 do
|
||||
local d = math.abs(buffer.readu8(a, i) - buffer.readu8(b, i))
|
||||
if d > worst then
|
||||
worst, at = d, i // 4
|
||||
end
|
||||
end
|
||||
return worst, at
|
||||
end
|
||||
R.maxDiff = maxDiff
|
||||
|
||||
-- cases: { { name, data, w, h, rgba, tol? } } (rgba: the reference decode)
|
||||
function R.decodes(t: any, Fmt: any, cases: { any }, opts: any?): number
|
||||
local n = 0
|
||||
for _, c in cases do
|
||||
local img, err = Fmt.decode(Bytes.reader(buffer.fromstring(c.data)), opts)
|
||||
t:check(img, c.name .. ": " .. tostring(err))
|
||||
if img then
|
||||
t:check(img.width == c.w and img.height == c.h and img.format == "rgba8", string.format("%s: %d x %d %s", c.name, img.width, img.height, img.format))
|
||||
if img.width == c.w and img.height == c.h then
|
||||
local d, at = maxDiff(img.pixels, buffer.fromstring(c.rgba), c.w * c.h)
|
||||
t:check(d <= (c.tol or 0), string.format("%s: %d off the reference at pixel %d", c.name, d, at))
|
||||
end
|
||||
n += 1
|
||||
end
|
||||
-- from inside a bigger buffer
|
||||
local big = buffer.create(#c.data + 9)
|
||||
buffer.writestring(big, 5, c.data)
|
||||
local img2 = Fmt.decode(Bytes.reader(big, 5, #c.data), opts)
|
||||
t:check(img2 and img and buffer.tostring(img2.pixels) == buffer.tostring(img.pixels), c.name .. ": from a sub-range")
|
||||
end
|
||||
return n
|
||||
end
|
||||
|
||||
-- image(w, h, rgba string) -> Types.Image
|
||||
function R.image(w: number, h: number, rgba: string): Types.Image
|
||||
local img = Types.Image.new(w, h)
|
||||
img.pixels = buffer.fromstring(rgba)
|
||||
return img
|
||||
end
|
||||
|
||||
-- roundTrip(t, Fmt, img, encodeOpts?, label, tol?) -> the encoded buffer
|
||||
function R.roundTrip(t: any, Fmt: any, img: Types.Image, eopts: any?, label: string, tol: number?): buffer?
|
||||
local enc, err = Fmt.encode(img, eopts)
|
||||
t:check(enc, label .. ": encode " .. tostring(err))
|
||||
if not enc then
|
||||
return nil
|
||||
end
|
||||
local back, derr = Fmt.decode(Bytes.reader(enc))
|
||||
t:check(back, label .. ": decode " .. tostring(derr))
|
||||
if back then
|
||||
t:check(back.width == img.width and back.height == img.height, label .. ": size")
|
||||
local d = maxDiff(back.pixels, img.pixels, img.width * img.height)
|
||||
t:check(d <= (tol or 0), string.format("%s: round trip %d off", label, d))
|
||||
end
|
||||
return enc
|
||||
end
|
||||
|
||||
-- samples(cases, every?) -> the fuzz samples (every n-th case's data)
|
||||
function R.samples(cases: { any }, every: number?): { string }
|
||||
local samples = {}
|
||||
for i, c in cases do
|
||||
if i % (every or 1) == 0 then
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
end
|
||||
return samples
|
||||
end
|
||||
|
||||
return R
|
||||
@@ -0,0 +1,72 @@
|
||||
-- image/ani tests: animated cursors around Pillow-written ICO / CUR frames (seq + rate, plain, cursor hotspots, INFO
|
||||
-- title) against Pillow's frame decodes and the written steps / delays; AF_ICON clear and a missing hook are
|
||||
-- UNSUPPORTED; the encoder through the ICO hook round-trips; the fuzz no-throw pass. Fixtures: tools/fixtures/ani.py.
|
||||
local T = require("@tests/T")
|
||||
local Ani = require("@formats/image/ani")
|
||||
local Ico = require("@formats/image/ico")
|
||||
local Png = require("@formats/image/png")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local R = require("@tests/image/_raster")
|
||||
local Fx = require("@tests/gen/ani")
|
||||
|
||||
local t = T.suite("ani")
|
||||
t:eq(Ani.name, "ani", "name")
|
||||
t:check(Ani.caps.decode and Ani.caps.encode, "caps")
|
||||
|
||||
local hooks = {
|
||||
decodeImage = function(b: buffer): (any, any)
|
||||
-- Pillow writes the ICO entries as PNG: the ICO decoder gets its own hook
|
||||
return Ico.decode(Bytes.reader(b), { decodeImage = function(p: buffer): (any, any)
|
||||
return Png.decode(Bytes.reader(p))
|
||||
end })
|
||||
end,
|
||||
encodeImage = function(img: any, _fmt: string): (any, any)
|
||||
return Ico.encode(img)
|
||||
end,
|
||||
}
|
||||
|
||||
for _, c in Fx.cases do
|
||||
local img, err = Ani.decode(Bytes.reader(buffer.fromstring(c.data)), hooks)
|
||||
if c.unsupported then
|
||||
t:check(img == nil and err and err.code == Err.UNSUPPORTED, c.name .. ": UNSUPPORTED")
|
||||
continue
|
||||
end
|
||||
t:check(img, c.name .. ": " .. tostring(err))
|
||||
t:check(img.width == c.w and img.height == c.h, c.name .. ": size")
|
||||
t:eq(#img.frames, #c.steps, c.name .. ": steps")
|
||||
for i, s in c.steps do
|
||||
local f = img.frames[i]
|
||||
t:check(math.abs(f.delay - s.delay) < 1e-9, c.name .. ": step " .. i .. " delay")
|
||||
t:eq(R.maxDiff(f.image.pixels, buffer.fromstring(c.frames[s.frame]), c.w * c.h), 0, c.name .. ": step " .. i .. " pixels")
|
||||
end
|
||||
t:eq(img.loops, 0, c.name .. ": loops forever")
|
||||
if c.title then
|
||||
t:eq(img.meta.text.title, c.title, c.name .. ": title")
|
||||
end
|
||||
if c.hotspot then
|
||||
t:check(img.meta.hotspot and img.meta.hotspot.x == c.hotspot[1] and img.meta.hotspot.y == c.hotspot[2], c.name .. ": hotspot")
|
||||
end
|
||||
-- re-encode through the ICO hook
|
||||
local enc, eerr = Ani.encode(img, hooks)
|
||||
t:check(enc, c.name .. ": encode " .. tostring(eerr))
|
||||
local back = Ani.decode(Bytes.reader(enc :: buffer), hooks) :: any
|
||||
t:eq(#back.frames, #img.frames, c.name .. ": re-encoded steps")
|
||||
for i, f in back.frames do
|
||||
t:eq(buffer.tostring(f.image.pixels), buffer.tostring(img.frames[i].image.pixels), c.name .. ": re-encoded frame " .. i)
|
||||
t:check(math.abs(f.delay - img.frames[i].delay) < 1 / 120, c.name .. ": re-encoded delay " .. i)
|
||||
end
|
||||
end
|
||||
do
|
||||
local c = Fx.cases[1]
|
||||
t:eq(Ani.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, "sniff")
|
||||
t:eq(Ani.sniff(Bytes.reader(buffer.fromstring("RIFF\0\0\0\0WAVE"))), 0, "sniff WAVE")
|
||||
local _, e = Ani.decode(Bytes.reader(buffer.fromstring(c.data)))
|
||||
t:check(e and e.code == Err.UNSUPPORTED, "no hook")
|
||||
local _, e2 = Ani.encode(Ico.decode(Bytes.reader(buffer.fromstring(c.data))) or ({ pixels = buffer.create(4) } :: any))
|
||||
t:check(e2 ~= nil, "encode without the hook")
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Ani.decode(Bytes.reader(b), hooks)
|
||||
end, R.samples(Fx.cases), { mutations = 10 })
|
||||
t:done()
|
||||
@@ -0,0 +1,212 @@
|
||||
-- image/dds tests: files from NVIDIA Texture Tools (BGRA, BC1..BC7 incl. BC6H, mips, DX10, cube / array / volume)
|
||||
-- and ImageMagick against every surface's reference decode (Pillow per surface, Godot floats for BC6H); hand-written
|
||||
-- uncompressed DXGI / legacy / FourCC formats against their values (rgba8 and native floats); our encoder's files read
|
||||
-- by Pillow and nvddsinfo, and round trips; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/dds.py.
|
||||
local T = require("@tests/T")
|
||||
local Dds = require("@formats/image/dds")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Fx = require("@tests/gen/dds")
|
||||
|
||||
local t = T.suite("dds")
|
||||
|
||||
t:eq(Dds.name, "dds", "name")
|
||||
t:check(Dds.caps.decode and Dds.caps.encode, "caps")
|
||||
|
||||
local function dec(data: any, opts: any?): (any, any)
|
||||
return Dds.decode(Bytes.reader(if type(data) == "string" then buffer.fromstring(data) else data), opts)
|
||||
end
|
||||
|
||||
local function maxDiff(a: buffer, b: buffer, n: number): number
|
||||
local worst = 0
|
||||
for i = 0, n * 4 - 1 do
|
||||
worst = math.max(worst, math.abs(buffer.readu8(a, i) - buffer.readu8(b, i)))
|
||||
end
|
||||
return worst
|
||||
end
|
||||
|
||||
-- tool-written files
|
||||
local surfaces = 0
|
||||
for _, c in Fx.cases do
|
||||
local img, err = dec(c.data, { mips = true })
|
||||
t:check(img, c.name .. ": " .. tostring(err))
|
||||
t:eq(img.meta.layout, c.layout, c.name .. ": layout")
|
||||
t:eq(img.meta.source.mips, c.mips, c.name .. ": mips")
|
||||
local frames = img.frames or { { image = img } }
|
||||
local native = nil
|
||||
for _, s in c.surfaces do
|
||||
local im
|
||||
if s.level == 0 then
|
||||
local idx = s.layer * (if c.layout == "volume" then c.depth else 1) + s.slice + 1
|
||||
im = frames[idx] and frames[idx].image
|
||||
else
|
||||
im = img.meta.mipmaps and img.meta.mipmaps[s.level]
|
||||
end
|
||||
local label = string.format("%s: level %d layer %d slice %d", c.name, s.level, s.layer, s.slice)
|
||||
t:check(im and im.width == s.w and im.height == s.h, label .. ": surface size")
|
||||
if s.floats then
|
||||
native = native or dec(c.data, { native = true, mips = true })
|
||||
local nim = if s.level == 0 then native else native.meta.mipmaps[s.level]
|
||||
t:eq(nim.format, "rgbaf32", label .. ": native rgbaf32")
|
||||
local g = buffer.fromstring(s.floats)
|
||||
local worst = 0
|
||||
for i = 0, s.w * s.h * 4 - 1 do
|
||||
if i % 4 ~= 3 then
|
||||
local a, b = buffer.readf32(nim.pixels, i * 4), buffer.readf32(g, i * 4)
|
||||
worst = math.max(worst, math.abs(a - b) / math.max(math.abs(b), 1e-3))
|
||||
end
|
||||
end
|
||||
t:check(worst < 1e-3, label .. ": floats against Godot " .. worst)
|
||||
else
|
||||
local d = maxDiff(im.pixels, buffer.fromstring(s.rgba), s.w * s.h)
|
||||
t:check(d <= s.tol, string.format("%s: %d off the reference", label, d))
|
||||
end
|
||||
surfaces += 1
|
||||
end
|
||||
-- surfaces = false keeps only the first
|
||||
local one = dec(c.data, { surfaces = false })
|
||||
t:check(one and one.frames == nil, c.name .. ": surfaces = false")
|
||||
end
|
||||
t:note("%d tool-written files, %d surfaces match the references", #Fx.cases, surfaces)
|
||||
|
||||
-- hand-written formats
|
||||
for _, c in Fx.hand do
|
||||
local img, err = dec(c.data)
|
||||
t:check(img, c.name .. ": " .. tostring(err))
|
||||
local n = img.width * img.height
|
||||
local d = maxDiff(img.pixels, buffer.fromstring(c.rgba8), n)
|
||||
t:check(d <= 1, string.format("%s: rgba8 %d off", c.name, d))
|
||||
if c.floats then
|
||||
local nimg = dec(c.data, { native = true })
|
||||
local f = buffer.fromstring(c.floats)
|
||||
local worst = 0
|
||||
local bpp = Types.BPP[nimg.format]
|
||||
for i = 0, n * 4 - 1 do
|
||||
local want = buffer.readf32(f, i * 4)
|
||||
local got
|
||||
if nimg.format == "rgbaf32" then
|
||||
got = buffer.readf32(nimg.pixels, i * 4)
|
||||
elseif nimg.format == "rgba16" then
|
||||
got = buffer.readu16(nimg.pixels, i * 2) / 65535
|
||||
else
|
||||
got = buffer.readu8(nimg.pixels, i) / 255
|
||||
end
|
||||
worst = math.max(worst, math.abs(got - want) / math.max(1, math.abs(want)))
|
||||
end
|
||||
local tol = if nimg.format == "rgba8" then 1 / 255 elseif nimg.format == "rgba16" then 1 / 65535 else 1e-6
|
||||
t:check(worst <= tol + 1e-9, string.format("%s: native %s off by %g", c.name, nimg.format, worst))
|
||||
t:check(bpp ~= nil, c.name .. ": a standard format")
|
||||
end
|
||||
end
|
||||
t:note("%d hand-written formats match", #Fx.hand)
|
||||
|
||||
-- our encoder: Pillow / nvddsinfo read the files, and they round-trip
|
||||
local function source(w: number, h: number): buffer
|
||||
local px = buffer.create(w * h * 4)
|
||||
for y = 0, h - 1 do
|
||||
for x = 0, w - 1 do
|
||||
local o = (y * w + x) * 4
|
||||
buffer.writeu8(px, o, math.floor(x / (w - 1) * 255 + 0.5))
|
||||
buffer.writeu8(px, o + 1, math.floor(y / (h - 1) * 255 + 0.5))
|
||||
buffer.writeu8(px, o + 2, math.floor(((x * 7 + y * 13) % 64) / 63 * 255 + 0.5))
|
||||
buffer.writeu8(px, o + 3, math.floor(((x + y) % 5) / 4 * 255 + 0.5))
|
||||
end
|
||||
end
|
||||
return px
|
||||
end
|
||||
local src = source(37, 23)
|
||||
for _, o in Fx.ours do
|
||||
local img, err = dec(o.data, { mips = true, native = true })
|
||||
t:check(img, o.name .. ": " .. tostring(err))
|
||||
t:check(o.width == img.width and o.height == img.height, o.name .. ": nvddsinfo size")
|
||||
local mips = img.meta.source.mips
|
||||
t:eq(math.max(1, o.mipcount), mips, o.name .. ": nvddsinfo mip count")
|
||||
if string.find(o.name, "mips") or string.find(o.name, "rgba16") or string.find(o.name, "rgba32f") or string.find(o.name, "cube") or string.find(o.name, "dx10") then
|
||||
if not string.find(o.name, "rgba16f") and not string.find(o.name, "array") then
|
||||
t:check(mips > 1 and #img.meta.mipmaps == mips - 1, o.name .. ": a mip chain")
|
||||
end
|
||||
end
|
||||
if o.pillow then
|
||||
local p = buffer.fromstring(o.pillow)
|
||||
local exact = string.find(o.name, "rgba8") or string.find(o.name, "bgra8")
|
||||
local d = maxDiff(img.pixels, p, img.width * img.height)
|
||||
t:check(d == 0, string.format("%s: Pillow reads %d off our decode", o.name, d))
|
||||
if exact then
|
||||
t:eq(buffer.tostring(p), buffer.tostring(src), o.name .. ": Pillow reads the source exactly")
|
||||
end
|
||||
end
|
||||
if string.find(o.name, "cube") then
|
||||
t:eq(img.meta.layout, "cube", o.name .. ": cube")
|
||||
t:eq(#img.frames, 6, o.name .. ": 6 faces")
|
||||
t:check(string.find(o.caps2, "FE00", 1, true) ~= nil, o.name .. ": nvddsinfo sees all faces")
|
||||
elseif string.find(o.name, "array") then
|
||||
t:eq(#img.frames, 6, o.name .. ": 6 layers")
|
||||
t:eq(o.array, "6", o.name .. ": nvddsinfo array size")
|
||||
end
|
||||
if string.find(o.name, "rgba32f") then
|
||||
t:check(string.find(o.dxgi, "R32G32B32A32_FLOAT", 1, true) ~= nil, o.name .. ": DXGI format " .. o.dxgi)
|
||||
t:eq(img.format, "rgbaf32", o.name .. ": rgbaf32")
|
||||
t:check(math.abs(buffer.readf32(img.pixels, 36 * 16) - 4) < 1e-6, o.name .. ": float values kept")
|
||||
elseif string.find(o.name, "rgba16f") then
|
||||
t:check(string.find(o.dxgi, "R16G16B16A16_FLOAT", 1, true) ~= nil, o.name .. ": DXGI format " .. o.dxgi)
|
||||
t:check(math.abs(buffer.readf32(img.pixels, 36 * 16) - 4) < 1e-3, o.name .. ": half values")
|
||||
elseif string.find(o.name, "rgba16") then
|
||||
t:check(string.find(o.dxgi, "R16G16B16A16_UNORM", 1, true) ~= nil, o.name .. ": DXGI format " .. o.dxgi)
|
||||
t:eq(img.format, "rgba16", o.name .. ": rgba16")
|
||||
end
|
||||
end
|
||||
t:note("%d of our files read by Pillow / nvddsinfo", #Fx.ours)
|
||||
|
||||
-- round trips
|
||||
do
|
||||
local img = Types.Image.new(37, 23)
|
||||
img.pixels = src
|
||||
for _, f in { "rgba8", "bgra8" } do
|
||||
local back = dec(Dds.encode(img, { pixelFormat = f :: any }) :: buffer)
|
||||
t:eq(buffer.tostring(back.pixels), buffer.tostring(src), f .. " round trip")
|
||||
end
|
||||
local f = Types.Image.new(3, 2, "rgbaf32")
|
||||
for i = 0, 23 do
|
||||
buffer.writef32(f.pixels, i * 4, i * 0.37 - 2)
|
||||
end
|
||||
local back = dec(Dds.encode(f) :: buffer, { native = true })
|
||||
t:eq(buffer.tostring(back.pixels), buffer.tostring(f.pixels), "rgba32f round trip")
|
||||
local _, e1 = Dds.encode(f, { pixelFormat = "bc1" })
|
||||
t:check(e1 and e1.code == Err.ARG, "bc1 needs rgba8")
|
||||
local _, e2 = Dds.encode(img, { pixelFormat = "bc7" :: any })
|
||||
t:check(e2 and e2.code == Err.ARG, "no bc7 encoder")
|
||||
end
|
||||
|
||||
-- sniff and errors
|
||||
do
|
||||
local c = Fx.cases[1]
|
||||
t:eq(Dds.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, "sniff")
|
||||
t:eq(Dds.sniff(Bytes.reader(buffer.fromstring("DDX \124\0\0\0"))), 0, "sniff other")
|
||||
local _, e = dec(string.sub(c.data, 1, 100))
|
||||
t:check(e and e.code == Err.TRUNCATED, "short header")
|
||||
local _, e2 = dec(string.sub(c.data, 1, 140))
|
||||
t:check(e2 and e2.code == Err.TRUNCATED, "no pixels: " .. tostring(e2))
|
||||
local bad = buffer.fromstring(c.data)
|
||||
buffer.writeu32(bad, 4, 100)
|
||||
local _, e3 = dec(bad)
|
||||
t:check(e3 and e3.code == Err.CORRUPT, "bad header size")
|
||||
local _, e4 = dec(c.data, { maxPixels = 10 })
|
||||
t:check(e4 and e4.code == Err.LIMIT, "limit")
|
||||
local info = Dds.info(Bytes.reader(buffer.fromstring(c.data)))
|
||||
t:check(info and info.width > 0, "info")
|
||||
end
|
||||
|
||||
local samples = {}
|
||||
for i, c in Fx.cases do
|
||||
if i % 3 == 0 then
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
end
|
||||
for _, c in Fx.hand do
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return dec(b, { mips = true })
|
||||
end, samples, { mutations = 6 })
|
||||
t:done()
|
||||
@@ -0,0 +1,143 @@
|
||||
-- image/exr tests: files from the OpenEXR 3.5 bindings (NONE / RLE / ZIPS / ZIP / PIZ; HALF / FLOAT / UINT; offset
|
||||
-- data window; decreasing lines; Y-only; a layer), a hand-written subsampled file, exrmaketiled tiles (one level,
|
||||
-- mip-map, rip-map, round up) and exrmultipart parts against the bindings' reads; PXR24 / B44 / DWAA UNSUPPORTED; our
|
||||
-- files read back by the bindings and exrheader; round trips; errors; the fuzz no-throw pass. Fixtures:
|
||||
-- tools/fixtures/exr.py.
|
||||
local T = require("@tests/T")
|
||||
local Exr = require("@formats/image/exr")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Fx = require("@tests/gen/exr")
|
||||
|
||||
local t = T.suite("exr")
|
||||
|
||||
t:eq(Exr.name, "exr", "name")
|
||||
t:check(Exr.caps.decode and Exr.caps.encode, "caps")
|
||||
|
||||
local function dec(data: any, opts: any?): (any, any)
|
||||
return Exr.decode(Bytes.reader(if type(data) == "string" then buffer.fromstring(data) else data), opts)
|
||||
end
|
||||
|
||||
-- the largest difference between two rgbaf32 buffers (exact for HALF / FLOAT, UINT as their values)
|
||||
local function worst(a: buffer, b: buffer, n: number): number
|
||||
local m = 0
|
||||
for i = 0, n * 4 - 1 do
|
||||
local x, y = buffer.readf32(a, i * 4), buffer.readf32(b, i * 4)
|
||||
if x ~= y then
|
||||
m = math.max(m, math.abs(x - y) / math.max(1, math.abs(y)))
|
||||
end
|
||||
end
|
||||
return m
|
||||
end
|
||||
|
||||
for _, c in Fx.cases do
|
||||
if c.unsupported then
|
||||
local img, e = dec(c.data)
|
||||
t:check(img == nil and e and e.code == Err.UNSUPPORTED, c.name .. ": UNSUPPORTED (" .. tostring(e) .. ")")
|
||||
continue
|
||||
end
|
||||
local opts = { native = true, layer = c.layer, part = c.part, mips = c.mips }
|
||||
local img, err = dec(c.data, opts)
|
||||
t:check(img, c.name .. ": " .. tostring(err))
|
||||
t:check(img.width == c.w and img.height == c.h and img.format == "rgbaf32", c.name .. ": size")
|
||||
local d = worst(img.pixels, buffer.fromstring(c.floats), c.w * c.h)
|
||||
t:check(d < 1e-6, string.format("%s: off by %g", c.name, d))
|
||||
if c.partName then
|
||||
local byName = dec(c.data, { native = true, part = c.partName })
|
||||
t:check(byName and buffer.tostring(byName.pixels) == buffer.tostring(img.pixels), c.name .. ": part by name")
|
||||
t:eq(img.meta.source.parts[c.part].name, c.partName, c.name .. ": part names")
|
||||
end
|
||||
if c.mips and string.find(c.name, "mip") then
|
||||
local mm = img.meta.mipmaps
|
||||
t:check(mm and #mm >= 5, c.name .. ": mip levels")
|
||||
local up = string.find(c.name, "up") ~= nil
|
||||
t:eq(mm[1].width, if up then math.ceil(c.w / 2) else c.w // 2, c.name .. ": level 1 width")
|
||||
end
|
||||
-- the rgba8 display conversion
|
||||
local d8 = dec(c.data, { layer = c.layer, part = c.part })
|
||||
t:eq(d8.format, "rgba8", c.name .. ": rgba8 by default")
|
||||
end
|
||||
t:note("%d files match the OpenEXR bindings", #Fx.cases)
|
||||
|
||||
-- the window, the attributes
|
||||
do
|
||||
for _, c in Fx.cases do
|
||||
if c.name == "window_zip.exr" then
|
||||
local img = dec(c.data)
|
||||
t:check(img.meta.dataWindow.x == 5 and img.meta.dataWindow.y == -3, "data window origin")
|
||||
t:check(img.meta.displayWindow.width == 40 and img.meta.displayWindow.height == 20, "display window")
|
||||
t:eq(img.meta.source.compression, "zip", "compression name")
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- our files: the bindings read our values back, exrheader accepts them
|
||||
for _, o in Fx.ours do
|
||||
t:check(o.headerOk, o.name .. ": exrheader")
|
||||
local img = dec(o.data, { native = true })
|
||||
local n = img.width * img.height
|
||||
local d = worst(img.pixels, buffer.fromstring(o.floats), n)
|
||||
t:check(d == 0, string.format("%s: the bindings read %g off our decode", o.name, d))
|
||||
end
|
||||
t:note("%d of our files read back by the OpenEXR bindings", #Fx.ours)
|
||||
|
||||
-- round trips: FLOAT exactly, HALF to half precision
|
||||
do
|
||||
local f = Types.Image.new(13, 9, "rgbaf32")
|
||||
local rand = T.rng(5)
|
||||
for i = 0, 13 * 9 * 4 - 1 do
|
||||
buffer.writef32(f.pixels, i * 4, (rand(20000) - 5000) / 997)
|
||||
end
|
||||
for _, comp in { "none", "zips", "zip" } do
|
||||
local back = dec(Exr.encode(f, { compression = comp :: any, pixelType = "float" }) :: buffer, { native = true })
|
||||
t:eq(buffer.tostring(back.pixels), buffer.tostring(f.pixels), comp .. ": float round trip")
|
||||
local hb = dec(Exr.encode(f, { compression = comp :: any }) :: buffer, { native = true })
|
||||
t:check(worst(hb.pixels, f.pixels, 13 * 9) < 1e-3, comp .. ": half round trip")
|
||||
end
|
||||
local img8 = Types.Image.new(4, 4)
|
||||
for i = 0, 63 do
|
||||
buffer.writeu8(img8.pixels, i, (i * 37) % 256)
|
||||
end
|
||||
local back8 = dec(Exr.encode(img8, { pixelType = "float" }) :: buffer)
|
||||
local ok = true
|
||||
for i = 0, 63 do
|
||||
ok = ok and math.abs(buffer.readu8(back8.pixels, i) - buffer.readu8(img8.pixels, i)) <= 1
|
||||
end
|
||||
t:check(ok, "rgba8 through the display curve and back")
|
||||
local _, e = Exr.encode(f, { compression = "piz" :: any })
|
||||
t:check(e and e.code == Err.ARG, "no PIZ encoder")
|
||||
end
|
||||
|
||||
-- sniff, info, errors
|
||||
do
|
||||
local c = Fx.cases[1]
|
||||
t:eq(Exr.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, "sniff")
|
||||
t:eq(Exr.sniff(Bytes.reader(buffer.fromstring("v/1\0"))), 0, "sniff other")
|
||||
local info = Exr.info(Bytes.reader(buffer.fromstring(c.data)))
|
||||
t:check(info and #info.parts == 1 and #info.parts[1].channels == 4, "info")
|
||||
local _, e = dec(string.sub(c.data, 1, 40))
|
||||
t:check(e and e.code == Err.TRUNCATED, "short header: " .. tostring(e))
|
||||
local _, e2 = dec(c.data, { maxPixels = 10 })
|
||||
t:check(e2 and e2.code == Err.LIMIT, "limit")
|
||||
local _, e3 = dec(c.data, { part = 3 })
|
||||
t:check(e3 and e3.code == Err.ARG, "no such part")
|
||||
-- a zeroed offset table is rebuilt
|
||||
local b = buffer.fromstring(c.data)
|
||||
local info2 = Exr.info(Bytes.reader(b)) :: any
|
||||
local tab = info2.dataStart - 8 * info2.parts[1].chunks
|
||||
buffer.fill(b, tab, 0, 8 * info2.parts[1].chunks)
|
||||
local img = dec(b, { native = true })
|
||||
t:check(img and buffer.tostring(img.pixels) == buffer.tostring(dec(c.data, { native = true }).pixels), "rebuilt offset table")
|
||||
end
|
||||
|
||||
local samples = {}
|
||||
for i, c in Fx.cases do
|
||||
if i % 3 == 0 or c.unsupported then
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return dec(b, { mips = true })
|
||||
end, samples, { mutations = 6 })
|
||||
t:done()
|
||||
@@ -0,0 +1,84 @@
|
||||
-- image/icns tests: a libicns file (RLE entries + masks, JPEG 2000 entries skipped), a Pillow file (PNG entries through
|
||||
-- the decodeImage hook) and a hand-written one (ics#, raw is32, ic04 ARGB) against icns2png's / the written pixels;
|
||||
-- our RLE file read back by icns2png; PNG entries through encodeImage; errors; the fuzz no-throw pass. Fixtures:
|
||||
-- tools/fixtures/icns.py.
|
||||
local T = require("@tests/T")
|
||||
local Icns = require("@formats/image/icns")
|
||||
local Png = require("@formats/image/png")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local R = require("@tests/image/_raster")
|
||||
local Fx = require("@tests/gen/icns")
|
||||
|
||||
local t = T.suite("icns")
|
||||
t:eq(Icns.name, "icns", "name")
|
||||
t:check(Icns.caps.decode and Icns.caps.encode, "caps")
|
||||
|
||||
local hooks = {
|
||||
decodeImage = function(b: buffer): (any, any)
|
||||
return Png.decode(Bytes.reader(b))
|
||||
end,
|
||||
encodeImage = function(img: any, _fmt: string): (any, any)
|
||||
return Png.encode(img)
|
||||
end,
|
||||
}
|
||||
|
||||
local function check(c: any)
|
||||
local img, err = Icns.decode(Bytes.reader(buffer.fromstring(c.data)), hooks)
|
||||
t:check(img, c.name .. ": " .. tostring(err))
|
||||
local frames = img.frames or { { image = img } }
|
||||
t:check(#frames >= #c.entries, c.name .. ": entries") -- icns2png writes one file per size (@2x entries collide)
|
||||
for _, e in c.entries do
|
||||
local found = nil
|
||||
for _, f in frames do
|
||||
local im = f.image
|
||||
if im.width == e.w and im.height == e.h and (e.type == "" or im.meta.source.type == e.type) then
|
||||
found = im
|
||||
end
|
||||
end
|
||||
t:check(found, c.name .. ": entry " .. e.type .. " " .. e.w)
|
||||
if found then
|
||||
local d = R.maxDiff(found.pixels, buffer.fromstring(e.rgba), e.w * e.h)
|
||||
t:eq(d, 0, string.format("%s: %s %dx%d pixels", c.name, e.type, e.w, e.h))
|
||||
end
|
||||
end
|
||||
t:eq(if img.meta.skipped then #img.meta.skipped else 0, c.skipped or 0, c.name .. ": skipped entries")
|
||||
return img
|
||||
end
|
||||
for _, c in Fx.cases do
|
||||
check(c)
|
||||
end
|
||||
for _, o in Fx.ours do
|
||||
check(o)
|
||||
end
|
||||
t:note("%d files and our encoder's file match", #Fx.cases)
|
||||
|
||||
do
|
||||
-- PNG entries through the hooks, legacy entries without them
|
||||
local img = Types.Image.new(64, 64)
|
||||
for i = 0, 64 * 64 - 1 do
|
||||
buffer.writeu32(img.pixels, i * 4, i * 2654435761 % 4294967296)
|
||||
end
|
||||
local small = Types.Image.new(16, 16)
|
||||
buffer.fill(small.pixels, 0, 200)
|
||||
img.frames = { { image = img, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" }, { image = small, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" } }
|
||||
local enc = Icns.encode(img, hooks) :: buffer
|
||||
local back = Icns.decode(Bytes.reader(enc), hooks) :: any
|
||||
t:check(back and back.width == 64 and buffer.tostring(back.pixels) == buffer.tostring(img.pixels), "PNG entries round trip")
|
||||
t:eq(#back.frames, 2, "two sizes")
|
||||
local _, e = Icns.encode(img)
|
||||
t:check(e and e.code == Err.ARG, "64 x 64 needs the PNG hook")
|
||||
local leg = Icns.encode(small) :: buffer
|
||||
local lb = Icns.decode(Bytes.reader(leg)) :: any
|
||||
t:eq(buffer.tostring(lb.pixels), buffer.tostring(small.pixels), "legacy round trip")
|
||||
local _, e2 = Icns.decode(Bytes.reader(enc))
|
||||
t:check(e2 and e2.code == Err.UNSUPPORTED, "PNG entries without the hook: UNSUPPORTED")
|
||||
t:eq(Icns.sniff(Bytes.reader(enc)), 1, "sniff")
|
||||
local _, e3 = Icns.encode(Types.Image.new(10, 12))
|
||||
t:check(e3 and e3.code == Err.ARG, "not square")
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Icns.decode(Bytes.reader(b), hooks)
|
||||
end, R.samples(Fx.cases), { mutations = 6 })
|
||||
t:done()
|
||||
@@ -0,0 +1,72 @@
|
||||
-- image/ilbm tests: files from netpbm's ppmtoilbm (palette, uncompressed, HAM6, HAM8, 24-bit) and hand-written ones
|
||||
-- (EHB, chunky PBM, a mask plane, a transparent colour) against ilbmtoppm (colours) and the written masks (alpha); our
|
||||
-- encoder's files read by ilbmtoppm; round trips (palette, 24 and 32 planes, uncompressed); errors; the fuzz no-throw
|
||||
-- pass. Fixtures: tools/fixtures/ilbm.py.
|
||||
local T = require("@tests/T")
|
||||
local Ilbm = require("@formats/image/ilbm")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local R = require("@tests/image/_raster")
|
||||
local Fx = require("@tests/gen/ilbm")
|
||||
|
||||
local t = T.suite("ilbm")
|
||||
t:eq(Ilbm.name, "ilbm", "name")
|
||||
t:check(Ilbm.caps.decode and Ilbm.caps.encode, "caps")
|
||||
|
||||
local function check(c: any)
|
||||
local img, err = Ilbm.decode(Bytes.reader(buffer.fromstring(c.data)))
|
||||
t:check(img, c.name .. ": " .. tostring(err))
|
||||
t:check(img.width == c.w and img.height == c.h, c.name .. ": size")
|
||||
local ref = buffer.fromstring(c.rgba)
|
||||
local bad, badA = 0, 0
|
||||
for i = 0, c.w * c.h - 1 do
|
||||
local transparent = c.transparent and c.transparent[i + 1]
|
||||
local v = buffer.readu32(img.pixels, i * 4)
|
||||
if transparent then
|
||||
badA += if v == 0 then 0 else 1
|
||||
else
|
||||
for k = 0, 3 do
|
||||
if math.abs(buffer.readu8(img.pixels, i * 4 + k) - buffer.readu8(ref, i * 4 + k)) > (c.tol or 0) then
|
||||
bad += 1
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
t:eq(bad, 0, c.name .. ": colours against ilbmtoppm")
|
||||
t:eq(badA, 0, c.name .. ": transparent pixels")
|
||||
return img
|
||||
end
|
||||
for _, c in Fx.cases do
|
||||
check(c)
|
||||
if not c.transparent and not c.tol then
|
||||
R.roundTrip(t, Ilbm, R.image(c.w, c.h, c.rgba), nil, c.name .. " re-encoded")
|
||||
R.roundTrip(t, Ilbm, R.image(c.w, c.h, c.rgba), { compress = false }, c.name .. " re-encoded uncompressed")
|
||||
end
|
||||
end
|
||||
for _, o in Fx.ours do
|
||||
check(o)
|
||||
end
|
||||
t:note("%d files and %d of ours match ilbmtoppm", #Fx.cases, #Fx.ours)
|
||||
do
|
||||
local img = R.image(3, 2, string.rep("\1\2\3\128", 6))
|
||||
local enc = R.roundTrip(t, Ilbm, img, nil, "alpha: 32 planes") :: buffer
|
||||
t:eq(Ilbm.sniff(Bytes.reader(enc)), 1, "sniff")
|
||||
t:eq(Ilbm.sniff(Bytes.reader(buffer.fromstring("FORM\0\0\0\4AIFF"))), 0, "sniff AIFF")
|
||||
local back = Ilbm.decode(Bytes.reader(enc)) :: any
|
||||
t:eq(back.meta.source.planes, 32, "32 planes")
|
||||
local _, e = Ilbm.decode(Bytes.reader(buffer.fromstring("FORM\0\0\0\4ILBM")))
|
||||
t:check(e and e.code == Err.CORRUPT, "no BMHD")
|
||||
local _, e2 = Ilbm.decode(Bytes.reader(enc), { maxPixels = 2 })
|
||||
t:check(e2 and e2.code == Err.LIMIT, "limit")
|
||||
for _, c in Fx.cases do
|
||||
if c.name == "hand_transparent.iff" then
|
||||
local im = Ilbm.decode(Bytes.reader(buffer.fromstring(c.data))) :: any
|
||||
t:eq(im.meta.text and im.meta.text.name, "tiny", "NAME chunk")
|
||||
end
|
||||
end
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Ilbm.decode(Bytes.reader(b))
|
||||
end, R.samples(Fx.cases), { mutations = 6 })
|
||||
t:done()
|
||||
@@ -0,0 +1,167 @@
|
||||
-- image/ktx tests: KTX2 files from KTX-Software (`ktx create` from PNGs and raw data in uncompressed / packed / float /
|
||||
-- BCn / ETC2 / EAC formats, mips, cube maps, arrays, 3D, Zstandard and ZLIB supercompression; Basis Universal is
|
||||
-- UNSUPPORTED) and KTX1 files from toktx / nvcompress / hand-written ones (big-endian, packed types, row padding,
|
||||
-- KTXorientation) against their sources or reference decodes; our KTX2 files through `ktx validate` / `ktx extract`;
|
||||
-- round trips; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/ktx.py.
|
||||
local T = require("@tests/T")
|
||||
local Ktx = require("@formats/image/ktx")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Fx = require("@tests/gen/ktx")
|
||||
|
||||
local t = T.suite("ktx")
|
||||
|
||||
t:eq(Ktx.name, "ktx", "name")
|
||||
t:check(Ktx.caps.decode and Ktx.caps.encode, "caps")
|
||||
|
||||
local function dec(data: any, opts: any?): (any, any)
|
||||
return Ktx.decode(Bytes.reader(if type(data) == "string" then buffer.fromstring(data) else data), opts)
|
||||
end
|
||||
|
||||
local function maxDiff(a: buffer, b: buffer, n: number): number
|
||||
local worst = 0
|
||||
for i = 0, n * 4 - 1 do
|
||||
worst = math.max(worst, math.abs(buffer.readu8(a, i) - buffer.readu8(b, i)))
|
||||
end
|
||||
return worst
|
||||
end
|
||||
|
||||
local nsurf = 0
|
||||
for _, c in Fx.cases do
|
||||
if c.unsupported then
|
||||
local img, e = dec(c.data)
|
||||
t:check(img == nil and e and e.code == Err.UNSUPPORTED, c.name .. ": UNSUPPORTED (" .. tostring(e) .. ")")
|
||||
continue
|
||||
end
|
||||
local img, err = dec(c.data, { mips = true })
|
||||
t:check(img, c.name .. ": " .. tostring(err))
|
||||
if c.layout then
|
||||
t:eq(img.meta.layout, c.layout, c.name .. ": layout")
|
||||
end
|
||||
if c.mips then
|
||||
t:eq(img.meta.source.mips, c.mips, c.name .. ": mip count")
|
||||
end
|
||||
if c.srgb then
|
||||
t:eq(img.meta.colorSpace, "srgb", c.name .. ": sRGB")
|
||||
end
|
||||
local native = nil
|
||||
local frames = img.frames or { { image = img } }
|
||||
for _, s in c.surfaces do
|
||||
local label = string.format("%s: level %d layer %d slice %d", c.name, s.level, s.layer, s.slice)
|
||||
local im
|
||||
if s.level == 0 then
|
||||
local f = frames[s.layer + s.slice + 1]
|
||||
im = f and f.image
|
||||
else
|
||||
im = img.meta.mipmaps and img.meta.mipmaps[s.level]
|
||||
end
|
||||
t:check(im and im.width == s.w and im.height == s.h, label .. ": surface size")
|
||||
if s.rgba then
|
||||
local d = maxDiff(im.pixels, buffer.fromstring(s.rgba), s.w * s.h)
|
||||
t:check(d <= s.tol, string.format("%s: %d off the reference", label, d))
|
||||
end
|
||||
if s.floats and s.level == 0 and s.layer == 0 then
|
||||
native = native or dec(c.data, { native = true })
|
||||
local f = buffer.fromstring(s.floats)
|
||||
local worst = 0
|
||||
for i = 0, s.w * s.h * 4 - 1 do
|
||||
local want = buffer.readf32(f, i * 4)
|
||||
local got
|
||||
if native.format == "rgbaf32" then
|
||||
got = buffer.readf32(native.pixels, i * 4)
|
||||
elseif native.format == "rgba16" then
|
||||
got = buffer.readu16(native.pixels, i * 2) / 65535
|
||||
else
|
||||
got = buffer.readu8(native.pixels, i) / 255
|
||||
end
|
||||
if i % 4 ~= 3 or not string.find(c.name, "bc6h") then
|
||||
worst = math.max(worst, math.abs(got - want) / math.max(1, math.abs(want)))
|
||||
end
|
||||
end
|
||||
local tol = if native.format == "rgba8" then 1 / 255 elseif native.format == "rgba16" then 1 / 65535 else 1e-3
|
||||
t:check(worst <= tol + 1e-9, string.format("%s: native %s off by %g", label, native.format, worst))
|
||||
end
|
||||
nsurf += 1
|
||||
end
|
||||
end
|
||||
t:note("%d files, %d surfaces match", #Fx.cases, nsurf)
|
||||
|
||||
-- our files: ktx validate accepts them, ktx extract reads the first image
|
||||
local function source(w: number, h: number): buffer
|
||||
local px = buffer.create(w * h * 4)
|
||||
for y = 0, h - 1 do
|
||||
for x = 0, w - 1 do
|
||||
local o = (y * w + x) * 4
|
||||
buffer.writeu8(px, o, math.floor(x / (w - 1) * 255 + 0.5))
|
||||
buffer.writeu8(px, o + 1, math.floor(y / (h - 1) * 255 + 0.5))
|
||||
buffer.writeu8(px, o + 2, math.floor(((x * 7 + y * 13) % 64) / 63 * 255 + 0.5))
|
||||
buffer.writeu8(px, o + 3, math.floor(((x + y) % 5) / 4 * 255 + 0.5))
|
||||
end
|
||||
end
|
||||
return px
|
||||
end
|
||||
local src = source(37, 23)
|
||||
for _, o in Fx.ours do
|
||||
t:check(o.valid, o.name .. ": ktx validate: " .. tostring(o.report))
|
||||
local img, err = dec(o.data, { mips = true, native = true })
|
||||
t:check(img, o.name .. ": " .. tostring(err))
|
||||
if o.png and (string.find(o.name, "rgba8") or string.find(o.name, "srgb")) then
|
||||
t:eq(o.png, buffer.tostring(src), o.name .. ": ktx extract gives the source")
|
||||
end
|
||||
if string.find(o.name, "mips") or string.find(o.name, "zlib") then
|
||||
t:eq(#img.meta.mipmaps, 5, o.name .. ": mip chain")
|
||||
end
|
||||
if string.find(o.name, "cube") then
|
||||
t:eq(img.meta.layout, "cube", o.name .. ": cube")
|
||||
t:eq(#img.frames, 6, o.name .. ": faces")
|
||||
end
|
||||
end
|
||||
t:note("%d of our files pass ktx validate", #Fx.ours)
|
||||
|
||||
-- round trips
|
||||
do
|
||||
local img = Types.Image.new(37, 23)
|
||||
img.pixels = src
|
||||
for _, o in { {}, { mips = true }, { zlib = 9 }, { srgb = true } } do
|
||||
local back = dec(Ktx.encode(img, o :: any) :: buffer)
|
||||
t:eq(buffer.tostring(back.pixels), buffer.tostring(src), "rgba8 round trip")
|
||||
end
|
||||
local f = Types.Image.new(3, 2, "rgbaf32")
|
||||
for i = 0, 23 do
|
||||
buffer.writef32(f.pixels, i * 4, i * 0.37 - 2)
|
||||
end
|
||||
local back = dec(Ktx.encode(f) :: buffer, { native = true })
|
||||
t:eq(buffer.tostring(back.pixels), buffer.tostring(f.pixels), "rgba32f round trip")
|
||||
local _, e = Ktx.encode(f, { pixelFormat = "rgba8" })
|
||||
t:check(e and e.code == Err.ARG, "format mismatch")
|
||||
local _, e2 = Ktx.encode(img, { zlib = 12 })
|
||||
t:check(e2 and e2.code == Err.ARG, "zlib level")
|
||||
end
|
||||
|
||||
-- sniff, info, errors
|
||||
do
|
||||
local c = Fx.cases[1]
|
||||
t:eq(Ktx.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, "sniff KTX2")
|
||||
t:eq(Ktx.sniff(Bytes.reader(buffer.fromstring("\171KTX 11\187\r\n\26\n"))), 1, "sniff KTX1")
|
||||
t:eq(Ktx.sniff(Bytes.reader(buffer.fromstring("PNG"))), 0, "sniff other")
|
||||
local info = Ktx.info(Bytes.reader(buffer.fromstring(c.data)))
|
||||
t:check(info and info.version == 2 and info.vkFormat == 37, "info")
|
||||
local _, e = dec(string.sub(c.data, 1, 60))
|
||||
t:check(e and e.code == Err.TRUNCATED, "short header")
|
||||
local _, e2 = dec(string.sub(c.data, 1, #c.data - 100))
|
||||
t:check(e2 and e2.code == Err.TRUNCATED, "cut data: " .. tostring(e2))
|
||||
local _, e3 = dec(c.data, { maxPixels = 10 })
|
||||
t:check(e3 and e3.code == Err.LIMIT, "limit")
|
||||
end
|
||||
|
||||
local samples = {}
|
||||
for i, c in Fx.cases do
|
||||
if i % 2 == 0 or c.unsupported then
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return dec(b, { mips = true })
|
||||
end, samples, { mutations = 6 })
|
||||
t:done()
|
||||
@@ -0,0 +1,39 @@
|
||||
-- image/pcx tests: files from netpbm (24-bit, 8-bit, packed 2 / 4-bit, 3 / 4 planes, mono), ImageMagick and Pillow
|
||||
-- against pcxtoppm's decode; our files read by ImageMagick; round trips (palette, 24-bit, 32-bit alpha); errors; the
|
||||
-- fuzz no-throw pass. Fixtures: tools/fixtures/pcx.py.
|
||||
local T = require("@tests/T")
|
||||
local Pcx = require("@formats/image/pcx")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local R = require("@tests/image/_raster")
|
||||
local Fx = require("@tests/gen/pcx")
|
||||
|
||||
local t = T.suite("pcx")
|
||||
t:eq(Pcx.name, "pcx", "name")
|
||||
t:check(Pcx.caps.decode and Pcx.caps.encode, "caps")
|
||||
|
||||
t:note("%d files match pcxtoppm", R.decodes(t, Pcx, Fx.cases))
|
||||
-- our files: ImageMagick reads what we decode
|
||||
for _, o in Fx.ours do
|
||||
local img = Pcx.decode(Bytes.reader(buffer.fromstring(o.data))) :: any
|
||||
t:eq(R.maxDiff(img.pixels, buffer.fromstring(o.rgba), o.w * o.h), 0, o.name .. ": ImageMagick reads our file")
|
||||
end
|
||||
for _, c in Fx.cases do
|
||||
R.roundTrip(t, Pcx, R.image(c.w, c.h, c.rgba), nil, c.name .. " re-encoded")
|
||||
R.roundTrip(t, Pcx, R.image(c.w, c.h, c.rgba), { palette = false }, c.name .. " re-encoded 24-bit")
|
||||
end
|
||||
do
|
||||
local img = R.image(3, 2, string.rep("\1\2\3\128", 6))
|
||||
local enc = R.roundTrip(t, Pcx, img, nil, "alpha: 4 planes") :: buffer
|
||||
t:eq(buffer.readu8(enc, 65), 4, "alpha -> 4 planes")
|
||||
t:eq(Pcx.sniff(Bytes.reader(enc)), 0.8, "sniff")
|
||||
t:eq(Pcx.sniff(Bytes.reader(buffer.fromstring("GIF89a"))), 0, "sniff other")
|
||||
local _, e = Pcx.decode(Bytes.reader(buffer.fromstring(string.sub(buffer.tostring(enc), 1, 60))))
|
||||
t:check(e and e.code == Err.TRUNCATED, "short header")
|
||||
local _, e2 = Pcx.decode(Bytes.reader(enc), { maxPixels = 2 })
|
||||
t:check(e2 and e2.code == Err.LIMIT, "limit")
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Pcx.decode(Bytes.reader(b))
|
||||
end, R.samples(Fx.cases), { mutations = 6 })
|
||||
t:done()
|
||||
@@ -0,0 +1,34 @@
|
||||
-- image/sgi tests: files from netpbm / ImageMagick / Pillow against ImageMagick's decode, our encoder's files read
|
||||
-- by ImageMagick, round trips through every option, errors, the fuzz no-throw pass. Fixtures: tools/fixtures/sgi.py.
|
||||
local T = require("@tests/T")
|
||||
local Sgi = require("@formats/image/sgi")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local R = require("@tests/image/_raster")
|
||||
local Fx = require("@tests/gen/sgi")
|
||||
|
||||
local t = T.suite("sgi")
|
||||
t:eq(Sgi.name, "sgi", "name")
|
||||
t:check(Sgi.caps.decode and Sgi.caps.encode, "caps")
|
||||
|
||||
t:note("%d files match ImageMagick", R.decodes(t, Sgi, Fx.cases))
|
||||
t:note("%d of our files read by ImageMagick", R.decodes(t, Sgi, Fx.ours))
|
||||
for _, c in Fx.cases do
|
||||
R.roundTrip(t, Sgi, R.image(c.w, c.h, c.rgba), nil, c.name .. " re-encoded")
|
||||
R.roundTrip(t, Sgi, R.image(c.w, c.h, c.rgba), { rle = false }, c.name .. " re-encoded without RLE")
|
||||
end
|
||||
do
|
||||
local enc = Sgi.encode(R.image(2, 2, string.rep("\1\2\3\4", 4))) :: buffer
|
||||
t:eq(Sgi.sniff(Bytes.reader(enc)), 1, "sniff")
|
||||
t:eq(Sgi.sniff(Bytes.reader(buffer.fromstring("GIF89a"))), 0, "sniff other")
|
||||
local _, e = Sgi.decode(Bytes.reader(buffer.fromstring(string.sub(buffer.tostring(enc), 1, 20))))
|
||||
t:check(e and e.code == Err.TRUNCATED, "short header")
|
||||
local _, e2 = Sgi.decode(Bytes.reader(enc), { maxPixels = 2 })
|
||||
t:check(e2 and e2.code == Err.LIMIT, "limit")
|
||||
local _, e3 = Sgi.encode({} :: any)
|
||||
t:check(e3 and e3.code == Err.ARG, "bad image")
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Sgi.decode(Bytes.reader(b))
|
||||
end, R.samples(Fx.cases), { mutations = 6 })
|
||||
t:done()
|
||||
@@ -0,0 +1,42 @@
|
||||
-- image/sunras tests: files from netpbm / ImageMagick against ImageMagick's decode, our encoder's files read
|
||||
-- by rasttopnm, round trips through every option, errors, the fuzz no-throw pass. Fixtures: tools/fixtures/sunras.py.
|
||||
local T = require("@tests/T")
|
||||
local Sunras = require("@formats/image/sunras")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local R = require("@tests/image/_raster")
|
||||
local Fx = require("@tests/gen/sunras")
|
||||
|
||||
local t = T.suite("sunras")
|
||||
t:eq(Sunras.name, "sunras", "name")
|
||||
t:check(Sunras.caps.decode and Sunras.caps.encode, "caps")
|
||||
|
||||
t:note("%d files match rasttopnm / ImageMagick", R.decodes(t, Sunras, Fx.cases))
|
||||
-- our files: rasttopnm reads the colours (it drops alpha)
|
||||
for _, o in Fx.ours do
|
||||
local img = Sunras.decode(Bytes.reader(buffer.fromstring(o.data))) :: any
|
||||
local px = buffer.fromstring(buffer.tostring(img.pixels))
|
||||
for i = 0, o.w * o.h - 1 do
|
||||
buffer.writeu8(px, i * 4 + 3, 255)
|
||||
end
|
||||
t:eq(R.maxDiff(px, buffer.fromstring(o.rgba), o.w * o.h), 0, o.name .. ": rasttopnm reads our file")
|
||||
end
|
||||
for _, c in Fx.cases do
|
||||
R.roundTrip(t, Sunras, R.image(c.w, c.h, c.rgba), nil, c.name .. " re-encoded")
|
||||
R.roundTrip(t, Sunras, R.image(c.w, c.h, c.rgba), { rle = false }, c.name .. " re-encoded without RLE")
|
||||
end
|
||||
do
|
||||
local enc = Sunras.encode(R.image(2, 2, string.rep("\1\2\3\4", 4))) :: buffer
|
||||
t:eq(Sunras.sniff(Bytes.reader(enc)), 1, "sniff")
|
||||
t:eq(Sunras.sniff(Bytes.reader(buffer.fromstring("GIF89a"))), 0, "sniff other")
|
||||
local _, e = Sunras.decode(Bytes.reader(buffer.fromstring(string.sub(buffer.tostring(enc), 1, 20))))
|
||||
t:check(e and e.code == Err.TRUNCATED, "short header")
|
||||
local _, e2 = Sunras.decode(Bytes.reader(enc), { maxPixels = 2 })
|
||||
t:check(e2 and e2.code == Err.LIMIT, "limit")
|
||||
local _, e3 = Sunras.encode({} :: any)
|
||||
t:check(e3 and e3.code == Err.ARG, "bad image")
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Sunras.decode(Bytes.reader(b))
|
||||
end, R.samples(Fx.cases), { mutations = 6 })
|
||||
t:done()
|
||||
@@ -0,0 +1,43 @@
|
||||
-- image/xbm tests: files from netpbm / ImageMagick / Pillow and hand-written ones against the reference decode
|
||||
-- (xbmtopbm), our encoder's files read back by it, round trips, errors, the fuzz no-throw pass.
|
||||
-- Fixtures: tools/fixtures/xbm.py.
|
||||
local T = require("@tests/T")
|
||||
local Xbm = require("@formats/image/xbm")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local R = require("@tests/image/_raster")
|
||||
local Fx = require("@tests/gen/xbm")
|
||||
|
||||
local t = T.suite("xbm")
|
||||
t:eq(Xbm.name, "xbm", "name")
|
||||
t:check(Xbm.caps.decode and Xbm.caps.encode, "caps")
|
||||
|
||||
t:note("%d files match the reference", R.decodes(t, Xbm, Fx.cases))
|
||||
t:note("%d of our files read back by it", R.decodes(t, Xbm, Fx.ours))
|
||||
for _, c in Fx.cases do
|
||||
R.roundTrip(t, Xbm, R.image(c.w, c.h, c.rgba), nil, c.name .. " re-encoded")
|
||||
if c.hotspot then
|
||||
local img = Xbm.decode(Bytes.reader(buffer.fromstring(c.data))) :: any
|
||||
t:check(img.meta.hotspot and img.meta.hotspot.x == c.hotspot[1] and img.meta.hotspot.y == c.hotspot[2], c.name .. ": hotspot")
|
||||
end
|
||||
end
|
||||
do
|
||||
-- decimal and octal values, the X10 short arrays
|
||||
local img = Xbm.decode(Bytes.reader(buffer.fromstring("#define a_width 9\n#define a_height 1\nstatic char a_bits[] = { 1, 0400 };"))) :: any
|
||||
t:eq(buffer.readu32(img.pixels, 0), 0xFF000000, "decimal: pixel 0 black")
|
||||
t:eq(buffer.readu32(img.pixels, 4), 0xFFFFFFFF, "decimal: pixel 1 white")
|
||||
local x10 = Xbm.decode(Bytes.reader(buffer.fromstring("#define b_width 17\n#define b_height 1\nstatic short b_bits[] = { 0x8001, 0x0001 };"))) :: any
|
||||
t:eq(buffer.readu32(x10.pixels, 15 * 4), 0xFF000000, "x10: bit 15")
|
||||
t:eq(buffer.readu32(x10.pixels, 16 * 4), 0xFF000000, "x10: second short")
|
||||
local tr = Xbm.decode(Bytes.reader(buffer.fromstring("#define c_width 2\n#define c_height 1\nstatic char c_bits[] = { 0x01 };")), { transparent = true }) :: any
|
||||
t:eq(buffer.readu32(tr.pixels, 4), 0x00FFFFFF, "transparent clear bits")
|
||||
t:eq(Xbm.sniff(Bytes.reader(buffer.fromstring("#define c_width 2\n"))), 0.9, "sniff")
|
||||
local _, e = Xbm.decode(Bytes.reader(buffer.fromstring("static char x[] = {};")))
|
||||
t:check(e and e.code == Err.CORRUPT, "no defines")
|
||||
local named = Xbm.encode(R.image(1, 1, "\0\0\0\255"), { name = "1 bad.xbm" }) :: buffer
|
||||
t:check(string.find(buffer.tostring(named), "#define _1_bad_width 1", 1, true) ~= nil, "name made an identifier")
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Xbm.decode(Bytes.reader(b))
|
||||
end, R.samples(Fx.cases), { mutations = 6 })
|
||||
t:done()
|
||||
@@ -0,0 +1,44 @@
|
||||
-- image/xpm tests: files from netpbm / ImageMagick and hand-written ones against the reference decode
|
||||
-- (ImageMagick), our encoder's files read back by it, round trips, errors, the fuzz no-throw pass.
|
||||
-- Fixtures: tools/fixtures/xpm.py.
|
||||
local T = require("@tests/T")
|
||||
local Xpm = require("@formats/image/xpm")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local R = require("@tests/image/_raster")
|
||||
local Fx = require("@tests/gen/xpm")
|
||||
|
||||
local t = T.suite("xpm")
|
||||
t:eq(Xpm.name, "xpm", "name")
|
||||
t:check(Xpm.caps.decode and Xpm.caps.encode, "caps")
|
||||
|
||||
t:note("%d files match the reference", R.decodes(t, Xpm, Fx.cases))
|
||||
t:note("%d of our files read back by it", R.decodes(t, Xpm, Fx.ours))
|
||||
for _, c in Fx.cases do
|
||||
R.roundTrip(t, Xpm, R.image(c.w, c.h, c.rgba), nil, c.name .. " re-encoded")
|
||||
if c.hotspot then
|
||||
local img = Xpm.decode(Bytes.reader(buffer.fromstring(c.data))) :: any
|
||||
t:check(img.meta.hotspot and img.meta.hotspot.x == c.hotspot[1] and img.meta.hotspot.y == c.hotspot[2], c.name .. ": hotspot")
|
||||
end
|
||||
end
|
||||
do
|
||||
local img = Xpm.decode(Bytes.reader(buffer.fromstring('/* XPM */\nstatic char *x[] = {"2 1 2 1 0 0", "a c gray50", "b c Unknownish", "ab"};'))) :: any
|
||||
t:eq(buffer.readu32(img.pixels, 0), 0xFF7F7F7F, "gray50")
|
||||
t:check(img.meta.unknownColours and img.meta.unknownColours[1] == "Unknownish", "unknown colour listed")
|
||||
t:check(img.meta.hotspot and img.meta.hotspot.x == 0, "hotspot")
|
||||
t:eq(Xpm.sniff(Bytes.reader(buffer.fromstring("/* XPM */\n"))), 1, "sniff")
|
||||
local _, e = Xpm.decode(Bytes.reader(buffer.fromstring('/* XPM */ static char *x[] = {"2 1 5 1", "a c red"};')))
|
||||
t:check(e and e.code == Err.TRUNCATED, "short colour table")
|
||||
-- many colours: two chars per pixel
|
||||
local big = R.image(300, 1, "")
|
||||
big.pixels = buffer.create(1200)
|
||||
for i = 0, 299 do
|
||||
buffer.writeu32(big.pixels, i * 4, i * 997 + 0xFF000000)
|
||||
end
|
||||
local enc = R.roundTrip(t, Xpm, big, nil, "300 colours") :: buffer
|
||||
t:check(string.find(buffer.tostring(enc), '"300 1 300 2"', 1, true) ~= nil, "two chars per pixel")
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Xpm.decode(Bytes.reader(b))
|
||||
end, R.samples(Fx.cases), { mutations = 6 })
|
||||
t:done()
|
||||
@@ -0,0 +1,124 @@
|
||||
-- layered/ora tests: OpenRaster files assembled by the spec (offsets, opacity, hidden, composite-ops, nested isolate /
|
||||
-- auto stacks, no merged image) against the attributes and pixels written there; our encoder's file taken apart by
|
||||
-- python (stored mimetype first, stack.xml, Pillow's read of every PNG); round trips; hooks; errors; the fuzz no-throw
|
||||
-- pass. Fixtures: tools/fixtures/ora.py.
|
||||
local T = require("@tests/T")
|
||||
local Ora = require("@formats/layered/ora")
|
||||
local Png = require("@formats/image/png")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Fx = require("@tests/gen/ora")
|
||||
|
||||
local t = T.suite("ora")
|
||||
t:eq(Ora.name, "ora", "name")
|
||||
t:eq(Ora.category, "layered", "category")
|
||||
t:check(Ora.caps.decode and Ora.caps.encode, "caps")
|
||||
|
||||
local hooks = {
|
||||
decodeImage = function(b: buffer): (any, any)
|
||||
return Png.decode(Bytes.reader(b))
|
||||
end,
|
||||
encodeImage = function(img: any, _f: string): (any, any)
|
||||
return Png.encode(img)
|
||||
end,
|
||||
}
|
||||
|
||||
-- the tree depth-first, bottom to top, groups before their children
|
||||
local function walk(layers: { any }, depth: number, out: { any })
|
||||
for _, l in layers do
|
||||
table.insert(out, { layer = l, depth = depth })
|
||||
if l.children then
|
||||
walk(l.children, depth + 1, out)
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local function compare(label: string, doc: any, want: { any })
|
||||
local got = walk(doc.layers, 0, {})
|
||||
t:eq(#got, #want, label .. ": layer count")
|
||||
for i, w in want do
|
||||
local g = got[i]
|
||||
if not g then
|
||||
break
|
||||
end
|
||||
local l = g.layer
|
||||
local ll = label .. ": " .. w.name
|
||||
t:eq(l.name, w.name, ll .. " name")
|
||||
t:eq(g.depth, w.depth, ll .. " depth")
|
||||
t:check(math.abs(l.opacity - w.opacity) < 1e-6, ll .. " opacity")
|
||||
t:eq(l.visible, w.visible, ll .. " visibility")
|
||||
t:eq(l.blend, w.blend, ll .. " blend")
|
||||
if not w.group then
|
||||
t:check(l.x == w.x and l.y == w.y, ll .. " position")
|
||||
t:check(l.image.width == w.w and l.image.height == w.h and buffer.tostring(l.image.pixels) == w.rgba, ll .. " pixels")
|
||||
else
|
||||
t:check(l.children ~= nil, ll .. " is a group")
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
for _, c in Fx.cases do
|
||||
local doc, err = Ora.decode(Bytes.reader(buffer.fromstring(c.data)), hooks)
|
||||
t:check(doc, c.name .. ": " .. tostring(err))
|
||||
t:check(doc.kind == "layered" and doc.width == c.w and doc.height == c.h, c.name .. ": size")
|
||||
compare(c.name, doc, c.layers)
|
||||
t:eq(doc.meta.composite ~= nil, c.merged, c.name .. ": merged image")
|
||||
if c.dpi then
|
||||
t:eq(doc.meta.dpi.x, c.dpi, c.name .. ": dpi")
|
||||
end
|
||||
-- round trip
|
||||
local enc, eerr = Ora.encode(doc, hooks)
|
||||
t:check(enc, c.name .. ": encode " .. tostring(eerr))
|
||||
local back = Ora.decode(Bytes.reader(enc :: buffer), hooks)
|
||||
compare(c.name .. " round trip", back, c.layers)
|
||||
t:eq(Ora.sniff(Bytes.reader(enc :: buffer)), 1, c.name .. ": sniff our file")
|
||||
end
|
||||
|
||||
-- our encoder's file, as python and Pillow read it
|
||||
do
|
||||
local o = Fx.ours
|
||||
t:check(o.ok, "ours: mimetype first, stored")
|
||||
t:eq(o.entries[1], "mimetype", "ours: first entry")
|
||||
t:check(table.find(o.entries, "mergedimage.png") ~= nil and table.find(o.entries, "Thumbnails/thumbnail.png") ~= nil, "ours: merged image and thumbnail")
|
||||
t:check(o.thumb[1] == 40 and o.thumb[2] == 30, "ours: thumbnail size")
|
||||
local doc = Ora.decode(Bytes.reader(buffer.fromstring(o.data)), hooks) :: any
|
||||
t:check(doc and doc.width == o.w and doc.height == o.h, "ours: decodes")
|
||||
-- python's walk is top first (xml order): compare by name
|
||||
local byName = {}
|
||||
for _, g in walk(doc.layers, 0, {}) do
|
||||
byName[g.layer.name] = g
|
||||
end
|
||||
for _, l in o.layers do
|
||||
local g = byName[l.name]
|
||||
t:check(g, "ours: layer " .. l.name)
|
||||
if g then
|
||||
t:check(math.abs(g.layer.opacity - l.opacity) < 1e-6 and g.layer.visible == l.visible and g.depth == l.depth, "ours: " .. l.name .. " attributes")
|
||||
if l.tag == "layer" then
|
||||
t:check(g.layer.x == l.x and g.layer.y == l.y, "ours: " .. l.name .. " position")
|
||||
t:eq(buffer.tostring(g.layer.image.pixels), l.rgba, "ours: " .. l.name .. " pixels through Pillow")
|
||||
end
|
||||
end
|
||||
end
|
||||
t:eq(buffer.tostring(doc.meta.composite.pixels), o.merged.rgba, "ours: merged image through Pillow")
|
||||
end
|
||||
|
||||
do
|
||||
local c = Fx.cases[1]
|
||||
local _, e = Ora.decode(Bytes.reader(buffer.fromstring(c.data)))
|
||||
t:check(e and e.code == Err.UNSUPPORTED, "no decodeImage hook")
|
||||
local doc = Ora.decode(Bytes.reader(buffer.fromstring(c.data)), hooks) :: any
|
||||
local _, e2 = Ora.encode(doc)
|
||||
t:check(e2 and e2.code == Err.UNSUPPORTED, "no encodeImage hook")
|
||||
local _, e3 = Ora.encode({} :: any, hooks)
|
||||
t:check(e3 and e3.code == Err.ARG, "not a document")
|
||||
t:eq(Ora.sniff(Bytes.reader(buffer.fromstring("PK\3\4"))), 0, "sniff a plain zip")
|
||||
end
|
||||
local samples = {}
|
||||
for _, c in Fx.cases do
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Ora.decode(Bytes.reader(b), hooks)
|
||||
end, samples, { mutations = 12 })
|
||||
t:done()
|
||||
@@ -1392,3 +1392,149 @@ do
|
||||
local dt = os.clock() - t0
|
||||
print(string.format("%-8s %-30s %8.2f ms %7.1fx real time", runtime, "smacker audio 22 kHz stereo", dt * 1000, n / a.sampleRate / dt))
|
||||
end
|
||||
do
|
||||
-- 3D (ws-3d): a 400 x 400 grid mesh (160k vertices, 318k triangles) through our own writers, then the readers; a
|
||||
-- 128^3 noise voxel grid through VOX and greedy meshing
|
||||
local Types = require("@formats/Types")
|
||||
local MeshOps = require("@formats/ops/MeshOps")
|
||||
local Gltf = require("@formats/model/gltf")
|
||||
local Obj = require("@formats/model/obj")
|
||||
local Stl = require("@formats/model/stl")
|
||||
local Ply = require("@formats/model/ply")
|
||||
local Vox = require("@formats/model/vox")
|
||||
local N = 400
|
||||
local pos = Types.Scene.accessor(nil, "f32", 3, N * N)
|
||||
local uv = Types.Scene.accessor(nil, "f32", 2, N * N)
|
||||
for y = 0, N - 1 do
|
||||
for x = 0, N - 1 do
|
||||
local i = y * N + x
|
||||
buffer.writef32(pos.data, i * 12, x / N)
|
||||
buffer.writef32(pos.data, i * 12 + 4, math.sin(x * 0.1) * math.cos(y * 0.1) * 0.05)
|
||||
buffer.writef32(pos.data, i * 12 + 8, y / N)
|
||||
buffer.writef32(uv.data, i * 8, x / N)
|
||||
buffer.writef32(uv.data, i * 8 + 4, y / N)
|
||||
end
|
||||
end
|
||||
local ind = Types.Scene.accessor(nil, "u32", 1, (N - 1) * (N - 1) * 6)
|
||||
local k = 0
|
||||
for y = 0, N - 2 do
|
||||
for x = 0, N - 2 do
|
||||
local a = y * N + x
|
||||
for _, v in { a, a + N, a + 1, a + 1, a + N, a + N + 1 } do
|
||||
buffer.writeu32(ind.data, k * 4, v)
|
||||
k += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
local prim = { attributes = { POSITION = pos, TEXCOORD_0 = uv }, indices = ind, mode = "triangles" } :: any
|
||||
MeshOps.computeNormals(prim)
|
||||
local scene = Types.Scene.fromPrimitive(prim, "grid")
|
||||
bench("meshops computeNormals 318k tris", 3, buffer.len(pos.data), function()
|
||||
MeshOps.computeNormals(prim)
|
||||
end)
|
||||
local glb = assert(Gltf.encode(scene, { binary = true }))
|
||||
bench("gltf glb decode (" .. buffer.len(glb) // 1000 .. " KB)", 5, buffer.len(glb), function()
|
||||
Gltf.decode(Bytes.reader(glb))
|
||||
end)
|
||||
bench("gltf glb encode", 3, buffer.len(glb), function()
|
||||
Gltf.encode(scene, { binary = true })
|
||||
end)
|
||||
local obj = assert(Obj.encode(scene))
|
||||
bench("obj decode (" .. buffer.len(obj) // 1000 .. " KB)", 2, buffer.len(obj), function()
|
||||
Obj.decode(Bytes.reader(obj))
|
||||
end)
|
||||
bench("obj encode", 2, buffer.len(obj), function()
|
||||
Obj.encode(scene)
|
||||
end)
|
||||
local stl = assert(Stl.encode(scene))
|
||||
bench("stl binary decode (" .. buffer.len(stl) // 1000 .. " KB)", 5, buffer.len(stl), function()
|
||||
Stl.decode(Bytes.reader(stl))
|
||||
end)
|
||||
local ply = assert(Ply.encode(scene))
|
||||
bench("ply binary decode (" .. buffer.len(ply) // 1000 .. " KB)", 5, buffer.len(ply), function()
|
||||
Ply.decode(Bytes.reader(ply))
|
||||
end)
|
||||
local Fbx = require("@formats/model/fbx")
|
||||
local fbx = assert(Fbx.encode(scene))
|
||||
bench("fbx binary decode (" .. buffer.len(fbx) // 1000 .. " KB)", 3, buffer.len(fbx), function()
|
||||
Fbx.decode(Bytes.reader(fbx))
|
||||
end)
|
||||
bench("fbx binary encode (zlib arrays)", 2, buffer.len(fbx), function()
|
||||
Fbx.encode(scene)
|
||||
end)
|
||||
bench("fbx binary encode (raw arrays)", 3, buffer.len(fbx), function()
|
||||
Fbx.encode(scene, { compress = false })
|
||||
end)
|
||||
local fbxa = assert(Fbx.encode(scene, { ascii = true }))
|
||||
bench("fbx ascii decode (" .. buffer.len(fbxa) // 1000 .. " KB)", 2, buffer.len(fbxa), function()
|
||||
Fbx.decode(Bytes.reader(fbxa))
|
||||
end)
|
||||
local ThreeMf = require("@formats/model/3mf")
|
||||
local tmf = assert(ThreeMf.encode(scene))
|
||||
bench("3mf decode (" .. buffer.len(tmf) // 1000 .. " KB zipped)", 2, buffer.len(tmf), function()
|
||||
ThreeMf.decode(Bytes.reader(tmf))
|
||||
end)
|
||||
bench("3mf encode", 2, buffer.len(tmf), function()
|
||||
ThreeMf.encode(scene)
|
||||
end)
|
||||
local V = 128
|
||||
local grid = Types.Voxels.new(V, V, V)
|
||||
for z = 0, V - 1 do
|
||||
for y = 0, V - 1 do
|
||||
for x = 0, V - 1 do
|
||||
local h = (math.sin(x * 0.11) + math.cos(y * 0.07) + 2) * V / 8 + z * 0
|
||||
if z < h then
|
||||
Types.Voxels.set(grid, x, y, z, 1 + (x // 8 + y // 8) % 6)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
local vox = assert(Vox.encode(grid))
|
||||
bench("vox decode (" .. buffer.len(vox) // 1000 .. " KB)", 5, buffer.len(vox), function()
|
||||
Vox.decode(Bytes.reader(vox))
|
||||
end)
|
||||
bench("greedy mesh 128^3 (MB of cells)", 3, V * V * V, function()
|
||||
MeshOps.voxelsToPrimitive(grid)
|
||||
end)
|
||||
end
|
||||
do
|
||||
-- textures (ws-tex): codecs/image/Bcn on a 256 x 256 image (tools/fixtures/bcn.py); MB/s of rgba8 output (decode)
|
||||
-- or input (encode); BC6H of rgbaf32 output
|
||||
local Bcn = require("@formats/codecs/image/Bcn")
|
||||
local BB = require("@tests/gen/bcn_bench")
|
||||
local w, h = BB.w, BB.h
|
||||
local px = buffer.fromstring(BB.rgba)
|
||||
for _, kind in { "bc1", "bc3", "bc5" } do
|
||||
local blocks = Bcn.encode(kind, px, w, h) :: buffer
|
||||
bench("bcn decode " .. kind .. " 256x256", 5, w * h * 4, function()
|
||||
Bcn.decode(kind, blocks, 0, w, h)
|
||||
end)
|
||||
bench("bcn encode " .. kind .. " 256x256", 2, w * h * 4, function()
|
||||
Bcn.encode(kind, px, w, h)
|
||||
end)
|
||||
end
|
||||
local b7, b6 = buffer.fromstring(BB.bc7), buffer.fromstring(BB.bc6h)
|
||||
bench("bcn decode bc7 256x256", 5, w * h * 4, function()
|
||||
Bcn.decode("bc7", b7, 0, w, h)
|
||||
end)
|
||||
bench("bcn decode bc6h 256x256", 5, w * h * 16, function()
|
||||
Bcn.decode("bc6h", b6, 0, w, h)
|
||||
end)
|
||||
end
|
||||
do
|
||||
-- OpenEXR (ws-tex): a 512 x 256 half RGBA image from the OpenEXR bindings (tools/fixtures/exr.py), ZIP and PIZ;
|
||||
-- MB/s of rgbaf32 output; our ZIP encoder on the decoded floats
|
||||
local Exr = require("@formats/image/exr")
|
||||
local EB = require("@tests/gen/exr_bench")
|
||||
local n = 512 * 256 * 16
|
||||
for _, k in { "zip", "piz" } do
|
||||
local data = buffer.fromstring(EB[k])
|
||||
bench("exr decode " .. k .. " 512x256 half", 3, n, function()
|
||||
Exr.decode(Bytes.reader(data), { native = true })
|
||||
end)
|
||||
end
|
||||
local img = Exr.decode(Bytes.reader(buffer.fromstring(EB.zip)), { native = true }) :: any
|
||||
bench("exr encode zip 512x256 half", 2, n, function()
|
||||
Exr.encode(img)
|
||||
end)
|
||||
end
|
||||
@@ -0,0 +1,122 @@
|
||||
# Shared by the simple raster fixture generators (pcx, sgi, sunras, xbm, xpm, ilbm, icns, ani): source images, a PNG
|
||||
# writer, netpbm / ImageMagick runs in one temp dir, and a PNM / PAM reader for their output.
|
||||
# work = Work(ctx) a temp dir; work.png(name, w, h, rgba); work.sh("netpbm", ["cmd", ...]); work.read(n)
|
||||
# pnm_rgba(data) -> (w, h, rgba) for P1..P7 (PBM 1 = black; PAM GRAYSCALE[_ALPHA] / RGB[_ALPHA])
|
||||
import os, random, shutil, struct, subprocess, tempfile, zlib
|
||||
|
||||
|
||||
def png(w, h, rgba):
|
||||
raw = b"".join(b"\0" + rgba[y * w * 4:(y + 1) * w * 4] for y in range(h))
|
||||
def chunk(t, d):
|
||||
return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d))
|
||||
return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0)) +
|
||||
chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b""))
|
||||
|
||||
|
||||
def photo(w, h, seed=1, alpha=False):
|
||||
rng = random.Random(seed)
|
||||
out = bytearray()
|
||||
for y in range(h):
|
||||
for x in range(w):
|
||||
r = (x * 255) // max(1, w - 1)
|
||||
g = (y * 255) // max(1, h - 1)
|
||||
b = ((x * 7 + y * 3) * 4 + rng.randrange(8)) % 256
|
||||
a = 255 if not alpha else ((x * 37 + y * 11) % 256)
|
||||
out += bytes((r, g, b, a))
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def palette_image(w, h, ncolours, seed=2):
|
||||
rng = random.Random(seed)
|
||||
cols = [(rng.randrange(256), rng.randrange(256), rng.randrange(256)) for _ in range(ncolours)]
|
||||
out = bytearray()
|
||||
for y in range(h):
|
||||
for x in range(w):
|
||||
out += bytes(cols[(x // 3 + y // 2 + (x * y) % 3) % ncolours]) + b"\xff"
|
||||
return bytes(out)
|
||||
|
||||
|
||||
class Work:
|
||||
def __init__(self, ctx):
|
||||
self.ctx = ctx
|
||||
self.dir = tempfile.mkdtemp(prefix="formats-raster-")
|
||||
|
||||
def close(self):
|
||||
shutil.rmtree(self.dir, ignore_errors=True)
|
||||
|
||||
def path(self, n):
|
||||
return os.path.join(self.dir, n)
|
||||
|
||||
def write(self, n, data):
|
||||
with open(self.path(n), "wb") as f:
|
||||
f.write(data)
|
||||
|
||||
def read(self, n):
|
||||
with open(self.path(n), "rb") as f:
|
||||
return f.read()
|
||||
|
||||
def png(self, n, w, h, rgba):
|
||||
self.write(n, png(w, h, rgba))
|
||||
|
||||
def sh(self, pkg, cmds):
|
||||
script = " && ".join(cmds)
|
||||
res = subprocess.run(["nix", "shell", "nixpkgs#" + pkg, "-c", "sh", "-c", "cd %s && %s" % (self.dir, script)], capture_output=True)
|
||||
if res.returncode:
|
||||
raise RuntimeError("%s failed: %s" % (pkg, res.stderr.decode()[-1500:]))
|
||||
return res.stdout
|
||||
|
||||
|
||||
def _tokens(data, n, pos):
|
||||
out = []
|
||||
while len(out) < n:
|
||||
while data[pos:pos + 1].isspace():
|
||||
pos += 1
|
||||
if data[pos:pos + 1] == b"#":
|
||||
while data[pos:pos + 1] not in (b"\n", b""):
|
||||
pos += 1
|
||||
continue
|
||||
s = pos
|
||||
while not data[pos:pos + 1].isspace():
|
||||
pos += 1
|
||||
out.append(int(data[s:pos]))
|
||||
return out, pos + 1
|
||||
|
||||
|
||||
def pnm_rgba(data):
|
||||
kind = data[:2]
|
||||
if kind == b"P7":
|
||||
end = data.index(b"ENDHDR\n") + 7
|
||||
hdr = dict(l.split(None, 1) for l in data[3:end - 7].decode().strip().split("\n") if l and not l.startswith("#"))
|
||||
w, h, d, mx = int(hdr["WIDTH"]), int(hdr["HEIGHT"]), int(hdr["DEPTH"]), int(hdr["MAXVAL"])
|
||||
raw, pos = data[end:], 0
|
||||
elif kind in (b"P4",):
|
||||
(w, h), pos = _tokens(data, 2, 2)
|
||||
bits = data[pos:]
|
||||
stride = (w + 7) // 8
|
||||
out = bytearray()
|
||||
for y in range(h):
|
||||
for x in range(w):
|
||||
v = 0 if (bits[y * stride + x // 8] >> (7 - x % 8)) & 1 else 255
|
||||
out += bytes((v, v, v, 255))
|
||||
return w, h, bytes(out)
|
||||
else:
|
||||
(w, h, mx), pos = _tokens(data, 3, 2)
|
||||
d = 1 if kind == b"P5" else 3
|
||||
raw = data[pos:]
|
||||
bps = 2 if mx > 255 else 1
|
||||
out = bytearray()
|
||||
for i in range(w * h):
|
||||
vals = []
|
||||
for k in range(d):
|
||||
o = (i * d + k) * bps
|
||||
v = raw[o] if bps == 1 else (raw[o] << 8 | raw[o + 1])
|
||||
vals.append((v * 255 + mx // 2) // mx)
|
||||
if d == 1:
|
||||
out += bytes((vals[0],) * 3 + (255,))
|
||||
elif d == 2:
|
||||
out += bytes((vals[0],) * 3 + (vals[1],))
|
||||
elif d == 3:
|
||||
out += bytes(vals) + b"\xff"
|
||||
else:
|
||||
out += bytes(vals)
|
||||
return w, h, bytes(out)
|
||||
@@ -0,0 +1,22 @@
|
||||
# Shared by the simple raster fixture generators: run our encoder (tools/fixtures/_tex_encode.luau -a <fmt>) and
|
||||
# decode files with ImageMagick into rgba8 (through PAM).
|
||||
import os, shutil, subprocess
|
||||
|
||||
|
||||
def ours(ctx, which):
|
||||
exe = shutil.which("luau")
|
||||
cmd = [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]
|
||||
res = subprocess.run(cmd + ["tools/fixtures/_tex_encode.luau", "-a", which], cwd=ctx.root, capture_output=True, check=True)
|
||||
files = {}
|
||||
for line in res.stdout.decode().split("\n"):
|
||||
if line.startswith("ours_") and "\t" in line:
|
||||
n, hx = line.split("\t", 1)
|
||||
files[n] = bytes.fromhex(hx.strip())
|
||||
return files
|
||||
|
||||
|
||||
def magick_cases(R, w, names, fmt=None):
|
||||
"""ImageMagick decodes of the named files in the work dir -> { name: (w, h, rgba) }"""
|
||||
pre = (fmt + ":") if fmt else ""
|
||||
w.sh("imagemagick", ["magick %s%s -depth 8 -alpha on pam:%s.pam" % (pre, n, n) for n in names])
|
||||
return {n: R.pnm_rgba(w.read(n + ".pam")) for n in names}
|
||||
@@ -0,0 +1,193 @@
|
||||
-- tools/fixtures/_tex_encode.luau: our texture encoders' output for the reference tools to read (run by
|
||||
-- tools/fixtures/{dds,ktx,exr}.py as `luau tools/fixtures/_tex_encode.luau -a <format>`). Prints "name\thex" lines.
|
||||
-- The source images are generated here (tools/fixtures/_tex_reference.py makes the same ones: source()).
|
||||
local Types = require("@formats/Types")
|
||||
|
||||
local which = ({ ... } :: { string })[1] or "dds"
|
||||
|
||||
local function hex(b: buffer): string
|
||||
local t = table.create(buffer.len(b))
|
||||
for i = 0, buffer.len(b) - 1 do
|
||||
t[i + 1] = string.format("%02x", buffer.readu8(b, i))
|
||||
end
|
||||
return table.concat(t)
|
||||
end
|
||||
|
||||
-- the test pattern (x, y, channel) -> 0..1, the same formula as _tex_reference.source()
|
||||
local function value(x: number, y: number, c: number, w: number, h: number, salt: number): number
|
||||
if c == 0 then
|
||||
return x / math.max(1, w - 1)
|
||||
elseif c == 1 then
|
||||
return y / math.max(1, h - 1)
|
||||
elseif c == 2 then
|
||||
return ((x * 7 + y * 13 + salt * 31) % 64) / 63
|
||||
end
|
||||
return ((x + y + salt) % 5) / 4
|
||||
end
|
||||
|
||||
local function image(w: number, h: number, fmt: string, salt: number, scale: number?): Types.Image
|
||||
local img = Types.Image.new(w, h, fmt :: any)
|
||||
for y = 0, h - 1 do
|
||||
for x = 0, w - 1 do
|
||||
for c = 0, 3 do
|
||||
local v = value(x, y, c, w, h, salt)
|
||||
local o = (y * w + x) * 4 + c
|
||||
if fmt == "rgba8" then
|
||||
buffer.writeu8(img.pixels, o, math.floor(v * 255 + 0.5))
|
||||
elseif fmt == "rgba16" then
|
||||
buffer.writeu16(img.pixels, o * 2, math.floor(v * 65535 + 0.5))
|
||||
else
|
||||
buffer.writef32(img.pixels, o * 4, if c < 3 then v * (scale or 1) else v)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return img
|
||||
end
|
||||
|
||||
local function emit(name: string, b: buffer?, err: any?)
|
||||
if not b then
|
||||
error(name .. ": " .. tostring(err))
|
||||
end
|
||||
print(name .. "\t" .. hex(b))
|
||||
end
|
||||
|
||||
if which == "dds" then
|
||||
local Dds = require("@formats/image/dds")
|
||||
local img = image(37, 23, "rgba8", 0)
|
||||
for _, f in { "rgba8", "bgra8", "bc1", "bc3", "bc4", "bc5" } do
|
||||
emit("ours_" .. f .. ".dds", Dds.encode(img, { pixelFormat = f :: any }))
|
||||
emit("ours_" .. f .. "_mips.dds", Dds.encode(img, { pixelFormat = f :: any, mips = true }))
|
||||
end
|
||||
emit("ours_rgba8_dx10.dds", Dds.encode(img, { dx10 = true, mips = true }))
|
||||
emit("ours_rgba16.dds", Dds.encode(image(37, 23, "rgba16", 0), { mips = true }))
|
||||
emit("ours_rgba32f.dds", Dds.encode(image(37, 23, "rgbaf32", 0, 4), { mips = true }))
|
||||
emit("ours_rgba16f.dds", Dds.encode(image(37, 23, "rgbaf32", 0, 4), { pixelFormat = "rgba16f" }))
|
||||
local cube = image(16, 16, "rgba8", 0)
|
||||
cube.frames = {}
|
||||
for i = 1, 6 do
|
||||
cube.frames[i] = { image = image(16, 16, "rgba8", i), delay = 0, x = 0, y = 0, dispose = "none", blend = "source" }
|
||||
end
|
||||
cube.meta.layout = "cube"
|
||||
emit("ours_cube.dds", Dds.encode(cube, { mips = true }))
|
||||
cube.meta.layout = "array"
|
||||
emit("ours_array_bc1.dds", Dds.encode(cube, { pixelFormat = "bc1" }))
|
||||
end
|
||||
|
||||
if which == "ktx" then
|
||||
local Ktx = require("@formats/image/ktx")
|
||||
local img = image(37, 23, "rgba8", 0)
|
||||
emit("ours_rgba8.ktx2", Ktx.encode(img))
|
||||
emit("ours_rgba8_mips.ktx2", Ktx.encode(img, { mips = true }))
|
||||
emit("ours_srgb_zlib.ktx2", Ktx.encode(img, { mips = true, srgb = true, zlib = 6 }))
|
||||
emit("ours_rgba16.ktx2", Ktx.encode(image(37, 23, "rgba16", 0), { mips = true }))
|
||||
emit("ours_rgba32f.ktx2", Ktx.encode(image(37, 23, "rgbaf32", 0, 4), { mips = true }))
|
||||
emit("ours_rgba16f.ktx2", Ktx.encode(image(37, 23, "rgbaf32", 0, 4), { pixelFormat = "rgba16f" }))
|
||||
local cube = image(16, 16, "rgba8", 0)
|
||||
cube.frames = {}
|
||||
for i = 1, 6 do
|
||||
cube.frames[i] = { image = image(16, 16, "rgba8", i), delay = 0, x = 0, y = 0, dispose = "none", blend = "source" }
|
||||
end
|
||||
cube.meta.layout = "cube"
|
||||
emit("ours_cube.ktx2", Ktx.encode(cube, { mips = true }))
|
||||
cube.meta.layout = "array"
|
||||
emit("ours_array.ktx2", Ktx.encode(cube))
|
||||
end
|
||||
|
||||
if which == "exr" then
|
||||
local Exr = require("@formats/image/exr")
|
||||
local f = image(37, 23, "rgbaf32", 0, 4)
|
||||
for _, c in { "none", "zips", "zip" } do
|
||||
emit("ours_half_" .. c .. ".exr", Exr.encode(f, { compression = c :: any }))
|
||||
emit("ours_float_" .. c .. ".exr", Exr.encode(f, { compression = c :: any, pixelType = "float" }))
|
||||
end
|
||||
local opaque = image(20, 40, "rgbaf32", 1, 2)
|
||||
for i = 0, 20 * 40 - 1 do
|
||||
buffer.writef32(opaque.pixels, i * 16 + 12, 1)
|
||||
end
|
||||
emit("ours_rgb_zip.exr", Exr.encode(opaque))
|
||||
emit("ours_from_rgba8.exr", Exr.encode(image(16, 16, "rgba8", 2)))
|
||||
end
|
||||
|
||||
-- the simple raster writers: a 37 x 23 photo-like image (opaque and with alpha) and a 12-colour one
|
||||
local function photo(alpha: boolean): Types.Image
|
||||
local img = image(37, 23, "rgba8", 0)
|
||||
if not alpha then
|
||||
for i = 0, 37 * 23 - 1 do
|
||||
buffer.writeu8(img.pixels, i * 4 + 3, 255)
|
||||
end
|
||||
end
|
||||
return img
|
||||
end
|
||||
local function few(): Types.Image
|
||||
local img = Types.Image.new(30, 20)
|
||||
for y = 0, 19 do
|
||||
for x = 0, 29 do
|
||||
local k = (x // 3 + y // 2) % 12
|
||||
buffer.writeu32(img.pixels, (y * 30 + x) * 4, (k * 20) + (255 - k * 20) * 256 + ((k * 77) % 256) * 65536 + 0xFF000000)
|
||||
end
|
||||
end
|
||||
return img
|
||||
end
|
||||
local function simple(): any
|
||||
if which == "pcx" then
|
||||
return require("@formats/image/pcx")
|
||||
elseif which == "sgi" then
|
||||
return require("@formats/image/sgi")
|
||||
elseif which == "sunras" then
|
||||
return require("@formats/image/sunras")
|
||||
elseif which == "xbm" then
|
||||
return require("@formats/image/xbm")
|
||||
elseif which == "xpm" then
|
||||
return require("@formats/image/xpm")
|
||||
elseif which == "ilbm" then
|
||||
return require("@formats/image/ilbm")
|
||||
end
|
||||
return nil
|
||||
end
|
||||
local Fmt = simple()
|
||||
if Fmt then
|
||||
for name, img in { opaque = photo(false), alpha = photo(true), few = few() } do
|
||||
local out, err = Fmt.encode(img)
|
||||
if out then
|
||||
emit("ours_" .. name .. "." .. which, out)
|
||||
else
|
||||
print("skip\t" .. name .. "\t" .. tostring(err))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
if which == "icns" then
|
||||
-- square icons 16 / 32 / 48 / 128 as RLE entries (no encodeImage hook here)
|
||||
local Icns = require("@formats/image/icns")
|
||||
local base = image(128, 128, "rgba8", 1)
|
||||
base.frames = {}
|
||||
for i, s in { 16, 32, 48, 128 } do
|
||||
base.frames[i] = { image = image(s, s, "rgba8", i), delay = 0, x = 0, y = 0, dispose = "none", blend = "source" }
|
||||
end
|
||||
base.pixels = base.frames[4].image.pixels
|
||||
emit("ours_legacy.icns", Icns.encode(base))
|
||||
end
|
||||
|
||||
if which == "ora" then
|
||||
-- a layered document: background, an offset half-opaque multiply layer, a hidden one, a group with a screen layer
|
||||
local Ora = require("@formats/layered/ora")
|
||||
local Png = require("@formats/image/png")
|
||||
local doc = Types.Layered.new(40, 30)
|
||||
local bg = Types.Layered.layer("background", image(40, 30, "rgba8", 0))
|
||||
for i = 0, 40 * 30 - 1 do
|
||||
buffer.writeu8(bg.image.pixels, i * 4 + 3, 255)
|
||||
end
|
||||
local mid = Types.Layered.layer("mid", image(20, 10, "rgba8", 1), 5, 7)
|
||||
mid.opacity, mid.blend = 0.5, "multiply"
|
||||
local hidden = Types.Layered.layer("hidden", image(8, 8, "rgba8", 2), 1, 1)
|
||||
hidden.visible = false
|
||||
local inner = Types.Layered.layer("inner", image(10, 10, "rgba8", 3), 20, 15)
|
||||
inner.blend = "screen"
|
||||
local g = Types.Layered.group("group", { inner })
|
||||
g.opacity = 0.75
|
||||
doc.layers = { bg, mid, hidden, g }
|
||||
emit("ours_doc.ora", Ora.encode(doc, { encodeImage = function(img: any, _f: string): (any, any)
|
||||
return Png.encode(img)
|
||||
end }))
|
||||
end
|
||||
@@ -0,0 +1,110 @@
|
||||
# Shared by the texture fixture generators (bcn.py, etc.py, dds.py, ktx.py): reference block decoders through nix.
|
||||
# godot(ctx, jobs) Godot 4's Image.decompress (bcdec for BC1-7, etcpak for ETC1 / ETC2 / EAC): each job is
|
||||
# (raw block bytes, w, h, godot format number, float) -> rgba8 bytes, or rgbaf32 little-endian
|
||||
# bytes when float is true
|
||||
# pillow(ctx, jobs) Pillow's DDS reader (BcnDecode.c): each job is (dds bytes) -> (mode, raw bytes)
|
||||
# dds_dx10(w, h, dxgi, data) / dds_fourcc(w, h, fourcc, data): minimal DDS files around block data
|
||||
import os, shutil, struct, tempfile
|
||||
|
||||
# Godot Image.Format numbers (checked against Godot 4.7)
|
||||
GODOT = {"bc1": 17, "bc2": 18, "bc3": 19, "bc4": 20, "bc5": 21, "bc7": 22, "bc6hs": 23, "bc6h": 24, "etc1": 25,
|
||||
"eac_r11": 26, "eac_r11s": 27, "eac_rg11": 28, "eac_rg11s": 29, "etc2_rgb": 30, "etc2_rgba": 31,
|
||||
"etc2_rgba1": 32}
|
||||
|
||||
GD_SCRIPT = r'''extends SceneTree
|
||||
func _init():
|
||||
var dir = OS.get_cmdline_user_args()[0]
|
||||
var lines = FileAccess.get_file_as_string(dir + "/jobs.txt").split("\n", false)
|
||||
for line in lines:
|
||||
var a = line.split(" ")
|
||||
var data = FileAccess.get_file_as_bytes(dir + "/" + a[0])
|
||||
var img = Image.create_from_data(int(a[1]), int(a[2]), false, int(a[3]), data)
|
||||
img.decompress()
|
||||
if a[4] == "1":
|
||||
img.convert(Image.FORMAT_RGBAF)
|
||||
else:
|
||||
img.convert(Image.FORMAT_RGBA8)
|
||||
var f = FileAccess.open(dir + "/" + a[0] + ".out", FileAccess.WRITE)
|
||||
f.store_buffer(img.get_data())
|
||||
f.close()
|
||||
quit()
|
||||
'''
|
||||
|
||||
|
||||
def godot(ctx, jobs):
|
||||
work = tempfile.mkdtemp(prefix="formats-godot-")
|
||||
try:
|
||||
lines = []
|
||||
for i, (data, w, h, fmt, flt) in enumerate(jobs):
|
||||
with open(os.path.join(work, "j%d" % i), "wb") as f:
|
||||
f.write(data)
|
||||
lines.append("j%d %d %d %d %d" % (i, w, h, fmt, 1 if flt else 0))
|
||||
with open(os.path.join(work, "jobs.txt"), "w") as f:
|
||||
f.write("\n".join(lines) + "\n")
|
||||
with open(os.path.join(work, "run.gd"), "w") as f:
|
||||
f.write(GD_SCRIPT)
|
||||
ctx.nix("godot", ["godot", "--headless", "--script", os.path.join(work, "run.gd"), "--", work])
|
||||
out = []
|
||||
for i in range(len(jobs)):
|
||||
with open(os.path.join(work, "j%d.out" % i), "rb") as f:
|
||||
out.append(f.read())
|
||||
return out
|
||||
finally:
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
|
||||
|
||||
def pillow(ctx, files):
|
||||
"""files: list of bytes (any format Pillow reads) -> list of (mode, w, h, raw bytes)"""
|
||||
work = tempfile.mkdtemp(prefix="formats-pillow-")
|
||||
try:
|
||||
for i, data in enumerate(files):
|
||||
with open(os.path.join(work, "f%d" % i), "wb") as f:
|
||||
f.write(data)
|
||||
code = ("import os\nfrom PIL import Image\nw=%r\nfor i in range(%d):\n"
|
||||
" im=Image.open(os.path.join(w,'f%%d'%%i)); im.load()\n"
|
||||
" open(os.path.join(w,'f%%d.out'%%i),'wb').write(im.tobytes())\n"
|
||||
" open(os.path.join(w,'f%%d.mode'%%i),'w').write('%%s %%d %%d'%%(im.mode,im.width,im.height))\n") % (work, len(files))
|
||||
ctx.python(["pillow"], code)
|
||||
out = []
|
||||
for i in range(len(files)):
|
||||
mode, w, h = open(os.path.join(work, "f%d.mode" % i)).read().split()
|
||||
out.append((mode, int(w), int(h), open(os.path.join(work, "f%d.out" % i), "rb").read()))
|
||||
return out
|
||||
finally:
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
|
||||
|
||||
def dds_header(w, h, pf, caps=0x1000, mips=0, flags=0x1007, pitch=0, depth=0, caps2=0):
|
||||
if mips:
|
||||
flags |= 0x20000
|
||||
return (b"DDS " + struct.pack("<7I", 124, flags, h, w, pitch, depth, mips) + b"\0" * 44 + pf +
|
||||
struct.pack("<4I", caps, caps2, 0, 0) + b"\0" * 4)
|
||||
|
||||
|
||||
def dds_dx10(w, h, dxgi, data, array=1, misc=0, mips=0, caps2=0):
|
||||
pf = struct.pack("<2I", 32, 4) + b"DX10" + b"\0" * 20
|
||||
return dds_header(w, h, pf, mips=mips, caps2=caps2) + struct.pack("<5I", dxgi, 3, misc, array, 0) + data
|
||||
|
||||
|
||||
def dds_fourcc(w, h, fourcc, data, mips=0, caps2=0):
|
||||
pf = struct.pack("<2I", 32, 4) + fourcc + b"\0" * 20
|
||||
return dds_header(w, h, pf, mips=mips, caps2=caps2) + data
|
||||
|
||||
|
||||
def rgba_from(mode, raw):
|
||||
"""Pillow raw bytes of mode L / RGB / RGBA -> rgba8 bytes"""
|
||||
if mode == "RGBA":
|
||||
return raw
|
||||
out = bytearray()
|
||||
if mode == "L":
|
||||
for v in raw:
|
||||
out += bytes((v, v, v, 255))
|
||||
elif mode == "LA":
|
||||
for i in range(0, len(raw), 2):
|
||||
out += bytes((raw[i], raw[i], raw[i], raw[i + 1]))
|
||||
elif mode == "RGB":
|
||||
for i in range(0, len(raw), 3):
|
||||
out += raw[i:i + 3] + b"\xff"
|
||||
else:
|
||||
raise ValueError(mode)
|
||||
return bytes(out)
|
||||
@@ -0,0 +1,66 @@
|
||||
# ANI fixtures (tools/fixtures.py): animated cursors assembled here around ICO / CUR frames written by Pillow (32 x 32
|
||||
# RGBA; the CUR ones patched from Pillow's ICO with hotspots): with seq + rate chunks, with neither, with INFO text, and
|
||||
# one with AF_ICON clear (UNSUPPORTED). References: Pillow's decode of every frame, the step order and delays here.
|
||||
# tests/gen/ani.luau { cases = { { name, data, w, h, steps = { { frame, delay } }, frames = { rgba }, hotspot?,
|
||||
# title?, unsupported? } } }
|
||||
import importlib.util, os, struct
|
||||
|
||||
def _load(n):
|
||||
spec = importlib.util.spec_from_file_location(n, os.path.join(os.path.dirname(os.path.abspath(__file__)), n + ".py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
R, T = _load("_raster_ref"), _load("_tex_reference")
|
||||
|
||||
|
||||
def chunk(cid, data):
|
||||
return cid + struct.pack("<I", len(data)) + data + (b"\0" if len(data) % 2 else b"")
|
||||
|
||||
|
||||
def riff_list(kind, items):
|
||||
return chunk(b"LIST", kind + b"".join(chunk(c, d) for c, d in items))
|
||||
|
||||
|
||||
def ani(icons, steps=None, rates=None, disp=10, flags=1, title=None):
|
||||
n = len(icons)
|
||||
ns = len(steps) if steps else n
|
||||
body = b"ACON" + chunk(b"anih", struct.pack("<9I", 36, n, ns, 32, 32, 32, 1, disp, flags | (2 if steps else 0)))
|
||||
if title:
|
||||
body += riff_list(b"INFO", [(b"INAM", title.encode() + b"\0")])
|
||||
if rates:
|
||||
body += chunk(b"rate", struct.pack("<%dI" % len(rates), *rates))
|
||||
if steps:
|
||||
body += chunk(b"seq ", struct.pack("<%dI" % len(steps), *steps))
|
||||
body += riff_list(b"fram", [(b"icon", d) for d in icons])
|
||||
return b"RIFF" + struct.pack("<I", len(body)) + body
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
w = R.Work(ctx)
|
||||
try:
|
||||
for i in range(4):
|
||||
px = bytes(v for p in range(32 * 32) for v in (((p * (i + 3)) % 256, 40 * i, (p // 32) * 8, 255 if (p + i) % 5 else 0)))
|
||||
w.png("f%d.png" % i, 32, 32, px)
|
||||
ctx.python(["pillow"], "from PIL import Image\nimport os\nos.chdir(%r)\nfor i in range(4):\n Image.open('f%%d.png' %% i).save('f%%d.ico' %% i, sizes=[(32, 32)])\n" % w.dir)
|
||||
icos = [w.read("f%d.ico" % i) for i in range(4)]
|
||||
# CUR: type 2, the planes / bit count fields of the entry become the hotspot
|
||||
curs = []
|
||||
for i, d in enumerate(icos):
|
||||
b = bytearray(d)
|
||||
b[2:4] = struct.pack("<H", 2)
|
||||
b[6 + 4:6 + 8] = struct.pack("<HH", 3 + i, 7)
|
||||
curs.append(bytes(b))
|
||||
refs = [T.rgba_from(m, raw) for (m, ww, hh, raw) in T.pillow(ctx, icos)]
|
||||
cases = []
|
||||
steps, rates = [0, 1, 2, 1, 3], [6, 12, 6, 30, 3]
|
||||
cases.append({"name": "seq + rate", "data": ani(icos, steps, rates, title="spinner"), "w": 32, "h": 32,
|
||||
"steps": [{"frame": s + 1, "delay": r / 60} for s, r in zip(steps, rates)], "frames": refs, "title": "spinner"})
|
||||
cases.append({"name": "plain", "data": ani(icos[:3], disp=4), "w": 32, "h": 32,
|
||||
"steps": [{"frame": i + 1, "delay": 4 / 60} for i in range(3)], "frames": refs[:3]})
|
||||
cases.append({"name": "cursor frames", "data": ani(curs[:2], disp=8), "w": 32, "h": 32,
|
||||
"steps": [{"frame": i + 1, "delay": 8 / 60} for i in range(2)], "frames": refs[:2], "hotspot": [3, 7]})
|
||||
cases.append({"name": "raw bitmaps", "data": ani(icos[:1], flags=0), "unsupported": True})
|
||||
ctx.emit("ani", {"cases": cases})
|
||||
finally:
|
||||
w.close()
|
||||
@@ -0,0 +1,119 @@
|
||||
# BCn fixtures (tools/fixtures.py): random BC1..BC7 blocks (every BC7 mode and BC6H mode forced in turn, the BC1
|
||||
# 3-colour mode, odd image sizes) decoded by two references: Pillow's DDS reader and Godot 4 (bcdec); plus encoder
|
||||
# baselines: test images and the PSNR Pillow's own BC1 / BC3 / BC5 encoder reaches on them.
|
||||
# tests/gen/bcn.luau { cases = { { name, kind, w, h, data, pillow?, godot?, tol } }, enc = { { name, w, h,
|
||||
# rgba, psnr = { bc1, bc3, bc5 } } } } (pillow / godot: rgba8 bytes, or rgbaf32 for BC6H)
|
||||
# tests/gen/bcn_bench.luau a 256 x 256 image and random BC1 / BC6H / BC7 blocks for tools/bench.luau
|
||||
import importlib.util, math, os, random, struct
|
||||
|
||||
_spec = importlib.util.spec_from_file_location("_tex_reference", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tex_reference.py"))
|
||||
R = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(R)
|
||||
|
||||
DXGI = {"bc1": 71, "bc2": 74, "bc3": 77, "bc4": 80, "bc5": 83, "bc5s": 84, "bc6h": 95, "bc6hs": 96, "bc7": 98}
|
||||
BLOCK = {"bc1": 8, "bc2": 16, "bc3": 16, "bc4": 8, "bc5": 16, "bc5s": 16, "bc6h": 16, "bc6hs": 16, "bc7": 16}
|
||||
BC6_HEADERS = [0, 1, 2, 6, 10, 14, 18, 22, 26, 30, 3, 7, 11, 15, 19, 23, 27, 31]
|
||||
|
||||
|
||||
def blocks(rng, kind, n, mode=None):
|
||||
out = bytearray()
|
||||
for _ in range(n):
|
||||
b = bytearray(rng.getrandbits(8) for _ in range(BLOCK[kind]))
|
||||
if kind == "bc7" and mode is not None:
|
||||
b[0] = (b[0] & ~((2 << mode) - 1) & 0xFF) | (1 << mode)
|
||||
elif kind.startswith("bc6h") and mode is not None:
|
||||
bitsn = 2 if mode < 2 else 5
|
||||
b[0] = (b[0] & ~((1 << bitsn) - 1) & 0xFF) | mode
|
||||
out += b
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def test_image(w, h, rng, alpha):
|
||||
px = bytearray()
|
||||
for y in range(h):
|
||||
for x in range(w):
|
||||
r = int(128 + 100 * math.sin(x / 7.0) * math.cos(y / 11.0))
|
||||
g = int(255 * x / (w - 1))
|
||||
b = int(255 * y / (h - 1)) if (x // 16 + y // 16) % 2 else 40
|
||||
n = rng.randrange(-12, 13)
|
||||
r, g, b = [max(0, min(255, v + n)) for v in (r, g, b)]
|
||||
a = 255
|
||||
if alpha:
|
||||
a = 0 if (x - w / 2) ** 2 + (y - h / 2) ** 2 < (w / 4) ** 2 else 255
|
||||
px += bytes((r, g, b, a))
|
||||
return bytes(px)
|
||||
|
||||
|
||||
def psnr(a, b, channels):
|
||||
se, n = 0, 0
|
||||
for i in range(0, len(a), 4):
|
||||
for c in channels:
|
||||
d = a[i + c] - b[i + c]
|
||||
se += d * d
|
||||
n += 1
|
||||
return 99.0 if se == 0 else 10 * math.log10(255 * 255 * n / se)
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = random.Random(7)
|
||||
cases = []
|
||||
|
||||
def add(name, kind, w, h, data):
|
||||
cases.append({"name": name, "kind": kind, "w": w, "h": h, "data": data})
|
||||
|
||||
for kind in ("bc1", "bc2", "bc3", "bc4", "bc5", "bc5s"):
|
||||
add(kind + " 32x32", kind, 32, 32, blocks(rng, kind, 64))
|
||||
add(kind + " 13x7", kind, 13, 7, blocks(rng, kind, 8))
|
||||
for m in range(8):
|
||||
add("bc7 mode %d" % m, "bc7", 32, 16, blocks(rng, "bc7", 32, m))
|
||||
add("bc7 15x9", "bc7", 15, 9, blocks(rng, "bc7", 12))
|
||||
for kind in ("bc6h", "bc6hs"):
|
||||
for m in BC6_HEADERS:
|
||||
add("%s mode %d" % (kind, m), kind, 16, 16, blocks(rng, kind, 16, m))
|
||||
# Pillow (BC1..BC5, BC5S, BC7, BC6H as clamped 8-bit)
|
||||
files = [R.dds_dx10(c["w"], c["h"], DXGI[c["kind"]], c["data"]) for c in cases]
|
||||
for c, (mode, w, h, raw) in zip(cases, R.pillow(ctx, files)):
|
||||
c["pillow"] = R.rgba_from(mode, raw)
|
||||
# Godot (bcdec): everything but the signed BC5 (no Godot format); BC6H as floats
|
||||
gj, gi = [], []
|
||||
for i, c in enumerate(cases):
|
||||
if c["kind"] in R.GODOT:
|
||||
gj.append((c["data"], c["w"], c["h"], R.GODOT[c["kind"]], c["kind"].startswith("bc6h")))
|
||||
gi.append(i)
|
||||
for i, out in zip(gi, R.godot(ctx, gj)):
|
||||
cases[i]["godot"] = out
|
||||
|
||||
# encoder baselines: Pillow's encoder on the same images, decoded by Pillow
|
||||
enc = []
|
||||
for name, w, h, alpha in (("photo 64x64", 64, 64, False), ("alpha 64x48", 64, 48, True), ("odd 37x21", 37, 21, False)):
|
||||
px = test_image(w, h, rng, alpha)
|
||||
e = {"name": name, "w": w, "h": h, "rgba": px, "psnr": {}}
|
||||
enc.append(e)
|
||||
import tempfile, shutil
|
||||
work = tempfile.mkdtemp(prefix="formats-bcn-")
|
||||
try:
|
||||
for i, e in enumerate(enc):
|
||||
open(os.path.join(work, "src%d" % i), "wb").write(e["rgba"])
|
||||
code = ("import os\nfrom PIL import Image\nw=%r\n"
|
||||
"for i, (W, H) in enumerate(%r):\n"
|
||||
" im=Image.frombytes('RGBA',(W,H),open(os.path.join(w,'src%%d'%%i),'rb').read())\n"
|
||||
" for pf in ('DXT1','DXT5','BC5'):\n"
|
||||
" p=os.path.join(w,'e%%d_%%s.dds'%%(i,pf))\n"
|
||||
" (im if pf!='BC5' else im.convert('RGB')).save(p,pixel_format=pf)\n"
|
||||
" back=Image.open(p).convert('RGBA')\n"
|
||||
" open(p+'.rgba','wb').write(back.tobytes())\n") % (work, [(e["w"], e["h"]) for e in enc])
|
||||
ctx.python(["pillow"], code)
|
||||
for i, e in enumerate(enc):
|
||||
for pf, kind, ch in (("DXT1", "bc1", (0, 1, 2)), ("DXT5", "bc3", (0, 1, 2, 3)), ("BC5", "bc5", (0, 1))):
|
||||
back = open(os.path.join(work, "e%d_%s.dds.rgba" % (i, pf)), "rb").read()
|
||||
e["psnr"][kind] = psnr(e["rgba"], back, ch)
|
||||
finally:
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
ctx.emit("bcn", {"cases": cases, "enc": enc})
|
||||
|
||||
# bench: a 512 x 512 image, and random BC7 blocks of every mode
|
||||
w = h = 256
|
||||
px = test_image(w, h, rng, True)
|
||||
bench = {"w": w, "h": h, "rgba": px, "bc7": blocks(rng, "bc7", (w // 4) * (h // 4)),
|
||||
"bc1": blocks(rng, "bc1", (w // 4) * (h // 4)), "bc6h": blocks(rng, "bc6h", (w // 4) * (h // 4), 3)}
|
||||
ctx.emit("bcn_bench", bench)
|
||||
@@ -0,0 +1,332 @@
|
||||
# DDS fixtures (tools/fixtures.py):
|
||||
# - files written by NVIDIA Texture Tools (nvcompress: uncompressed BGRA, BC1 / BC1a / BC2 / BC3 / BC4 / BC5 / BC6H /
|
||||
# BC7, with and without mip chains, legacy and DX10 headers; nvassemble: cube maps, arrays, volumes) and by
|
||||
# ImageMagick (none / DXT1 / DXT5 with mip maps);
|
||||
# - hand-written ones for the uncompressed DXGI and legacy formats nothing here writes (floats, snorm, packed,
|
||||
# shared exponent, YUY2, luminance, bit masks, D3DFMT numbers), with the values they hold;
|
||||
# - our encoder's files (tools/fixtures/_tex_encode.luau -a dds) read back by Pillow and nvddsinfo.
|
||||
# Reference pixels: every surface is cut out here (an independent walk of the DDS layout) and decoded by Pillow
|
||||
# (BCn through a one-surface DX10 file; BC6H by Godot as floats); the hand-written files carry their expected values.
|
||||
# tests/gen/dds.luau { cases = { { name, data, layout, mips, layers, depth, surfaces = { { level, layer, slice, w,
|
||||
# h, rgba?, floats?, tol } } } }, ours = { { name, data, pillow?, info } } }
|
||||
import importlib.util, json, math, os, random, shutil, struct, subprocess, tempfile, zlib
|
||||
|
||||
_spec = importlib.util.spec_from_file_location("_tex_reference", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tex_reference.py"))
|
||||
R = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(R)
|
||||
|
||||
INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/dds", "src/Formats/codecs/image/Bcn", "src/Formats/codecs/image/Texture.luau"]
|
||||
|
||||
BLOCK = {"bc1": 8, "bc2": 16, "bc3": 16, "bc4": 8, "bc5": 16, "bc6h": 16, "bc7": 16}
|
||||
DXGI_BC = {70: "bc1", 71: "bc1", 72: "bc1", 73: "bc2", 74: "bc2", 75: "bc2", 76: "bc3", 77: "bc3", 78: "bc3", 79: "bc4",
|
||||
80: "bc4", 82: "bc5", 83: "bc5", 94: "bc6h", 95: "bc6h", 97: "bc7", 98: "bc7", 99: "bc7"}
|
||||
FOURCC_BC = {b"DXT1": "bc1", b"DXT3": "bc2", b"DXT5": "bc3", b"ATI1": "bc4", b"BC4U": "bc4", b"ATI2": "bc5", b"BC5U": "bc5"}
|
||||
|
||||
|
||||
def png(w, h, rgba):
|
||||
raw = b"".join(b"\0" + rgba[y * w * 4:(y + 1) * w * 4] for y in range(h))
|
||||
def chunk(t, d):
|
||||
return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d))
|
||||
return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0)) +
|
||||
chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b""))
|
||||
|
||||
|
||||
def source(w, h, salt=0):
|
||||
out = bytearray()
|
||||
for y in range(h):
|
||||
for x in range(w):
|
||||
r = x / max(1, w - 1)
|
||||
g = y / max(1, h - 1)
|
||||
b = ((x * 7 + y * 13 + salt * 31) % 64) / 63
|
||||
a = ((x + y + salt) % 5) / 4
|
||||
out += bytes(int(v * 255 + 0.5) for v in (r, g, b, a))
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def layout(data):
|
||||
"""an independent walk of a DDS file: (info, [(level, layer, slice, w, h, format, offset, size)])"""
|
||||
flags, h, w, pitch, depth, mips = struct.unpack("<6I", data[8:32])
|
||||
pf_flags, fourcc, bits, rm, gm, bm, am = struct.unpack("<I4s5I", data[80:108])
|
||||
caps2 = struct.unpack("<I", data[112:116])[0]
|
||||
mips = max(1, mips if flags & 0x20000 else 1)
|
||||
off, layers, fmt, cube = 128, 1, None, False
|
||||
if pf_flags & 4 and fourcc == b"DX10":
|
||||
dxgi, dim, misc, arr = struct.unpack("<4I", data[128:144])
|
||||
off, layers = 148, max(1, arr)
|
||||
fmt = DXGI_BC.get(dxgi) or ("dxgi%d" % dxgi)
|
||||
cube = bool(misc & 4)
|
||||
volume = dim == 4
|
||||
elif pf_flags & 4:
|
||||
fmt = FOURCC_BC[fourcc]
|
||||
volume = bool(caps2 & 0x200000)
|
||||
cube = bool(caps2 & 0x200)
|
||||
else:
|
||||
fmt = "rgb%d" % bits
|
||||
volume = bool(caps2 & 0x200000)
|
||||
cube = bool(caps2 & 0x200)
|
||||
d0 = max(1, depth) if volume else 1
|
||||
count = layers * (6 if cube else 1)
|
||||
out = []
|
||||
for layer in range(count):
|
||||
lw, lh, ld = w, h, d0
|
||||
for level in range(mips):
|
||||
if fmt in BLOCK:
|
||||
size = ((lw + 3) // 4) * ((lh + 3) // 4) * BLOCK[fmt]
|
||||
elif fmt.startswith("rgb"):
|
||||
size = lw * lh * bits // 8
|
||||
else:
|
||||
size = lw * lh * 4 # dxgi28 / 87 (the only uncompressed DX10 ones nvassemble writes)
|
||||
for s in range(ld):
|
||||
out.append((level, layer, s, lw, lh, fmt, off, size))
|
||||
off += size
|
||||
lw, lh, ld = max(1, lw // 2), max(1, lh // 2), max(1, ld // 2)
|
||||
return {"w": w, "h": h, "mips": mips, "layers": layers, "cube": cube, "volume": volume, "depth": d0, "masks": (rm, gm, bm, am), "bits": bits}, out
|
||||
|
||||
|
||||
def mask_decode(raw, bits, masks):
|
||||
"""legacy bit-mask pixels -> rgba8 with rounding (the Texel rule)"""
|
||||
out = bytearray()
|
||||
nb = bits // 8
|
||||
for i in range(0, len(raw), nb):
|
||||
v = int.from_bytes(raw[i:i + nb], "little")
|
||||
px = []
|
||||
for k, m in enumerate(masks):
|
||||
if m == 0:
|
||||
px.append(255 if k == 3 else 0)
|
||||
continue
|
||||
sh = (m & -m).bit_length() - 1
|
||||
mx = m >> sh
|
||||
px.append(int(((v & m) >> sh) / mx * 255 + 0.5))
|
||||
out += bytes(px)
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def references(ctx, cases):
|
||||
"""fill c["surfaces"] for files from the tools: Pillow per surface (BCn / masks), Godot floats for BC6H"""
|
||||
pil_files, pil_targets, gd_jobs, gd_targets = [], [], [], []
|
||||
for c in cases:
|
||||
info, surf = layout(c["data"])
|
||||
c["layout"] = "volume" if info["volume"] else ("cube" if info["cube"] else ("array" if info["layers"] > 1 else "2d"))
|
||||
c["mips"], c["layers"], c["depth"] = info["mips"], info["layers"], info["depth"]
|
||||
c["surfaces"] = []
|
||||
for (level, layer, s, w, h, fmt, off, size) in surf:
|
||||
if level > 0 and (layer > 0 or s > 0):
|
||||
continue
|
||||
sd = {"level": level, "layer": layer, "slice": s, "w": w, "h": h, "tol": 0}
|
||||
raw = c["data"][off:off + size]
|
||||
c["surfaces"].append(sd)
|
||||
if fmt == "bc6h":
|
||||
gd_jobs.append((raw, w, h, R.GODOT["bc6h"], True))
|
||||
gd_targets.append(sd)
|
||||
elif fmt in BLOCK:
|
||||
dx = {"bc1": 71, "bc2": 74, "bc3": 77, "bc4": 80, "bc5": 83, "bc7": 98}[fmt]
|
||||
pil_files.append(R.dds_dx10(w, h, dx, raw))
|
||||
pil_targets.append((sd, fmt))
|
||||
elif fmt.startswith("rgb"):
|
||||
sd["rgba"] = mask_decode(raw, info["bits"], info["masks"])
|
||||
elif fmt == "dxgi28":
|
||||
sd["rgba"] = raw
|
||||
elif fmt == "dxgi87":
|
||||
sd["rgba"] = bytes(raw[i + k] for i in range(0, len(raw), 4) for k in (2, 1, 0, 3))
|
||||
for (sd, fmt), (mode, w, h, raw) in zip(pil_targets, R.pillow(ctx, pil_files)):
|
||||
rgba = R.rgba_from(mode, raw)
|
||||
if fmt == "bc5":
|
||||
rgba = bytes(v if i % 4 < 2 else (255 if i % 4 == 3 else 0) for i, v in enumerate(rgba))
|
||||
sd["rgba"] = rgba
|
||||
for sd, out in zip(gd_targets, R.godot(ctx, gd_jobs)):
|
||||
sd["floats"] = out
|
||||
|
||||
|
||||
def hand_cases(rng):
|
||||
"""uncompressed formats with known values: (name, dds bytes, expected rgba8, expected floats or None)"""
|
||||
W, H = 5, 3
|
||||
cases = []
|
||||
|
||||
def f32(v):
|
||||
return struct.unpack("<f", struct.pack("<f", v))[0]
|
||||
|
||||
def half(v):
|
||||
return struct.unpack("<e", struct.pack("<e", v))[0]
|
||||
|
||||
def q8(v):
|
||||
return 0 if v != v or v <= 0 else (255 if v >= 1 else int(v * 255 + 0.5))
|
||||
|
||||
def add(name, dds, texels):
|
||||
"""texels: list of (r, g, b, a) floats (the native values) -> expected rgba8 by the rules"""
|
||||
cases.append({"name": name, "data": dds, "rgba8": bytes(q8(v) for t in texels for v in t),
|
||||
"floats": b"".join(struct.pack("<4f", *t) for t in texels)})
|
||||
|
||||
# floats
|
||||
vals = [(rng.uniform(-0.5, 3), rng.uniform(0, 1), rng.uniform(0, 1.5), rng.uniform(0, 1)) for _ in range(W * H)]
|
||||
data = b"".join(struct.pack("<4f", *v) for v in vals)
|
||||
add("dxgi R32G32B32A32_FLOAT", R.dds_dx10(W, H, 2, data), [tuple(f32(x) for x in v) for v in vals])
|
||||
data = b"".join(struct.pack("<4e", *v) for v in vals)
|
||||
add("dxgi R16G16B16A16_FLOAT", R.dds_dx10(W, H, 10, data), [tuple(half(x) for x in v) for v in vals])
|
||||
add("d3dfmt 113 (A16B16G16R16F)", R.dds_fourcc(W, H, struct.pack("<I", 113), data), [tuple(half(x) for x in v) for v in vals])
|
||||
data = b"".join(struct.pack("<f", v[0]) for v in vals)
|
||||
add("dxgi R32_FLOAT (grey)", R.dds_dx10(W, H, 41, data), [(f32(v[0]),) * 3 + (1.0,) for v in vals])
|
||||
data = b"".join(struct.pack("<2e", v[0], v[1]) for v in vals)
|
||||
add("dxgi R16G16_FLOAT", R.dds_dx10(W, H, 34, data), [(half(v[0]), half(v[1]), 0.0, 1.0) for v in vals])
|
||||
data = b"".join(struct.pack("<3f", *v[:3]) for v in vals)
|
||||
add("dxgi R32G32B32_FLOAT", R.dds_dx10(W, H, 6, data), [tuple(f32(x) for x in v[:3]) + (1.0,) for v in vals])
|
||||
# unorm / snorm
|
||||
u16 = [tuple(rng.randrange(65536) for _ in range(4)) for _ in range(W * H)]
|
||||
add("dxgi R16G16B16A16_UNORM", R.dds_dx10(W, H, 11, b"".join(struct.pack("<4H", *v) for v in u16)),
|
||||
[tuple(x / 65535 for x in v) for v in u16])
|
||||
add("d3dfmt 36 (A16B16G16R16)", R.dds_fourcc(W, H, struct.pack("<I", 36), b"".join(struct.pack("<4H", *v) for v in u16)),
|
||||
[tuple(x / 65535 for x in v) for v in u16])
|
||||
s8 = [tuple(rng.randrange(-128, 128) for _ in range(4)) for _ in range(W * H)]
|
||||
cases_s8 = [tuple(max(x, -127) / 127 for x in v) for v in s8]
|
||||
cases.append({"name": "dxgi R8G8B8A8_SNORM", "data": R.dds_dx10(W, H, 31, b"".join(struct.pack("<4b", *v) for v in s8)),
|
||||
"rgba8": bytes(max(x, -127) + 128 for v in s8 for x in v),
|
||||
"floats": b"".join(struct.pack("<4f", *v) for v in cases_s8)})
|
||||
u8 = [tuple(rng.randrange(256) for _ in range(4)) for _ in range(W * H)]
|
||||
add("dxgi R8_UNORM (grey)", R.dds_dx10(W, H, 61, bytes(v[0] for v in u8)), [(v[0] / 255,) * 3 + (1.0,) for v in u8])
|
||||
add("dxgi R8G8_UNORM", R.dds_dx10(W, H, 49, bytes(x for v in u8 for x in v[:2])), [(v[0] / 255, v[1] / 255, 0.0, 1.0) for v in u8])
|
||||
add("dxgi A8_UNORM", R.dds_dx10(W, H, 65, bytes(v[3] for v in u8)), [(0.0, 0.0, 0.0, v[3] / 255) for v in u8])
|
||||
add("dxgi B8G8R8X8_UNORM", R.dds_dx10(W, H, 88, bytes(x for v in u8 for x in (v[2], v[1], v[0], 7))),
|
||||
[(v[0] / 255, v[1] / 255, v[2] / 255, 1.0) for v in u8])
|
||||
add("dxgi R16_UNORM (grey)", R.dds_dx10(W, H, 56, b"".join(struct.pack("<H", v[0]) for v in u16)), [(v[0] / 65535,) * 3 + (1.0,) for v in u16])
|
||||
# packed
|
||||
p32 = [rng.getrandbits(32) for _ in range(W * H)]
|
||||
add("dxgi R10G10B10A2_UNORM", R.dds_dx10(W, H, 24, b"".join(struct.pack("<I", v) for v in p32)),
|
||||
[((v & 1023) / 1023, ((v >> 10) & 1023) / 1023, ((v >> 20) & 1023) / 1023, (v >> 30) / 3) for v in p32])
|
||||
|
||||
def uf(v, mb):
|
||||
e, m = v >> mb, v & ((1 << mb) - 1)
|
||||
if e == 0:
|
||||
return m / (1 << mb) * 2 ** -14
|
||||
return (1 + m / (1 << mb)) * 2 ** (e - 15)
|
||||
p11 = [rng.getrandbits(32) & ~((1 << 30) | (1 << 9) | (1 << 20)) for _ in range(W * H)] # keep exponents < 31
|
||||
add("dxgi R11G11B10_FLOAT", R.dds_dx10(W, H, 26, b"".join(struct.pack("<I", v) for v in p11)),
|
||||
[(uf(v & 2047, 6), uf((v >> 11) & 2047, 6), uf(v >> 22, 5), 1.0) for v in p11])
|
||||
add("dxgi R9G9B9E5_SHAREDEXP", R.dds_dx10(W, H, 67, b"".join(struct.pack("<I", v) for v in p32)),
|
||||
[tuple((v >> (9 * k) & 511) * 2.0 ** ((v >> 27) - 24) for k in range(3)) + (1.0,) for v in p32])
|
||||
p16 = [rng.getrandbits(16) for _ in range(W * H)]
|
||||
add("dxgi B5G6R5_UNORM", R.dds_dx10(W, H, 85, b"".join(struct.pack("<H", v) for v in p16)),
|
||||
[((v >> 11) / 31, ((v >> 5) & 63) / 63, (v & 31) / 31, 1.0) for v in p16])
|
||||
add("dxgi B5G5R5A1_UNORM", R.dds_dx10(W, H, 86, b"".join(struct.pack("<H", v) for v in p16)),
|
||||
[(((v >> 10) & 31) / 31, ((v >> 5) & 31) / 31, (v & 31) / 31, (v >> 15) * 1.0) for v in p16])
|
||||
add("dxgi B4G4R4A4_UNORM", R.dds_dx10(W, H, 115, b"".join(struct.pack("<H", v) for v in p16)),
|
||||
[(((v >> 8) & 15) / 15, ((v >> 4) & 15) / 15, (v & 15) / 15, (v >> 12) / 15) for v in p16])
|
||||
# legacy masks
|
||||
def legacy(bits, flags, masks, data):
|
||||
pf = struct.pack("<2I4s5I", 32, flags, b"\0\0\0\0", bits, *masks)
|
||||
return R.dds_header(W, H, pf) + data
|
||||
add("legacy R5G6B5", legacy(16, 0x40, (0xF800, 0x7E0, 0x1F, 0), b"".join(struct.pack("<H", v) for v in p16)),
|
||||
[((v >> 11) / 31, ((v >> 5) & 63) / 63, (v & 31) / 31, 1.0) for v in p16])
|
||||
add("legacy A1R5G5B5", legacy(16, 0x41, (0x7C00, 0x3E0, 0x1F, 0x8000), b"".join(struct.pack("<H", v) for v in p16)),
|
||||
[(((v >> 10) & 31) / 31, ((v >> 5) & 31) / 31, (v & 31) / 31, (v >> 15) * 1.0) for v in p16])
|
||||
add("legacy X8R8G8B8", legacy(32, 0x40, (0xFF0000, 0xFF00, 0xFF, 0), b"".join(struct.pack("<I", v) for v in p32)),
|
||||
[(((v >> 16) & 255) / 255, ((v >> 8) & 255) / 255, (v & 255) / 255, 1.0) for v in p32])
|
||||
add("legacy R8G8B8 (24-bit)", legacy(24, 0x40, (0xFF0000, 0xFF00, 0xFF, 0), b"".join(struct.pack("<I", v)[:3] for v in p32)),
|
||||
[(((v >> 16) & 255) / 255, ((v >> 8) & 255) / 255, (v & 255) / 255, 1.0) for v in p32])
|
||||
add("legacy A2B10G10R10", legacy(32, 0x41, (0x3FF, 0xFFC00, 0x3FF00000, 0xC0000000), b"".join(struct.pack("<I", v) for v in p32)),
|
||||
[((v & 1023) / 1023, ((v >> 10) & 1023) / 1023, ((v >> 20) & 1023) / 1023, (v >> 30) / 3) for v in p32])
|
||||
add("legacy L8", legacy(8, 0x20000, (0xFF, 0, 0, 0), bytes(v[0] for v in u8)), [(v[0] / 255,) * 3 + (1.0,) for v in u8])
|
||||
add("legacy A8L8", legacy(16, 0x20001, (0xFF, 0, 0, 0xFF00), bytes(x for v in u8 for x in (v[0], v[3]))),
|
||||
[(v[0] / 255,) * 3 + (v[3] / 255,) for v in u8])
|
||||
add("legacy A8", legacy(8, 0x2, (0, 0, 0, 0xFF), bytes(v[3] for v in u8)), [(0.0, 0.0, 0.0, v[3] / 255) for v in u8])
|
||||
add("legacy A4R4G4B4", legacy(16, 0x41, (0xF00, 0xF0, 0xF, 0xF000), b"".join(struct.pack("<H", v) for v in p16)),
|
||||
[(((v >> 8) & 15) / 15, ((v >> 4) & 15) / 15, (v & 15) / 15, (v >> 12) / 15) for v in p16])
|
||||
# YUY2 (BT.601 limited range)
|
||||
def ycc(y, u, v):
|
||||
c, d, e = 1.164 * (y - 16), u - 128, v - 128
|
||||
cl = lambda x: max(0, min(255, int(math.floor(x + 0.5))))
|
||||
return (cl(c + 1.596 * e), cl(c - 0.392 * d - 0.813 * e), cl(c + 2.017 * d), 255)
|
||||
W2 = 6
|
||||
yuy = bytes(rng.randrange(16, 240) for _ in range(W2 * H * 2))
|
||||
exp = []
|
||||
for y in range(H):
|
||||
for x in range(W2):
|
||||
q = y * W2 * 2 + (x // 2) * 4
|
||||
exp.append(ycc(yuy[q + (2 if x % 2 else 0)], yuy[q + 1], yuy[q + 3]))
|
||||
pf = struct.pack("<2I4s5I", 32, 4, b"YUY2", 0, 0, 0, 0, 0)
|
||||
cases.append({"name": "fourcc YUY2", "data": R.dds_header(W2, H, pf) + yuy, "rgba8": bytes(v for t in exp for v in t)})
|
||||
return cases
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = random.Random(5)
|
||||
work = tempfile.mkdtemp(prefix="formats-dds-")
|
||||
try:
|
||||
cases = _tools(ctx, work)
|
||||
references(ctx, cases)
|
||||
hand = hand_cases(rng)
|
||||
ours = _ours(ctx, work)
|
||||
finally:
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
ctx.emit("dds", {"cases": cases, "hand": hand, "ours": ours})
|
||||
|
||||
|
||||
def _tools(ctx, work):
|
||||
cases = []
|
||||
for name, w, h in (("a", 37, 23), ("b", 64, 32)):
|
||||
with open(os.path.join(work, name + ".png"), "wb") as f:
|
||||
f.write(png(w, h, source(w, h)))
|
||||
jobs = []
|
||||
for src in ("a", "b"):
|
||||
for fl in ("-rgb", "-bc1", "-bc1a", "-bc2", "-bc3", "-bc4", "-bc5", "-bc7"):
|
||||
jobs.append((src, fl, []))
|
||||
jobs.append((src, "-bc1", ["-nomips", "-dds10"]))
|
||||
jobs.append(("a", "-bc6", ["-nomips"]))
|
||||
script = []
|
||||
for src, fl, extra in jobs:
|
||||
out = "%s%s%s.dds" % (src, fl, "".join(extra))
|
||||
script.append("nvcompress -silent %s %s %s.png %s" % (fl, " ".join(extra), src, out))
|
||||
for i in range(6):
|
||||
with open(os.path.join(work, "f%d.png" % i), "wb") as f:
|
||||
f.write(png(16, 16, source(16, 16, i + 1)))
|
||||
faces = " ".join("f%d.png" % i for i in range(6))
|
||||
script.append("nvassemble -cube %s -o cube.dds" % faces)
|
||||
script.append("nvassemble -array f0.png f1.png f2.png -o array.dds")
|
||||
script.append("nvassemble -volume f0.png f1.png f2.png f3.png -o volume.dds")
|
||||
ctx.nix("nvidia-texture-tools", ["sh", "-c", "cd %s && %s" % (work, " && ".join(script))])
|
||||
im = []
|
||||
for comp in ("none", "dxt1", "dxt5"):
|
||||
im.append("magick a.png -define dds:compression=%s -define dds:mipmaps=3 im_%s.dds" % (comp, comp))
|
||||
ctx.nix("imagemagick", ["sh", "-c", "cd %s && %s" % (work, " && ".join(im))])
|
||||
names = ["%s%s%s.dds" % (s, f, "".join(e)) for s, f, e in jobs] + ["cube.dds", "array.dds", "volume.dds"] + ["im_%s.dds" % c for c in ("none", "dxt1", "dxt5")]
|
||||
for n in names:
|
||||
cases.append({"name": n, "data": open(os.path.join(work, n), "rb").read()})
|
||||
return cases
|
||||
|
||||
|
||||
def _ours(ctx, work):
|
||||
exe = shutil.which("luau")
|
||||
cmd = [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]
|
||||
res = subprocess.run(cmd + ["tools/fixtures/_tex_encode.luau", "-a", "dds"], cwd=ctx.root, capture_output=True, check=True)
|
||||
files = {}
|
||||
for line in res.stdout.decode().split("\n"):
|
||||
if "\t" in line:
|
||||
n, hx = line.split("\t", 1)
|
||||
files[n] = bytes.fromhex(hx.strip())
|
||||
out = []
|
||||
pil, pil_idx = [], []
|
||||
names = sorted(files)
|
||||
for n in names:
|
||||
with open(os.path.join(work, n), "wb") as f:
|
||||
f.write(files[n])
|
||||
info = ctx.nix("nvidia-texture-tools", ["sh", "-c", "cd %s && for f in %s; do echo \"== $f\"; nvddsinfo $f; done" % (work, " ".join(names))]).decode(errors="replace")
|
||||
blocks = {}
|
||||
for part in info.split("== ")[1:]:
|
||||
n, body = part.split("\n", 1)
|
||||
blocks[n.strip()] = body
|
||||
for i, n in enumerate(names):
|
||||
body = blocks.get(n, "")
|
||||
def field(key):
|
||||
for line in body.split("\n"):
|
||||
if line.strip().startswith(key):
|
||||
return line.split(":", 1)[1].strip()
|
||||
return ""
|
||||
e = {"name": n, "data": files[n], "width": int(field("Width") or 0), "height": int(field("Height") or 0),
|
||||
"mipcount": int(field("Mipmap count") or 0), "dxgi": field("DXGI Format"), "array": field("Array size"),
|
||||
"caps2": field("Caps 2")}
|
||||
out.append(e)
|
||||
if not any(k in n for k in ("rgba16", "rgba32f", "rgba16f", "cube", "array")):
|
||||
pil.append(files[n])
|
||||
pil_idx.append(i)
|
||||
for i, (mode, w, h, raw) in zip(pil_idx, R.pillow(ctx, pil)):
|
||||
out[i]["pillow"] = R.rgba_from(mode, raw)
|
||||
out[i]["pillowMode"] = mode
|
||||
return out
|
||||
@@ -0,0 +1,128 @@
|
||||
# ETC fixtures (tools/fixtures.py): random ETC1 / ETC2 / EAC blocks, sorted by mode so that every ETC2 mode
|
||||
# (individual, differential, T, H, planar; punch-through opaque and transparent) and every EAC multiplier case is
|
||||
# covered, decoded by Godot 4 (etcpak's decoder, through Image.decompress).
|
||||
# tests/gen/etc.luau { { name, kind, w, h, data, godot (rgba8 bytes) } }
|
||||
import importlib.util, os, random
|
||||
|
||||
_spec = importlib.util.spec_from_file_location("_tex_reference", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tex_reference.py"))
|
||||
R = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(R)
|
||||
|
||||
|
||||
def mode(b, punch):
|
||||
"""the ETC2 mode of an 8-byte colour block"""
|
||||
hi = int.from_bytes(b[:4], "big")
|
||||
if not punch and not (hi >> 1) & 1:
|
||||
return "individual"
|
||||
def s3(v):
|
||||
return v - 8 if v >= 4 else v
|
||||
r, g, bb = (hi >> 27) & 31, (hi >> 19) & 31, (hi >> 11) & 31
|
||||
dr, dg, db = s3((hi >> 24) & 7), s3((hi >> 16) & 7), s3((hi >> 8) & 7)
|
||||
if not 0 <= r + dr <= 31:
|
||||
return "T"
|
||||
if not 0 <= g + dg <= 31:
|
||||
return "H"
|
||||
if not 0 <= bb + db <= 31:
|
||||
return "planar"
|
||||
return "differential"
|
||||
|
||||
|
||||
def colour_blocks(rng, n, want, punch=False, opaque=None):
|
||||
out = bytearray()
|
||||
while len(out) < n * 8:
|
||||
b = bytearray(rng.getrandbits(8) for _ in range(8))
|
||||
if opaque is not None:
|
||||
b[3] = (b[3] & 0xFD) | (2 if opaque else 0)
|
||||
if mode(b, punch) == want:
|
||||
out += b
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def eac_blocks(rng, n, zero_mult=False):
|
||||
out = bytearray()
|
||||
for _ in range(n):
|
||||
b = bytearray(rng.getrandbits(8) for _ in range(8))
|
||||
if zero_mult:
|
||||
b[1] &= 0x0F
|
||||
out += b
|
||||
return bytes(out)
|
||||
|
||||
|
||||
EAC = [[-3, -6, -9, -15, 2, 5, 8, 14], [-3, -7, -10, -13, 2, 6, 9, 12], [-2, -5, -8, -13, 1, 4, 7, 12],
|
||||
[-2, -4, -6, -13, 1, 3, 5, 12], [-3, -6, -8, -12, 2, 5, 7, 11], [-3, -7, -9, -11, 2, 6, 8, 10],
|
||||
[-4, -7, -8, -11, 3, 6, 7, 10], [-3, -5, -8, -11, 2, 4, 7, 10], [-2, -6, -8, -10, 1, 5, 7, 9],
|
||||
[-2, -5, -8, -10, 1, 4, 7, 9], [-2, -4, -8, -10, 1, 3, 7, 9], [-2, -5, -7, -10, 1, 4, 6, 9],
|
||||
[-3, -4, -7, -10, 2, 3, 6, 9], [-1, -2, -3, -10, 0, 1, 2, 9], [-4, -6, -8, -9, 3, 5, 7, 8],
|
||||
[-3, -5, -7, -9, 2, 4, 6, 8]]
|
||||
|
||||
|
||||
def s11(c):
|
||||
"""signed EAC R11 / RG11 -> the 11-bit values (-1023..1023) per pixel and channel, as a flat list"""
|
||||
two = c["kind"] == "eac_rg11s"
|
||||
w, h, data = c["w"], c["h"], c["data"]
|
||||
bw = (w + 3) // 4
|
||||
out = [0] * (w * h * 2)
|
||||
step = 16 if two else 8
|
||||
for bi in range(len(data) // step):
|
||||
bx, by = bi % bw, bi // bw
|
||||
for ch in range(2 if two else 1):
|
||||
b = data[bi * step + ch * 8: bi * step + ch * 8 + 8]
|
||||
base = b[0] - 256 if b[0] >= 128 else b[0]
|
||||
base = max(base, -127)
|
||||
mult, tab = b[1] >> 4, EAC[b[1] & 15]
|
||||
bits = int.from_bytes(b[2:], "big")
|
||||
for i in range(16):
|
||||
m = tab[(bits >> (45 - 3 * i)) & 7]
|
||||
v = base * 8 + (m * mult * 8 if mult else m)
|
||||
v = max(-1023, min(1023, v))
|
||||
x, y = bx * 4 + i // 4, by * 4 + i % 4
|
||||
if x < w and y < h:
|
||||
out[(y * w + x) * 2 + ch] = v
|
||||
return out
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = random.Random(11)
|
||||
cases = []
|
||||
|
||||
def add(name, kind, w, h, data):
|
||||
cases.append({"name": name, "kind": kind, "w": w, "h": h, "data": data})
|
||||
|
||||
add("etc1 individual", "etc1", 16, 16, colour_blocks(rng, 16, "individual"))
|
||||
add("etc1 differential", "etc1", 16, 16, colour_blocks(rng, 16, "differential"))
|
||||
add("etc1 random 13x6", "etc1", 13, 6, bytes(rng.getrandbits(8) for _ in range(8 * 8)))
|
||||
for m in ("individual", "differential", "T", "H", "planar"):
|
||||
add("etc2_rgb " + m, "etc2_rgb", 16, 16, colour_blocks(rng, 16, m))
|
||||
for m in ("differential", "T", "H", "planar"):
|
||||
for op in (True, False):
|
||||
add("etc2_rgba1 %s %s" % (m, "opaque" if op else "transparent"), "etc2_rgba1", 16, 16,
|
||||
colour_blocks(rng, 16, m, True, op))
|
||||
for m in ("individual", "differential", "T", "H", "planar"):
|
||||
rgba = bytearray()
|
||||
col = colour_blocks(rng, 16, m)
|
||||
alpha = eac_blocks(rng, 16, m == "planar")
|
||||
for i in range(16):
|
||||
rgba += alpha[i * 8:i * 8 + 8] + col[i * 8:i * 8 + 8]
|
||||
add("etc2_rgba " + m, "etc2_rgba", 16, 16, bytes(rgba))
|
||||
for kind in ("eac_r11", "eac_r11s"):
|
||||
add(kind, kind, 16, 16, eac_blocks(rng, 16))
|
||||
add(kind + " multiplier 0", kind, 8, 8, eac_blocks(rng, 4, True))
|
||||
for kind in ("eac_rg11", "eac_rg11s"):
|
||||
add(kind, kind, 16, 12, eac_blocks(rng, 24))
|
||||
add("etc2_rgb 10x5", "etc2_rgb", 10, 5, bytes(rng.getrandbits(8) for _ in range(6 * 8)))
|
||||
# Godot cannot decode RGB A1 or the signed EAC kinds: A1 blocks go through it as ETC2 RGB (the test checks the
|
||||
# punch-through rules on top; the opaque bit is set for Godot, else ETC2 RGB reads the individual mode), signed EAC is checked against s11() below (the KDFS 1.3 rule, written here)
|
||||
jobs, idx = [], []
|
||||
for i, c in enumerate(cases):
|
||||
k = "etc2_rgb" if c["kind"] == "etc2_rgba1" else c["kind"]
|
||||
if k in ("eac_r11s", "eac_rg11s"):
|
||||
c["spec"] = s11(c)
|
||||
else:
|
||||
data = c["data"]
|
||||
if c["kind"] == "etc2_rgba1": # with the opaque bit set: ETC2 RGB's differential / T / H / planar
|
||||
data = bytes(v | 2 if i % 8 == 3 else v for i, v in enumerate(data))
|
||||
jobs.append((data, c["w"], c["h"], R.GODOT[k], False))
|
||||
idx.append(i)
|
||||
for i, out in zip(idx, R.godot(ctx, jobs)):
|
||||
cases[i]["godot"] = out
|
||||
ctx.emit("etc", cases)
|
||||
@@ -0,0 +1,195 @@
|
||||
# OpenEXR fixtures (tools/fixtures.py): files written by the OpenEXR 3.5 python bindings (every compression NONE /
|
||||
# RLE / ZIPS / ZIP / PIZ, HALF / FLOAT / UINT channels, odd sizes, an offset data window, decreasing line order, a
|
||||
# Y-only image, a layer (diffuse.R ...), subsampled channels, PXR24 / B44 / DWAA for the UNSUPPORTED path), tiled
|
||||
# versions by exrmaketiled (one level, mip-map with unfiltered levels, rip-map, round up, several compressions),
|
||||
# multipart files by exrmultipart; our encoder's files (tools/fixtures/_tex_encode.luau -a exr) read back by the
|
||||
# bindings and exrheader. References: the bindings' read of each file (RGBA as little-endian f32; Y as grey).
|
||||
# tests/gen/exr.luau { cases = { { name, data, w, h, floats?, unsupported?, opts?, mips? } }, ours = { { name,
|
||||
# data, floats, compression, header_ok } } }
|
||||
# tests/gen/exr_bench.luau a 512 x 256 half RGBA image in ZIP and PIZ
|
||||
import os, shutil, subprocess, tempfile
|
||||
|
||||
INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/exr"]
|
||||
|
||||
WRITE = r'''
|
||||
import OpenEXR, numpy as np, os, sys, json
|
||||
w = sys.argv[1]
|
||||
rng = np.random.default_rng(3)
|
||||
def win(x0, y0, x1, y1):
|
||||
return (np.array([x0, y0], dtype=np.int32), np.array([x1, y1], dtype=np.int32))
|
||||
def img(h, wd, kind="f2"):
|
||||
y, x = np.mgrid[0:h, 0:wd]
|
||||
r = (x / max(1, wd - 1)) * 3 - 0.5
|
||||
g = np.sin(y * 0.7) * 0.5 + 0.5
|
||||
b = rng.random((h, wd)) * 0.01 + (x * y % 7) * 0.2
|
||||
a = ((x + y) % 4) / 3.0
|
||||
return [c.astype(kind) for c in (r, g, b, a)]
|
||||
def save(name, header, channels):
|
||||
h = {"type": OpenEXR.scanlineimage}
|
||||
h.update(header)
|
||||
OpenEXR.File(h, channels).write(os.path.join(w, name))
|
||||
C = {"none": OpenEXR.NO_COMPRESSION, "rle": OpenEXR.RLE_COMPRESSION, "zips": OpenEXR.ZIPS_COMPRESSION,
|
||||
"zip": OpenEXR.ZIP_COMPRESSION, "piz": OpenEXR.PIZ_COMPRESSION}
|
||||
names = []
|
||||
for cn, c in C.items():
|
||||
r, g, b, a = img(23, 37)
|
||||
save("half_rgba_%s.exr" % cn, {"compression": c}, {"R": r, "G": g, "B": b, "A": a})
|
||||
r, g, b, a = img(19, 41, "f4")
|
||||
save("float_rgb_%s.exr" % cn, {"compression": c}, {"R": r, "G": g, "B": b})
|
||||
r, g, b, a = img(37, 70)
|
||||
u = (rng.random((37, 70)) * 100000).astype("uint32")
|
||||
save("mixed_%s.exr" % cn, {"compression": c, "lineOrder": OpenEXR.DECREASING_Y}, {"R": r, "G": g.astype("f4"), "B": u})
|
||||
names += ["half_rgba_%s.exr" % cn, "float_rgb_%s.exr" % cn, "mixed_%s.exr" % cn]
|
||||
r, g, b, a = img(20, 30)
|
||||
save("window_zip.exr", {"compression": C["zip"], "dataWindow": win(5, -3, 34, 16), "displayWindow": win(0, 0, 39, 19)}, {"R": r, "G": g, "B": b, "A": a})
|
||||
save("grey_piz.exr", {"compression": C["piz"]}, {"Y": r})
|
||||
save("layer_zips.exr", {"compression": C["zips"]}, {"diffuse.R": r, "diffuse.G": g, "diffuse.B": b, "R": a, "G": a, "B": a})
|
||||
r, g, b, a = img(64, 96)
|
||||
save("big_piz.exr", {"compression": C["piz"]}, {"R": r, "G": g, "B": b, "A": a})
|
||||
save("big_zip.exr", {"compression": C["zip"]}, {"R": r, "G": g, "B": b, "A": a})
|
||||
names += ["window_zip.exr", "grey_piz.exr", "layer_zips.exr", "big_piz.exr", "big_zip.exr"]
|
||||
y, x = np.mgrid[0:16, 0:24]
|
||||
Y = (x / 23.0).astype("f2")
|
||||
sub = (np.mgrid[0:8, 0:12][1] / 11.0).astype("f2")
|
||||
# subsampled: hand-written (the bindings only write full-resolution channels): NONE, A at 2 x 2, R / G / B full
|
||||
import struct
|
||||
def attr(n, t, d):
|
||||
return n.encode() + b"\0" + t.encode() + b"\0" + struct.pack("<i", len(d)) + d
|
||||
chl = b""
|
||||
for n, xs in (("A", 2), ("B", 1), ("G", 1), ("R", 1)):
|
||||
chl += n.encode() + b"\0" + struct.pack("<iB3xii", 1, 0, xs, xs)
|
||||
chl += b"\0"
|
||||
W, H = 24, 16
|
||||
hdr = (b"\x76\x2f\x31\x01" + struct.pack("<I", 2) + attr("channels", "chlist", chl) + attr("compression", "compression", b"\0") +
|
||||
attr("dataWindow", "box2i", struct.pack("<4i", 0, 0, W - 1, H - 1)) + attr("displayWindow", "box2i", struct.pack("<4i", 0, 0, W - 1, H - 1)) +
|
||||
attr("lineOrder", "lineOrder", b"\0") + attr("pixelAspectRatio", "float", struct.pack("<f", 1)) +
|
||||
attr("screenWindowCenter", "v2f", struct.pack("<2f", 0, 0)) + attr("screenWindowWidth", "float", struct.pack("<f", 1)) + b"\0")
|
||||
blocks = []
|
||||
for yy in range(H):
|
||||
line = b""
|
||||
if yy % 2 == 0:
|
||||
line += np.array([(x2 * 2) / 23.0 for x2 in range(W // 2)], dtype="f2").tobytes()
|
||||
for ch in range(3):
|
||||
line += Y[yy].tobytes()
|
||||
blocks.append(struct.pack("<ii", yy, len(line)) + line)
|
||||
off = len(hdr) + 8 * H
|
||||
table = b""
|
||||
for bl in blocks:
|
||||
table += struct.pack("<Q", off)
|
||||
off += len(bl)
|
||||
open(os.path.join(w, "subsampled_none.exr"), "wb").write(hdr + table + b"".join(blocks))
|
||||
names.append("subsampled_none.exr")
|
||||
for cn, c in (("pxr24", OpenEXR.PXR24_COMPRESSION), ("b44", OpenEXR.B44_COMPRESSION), ("dwaa", OpenEXR.DWAA_COMPRESSION)):
|
||||
r, g, b, a = img(8, 8)
|
||||
save("unsupported_%s.exr" % cn, {"compression": c}, {"R": r, "G": g, "B": b})
|
||||
r, g, b, a = img(256, 512)
|
||||
save("bench_zip.exr", {"compression": C["zip"]}, {"R": r, "G": g, "B": b, "A": a})
|
||||
save("bench_piz.exr", {"compression": C["piz"]}, {"R": r, "G": g, "B": b, "A": a})
|
||||
print(json.dumps(names))
|
||||
'''
|
||||
|
||||
READ = r'''
|
||||
import OpenEXR, numpy as np, os, sys, json
|
||||
w = sys.argv[1]
|
||||
out = {}
|
||||
for name in json.loads(sys.argv[2]):
|
||||
f = OpenEXR.File(os.path.join(w, name), separate_channels=True)
|
||||
hdr = f.header()
|
||||
ch = f.channels()
|
||||
(x0, y0), (x1, y1) = hdr["dataWindow"]
|
||||
W, H = int(x1 - x0 + 1), int(y1 - y0 + 1)
|
||||
layer = sys.argv[3] if len(sys.argv) > 3 and name.startswith("layer") else ""
|
||||
px = np.zeros((H, W, 4), dtype="f4")
|
||||
px[:, :, 3] = 1
|
||||
def get(n):
|
||||
c = ch.get(layer + n)
|
||||
if c is None:
|
||||
return None
|
||||
p = c.pixels.astype("f4")
|
||||
if p.shape != (H, W):
|
||||
p = np.repeat(np.repeat(p, c.ySampling, axis=0), c.xSampling, axis=1)[:H, :W]
|
||||
return p
|
||||
if get("R") is None and get("Y") is not None:
|
||||
for k in range(3):
|
||||
px[:, :, k] = get("Y")
|
||||
for k, n in enumerate("RGBA"):
|
||||
p = get(n)
|
||||
if p is not None:
|
||||
px[:, :, k] = p
|
||||
out[name] = {"w": W, "h": H, "floats": px.tobytes().hex(), "compression": str(hdr["compression"]).split(".")[-1]}
|
||||
print(json.dumps(out))
|
||||
'''
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
work = tempfile.mkdtemp(prefix="formats-exr-")
|
||||
try:
|
||||
_generate(ctx, work)
|
||||
finally:
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
|
||||
|
||||
def py(ctx, code, *args):
|
||||
expr = "with import <nixpkgs> {}; python3.withPackages (p: [p.openexr p.numpy])"
|
||||
res = subprocess.run(["nix", "shell", "--impure", "--expr", expr, "-c", "python3", "-I", "-c", code] + list(args), capture_output=True)
|
||||
if res.returncode:
|
||||
raise RuntimeError("OpenEXR bindings failed: " + res.stderr.decode()[-2000:])
|
||||
return res.stdout
|
||||
|
||||
|
||||
def _generate(ctx, work):
|
||||
import json
|
||||
names = json.loads(py(ctx, WRITE, work))
|
||||
tiled = []
|
||||
sh = []
|
||||
for cn in ("none", "rle", "zip", "piz"):
|
||||
sh.append("exrmaketiled -o -t 16 8 -z %s half_rgba_zip.exr tiled_%s.exr" % (cn, cn))
|
||||
tiled.append("tiled_%s.exr" % cn)
|
||||
sh.append("exrmaketiled -m -t 8 8 -z zip -f R -f G -f B -f A half_rgba_zip.exr tiled_mip.exr")
|
||||
sh.append("exrmaketiled -m -u -t 8 8 -z piz half_rgba_zip.exr tiled_mip_up.exr")
|
||||
sh.append("exrmaketiled -r -t 16 16 -z zips half_rgba_zip.exr tiled_rip.exr")
|
||||
sh.append("exrmaketiled -o -t 8 8 -z zip float_rgb_none.exr tiled_float.exr")
|
||||
sh.append("exrmaketiled -o -t 7 5 -z zip window_zip.exr tiled_window.exr")
|
||||
tiled += ["tiled_mip.exr", "tiled_mip_up.exr", "tiled_rip.exr", "tiled_float.exr", "tiled_window.exr"]
|
||||
sh.append("exrmultipart -combine -i half_rgba_piz.exr::left half_rgba_rle.exr::right tiled_zip.exr::tiles -o multipart.exr")
|
||||
ctx.nix("openexr", ["sh", "-c", "cd %s && %s" % (work, " && ".join(sh))])
|
||||
ref = json.loads(py(ctx, READ, work, json.dumps(names + tiled), "diffuse."))
|
||||
cases = []
|
||||
for n in names + tiled:
|
||||
r = ref[n]
|
||||
c = {"name": n, "data": open(os.path.join(work, n), "rb").read(), "w": r["w"], "h": r["h"], "floats": bytes.fromhex(r["floats"])}
|
||||
if n.startswith("layer"):
|
||||
c["layer"] = "diffuse"
|
||||
if n.startswith("tiled_mip") or n.startswith("tiled_rip"):
|
||||
c["mips"] = True
|
||||
cases.append(c)
|
||||
# multipart: every part against the file it came from
|
||||
mp = open(os.path.join(work, "multipart.exr"), "rb").read()
|
||||
for i, (src, pname) in enumerate((("half_rgba_piz.exr", "left"), ("half_rgba_rle.exr", "right"), ("tiled_zip.exr", "tiles"))):
|
||||
r = ref[src]
|
||||
cases.append({"name": "multipart part %d (%s)" % (i + 1, pname), "data": mp, "part": i + 1, "partName": pname,
|
||||
"w": r["w"], "h": r["h"], "floats": bytes.fromhex(r["floats"])})
|
||||
for cn in ("pxr24", "b44", "dwaa"):
|
||||
cases.append({"name": "unsupported_%s.exr" % cn, "data": open(os.path.join(work, "unsupported_%s.exr" % cn), "rb").read(), "unsupported": True})
|
||||
ours = _ours(ctx, work)
|
||||
ctx.emit("exr", {"cases": cases, "ours": ours})
|
||||
ctx.emit("exr_bench", {"zip": open(os.path.join(work, "bench_zip.exr"), "rb").read(), "piz": open(os.path.join(work, "bench_piz.exr"), "rb").read()})
|
||||
|
||||
|
||||
def _ours(ctx, work):
|
||||
import json
|
||||
exe = shutil.which("luau")
|
||||
cmd = [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]
|
||||
res = subprocess.run(cmd + ["tools/fixtures/_tex_encode.luau", "-a", "exr"], cwd=ctx.root, capture_output=True, check=True)
|
||||
files = {}
|
||||
for line in res.stdout.decode().split("\n"):
|
||||
if "\t" in line:
|
||||
n, hx = line.split("\t", 1)
|
||||
files[n] = bytes.fromhex(hx.strip())
|
||||
names = sorted(files)
|
||||
for n in names:
|
||||
open(os.path.join(work, n), "wb").write(files[n])
|
||||
ref = json.loads(py(ctx, READ, work, json.dumps(names)))
|
||||
rc = ctx.nix("openexr", ["sh", "-c", "cd %s && for f in %s; do exrheader $f > /dev/null 2>&1; echo $f $?; done" % (work, " ".join(names))]).decode()
|
||||
ok = {line.split()[0]: line.split()[1] == "0" for line in rc.strip().split("\n")}
|
||||
return [{"name": n, "data": files[n], "floats": bytes.fromhex(ref[n]["floats"]), "compression": ref[n]["compression"], "headerOk": ok.get(n, False)} for n in names]
|
||||
@@ -0,0 +1,73 @@
|
||||
# ICNS fixtures (tools/fixtures.py): a libicns png2icns file (is32 / il32 / ih32 RLE entries with their masks, ic07 /
|
||||
# ic08 PNG entries), a JPEG 2000 entry that must be skipped (hand-written into hand.icns), a Pillow file (PNG entries), a hand-written one (ics# / ICN#
|
||||
# 1-bit icons, an ic04 ARGB entry, an uncompressed is32); every entry's reference pixels from icns2png -x (libicns)
|
||||
# or written here; our encoder's RLE file (tools/fixtures/_tex_encode.luau -a icns) read back by icns2png.
|
||||
# tests/gen/icns.luau { cases = { { name, data, entries = { { type, w, h, rgba } }, skipped } }, ours = { ... } }
|
||||
import importlib.util, os, re, struct
|
||||
|
||||
def _load(n):
|
||||
spec = importlib.util.spec_from_file_location(n, os.path.join(os.path.dirname(os.path.abspath(__file__)), n + ".py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
R, S, T = _load("_raster_ref"), _load("_simple"), _load("_tex_reference")
|
||||
INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/icns"]
|
||||
|
||||
|
||||
def extract(ctx, w, name):
|
||||
"""icns2png -x name -> { 'WxH': rgba } (one per extracted entry)"""
|
||||
log = w.sh("libicns", ["mkdir -p x_%s && cd x_%s && icns2png -x ../%s" % (name, name, name)]).decode()
|
||||
files = sorted(f for f in os.listdir(w.path("x_" + name)) if f.endswith(".png"))
|
||||
out = {}
|
||||
for f, (mode, ww, hh, raw) in zip(files, T.pillow(ctx, [w.read(os.path.join("x_" + name, f)) for f in files])):
|
||||
out["%dx%d" % (ww, hh)] = T.rgba_from(mode, raw)
|
||||
return out
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
w = R.Work(ctx)
|
||||
try:
|
||||
for s in (16, 32, 48, 128, 256):
|
||||
w.png("i%d.png" % s, s, s, R.photo(s, s, s, True))
|
||||
w.sh("libicns", ["png2icns libicns.icns i16.png i32.png i48.png i128.png i256.png"])
|
||||
w.png("p64.png", 64, 64, R.photo(64, 64, 9, True))
|
||||
ctx.python(["pillow"], "from PIL import Image\nimport os\nos.chdir(%r)\nImage.open('p64.png').save('pillow.icns')\n" % w.dir)
|
||||
cases = []
|
||||
lib = extract(ctx, w, "libicns.icns")
|
||||
cases.append({"name": "libicns.icns", "data": w.read("libicns.icns"), "skipped": 0,
|
||||
"entries": [{"type": t, "w": s, "h": s, "rgba": lib["%dx%d" % (s, s)]} for t, s in (("is32", 16), ("il32", 32), ("ih32", 48), ("ic07", 128), ("ic08", 256))]})
|
||||
pil = extract(ctx, w, "pillow.icns")
|
||||
cases.append({"name": "pillow.icns", "data": w.read("pillow.icns"), "skipped": 0,
|
||||
"entries": [{"type": "", "w": int(k.split("x")[0]), "h": int(k.split("x")[1]), "rgba": v} for k, v in sorted(pil.items())]})
|
||||
# hand-written: ics# (16x16 1-bit + mask), an uncompressed is32 + s8mk, an ic04 ARGB with RLE runs
|
||||
bits = bytes((0xF0 if (i // 2) % 2 else 0x0F) for i in range(32))
|
||||
mask = bytes((0xFF if i < 24 else 0x00) for i in range(32))
|
||||
mono = []
|
||||
for i in range(256):
|
||||
b = (bits[i // 8] >> (7 - i % 8)) & 1
|
||||
m = (mask[i // 8] >> (7 - i % 8)) & 1
|
||||
mono += [0, 0, 0] if b else [255, 255, 255]
|
||||
mono.append(255 if m else 0)
|
||||
raw = bytes((i * 3 + k * 50) % 256 for k in range(3) for i in range(256))
|
||||
alpha = bytes((i * 7) % 256 for i in range(256))
|
||||
rgb = bytes(v for i in range(256) for v in (raw[i], raw[256 + i], raw[512 + i], alpha[i]))
|
||||
def ch(t, d):
|
||||
return t + struct.pack(">I", len(d) + 8) + d
|
||||
# ARGB channels: A = 256 x 77 (two runs of 128), then R / G / B as runs
|
||||
argb = b"ARGB" + bytes((253, 77, 253, 77)) + bytes((253, 10, 253, 10)) + bytes((253, 20, 253, 20)) + bytes((253, 30, 253, 30))
|
||||
jp2 = b"\0\0\0\x0cjP \r\n\x87\n" + b"\0" * 20
|
||||
body = ch(b"ics#", bits + mask) + ch(b"is32", raw) + ch(b"s8mk", alpha) + ch(b"ic04", argb) + ch(b"ic09", jp2)
|
||||
hand = b"icns" + struct.pack(">I", len(body) + 8) + body
|
||||
cases.append({"name": "hand.icns", "data": hand, "skipped": 1, "entries": [
|
||||
{"type": "ics#", "w": 16, "h": 16, "rgba": bytes(mono)}, {"type": "is32", "w": 16, "h": 16, "rgba": rgb},
|
||||
{"type": "ic04", "w": 16, "h": 16, "rgba": bytes((10, 20, 30, 77)) * 256}]})
|
||||
mine = S.ours(ctx, "icns")
|
||||
ours = []
|
||||
for n, d in mine.items():
|
||||
w.write(n, d)
|
||||
ex = extract(ctx, w, n)
|
||||
ours.append({"name": n, "data": d, "entries": [{"type": "", "w": int(k.split("x")[0]), "h": int(k.split("x")[1]), "rgba": v} for k, v in sorted(ex.items())]})
|
||||
ctx.emit("icns", {"cases": cases, "ours": ours})
|
||||
finally:
|
||||
w.close()
|
||||
@@ -0,0 +1,121 @@
|
||||
# IFF ILBM fixtures (tools/fixtures.py): files from netpbm's ppmtoilbm (palette ByteRun1 / uncompressed, few planes,
|
||||
# HAM6, HAM8, 24-bit deep) and hand-written ones (EHB, chunky PBM, a mask plane, a transparent colour index, an odd
|
||||
# CMAP), decoded by ilbmtoppm as the reference (alpha separately: ilbmtoppm writes PPM; HAM values within the scaling
|
||||
# difference: ilbmtoppm shifts, we replicate bits); our encoder's files
|
||||
# (tools/fixtures/_tex_encode.luau -a ilbm) read by ilbmtoppm.
|
||||
# tests/gen/ilbm.luau { cases = { { name, data, w, h, rgba, transparent? } }, ours = { ... } }
|
||||
import importlib.util, os, random, struct
|
||||
|
||||
def _load(n):
|
||||
spec = importlib.util.spec_from_file_location(n, os.path.join(os.path.dirname(os.path.abspath(__file__)), n + ".py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
R, S = _load("_raster_ref"), _load("_simple")
|
||||
INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/ilbm"]
|
||||
|
||||
|
||||
def chunk(cid, data):
|
||||
return cid + struct.pack(">I", len(data)) + data + (b"\0" if len(data) % 2 else b"")
|
||||
|
||||
|
||||
def byterun1(row):
|
||||
out = bytearray()
|
||||
i = 0
|
||||
while i < len(row):
|
||||
run = 1
|
||||
while i + run < len(row) and run < 128 and row[i + run] == row[i]:
|
||||
run += 1
|
||||
if run >= 2:
|
||||
out += bytes((257 - run, row[i]))
|
||||
i += run
|
||||
else:
|
||||
j = i
|
||||
while j < len(row) and j - i < 128 and not (j + 1 < len(row) and row[j + 1] == row[j]):
|
||||
j += 1
|
||||
j = max(j, i + 1)
|
||||
out += bytes((j - i - 1,)) + row[i:j]
|
||||
i = j
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def planar(w, h, idx, planes, mask=None, comp=True):
|
||||
rb = ((w + 15) // 16) * 2
|
||||
body = bytearray()
|
||||
for y in range(h):
|
||||
rows = []
|
||||
for k in range(planes):
|
||||
row = bytearray(rb)
|
||||
for x in range(w):
|
||||
if (idx[y * w + x] >> k) & 1:
|
||||
row[x // 8] |= 0x80 >> (x % 8)
|
||||
rows.append(bytes(row))
|
||||
if mask is not None:
|
||||
row = bytearray(rb)
|
||||
for x in range(w):
|
||||
if mask[y * w + x]:
|
||||
row[x // 8] |= 0x80 >> (x % 8)
|
||||
rows.append(bytes(row))
|
||||
for row in rows:
|
||||
body += byterun1(row) if comp else row
|
||||
return bytes(body)
|
||||
|
||||
|
||||
def ilbm(w, h, planes, body, cmap=b"", camg=None, masking=0, trans=0, comp=1, form=b"ILBM", extra=b""):
|
||||
bmhd = struct.pack(">HHhhBBBxHBBhh", w, h, 0, 0, planes, masking, comp, trans, 10, 11, w, h)
|
||||
data = form + chunk(b"BMHD", bmhd) + (chunk(b"CMAP", cmap) if cmap else b"") + (chunk(b"CAMG", struct.pack(">I", camg)) if camg is not None else b"") + extra + chunk(b"BODY", body)
|
||||
return b"FORM" + struct.pack(">I", len(data)) + data
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = random.Random(8)
|
||||
w = R.Work(ctx)
|
||||
try:
|
||||
w.png("photo.png", 37, 23, R.photo(37, 23))
|
||||
w.png("pal.png", 31, 19, R.palette_image(31, 19, 60))
|
||||
w.png("pal8.png", 26, 11, R.palette_image(26, 11, 7))
|
||||
w.sh("netpbm", ["pngtopam photo.png | pamtopnm > photo.ppm", "pngtopam pal.png | pamtopnm > pal.ppm", "pngtopam pal8.png | pamtopnm > pal8.ppm",
|
||||
"ppmtoilbm pal.ppm > nb_pal.iff", "ppmtoilbm -nocompress pal.ppm > nb_pal_raw.iff", "ppmtoilbm pal8.ppm > nb_3planes.iff",
|
||||
"ppmtoilbm -ham6 photo.ppm > nb_ham6.iff", "ppmtoilbm -ham8 photo.ppm > nb_ham8.iff", "ppmtoilbm -24force photo.ppm > nb_24.iff"])
|
||||
hand = []
|
||||
# EHB: 6 planes, 32 colours
|
||||
W, H = 20, 7
|
||||
cm = bytes(rng.randrange(256) for _ in range(32 * 3))
|
||||
idx = [rng.randrange(64) for _ in range(W * H)]
|
||||
hand.append(("hand_ehb.iff", ilbm(W, H, 6, planar(W, H, idx, 6), cm, 0x80), None))
|
||||
# chunky PBM (rows padded to even), 256 colours
|
||||
cm2 = bytes(rng.randrange(256) for _ in range(256 * 3))
|
||||
W2 = 14
|
||||
idx2 = [rng.randrange(256) for _ in range(W2 * H)]
|
||||
hand.append(("hand_pbm.lbm", ilbm(W2, H, 8, b"".join(byterun1(bytes(idx2[y * W2:(y + 1) * W2])) for y in range(H)), cm2, form=b"PBM "), None))
|
||||
# a mask plane and a transparent colour index
|
||||
cm3 = bytes(rng.randrange(256) for _ in range(16 * 3))
|
||||
idx3 = [rng.randrange(16) for _ in range(W * H)]
|
||||
mask = [rng.random() < 0.7 for _ in range(W * H)]
|
||||
hand.append(("hand_mask.iff", ilbm(W, H, 4, planar(W, H, idx3, 4, mask), cm3, masking=1), [not m for m in mask]))
|
||||
hand.append(("hand_transparent.iff", ilbm(W, H, 4, planar(W, H, idx3, 4, comp=False), cm3, masking=2, trans=5, comp=0,
|
||||
extra=chunk(b"NAME", b"tiny\0")), [i == 5 for i in idx3]))
|
||||
for n, data, _ in hand:
|
||||
w.write(n, data)
|
||||
names = sorted(f for f in os.listdir(w.dir) if f.endswith(".iff") or f.endswith(".lbm"))
|
||||
mine = S.ours(ctx, "ilbm")
|
||||
for n, d in mine.items():
|
||||
w.write(n, d)
|
||||
allnames = names + sorted(mine)
|
||||
allnames = [n for n in allnames if n != "ours_alpha.ilbm"] # ilbmtoppm reads no 32-plane files
|
||||
w.sh("netpbm", ["ilbmtoppm %s > %s.ppm" % (n, n) for n in allnames])
|
||||
tmap = {n: t for n, _, t in hand}
|
||||
out = {"cases": [], "ours": []}
|
||||
for n in allnames:
|
||||
ww, hh, rgba = R.pnm_rgba(w.read(n + ".ppm"))
|
||||
c = {"name": n, "data": w.read(n), "w": ww, "h": hh, "rgba": rgba}
|
||||
if "ham" in n:
|
||||
# ilbmtoppm scales HAM values by shifting (4-bit v -> v << 4); we replicate the bits (v * 17)
|
||||
c["tol"] = 15 if "ham6" in n else 3
|
||||
if tmap.get(n):
|
||||
c["transparent"] = [bool(v) for v in tmap[n]]
|
||||
out["ours" if n.startswith("ours_") else "cases"].append(c)
|
||||
ctx.emit("ilbm", out)
|
||||
finally:
|
||||
w.close()
|
||||
@@ -0,0 +1,279 @@
|
||||
# KTX fixtures (tools/fixtures.py):
|
||||
# - KTX2 from KTX-Software 4.4 (`ktx create`): PNG sources (mip chains, sRGB, cube maps, arrays), --raw data in
|
||||
# uncompressed / packed / float / BCn / ETC2 / EAC VkFormats, a 3D texture, `ktx deflate` Zstandard and ZLIB
|
||||
# supercompression, Basis Universal (ETC1S and UASTC: must give UNSUPPORTED);
|
||||
# - KTX1 from toktx (PNG sources, mips, cube map, odd widths with row padding) and nvcompress -ktx (BC1 / BC3 / BC7),
|
||||
# plus hand-written big-endian and packed-type KTX1 files;
|
||||
# - our encoder's KTX2 files (tools/fixtures/_tex_encode.luau -a ktx): `ktx validate` and `ktx extract` read them.
|
||||
# References: the PNG sources / raw values themselves, `ktx extract` PNGs for the generated mip levels, Pillow (BCn,
|
||||
# through a one-surface DDS) and Godot (ETC / EAC) for block data.
|
||||
# tests/gen/ktx.luau { cases = { { name, data, layout?, mips?, surfaces = { { level, layer, slice, w, h, rgba?,
|
||||
# floats?, tol } }, unsupported? } }, ours = { { name, data, valid, extract = { rgba / floats } } } }
|
||||
import importlib.util, os, random, shutil, struct, subprocess, tempfile
|
||||
|
||||
_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
_spec = importlib.util.spec_from_file_location("_tex_reference", os.path.join(_dir, "_tex_reference.py"))
|
||||
R = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(R)
|
||||
_spec2 = importlib.util.spec_from_file_location("_dds_fixture", os.path.join(_dir, "dds.py"))
|
||||
D = importlib.util.module_from_spec(_spec2)
|
||||
_spec2.loader.exec_module(D)
|
||||
|
||||
INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/ktx", "tools/fixtures/dds.py"]
|
||||
|
||||
|
||||
def q8(v):
|
||||
return 0 if v != v or v <= 0 else (255 if v >= 1 else int(v * 255 + 0.5))
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
work = tempfile.mkdtemp(prefix="formats-ktx-")
|
||||
try:
|
||||
cases = _cases(ctx, work, random.Random(9))
|
||||
ours = _ours(ctx, work)
|
||||
finally:
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
ctx.emit("ktx", {"cases": cases, "ours": ours})
|
||||
|
||||
|
||||
def read_png(ctx, paths):
|
||||
return [R.rgba_from(m, raw) if m in ("RGB", "L", "LA", "RGBA") else raw for (m, w, h, raw) in
|
||||
R.pillow(ctx, [open(p, "rb").read() for p in paths])]
|
||||
|
||||
|
||||
def _cases(ctx, work, rng):
|
||||
cases = []
|
||||
sh = []
|
||||
|
||||
def run(cmd):
|
||||
sh.append(cmd)
|
||||
|
||||
# sources
|
||||
srcs = {}
|
||||
for name, w, h, salt in (("a", 37, 23, 0), ("sq", 32, 32, 3)):
|
||||
srcs[name] = (w, h, D.source(w, h, salt))
|
||||
open(os.path.join(work, name + ".png"), "wb").write(D.png(w, h, srcs[name][2]))
|
||||
faces = []
|
||||
for i in range(6):
|
||||
px = D.source(16, 16, i + 1)
|
||||
faces.append(px)
|
||||
open(os.path.join(work, "f%d.png" % i), "wb").write(D.png(16, 16, px))
|
||||
fl = " ".join("f%d.png" % i for i in range(6))
|
||||
run("ktx create --format R8G8B8A8_UNORM --assign-tf linear a.png k2_rgba8.ktx2")
|
||||
run("ktx create --format R8G8B8A8_SRGB --assign-tf srgb --generate-mipmap sq.png k2_srgb_mips.ktx2")
|
||||
run("ktx extract --level all k2_srgb_mips.ktx2 k2mips")
|
||||
run("ktx create --format R8G8B8A8_UNORM --assign-tf linear --cubemap %s k2_cube.ktx2" % fl)
|
||||
run("ktx create --format R8G8B8A8_UNORM --assign-tf linear --layers 3 f0.png f1.png f2.png k2_array.ktx2")
|
||||
run("ktx create --format R8G8B8_UNORM --assign-tf linear a.png k2_rgb8.ktx2")
|
||||
run("ktx deflate --zstd 12 k2_srgb_mips.ktx2 k2_zstd.ktx2")
|
||||
run("ktx deflate --zlib 6 k2_cube.ktx2 k2_zlib.ktx2")
|
||||
run("ktx create --format R8G8B8A8_UNORM --assign-tf linear --encode basis-lz a.png k2_basis.ktx2")
|
||||
run("ktx create --format R8G8B8A8_UNORM --assign-tf linear --encode uastc a.png k2_uastc.ktx2")
|
||||
# raw formats with known values
|
||||
W, H = 8, 4
|
||||
raws = []
|
||||
|
||||
def raw(name, vk, data, texels=None, block=None, w=W, h=H, extra="", parts=1):
|
||||
n = len(data) // parts
|
||||
files = []
|
||||
for i in range(parts):
|
||||
open(os.path.join(work, "%s_%d.raw" % (name, i)), "wb").write(data[i * n:(i + 1) * n])
|
||||
files.append("%s_%d.raw" % (name, i))
|
||||
run("ktx create --raw --width %d --height %d --format %s %s %s %s.ktx2" % (w, h, vk, extra, " ".join(files), name))
|
||||
raws.append((name, texels, block, w, h, data))
|
||||
|
||||
u8 = bytes(rng.randrange(256) for _ in range(W * H * 4))
|
||||
raw("k2_raw_rgba8", "R8G8B8A8_UNORM", u8, [tuple(u8[i + k] / 255 for k in range(4)) for i in range(0, len(u8), 4)])
|
||||
raw("k2_raw_bgra8_srgb", "B8G8R8A8_SRGB", u8, [(u8[i + 2] / 255, u8[i + 1] / 255, u8[i] / 255, u8[i + 3] / 255) for i in range(0, len(u8), 4)])
|
||||
raw("k2_raw_rg8", "R8G8_UNORM", u8[:W * H * 2], [(u8[i] / 255, u8[i + 1] / 255, 0.0, 1.0) for i in range(0, W * H * 2, 2)])
|
||||
vals = [(rng.uniform(-1, 4), rng.uniform(0, 1), rng.uniform(0, 2), rng.uniform(0, 1)) for _ in range(W * H)]
|
||||
hd = b"".join(struct.pack("<4e", *v) for v in vals)
|
||||
raw("k2_raw_rgba16f", "R16G16B16A16_SFLOAT", hd, [struct.unpack("<4e", hd[i:i + 8]) for i in range(0, len(hd), 8)])
|
||||
fd = b"".join(struct.pack("<4f", *v) for v in vals)
|
||||
raw("k2_raw_rgba32f", "R32G32B32A32_SFLOAT", fd, [struct.unpack("<4f", fd[i:i + 16]) for i in range(0, len(fd), 16)])
|
||||
u16 = [rng.randrange(65536) for _ in range(W * H)]
|
||||
raw("k2_raw_r16", "R16_UNORM", b"".join(struct.pack("<H", v) for v in u16), [(v / 65535,) * 3 + (1.0,) for v in u16])
|
||||
raw("k2_raw_r5g6b5", "R5G6B5_UNORM_PACK16", b"".join(struct.pack("<H", v) for v in u16),
|
||||
[((v >> 11) / 31, ((v >> 5) & 63) / 63, (v & 31) / 31, 1.0) for v in u16])
|
||||
p32 = [rng.getrandbits(32) for _ in range(W * H)]
|
||||
raw("k2_raw_a2b10g10r10", "A2B10G10R10_UNORM_PACK32", b"".join(struct.pack("<I", v) for v in p32),
|
||||
[((v & 1023) / 1023, ((v >> 10) & 1023) / 1023, ((v >> 20) & 1023) / 1023, (v >> 30) / 3) for v in p32])
|
||||
raw("k2_raw_e5b9g9r9", "E5B9G9R9_UFLOAT_PACK32", b"".join(struct.pack("<I", v) for v in p32),
|
||||
[tuple((v >> (9 * k) & 511) * 2.0 ** ((v >> 27) - 24) for k in range(3)) + (1.0,) for v in p32])
|
||||
vol = bytes(rng.randrange(256) for _ in range(4 * 4 * 3 * 4))
|
||||
raw("k2_raw_3d", "R8G8B8A8_UNORM", vol, None, None, 4, 4, "--depth 3", 3)
|
||||
for kind, vk in (("bc1", "BC1_RGB_UNORM_BLOCK"), ("bc1", "BC1_RGBA_UNORM_BLOCK"), ("bc3", "BC3_UNORM_BLOCK"),
|
||||
("bc7", "BC7_UNORM_BLOCK"), ("bc6h", "BC6H_UFLOAT_BLOCK"), ("etc2_rgba", "ETC2_R8G8B8A8_UNORM_BLOCK"),
|
||||
("etc2_rgb", "ETC2_R8G8B8_UNORM_BLOCK"), ("eac_rg11", "EAC_R11G11_UNORM_BLOCK")):
|
||||
bb = {"bc1": 8, "bc3": 16, "bc7": 16, "bc6h": 16, "etc2_rgba": 16, "etc2_rgb": 8, "eac_rg11": 16}[kind]
|
||||
data = bytes(rng.getrandbits(8) for _ in range(4 * 2 * bb))
|
||||
raw("k2_raw_" + vk.lower(), vk, data, None, kind, 13, 7)
|
||||
# KTX1
|
||||
run("toktx --genmipmap k1_mips.ktx sq.png")
|
||||
run("toktx k1_rgba.ktx a.png")
|
||||
run("toktx --cubemap k1_cube.ktx %s" % fl)
|
||||
run("ktx2ktx2 -o k1_mips_as2.ktx2 k1_mips.ktx")
|
||||
run("ktx extract --level all k1_mips_as2.ktx2 k1mips")
|
||||
ctx.nix("ktx-tools", ["sh", "-c", "cd %s && %s" % (work, " && ".join(sh))])
|
||||
ctx.nix("nvidia-texture-tools", ["sh", "-c", "cd %s && nvcompress -silent -ktx -bc1 a.png n_bc1.ktx && nvcompress -silent -ktx -bc3 a.png n_bc3.ktx && nvcompress -silent -ktx -bc7 -nomips a.png n_bc7.ktx" % work])
|
||||
|
||||
def rd(n):
|
||||
return open(os.path.join(work, n), "rb").read()
|
||||
|
||||
def surf(level, layer, s, w, h, rgba=None, floats=None, tol=0):
|
||||
d = {"level": level, "layer": layer, "slice": s, "w": w, "h": h, "tol": tol}
|
||||
if rgba is not None:
|
||||
d["rgba"] = rgba
|
||||
if floats is not None:
|
||||
d["floats"] = floats
|
||||
return d
|
||||
|
||||
aw, ah, apx = srcs["a"]
|
||||
sw, shh, spx = srcs["sq"]
|
||||
cases.append({"name": "k2_rgba8.ktx2", "data": rd("k2_rgba8.ktx2"), "layout": "2d", "surfaces": [surf(0, 0, 0, aw, ah, apx)]})
|
||||
mip_files = sorted(f for f in os.listdir(work) if f.startswith("k2mips") or f.startswith("output_level"))
|
||||
mips = []
|
||||
lw = sw
|
||||
level = 0
|
||||
while True:
|
||||
p = os.path.join(work, "k2mips_level%d.png" % level)
|
||||
if not os.path.exists(p):
|
||||
p = os.path.join(work, "k2mips", "output_level%d.png" % level)
|
||||
if not os.path.exists(p):
|
||||
break
|
||||
mips.append((level, p))
|
||||
level += 1
|
||||
if not mips:
|
||||
raise RuntimeError("ktx extract wrote no mip levels: %r" % os.listdir(work))
|
||||
pngs = read_png(ctx, [p for _, p in mips])
|
||||
msurf = [surf(lv, 0, 0, max(1, sw >> lv), max(1, shh >> lv), px) for (lv, _), px in zip(mips, pngs)]
|
||||
cases.append({"name": "k2_srgb_mips.ktx2", "data": rd("k2_srgb_mips.ktx2"), "layout": "2d", "mips": len(mips), "srgb": True, "surfaces": msurf})
|
||||
cases.append({"name": "k2_zstd.ktx2", "data": rd("k2_zstd.ktx2"), "layout": "2d", "mips": len(mips), "surfaces": msurf})
|
||||
csurf = [surf(0, i, 0, 16, 16, faces[i]) for i in range(6)]
|
||||
cases.append({"name": "k2_cube.ktx2", "data": rd("k2_cube.ktx2"), "layout": "cube", "surfaces": csurf})
|
||||
cases.append({"name": "k2_zlib.ktx2", "data": rd("k2_zlib.ktx2"), "layout": "cube", "surfaces": csurf})
|
||||
cases.append({"name": "k2_array.ktx2", "data": rd("k2_array.ktx2"), "layout": "array", "surfaces": [surf(0, i, 0, 16, 16, faces[i]) for i in range(3)]})
|
||||
opaque = bytes(v if i % 4 != 3 else 255 for i, v in enumerate(apx))
|
||||
cases.append({"name": "k2_rgb8.ktx2", "data": rd("k2_rgb8.ktx2"), "layout": "2d", "surfaces": [surf(0, 0, 0, aw, ah, opaque)]})
|
||||
cases.append({"name": "k2_basis.ktx2", "data": rd("k2_basis.ktx2"), "unsupported": True, "surfaces": []})
|
||||
cases.append({"name": "k2_uastc.ktx2", "data": rd("k2_uastc.ktx2"), "unsupported": True, "surfaces": []})
|
||||
pil, pil_t, gd, gd_t = [], [], [], []
|
||||
for (name, texels, block, w, h, data) in raws:
|
||||
c = {"name": name + ".ktx2", "data": rd(name + ".ktx2"), "layout": "volume" if name.endswith("3d") else "2d"}
|
||||
if texels is not None:
|
||||
c["surfaces"] = [surf(0, 0, 0, w, h, bytes(q8(v) for t in texels for v in t), b"".join(struct.pack("<4f", *t) for t in texels), 1)]
|
||||
elif block is None:
|
||||
c["surfaces"] = [surf(0, 0, s, w, h, data[s * w * h * 4:(s + 1) * w * h * 4]) for s in range(3)]
|
||||
else:
|
||||
sd = surf(0, 0, 0, w, h)
|
||||
c["surfaces"] = [sd]
|
||||
if block.startswith("bc") and block != "bc6h":
|
||||
dx = {"bc1": 71, "bc3": 77, "bc7": 98}[block]
|
||||
pil.append(R.dds_dx10(w, h, dx, data))
|
||||
pil_t.append((sd, "RGB_UNORM" in name.upper()))
|
||||
else:
|
||||
gd.append((data, w, h, R.GODOT[block], block == "bc6h"))
|
||||
gd_t.append((sd, block))
|
||||
cases.append(c)
|
||||
for (sd, opaque_), (mode, w, h, rw) in zip(pil_t, R.pillow(ctx, pil)):
|
||||
px = R.rgba_from(mode, rw)
|
||||
if opaque_:
|
||||
px = bytes(v if i % 4 != 3 else 255 for i, v in enumerate(px))
|
||||
sd["rgba"] = px
|
||||
for (sd, block), out in zip(gd_t, R.godot(ctx, gd)):
|
||||
if block == "bc6h":
|
||||
sd["floats"] = out
|
||||
elif block == "eac_rg11":
|
||||
sd["rgba"] = bytes(v if i % 4 < 2 else (255 if i % 4 == 3 else 0) for i, v in enumerate(out))
|
||||
sd["tol"] = 1
|
||||
else:
|
||||
sd["rgba"] = out
|
||||
# KTX1
|
||||
k1 = []
|
||||
level = 0
|
||||
while True:
|
||||
p = os.path.join(work, "k1mips_level%d.png" % level)
|
||||
if not os.path.exists(p):
|
||||
p = os.path.join(work, "k1mips", "output_level%d.png" % level)
|
||||
if not os.path.exists(p):
|
||||
break
|
||||
k1.append(p)
|
||||
level += 1
|
||||
k1png = read_png(ctx, k1)
|
||||
cases.append({"name": "k1_mips.ktx", "data": rd("k1_mips.ktx"), "layout": "2d", "mips": len(k1),
|
||||
"surfaces": [surf(lv, 0, 0, max(1, sw >> lv), max(1, shh >> lv), px) for lv, px in enumerate(k1png)]})
|
||||
cases.append({"name": "k1_rgba.ktx", "data": rd("k1_rgba.ktx"), "layout": "2d", "surfaces": [surf(0, 0, 0, aw, ah, apx)]})
|
||||
cases.append({"name": "k1_cube.ktx", "data": rd("k1_cube.ktx"), "layout": "cube",
|
||||
"surfaces": [surf(0, i, 0, 16, 16, faces[i]) for i in range(6)]})
|
||||
# nvcompress KTX1: the level-0 blocks follow the 64-byte header + key / value data + imageSize
|
||||
nv = []
|
||||
for n, dx in (("n_bc1.ktx", 71), ("n_bc3.ktx", 77), ("n_bc7.ktx", 98)):
|
||||
d = rd(n)
|
||||
kvb = struct.unpack("<I", d[60:64])[0]
|
||||
off = 64 + kvb + 4
|
||||
size = struct.unpack("<I", d[off - 4:off])[0]
|
||||
nv.append((n, d, R.dds_dx10(aw, ah, dx, d[off:off + size])))
|
||||
for (n, d, dds), (mode, w, h, rw) in zip(nv, R.pillow(ctx, [x[2] for x in nv])):
|
||||
px = R.rgba_from(mode, rw)
|
||||
if n == "n_bc1.ktx":
|
||||
px = bytes(v if i % 4 != 3 else 255 for i, v in enumerate(px)) # GL_COMPRESSED_RGB_S3TC_DXT1
|
||||
cases.append({"name": n, "data": d, "layout": "2d", "surfaces": [surf(0, 0, 0, aw, ah, px)]})
|
||||
# hand-written KTX1: big-endian 16-bit RGBA, GL_UNSIGNED_SHORT_5_6_5, RGB8 with row padding and T=u orientation
|
||||
def ktx1(gltype, typesize, glformat, internal, base, w, h, image, be=False, kv=b""):
|
||||
f = ">" if be else "<"
|
||||
hdr = b"\xabKTX 11\xbb\r\n\x1a\n" + struct.pack(f + "13I", 0x04030201, gltype, typesize, glformat, internal, base, w, h, 0, 0, 1, 1, len(kv))
|
||||
return hdr + kv + struct.pack(f + "I", len(image)) + image
|
||||
W2, H2 = 5, 3
|
||||
v16 = [tuple(rng.randrange(65536) for _ in range(4)) for _ in range(W2 * H2)]
|
||||
img = b"".join(struct.pack(">4H", *v) for v in v16) + b"\0" * 0 # rows of 40 bytes: already 4-aligned
|
||||
cases.append({"name": "hand big-endian RGBA16", "data": ktx1(0x1403, 2, 0x1908, 0x805B, 0x1908, W2, H2, img, True), "layout": "2d",
|
||||
"surfaces": [surf(0, 0, 0, W2, H2, bytes(q8(x / 65535) for v in v16 for x in v), b"".join(struct.pack("<4f", *(x / 65535 for x in v)) for v in v16), 1)]})
|
||||
p565 = [rng.getrandbits(16) for _ in range(W2 * H2)]
|
||||
rows = b"".join(b"".join(struct.pack("<H", p565[y * W2 + x]) for x in range(W2)) + b"\0\0" for y in range(H2))
|
||||
cases.append({"name": "hand RGB 5_6_5 (row padding)", "data": ktx1(0x8363, 2, 0x1907, 0x8D62, 0x1907, W2, H2, rows), "layout": "2d",
|
||||
"surfaces": [surf(0, 0, 0, W2, H2, bytes(q8(v) for p in p565 for v in ((p >> 11) / 31, ((p >> 5) & 63) / 63, (p & 31) / 31, 1.0)), None, 1)]})
|
||||
rgb = bytes(rng.randrange(256) for _ in range(W2 * H2 * 3))
|
||||
rows = b"".join(rgb[y * W2 * 3:(y + 1) * W2 * 3] + b"\0" for y in range(H2))
|
||||
kv = b"KTXorientation\0S=r,T=u\0"
|
||||
kv = struct.pack("<I", len(kv)) + kv + b"\0" * ((4 - len(kv) % 4) % 4)
|
||||
flipped = b"".join(rgb[(H2 - 1 - y) * W2 * 3 + x * 3:(H2 - 1 - y) * W2 * 3 + x * 3 + 3] + b"\xff" for y in range(H2) for x in range(W2))
|
||||
cases.append({"name": "hand RGB8 T=u", "data": ktx1(0x1401, 1, 0x1907, 0x8051, 0x1907, W2, H2, rows, False, kv), "layout": "2d",
|
||||
"surfaces": [surf(0, 0, 0, W2, H2, flipped)]})
|
||||
return cases
|
||||
|
||||
|
||||
def _ours(ctx, work):
|
||||
exe = shutil.which("luau")
|
||||
cmd = [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]
|
||||
res = subprocess.run(cmd + ["tools/fixtures/_tex_encode.luau", "-a", "ktx"], cwd=ctx.root, capture_output=True, check=True)
|
||||
files = {}
|
||||
for line in res.stdout.decode().split("\n"):
|
||||
if "\t" in line:
|
||||
n, hx = line.split("\t", 1)
|
||||
files[n] = bytes.fromhex(hx.strip())
|
||||
names = sorted(files)
|
||||
sh = []
|
||||
for n in names:
|
||||
open(os.path.join(work, n), "wb").write(files[n])
|
||||
base = n[:-5]
|
||||
sh.append("(ktx validate %s > %s.val 2>&1; echo $? > %s.rc)" % (n, base, base))
|
||||
sh.append("(ktx extract %s %s.x > /dev/null 2>&1 || true)" % (n, base))
|
||||
ctx.nix("ktx-tools", ["sh", "-c", "cd %s && %s" % (work, " ; ".join(sh))])
|
||||
out = []
|
||||
pngs, idx = [], []
|
||||
for i, n in enumerate(names):
|
||||
base = n[:-5]
|
||||
rc = open(os.path.join(work, base + ".rc")).read().strip()
|
||||
e = {"name": n, "data": files[n], "valid": rc == "0", "report": open(os.path.join(work, base + ".val"), "rb").read()[:2000]}
|
||||
for ext in (".x", ".x.png", ".x.exr"):
|
||||
p = os.path.join(work, base + ext)
|
||||
if os.path.exists(p) and os.path.isfile(p):
|
||||
e["extracted"] = open(p, "rb").read()[:8]
|
||||
if open(p, "rb").read(4) == b"\x89PNG":
|
||||
pngs.append(p)
|
||||
idx.append(i)
|
||||
out.append(e)
|
||||
for i, (mode, w, h, raw) in zip(idx, R.pillow(ctx, [open(p, "rb").read() for p in pngs])):
|
||||
if mode in ("RGBA", "RGB", "L", "LA"):
|
||||
out[i]["png"] = R.rgba_from(mode, raw)
|
||||
return out
|
||||
@@ -0,0 +1,95 @@
|
||||
# OpenRaster fixtures (tools/fixtures.py): ORA files assembled here by the specification (python zipfile, the stored
|
||||
# mimetype first, stack.xml, Pillow-written PNG layers, mergedimage.png, a thumbnail): plain layers with offsets /
|
||||
# opacity / hidden / composite-ops, nested stacks (isolate and auto), a file without mergedimage; and our encoder's
|
||||
# file (tools/fixtures/_tex_encode.luau -a ora) taken apart by python (zip order and method, stack.xml, PNG pixels
|
||||
# through Pillow). References: the layer attributes and source pixels written here.
|
||||
# tests/gen/ora.luau { cases = { { name, data, w, h, layers (bottom to top, depth-first) = { { name, x, y, opacity,
|
||||
# visible, blend, depth, rgba?, w?, h? } }, merged? } }, ours = { ok, entries, layers } }
|
||||
import importlib.util, io, os, struct, xml.etree.ElementTree as ET, zipfile
|
||||
|
||||
def _load(n):
|
||||
spec = importlib.util.spec_from_file_location(n, os.path.join(os.path.dirname(os.path.abspath(__file__)), n + ".py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
R, S, T = _load("_raster_ref"), _load("_simple"), _load("_tex_reference")
|
||||
INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/layered/ora"]
|
||||
OPS = {"svg:src-over": "normal", "svg:multiply": "multiply", "svg:screen": "screen", "svg:overlay": "overlay", "svg:color-dodge": "colorDodge"}
|
||||
|
||||
|
||||
def build(stack_xml, pngs, merged=True, w=40, h=30):
|
||||
buf = io.BytesIO()
|
||||
z = zipfile.ZipFile(buf, "w")
|
||||
z.writestr(zipfile.ZipInfo("mimetype"), "image/openraster", compress_type=zipfile.ZIP_STORED)
|
||||
z.writestr("stack.xml", stack_xml, compress_type=zipfile.ZIP_DEFLATED)
|
||||
for n, d in pngs.items():
|
||||
z.writestr(n, d, compress_type=zipfile.ZIP_STORED)
|
||||
if merged:
|
||||
z.writestr("mergedimage.png", R.png(w, h, bytes(w * h * 4)), compress_type=zipfile.ZIP_STORED)
|
||||
z.close()
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
cases = []
|
||||
imgs = {}
|
||||
for i, (w, h) in enumerate(((40, 30), (20, 10), (8, 8), (10, 12), (6, 5))):
|
||||
imgs["data/l%d.png" % i] = (w, h, R.photo(w, h, i + 1, i > 0))
|
||||
pngs = {k: R.png(*v) for k, v in imgs.items()}
|
||||
|
||||
def lay(src, name, x, y, op, vis, depth):
|
||||
w, h, px = imgs[src]
|
||||
return {"name": name, "x": x, "y": y, "opacity": op[0], "visible": vis, "blend": op[1], "depth": depth, "rgba": px, "w": w, "h": h}
|
||||
|
||||
xml1 = '''<?xml version="1.0" encoding="UTF-8"?>
|
||||
<image version="0.0.6" w="40" h="30" xres="144" yres="144"><stack>
|
||||
<layer name="top hidden" src="data/l2.png" x="1" y="2" visibility="hidden" opacity="1.0"/>
|
||||
<layer name="mid" src="data/l1.png" x="5" y="7" opacity="0.5" composite-op="svg:multiply"/>
|
||||
<layer name="background" src="data/l0.png"/>
|
||||
</stack></image>'''
|
||||
cases.append({"name": "plain", "data": build(xml1, pngs), "w": 40, "h": 30, "dpi": 144, "merged": True, "layers": [
|
||||
lay("data/l0.png", "background", 0, 0, (1.0, "normal"), True, 0), lay("data/l1.png", "mid", 5, 7, (0.5, "multiply"), True, 0),
|
||||
lay("data/l2.png", "top hidden", 1, 2, (1.0, "normal"), False, 0)]})
|
||||
xml2 = '''<image w="40" h="30"><stack>
|
||||
<stack name="outer" isolation="isolate" opacity="0.8" x="2" y="3">
|
||||
<layer name="a" src="data/l3.png" x="1" y="1" composite-op="svg:screen"/>
|
||||
<stack name="inner" opacity="0.5"><layer name="b" src="data/l4.png" composite-op="svg:color-dodge"/></stack>
|
||||
</stack>
|
||||
<layer name="base" src="data/l0.png"/>
|
||||
</stack></image>'''
|
||||
cases.append({"name": "nested", "data": build(xml2, pngs, merged=False), "w": 40, "h": 30, "merged": False, "layers": [
|
||||
lay("data/l0.png", "base", 0, 0, (1.0, "normal"), True, 0),
|
||||
{"name": "outer", "x": 0, "y": 0, "opacity": 0.8, "visible": True, "blend": "normal", "depth": 0, "group": True},
|
||||
{"name": "inner", "x": 0, "y": 0, "opacity": 0.5, "visible": True, "blend": "passThrough", "depth": 1, "group": True},
|
||||
lay("data/l4.png", "b", 2, 3, (1.0, "colorDodge"), True, 2),
|
||||
lay("data/l3.png", "a", 3, 4, (1.0, "screen"), True, 1)]})
|
||||
# ours, taken apart
|
||||
mine = S.ours(ctx, "ora")["ours_doc.ora"]
|
||||
z = zipfile.ZipFile(io.BytesIO(mine))
|
||||
infos = z.infolist()
|
||||
ok = infos[0].filename == "mimetype" and infos[0].compress_type == zipfile.ZIP_STORED and z.read("mimetype") == b"image/openraster"
|
||||
root = ET.fromstring(z.read("stack.xml"))
|
||||
layers = []
|
||||
|
||||
def walk(node, depth):
|
||||
for ch in node:
|
||||
a = ch.attrib
|
||||
e = {"tag": ch.tag, "name": a.get("name", ""), "depth": depth, "opacity": float(a.get("opacity", "1")),
|
||||
"visible": a.get("visibility", "visible") == "visible", "op": a.get("composite-op", ""), "isolation": a.get("isolation", "")}
|
||||
if ch.tag == "layer":
|
||||
e["x"], e["y"] = int(a.get("x", "0")), int(a.get("y", "0"))
|
||||
e["src"] = a["src"]
|
||||
layers.append(e)
|
||||
if ch.tag == "stack":
|
||||
walk(ch, depth + 1)
|
||||
walk(root.find("stack"), 0)
|
||||
srcs = [l["src"] for l in layers if l["tag"] == "layer"] + ["mergedimage.png", "Thumbnails/thumbnail.png"]
|
||||
decoded = T.pillow(ctx, [z.read(s) for s in srcs])
|
||||
px = {s: {"w": d[1], "h": d[2], "rgba": T.rgba_from(d[0], d[3])} for s, d in zip(srcs, decoded)}
|
||||
for l in layers:
|
||||
if l["tag"] == "layer":
|
||||
l.update(px[l["src"]])
|
||||
ours = {"data": mine, "ok": ok, "w": int(root.attrib["w"]), "h": int(root.attrib["h"]), "entries": [i.filename for i in infos],
|
||||
"layers": layers, "merged": px["mergedimage.png"], "thumb": [px["Thumbnails/thumbnail.png"]["w"], px["Thumbnails/thumbnail.png"]["h"]]}
|
||||
ctx.emit("ora", {"cases": cases, "ours": ours})
|
||||
@@ -0,0 +1,58 @@
|
||||
# PCX fixtures (tools/fixtures.py): files from netpbm's ppmtopcx (24-bit planes, 8-bit palette, packed 1 / 2 / 4-bit,
|
||||
# 4-plane EGA, 1-bit mono), ImageMagick (24-bit, palette) and Pillow (RGB, P, L, 1), decoded by pcxtoppm (netpbm) as
|
||||
# the reference; our encoder's files (tools/fixtures/_tex_encode.luau -a pcx) decoded by ImageMagick (it reads 4-plane alpha).
|
||||
# tests/gen/pcx.luau { cases = { { name, data, w, h, rgba } }, ours = { { name, data, w, h, rgba } } }
|
||||
import importlib.util, os, shutil, subprocess
|
||||
|
||||
_spec = importlib.util.spec_from_file_location("_raster_ref", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_raster_ref.py"))
|
||||
R = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(R)
|
||||
|
||||
INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/pcx"]
|
||||
|
||||
|
||||
def ours(ctx, which):
|
||||
exe = shutil.which("luau")
|
||||
cmd = [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]
|
||||
res = subprocess.run(cmd + ["tools/fixtures/_tex_encode.luau", "-a", which], cwd=ctx.root, capture_output=True, check=True)
|
||||
files = {}
|
||||
for line in res.stdout.decode().split("\n"):
|
||||
if line.startswith("ours_") and "\t" in line:
|
||||
n, hx = line.split("\t", 1)
|
||||
files[n] = bytes.fromhex(hx.strip())
|
||||
return files
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
w = R.Work(ctx)
|
||||
try:
|
||||
w.png("photo.png", 37, 23, R.photo(37, 23))
|
||||
w.png("pal.png", 40, 30, R.palette_image(40, 30, 200))
|
||||
w.png("c16.png", 33, 17, R.palette_image(33, 17, 16, 5))
|
||||
w.png("c4.png", 21, 9, R.palette_image(21, 9, 4, 6))
|
||||
w.png("mono.png", 29, 13, bytes(v for i in range(29 * 13) for v in ((255,) * 3 if (i * 7) % 5 < 2 else (0,) * 3) + (255,)))
|
||||
nb = ["pngtopam photo.png | pamtopnm > photo.ppm", "pngtopam pal.png | pamtopnm > pal.ppm", "pngtopam c16.png | pamtopnm > c16.ppm",
|
||||
"pngtopam c4.png | pamtopnm > c4.ppm", "pngtopam mono.png | pamtopnm | ppmtopgm | pgmtopbm > mono.pbm",
|
||||
"ppmtopcx -24bit photo.ppm > nb_24bit.pcx", "ppmtopcx -8bit pal.ppm > nb_8bit.pcx", "ppmtopcx -packed c16.ppm > nb_packed4.pcx",
|
||||
"ppmtopcx -packed c4.ppm > nb_packed2.pcx", "ppmtopcx -planes 4 c16.ppm > nb_planes4.pcx", "ppmtopcx mono.pbm > nb_mono.pcx",
|
||||
"ppmtopcx -planes 3 c4.ppm > nb_planes3.pcx"]
|
||||
w.sh("netpbm", nb)
|
||||
w.sh("imagemagick", ["magick photo.png -alpha off im_24bit.pcx", "magick pal.png -alpha off -type palette im_palette.pcx"])
|
||||
code = ("from PIL import Image\nimport os\nos.chdir(%r)\nim=Image.open('photo.png').convert('RGB')\nim.save('pil_rgb.pcx')\n"
|
||||
"Image.open('pal.png').convert('RGB').quantize(256).save('pil_p.pcx')\nim.convert('L').save('pil_l.pcx')\n"
|
||||
"Image.open('mono.png').convert('1').save('pil_1.pcx')\n") % w.dir
|
||||
ctx.python(["pillow"], code)
|
||||
names = sorted(f for f in os.listdir(w.dir) if f.endswith(".pcx"))
|
||||
mine = ours(ctx, "pcx")
|
||||
for n, d in mine.items():
|
||||
w.write(n, d)
|
||||
allnames = names + sorted(mine)
|
||||
w.sh("netpbm", ["pcxtoppm %s > %s.ppm" % (n, n) for n in names])
|
||||
w.sh("imagemagick", ["magick %s -depth 8 pam:%s.ppm" % (n, n) for n in sorted(mine)])
|
||||
cases, our = [], []
|
||||
for n in allnames:
|
||||
ww, hh, rgba = R.pnm_rgba(w.read(n + ".ppm"))
|
||||
(our if n.startswith("ours_") else cases).append({"name": n, "data": w.read(n), "w": ww, "h": hh, "rgba": rgba})
|
||||
ctx.emit("pcx", {"cases": cases, "ours": our})
|
||||
finally:
|
||||
w.close()
|
||||
@@ -0,0 +1,39 @@
|
||||
# SGI fixtures (tools/fixtures.py): files from netpbm (pnmtosgi: RLE and verbatim, RGB and grey), ImageMagick (RGB,
|
||||
# RGBA, 16-bit) and Pillow (L, RGB, RGBA), plus our encoder's files (tools/fixtures/_tex_encode.luau -a sgi); the
|
||||
# reference is ImageMagick's decode of each file (16-bit within 1: it rounds where we keep the high byte).
|
||||
# tests/gen/sgi.luau { cases = { { name, data, w, h, rgba, tol } }, ours = { ... } }
|
||||
import importlib.util, os
|
||||
|
||||
def _load(n):
|
||||
spec = importlib.util.spec_from_file_location(n, os.path.join(os.path.dirname(os.path.abspath(__file__)), n + ".py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
R, S = _load("_raster_ref"), _load("_simple")
|
||||
INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/sgi"]
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
w = R.Work(ctx)
|
||||
try:
|
||||
w.png("photo.png", 37, 23, R.photo(37, 23))
|
||||
w.png("alpha.png", 30, 17, R.photo(30, 17, 3, True))
|
||||
w.sh("netpbm", ["pngtopam photo.png | pamtopnm > photo.ppm", "pnmtosgi -rle photo.ppm > nb_rle.sgi", "pnmtosgi -verbatim photo.ppm > nb_verbatim.sgi",
|
||||
"ppmtopgm photo.ppm | pnmtosgi -rle > nb_grey.sgi"])
|
||||
w.sh("imagemagick", ["magick photo.png -alpha off im_rgb.sgi", "magick alpha.png im_rgba.sgi", "magick photo.png -alpha off -depth 16 im_rgb16.sgi",
|
||||
"magick alpha.png -compress none im_rgba_verbatim.sgi"])
|
||||
ctx.python(["pillow"], ("from PIL import Image\nimport os\nos.chdir(%r)\nim=Image.open('alpha.png')\nim.save('pil_rgba.sgi')\n"
|
||||
"im.convert('RGB').save('pil_rgb.sgi')\nim.convert('L').save('pil_l.sgi')\n") % w.dir)
|
||||
names = sorted(f for f in os.listdir(w.dir) if f.endswith(".sgi"))
|
||||
mine = S.ours(ctx, "sgi")
|
||||
for n, d in mine.items():
|
||||
w.write(n, d)
|
||||
ref = S.magick_cases(R, w, names + sorted(mine))
|
||||
out = {"cases": [], "ours": []}
|
||||
for n in names + sorted(mine):
|
||||
ww, hh, rgba = ref[n]
|
||||
out["ours" if n.startswith("ours_") else "cases"].append({"name": n, "data": w.read(n), "w": ww, "h": hh, "rgba": rgba, "tol": 1 if "16" in n else 0})
|
||||
ctx.emit("sgi", out)
|
||||
finally:
|
||||
w.close()
|
||||
@@ -0,0 +1,45 @@
|
||||
# Sun Raster fixtures (tools/fixtures.py): files from netpbm (pnmtorast: standard and byte-encoded, 1 / 8 / 24-bit) and
|
||||
# ImageMagick (24-bit, 32-bit with alpha, 8-bit palette, 1-bit), plus our encoder's files (tools/fixtures/_tex_encode
|
||||
# .luau -a sunras); the reference is rasttopnm for netpbm's and our files (RGB only) and ImageMagick's decode for the others.
|
||||
# tests/gen/sunras.luau { cases = { { name, data, w, h, rgba } }, ours = { ... } }
|
||||
import importlib.util, os
|
||||
|
||||
def _load(n):
|
||||
spec = importlib.util.spec_from_file_location(n, os.path.join(os.path.dirname(os.path.abspath(__file__)), n + ".py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
R, S = _load("_raster_ref"), _load("_simple")
|
||||
INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/sunras"]
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
w = R.Work(ctx)
|
||||
try:
|
||||
w.png("photo.png", 37, 23, R.photo(37, 23))
|
||||
w.png("pal.png", 31, 19, R.palette_image(31, 19, 40))
|
||||
w.png("alpha.png", 30, 17, R.photo(30, 17, 3, True))
|
||||
w.sh("netpbm", ["pngtopam photo.png | pamtopnm > photo.ppm", "pngtopam pal.png | pamtopnm > pal.ppm",
|
||||
"pnmtorast -standard photo.ppm > nb_24_standard.ras", "pnmtorast -rle photo.ppm > nb_24_rle.ras",
|
||||
"pnmtorast -rle pal.ppm > nb_8_rle.ras", "ppmtopgm photo.ppm | pnmtorast -standard > nb_grey.ras",
|
||||
"ppmtopgm photo.ppm | pgmtopbm | pnmtorast -rle > nb_1.ras"])
|
||||
w.sh("imagemagick", ["magick photo.png -alpha off im_24.ras", "magick alpha.png im_32.ras", "magick pal.png -alpha off -type palette im_8.ras",
|
||||
"magick photo.png -monochrome im_1.ras"])
|
||||
names = sorted(f for f in os.listdir(w.dir) if f.endswith(".ras"))
|
||||
mine = S.ours(ctx, "sunras")
|
||||
for n, d in mine.items():
|
||||
w.write(n, d)
|
||||
# netpbm's own files through rasttopnm (ImageMagick cuts the last row of nb_8_rle short), the rest through ImageMagick
|
||||
nb = [n for n in names if n.startswith("nb_")] + sorted(mine)
|
||||
w.sh("netpbm", ["rasttopnm %s > %s.pnm" % (n, n) for n in nb])
|
||||
ref = S.magick_cases(R, w, [n for n in names if not n.startswith("nb_")], "sun")
|
||||
for n in nb:
|
||||
ref[n] = R.pnm_rgba(w.read(n + ".pnm"))
|
||||
out = {"cases": [], "ours": []}
|
||||
for n in names + sorted(mine):
|
||||
ww, hh, rgba = ref[n]
|
||||
out["ours" if n.startswith("ours_") else "cases"].append({"name": n, "data": w.read(n), "w": ww, "h": hh, "rgba": rgba})
|
||||
ctx.emit("sunras", out)
|
||||
finally:
|
||||
w.close()
|
||||
@@ -0,0 +1,43 @@
|
||||
# XBM fixtures (tools/fixtures.py): files from netpbm (pbmtoxbm X11 and -x10), ImageMagick and Pillow (with a hotspot),
|
||||
# a hand-written one (comments, odd spacing); the reference is xbmtopbm (netpbm); our encoder's files
|
||||
# (tools/fixtures/_tex_encode.luau -a xbm) read by xbmtopbm.
|
||||
# tests/gen/xbm.luau { cases = { { name, data, w, h, rgba, hotspot? } }, ours = { ... } }
|
||||
import importlib.util, os
|
||||
|
||||
def _load(n):
|
||||
spec = importlib.util.spec_from_file_location(n, os.path.join(os.path.dirname(os.path.abspath(__file__)), n + ".py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
R, S = _load("_raster_ref"), _load("_simple")
|
||||
INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/xbm"]
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
w = R.Work(ctx)
|
||||
try:
|
||||
mono = bytes(v for i in range(29 * 13) for v in ((0,) * 3 if (i * 7 + i // 29) % 5 < 2 else (255,) * 3) + (255,))
|
||||
w.png("mono.png", 29, 13, mono)
|
||||
w.png("mono2.png", 16, 9, bytes(v for i in range(16 * 9) for v in ((0,) * 3 if (i % 3 == 0) else (255,) * 3) + (255,)))
|
||||
w.sh("netpbm", ["pngtopam mono.png | pamtopnm | ppmtopgm | pgmtopbm -threshold > mono.pbm", "pbmtoxbm mono.pbm > nb_x11.xbm",
|
||||
"pbmtoxbm -x10 mono.pbm > nb_x10.xbm"])
|
||||
w.sh("imagemagick", ["magick mono2.png im.xbm"])
|
||||
ctx.python(["pillow"], "from PIL import Image\nimport os\nos.chdir(%r)\nImage.open('mono.png').convert('1').save('pil.xbm', hotspot=(3, 4))\n" % w.dir)
|
||||
w.write("hand.xbm", b"/* a comment */\n#define hand_width 10\n#define hand_height 2\nstatic unsigned char hand_bits[] = {\n 0xff,0x03, /* row 0 */\n 0x00, 0x01 };\n")
|
||||
names = sorted(f for f in os.listdir(w.dir) if f.endswith(".xbm"))
|
||||
mine = S.ours(ctx, "xbm")
|
||||
for n, d in mine.items():
|
||||
w.write(n, d)
|
||||
allnames = names + sorted(mine)
|
||||
w.sh("netpbm", ["xbmtopbm %s > %s.pbm" % (n, n) for n in allnames])
|
||||
out = {"cases": [], "ours": []}
|
||||
for n in allnames:
|
||||
ww, hh, rgba = R.pnm_rgba(w.read(n + ".pbm"))
|
||||
c = {"name": n, "data": w.read(n), "w": ww, "h": hh, "rgba": rgba}
|
||||
if n == "pil.xbm":
|
||||
c["hotspot"] = [3, 4]
|
||||
out["ours" if n.startswith("ours_") else "cases"].append(c)
|
||||
ctx.emit("xbm", out)
|
||||
finally:
|
||||
w.close()
|
||||
@@ -0,0 +1,58 @@
|
||||
# XPM fixtures (tools/fixtures.py): files from netpbm (ppmtoxpm -hexonly), ImageMagick (with alpha: None) and
|
||||
# hand-written ones (colour names, #RGB / #RRRRGGGGBBBB, g / m keys, two chars per pixel, XPM 2); the reference is
|
||||
# ImageMagick's decode (the XPM 2 file's values are written here: ImageMagick does not read XPM 2); our encoder's files (tools/fixtures/_tex_encode.luau -a xpm) read by ImageMagick.
|
||||
# tests/gen/xpm.luau { cases = { { name, data, w, h, rgba } }, ours = { ... } }
|
||||
import importlib.util, os
|
||||
|
||||
def _load(n):
|
||||
spec = importlib.util.spec_from_file_location(n, os.path.join(os.path.dirname(os.path.abspath(__file__)), n + ".py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
R, S = _load("_raster_ref"), _load("_simple")
|
||||
INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/xpm"]
|
||||
|
||||
HAND = b'''/* XPM */
|
||||
static char * hand_xpm[] = {
|
||||
/* width height ncolors cpp */
|
||||
"6 4 6 2",
|
||||
" c None",
|
||||
".. c red",
|
||||
"XX g4 #888 c LightBlue m white",
|
||||
"oo c #FFFF00000000",
|
||||
"++ s mine c navy",
|
||||
"@@ c Gold",
|
||||
" ..XXoo++@@",
|
||||
"..XXoo++@@ ",
|
||||
"XXoo++@@ ..",
|
||||
"oo++@@ ..XX"};
|
||||
'''
|
||||
XPM2 = b"! XPM2\n3 2 2 1\na c #102030\nb c white\nabb\nbab\n"
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
w = R.Work(ctx)
|
||||
try:
|
||||
w.png("pal.png", 31, 19, R.palette_image(31, 19, 40))
|
||||
w.png("alpha.png", 20, 11, bytes(v for i in range(20 * 11) for v in (((i * 40) % 256, 80, 200, 255 if i % 3 else 0))))
|
||||
w.sh("netpbm", ["pngtopam pal.png | pamtopnm > pal.ppm", "ppmtoxpm -hexonly pal.ppm > nb.xpm"])
|
||||
w.sh("imagemagick", ["magick pal.png -alpha off im.xpm", "magick alpha.png im_alpha.xpm"])
|
||||
w.write("hand.xpm", HAND)
|
||||
w.write("hand2.xpm", XPM2)
|
||||
names = sorted(f for f in os.listdir(w.dir) if f.endswith(".xpm") and f != "hand2.xpm")
|
||||
mine = S.ours(ctx, "xpm")
|
||||
for n, d in mine.items():
|
||||
w.write(n, d)
|
||||
ref = S.magick_cases(R, w, names + sorted(mine), "xpm")
|
||||
out = {"cases": [], "ours": []}
|
||||
for n in names + sorted(mine):
|
||||
ww, hh, rgba = ref[n]
|
||||
# ImageMagick keeps the colour of transparent pixels; we decode None as transparent black
|
||||
rgba = bytes(0 if rgba[i - i % 4 + 3] == 0 else v for i, v in enumerate(rgba))
|
||||
out["ours" if n.startswith("ours_") else "cases"].append({"name": n, "data": w.read(n), "w": ww, "h": hh, "rgba": rgba})
|
||||
a, b = bytes((0x10, 0x20, 0x30, 255)), b"\xff" * 4
|
||||
out["cases"].append({"name": "hand2.xpm (XPM 2)", "data": XPM2, "w": 3, "h": 2, "rgba": a + b + b + b + a + b})
|
||||
ctx.emit("xpm", out)
|
||||
finally:
|
||||
w.close()
|
||||
Reference in new issue
Block a user