ws-3d3: codecs/model/Draco: Draco decoder (port of Google Draco 1.5.7, Apache-2.0)
Meshes (sequential; Edgebreaker standard / predictive / valence, topology splits, attribute seams) and sequential point clouds, bitstreams 1.0 - 2.2; generic / integer / quantization / octahedral normal attribute decoders; difference, parallelogram, multi and constrained multi-parallelogram, tex coords (deprecated and portable, exact int64 arithmetic) and geometric normal predictions; metadata. Byte-exact against libdraco on 196 files (Draco test data 0.9 - 2.2 and draco_encoder outputs at every level / quantization). kd-tree point clouds: UNSUPPORTED for now.
This commit is contained in:
1 parent
de4f14a343
commit
9a6ddd5c16
12 files changed
+4159
No files matched your search
@@ -124,6 +124,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain:
|
||||
- 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
|
||||
- **model**
|
||||
- codecs/model/Draco: Google Draco geometry decompression (.drc; glTF KHR_draco_mesh_compression; Roblox mesh v6 / v7).
|
||||
- codecs/model/Mat4: 4x4 matrix and quaternion helpers for the model formats: column-major flat arrays of 16
|
||||
- codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks
|
||||
- **text**
|
||||
|
||||
@@ -37,6 +37,7 @@
|
||||
| `src/Formats/codecs/Vp8/` inter frames (Decode: inter headers / modes / motion vectors / references, Predict, the inter tables in Tables) | Luau translations of libvpx 1.17 (WebM Project): vp8/decoder/decodeframe.c, decodemv.c, onyxd_if.c; vp8/common/findnearmv.c, reconinter.c, filter.c, vp8_loopfilter.c, entropymode.c, entropymv.c, modecont.c | BSD-3-Clause + patent grant: [libvpx-LICENSE.txt](libvpx-LICENSE.txt) |
|
||||
| `tests/fixtures/vp8video/vp80-*.ivf` | the VP8 test vectors of the libvpx test data (vp80-00-comprehensive-001..018 and others) | WebM Project, BSD-3-Clause + patent grant: [libvpx-LICENSE.txt](libvpx-LICENSE.txt) |
|
||||
| `src/Formats/codecs/H264/` (Tables: CAVLC / CABAC / deblocking / scaling constant tables of ITU-T H.264, extracted from openh264 sources; the decoder itself is written from the spec) | openh264 2.x (Cisco) | BSD-2-Clause: [openh264-LICENSE.txt](openh264-LICENSE.txt) |
|
||||
| `src/Formats/codecs/model/Draco/` | Luau port of the Draco 1.5.7 decoder (Google): compression/{decode, mesh, attributes, entropy, bit_coders, point_cloud}, mesh/corner_table, mesh/mesh_attribute_corner_table, core/{decoder_buffer, varint_decoding, math_utils}, attributes/attribute_{quantization,octahedron}_transform | Apache-2.0: [draco-LICENSE.txt](draco-LICENSE.txt) |
|
||||
| `tests/gen/h264_jvt` (downloaded at fixture time, not committed) | ITU-T H.264.1 / JVT conformance bitstreams (itu.int) | ITU-T test data |
|
||||
|
||||
Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
Files: docs/assets/js/ASCIIMathML.js
|
||||
|
||||
Copyright (c) 2014 Peter Jipsen and other ASCIIMathML.js contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
Files: docs/assets/css/pygments/*
|
||||
|
||||
This is free and unencumbered software released into the public domain.
|
||||
|
||||
Anyone is free to copy, modify, publish, use, compile, sell, or
|
||||
distribute this software, either in source code form or as a compiled
|
||||
binary, for any purpose, commercial or non-commercial, and by any
|
||||
means.
|
||||
|
||||
In jurisdictions that recognize copyright laws, the author or authors
|
||||
of this software dedicate any and all copyright interest in the
|
||||
software to the public domain. We make this dedication for the benefit
|
||||
of the public at large and to the detriment of our heirs and
|
||||
successors. We intend this dedication to be an overt act of
|
||||
relinquishment in perpetuity of all present and future rights to this
|
||||
software under copyright law.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
||||
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
For more information, please refer to <http://unlicense.org>
|
||||
@@ -0,0 +1,473 @@
|
||||
--!strict
|
||||
-- codecs/model/Draco/Attributes: Draco attribute decoding. The attributes decoders (one per connectivity: linear
|
||||
-- sequencer for sequential meshes and point clouds, traversal sequencers for Edgebreaker), their attribute
|
||||
-- descriptors, and the sequential attribute decoders: generic (raw values), integer, quantization (dequantized to
|
||||
-- f32 exactly like the C++) and octahedral normals; prediction through codecs/model/Draco/Predict. Bitstream
|
||||
-- versions 1.0 - 2.2. Ported from Google's Draco 1.5.7 (compression/attributes/*, compression/point_cloud/
|
||||
-- point_cloud_decoder.cc, attributes/attribute_quantization_transform.cc, attribute_octahedron_transform.cc;
|
||||
-- Apache-2.0, licenses/draco-LICENSE.txt).
|
||||
local Reader = require("@formats/codecs/model/Draco/Reader")
|
||||
local Connectivity = require("@formats/codecs/model/Draco/Connectivity")
|
||||
local Predict = require("@formats/codecs/model/Draco/Predict")
|
||||
|
||||
local Attributes = {}
|
||||
|
||||
type D = Reader.D
|
||||
|
||||
-- data type ids (draco::DataType) -> byte length
|
||||
local DT_LENGTH = { [1] = 1, [2] = 1, [3] = 2, [4] = 2, [5] = 4, [6] = 4, [7] = 8, [8] = 8, [9] = 4, [10] = 8, [11] = 1 }
|
||||
Attributes.DT_LENGTH = DT_LENGTH
|
||||
|
||||
export type Attr = {
|
||||
id: number, -- 0-based attribute id
|
||||
type: number, -- GeometryAttribute::Type (0 POSITION, 1 NORMAL, 2 COLOR, 3 TEX_COORD, 4 GENERIC, 5.. transcoder types)
|
||||
dataType: number,
|
||||
comps: number,
|
||||
normalized: boolean,
|
||||
uniqueId: number,
|
||||
seqType: number, -- 0 generic, 1 integer, 2 quantization, 3 normals
|
||||
map: { number }?, -- point -> value (0-based values at [point + 1]); nil = identity
|
||||
numValues: number,
|
||||
portable: { number }?, -- the integer (portable) values
|
||||
values: { number }?, -- the final values (numbers), flat
|
||||
raw: buffer?, -- generic attributes: the raw values
|
||||
quant: { min: { number }, range: number, bits: number }?,
|
||||
octBits: number?,
|
||||
scheme: Predict.Scheme?,
|
||||
}
|
||||
|
||||
type Decoder = {
|
||||
attrs: { Attr },
|
||||
traversal: { ct: Connectivity.CT, enc: Connectivity.Enc, method: number }?,
|
||||
md: Predict.MeshData?,
|
||||
points: { number }?,
|
||||
}
|
||||
|
||||
-- the geometry the attributes decode against
|
||||
export type Geom = { numPoints: number, mesh: Connectivity.Mesh?, edgebreaker: boolean, kdTree: boolean }
|
||||
|
||||
local function zigzag(v: number): number
|
||||
if v % 2 == 1 then
|
||||
return -(v // 2) - 1
|
||||
end
|
||||
return v // 2
|
||||
end
|
||||
|
||||
-- the parent (position) getter for a scheme: portable integers from 2.0 on, the final values before (truncated to
|
||||
-- integers unless the scheme works in floats)
|
||||
local function parentGetter(ver: number, pos: Attr, floats: boolean): Predict.Parent?
|
||||
local old = ver < 0x0200
|
||||
local vals = if old then pos.values else pos.portable
|
||||
if not vals or pos.comps ~= 3 or (not old and pos.seqType == 3) then
|
||||
return nil
|
||||
end
|
||||
local map = pos.map
|
||||
local trunc = old and not floats
|
||||
return function(point: number): (number, number, number)
|
||||
local e = if map then (map[point + 1] or 0) else point
|
||||
local o = e * 3
|
||||
local x, y, z = vals[o + 1] or 0, vals[o + 2] or 0, vals[o + 3] or 0
|
||||
if trunc then
|
||||
x = if x < 0 then math.ceil(x) else math.floor(x)
|
||||
y = if y < 0 then math.ceil(y) else math.floor(y)
|
||||
z = if z < 0 then math.ceil(z) else math.floor(z)
|
||||
end
|
||||
return x, y, z
|
||||
end
|
||||
end
|
||||
|
||||
local function decodeIntegerValues(d: D, a: Attr, points: { number }, scheme: Predict.Scheme?): (boolean, string?)
|
||||
local comps = if a.seqType == 3 then 2 else a.comps
|
||||
local n = #points
|
||||
local numValues = n * comps
|
||||
if n == 0 then
|
||||
return false, "no values"
|
||||
end
|
||||
local compressed = Reader.u8(d)
|
||||
if d.bad then
|
||||
return false, d.bad
|
||||
end
|
||||
local vals: { number }
|
||||
if compressed > 0 then
|
||||
local s = Reader.symbols(d, numValues, comps)
|
||||
if not s then
|
||||
return false, d.bad or "bad values"
|
||||
end
|
||||
vals = s
|
||||
else
|
||||
local nb = Reader.u8(d)
|
||||
if d.bad then
|
||||
return false, d.bad
|
||||
end
|
||||
if nb < 1 or nb > 4 then
|
||||
return false, "bad value byte count"
|
||||
end
|
||||
if Reader.remaining(d) < nb * numValues then
|
||||
return false, "truncated values"
|
||||
end
|
||||
vals = table.create(numValues, 0)
|
||||
local b, p = d.b, d.pos
|
||||
if nb == 4 then
|
||||
for i = 1, numValues do
|
||||
vals[i] = buffer.readu32(b, p)
|
||||
p += 4
|
||||
end
|
||||
elseif nb == 1 then
|
||||
for i = 1, numValues do
|
||||
vals[i] = buffer.readu8(b, p)
|
||||
p += 1
|
||||
end
|
||||
elseif nb == 2 then
|
||||
for i = 1, numValues do
|
||||
vals[i] = buffer.readu16(b, p)
|
||||
p += 2
|
||||
end
|
||||
else
|
||||
for i = 1, numValues do
|
||||
vals[i] = buffer.readu16(b, p) + buffer.readu8(b, p + 2) * 65536
|
||||
p += 3
|
||||
end
|
||||
end
|
||||
d.pos = p
|
||||
end
|
||||
if not scheme or not scheme.tr.positive then
|
||||
for i = 1, numValues do
|
||||
vals[i] = zigzag(vals[i])
|
||||
end
|
||||
else
|
||||
local i32 = Predict.i32
|
||||
for i = 1, numValues do
|
||||
vals[i] = i32(vals[i])
|
||||
end
|
||||
end
|
||||
if scheme then
|
||||
if not Predict.decodeData(scheme, d) then
|
||||
return false, d.bad or "bad prediction data"
|
||||
end
|
||||
local ok, err = Predict.compute(scheme, vals, n, comps, points)
|
||||
if not ok then
|
||||
return false, err
|
||||
end
|
||||
end
|
||||
a.portable = vals
|
||||
a.numValues = n
|
||||
return true, nil
|
||||
end
|
||||
|
||||
local function decodeQuantInfo(d: D, a: Attr): boolean
|
||||
local mins = table.create(a.comps, 0)
|
||||
for c = 1, a.comps do
|
||||
mins[c] = Reader.f32(d)
|
||||
end
|
||||
local range = Reader.f32(d)
|
||||
local bits = Reader.u8(d)
|
||||
if d.bad or bits < 1 or bits > 30 then
|
||||
return false
|
||||
end
|
||||
a.quant = { min = mins, range = range, bits = bits }
|
||||
return true
|
||||
end
|
||||
|
||||
-- StoreValues: integer -> the data type; quantized -> f32; octahedral -> unit vectors
|
||||
local function storeValues(a: Attr): (boolean, string?)
|
||||
local src = a.portable :: { number }
|
||||
local n = a.numValues
|
||||
local fround = Predict.fround
|
||||
if a.seqType == 1 then
|
||||
local dt = a.dataType
|
||||
local out = table.create(n * a.comps, 0)
|
||||
for i = 1, n * a.comps do
|
||||
local v = src[i]
|
||||
if dt == 1 then
|
||||
v = (v + 128) % 256 - 128
|
||||
elseif dt == 2 or dt == 11 then
|
||||
v %= 256
|
||||
elseif dt == 3 then
|
||||
v = (v + 32768) % 65536 - 32768
|
||||
elseif dt == 4 then
|
||||
v %= 65536
|
||||
elseif dt == 6 then
|
||||
v %= 4294967296
|
||||
elseif dt ~= 5 then
|
||||
return false, "unsupported: integer attribute of data type " .. dt
|
||||
end
|
||||
out[i] = v
|
||||
end
|
||||
a.values = out
|
||||
elseif a.seqType == 2 then
|
||||
local q = a.quant
|
||||
if not q then
|
||||
return false, "no quantization data"
|
||||
end
|
||||
local maxQ = 2 ^ q.bits - 1
|
||||
local delta = fround(q.range / fround(maxQ))
|
||||
local comps = a.comps
|
||||
local mins = q.min
|
||||
local out = table.create(n * comps, 0)
|
||||
local k = 1
|
||||
for _ = 1, n do
|
||||
for c = 1, comps do
|
||||
out[k] = fround(fround(fround(src[k]) * delta) + mins[c])
|
||||
k += 1
|
||||
end
|
||||
end
|
||||
a.values = out
|
||||
elseif a.seqType == 3 then
|
||||
local o = Predict.octahedron(a.octBits or 0)
|
||||
if not o then
|
||||
return false, "bad normal quantization"
|
||||
end
|
||||
local out = table.create(n * 3, 0)
|
||||
for i = 0, n - 1 do
|
||||
local x, y, z = Predict.octToVector(o, src[i * 2 + 1], src[i * 2 + 2])
|
||||
out[i * 3 + 1], out[i * 3 + 2], out[i * 3 + 3] = x, y, z
|
||||
end
|
||||
a.values = out
|
||||
end
|
||||
return true, nil
|
||||
end
|
||||
|
||||
-- decodes every attribute; returns them in attribute id order
|
||||
function Attributes.decode(d: D, g: Geom): ({ Attr }?, string?)
|
||||
local ver = d.ver
|
||||
local numDecoders = Reader.u8(d)
|
||||
if d.bad then
|
||||
return nil, d.bad
|
||||
end
|
||||
local mesh = g.mesh
|
||||
local decoders: { Decoder } = {}
|
||||
for i = 0, numDecoders - 1 do
|
||||
local dec: Decoder = { attrs = {}, traversal = nil, md = nil, points = nil }
|
||||
if g.edgebreaker and mesh then
|
||||
local attDataId = Reader.i8(d)
|
||||
local decoderType = Reader.u8(d)
|
||||
if d.bad then
|
||||
return nil, d.bad
|
||||
end
|
||||
local ad = nil
|
||||
if attDataId >= 0 then
|
||||
ad = mesh.attrData[attDataId + 1]
|
||||
if not ad or ad.decoderId >= 0 then
|
||||
return nil, "bad attribute data id"
|
||||
end
|
||||
ad.decoderId = i
|
||||
else
|
||||
if mesh.posDecoderId >= 0 then
|
||||
return nil, "two position decoders"
|
||||
end
|
||||
mesh.posDecoderId = i
|
||||
end
|
||||
local method = 0
|
||||
if ver >= 0x0102 then
|
||||
method = Reader.u8(d)
|
||||
if d.bad or method >= 2 then
|
||||
return nil, "bad traversal method"
|
||||
end
|
||||
end
|
||||
local ct = mesh.ct :: Connectivity.CT
|
||||
local enc
|
||||
if decoderType == 0 then
|
||||
if ad then
|
||||
enc = ad.enc
|
||||
ad.used = false
|
||||
else
|
||||
enc = mesh.posEnc :: Connectivity.Enc
|
||||
end
|
||||
dec.traversal = { ct = ct, enc = enc, method = method }
|
||||
else
|
||||
if method ~= 0 or not ad then
|
||||
return nil, "bad corner attribute decoder"
|
||||
end
|
||||
local cad = ad :: Connectivity.AttrData
|
||||
enc = cad.enc
|
||||
dec.traversal = { ct = cad.ct :: Connectivity.CT, enc = enc, method = 0 }
|
||||
end
|
||||
-- prediction data: the attribute's own corner table when its seams are in use
|
||||
local pct = if ad and ad.used then ad.ct :: Connectivity.CT else ct
|
||||
dec.md = { ct = pct, e2c = enc.e2c, v2e = enc.v2e }
|
||||
elseif g.kdTree then
|
||||
return nil, "unsupported: kd-tree point clouds"
|
||||
end
|
||||
decoders[i + 1] = dec
|
||||
end
|
||||
-- the attribute descriptors
|
||||
local all: { Attr } = {}
|
||||
for _, dec in decoders do
|
||||
local n = Reader.count(d, 0x0200)
|
||||
if d.bad then
|
||||
return nil, d.bad
|
||||
end
|
||||
if n == 0 or n > 5 * Reader.remaining(d) then
|
||||
return nil, "bad attribute count"
|
||||
end
|
||||
for _ = 1, n do
|
||||
local attType, dataType, comps, normalized = Reader.u8(d), Reader.u8(d), Reader.u8(d), Reader.u8(d)
|
||||
if d.bad then
|
||||
return nil, d.bad
|
||||
end
|
||||
if attType >= 9 or dataType == 0 or dataType >= 12 or comps == 0 then
|
||||
return nil, "bad attribute descriptor"
|
||||
end
|
||||
local uniqueId = if ver < 0x0103 then Reader.u16(d) else Reader.varint(d)
|
||||
local a: Attr = {
|
||||
id = #all,
|
||||
type = attType,
|
||||
dataType = dataType,
|
||||
comps = comps,
|
||||
normalized = normalized > 0,
|
||||
uniqueId = uniqueId,
|
||||
seqType = 0,
|
||||
map = nil,
|
||||
numValues = 0,
|
||||
}
|
||||
table.insert(all, a)
|
||||
table.insert(dec.attrs, a)
|
||||
end
|
||||
for _, a in dec.attrs do
|
||||
local t = Reader.u8(d)
|
||||
if d.bad then
|
||||
return nil, d.bad
|
||||
end
|
||||
if t > 3 then
|
||||
return nil, "unknown attribute decoder " .. t
|
||||
end
|
||||
if (t == 2 or t == 3) and a.dataType ~= 9 then
|
||||
return nil, "quantized attribute is not f32"
|
||||
end
|
||||
if t == 3 and a.comps ~= 3 then
|
||||
return nil, "normal attribute without 3 components"
|
||||
end
|
||||
a.seqType = t
|
||||
end
|
||||
end
|
||||
if d.bad then
|
||||
return nil, d.bad
|
||||
end
|
||||
local function named(t: number): Attr?
|
||||
for _, a in all do
|
||||
if a.type == t then
|
||||
return a
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
-- decode
|
||||
for _, dec in decoders do
|
||||
local points: { number }
|
||||
local trav = dec.traversal
|
||||
if trav then
|
||||
local faces = (mesh :: Connectivity.Mesh).faces
|
||||
local p = Connectivity.traverse(trav.ct, faces, trav.enc, trav.method)
|
||||
if not p then
|
||||
return nil, "bad attribute traversal"
|
||||
end
|
||||
points = p
|
||||
local numPoints = (mesh :: Connectivity.Mesh).numPoints
|
||||
for _, a in dec.attrs do
|
||||
local m = Connectivity.mapping(trav.ct, faces, trav.enc, numPoints)
|
||||
if not m then
|
||||
return nil, "bad attribute mapping"
|
||||
end
|
||||
a.map = m
|
||||
end
|
||||
else
|
||||
points = table.create(g.numPoints, 0)
|
||||
for i = 1, g.numPoints do
|
||||
points[i] = i - 1
|
||||
end
|
||||
end
|
||||
dec.points = points
|
||||
-- portable values
|
||||
for _, a in dec.attrs do
|
||||
if a.seqType == 0 then
|
||||
local stride = DT_LENGTH[a.dataType] * a.comps
|
||||
local size = #points * stride
|
||||
if Reader.remaining(d) < size then
|
||||
return nil, "truncated attribute values"
|
||||
end
|
||||
local raw = buffer.create(size)
|
||||
buffer.copy(raw, 0, d.b, d.pos, size)
|
||||
d.pos += size
|
||||
a.raw = raw
|
||||
a.numValues = #points
|
||||
continue
|
||||
end
|
||||
local psm = Reader.i8(d)
|
||||
if d.bad then
|
||||
return nil, d.bad
|
||||
end
|
||||
if psm < -2 or psm >= 7 then
|
||||
return nil, "bad prediction scheme"
|
||||
end
|
||||
local scheme: Predict.Scheme? = nil
|
||||
if psm ~= -2 then
|
||||
local ptt = Reader.i8(d)
|
||||
if d.bad then
|
||||
return nil, d.bad
|
||||
end
|
||||
if ptt < -1 or ptt >= 4 then
|
||||
return nil, "bad prediction transform"
|
||||
end
|
||||
if a.seqType == 3 then
|
||||
if ptt == 2 or ptt == 3 then
|
||||
scheme = Predict.new(psm, Predict.transform(ptt), dec.md)
|
||||
end
|
||||
elseif ptt == 1 then
|
||||
scheme = Predict.new(psm, Predict.transform(1), dec.md)
|
||||
end
|
||||
end
|
||||
if scheme and Predict.needsParent(scheme) then
|
||||
local pos = named(0)
|
||||
local getter = pos and parentGetter(ver, pos, scheme.method == 3)
|
||||
if not getter then
|
||||
return nil, "prediction needs the decoded positions"
|
||||
end
|
||||
scheme.parent = getter
|
||||
end
|
||||
if ver < 0x0200 then
|
||||
if a.seqType == 2 and not decodeQuantInfo(d, a) then
|
||||
return nil, d.bad or "bad quantization data"
|
||||
elseif a.seqType == 3 then
|
||||
a.octBits = Reader.u8(d)
|
||||
end
|
||||
end
|
||||
local ok, err = decodeIntegerValues(d, a, points, scheme)
|
||||
if not ok then
|
||||
return nil, err
|
||||
end
|
||||
a.scheme = scheme
|
||||
if ver < 0x0200 then
|
||||
local ok2, err2 = storeValues(a)
|
||||
if not ok2 then
|
||||
return nil, err2
|
||||
end
|
||||
end
|
||||
end
|
||||
-- data needed by the transforms
|
||||
if ver >= 0x0200 then
|
||||
for _, a in dec.attrs do
|
||||
if a.seqType == 2 then
|
||||
if not decodeQuantInfo(d, a) then
|
||||
return nil, d.bad or "bad quantization data"
|
||||
end
|
||||
elseif a.seqType == 3 then
|
||||
a.octBits = Reader.u8(d)
|
||||
end
|
||||
end
|
||||
if d.bad then
|
||||
return nil, d.bad
|
||||
end
|
||||
for _, a in dec.attrs do
|
||||
if a.seqType ~= 0 then
|
||||
local ok, err = storeValues(a)
|
||||
if not ok then
|
||||
return nil, err
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return all, nil
|
||||
end
|
||||
|
||||
return Attributes
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,156 @@
|
||||
--!strict
|
||||
-- codecs/model/Draco/Int64: the 64-bit integer arithmetic Draco's portable tex coord predictor relies on (int64 /
|
||||
-- uint64 with wrap-around, truncating division, IntSqrt), on (hi, lo) pairs of 32-bit halves held in numbers (both
|
||||
-- runtimes: no native 64-bit integers). Two's complement: hi >= 2^31 is negative when read as signed.
|
||||
local Int64 = {}
|
||||
|
||||
local P32 = 4294967296
|
||||
local P31 = 2147483648
|
||||
|
||||
function Int64.from(n: number): (number, number)
|
||||
if n >= 0 then
|
||||
return (n // P32) % P32, n % P32
|
||||
end
|
||||
local h, l = Int64.from(-n)
|
||||
return Int64.neg(h, l)
|
||||
end
|
||||
|
||||
function Int64.neg(h: number, l: number): (number, number)
|
||||
if l == 0 then
|
||||
return (P32 - h) % P32, 0
|
||||
end
|
||||
return P32 - 1 - h, P32 - l
|
||||
end
|
||||
|
||||
function Int64.add(ah: number, al: number, bh: number, bl: number): (number, number)
|
||||
local l = al + bl
|
||||
local c = 0
|
||||
if l >= P32 then
|
||||
l -= P32
|
||||
c = 1
|
||||
end
|
||||
return (ah + bh + c) % P32, l
|
||||
end
|
||||
|
||||
function Int64.sub(ah: number, al: number, bh: number, bl: number): (number, number)
|
||||
local nh, nl = Int64.neg(bh, bl)
|
||||
return Int64.add(ah, al, nh, nl)
|
||||
end
|
||||
|
||||
-- the product mod 2^64 (the same bits for signed and unsigned operands)
|
||||
function Int64.mul(ah: number, al: number, bh: number, bl: number): (number, number)
|
||||
local a0, a1, a2, a3 = al % 65536, al // 65536, ah % 65536, ah // 65536
|
||||
local b0, b1, b2, b3 = bl % 65536, bl // 65536, bh % 65536, bh // 65536
|
||||
local c0 = a0 * b0
|
||||
local c1 = a1 * b0 + a0 * b1
|
||||
local c2 = a2 * b0 + a1 * b1 + a0 * b2
|
||||
local c3 = a3 * b0 + a2 * b1 + a1 * b2 + a0 * b3
|
||||
local lo = c0 + (c1 % 65536) * 65536
|
||||
local carry = lo // P32
|
||||
lo %= P32
|
||||
local hi = (c1 // 65536 + c2 + (c3 % 65536) * 65536 + carry) % P32
|
||||
return hi, lo
|
||||
end
|
||||
|
||||
function Int64.isNeg(h: number): boolean
|
||||
return h >= P31
|
||||
end
|
||||
|
||||
-- the signed value as a number (exact below 2^53 in magnitude)
|
||||
function Int64.signed(h: number, l: number): number
|
||||
if h >= P31 then
|
||||
return (h - P32) * P32 + l
|
||||
end
|
||||
return h * P32 + l
|
||||
end
|
||||
|
||||
-- the unsigned value as a number (rounded past 2^53)
|
||||
function Int64.unsigned(h: number, l: number): number
|
||||
return h * P32 + l
|
||||
end
|
||||
|
||||
-- unsigned compare: -1, 0, 1
|
||||
function Int64.ucmp(ah: number, al: number, bh: number, bl: number): number
|
||||
if ah ~= bh then
|
||||
return if ah < bh then -1 else 1
|
||||
end
|
||||
if al ~= bl then
|
||||
return if al < bl then -1 else 1
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- signed compare: -1, 0, 1
|
||||
function Int64.cmp(ah: number, al: number, bh: number, bl: number): number
|
||||
local sa = if ah >= P31 then ah - P32 else ah
|
||||
local sb = if bh >= P31 then bh - P32 else bh
|
||||
if sa ~= sb then
|
||||
return if sa < sb then -1 else 1
|
||||
end
|
||||
return Int64.ucmp(0, al, 0, bl)
|
||||
end
|
||||
|
||||
-- unsigned division (b ~= 0): quotient, remainder
|
||||
function Int64.udivmod(ah: number, al: number, bh: number, bl: number): (number, number, number, number)
|
||||
if ah == 0 and bh == 0 then
|
||||
return 0, al // bl, 0, al % bl
|
||||
end
|
||||
local qh, ql, rh, rl = 0, 0, 0, 0
|
||||
for i = 63, 0, -1 do
|
||||
-- r = r * 2 + bit i of a
|
||||
local bit = if i >= 32 then (ah // 2 ^ (i - 32)) % 2 else (al // 2 ^ i) % 2
|
||||
local over = rh >= P31
|
||||
rh = (rh * 2 + rl // P31) % P32
|
||||
rl = (rl * 2) % P32 + bit
|
||||
if over or Int64.ucmp(rh, rl, bh, bl) >= 0 then
|
||||
rh, rl = Int64.sub(rh, rl, bh, bl)
|
||||
if i >= 32 then
|
||||
qh += 2 ^ (i - 32)
|
||||
else
|
||||
ql += 2 ^ i
|
||||
end
|
||||
end
|
||||
end
|
||||
return qh, ql, rh, rl
|
||||
end
|
||||
|
||||
-- signed division truncating toward zero (b ~= 0)
|
||||
function Int64.div(ah: number, al: number, bh: number, bl: number): (number, number)
|
||||
local na, nb = ah >= P31, bh >= P31
|
||||
if na then
|
||||
ah, al = Int64.neg(ah, al)
|
||||
end
|
||||
if nb then
|
||||
bh, bl = Int64.neg(bh, bl)
|
||||
end
|
||||
local qh, ql = Int64.udivmod(ah, al, bh, bl)
|
||||
if na ~= nb then
|
||||
return Int64.neg(qh, ql)
|
||||
end
|
||||
return qh, ql
|
||||
end
|
||||
|
||||
-- IntSqrt (draco/core/math_utils.h) on a uint64, step for step (wrap-around included)
|
||||
function Int64.isqrt(h: number, l: number): (number, number)
|
||||
if h == 0 and l == 0 then
|
||||
return 0, 0
|
||||
end
|
||||
local acth, actl = h, l
|
||||
local sh, sl = 0, 1
|
||||
while Int64.ucmp(acth, actl, 0, 2) >= 0 do
|
||||
sh, sl = Int64.add(sh, sl, sh, sl)
|
||||
acth, actl = Int64.udivmod(acth, actl, 0, 4)
|
||||
end
|
||||
repeat
|
||||
local qh, ql = Int64.udivmod(h, l, sh, sl)
|
||||
local th, tl = Int64.add(sh, sl, qh, ql)
|
||||
sh, sl = Int64.udivmod(th, tl, 0, 2)
|
||||
if sh == 0 and sl == 0 then
|
||||
return 0, 0
|
||||
end
|
||||
local pph, ppl = Int64.mul(sh, sl, sh, sl)
|
||||
until Int64.ucmp(pph, ppl, h, l) <= 0
|
||||
return sh, sl
|
||||
end
|
||||
|
||||
return Int64
|
||||
@@ -0,0 +1,977 @@
|
||||
--!strict
|
||||
-- codecs/model/Draco/Predict: Draco attribute prediction schemes and their decoding transforms. Schemes: difference
|
||||
-- (delta), parallelogram, multi-parallelogram, constrained multi-parallelogram, tex coords (deprecated, float) and
|
||||
-- portable tex coords, geometric normal; transforms: wrap, normal octahedron and canonicalized normal octahedron.
|
||||
-- Integer semantics follow the C++ (int32 wrap, truncating division, exact 64-bit products where they can pass 2^53;
|
||||
-- float math rounded to f32 at every step). Ported from Google's Draco 1.5.7
|
||||
-- (compression/attributes/prediction_schemes/*, compression/attributes/normal_compression_utils.h; Apache-2.0,
|
||||
-- licenses/draco-LICENSE.txt).
|
||||
local Reader = require("@formats/codecs/model/Draco/Reader")
|
||||
local Connectivity = require("@formats/codecs/model/Draco/Connectivity")
|
||||
local Int64 = require("@formats/codecs/model/Draco/Int64")
|
||||
|
||||
local Predict = {}
|
||||
|
||||
type D = Reader.D
|
||||
type CT = Connectivity.CT
|
||||
|
||||
local nextC, prevC = Connectivity.next, Connectivity.prev
|
||||
|
||||
local F32 = buffer.create(4)
|
||||
local function fround(x: number): number
|
||||
buffer.writef32(F32, 0, x)
|
||||
return buffer.readf32(F32, 0)
|
||||
end
|
||||
Predict.fround = fround
|
||||
|
||||
local function i32(x: number): number
|
||||
return (x + 2147483648) % 4294967296 - 2147483648
|
||||
end
|
||||
Predict.i32 = i32
|
||||
|
||||
local function tdiv(a: number, b: number): number
|
||||
local q = a / b
|
||||
return if q < 0 then math.ceil(q) else math.floor(q)
|
||||
end
|
||||
|
||||
-- static_cast<int> of a float with the decoder's NaN / range guard (INT_MIN)
|
||||
local function truncInt(x: number): number
|
||||
if x ~= x or x > 2147483647 or x < -2147483648 then
|
||||
return -2147483648
|
||||
end
|
||||
return tdiv(x, 1)
|
||||
end
|
||||
|
||||
-- exact a * b = p + e (Dekker), for integers below 2^53
|
||||
local SPLIT = 134217729
|
||||
local function twoProd(a: number, b: number): (number, number)
|
||||
local p = a * b
|
||||
local t = SPLIT * a
|
||||
local ah = t - (t - a)
|
||||
local al = a - ah
|
||||
t = SPLIT * b
|
||||
local bh = t - (t - b)
|
||||
local bl = b - bh
|
||||
return p, ((ah * bh - p) + ah * bl + al * bh) + al * bl
|
||||
end
|
||||
|
||||
-- trunc(a * b / c) for integers, exact while the true product is below 2^106 (c > 0)
|
||||
local function mulDiv(a: number, b: number, c: number): number
|
||||
local neg = (a < 0) ~= (b < 0)
|
||||
a, b = math.abs(a), math.abs(b)
|
||||
local p = a * b
|
||||
local q
|
||||
if p < 9007199254740992 then
|
||||
q = p // c
|
||||
else
|
||||
q = math.floor(p / c)
|
||||
local ph, pl = twoProd(a, b)
|
||||
local qh, ql = twoProd(q, c)
|
||||
local r = (ph - qh) + (pl - ql)
|
||||
while r < 0 do
|
||||
q -= 1
|
||||
r += c
|
||||
end
|
||||
while r >= c do
|
||||
q += 1
|
||||
r -= c
|
||||
end
|
||||
end
|
||||
return if neg then -q else q
|
||||
end
|
||||
|
||||
-- floor(sqrt(a * b)) (IntSqrt of a 64-bit product), exact for a, b < 2^53
|
||||
local function isqrtProd(a: number, b: number): number
|
||||
if a == 0 or b == 0 then
|
||||
return 0
|
||||
end
|
||||
local s = math.floor(math.sqrt(a) * math.sqrt(b))
|
||||
local ph, pl = twoProd(a, b)
|
||||
local function le(x: number): boolean -- x * x <= a * b
|
||||
local xh, xl = twoProd(x, x)
|
||||
if xh ~= ph then
|
||||
return xh < ph
|
||||
end
|
||||
return xl <= pl
|
||||
end
|
||||
while s > 0 and not le(s) do
|
||||
s -= 1
|
||||
end
|
||||
while le(s + 1) do
|
||||
s += 1
|
||||
end
|
||||
return s
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ octahedron toolbox
|
||||
export type Oct = { bits: number, maxQ: number, maxV: number, center: number, scale: number }
|
||||
|
||||
function Predict.octahedron(bits: number): Oct?
|
||||
if bits < 2 or bits > 30 then
|
||||
return nil
|
||||
end
|
||||
local maxQ = 2 ^ bits - 1
|
||||
local maxV = maxQ - 1
|
||||
return { bits = bits, maxQ = maxQ, maxV = maxV, center = maxV // 2, scale = fround(2 / fround(maxV)) }
|
||||
end
|
||||
|
||||
local function canonicalizeCoords(o: Oct, s: number, t: number): (number, number)
|
||||
local maxV, center = o.maxV, o.center
|
||||
if (s == 0 and t == 0) or (s == 0 and t == maxV) or (s == maxV and t == 0) then
|
||||
return maxV, maxV
|
||||
elseif s == 0 and t > center then
|
||||
t = center - (t - center)
|
||||
elseif s == maxV and t < center then
|
||||
t = center + (center - t)
|
||||
elseif t == maxV and s < center then
|
||||
s = center + (center - s)
|
||||
elseif t == 0 and s > center then
|
||||
s = center - (s - center)
|
||||
end
|
||||
return s, t
|
||||
end
|
||||
|
||||
local function intVectorToOct(o: Oct, x: number, y: number, z: number): (number, number)
|
||||
local s, t
|
||||
local center, maxV = o.center, o.maxV
|
||||
if x >= 0 then
|
||||
s, t = y + center, z + center
|
||||
else
|
||||
s = if y < 0 then math.abs(z) else maxV - math.abs(z)
|
||||
t = if z < 0 then math.abs(y) else maxV - math.abs(y)
|
||||
end
|
||||
return canonicalizeCoords(o, s, t)
|
||||
end
|
||||
|
||||
local function canonicalizeVector(o: Oct, x: number, y: number, z: number): (number, number, number)
|
||||
local sum = math.abs(x) + math.abs(y) + math.abs(z)
|
||||
local center = o.center
|
||||
if sum == 0 then
|
||||
return center, y, z
|
||||
end
|
||||
x = mulDiv(x, center, sum)
|
||||
y = mulDiv(y, center, sum)
|
||||
if z >= 0 then
|
||||
z = center - math.abs(x) - math.abs(y)
|
||||
else
|
||||
z = -(center - math.abs(x) - math.abs(y))
|
||||
end
|
||||
return x, y, z
|
||||
end
|
||||
|
||||
local function invertDiamond(o: Oct, s: number, t: number): (number, number)
|
||||
local signS, signT
|
||||
if s >= 0 and t >= 0 then
|
||||
signS, signT = 1, 1
|
||||
elseif s <= 0 and t <= 0 then
|
||||
signS, signT = -1, -1
|
||||
else
|
||||
signS = if s > 0 then 1 else -1
|
||||
signT = if t > 0 then 1 else -1
|
||||
end
|
||||
local cs, ctv = signS * o.center, signT * o.center
|
||||
local us, ut = s + s - cs, t + t - ctv
|
||||
if signS * signT >= 0 then
|
||||
us, ut = -ut, -us
|
||||
else
|
||||
us, ut = ut, us
|
||||
end
|
||||
return tdiv(i32(us + cs), 2), tdiv(i32(ut + ctv), 2)
|
||||
end
|
||||
|
||||
local function modMax(o: Oct, x: number): number
|
||||
if x > o.center then
|
||||
return x - o.maxQ
|
||||
elseif x < -o.center then
|
||||
return x + o.maxQ
|
||||
end
|
||||
return x
|
||||
end
|
||||
|
||||
-- quantized octahedral (s, t) -> unit vector, in f32 like the C++
|
||||
function Predict.octToVector(o: Oct, s: number, t: number): (number, number, number)
|
||||
local y = fround(fround(fround(s) * o.scale) - 1)
|
||||
local z = fround(fround(fround(t) * o.scale) - 1)
|
||||
local x = fround(fround(1 - math.abs(y)) - math.abs(z))
|
||||
local xo = -x
|
||||
if xo < 0 then
|
||||
xo = 0
|
||||
end
|
||||
y = fround(if y < 0 then y + xo else y - xo)
|
||||
z = fround(if z < 0 then z + xo else z - xo)
|
||||
local n2 = fround(fround(fround(x * x) + fround(y * y)) + fround(z * z))
|
||||
if n2 < 1e-6 then
|
||||
return 0, 0, 0
|
||||
end
|
||||
local dd = fround(1 / fround(math.sqrt(n2)))
|
||||
return fround(x * dd), fround(y * dd), fround(z * dd)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ transforms
|
||||
-- tr.apply(pred, data, off): data[off + 1 ..] holds the corrections and receives the original values
|
||||
export type Transform = {
|
||||
kind: number, -- 1 wrap, 2 octahedron, 3 octahedron canonicalized
|
||||
positive: boolean, -- corrections are stored without the zig-zag sign mapping
|
||||
min: number,
|
||||
max: number,
|
||||
maxDif: number,
|
||||
oct: Oct?,
|
||||
}
|
||||
|
||||
function Predict.transform(kind: number): Transform
|
||||
return { kind = kind, positive = kind ~= 1, min = 0, max = 0, maxDif = 0, oct = nil }
|
||||
end
|
||||
|
||||
function Predict.decodeTransform(tr: Transform, d: D): boolean
|
||||
if tr.kind == 1 then
|
||||
local mn, mx = Reader.i32(d), Reader.i32(d)
|
||||
if d.bad or mn > mx then
|
||||
return false
|
||||
end
|
||||
local dif = mx - mn
|
||||
if dif >= 2147483647 then
|
||||
return false
|
||||
end
|
||||
tr.min, tr.max, tr.maxDif = mn, mx, dif + 1
|
||||
return true
|
||||
end
|
||||
local maxQ = Reader.i32(d)
|
||||
if tr.kind == 3 or d.ver < 0x0202 then
|
||||
Reader.i32(d) -- center value (unused)
|
||||
end
|
||||
if d.bad or maxQ <= 0 or maxQ % 2 == 0 then
|
||||
return false
|
||||
end
|
||||
local bits = 0
|
||||
while 2 ^ bits <= maxQ do
|
||||
bits += 1
|
||||
end
|
||||
local o = Predict.octahedron(bits)
|
||||
if not o then
|
||||
return false
|
||||
end
|
||||
tr.oct = o
|
||||
return true
|
||||
end
|
||||
|
||||
-- the original values from a prediction (pred[1 .. comps]) and the corrections at data[off + 1 ..]
|
||||
local function apply(tr: Transform, pred: { number }, data: { number }, off: number, comps: number)
|
||||
if tr.kind == 1 then
|
||||
local mn, mx, dif = tr.min, tr.max, tr.maxDif
|
||||
for c = 1, comps do
|
||||
local p = pred[c]
|
||||
if p > mx then
|
||||
p = mx
|
||||
elseif p < mn then
|
||||
p = mn
|
||||
end
|
||||
local v = i32(p + data[off + c])
|
||||
if v > mx then
|
||||
v -= dif
|
||||
elseif v < mn then
|
||||
v += dif
|
||||
end
|
||||
data[off + c] = v
|
||||
end
|
||||
return
|
||||
end
|
||||
local o = tr.oct :: Oct
|
||||
local center = o.center
|
||||
local ps, pt = pred[1] - center, pred[2] - center
|
||||
local cs, ct = data[off + 1], data[off + 2]
|
||||
local inDiamond = math.abs(ps) + math.abs(pt) <= center
|
||||
if not inDiamond then
|
||||
ps, pt = invertDiamond(o, ps, pt)
|
||||
end
|
||||
local os_: number, ot: number = 0, 0
|
||||
if tr.kind == 2 then
|
||||
os_ = modMax(o, i32(ps + cs))
|
||||
ot = modMax(o, i32(pt + ct))
|
||||
else
|
||||
local bottomLeft = (ps == 0 and pt == 0) or (ps < 0 and pt <= 0)
|
||||
local rot = 0
|
||||
if ps == 0 then
|
||||
rot = if pt == 0 then 0 elseif pt > 0 then 3 else 1
|
||||
elseif ps > 0 then
|
||||
rot = if pt >= 0 then 2 else 1
|
||||
else
|
||||
rot = if pt <= 0 then 0 else 3
|
||||
end
|
||||
local function rotate(x: number, y: number, r: number): (number, number)
|
||||
if r == 1 then
|
||||
return y, -x
|
||||
elseif r == 2 then
|
||||
return -x, -y
|
||||
elseif r == 3 then
|
||||
return -y, x
|
||||
end
|
||||
return x, y
|
||||
end
|
||||
if not bottomLeft then
|
||||
ps, pt = rotate(ps, pt, rot)
|
||||
end
|
||||
os_ = modMax(o, i32(ps + cs))
|
||||
ot = modMax(o, i32(pt + ct))
|
||||
if not bottomLeft then
|
||||
os_, ot = rotate(os_, ot, (4 - rot) % 4)
|
||||
end
|
||||
end
|
||||
if not inDiamond then
|
||||
os_, ot = invertDiamond(o, os_, ot)
|
||||
end
|
||||
data[off + 1] = os_ + center
|
||||
data[off + 2] = ot + center
|
||||
end
|
||||
Predict.apply = apply
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ schemes
|
||||
-- the mesh data of a scheme: corner table, value -> corner, vertex -> value
|
||||
export type MeshData = { ct: CT, e2c: { number }, v2e: { number } }
|
||||
-- the parent position attribute: pos(point) -> x, y, z (portable integers, or floats before 2.0)
|
||||
export type Parent = (point: number) -> (number, number, number)
|
||||
|
||||
export type Scheme = {
|
||||
method: number,
|
||||
tr: Transform,
|
||||
md: MeshData?,
|
||||
parent: Parent?,
|
||||
-- per-scheme decoded data
|
||||
crease: { { boolean } }?,
|
||||
orient: { boolean }?,
|
||||
flips: Reader.Bits?,
|
||||
areaMode: boolean,
|
||||
ver: number,
|
||||
}
|
||||
|
||||
local DELTA, PARALLELOGRAM, MULTI, TEXDEP, CONSTRAINED, TEXPORT, GEONORMAL = 0, 1, 2, 3, 4, 5, 6
|
||||
Predict.GEOMETRIC_NORMAL = GEONORMAL
|
||||
|
||||
-- whether the scheme needs the position attribute
|
||||
function Predict.needsParent(s: Scheme): boolean
|
||||
return s.md ~= nil and (s.method == TEXDEP or s.method == TEXPORT or s.method == GEONORMAL)
|
||||
end
|
||||
|
||||
-- CreatePredictionSchemeForDecoder: md = nil (no corner table: sequential connectivity, point clouds) gives delta
|
||||
function Predict.new(method: number, tr: Transform, md: MeshData?): Scheme
|
||||
local m = method
|
||||
if not md then
|
||||
m = DELTA
|
||||
elseif tr.kind ~= 1 then
|
||||
if m ~= GEONORMAL then
|
||||
m = DELTA
|
||||
md = nil
|
||||
end
|
||||
elseif m < PARALLELOGRAM or m > GEONORMAL then
|
||||
m = DELTA
|
||||
md = nil
|
||||
end
|
||||
return { method = m, tr = tr, md = if m == DELTA then nil else md, parent = nil, areaMode = true, ver = 0x0202 }
|
||||
end
|
||||
|
||||
-- DecodePredictionData
|
||||
function Predict.decodeData(s: Scheme, d: D): boolean
|
||||
local m = s.method
|
||||
s.ver = d.ver
|
||||
if m == CONSTRAINED then
|
||||
if d.ver < 0x0202 then
|
||||
local mode = Reader.u8(d)
|
||||
if d.bad or mode ~= 0 then
|
||||
return false
|
||||
end
|
||||
end
|
||||
local md = s.md :: MeshData
|
||||
local crease = {}
|
||||
for i = 1, 4 do
|
||||
local n = Reader.varint(d)
|
||||
if d.bad or n > md.ct.nf * 3 then
|
||||
return false
|
||||
end
|
||||
local flags = table.create(n, false)
|
||||
if n > 0 then
|
||||
local bd = Reader.bitDecoder(d)
|
||||
if not bd then
|
||||
return false
|
||||
end
|
||||
for j = 1, n do
|
||||
flags[j] = Reader.bit(bd)
|
||||
end
|
||||
end
|
||||
crease[i] = flags
|
||||
end
|
||||
s.crease = crease
|
||||
elseif m == TEXPORT then
|
||||
local n = Reader.i32(d)
|
||||
if d.bad or n < 0 or n > (s.md :: MeshData).ct.nf * 3 then
|
||||
return false
|
||||
end
|
||||
local bd = Reader.bitDecoder(d)
|
||||
if not bd then
|
||||
return false
|
||||
end
|
||||
local orient = table.create(n, false)
|
||||
local last = true
|
||||
for i = 1, n do
|
||||
if not Reader.bit(bd) then
|
||||
last = not last
|
||||
end
|
||||
orient[i] = last
|
||||
end
|
||||
s.orient = orient
|
||||
elseif m == TEXDEP then
|
||||
local n = Reader.count(d, 0x0202)
|
||||
local md = s.md :: MeshData
|
||||
if d.bad or n == 0 or n > md.ct.nf * 3 then
|
||||
return false
|
||||
end
|
||||
local bd = Reader.bitDecoder(d)
|
||||
if not bd then
|
||||
return false
|
||||
end
|
||||
local orient = table.create(n, false)
|
||||
local last = true
|
||||
for i = 1, n do
|
||||
if not Reader.bit(bd) then
|
||||
last = not last
|
||||
end
|
||||
orient[i] = last
|
||||
end
|
||||
s.orient = orient
|
||||
elseif m == GEONORMAL then
|
||||
if not Predict.decodeTransform(s.tr, d) then
|
||||
return false
|
||||
end
|
||||
if d.ver < 0x0202 then
|
||||
local mode = Reader.u8(d)
|
||||
if d.bad or mode > 1 then
|
||||
return false
|
||||
end
|
||||
s.areaMode = mode == 1
|
||||
end
|
||||
local bd = Reader.bitDecoder(d)
|
||||
if not bd then
|
||||
return false
|
||||
end
|
||||
s.flips = bd
|
||||
return true
|
||||
end
|
||||
return Predict.decodeTransform(s.tr, d)
|
||||
end
|
||||
|
||||
local function parallelogram(md: MeshData, p: number, ci: number, data: { number }, comps: number, out: { number }): boolean
|
||||
local ct = md.ct
|
||||
local oci = if ci < 0 then -1 else (ct.opp[ci + 1] or -1)
|
||||
if oci == -1 then
|
||||
return false
|
||||
end
|
||||
local c2v, v2e = ct.c2v, md.v2e
|
||||
local vo, vn, vp = c2v[oci + 1] or -1, c2v[nextC(oci) + 1] or -1, c2v[prevC(oci) + 1] or -1
|
||||
if vo < 0 or vn < 0 or vp < 0 then
|
||||
return false
|
||||
end
|
||||
local eo, en, ep = v2e[vo + 1] or 0, v2e[vn + 1] or 0, v2e[vp + 1] or 0
|
||||
if eo < p and en < p and ep < p then
|
||||
for c = 1, comps do
|
||||
out[c] = i32((data[en * comps + c] + data[ep * comps + c]) - data[eo * comps + c])
|
||||
end
|
||||
return true
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
local function swingRight(ct: CT, c: number): number
|
||||
local p = prevC(c)
|
||||
local o = if p < 0 then -1 else (ct.opp[p + 1] or -1)
|
||||
return prevC(o)
|
||||
end
|
||||
local function swingLeft(ct: CT, c: number): number
|
||||
local n = nextC(c)
|
||||
local o = if n < 0 then -1 else (ct.opp[n + 1] or -1)
|
||||
return nextC(o)
|
||||
end
|
||||
|
||||
-- the portable tex coord prediction when both neighbours are decoded (MeshPredictionSchemeTexCoordsPortablePredictor
|
||||
-- ::ComputePredictedValue), in int64 / uint64 arithmetic like the C++. Returns "ok", u, v; "fallback" (degenerate
|
||||
-- edge: predict from a neighbour); or "fail", message.
|
||||
local function texPortable(nu: number, nv: number, pu: number, pv: number, tx: number, ty: number, tz: number, nx: number, ny: number, nz: number, qx: number, qy: number, qz: number, pop: () -> boolean?): (string, any, any)
|
||||
local pnx, pny, pnz = qx - nx, qy - ny, qz - nz
|
||||
local cnx, cny, cnz = tx - nx, ty - ny, tz - nz
|
||||
local pnu, pnv = pu - nu, pv - nv
|
||||
local B = 67108864 -- 2^26: below it every product and sum stays exact in a double
|
||||
local small = math.abs(pnx) < B and math.abs(pny) < B and math.abs(pnz) < B and math.abs(cnx) < B and math.abs(cny) < B and math.abs(cnz) < B
|
||||
if small then
|
||||
local pn2 = pnx * pnx + pny * pny + pnz * pnz
|
||||
local dot = pnx * cnx + pny * cny + pnz * cnz
|
||||
if pn2 < B and math.abs(dot) < B and math.abs(nu) < B and math.abs(nv) < B and math.abs(pnu) < B and math.abs(pnv) < B then
|
||||
if pn2 == 0 then
|
||||
return "fallback"
|
||||
end
|
||||
local xu, xv = nu * pn2 + dot * pnu, nv * pn2 + dot * pnv
|
||||
local dx = tx - (nx + tdiv(dot * pnx, pn2))
|
||||
local dy = ty - (ny + tdiv(dot * pny, pn2))
|
||||
local dz = tz - (nz + tdiv(dot * pnz, pn2))
|
||||
local cx2 = dx * dx + dy * dy + dz * dz
|
||||
if cx2 < B then
|
||||
local norm = isqrtProd(cx2, pn2)
|
||||
local cxu, cxv = pnv * norm, -pnu * norm
|
||||
local o = pop()
|
||||
if o == nil then
|
||||
return "fail", "prediction: orientations run out"
|
||||
end
|
||||
if o then
|
||||
return "ok", i32(tdiv(xu + cxu, pn2)), i32(tdiv(xv + cxv, pn2))
|
||||
end
|
||||
return "ok", i32(tdiv(xu - cxu, pn2)), i32(tdiv(xv - cxv, pn2))
|
||||
end
|
||||
end
|
||||
end
|
||||
-- the general case: int64
|
||||
local from, add, sub, mul, div = Int64.from, Int64.add, Int64.sub, Int64.mul, Int64.div
|
||||
local function dot3(ax: number, ay: number, az: number, bx: number, by: number, bz: number): (number, number)
|
||||
local xh, xl = from(ax)
|
||||
local yh, yl = from(ay)
|
||||
local zh, zl = from(az)
|
||||
local uh, ul = from(bx)
|
||||
local vh, vl = from(by)
|
||||
local wh, wl = from(bz)
|
||||
local h1, l1 = mul(xh, xl, uh, ul)
|
||||
local h2, l2 = mul(yh, yl, vh, vl)
|
||||
local h3, l3 = mul(zh, zl, wh, wl)
|
||||
h1, l1 = add(h1, l1, h2, l2)
|
||||
return add(h1, l1, h3, l3)
|
||||
end
|
||||
local p2h, p2l = dot3(pnx, pny, pnz, pnx, pny, pnz)
|
||||
if p2h == 0 and p2l == 0 then
|
||||
return "fallback"
|
||||
end
|
||||
local dh, dl = dot3(pnx, pny, pnz, cnx, cny, cnz)
|
||||
local MAXH, MAXL = 2147483647, 4294967295 -- INT64_MAX
|
||||
local function absmax(...: number): (number, number)
|
||||
local m = 0
|
||||
for _, x in { ... } do
|
||||
m = math.max(m, math.abs(x))
|
||||
end
|
||||
return from(m)
|
||||
end
|
||||
local function absI(h: number, l: number): (number, number)
|
||||
if Int64.isNeg(h) then
|
||||
return Int64.neg(h, l)
|
||||
end
|
||||
return h, l
|
||||
end
|
||||
-- the overflow guards (unsigned divisions as in the C++)
|
||||
local nmh, nml = absmax(nu, nv)
|
||||
local lh, ll = Int64.udivmod(MAXH, MAXL, p2h, p2l)
|
||||
if Int64.ucmp(nmh, nml, lh, ll) > 0 then
|
||||
return "fail", "prediction: tex coord overflow"
|
||||
end
|
||||
local adh, adl = absI(dh, dl)
|
||||
local pmh, pml = absmax(pnu, pnv)
|
||||
lh, ll = Int64.div(MAXH, MAXL, pmh, pml)
|
||||
if Int64.cmp(adh, adl, lh, ll) > 0 then
|
||||
return "fail", "prediction: tex coord overflow"
|
||||
end
|
||||
local nuh, nul = from(nu)
|
||||
local nvh, nvl = from(nv)
|
||||
local puh, pul = from(pnu)
|
||||
local pvh, pvl = from(pnv)
|
||||
local xuh, xul
|
||||
do
|
||||
local ah, al = mul(nuh, nul, p2h, p2l)
|
||||
local bh, bl = mul(dh, dl, puh, pul)
|
||||
xuh, xul = add(ah, al, bh, bl)
|
||||
end
|
||||
local xvh, xvl
|
||||
do
|
||||
local ah, al = mul(nvh, nvl, p2h, p2l)
|
||||
local bh, bl = mul(dh, dl, pvh, pvl)
|
||||
xvh, xvl = add(ah, al, bh, bl)
|
||||
end
|
||||
local pam = math.max(math.abs(pnx), math.abs(pny), math.abs(pnz))
|
||||
local pah, pal = from(pam)
|
||||
lh, ll = Int64.div(MAXH, MAXL, pah, pal)
|
||||
if Int64.cmp(adh, adl, lh, ll) > 0 then
|
||||
return "fail", "prediction: tex coord overflow"
|
||||
end
|
||||
-- x_pos = next + (dot * pn) / pn2; cx = tip - x_pos
|
||||
local function proj(n: number, pc: number, t: number): (number, number)
|
||||
local ph, pl = from(pc)
|
||||
local mh, ml = mul(dh, dl, ph, pl)
|
||||
local qh, ql = div(mh, ml, p2h, p2l)
|
||||
local nh, nl = from(n)
|
||||
local xh, xl = add(nh, nl, qh, ql)
|
||||
local th, tl = from(t)
|
||||
return sub(th, tl, xh, xl)
|
||||
end
|
||||
local ax, axl = proj(nx, pnx, tx)
|
||||
local ay, ayl = proj(ny, pny, ty)
|
||||
local az, azl = proj(nz, pnz, tz)
|
||||
local c2h, c2l = mul(ax, axl, ax, axl)
|
||||
do
|
||||
local h, l = mul(ay, ayl, ay, ayl)
|
||||
c2h, c2l = add(c2h, c2l, h, l)
|
||||
h, l = mul(az, azl, az, azl)
|
||||
c2h, c2l = add(c2h, c2l, h, l)
|
||||
end
|
||||
local prh, prl = mul(c2h, c2l, p2h, p2l)
|
||||
local sh, sl = Int64.isqrt(prh, prl)
|
||||
-- cx_uv = (pn_uv.v, -pn_uv.u) * norm
|
||||
local cuh, cul = mul(pvh, pvl, sh, sl)
|
||||
local nh, nl = Int64.neg(puh, pul)
|
||||
local cvh, cvl = mul(nh, nl, sh, sl)
|
||||
local o = pop()
|
||||
if o == nil then
|
||||
return "fail", "prediction: orientations run out"
|
||||
end
|
||||
local uh, ul, vh, vl
|
||||
if o then
|
||||
uh, ul = add(xuh, xul, cuh, cul)
|
||||
vh, vl = add(xvh, xvl, cvh, cvl)
|
||||
else
|
||||
uh, ul = sub(xuh, xul, cuh, cul)
|
||||
vh, vl = sub(xvh, xvl, cvh, cvl)
|
||||
end
|
||||
uh, ul = div(uh, ul, p2h, p2l)
|
||||
vh, vl = div(vh, vl, p2h, p2l)
|
||||
-- static_cast<int>: the low 32 bits
|
||||
return "ok", i32(ul), i32(vl)
|
||||
end
|
||||
|
||||
-- ComputeOriginalValues over data (corrections in, values out, in place); points = the entry -> point map
|
||||
function Predict.compute(s: Scheme, data: { number }, numEntries: number, comps: number, points: { number }): (boolean, string?)
|
||||
local tr = s.tr
|
||||
local m = s.method
|
||||
local pred = table.create(math.max(comps, 3), 0)
|
||||
if m == DELTA then
|
||||
if numEntries == 0 then
|
||||
return true, nil
|
||||
end
|
||||
apply(tr, pred, data, 0, comps)
|
||||
for e = 1, numEntries - 1 do
|
||||
local off = e * comps
|
||||
for c = 1, comps do
|
||||
pred[c] = data[off - comps + c]
|
||||
end
|
||||
apply(tr, pred, data, off, comps)
|
||||
end
|
||||
return true, nil
|
||||
end
|
||||
local md = s.md :: MeshData
|
||||
local e2c = md.e2c
|
||||
local n = #e2c
|
||||
if n ~= numEntries then
|
||||
return false, "prediction: value count mismatch"
|
||||
end
|
||||
local ct = md.ct
|
||||
local function previous(p: number)
|
||||
local off = (p - 1) * comps
|
||||
for c = 1, comps do
|
||||
pred[c] = data[off + c]
|
||||
end
|
||||
end
|
||||
if m == PARALLELOGRAM or m == MULTI or m == CONSTRAINED then
|
||||
if n == 0 then
|
||||
return true, nil
|
||||
end
|
||||
apply(tr, pred, data, 0, comps)
|
||||
local para = table.create(comps, 0)
|
||||
local preds: { { number } } = { table.create(comps, 0), table.create(comps, 0), table.create(comps, 0), table.create(comps, 0) }
|
||||
local creasePos = { 0, 0, 0, 0 }
|
||||
local nc = ct.nf * 3
|
||||
for p = 1, n - 1 do
|
||||
local start = e2c[p + 1]
|
||||
local off = p * comps
|
||||
if m == PARALLELOGRAM then
|
||||
if parallelogram(md, p, start, data, comps, pred) then
|
||||
apply(tr, pred, data, off, comps)
|
||||
else
|
||||
previous(p)
|
||||
apply(tr, pred, data, off, comps)
|
||||
end
|
||||
elseif m == MULTI then
|
||||
for c = 1, comps do
|
||||
pred[c] = 0
|
||||
end
|
||||
local count = 0
|
||||
local ci = start
|
||||
local guard = 0
|
||||
while ci ~= -1 do
|
||||
if parallelogram(md, p, ci, data, comps, para) then
|
||||
for c = 1, comps do
|
||||
pred[c] = i32(pred[c] + para[c])
|
||||
end
|
||||
count += 1
|
||||
end
|
||||
ci = swingRight(ct, ci)
|
||||
if ci == start then
|
||||
ci = -1
|
||||
end
|
||||
guard += 1
|
||||
if guard > nc then
|
||||
return false, "prediction: bad vertex fan"
|
||||
end
|
||||
end
|
||||
if count == 0 then
|
||||
previous(p)
|
||||
else
|
||||
for c = 1, comps do
|
||||
pred[c] = tdiv(pred[c], count)
|
||||
end
|
||||
end
|
||||
apply(tr, pred, data, off, comps)
|
||||
else
|
||||
local count = 0
|
||||
local ci = start
|
||||
local first = true
|
||||
local guard = 0
|
||||
while ci ~= -1 do
|
||||
if parallelogram(md, p, ci, data, comps, preds[count + 1]) then
|
||||
count += 1
|
||||
if count == 4 then
|
||||
break
|
||||
end
|
||||
end
|
||||
if first then
|
||||
ci = swingLeft(ct, ci)
|
||||
else
|
||||
ci = swingRight(ct, ci)
|
||||
end
|
||||
if ci == start then
|
||||
break
|
||||
end
|
||||
if ci == -1 and first then
|
||||
first = false
|
||||
ci = swingRight(ct, start)
|
||||
end
|
||||
guard += 1
|
||||
if guard > nc then
|
||||
return false, "prediction: bad vertex fan"
|
||||
end
|
||||
end
|
||||
local used = 0
|
||||
if count > 0 then
|
||||
for c = 1, comps do
|
||||
pred[c] = 0
|
||||
end
|
||||
local crease = s.crease :: { { boolean } }
|
||||
for i = 1, count do
|
||||
local pos = creasePos[count] + 1
|
||||
creasePos[count] = pos
|
||||
local flag = crease[count][pos]
|
||||
if flag == nil then
|
||||
return false, "prediction: crease flags run out"
|
||||
end
|
||||
if not flag then
|
||||
used += 1
|
||||
for c = 1, comps do
|
||||
pred[c] = i32(pred[c] + preds[i][c])
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if used == 0 then
|
||||
previous(p)
|
||||
else
|
||||
for c = 1, comps do
|
||||
pred[c] = tdiv(pred[c], used)
|
||||
end
|
||||
end
|
||||
apply(tr, pred, data, off, comps)
|
||||
end
|
||||
end
|
||||
return true, nil
|
||||
end
|
||||
local parent = s.parent
|
||||
if not parent then
|
||||
return false, "prediction: no position attribute"
|
||||
end
|
||||
local c2v, v2e = ct.c2v, md.v2e
|
||||
local function entryOf(c: number): number
|
||||
local v = if c < 0 then -1 else (c2v[c + 1] or -1)
|
||||
if v < 0 then
|
||||
return math.huge
|
||||
end
|
||||
return v2e[v + 1] or 0
|
||||
end
|
||||
local function posOf(e: number): (number, number, number)
|
||||
local pt = points[e + 1]
|
||||
if pt == nil then
|
||||
return 0, 0, 0
|
||||
end
|
||||
return parent(pt)
|
||||
end
|
||||
if m == TEXPORT or m == TEXDEP then
|
||||
if comps ~= 2 then
|
||||
return false, "prediction: tex coords need 2 components"
|
||||
end
|
||||
local orient = s.orient :: { boolean }
|
||||
local no = #orient
|
||||
for p = 0, n - 1 do
|
||||
local ci = e2c[p + 1]
|
||||
local ne, pe = entryOf(nextC(ci)), entryOf(prevC(ci))
|
||||
local done = false
|
||||
if pe < p and ne < p then
|
||||
local nu, nv = data[ne * 2 + 1], data[ne * 2 + 2]
|
||||
local pu, pv = data[pe * 2 + 1], data[pe * 2 + 2]
|
||||
if m == TEXPORT then
|
||||
if pu == nu and pv == nv then
|
||||
pred[1], pred[2] = pu, pv
|
||||
done = true
|
||||
else
|
||||
local tx, ty, tz = posOf(p)
|
||||
local nx, ny, nz = posOf(ne)
|
||||
local qx, qy, qz = posOf(pe)
|
||||
local status, u, v = texPortable(nu, nv, pu, pv, tx, ty, tz, nx, ny, nz, qx, qy, qz, function(): boolean?
|
||||
if no == 0 then
|
||||
return nil
|
||||
end
|
||||
local o = orient[no]
|
||||
orient[no] = nil
|
||||
no -= 1
|
||||
return o
|
||||
end)
|
||||
if status == "fail" then
|
||||
return false, u :: any
|
||||
elseif status == "ok" then
|
||||
pred[1], pred[2] = u, v
|
||||
done = true
|
||||
end
|
||||
end
|
||||
else
|
||||
local fnu, fnv, fpu, fpv = fround(nu), fround(nv), fround(pu), fround(pv)
|
||||
if fpu == fnu and fpv == fnv then
|
||||
pred[1], pred[2] = truncInt(fpu), truncInt(fpv)
|
||||
done = true
|
||||
else
|
||||
local tx: number, ty: number, tz: number = posOf(p)
|
||||
local nx: number, ny: number, nz: number = posOf(ne)
|
||||
local qx: number, qy: number, qz: number = posOf(pe)
|
||||
tx, ty, tz, nx, ny, nz = fround(tx), fround(ty), fround(tz), fround(nx), fround(ny), fround(nz)
|
||||
qx, qy, qz = fround(qx), fround(qy), fround(qz)
|
||||
local pnx, pny, pnz = fround(qx - nx), fround(qy - ny), fround(qz - nz)
|
||||
local cnx, cny, cnz = fround(tx - nx), fround(ty - ny), fround(tz - nz)
|
||||
local pn2 = fround(fround(fround(pnx * pnx) + fround(pny * pny)) + fround(pnz * pnz))
|
||||
local sv, tv = 0, 0
|
||||
if s.ver < 0x0102 or pn2 > 0 then
|
||||
local dot = fround(fround(fround(pnx * cnx) + fround(pny * cny)) + fround(pnz * cnz))
|
||||
sv = fround(dot / pn2)
|
||||
local ex, ey, ez = fround(cnx - fround(pnx * sv)), fround(cny - fround(pny * sv)), fround(cnz - fround(pnz * sv))
|
||||
local e2 = fround(fround(fround(ex * ex) + fround(ey * ey)) + fround(ez * ez))
|
||||
tv = fround(math.sqrt(fround(e2 / pn2)))
|
||||
end
|
||||
local pnu, pnv = fround(fpu - fnu), fround(fpv - fnv)
|
||||
local pnus = fround(fround(pnu * sv) + fnu)
|
||||
local pnut = fround(pnu * tv)
|
||||
local pnvs = fround(fround(pnv * sv) + fnv)
|
||||
local pnvt = fround(pnv * tv)
|
||||
if no == 0 then
|
||||
return false, "prediction: orientations run out"
|
||||
end
|
||||
local o = orient[no]
|
||||
orient[no] = nil
|
||||
no -= 1
|
||||
local u: number, v: number = 0, 0
|
||||
if o then
|
||||
u = fround(pnus - pnvt)
|
||||
v = fround(pnvs + pnut)
|
||||
else
|
||||
u = fround(pnus + pnvt)
|
||||
v = fround(pnvs - pnut)
|
||||
end
|
||||
local function toInt(x: number): number
|
||||
local r = math.floor(x + 0.5)
|
||||
if r ~= r or r > 2147483647 or r < -2147483648 then
|
||||
return -2147483648
|
||||
end
|
||||
return r
|
||||
end
|
||||
pred[1] = toInt(u)
|
||||
pred[2] = toInt(v)
|
||||
done = true
|
||||
end
|
||||
end
|
||||
end
|
||||
if not done then
|
||||
local off = -1
|
||||
if pe < p then
|
||||
off = pe * 2
|
||||
end
|
||||
if ne < p then
|
||||
off = ne * 2
|
||||
elseif p > 0 then
|
||||
off = (p - 1) * 2
|
||||
else
|
||||
off = -1
|
||||
end
|
||||
if off < 0 then
|
||||
pred[1], pred[2] = 0, 0
|
||||
else
|
||||
pred[1], pred[2] = data[off + 1], data[off + 2]
|
||||
end
|
||||
end
|
||||
apply(tr, pred, data, p * 2, 2)
|
||||
end
|
||||
return true, nil
|
||||
end
|
||||
-- geometric normal
|
||||
local o = tr.oct
|
||||
local flips = s.flips
|
||||
if not o or not flips or comps ~= 2 then
|
||||
return false, "prediction: bad geometric normal setup"
|
||||
end
|
||||
local nc = ct.nf * 3
|
||||
for p = 0, n - 1 do
|
||||
local ci = e2c[p + 1]
|
||||
local cx, cy, cz = posOf(entryOf(ci))
|
||||
local sx, sy, sz = 0, 0, 0
|
||||
-- VertexCornersIterator from ci: swing left, then right from the start
|
||||
local c = ci
|
||||
local left = true
|
||||
local guard = 0
|
||||
while c ~= -1 do
|
||||
local cn, cp
|
||||
if s.areaMode then
|
||||
cn, cp = nextC(c), prevC(c)
|
||||
else
|
||||
cn, cp = nextC(ci), prevC(ci)
|
||||
end
|
||||
local ax, ay, az = posOf(entryOf(cn))
|
||||
local bx, by, bz = posOf(entryOf(cp))
|
||||
ax, ay, az = ax - cx, ay - cy, az - cz
|
||||
bx, by, bz = bx - cx, by - cy, bz - cz
|
||||
sx += ay * bz - az * by
|
||||
sy += az * bx - ax * bz
|
||||
sz += ax * by - ay * bx
|
||||
if left then
|
||||
c = swingLeft(ct, c)
|
||||
if c == -1 then
|
||||
c = swingRight(ct, ci)
|
||||
left = false
|
||||
elseif c == ci then
|
||||
c = -1
|
||||
end
|
||||
else
|
||||
c = swingRight(ct, c)
|
||||
end
|
||||
guard += 1
|
||||
if guard > nc then
|
||||
return false, "prediction: bad vertex fan"
|
||||
end
|
||||
end
|
||||
local upper = 2 ^ 29
|
||||
local sum = math.abs(sx) + math.abs(sy) + math.abs(sz)
|
||||
if sum > upper then
|
||||
local q = sum // upper
|
||||
sx, sy, sz = tdiv(sx, q), tdiv(sy, q), tdiv(sz, q)
|
||||
end
|
||||
sx, sy, sz = i32(sx), i32(sy), i32(sz)
|
||||
sx, sy, sz = canonicalizeVector(o, sx, sy, sz)
|
||||
if Reader.bit(flips) then
|
||||
sx, sy, sz = -sx, -sy, -sz
|
||||
end
|
||||
pred[1], pred[2] = intVectorToOct(o, sx, sy, sz)
|
||||
apply(tr, pred, data, p * 2, 2)
|
||||
end
|
||||
return true, nil
|
||||
end
|
||||
|
||||
return Predict
|
||||
@@ -0,0 +1,480 @@
|
||||
--!strict
|
||||
-- codecs/model/Draco/Reader: the Draco decoder buffer (little-endian fields, LEB128 varints, LSB-first bit runs) and
|
||||
-- its entropy decoders: rANS symbol coding (tagged and raw schemes, DecodeSymbols) and the binary rANS / rABS bit
|
||||
-- decoder. Ported from Google's Draco 1.5.7 (core/decoder_buffer, core/varint_decoding, compression/entropy/ans.h,
|
||||
-- rans_symbol_decoder.h, symbol_decoding.cc, compression/bit_coders/rans_bit_decoder.cc; Apache-2.0,
|
||||
-- licenses/draco-LICENSE.txt). Bitstream versions 1.0 - 2.2 (fixed-width counts before 2.0 / 2.2).
|
||||
-- A failed read sets the sticky d.bad message and returns 0; callers check d.bad at their boundaries.
|
||||
local Reader = {}
|
||||
|
||||
local readu8, readu16, readu32, readi32, readf32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi32, buffer.readf32
|
||||
local band, rshift = bit32.band, bit32.rshift
|
||||
|
||||
export type D = {
|
||||
b: buffer,
|
||||
pos: number, -- absolute offset in b
|
||||
limit: number, -- absolute end
|
||||
ver: number, -- major * 256 + minor
|
||||
bad: string?,
|
||||
bitMode: boolean,
|
||||
bitStart: number, -- absolute byte where the bit run starts
|
||||
bitOff: number, -- bits consumed
|
||||
}
|
||||
|
||||
function Reader.new(b: buffer, pos: number, limit: number, ver: number): D
|
||||
return { b = b, pos = pos, limit = limit, ver = ver, bad = nil, bitMode = false, bitStart = pos, bitOff = 0 }
|
||||
end
|
||||
|
||||
-- a copy (C++ DecoderBuffer is copied by value: positions are independent afterwards)
|
||||
function Reader.copy(d: D): D
|
||||
return { b = d.b, pos = d.pos, limit = d.limit, ver = d.ver, bad = d.bad, bitMode = d.bitMode, bitStart = d.bitStart, bitOff = d.bitOff }
|
||||
end
|
||||
|
||||
function Reader.fail(d: D, msg: string): number
|
||||
if not d.bad then
|
||||
d.bad = msg
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
function Reader.remaining(d: D): number
|
||||
return d.limit - d.pos
|
||||
end
|
||||
|
||||
function Reader.u8(d: D): number
|
||||
local p = d.pos
|
||||
if p + 1 > d.limit then
|
||||
return Reader.fail(d, "truncated")
|
||||
end
|
||||
d.pos = p + 1
|
||||
return readu8(d.b, p)
|
||||
end
|
||||
|
||||
function Reader.i8(d: D): number
|
||||
local v = Reader.u8(d)
|
||||
return if v >= 128 then v - 256 else v
|
||||
end
|
||||
|
||||
function Reader.u16(d: D): number
|
||||
local p = d.pos
|
||||
if p + 2 > d.limit then
|
||||
return Reader.fail(d, "truncated")
|
||||
end
|
||||
d.pos = p + 2
|
||||
return readu16(d.b, p)
|
||||
end
|
||||
|
||||
function Reader.u32(d: D): number
|
||||
local p = d.pos
|
||||
if p + 4 > d.limit then
|
||||
return Reader.fail(d, "truncated")
|
||||
end
|
||||
d.pos = p + 4
|
||||
return readu32(d.b, p)
|
||||
end
|
||||
|
||||
function Reader.i32(d: D): number
|
||||
local p = d.pos
|
||||
if p + 4 > d.limit then
|
||||
return Reader.fail(d, "truncated")
|
||||
end
|
||||
d.pos = p + 4
|
||||
return readi32(d.b, p)
|
||||
end
|
||||
|
||||
-- u64 as a number (exact below 2^53; sizes beyond that fail the bounds checks anyway)
|
||||
function Reader.u64(d: D): number
|
||||
local p = d.pos
|
||||
if p + 8 > d.limit then
|
||||
return Reader.fail(d, "truncated")
|
||||
end
|
||||
d.pos = p + 8
|
||||
return readu32(d.b, p) + readu32(d.b, p + 4) * 4294967296
|
||||
end
|
||||
|
||||
function Reader.f32(d: D): number
|
||||
local p = d.pos
|
||||
if p + 4 > d.limit then
|
||||
return Reader.fail(d, "truncated")
|
||||
end
|
||||
d.pos = p + 4
|
||||
return readf32(d.b, p)
|
||||
end
|
||||
|
||||
-- LEB128 (at most 5 bytes for 32-bit values, 10 for 64-bit); 32-bit values wrap like the C++ shifts
|
||||
function Reader.varint(d: D, wide: boolean?): number
|
||||
local maxBytes = if wide then 10 else 5
|
||||
local v, mul = 0, 1
|
||||
for _ = 1, maxBytes do
|
||||
local p = d.pos
|
||||
if p + 1 > d.limit then
|
||||
return Reader.fail(d, "truncated varint")
|
||||
end
|
||||
local c = readu8(d.b, p)
|
||||
d.pos = p + 1
|
||||
v += band(c, 127) * mul
|
||||
if c < 128 then
|
||||
if not wide then
|
||||
v %= 4294967296
|
||||
end
|
||||
return v
|
||||
end
|
||||
mul *= 128
|
||||
end
|
||||
return Reader.fail(d, "varint too long")
|
||||
end
|
||||
|
||||
-- a count stored as u32 before `fixedBefore` (a version number) and as a varint from then on
|
||||
function Reader.count(d: D, fixedBefore: number): number
|
||||
if d.ver < fixedBefore then
|
||||
return Reader.u32(d)
|
||||
end
|
||||
return Reader.varint(d)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ bit runs
|
||||
-- StartBitDecoding(decodeSize): an optional size (u64 before 2.2, varint64 after), then LSB-first bits up to the end
|
||||
-- of the buffer; EndBitDecoding moves pos past the whole bytes consumed.
|
||||
function Reader.startBits(d: D, decodeSize: boolean): number
|
||||
local size = 0
|
||||
if decodeSize then
|
||||
if d.ver < 0x0202 then
|
||||
size = Reader.u64(d)
|
||||
else
|
||||
size = Reader.varint(d, true)
|
||||
end
|
||||
end
|
||||
d.bitMode = true
|
||||
d.bitStart = d.pos
|
||||
d.bitOff = 0
|
||||
return size
|
||||
end
|
||||
|
||||
function Reader.bits(d: D, n: number): number
|
||||
if not d.bitMode then
|
||||
return Reader.fail(d, "bit decoder not active")
|
||||
end
|
||||
if n > 32 then
|
||||
return Reader.fail(d, "bit run over 32 bits")
|
||||
end
|
||||
local b, start, limit = d.b, d.bitStart, d.limit
|
||||
local off = d.bitOff
|
||||
local v, mul = 0, 1
|
||||
for _ = 1, n do
|
||||
local byte = start + rshift(off, 3)
|
||||
if byte < limit then
|
||||
if band(rshift(readu8(b, byte), band(off, 7)), 1) == 1 then
|
||||
v += mul
|
||||
end
|
||||
off += 1
|
||||
end
|
||||
mul *= 2
|
||||
end
|
||||
d.bitOff = off
|
||||
return v
|
||||
end
|
||||
|
||||
function Reader.endBits(d: D)
|
||||
d.bitMode = false
|
||||
d.pos = d.bitStart + (d.bitOff + 7) // 8
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ rANS symbols
|
||||
-- the precision for a symbol alphabet of `bitLength`-bit symbols: (3 * bits) / 2 clamped to 12..20
|
||||
local function precisionBits(bitLength: number): number
|
||||
local p = (3 * bitLength) // 2
|
||||
return if p < 12 then 12 elseif p > 20 then 20 else p
|
||||
end
|
||||
|
||||
export type Rans = {
|
||||
b: buffer,
|
||||
base: number, -- absolute start of the coded bytes
|
||||
off: number, -- bytes left (read backwards from base + off)
|
||||
state: number,
|
||||
lBase: number,
|
||||
precBits: number,
|
||||
lut: { number }, -- rem + 1 -> symbol + 1
|
||||
prob: { number },
|
||||
cum: { number },
|
||||
numSymbols: number,
|
||||
}
|
||||
|
||||
-- RAnsSymbolDecoder::Create: the probability table
|
||||
local function ransCreate(d: D, precBits: number): Rans?
|
||||
local numSymbols = Reader.count(d, 0x0200)
|
||||
if d.bad then
|
||||
return nil
|
||||
end
|
||||
if numSymbols // 64 > Reader.remaining(d) then
|
||||
Reader.fail(d, "rans: too many symbols")
|
||||
return nil
|
||||
end
|
||||
local prec = 2 ^ precBits
|
||||
local prob = table.create(numSymbols, 0)
|
||||
local i = 0
|
||||
while i < numSymbols do
|
||||
local data = Reader.u8(d)
|
||||
if d.bad then
|
||||
return nil
|
||||
end
|
||||
local token = band(data, 3)
|
||||
if token == 3 then
|
||||
local offset = rshift(data, 2)
|
||||
if i + offset >= numSymbols then
|
||||
Reader.fail(d, "rans: bad zero run")
|
||||
return nil
|
||||
end
|
||||
for j = 0, offset do
|
||||
prob[i + j + 1] = 0
|
||||
end
|
||||
i += offset + 1
|
||||
else
|
||||
local p = rshift(data, 2)
|
||||
for k = 1, token do
|
||||
p += Reader.u8(d) * 2 ^ (8 * k - 2)
|
||||
end
|
||||
if d.bad then
|
||||
return nil
|
||||
end
|
||||
prob[i + 1] = p
|
||||
i += 1
|
||||
end
|
||||
end
|
||||
local lut: { number } = {}
|
||||
local cum = table.create(numSymbols, 0)
|
||||
if numSymbols > 0 then
|
||||
lut = table.create(prec, 0)
|
||||
local c, act = 0, 0
|
||||
for s = 1, numSymbols do
|
||||
cum[s] = c
|
||||
c += prob[s]
|
||||
if c > prec then
|
||||
Reader.fail(d, "rans: probabilities over the precision")
|
||||
return nil
|
||||
end
|
||||
for j = act + 1, c do
|
||||
lut[j] = s
|
||||
end
|
||||
act = c
|
||||
end
|
||||
if c ~= prec then
|
||||
Reader.fail(d, "rans: probabilities do not sum to the precision")
|
||||
return nil
|
||||
end
|
||||
end
|
||||
return {
|
||||
b = d.b,
|
||||
base = 0,
|
||||
off = 0,
|
||||
state = 0,
|
||||
lBase = prec * 4,
|
||||
precBits = precBits,
|
||||
lut = lut,
|
||||
prob = prob,
|
||||
cum = cum,
|
||||
numSymbols = numSymbols,
|
||||
}
|
||||
end
|
||||
|
||||
-- read_init over [base, base + size): the final state is stored in the last 1-4 bytes
|
||||
local function ansInit(b: buffer, base: number, size: number, lBase: number, allow4: boolean): (number?, number?)
|
||||
if size < 1 then
|
||||
return nil, nil
|
||||
end
|
||||
local x = rshift(readu8(b, base + size - 1), 6)
|
||||
local off: number, state: number = 0, 0
|
||||
if x == 0 then
|
||||
off = size - 1
|
||||
state = band(readu8(b, base + size - 1), 0x3F)
|
||||
elseif x == 1 then
|
||||
if size < 2 then
|
||||
return nil, nil
|
||||
end
|
||||
off = size - 2
|
||||
state = band(readu16(b, base + size - 2), 0x3FFF)
|
||||
elseif x == 2 then
|
||||
if size < 3 then
|
||||
return nil, nil
|
||||
end
|
||||
off = size - 3
|
||||
state = readu16(b, base + size - 3) + band(readu8(b, base + size - 1), 0x3F) * 65536
|
||||
else
|
||||
if not allow4 or size < 4 then
|
||||
return nil, nil
|
||||
end
|
||||
off = size - 4
|
||||
state = band(readu32(b, base + size - 4), 0x3FFFFFFF)
|
||||
end
|
||||
state += lBase
|
||||
if state >= lBase * 256 then
|
||||
return nil, nil
|
||||
end
|
||||
return off, state
|
||||
end
|
||||
|
||||
-- RAnsSymbolDecoder::StartDecoding: the coded size, then the bytes
|
||||
local function ransStart(d: D, r: Rans): boolean
|
||||
local size
|
||||
if d.ver < 0x0200 then
|
||||
size = Reader.u64(d)
|
||||
else
|
||||
size = Reader.varint(d, true)
|
||||
end
|
||||
if d.bad then
|
||||
return false
|
||||
end
|
||||
if size > Reader.remaining(d) then
|
||||
Reader.fail(d, "rans: data past the end")
|
||||
return false
|
||||
end
|
||||
local off, state = ansInit(d.b, d.pos, size, r.lBase, true)
|
||||
if not off then
|
||||
Reader.fail(d, "rans: bad initial state")
|
||||
return false
|
||||
end
|
||||
r.base, r.off, r.state = d.pos, off, state :: number
|
||||
d.pos += size
|
||||
return true
|
||||
end
|
||||
|
||||
-- decodes n symbols into out[first .. first + n - 1] (0-based symbol values)
|
||||
local function ransRead(r: Rans, n: number, out: { number }, first: number)
|
||||
local b, base, off, state = r.b, r.base, r.off, r.state
|
||||
local lBase, bits = r.lBase, r.precBits
|
||||
local mask = 2 ^ bits - 1
|
||||
local lut, prob, cum = r.lut, r.prob, r.cum
|
||||
for i = first, first + n - 1 do
|
||||
while state < lBase and off > 0 do
|
||||
off -= 1
|
||||
state = state * 256 + readu8(b, base + off)
|
||||
end
|
||||
local quo, rem = rshift(state, bits), band(state, mask)
|
||||
local s = lut[rem + 1]
|
||||
state = quo * prob[s] + rem - cum[s]
|
||||
out[i] = s - 1
|
||||
end
|
||||
r.off, r.state = off, state
|
||||
end
|
||||
|
||||
local function decodeTagged(d: D, n: number, comps: number, out: { number }): boolean
|
||||
local tag = ransCreate(d, precisionBits(5))
|
||||
if not tag or not ransStart(d, tag) then
|
||||
return false
|
||||
end
|
||||
if n > 0 and tag.numSymbols == 0 then
|
||||
Reader.fail(d, "rans: no symbols")
|
||||
return false
|
||||
end
|
||||
Reader.startBits(d, false)
|
||||
local len = { 0 }
|
||||
local k = 1
|
||||
local i = 0
|
||||
while i < n do
|
||||
ransRead(tag, 1, len, 1)
|
||||
local bitLength = len[1]
|
||||
for _ = 1, comps do
|
||||
if k > n then
|
||||
break
|
||||
end
|
||||
out[k] = Reader.bits(d, bitLength)
|
||||
k += 1
|
||||
end
|
||||
if d.bad then
|
||||
return false
|
||||
end
|
||||
i += comps
|
||||
end
|
||||
Reader.endBits(d)
|
||||
return true
|
||||
end
|
||||
|
||||
local function decodeRaw(d: D, n: number, out: { number }): boolean
|
||||
local maxBitLength = Reader.u8(d)
|
||||
if d.bad then
|
||||
return false
|
||||
end
|
||||
if maxBitLength < 1 or maxBitLength > 18 then
|
||||
Reader.fail(d, "rans: bad symbol bit length")
|
||||
return false
|
||||
end
|
||||
local r = ransCreate(d, precisionBits(maxBitLength))
|
||||
if not r then
|
||||
return false
|
||||
end
|
||||
if n > 0 and r.numSymbols == 0 then
|
||||
Reader.fail(d, "rans: no symbols")
|
||||
return false
|
||||
end
|
||||
if not ransStart(d, r) then
|
||||
return false
|
||||
end
|
||||
ransRead(r, n, out, 1)
|
||||
return true
|
||||
end
|
||||
|
||||
-- DecodeSymbols(n, components) -> { u32 } (1-based) | nil (d.bad set)
|
||||
function Reader.symbols(d: D, n: number, comps: number): { number }?
|
||||
local out = table.create(n, 0)
|
||||
if n == 0 then
|
||||
return out
|
||||
end
|
||||
local scheme = Reader.u8(d)
|
||||
if d.bad then
|
||||
return nil
|
||||
end
|
||||
local ok
|
||||
if scheme == 0 then
|
||||
ok = decodeTagged(d, n, math.max(comps, 1), out)
|
||||
elseif scheme == 1 then
|
||||
ok = decodeRaw(d, n, out)
|
||||
else
|
||||
Reader.fail(d, "rans: unknown symbol coding scheme")
|
||||
ok = false
|
||||
end
|
||||
return if ok then out else nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ binary rANS
|
||||
export type Bits = { b: buffer, base: number, off: number, state: number, p0: number, p: number }
|
||||
|
||||
-- RAnsBitDecoder::StartDecoding: prob_zero, the size (u32 before 2.2), the bytes
|
||||
function Reader.bitDecoder(d: D): Bits?
|
||||
local p0 = Reader.u8(d)
|
||||
local size = Reader.count(d, 0x0202)
|
||||
if d.bad then
|
||||
return nil
|
||||
end
|
||||
if size > Reader.remaining(d) then
|
||||
Reader.fail(d, "rabs: data past the end")
|
||||
return nil
|
||||
end
|
||||
local off, state = ansInit(d.b, d.pos, size, 4096, false)
|
||||
if not off then
|
||||
Reader.fail(d, "rabs: bad initial state")
|
||||
return nil
|
||||
end
|
||||
local bd = { b = d.b, base = d.pos, off = off, state = state :: number, p0 = p0, p = 256 - p0 }
|
||||
d.pos += size
|
||||
return bd
|
||||
end
|
||||
|
||||
-- rabs_desc_read: one bit (true / false)
|
||||
function Reader.bit(bd: Bits): boolean
|
||||
local state, off = bd.state, bd.off
|
||||
if state < 4096 and off > 0 then
|
||||
off -= 1
|
||||
state = state * 256 + readu8(bd.b, bd.base + off)
|
||||
bd.off = off
|
||||
end
|
||||
local quot, rem = rshift(state, 8), band(state, 255)
|
||||
local p = bd.p
|
||||
local xn = quot * p
|
||||
if rem < p then
|
||||
bd.state = xn + rem
|
||||
return true
|
||||
end
|
||||
bd.state = state - xn - p
|
||||
return false
|
||||
end
|
||||
|
||||
return Reader
|
||||
@@ -0,0 +1,354 @@
|
||||
--!strict
|
||||
-- codecs/model/Draco: Google Draco geometry decompression (.drc; glTF KHR_draco_mesh_compression; Roblox mesh v6 / v7).
|
||||
-- A codec, not a format: model/gltf (and any format carrying Draco data) calls it on a byte range.
|
||||
-- Ported from Google's Draco 1.5.7 (Apache-2.0, licenses/draco-LICENSE.txt): the decoder only, bitstream versions
|
||||
-- 1.0 - 2.2 for meshes (sequential and Edgebreaker connectivity: standard, predictive and valence traversals; topology
|
||||
-- splits, attribute seams) and sequential point clouds; attribute decoders generic / integer / quantization /
|
||||
-- octahedral normals; prediction schemes difference, parallelogram, multi-parallelogram, constrained
|
||||
-- multi-parallelogram, tex coords (deprecated and portable), geometric normal, with the wrap and normal octahedron
|
||||
-- transforms; metadata. Values match draco_decoder bit for bit (f32 rounding at every step of the dequantization).
|
||||
-- Not supported: kd-tree point clouds (Err.UNSUPPORTED).
|
||||
--
|
||||
-- local Draco = require("@formats/codecs/model/Draco")
|
||||
-- local g, err = Draco.decode(buf, off?, len?, opts?) -- buffer | string
|
||||
-- g.kind ("mesh" | "points"), g.numPoints, g.numFaces, g.indices (u32 x 3 per face, or nil for points)
|
||||
-- g.attributes[i] = { name = "POSITION" | "NORMAL" | "COLOR" | "TEX_COORD" | "GENERIC" | ..., uniqueId,
|
||||
-- components, type = "f32" | "u8" | "i16" | ..., normalized, data (per point, packed) }
|
||||
-- Draco.attribute(g, uniqueId) -> the attribute with that unique id (glTF's attribute map)
|
||||
-- g.metadata = { entries = { [name] = buffer }, children = { [name] = Metadata }, attributes = { [uniqueId] = Metadata } }
|
||||
--
|
||||
-- Options: maxPoints (default 2^24), maxFaces (default 2^24): larger geometry returns Err.LIMIT.
|
||||
-- Never throws: bad data returns nil, Err (TRUNCATED / CORRUPT / UNSUPPORTED / LIMIT).
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Reader = require("@formats/codecs/model/Draco/Reader")
|
||||
local Connectivity = require("@formats/codecs/model/Draco/Connectivity")
|
||||
local Attributes = require("@formats/codecs/model/Draco/Attributes")
|
||||
|
||||
local Draco = {}
|
||||
|
||||
local NAMES = { [0] = "POSITION", "NORMAL", "COLOR", "TEX_COORD", "GENERIC", "TANGENT", "MATERIAL", "JOINTS", "WEIGHTS" }
|
||||
local TYPES = { "i8", "u8", "i16", "u16", "i32", "u32", "i64", "u64", "f32", "f64", "bool" }
|
||||
Draco.ATTRIBUTE_NAMES = NAMES
|
||||
Draco.DATA_TYPES = TYPES
|
||||
|
||||
export type Attribute = {
|
||||
name: string,
|
||||
typeId: number,
|
||||
uniqueId: number,
|
||||
components: number,
|
||||
type: string,
|
||||
normalized: boolean,
|
||||
data: buffer,
|
||||
}
|
||||
export type Metadata = { entries: { [string]: buffer }, children: { [string]: Metadata }, attributes: { [number]: Metadata }? }
|
||||
export type Geometry = {
|
||||
kind: "mesh" | "points",
|
||||
version: string,
|
||||
method: string,
|
||||
numPoints: number,
|
||||
numFaces: number,
|
||||
indices: buffer?,
|
||||
attributes: { Attribute },
|
||||
metadata: Metadata?,
|
||||
}
|
||||
export type Header = { major: number, minor: number, kind: "mesh" | "points", method: number, flags: number }
|
||||
|
||||
-- sniff(buf, off?) -> whether the bytes start with "DRACO"
|
||||
function Draco.sniff(buf: buffer, off: number?): boolean
|
||||
local o = off or 0
|
||||
return buffer.len(buf) >= o + 5 and buffer.readstring(buf, o, 5) == "DRACO"
|
||||
end
|
||||
|
||||
local function header(d: Reader.D): (Header?, string?)
|
||||
if Reader.remaining(d) < 11 then
|
||||
return nil, "truncated header"
|
||||
end
|
||||
if buffer.readstring(d.b, d.pos, 5) ~= "DRACO" then
|
||||
return nil, "not Draco data"
|
||||
end
|
||||
d.pos += 5
|
||||
local major, minor, kind, method = Reader.u8(d), Reader.u8(d), Reader.u8(d), Reader.u8(d)
|
||||
local flags = Reader.u16(d)
|
||||
if kind > 1 then
|
||||
return nil, "unsupported: geometry type " .. kind
|
||||
end
|
||||
return { major = major, minor = minor, kind = if kind == 0 then "points" else "mesh", method = method, flags = flags }, nil
|
||||
end
|
||||
|
||||
-- info(buf, off?, len?) -> the header
|
||||
function Draco.info(src: buffer | string, off: number?, len: number?): (Header?, Err.Err?)
|
||||
local buf, o, l, aerr = Bytes.span("draco", src, off, len)
|
||||
if not buf then
|
||||
return nil, aerr
|
||||
end
|
||||
local d = Reader.new(buf, o, o + l, 0)
|
||||
local h, err = header(d)
|
||||
if not h then
|
||||
return nil, Err.from(err, 0)
|
||||
end
|
||||
return h, nil
|
||||
end
|
||||
|
||||
local function metadataElement(d: Reader.D, depth: number): Metadata?
|
||||
if depth > 1000 then
|
||||
return nil
|
||||
end
|
||||
local m: Metadata = { entries = {}, children = {} }
|
||||
local n = Reader.varint(d)
|
||||
if d.bad or n > Reader.remaining(d) then
|
||||
return nil
|
||||
end
|
||||
for _ = 1, n do
|
||||
local nameLen = Reader.u8(d)
|
||||
if d.bad or Reader.remaining(d) < nameLen then
|
||||
return nil
|
||||
end
|
||||
local name = buffer.readstring(d.b, d.pos, nameLen)
|
||||
d.pos += nameLen
|
||||
local size = Reader.varint(d)
|
||||
if d.bad or size == 0 or size > Reader.remaining(d) then
|
||||
return nil
|
||||
end
|
||||
local v = buffer.create(size)
|
||||
buffer.copy(v, 0, d.b, d.pos, size)
|
||||
d.pos += size
|
||||
m.entries[name] = v
|
||||
end
|
||||
local subs = Reader.varint(d)
|
||||
if d.bad or subs > Reader.remaining(d) then
|
||||
return nil
|
||||
end
|
||||
for _ = 1, subs do
|
||||
local nameLen = Reader.u8(d)
|
||||
if d.bad or Reader.remaining(d) < nameLen then
|
||||
return nil
|
||||
end
|
||||
local name = buffer.readstring(d.b, d.pos, nameLen)
|
||||
d.pos += nameLen
|
||||
local child = metadataElement(d, depth + 1)
|
||||
if not child then
|
||||
return nil
|
||||
end
|
||||
m.children[name] = child
|
||||
end
|
||||
return m
|
||||
end
|
||||
|
||||
local function metadata(d: Reader.D): Metadata?
|
||||
local n = Reader.varint(d)
|
||||
if d.bad or n > Reader.remaining(d) then
|
||||
return nil
|
||||
end
|
||||
local atts: { [number]: Metadata } = {}
|
||||
for _ = 1, n do
|
||||
local id = Reader.varint(d)
|
||||
local m = metadataElement(d, 0)
|
||||
if not m then
|
||||
return nil
|
||||
end
|
||||
atts[id] = m
|
||||
end
|
||||
local m = metadataElement(d, 0)
|
||||
if not m then
|
||||
return nil
|
||||
end
|
||||
m.attributes = atts
|
||||
return m
|
||||
end
|
||||
|
||||
local WRITE: { [number]: (buffer, number, number) -> () } = {
|
||||
[1] = buffer.writei8,
|
||||
[2] = buffer.writeu8,
|
||||
[3] = buffer.writei16,
|
||||
[4] = buffer.writeu16,
|
||||
[5] = buffer.writei32,
|
||||
[6] = buffer.writeu32,
|
||||
[9] = buffer.writef32,
|
||||
[11] = buffer.writeu8,
|
||||
}
|
||||
|
||||
-- per point output buffer of an attribute
|
||||
local function expand(a: Attributes.Attr, numPoints: number): (buffer?, string?)
|
||||
local size = Attributes.DT_LENGTH[a.dataType]
|
||||
local comps = a.comps
|
||||
local stride = size * comps
|
||||
local out = buffer.create(numPoints * stride)
|
||||
local map = a.map
|
||||
local n = a.numValues
|
||||
if a.raw then
|
||||
local raw = a.raw :: buffer
|
||||
for p = 0, numPoints - 1 do
|
||||
local e = if map then map[p + 1] else p
|
||||
if e >= n then
|
||||
return nil, "attribute value out of range"
|
||||
end
|
||||
buffer.copy(out, p * stride, raw, e * stride, stride)
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
local vals = a.values :: { number }
|
||||
local w = WRITE[a.dataType]
|
||||
if not w then
|
||||
return nil, "unsupported: data type " .. a.dataType
|
||||
end
|
||||
for p = 0, numPoints - 1 do
|
||||
local e = if map then map[p + 1] else p
|
||||
if e >= n then
|
||||
return nil, "attribute value out of range"
|
||||
end
|
||||
local o = p * stride
|
||||
local k = e * comps
|
||||
for c = 1, comps do
|
||||
w(out, o, vals[k + c])
|
||||
o += size
|
||||
end
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
local function decode(buf: buffer, o: number, l: number, opts: any): (Geometry?, string?, string?)
|
||||
local d = Reader.new(buf, o, o + l, 0)
|
||||
local h, herr = header(d)
|
||||
if not h then
|
||||
return nil, herr, nil
|
||||
end
|
||||
local ver = h.major * 256 + h.minor
|
||||
local maxVer = if h.kind == "points" then 0x0203 else 0x0202
|
||||
if h.major < 1 or ver > maxVer then
|
||||
return nil, string.format("unsupported: bitstream version %d.%d", h.major, h.minor), nil
|
||||
end
|
||||
d.ver = ver
|
||||
local maxPoints = (opts and opts.maxPoints) or 2 ^ 24
|
||||
local maxFaces = (opts and opts.maxFaces) or 2 ^ 24
|
||||
local meta: Metadata? = nil
|
||||
if ver >= 0x0103 and bit32.band(h.flags, 0x8000) ~= 0 then
|
||||
meta = metadata(d)
|
||||
if not meta then
|
||||
return nil, d.bad or "bad metadata", nil
|
||||
end
|
||||
end
|
||||
local mesh: Connectivity.Mesh? = nil
|
||||
local numPoints = 0
|
||||
local method
|
||||
if h.kind == "mesh" then
|
||||
if h.method == 0 then
|
||||
method = "sequential"
|
||||
local m, err = Connectivity.sequential(d)
|
||||
if not m then
|
||||
return nil, err, nil
|
||||
end
|
||||
mesh = m
|
||||
elseif h.method == 1 then
|
||||
method = "edgebreaker"
|
||||
local kind = Reader.u8(d)
|
||||
if d.bad then
|
||||
return nil, d.bad, nil
|
||||
end
|
||||
if kind > 2 then
|
||||
return nil, "unknown edgebreaker traversal " .. kind, nil
|
||||
end
|
||||
local m, err = Connectivity.edgebreaker(d, kind)
|
||||
if not m then
|
||||
return nil, err, nil
|
||||
end
|
||||
mesh = m
|
||||
else
|
||||
return nil, "unsupported: mesh encoding method " .. h.method, nil
|
||||
end
|
||||
local m = mesh :: Connectivity.Mesh
|
||||
if m.numFaces > maxFaces then
|
||||
return nil, "too many faces", "limit"
|
||||
end
|
||||
numPoints = m.numPoints
|
||||
else
|
||||
if h.method == 1 then
|
||||
return nil, "unsupported: kd-tree point clouds", nil
|
||||
elseif h.method ~= 0 then
|
||||
return nil, "unsupported: point cloud encoding method " .. h.method, nil
|
||||
end
|
||||
method = "sequential"
|
||||
numPoints = Reader.i32(d)
|
||||
if d.bad then
|
||||
return nil, d.bad, nil
|
||||
end
|
||||
if numPoints < 0 then
|
||||
return nil, "bad point count", nil
|
||||
end
|
||||
end
|
||||
if numPoints > maxPoints then
|
||||
return nil, "too many points", "limit"
|
||||
end
|
||||
local attrs, aerr = Attributes.decode(d, { numPoints = numPoints, mesh = mesh, edgebreaker = method == "edgebreaker", kdTree = false })
|
||||
if not attrs then
|
||||
return nil, aerr, nil
|
||||
end
|
||||
local g: Geometry = {
|
||||
kind = h.kind,
|
||||
version = h.major .. "." .. h.minor,
|
||||
method = method,
|
||||
numPoints = numPoints,
|
||||
numFaces = 0,
|
||||
indices = nil,
|
||||
attributes = {},
|
||||
metadata = meta,
|
||||
}
|
||||
if mesh then
|
||||
local nf = mesh.numFaces
|
||||
local idx = buffer.create(nf * 12)
|
||||
local faces = mesh.faces
|
||||
for i = 1, nf * 3 do
|
||||
local v = faces[i]
|
||||
if v < 0 or v >= numPoints then
|
||||
return nil, "face index out of range", nil
|
||||
end
|
||||
buffer.writeu32(idx, (i - 1) * 4, v)
|
||||
end
|
||||
g.numFaces = nf
|
||||
g.indices = idx
|
||||
end
|
||||
for _, a in attrs do
|
||||
local data, err = expand(a, numPoints)
|
||||
if not data then
|
||||
return nil, err, nil
|
||||
end
|
||||
table.insert(g.attributes, {
|
||||
name = NAMES[a.type] or "GENERIC",
|
||||
typeId = a.type,
|
||||
uniqueId = a.uniqueId,
|
||||
components = a.comps,
|
||||
type = TYPES[a.dataType],
|
||||
normalized = a.normalized,
|
||||
data = data,
|
||||
})
|
||||
end
|
||||
return g, nil, nil
|
||||
end
|
||||
|
||||
-- decode(src, off?, len?, opts?) -> Geometry | nil, Err
|
||||
function Draco.decode(src: buffer | string, off: number?, len: number?, opts: any?): (Geometry?, Err.Err?)
|
||||
local buf, o, l, aerr = Bytes.span("draco", src, off, len)
|
||||
if not buf then
|
||||
return nil, aerr
|
||||
end
|
||||
local ok, g, msg, kind = pcall(decode, buf, o, l, opts)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, "draco: internal error: " .. tostring(g))
|
||||
end
|
||||
if not g then
|
||||
return nil, Err.from("draco: " .. tostring(msg), nil, kind or (if string.find(tostring(msg), "^unsupported") then "unsupported" elseif string.find(tostring(msg), "truncated") then "truncated" else nil))
|
||||
end
|
||||
return g, nil
|
||||
end
|
||||
|
||||
-- attribute(g, uniqueId) -> the attribute with that unique id
|
||||
function Draco.attribute(g: Geometry, uniqueId: number): Attribute?
|
||||
for _, a in g.attributes do
|
||||
if a.uniqueId == uniqueId then
|
||||
return a
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
return Draco
|
||||
@@ -0,0 +1,80 @@
|
||||
-- codecs/model/Draco tests: Google's Draco test data (bitstreams 0.9 - 2.2) and files encoded by draco_encoder 1.5.7
|
||||
-- at every compression level, quantization and as point clouds, decoded and compared byte for byte (points, faces,
|
||||
-- every attribute's values per point, as CRCs) with libdraco's own decoder (tools/fixtures/_draco_dump.cc); kd-tree
|
||||
-- point clouds report UNSUPPORTED; argument errors; the fuzz no-throw pass (which also fails on any internal error the
|
||||
-- decoder's safety net caught). Fixtures: tools/fixtures/draco.py.
|
||||
local T = require("@tests/T")
|
||||
local Draco = require("@formats/codecs/model/Draco")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local Cases = require("@tests/gen/draco_cases")
|
||||
|
||||
local t = T.suite("draco")
|
||||
|
||||
local counts = { exact = 0, unsupported = 0, rejected = 0 }
|
||||
local samples = {}
|
||||
for _, c in Cases do
|
||||
local g, err = Draco.decode(c.data)
|
||||
if c.error then
|
||||
t:check(g == nil and err ~= nil, c.name .. ": libdraco rejects it, so do we")
|
||||
counts.rejected += 1
|
||||
elseif not g and err and err.code == Err.UNSUPPORTED and string.find(err.message, "kd-tree", 1, true) then
|
||||
counts.unsupported += 1
|
||||
else
|
||||
t:check(g, c.name .. ": decode: " .. tostring(err))
|
||||
if g then
|
||||
t:eq(g.numPoints, c.points, c.name .. ": points")
|
||||
if c.faces then
|
||||
t:eq(g.numFaces, c.faces, c.name .. ": faces")
|
||||
t:eq(Crc32.of(g.indices :: buffer), c.indices, c.name .. ": indices")
|
||||
end
|
||||
t:eq(#g.attributes, #c.attrs, c.name .. ": attribute count")
|
||||
for i, want in c.attrs do
|
||||
local a = g.attributes[i]
|
||||
if a then
|
||||
t:eq(a.typeId, want.type, c.name .. ": attribute " .. i .. " type")
|
||||
t:eq(a.type, Draco.DATA_TYPES[want.dataType], c.name .. ": attribute " .. i .. " data type")
|
||||
t:eq(a.components, want.components, c.name .. ": attribute " .. i .. " components")
|
||||
t:eq(a.normalized, want.normalized, c.name .. ": attribute " .. i .. " normalized")
|
||||
t:eq(a.uniqueId, want.uniqueId, c.name .. ": attribute " .. i .. " unique id")
|
||||
t:eq(Crc32.of(a.data), want.crc, c.name .. ": attribute " .. i .. " (" .. a.name .. ") values")
|
||||
end
|
||||
end
|
||||
counts.exact += 1
|
||||
if #c.data < 4000 then
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
t:note("%d files decoded exactly like libdraco, %d kd-tree point clouds unsupported, %d rejected by both", counts.exact, counts.unsupported, counts.rejected)
|
||||
|
||||
-- the attribute lookup and the header
|
||||
local first = Cases[1]
|
||||
local info = Draco.info(first.data)
|
||||
t:check(info and (info.kind == "mesh" or info.kind == "points"), "info")
|
||||
t:check(Draco.sniff(buffer.fromstring(first.data)), "sniff")
|
||||
t:check(not Draco.sniff(buffer.fromstring("DRAC")), "sniff short")
|
||||
|
||||
-- errors
|
||||
local _, e1 = Draco.decode(buffer.fromstring("NOTDRACO......"))
|
||||
t:check(e1 and e1.code == Err.CORRUPT, "not Draco data: " .. tostring(e1))
|
||||
local _, e2 = Draco.decode(buffer.fromstring("DRACO\9\0\1\1\0\0"))
|
||||
t:check(e2 and e2.code == Err.UNSUPPORTED, "future version: " .. tostring(e2))
|
||||
local _, e3 = Draco.decode(42 :: any)
|
||||
t:check(e3 and e3.code == Err.ARG, "bad argument")
|
||||
|
||||
-- fuzz: never throws, and the internal safety net never fires
|
||||
local internal = 0
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
local g, err = Draco.decode(b)
|
||||
if not g and err and string.find(err.message, "internal error", 1, true) then
|
||||
internal += 1
|
||||
if internal <= 5 then
|
||||
print(" internal error: " .. err.message)
|
||||
end
|
||||
end
|
||||
return g
|
||||
end, samples, { mutations = 12, keepHeader = 11 })
|
||||
t:eq(internal, 0, "fuzz: internal errors")
|
||||
t:done()
|
||||
@@ -0,0 +1,44 @@
|
||||
// Dumps a decoded Draco file: points, faces and every attribute's per-point bytes (hex), for the fixture generator.
|
||||
#include "draco/compression/decode.h"
|
||||
#include <cstdio>
|
||||
#include <fstream>
|
||||
#include <iterator>
|
||||
#include <vector>
|
||||
static void hex(const uint8_t* p, size_t n) { for (size_t i = 0; i < n; ++i) printf("%02x", p[i]); }
|
||||
int main(int argc, char** argv) {
|
||||
std::ifstream f(argv[1], std::ios::binary);
|
||||
std::vector<char> data((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
|
||||
draco::DecoderBuffer buf;
|
||||
buf.Init(data.data(), data.size());
|
||||
auto type = draco::Decoder::GetEncodedGeometryType(&buf);
|
||||
if (!type.ok()) { printf("ERROR %s\n", type.status().error_msg()); return 0; }
|
||||
draco::Decoder dec;
|
||||
std::unique_ptr<draco::PointCloud> pc;
|
||||
std::unique_ptr<draco::Mesh> mesh;
|
||||
if (type.value() == draco::TRIANGULAR_MESH) {
|
||||
auto r = dec.DecodeMeshFromBuffer(&buf);
|
||||
if (!r.ok()) { printf("ERROR %s\n", r.status().error_msg()); return 0; }
|
||||
mesh = std::move(r).value();
|
||||
} else {
|
||||
auto r = dec.DecodePointCloudFromBuffer(&buf);
|
||||
if (!r.ok()) { printf("ERROR %s\n", r.status().error_msg()); return 0; }
|
||||
pc = std::move(r).value();
|
||||
}
|
||||
const draco::PointCloud* g = mesh ? mesh.get() : pc.get();
|
||||
printf("POINTS %u\n", g->num_points());
|
||||
if (mesh) {
|
||||
printf("FACES %u ", mesh->num_faces());
|
||||
for (draco::FaceIndex fi(0); fi < mesh->num_faces(); ++fi) {
|
||||
const auto& face = mesh->face(fi);
|
||||
for (int c = 0; c < 3; ++c) { uint32_t v = face[c].value(); hex((const uint8_t*)&v, 4); }
|
||||
}
|
||||
printf("\n");
|
||||
}
|
||||
for (int i = 0; i < g->num_attributes(); ++i) {
|
||||
const draco::PointAttribute* a = g->attribute(i);
|
||||
printf("ATTR %d %d %d %d %u ", (int)a->attribute_type(), (int)a->data_type(), (int)a->num_components(), a->normalized() ? 1 : 0, a->unique_id());
|
||||
for (draco::PointIndex p(0); p < g->num_points(); ++p) hex(a->GetAddress(a->mapped_index(p)), a->byte_stride());
|
||||
printf("\n");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
# Draco fixtures (tools/fixtures.py): every .drc file of Google's Draco test data (bitstreams 0.9 - 2.2, read from the
|
||||
# nixpkgs draco source, never committed) and files made here by draco_encoder 1.5.7 (nix) from the test data meshes
|
||||
# and generated ones (a UV sphere with seams, a noisy grid, a coloured PLY), at every compression level (sequential,
|
||||
# Edgebreaker standard / valence; difference, parallelogram, constrained multi-parallelogram, portable tex coords and
|
||||
# geometric normal predictions), several quantizations (up to 30 bits) and as point clouds. The reference values come
|
||||
# from libdraco itself: tools/fixtures/_draco_dump.cc, compiled here against nixpkgs#draco, prints the decoded points,
|
||||
# faces and each attribute's bytes per point.
|
||||
# tests/gen/draco_cases.luau { { name, data, error? = true, points, faces, indices = crc, attrs = { { type, dataType,
|
||||
# components, normalized, uniqueId, crc } } } }
|
||||
import math, os, subprocess, tempfile, zlib
|
||||
|
||||
INPUTS = ["tools/fixtures/_draco_dump.cc"]
|
||||
|
||||
|
||||
def store_path(attr):
|
||||
out = subprocess.run(["nix", "build", "nixpkgs#" + attr, "--no-link", "--print-out-paths"], capture_output=True, check=True)
|
||||
return out.stdout.decode().strip().split("\n")[-1]
|
||||
|
||||
|
||||
def uv_sphere(rings=12, segs=20):
|
||||
# an OBJ sphere with a UV seam and poles: vertices shared by position, split by UV
|
||||
v, vt, vn, f = [], [], [], []
|
||||
for r in range(rings + 1):
|
||||
th = math.pi * r / rings
|
||||
for s in range(segs + 1):
|
||||
ph = 2 * math.pi * s / segs
|
||||
x, y, z = math.sin(th) * math.cos(ph), math.cos(th), math.sin(th) * math.sin(ph)
|
||||
v.append((x, y, z))
|
||||
vn.append((x, y, z))
|
||||
vt.append((s / segs, r / rings))
|
||||
w = segs + 1
|
||||
for r in range(rings):
|
||||
for s in range(segs):
|
||||
a, b, c, d = r * w + s + 1, r * w + s + 2, (r + 1) * w + s + 2, (r + 1) * w + s + 1
|
||||
if r > 0:
|
||||
f.append((a, b, c))
|
||||
if r < rings - 1:
|
||||
f.append((a, c, d))
|
||||
out = ["v %.6f %.6f %.6f" % p for p in v] + ["vt %.6f %.6f" % p for p in vt] + ["vn %.6f %.6f %.6f" % p for p in vn]
|
||||
out += ["f %d/%d/%d %d/%d/%d %d/%d/%d" % (a, a, a, b, b, b, c, c, c) for a, b, c in f]
|
||||
return "\n".join(out) + "\n"
|
||||
|
||||
|
||||
def noisy_grid(rng, n=24):
|
||||
# a height field with a hole and per-vertex UVs: boundaries, holes and parallelogram predictions
|
||||
v, vt, f = [], [], []
|
||||
for j in range(n):
|
||||
for i in range(n):
|
||||
v.append((i * 0.1, rng.uniform(-0.05, 0.05), j * 0.1))
|
||||
vt.append((i / (n - 1), j / (n - 1)))
|
||||
for j in range(n - 1):
|
||||
for i in range(n - 1):
|
||||
if 8 <= i < 12 and 8 <= j < 12:
|
||||
continue
|
||||
a, b, c, d = j * n + i + 1, j * n + i + 2, (j + 1) * n + i + 2, (j + 1) * n + i + 1
|
||||
f.append((a, b, c))
|
||||
f.append((a, c, d))
|
||||
out = ["v %.6f %.6f %.6f" % p for p in v] + ["vt %.6f %.6f" % p for p in vt]
|
||||
out += ["f %d/%d %d/%d %d/%d" % (a, a, b, b, c, c) for a, b, c in f]
|
||||
return "\n".join(out) + "\n"
|
||||
|
||||
|
||||
def colored_ply(rng, n=200):
|
||||
# an ASCII point set / mesh with colours (u8) and a generic float property
|
||||
pts = [(rng.uniform(-1, 1), rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(n)]
|
||||
faces = [(i, i + 1, i + 2) for i in range(0, n - 2, 3)]
|
||||
head = ["ply", "format ascii 1.0", "element vertex %d" % n, "property float x", "property float y", "property float z",
|
||||
"property uchar red", "property uchar green", "property uchar blue", "property uchar alpha",
|
||||
"element face %d" % len(faces), "property list uchar int vertex_indices", "end_header"]
|
||||
body = ["%.5f %.5f %.5f %d %d %d %d" % (p[0], p[1], p[2], rng.randrange(256), rng.randrange(256), rng.randrange(256), 255) for p in pts]
|
||||
body += ["3 %d %d %d" % t for t in faces]
|
||||
return "\n".join(head + body) + "\n"
|
||||
|
||||
|
||||
def parse_dump(txt):
|
||||
out = {"attrs": []}
|
||||
for line in txt.split("\n"):
|
||||
parts = line.split(" ")
|
||||
if parts[0] == "ERROR":
|
||||
return {"error": True}
|
||||
if parts[0] == "POINTS":
|
||||
out["points"] = int(parts[1])
|
||||
elif parts[0] == "FACES":
|
||||
out["faces"] = int(parts[1])
|
||||
out["indices"] = zlib.crc32(bytes.fromhex(parts[2] if len(parts) > 2 else ""))
|
||||
elif parts[0] == "ATTR":
|
||||
out["attrs"].append({"type": int(parts[1]), "dataType": int(parts[2]), "components": int(parts[3]),
|
||||
"normalized": parts[4] == "1", "uniqueId": int(parts[5]),
|
||||
"crc": zlib.crc32(bytes.fromhex(parts[6] if len(parts) > 6 else ""))})
|
||||
return out
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
draco = store_path("draco")
|
||||
src = store_path("draco.src")
|
||||
testdata = os.path.join(src, "testdata")
|
||||
tmp = tempfile.mkdtemp(prefix="formats-draco-")
|
||||
dump = os.path.join(tmp, "dump")
|
||||
ctx.nix("gcc", ["g++", "-O1", "-std=c++17", "-I" + os.path.join(draco, "include"), os.path.join(ctx.root, "tools", "fixtures", "_draco_dump.cc"),
|
||||
"-L" + os.path.join(draco, "lib"), "-l:libdraco.a", "-o", dump])
|
||||
encoder = os.path.join(draco, "bin", "draco_encoder")
|
||||
|
||||
files = [] # (name, path)
|
||||
for f in sorted(os.listdir(testdata)):
|
||||
if f.endswith(".drc"):
|
||||
files.append(("testdata/" + f, os.path.join(testdata, f)))
|
||||
|
||||
rng = ctx.rng(31)
|
||||
gen_inputs = {"uvsphere.obj": uv_sphere(), "grid.obj": noisy_grid(rng), "colored.ply": colored_ply(rng)}
|
||||
for name, text in gen_inputs.items():
|
||||
with open(os.path.join(tmp, name), "w") as fh:
|
||||
fh.write(text)
|
||||
inputs = [(n, os.path.join(tmp, n)) for n in gen_inputs] + [(n, os.path.join(testdata, n)) for n in
|
||||
("cube_att.obj", "test_nm.obj", "sphere.obj", "cube_quads.obj", "test_generic.ply", "Box.ply")]
|
||||
variants = [("cl%d" % cl, ["-cl", str(cl)]) for cl in range(11)]
|
||||
variants += [("q14", ["-qp", "14", "-qt", "12", "-qn", "10"]), ("q20", ["-qp", "20", "-qt", "16", "-qn", "14", "-qg", "12"]),
|
||||
("q30", ["-qp", "30", "-qt", "30", "-qn", "30", "-qg", "30"]), ("q30cl10", ["-cl", "10", "-qp", "24", "-qt", "24", "-qn", "24"]),
|
||||
("raw", ["-qp", "0", "-qt", "0", "-qn", "0", "-qg", "0"]), ("meta", ["--metadata"]), ("poly", ["-preserve_polygons"]),
|
||||
("pc", ["-point_cloud", "-cl", "0"]), ("pckd", ["-point_cloud"])]
|
||||
for iname, ipath in inputs:
|
||||
for vname, args in variants:
|
||||
out = os.path.join(tmp, "%s.%s.drc" % (iname, vname))
|
||||
r = subprocess.run([encoder, "-i", ipath, "-o", out] + args, capture_output=True)
|
||||
if r.returncode == 0 and os.path.exists(out):
|
||||
files.append(("enc/%s.%s" % (iname, vname), out))
|
||||
# the large bunny once (Edgebreaker valence + normals)
|
||||
out = os.path.join(tmp, "bunny.drc")
|
||||
if subprocess.run([encoder, "-i", os.path.join(testdata, "bunny_norm.obj"), "-o", out, "-cl", "7"], capture_output=True).returncode == 0:
|
||||
files.append(("enc/bunny_norm.obj.cl7", out))
|
||||
|
||||
cases = []
|
||||
for name, path in files:
|
||||
ref = parse_dump(subprocess.run([dump, path], capture_output=True).stdout.decode())
|
||||
case = {"name": name, "data": open(path, "rb").read()}
|
||||
case.update(ref)
|
||||
cases.append(case)
|
||||
ctx.emit("draco_cases", cases)
|
||||
Reference in new issue
Block a user