feat: Spektrafilm optical simulation and emulsion tuning controls
This commit is contained in:
1 parent
e21fb691e0
commit
ba936e1214
87 files changed
+5861
-750
No files matched your search
@@ -24,9 +24,9 @@
|
||||
"viewingIlluminant": "D50",
|
||||
"model": {
|
||||
"path": "model/fujifilm_c200.spkm",
|
||||
"sha256": "d4e7ef7d0af7754ee77221e3a6eff674e9823bb05e0c2080c667204583846c77",
|
||||
"bytes": 13702,
|
||||
"uncompressedBytes": 16556
|
||||
"sha256": "f495e79f1c0451174de728980ccdf3f7ed023bfd23008b196799e75e057b9b6f",
|
||||
"bytes": 30478,
|
||||
"uncompressedBytes": 35020
|
||||
}
|
||||
},
|
||||
"fujifilm_pro_400h": {
|
||||
@@ -35,9 +35,9 @@
|
||||
"viewingIlluminant": "D50",
|
||||
"model": {
|
||||
"path": "model/fujifilm_pro_400h.spkm",
|
||||
"sha256": "4834bdf00008e584f3a2e267a3dc40a731f5daf39afecab91b37d21679c9f7db",
|
||||
"bytes": 13664,
|
||||
"uncompressedBytes": 16556
|
||||
"sha256": "2926e8309a347936905ad7f27122658e88cf4dfba092400b301e66fc5d0ef5d8",
|
||||
"bytes": 29595,
|
||||
"uncompressedBytes": 35020
|
||||
}
|
||||
},
|
||||
"fujifilm_provia_100f": {
|
||||
@@ -46,9 +46,9 @@
|
||||
"viewingIlluminant": "D50",
|
||||
"model": {
|
||||
"path": "model/fujifilm_provia_100f.spkm",
|
||||
"sha256": "38d4058e4eed31d03ab72df3e8b2412b936b7db4b182454a810d0a19aba47fd8",
|
||||
"bytes": 13092,
|
||||
"uncompressedBytes": 16010
|
||||
"sha256": "b83efc6ad79a28db3e0f0279aa6583e288cdfc8abb99eb6042cc57791ad27195",
|
||||
"bytes": 30382,
|
||||
"uncompressedBytes": 34474
|
||||
}
|
||||
},
|
||||
"fujifilm_velvia_100": {
|
||||
@@ -57,9 +57,9 @@
|
||||
"viewingIlluminant": "D50",
|
||||
"model": {
|
||||
"path": "model/fujifilm_velvia_100.spkm",
|
||||
"sha256": "b8e5060532944c377cd638fdf2ca9dbb03119cdd2410a78621d0719f15dd8047",
|
||||
"bytes": 12973,
|
||||
"uncompressedBytes": 16010
|
||||
"sha256": "c586cdf53accefae52c78f778b6ff0e6b6b79af0b6942236a751f67fa8bfe78f",
|
||||
"bytes": 29984,
|
||||
"uncompressedBytes": 34474
|
||||
}
|
||||
},
|
||||
"fujifilm_xtra_400": {
|
||||
@@ -68,9 +68,9 @@
|
||||
"viewingIlluminant": "D50",
|
||||
"model": {
|
||||
"path": "model/fujifilm_xtra_400.spkm",
|
||||
"sha256": "341d8e6d76a33f2a26b43771f4080320f3c739e86da3328c3ada56dc9024cfad",
|
||||
"bytes": 13741,
|
||||
"uncompressedBytes": 16556
|
||||
"sha256": "b141ef97ca5861fd2d0601be6e3c246db21a28806f47294939b464aeebaa63aa",
|
||||
"bytes": 30737,
|
||||
"uncompressedBytes": 35020
|
||||
}
|
||||
},
|
||||
"kodak_ektachrome_100": {
|
||||
@@ -79,9 +79,9 @@
|
||||
"viewingIlluminant": "D50",
|
||||
"model": {
|
||||
"path": "model/kodak_ektachrome_100.spkm",
|
||||
"sha256": "00adceae8a1b205f134e13d358fe1ad28349bcaa7fb6e36b6c4c06899083fb6d",
|
||||
"bytes": 13015,
|
||||
"uncompressedBytes": 16010
|
||||
"sha256": "4f493856ddf167c8158801810cdde888795adff6a3d63a51625172fd0263734d",
|
||||
"bytes": 30245,
|
||||
"uncompressedBytes": 34474
|
||||
}
|
||||
},
|
||||
"kodak_ektar_100": {
|
||||
@@ -90,9 +90,9 @@
|
||||
"viewingIlluminant": "D50",
|
||||
"model": {
|
||||
"path": "model/kodak_ektar_100.spkm",
|
||||
"sha256": "245946ae79ffab00ed60edf5cbd466c765050fcffb3f7838f0c1f5770b48ca9f",
|
||||
"bytes": 13638,
|
||||
"uncompressedBytes": 16556
|
||||
"sha256": "d334498b689ded30f67dd89f3f6efbb7c779aa3faab8fb2beb8ddf485d7e53fb",
|
||||
"bytes": 29482,
|
||||
"uncompressedBytes": 35020
|
||||
}
|
||||
},
|
||||
"kodak_gold_200": {
|
||||
@@ -101,9 +101,9 @@
|
||||
"viewingIlluminant": "D50",
|
||||
"model": {
|
||||
"path": "model/kodak_gold_200.spkm",
|
||||
"sha256": "3c546d8dfd05a94b0799b8f98d30a744d4fb2279b595ed3695248942a15a4492",
|
||||
"bytes": 13620,
|
||||
"uncompressedBytes": 16556
|
||||
"sha256": "472cf6a621b7a666b90310ccbaca804b3dba6568a3396133731a7c44a93987c2",
|
||||
"bytes": 29512,
|
||||
"uncompressedBytes": 35020
|
||||
}
|
||||
},
|
||||
"kodak_kodachrome_64": {
|
||||
@@ -112,9 +112,9 @@
|
||||
"viewingIlluminant": "D50",
|
||||
"model": {
|
||||
"path": "model/kodak_kodachrome_64.spkm",
|
||||
"sha256": "44df3fa97480e9a9cb07b03b8001eb56720a1c516f034a11b15aeebb7d359a99",
|
||||
"bytes": 12818,
|
||||
"uncompressedBytes": 16010
|
||||
"sha256": "ff0ca03cd90000f39ce9060ded04bfc45d83c736a5bacc24c84f95d79a9a6813",
|
||||
"bytes": 30281,
|
||||
"uncompressedBytes": 34474
|
||||
}
|
||||
},
|
||||
"kodak_portra_160": {
|
||||
@@ -123,9 +123,9 @@
|
||||
"viewingIlluminant": "D50",
|
||||
"model": {
|
||||
"path": "model/kodak_portra_160.spkm",
|
||||
"sha256": "9d7669fd3991d6afc4142ea450ccff6b3a8234a3829451a7f897ffa03bd0bf2e",
|
||||
"bytes": 13611,
|
||||
"uncompressedBytes": 16556
|
||||
"sha256": "fdc3d01fe0a15e7460d8676d15595788836c3de40494651245e54d4f5c91e422",
|
||||
"bytes": 29033,
|
||||
"uncompressedBytes": 35020
|
||||
}
|
||||
},
|
||||
"kodak_portra_400": {
|
||||
@@ -134,9 +134,9 @@
|
||||
"viewingIlluminant": "D50",
|
||||
"model": {
|
||||
"path": "model/kodak_portra_400.spkm",
|
||||
"sha256": "0e647e105a7c81e05dfe558e2892b9c76d8dce5621cb4c898c44ddab7559e601",
|
||||
"bytes": 13655,
|
||||
"uncompressedBytes": 16556
|
||||
"sha256": "72657bbde5f21b3820de9bd3b7e8f6010bc6ffad9d64c53deca6ba58edcc6505",
|
||||
"bytes": 29409,
|
||||
"uncompressedBytes": 35020
|
||||
}
|
||||
},
|
||||
"kodak_portra_800": {
|
||||
@@ -145,9 +145,9 @@
|
||||
"viewingIlluminant": "D50",
|
||||
"model": {
|
||||
"path": "model/kodak_portra_800.spkm",
|
||||
"sha256": "f3542ea69dc4a61618aa20276c67093e38794b2a2f1222b82a10a0c9382fe2c4",
|
||||
"bytes": 13655,
|
||||
"uncompressedBytes": 16556
|
||||
"sha256": "e81edaf1b753c24b781f0422bb0a672ce9e7d1d7eed8bccc965c6fafd5dfa7c6",
|
||||
"bytes": 29742,
|
||||
"uncompressedBytes": 35020
|
||||
}
|
||||
},
|
||||
"kodak_portra_800_push1": {
|
||||
@@ -156,9 +156,9 @@
|
||||
"viewingIlluminant": "D50",
|
||||
"model": {
|
||||
"path": "model/kodak_portra_800_push1.spkm",
|
||||
"sha256": "661a278825375a93b6194bf81484b7e675c57f834274eb098fc6cd582f9321d2",
|
||||
"bytes": 13684,
|
||||
"uncompressedBytes": 16556
|
||||
"sha256": "ae1e8904a7901a52007499eb6c51fbe81c0b79f4dd702a1b208e87d19b7ddfb4",
|
||||
"bytes": 30017,
|
||||
"uncompressedBytes": 35020
|
||||
}
|
||||
},
|
||||
"kodak_portra_800_push2": {
|
||||
@@ -167,9 +167,9 @@
|
||||
"viewingIlluminant": "D50",
|
||||
"model": {
|
||||
"path": "model/kodak_portra_800_push2.spkm",
|
||||
"sha256": "0c3ab6f729bc2f6697902e10f7ad14c97a225d3c01c421debf938239d81d8354",
|
||||
"bytes": 13694,
|
||||
"uncompressedBytes": 16556
|
||||
"sha256": "d6021fb19b45b8c165a7f0365c16495bb89d5058a0978f769c27ca79bc0b4929",
|
||||
"bytes": 30372,
|
||||
"uncompressedBytes": 35020
|
||||
}
|
||||
},
|
||||
"kodak_ultramax_400": {
|
||||
@@ -178,9 +178,9 @@
|
||||
"viewingIlluminant": "D50",
|
||||
"model": {
|
||||
"path": "model/kodak_ultramax_400.spkm",
|
||||
"sha256": "eeb9651c1e87bb93b9d3cfbc7f3cbb78cba2c110787f69727d51712bc6b1a74a",
|
||||
"bytes": 13648,
|
||||
"uncompressedBytes": 16556
|
||||
"sha256": "5f00047bfd7cdf3227bb0a193001903a1c57fbc8eb7180d56c20f7687ef793e6",
|
||||
"bytes": 29645,
|
||||
"uncompressedBytes": 35020
|
||||
}
|
||||
},
|
||||
"kodak_verita_200d": {
|
||||
@@ -189,9 +189,9 @@
|
||||
"viewingIlluminant": "D50",
|
||||
"model": {
|
||||
"path": "model/kodak_verita_200d.spkm",
|
||||
"sha256": "e9e5af0b493452895913ef894b355ffc85f52016b431924175c9fa7dbd61789a",
|
||||
"bytes": 13651,
|
||||
"uncompressedBytes": 16556
|
||||
"sha256": "5adc339869058b5828d1b36ef0ce4f7414d4aae9fdfa08256dfee816c9bd8c8a",
|
||||
"bytes": 29560,
|
||||
"uncompressedBytes": 35020
|
||||
}
|
||||
},
|
||||
"kodak_vision3_200t": {
|
||||
@@ -200,9 +200,9 @@
|
||||
"viewingIlluminant": "D50",
|
||||
"model": {
|
||||
"path": "model/kodak_vision3_200t.spkm",
|
||||
"sha256": "04c0920e64577173d07f19ddcd654803bbacd886718ddae5b43c8f71aa56295a",
|
||||
"bytes": 13782,
|
||||
"uncompressedBytes": 16556
|
||||
"sha256": "a59caa68219007df034daefd9c3e559dd5e357966c07831e4af94a84f8fda4e6",
|
||||
"bytes": 29957,
|
||||
"uncompressedBytes": 35020
|
||||
}
|
||||
},
|
||||
"kodak_vision3_250d": {
|
||||
@@ -211,9 +211,9 @@
|
||||
"viewingIlluminant": "D50",
|
||||
"model": {
|
||||
"path": "model/kodak_vision3_250d.spkm",
|
||||
"sha256": "32b7abf94b009c6a5b23b5c3e3f8ec8ad877683c4fdba845e8e7b117a9624d5a",
|
||||
"bytes": 13829,
|
||||
"uncompressedBytes": 16556
|
||||
"sha256": "f0924ad3c5776839cba64923e020939cb991f9561fc8ef4c11ceebcad13ebd4e",
|
||||
"bytes": 30629,
|
||||
"uncompressedBytes": 35020
|
||||
}
|
||||
},
|
||||
"kodak_vision3_500t": {
|
||||
@@ -222,9 +222,9 @@
|
||||
"viewingIlluminant": "D50",
|
||||
"model": {
|
||||
"path": "model/kodak_vision3_500t.spkm",
|
||||
"sha256": "0cec945418953e9e312a613c6f55a6cf8bdba0f756b5b418ab893dc5bc400e22",
|
||||
"bytes": 13802,
|
||||
"uncompressedBytes": 16556
|
||||
"sha256": "aaf8bfe0b33b5799e478260454dd103fa79f4649ba3403acbd5b299452f71174",
|
||||
"bytes": 30596,
|
||||
"uncompressedBytes": 35020
|
||||
}
|
||||
},
|
||||
"kodak_vision3_50d": {
|
||||
@@ -233,9 +233,9 @@
|
||||
"viewingIlluminant": "D50",
|
||||
"model": {
|
||||
"path": "model/kodak_vision3_50d.spkm",
|
||||
"sha256": "a0273756d668a64481fd20fb40e616a3b3044ed78e3b3d17012c5bc92def8f71",
|
||||
"bytes": 13723,
|
||||
"uncompressedBytes": 16556
|
||||
"sha256": "09c7bd2440d842682592d2a1ba90e433cea6b1a66bd1594dca69f97e8fb28d34",
|
||||
"bytes": 29485,
|
||||
"uncompressedBytes": 35020
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -244,72 +244,72 @@
|
||||
"viewingIlluminant": "D50",
|
||||
"model": {
|
||||
"path": "model/fujifilm_crystal_archive_typeii.spkm",
|
||||
"sha256": "372b253d1f6e7109808da0bdae920a2462dd0ca5e34a644f2d82661b24a3f9c9",
|
||||
"bytes": 6188,
|
||||
"uncompressedBytes": 8542
|
||||
"sha256": "eed5034f33cfc331f8061056f0833a37fc6ac5e59fd95d647151a1663cc99ebc",
|
||||
"bytes": 11900,
|
||||
"uncompressedBytes": 14715
|
||||
}
|
||||
},
|
||||
"kodak_2383": {
|
||||
"viewingIlluminant": "K75P",
|
||||
"model": {
|
||||
"path": "model/kodak_2383.spkm",
|
||||
"sha256": "c8c39fcba1e592b11b240e94e145067a801c0a38dbc798c91d92253b354b9407",
|
||||
"bytes": 6426,
|
||||
"uncompressedBytes": 8542
|
||||
"sha256": "0ac269230956ee9334ef91fc136e45d069c9d2d30a6a5b32ede43860bfabdee3",
|
||||
"bytes": 12205,
|
||||
"uncompressedBytes": 14715
|
||||
}
|
||||
},
|
||||
"kodak_2393": {
|
||||
"viewingIlluminant": "K75P",
|
||||
"model": {
|
||||
"path": "model/kodak_2393.spkm",
|
||||
"sha256": "332d778373f08d4a11e43e7a89be77542e93c25fe4c6f6ded09fc482eecace07",
|
||||
"bytes": 6271,
|
||||
"uncompressedBytes": 8542
|
||||
"sha256": "d24a59a403fe6e266a01961a0aaa8e1595d4f222b2b807a80471e8d6a8a7b650",
|
||||
"bytes": 12014,
|
||||
"uncompressedBytes": 14715
|
||||
}
|
||||
},
|
||||
"kodak_ektacolor_edge": {
|
||||
"viewingIlluminant": "D50",
|
||||
"model": {
|
||||
"path": "model/kodak_ektacolor_edge.spkm",
|
||||
"sha256": "f33d568b6e9cac7c8c7ca0e69187b61c882448f6af0fdb71d486805039ab4858",
|
||||
"bytes": 6044,
|
||||
"uncompressedBytes": 8542
|
||||
"sha256": "b7fe77e50748502a02fc74fce68945dc57a3a8081f437a3c6b7d4791dd486466",
|
||||
"bytes": 11776,
|
||||
"uncompressedBytes": 14715
|
||||
}
|
||||
},
|
||||
"kodak_endura_premier": {
|
||||
"viewingIlluminant": "D50",
|
||||
"model": {
|
||||
"path": "model/kodak_endura_premier.spkm",
|
||||
"sha256": "aec10298877b80248e1e1686398c06963bcc63518603a17b3107fd1e5ab51506",
|
||||
"bytes": 5989,
|
||||
"uncompressedBytes": 8542
|
||||
"sha256": "3cd476766480dd827001a5f464de75c3b7ec3001424d2c504af5d0aa5329edd4",
|
||||
"bytes": 11703,
|
||||
"uncompressedBytes": 14715
|
||||
}
|
||||
},
|
||||
"kodak_portra_endura": {
|
||||
"viewingIlluminant": "D50",
|
||||
"model": {
|
||||
"path": "model/kodak_portra_endura.spkm",
|
||||
"sha256": "019c38eaa13b37f351923b802be5fc8ea9ca392eeea3a0440cbffe70f12306c8",
|
||||
"bytes": 6085,
|
||||
"uncompressedBytes": 8542
|
||||
"sha256": "59f31c757a1334c271fc7fd4ecfa9e5d53f0a4536922573fc48b797b2de74aa5",
|
||||
"bytes": 11831,
|
||||
"uncompressedBytes": 14715
|
||||
}
|
||||
},
|
||||
"kodak_supra_endura": {
|
||||
"viewingIlluminant": "D50",
|
||||
"model": {
|
||||
"path": "model/kodak_supra_endura.spkm",
|
||||
"sha256": "e894d2ddc1cf37e33090eb08446e935f469bc50b3ad91d1d1cfac7e5901c5d39",
|
||||
"bytes": 6080,
|
||||
"uncompressedBytes": 8542
|
||||
"sha256": "8d278445277ccb208f93f0ea0479599b26872a3458d98e17bfe460891427e184",
|
||||
"bytes": 11792,
|
||||
"uncompressedBytes": 14715
|
||||
}
|
||||
},
|
||||
"kodak_ultra_endura": {
|
||||
"viewingIlluminant": "D50",
|
||||
"model": {
|
||||
"path": "model/kodak_ultra_endura.spkm",
|
||||
"sha256": "fb0cb92259aae2552fc1a1f570a9d555ce8afe1601877fc5b163b8da4df7342b",
|
||||
"bytes": 6050,
|
||||
"uncompressedBytes": 8542
|
||||
"sha256": "33a2b7eaf5d4186168e85914e99c2cbd6fe9b7dfc13723efdb2adb1f2242ec0f",
|
||||
"bytes": 11761,
|
||||
"uncompressedBytes": 14715
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -338,6 +338,7 @@ add_library(my-native-lib SHARED
|
||||
spektrafilm/spectral_gamut.cpp
|
||||
spektrafilm/spectral_printing.cpp
|
||||
spektrafilm/spectral_generator.cpp
|
||||
spektrafilm/spectral_graph.cpp
|
||||
spektrafilm/spectral_jni.cpp
|
||||
gles_gpu_timer_query_jni.cpp
|
||||
gles_hardware_buffer_jni.cpp
|
||||
@@ -390,6 +391,7 @@ set_source_files_properties(
|
||||
spektrafilm/spectral_gamut.cpp
|
||||
spektrafilm/spectral_printing.cpp
|
||||
spektrafilm/spectral_generator.cpp
|
||||
spektrafilm/spectral_graph.cpp
|
||||
spektrafilm/spectral_jni.cpp
|
||||
PROPERTIES COMPILE_OPTIONS "-fno-fast-math;-ffp-contract=off"
|
||||
)
|
||||
|
||||
@@ -1,16 +1,32 @@
|
||||
// Port of Spektrafilm 0.3.4 filming, Hanatos adaptation and DIR chemistry.
|
||||
// Upstream commit 3bb2c2d2801ff68b92019cf1dbcbb133d60832bc; see LICENSE.spektrafilm.
|
||||
#include "spectral_filming.h"
|
||||
#include "spectral_gamut.h"
|
||||
#include "spectral_mallett_basis.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace spektrafilm {
|
||||
namespace {
|
||||
using Vec2 = std::array<double, 2>;
|
||||
|
||||
constexpr std::array<double, 9> proPhotoToSrgb{
|
||||
2.036491724209688, -0.7375906525094321, -0.2992598688901142,
|
||||
-0.2257179790832855, 1.2231765312786034, 0.002725224767466494,
|
||||
-0.010545128632237163, -0.1348798497250494, 1.1452101524691205,
|
||||
};
|
||||
|
||||
Vec3 multiply(const std::array<double, 9>& matrix, const Vec3& rgb) {
|
||||
Vec3 result{};
|
||||
for (int row = 0; row < 3; ++row)
|
||||
for (int c = 0; c < 3; ++c) result[row] += matrix[row * 3 + c] * rgb[c];
|
||||
return result;
|
||||
}
|
||||
|
||||
const std::vector<double>& data(const DataSet& set, const char* key, size_t size = 0) {
|
||||
auto found = set.find(key);
|
||||
if (found == set.end() || (size && found->second.size() != size))
|
||||
@@ -134,7 +150,7 @@ int reflectSpectral(int index, int size) {
|
||||
}
|
||||
} // namespace
|
||||
|
||||
Filming::Filming(const DataSet& shared, const DataSet& film) {
|
||||
Filming::Filming(const DataSet& shared, const DataSet& film, const SpectralOptics& optics) {
|
||||
const auto shape = fixed<3>(shared, "hanatos_shape");
|
||||
tcSize_ = int(shape[0]);
|
||||
const int wavelengths = int(shape[2]);
|
||||
@@ -147,86 +163,103 @@ Filming::Filming(const DataSet& shared, const DataSet& film) {
|
||||
if (locus.size() < 8 || locus.size()%2) throw std::invalid_argument("Invalid spectral locus");
|
||||
const auto& flags = data(film, "filming_flags", 6);
|
||||
positive_ = flags[0] != 0;
|
||||
dirActive_ = flags[4] != 0;
|
||||
stockDirActive_ = flags[4] != 0;
|
||||
mallett_ = optics.mallett;
|
||||
const auto& sensitivity = data(film, "filming_sensitivity", wavelengths*3);
|
||||
const auto& illuminant = data(film, "filming_reference_illuminant", wavelengths);
|
||||
const auto reference = fixed<2>(film, "filming_reference_xy");
|
||||
const auto center = tri2quad(reference);
|
||||
const auto& windowParams = data(film, "filming_window", 4);
|
||||
const auto& surfaceParams = data(film, "filming_surface", 45);
|
||||
const auto knee = fixed<3>(film, "filming_knee");
|
||||
const auto knee = optics.gamutKnee;
|
||||
if (knee[0] < 0 || knee[0] >= 1 || knee[1] <= knee[0] || knee[2] <= 0)
|
||||
throw std::invalid_argument("Invalid input gamut knee");
|
||||
proPhotoMatrix_ = fixed<9>(film, "filming_prophoto_to_xyz");
|
||||
srgbMatrix_ = fixed<9>(film, "filming_srgb_to_xyz");
|
||||
dirMatrix_ = fixed<9>(film, "filming_dir_matrix");
|
||||
gamma_ = fixed<3>(film, "filming_gamma");
|
||||
for (double g : gamma_) if (g <= 0) throw std::invalid_argument("Invalid film curve gamma");
|
||||
stockDirMatrix_ = fixed<9>(film, "filming_dir_matrix");
|
||||
stockGamma_ = fixed<3>(film, "filming_gamma");
|
||||
for (double g : stockGamma_) if (g <= 0) throw std::invalid_argument("Invalid film curve gamma");
|
||||
|
||||
std::vector<double> response = sensitivity;
|
||||
if (flags[1] != 0) {
|
||||
if (windowParams[1] <= 0 || windowParams[3] <= 0) throw std::invalid_argument("Invalid film window sigma");
|
||||
std::vector<double> window(wavelengths);
|
||||
for (int w=0; w<wavelengths; ++w) {
|
||||
double uv=0.5*(1+std::erf((wl[w]-windowParams[0])/(windowParams[1]*std::sqrt(2.0))));
|
||||
double ir=0.5*(1-std::erf((wl[w]-windowParams[2])/(windowParams[3]*std::sqrt(2.0))));
|
||||
window[w]=uv*ir;
|
||||
if (mallett_) {
|
||||
if (size_t(wavelengths) != kMallettBasis.size()) throw std::invalid_argument("Invalid Mallett spectral grid");
|
||||
double greenMidgray = 0;
|
||||
for (int w = 0; w < wavelengths; ++w) {
|
||||
greenMidgray += illuminant[w] * 0.184 * sensitivity[w * 3 + 1];
|
||||
for (int output = 0; output < 3; ++output)
|
||||
for (int input = 0; input < 3; ++input)
|
||||
mallettResponse_[output * 3 + input] +=
|
||||
kMallettBasis[w][input] * illuminant[w] * sensitivity[w * 3 + output];
|
||||
}
|
||||
for (int c=0; c<3; ++c) {
|
||||
double numerator=0, denominator=0;
|
||||
if (!(greenMidgray > 0)) throw std::invalid_argument("Invalid Mallett green normalization");
|
||||
for (double& value : mallettResponse_) value /= greenMidgray;
|
||||
} else {
|
||||
std::vector<double> response = sensitivity;
|
||||
if (optics.adaptationWindow) {
|
||||
if (windowParams[1] <= 0 || windowParams[3] <= 0) throw std::invalid_argument("Invalid film window sigma");
|
||||
std::vector<double> window(wavelengths);
|
||||
for (int w=0; w<wavelengths; ++w) {
|
||||
numerator += sensitivity[w*3+c]*illuminant[w]*window[w];
|
||||
denominator += sensitivity[w*3+c]*illuminant[w];
|
||||
double uv=0.5*(1+std::erf((wl[w]-windowParams[0])/(windowParams[1]*std::sqrt(2.0))));
|
||||
double ir=0.5*(1-std::erf((wl[w]-windowParams[2])/(windowParams[3]*std::sqrt(2.0))));
|
||||
window[w]=uv*ir;
|
||||
}
|
||||
double normalization=numerator/denominator;
|
||||
if (!std::isfinite(normalization) || normalization <= 0) throw std::invalid_argument("Invalid film window normalization");
|
||||
for (int w=0; w<wavelengths; ++w) response[w*3+c] *= window[w]/normalization;
|
||||
}
|
||||
}
|
||||
// scipy.ndimage.gaussian_filter(..., sigma=(0,0,sigma)) uses half-sample
|
||||
// symmetric reflection and a four-sigma kernel on the spectral axis.
|
||||
double sigma=flags[3];
|
||||
if (sigma < 0 || sigma > 100) throw std::invalid_argument("Invalid spectral blur sigma");
|
||||
int radius=int(4*sigma+0.5);
|
||||
std::vector<double> kernel;
|
||||
if (sigma > 0) {
|
||||
kernel.resize(radius*2+1);
|
||||
double sum=0;
|
||||
for (int k=-radius; k<=radius; ++k) { kernel[k+radius]=std::exp(-0.5*k*k/(sigma*sigma)); sum+=kernel[k+radius]; }
|
||||
for (double& v:kernel) v/=sum;
|
||||
}
|
||||
tcLut_.resize(size_t(tcSize_)*tcSize_*3);
|
||||
for (int i=0; i<tcSize_; ++i) for (int j=0; j<tcSize_; ++j) {
|
||||
size_t pixel=size_t(i)*tcSize_+j;
|
||||
Vec3 raw{};
|
||||
for (int w=0; w<wavelengths; ++w) {
|
||||
double spectrum=basis[pixel*wavelengths+w];
|
||||
if (sigma > 0) {
|
||||
spectrum=0;
|
||||
for (int k=-radius; k<=radius; ++k)
|
||||
spectrum+=kernel[k+radius]*basis[pixel*wavelengths+reflectSpectral(w+k,wavelengths)];
|
||||
for (int c=0; c<3; ++c) {
|
||||
double numerator=0, denominator=0;
|
||||
for (int w=0; w<wavelengths; ++w) {
|
||||
numerator += sensitivity[w*3+c]*illuminant[w]*window[w];
|
||||
denominator += sensitivity[w*3+c]*illuminant[w];
|
||||
}
|
||||
double normalization=numerator/denominator;
|
||||
if (!std::isfinite(normalization) || normalization <= 0) throw std::invalid_argument("Invalid film window normalization");
|
||||
for (int w=0; w<wavelengths; ++w) response[w*3+c] *= window[w]/normalization;
|
||||
}
|
||||
for (int c=0; c<3; ++c) raw[c]+=spectrum*response[w*3+c];
|
||||
}
|
||||
Vec2 tc{double(i)/(tcSize_-1), double(j)/(tcSize_-1)};
|
||||
for (int c=0; c<3; ++c) {
|
||||
if (flags[2] != 0) {
|
||||
double surface=poly4(tc,center,surfaceParams.data()+c*15);
|
||||
surface/=std::sqrt(1+(surface/2)*(surface/2));
|
||||
raw[c]*=std::exp2(surface);
|
||||
}
|
||||
tcLut_[pixel*3+c]=raw[c];
|
||||
// scipy.ndimage.gaussian_filter(..., sigma=(0,0,sigma)) uses half-sample
|
||||
// symmetric reflection and a four-sigma kernel on the spectral axis.
|
||||
double sigma=optics.blur;
|
||||
if (sigma < 0 || sigma > 100) throw std::invalid_argument("Invalid spectral blur sigma");
|
||||
int radius=int(4*sigma+0.5);
|
||||
std::vector<double> kernel;
|
||||
if (sigma > 0) {
|
||||
kernel.resize(radius*2+1);
|
||||
double sum=0;
|
||||
for (int k=-radius; k<=radius; ++k) { kernel[k+radius]=std::exp(-0.5*k*k/(sigma*sigma)); sum+=kernel[k+radius]; }
|
||||
for (double& v:kernel) v/=sum;
|
||||
}
|
||||
}
|
||||
if (flags[5] != 0) {
|
||||
std::vector<double> remapped(tcLut_.size());
|
||||
tcLut_.resize(size_t(tcSize_)*tcSize_*3);
|
||||
for (int i=0; i<tcSize_; ++i) for (int j=0; j<tcSize_; ++j) {
|
||||
Vec2 tc{double(i)/(tcSize_-1),double(j)/(tcSize_-1)};
|
||||
Vec2 compressed=compressXy(quad2tri(tc),reference,knee,locus);
|
||||
Vec3 value=bilinear(tcLut_,tcSize_,tri2quad(compressed));
|
||||
for (int c=0; c<3; ++c) remapped[(size_t(i)*tcSize_+j)*3+c]=value[c];
|
||||
size_t pixel=size_t(i)*tcSize_+j;
|
||||
Vec3 raw{};
|
||||
for (int w=0; w<wavelengths; ++w) {
|
||||
double spectrum=basis[pixel*wavelengths+w];
|
||||
if (sigma > 0) {
|
||||
spectrum=0;
|
||||
for (int k=-radius; k<=radius; ++k)
|
||||
spectrum+=kernel[k+radius]*basis[pixel*wavelengths+reflectSpectral(w+k,wavelengths)];
|
||||
}
|
||||
for (int c=0; c<3; ++c) raw[c]+=spectrum*response[w*3+c];
|
||||
}
|
||||
Vec2 tc{double(i)/(tcSize_-1), double(j)/(tcSize_-1)};
|
||||
for (int c=0; c<3; ++c) {
|
||||
if (optics.adaptationSurface) {
|
||||
double surface=poly4(tc,center,surfaceParams.data()+c*15);
|
||||
surface/=std::sqrt(1+(surface/2)*(surface/2));
|
||||
raw[c]*=std::exp2(surface);
|
||||
}
|
||||
tcLut_[pixel*3+c]=raw[c];
|
||||
}
|
||||
}
|
||||
if (optics.gamutCompression) {
|
||||
const auto oklch = optics.oklchGamut ? std::make_unique<InputOklchGamut>(locus) : nullptr;
|
||||
std::vector<double> remapped(tcLut_.size());
|
||||
for (int i=0; i<tcSize_; ++i) for (int j=0; j<tcSize_; ++j) {
|
||||
Vec2 tc{double(i)/(tcSize_-1),double(j)/(tcSize_-1)};
|
||||
const Vec2 xy = quad2tri(tc);
|
||||
Vec2 compressed = oklch ? oklch->compress(xy, knee) : compressXy(xy, reference, knee, locus);
|
||||
Vec3 value=bilinear(tcLut_,tcSize_,tri2quad(compressed));
|
||||
for (int c=0; c<3; ++c) remapped[(size_t(i)*tcSize_+j)*3+c]=value[c];
|
||||
}
|
||||
tcLut_=std::move(remapped);
|
||||
}
|
||||
tcLut_=std::move(remapped);
|
||||
}
|
||||
|
||||
logExposure_=data(film,"filming_log_exposure");
|
||||
@@ -244,6 +277,20 @@ Filming::Filming(const DataSet& shared, const DataSet& film) {
|
||||
densityMax_[c]=curveMax_[c]-curveMin_[c];
|
||||
for (size_t k=0; k<logExposure_.size(); ++k) normalizedCurves_[k*3+c]-=curveMin_[c];
|
||||
}
|
||||
configureDevelopment({});
|
||||
}
|
||||
|
||||
void Filming::configureDevelopment(const FilmDevelopment& development) {
|
||||
dirActive_ = stockDirActive_ && development.dirEnabled;
|
||||
for (int c = 0; c < 3; ++c) gamma_[c] = stockGamma_[c] * development.gamma;
|
||||
for (int donor = 0; donor < 3; ++donor) {
|
||||
for (int receiver = 0; receiver < 3; ++receiver) {
|
||||
const double layer = donor == receiver ? development.dirSameLayer : development.dirInterLayer;
|
||||
const int i = donor * 3 + receiver;
|
||||
const double coefficient = development.customDirMatrix ? development.dirCoefficients[i] : stockDirMatrix_[i];
|
||||
dirMatrix_[i] = dirActive_ ? coefficient * development.dirAmount * layer : 0;
|
||||
}
|
||||
}
|
||||
if (dirActive_) {
|
||||
beforeDirCurves_.resize(normalizedCurves_.size());
|
||||
for (int receiver=0; receiver<3; ++receiver) {
|
||||
@@ -257,6 +304,8 @@ Filming::Filming(const DataSet& shared, const DataSet& film) {
|
||||
}
|
||||
axis[k]=logExposure_[k]-correction;
|
||||
}
|
||||
if (!std::is_sorted(axis.begin(), axis.end()))
|
||||
throw std::invalid_argument("Nonmonotonic Spektrafilm DIR exposure axis");
|
||||
for (size_t k=0; k<axis.size(); ++k)
|
||||
beforeDirCurves_[k*3+receiver]=interp(logExposure_[k],axis,normalizedCurves_,receiver);
|
||||
}
|
||||
@@ -264,8 +313,7 @@ Filming::Filming(const DataSet& shared, const DataSet& film) {
|
||||
}
|
||||
|
||||
Vec3 Filming::expose(const Vec3& rgb, const std::array<double,9>& matrix) const {
|
||||
Vec3 xyz{};
|
||||
for (int row=0; row<3; ++row) for (int c=0; c<3; ++c) xyz[row]+=matrix[row*3+c]*rgb[c];
|
||||
Vec3 xyz = multiply(matrix, rgb);
|
||||
double brightness=xyz[0]+xyz[1]+xyz[2];
|
||||
Vec2 xy{xyz[0]/std::fmax(brightness,1e-10), xyz[1]/std::fmax(brightness,1e-10)};
|
||||
Vec3 raw=cubic(tcLut_,tcSize_,tri2quad(xy));
|
||||
@@ -273,6 +321,14 @@ Vec3 Filming::expose(const Vec3& rgb, const std::array<double,9>& matrix) const
|
||||
return raw;
|
||||
}
|
||||
|
||||
Vec3 Filming::exposeMallett(const Vec3& srgb) const {
|
||||
return multiply(mallettResponse_, srgb);
|
||||
}
|
||||
|
||||
Vec3 Filming::exposeProPhoto(const Vec3& linearProPhoto) const {
|
||||
return mallett_ ? exposeMallett(multiply(proPhotoToSrgb, linearProPhoto)) : expose(linearProPhoto, proPhotoMatrix_);
|
||||
}
|
||||
|
||||
Vec3 Filming::interpolate(const Vec3& logRaw,const std::vector<double>& curves) const {
|
||||
Vec3 result{};
|
||||
for (int c=0; c<3; ++c) result[c]=interp(logRaw[c]*gamma_[c],logExposure_,curves,c);
|
||||
@@ -280,9 +336,9 @@ Vec3 Filming::interpolate(const Vec3& logRaw,const std::vector<double>& curves)
|
||||
}
|
||||
|
||||
Vec3 Filming::develop(const Vec3& linearProPhoto) const {
|
||||
Vec3 raw=expose(linearProPhoto,proPhotoMatrix_);
|
||||
Vec3 raw=exposeProPhoto(linearProPhoto);
|
||||
Vec3 logRaw{};
|
||||
for (int c=0; c<3; ++c) logRaw[c]=std::log10(std::fmax(raw[c],0.0)+1e-10);
|
||||
for (int c=0; c<3; ++c) logRaw[c]=std::log10(std::fmax(raw[c] * scanExposureMultiplier_,0.0)+1e-10);
|
||||
Vec3 density=interpolate(logRaw,normalizedCurves_);
|
||||
if (!dirActive_) return density;
|
||||
Vec3 silver=density;
|
||||
@@ -292,8 +348,10 @@ Vec3 Filming::develop(const Vec3& linearProPhoto) const {
|
||||
return interpolate(logRaw,beforeDirCurves_);
|
||||
}
|
||||
|
||||
Vec3 Filming::midgrayDensity() const {
|
||||
Vec3 raw=expose({0.184,0.184,0.184},srgbMatrix_);
|
||||
Vec3 Filming::midgrayDensity(double exposureEv) const {
|
||||
const double middleGray = 0.184 * std::exp2(exposureEv);
|
||||
const Vec3 srgb{middleGray, middleGray, middleGray};
|
||||
Vec3 raw = mallett_ ? exposeMallett(srgb) : expose(srgb, srgbMatrix_);
|
||||
Vec3 logRaw{};
|
||||
for (int c=0; c<3; ++c) logRaw[c]=std::log10(raw[c]+1e-10);
|
||||
return interpolate(logRaw,originalCurves_);
|
||||
|
||||
@@ -4,26 +4,63 @@
|
||||
|
||||
namespace spektrafilm {
|
||||
|
||||
/** Deterministic upstream lut_mode filming, from linear ProPhoto RGB to CMY. */
|
||||
struct SpectralOptics {
|
||||
bool adaptationWindow = true;
|
||||
bool adaptationSurface = false;
|
||||
double blur = 0;
|
||||
bool gamutCompression = true;
|
||||
bool mallett = false;
|
||||
bool oklchGamut = false;
|
||||
Vec3 gamutKnee{0, 1, 6};
|
||||
};
|
||||
|
||||
struct FilmDevelopment {
|
||||
double gamma = 1;
|
||||
bool dirEnabled = true;
|
||||
double dirAmount = 1;
|
||||
double dirSameLayer = 1;
|
||||
double dirInterLayer = 1;
|
||||
bool customDirMatrix = false;
|
||||
std::array<double, 9> dirCoefficients{};
|
||||
};
|
||||
|
||||
/** Pointwise filming, from linear ProPhoto RGB to CMY. */
|
||||
class Filming {
|
||||
public:
|
||||
Filming(const DataSet& shared, const DataSet& film);
|
||||
Filming(const DataSet& shared, const DataSet& film, const SpectralOptics& optics = {});
|
||||
void configureDevelopment(const FilmDevelopment& development);
|
||||
Vec3 exposeProPhoto(const Vec3& linearProPhoto) const;
|
||||
Vec3 develop(const Vec3& linearProPhoto) const;
|
||||
double exposureMultiplier() const { return scanExposureMultiplier_; }
|
||||
void setScanExposureMultiplier(double value) { scanExposureMultiplier_ = value; }
|
||||
// Upstream enlarger balance uses unnormalised stock curves, without DIR,
|
||||
// and its default sRGB .184 reference rather than ProPhoto .184.
|
||||
Vec3 midgrayDensity() const;
|
||||
Vec3 midgrayDensity(double exposureEv = 0) const;
|
||||
bool positive() const { return positive_; }
|
||||
const Vec3& curveMin() const { return curveMin_; }
|
||||
const Vec3& curveMax() const { return curveMax_; }
|
||||
const Vec3& densityMax() const { return densityMax_; }
|
||||
const Vec3& gamma() const { return gamma_; }
|
||||
const std::vector<double>& logExposure() const { return logExposure_; }
|
||||
const std::vector<double>& originalCurves() const { return originalCurves_; }
|
||||
const std::vector<double>& normalizedCurves() const { return normalizedCurves_; }
|
||||
const std::vector<double>& beforeDirCurves() const { return beforeDirCurves_; }
|
||||
bool dirActive() const { return dirActive_; }
|
||||
const std::array<double, 9>& dirMatrix() const { return dirMatrix_; }
|
||||
|
||||
private:
|
||||
Vec3 expose(const Vec3& rgb, const std::array<double, 9>& matrix) const;
|
||||
Vec3 exposeMallett(const Vec3& srgb) const;
|
||||
Vec3 interpolate(const Vec3& logRaw, const std::vector<double>& curves) const;
|
||||
int tcSize_ = 0;
|
||||
bool positive_ = false;
|
||||
bool dirActive_ = false;
|
||||
Vec3 curveMin_{}, curveMax_{}, densityMax_{}, gamma_{};
|
||||
std::array<double, 9> proPhotoMatrix_{}, srgbMatrix_{}, dirMatrix_{};
|
||||
bool stockDirActive_ = false;
|
||||
bool mallett_ = false;
|
||||
double scanExposureMultiplier_ = 1;
|
||||
Vec3 curveMin_{}, curveMax_{}, densityMax_{}, stockGamma_{}, gamma_{};
|
||||
std::array<double, 9> proPhotoMatrix_{}, srgbMatrix_{}, stockDirMatrix_{}, dirMatrix_{};
|
||||
std::array<double, 9> mallettResponse_{};
|
||||
std::vector<double> tcLut_, logExposure_, originalCurves_, normalizedCurves_, beforeDirCurves_;
|
||||
};
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
#include <stdexcept>
|
||||
#include <vector>
|
||||
|
||||
namespace spektrafilm {
|
||||
@@ -31,6 +32,38 @@ constexpr Matrix kInverseCat16{{
|
||||
{1.8620678550872327, -1.0112546305316843, 0.14918677544445175},
|
||||
{0.3875265432361372, 0.6214474419314753, -0.00897398516761252},
|
||||
{-0.01584149884933386, -0.03412293802851557, 1.0499644368778496}}};
|
||||
constexpr Matrix kXyzToOklabLms{{
|
||||
{0.8189330101, 0.3618667424, -0.1288597137},
|
||||
{0.0329845436, 0.9293118715, 0.0361456387},
|
||||
{0.0482003018, 0.2643662691, 0.6338517070}}};
|
||||
constexpr Matrix kOklabLmsToXyz{{
|
||||
{1.2270138511035211, -0.5577999806518222, 0.2812561489664678},
|
||||
{-0.0405801784232806, 1.11225686961683, -0.07167667866560119},
|
||||
{-0.0763812845057069, -0.4214819784180127, 1.5861632204407947}}};
|
||||
constexpr Matrix kOklabLmsToLab{{
|
||||
{0.2104542553, 0.7936177850, -0.0040720468},
|
||||
{1.9779984951, -2.4285922050, 0.4505937099},
|
||||
{0.0259040371, 0.7827717662, -0.8086757660}}};
|
||||
constexpr Matrix kOklabLabToLms{{
|
||||
{0.9999999984505196, 0.3963377921737678, 0.21580375806075877},
|
||||
{1.0000000088817607, -0.10556134232365633, -0.0638541747717059},
|
||||
{1.0000000546724108, -0.08948418209496574, -1.2914855378640917}}};
|
||||
constexpr Matrix kXyzToJzLms{{
|
||||
{0.41478972, 0.579999, 0.0146480},
|
||||
{-0.2015100, 1.120649, 0.0531008},
|
||||
{-0.0166008, 0.264800, 0.6684799}}};
|
||||
constexpr Matrix kJzLmsToXyz{{
|
||||
{1.9242264357876069, -1.0047923125953657, 0.037651404030617994},
|
||||
{0.35031676209499907, 0.7264811939316552, -0.06538442294808501},
|
||||
{-0.09098281098284752, -0.3127282905230739, 1.5227665613052603}}};
|
||||
constexpr Matrix kJzLmsToIab{{
|
||||
{0.5, 0.5, 0.0},
|
||||
{3.524, -4.066708, 0.542708},
|
||||
{0.199076, 1.096799, -1.295875}}};
|
||||
constexpr Matrix kJzIabToLms{{
|
||||
{1.0, 0.1386050432715393, 0.05804731615611882},
|
||||
{1.0, -0.13860504327153927, -0.05804731615611891},
|
||||
{1.0, -0.09601924202631895, -0.811891896056039}}};
|
||||
|
||||
Vec3 multiply(const Matrix& matrix, const Vec3& value) {
|
||||
Vec3 out{};
|
||||
@@ -54,7 +87,150 @@ double knee(double value, double threshold, double limit, double power) {
|
||||
if (value <= threshold) return value;
|
||||
const double scale = limit - threshold;
|
||||
const double x = (value - threshold) / scale;
|
||||
return threshold + scale * x / std::pow(1.0 + std::pow(x, power), 1.0 / power);
|
||||
const double raised = std::pow(x, power);
|
||||
if (std::isinf(raised)) return limit;
|
||||
return threshold + scale * x / std::pow(1.0 + raised, 1.0 / power);
|
||||
}
|
||||
|
||||
Vec3 toOklab(const Vec3& xyz) {
|
||||
Vec3 lms = multiply(kXyzToOklabLms, xyz);
|
||||
for (double& value : lms) value = std::cbrt(value);
|
||||
return multiply(kOklabLmsToLab, lms);
|
||||
}
|
||||
|
||||
Vec3 fromOklab(const Vec3& lab) {
|
||||
Vec3 lms = multiply(kOklabLabToLms, lab);
|
||||
for (double& value : lms) value = value * value * value;
|
||||
return multiply(kOklabLmsToXyz, lms);
|
||||
}
|
||||
|
||||
constexpr double kLr1 = 0.206, kLr2 = 0.03, kLr3 = (1.0 + kLr1) / (1.0 + kLr2);
|
||||
|
||||
double toLr(double l) {
|
||||
const double t = kLr3 * l - kLr1;
|
||||
return (t + std::sqrt(t * t + 4.0 * kLr2 * kLr3 * l)) * 0.5;
|
||||
}
|
||||
|
||||
Vec3 fromOklrab(Vec3 lab) {
|
||||
lab[0] = (lab[0] * (lab[0] + kLr1)) / (kLr3 * (lab[0] + kLr2));
|
||||
return fromOklab(lab);
|
||||
}
|
||||
|
||||
constexpr double kPqM1 = 2610.0 / 16384, kPqM2 = 1.7 * 2523.0 / 32;
|
||||
constexpr double kPqC1 = 3424.0 / 4096, kPqC2 = 2413.0 / 128, kPqC3 = 2392.0 / 128;
|
||||
constexpr double kJzD = -0.56, kJzD0 = 1.6295499532821566e-11;
|
||||
|
||||
Vec3 toJzazbz(const Vec3& xyz) {
|
||||
Vec3 lms = multiply(kXyzToJzLms, {
|
||||
100 * (1.15 * xyz[0] - 0.15 * xyz[2]),
|
||||
100 * (0.66 * xyz[1] + 0.34 * xyz[0]),
|
||||
100 * xyz[2],
|
||||
});
|
||||
for (double& value : lms) {
|
||||
const double pq = signedPower(value / 10000, kPqM1);
|
||||
value = signedPower((kPqC1 + kPqC2 * pq) / (1 + kPqC3 * pq), kPqM2);
|
||||
}
|
||||
Vec3 jab = multiply(kJzLmsToIab, lms);
|
||||
jab[0] = (1 + kJzD) * jab[0] / (1 + kJzD * jab[0]) - kJzD0;
|
||||
return jab;
|
||||
}
|
||||
|
||||
Vec3 fromJzazbz(Vec3 jab) {
|
||||
jab[0] += kJzD0;
|
||||
jab[0] /= 1 + kJzD - kJzD * jab[0];
|
||||
Vec3 lms = multiply(kJzIabToLms, jab);
|
||||
for (double& value : lms) {
|
||||
const double pq = signedPower(value, 1 / kPqM2);
|
||||
value = 100 * signedPower(std::max(0.0, pq - kPqC1) / (kPqC2 - kPqC3 * pq), 1 / kPqM1);
|
||||
}
|
||||
Vec3 xyz = multiply(kJzLmsToXyz, lms);
|
||||
xyz[0] = (xyz[0] + 0.15 * xyz[2]) / 1.15;
|
||||
xyz[1] = (xyz[1] - 0.34 * xyz[0]) / 0.66;
|
||||
return xyz;
|
||||
}
|
||||
|
||||
Chromaticity xyzToXy(const Vec3& xyz) {
|
||||
const double total = std::max(xyz[0] + xyz[1] + xyz[2], 1e-12);
|
||||
return {xyz[0] / total, xyz[1] / total};
|
||||
}
|
||||
|
||||
bool inLocus(const Chromaticity& xy, const std::vector<double>& locus) {
|
||||
bool inside = false;
|
||||
for (size_t i = 2; i < locus.size(); i += 2) {
|
||||
const double y0 = locus[i - 1], y1 = locus[i + 1];
|
||||
if ((y0 > xy[1]) == (y1 > xy[1])) continue;
|
||||
const double edgeX = locus[i - 2] + (locus[i] - locus[i - 2]) * (xy[1] - y0) / (y1 - y0);
|
||||
if (xy[0] < edgeX) inside = !inside;
|
||||
}
|
||||
return inside;
|
||||
}
|
||||
|
||||
template <typename Predicate>
|
||||
std::vector<double> makeBoundary(double minimumL, double maximumL, double maximumC, const Predicate& inside) {
|
||||
std::vector<double> cmax(kLightnessCount * kHueCount);
|
||||
for (int l = 0; l < kLightnessCount; ++l) {
|
||||
const double lightness = minimumL + l * ((maximumL - minimumL) / (kLightnessCount - 1));
|
||||
for (int h = 0; h < kHueCount; ++h) {
|
||||
const double hue = -kPi + h * (2.0 * kPi / kHueCount);
|
||||
const double ch = std::cos(hue), sh = std::sin(hue);
|
||||
double lo = 0, hi = maximumC;
|
||||
for (int iteration = 0; iteration < kBisections; ++iteration) {
|
||||
const double mid = (lo + hi) * 0.5;
|
||||
if (inside(Vec3{lightness, mid * ch, mid * sh})) lo = mid;
|
||||
else hi = mid;
|
||||
}
|
||||
cmax[l * kHueCount + h] = lo;
|
||||
}
|
||||
}
|
||||
return cmax;
|
||||
}
|
||||
|
||||
double boundaryLookup(const std::vector<double>& table, double lightness, double hue, double minimum, double maximum) {
|
||||
const double li = (std::clamp(lightness, minimum, maximum) - minimum) / (maximum - minimum) * (kLightnessCount - 1);
|
||||
const int l0 = std::clamp(static_cast<int>(std::floor(li)), 0, kLightnessCount - 2);
|
||||
const double lf = li - l0;
|
||||
const double hueStep = (-kPi + 2.0 * kPi / kHueCount) - (-kPi);
|
||||
const double hi = (hue + kPi) / hueStep, floorHue = std::floor(hi);
|
||||
const int h0 = (static_cast<int>(floorHue) % kHueCount + kHueCount) % kHueCount;
|
||||
const int h1 = (h0 + 1) % kHueCount;
|
||||
const double hf = hi - floorHue;
|
||||
return table[l0 * kHueCount + h0] * (1.0 - lf) * (1.0 - hf) +
|
||||
table[l0 * kHueCount + h1] * (1.0 - lf) * hf +
|
||||
table[(l0 + 1) * kHueCount + h0] * lf * (1.0 - hf) +
|
||||
table[(l0 + 1) * kHueCount + h1] * lf * hf;
|
||||
}
|
||||
|
||||
template <typename Conversion>
|
||||
std::vector<double> makeOutputBoundary(double minimumL, double maximumL, double maximumC, const Conversion& convert) {
|
||||
return makeBoundary(minimumL, maximumL, maximumC, [&](const Vec3& lab) {
|
||||
const Vec3 rgb = multiply(kXyzToRgb, convert(lab));
|
||||
return std::all_of(rgb.begin(), rgb.end(), [](double value) {
|
||||
return value >= -1e-6 && value <= 1 + 1e-6;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const std::vector<double>& outputBoundary(OutputGamutAlgorithm algorithm) {
|
||||
if (algorithm == OutputGamutAlgorithm::Jzazbz) {
|
||||
static const auto table = makeOutputBoundary(0.002, 0.18, 0.3, fromJzazbz);
|
||||
return table;
|
||||
}
|
||||
if (algorithm == OutputGamutAlgorithm::Oklrab) {
|
||||
static const auto table = makeOutputBoundary(0.02, 1, 0.5, fromOklrab);
|
||||
return table;
|
||||
}
|
||||
static const auto table = makeOutputBoundary(0.02, 1, 0.5, fromOklab);
|
||||
return table;
|
||||
}
|
||||
|
||||
void compressChroma(Vec3& lab, const Vec3& chromaKnee, const std::vector<double>& table,
|
||||
double lookupLightness, double minimum, double maximum) {
|
||||
const double hue = std::atan2(lab[2], lab[1]);
|
||||
const double maxChroma = std::max(1e-9, boundaryLookup(table, lookupLightness, hue, minimum, maximum));
|
||||
const double chroma = std::hypot(lab[1], lab[2]);
|
||||
const double adjusted = knee(chroma / maxChroma, chromaKnee[0], chromaKnee[1], chromaKnee[2]) * maxChroma;
|
||||
lab[1] = adjusted * std::cos(hue);
|
||||
lab[2] = adjusted * std::sin(hue);
|
||||
}
|
||||
|
||||
struct Cam16 {
|
||||
@@ -165,47 +341,10 @@ struct GamutBoundary {
|
||||
Cam16 cam;
|
||||
std::vector<double> cmax;
|
||||
double whiteJp;
|
||||
// Match numpy.linspace's step followed by h_grid[1]-h_grid[0].
|
||||
double hueStep = (-kPi + 2.0 * kPi / kHueCount) - (-kPi);
|
||||
|
||||
GamutBoundary() : cmax(kLightnessCount * kHueCount) {
|
||||
const Vec3 white{0.3457 / 0.3585, 1.0, (1.0 - 0.3457 - 0.3585) / 0.3585};
|
||||
whiteJp = cam.forward(white)[0];
|
||||
for (int l = 0; l < kLightnessCount; ++l) {
|
||||
const double lightness = 1.0 + l * (109.0 / (kLightnessCount - 1));
|
||||
for (int h = 0; h < kHueCount; ++h) {
|
||||
const double hue = -kPi + h * (2.0 * kPi / kHueCount);
|
||||
const double ch = std::cos(hue);
|
||||
const double sh = std::sin(hue);
|
||||
double lo = 0.0;
|
||||
double hi = 150.0;
|
||||
for (int iteration = 0; iteration < kBisections; ++iteration) {
|
||||
const double mid = (lo + hi) * 0.5;
|
||||
const Vec3 rgb = multiply(kXyzToRgb, cam.inverse({lightness, mid * ch, mid * sh}));
|
||||
const bool inside = std::all_of(rgb.begin(), rgb.end(), [](double v) {
|
||||
return v >= -1e-6 && v <= 1.0 + 1e-6;
|
||||
});
|
||||
if (inside) lo = mid; else hi = mid;
|
||||
}
|
||||
cmax[l * kHueCount + h] = lo;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
double lookup(double lightness, double hue) const {
|
||||
const double li = (std::clamp(lightness, 1.0, 110.0) - 1.0) / 109.0 * (kLightnessCount - 1);
|
||||
const int l0 = std::clamp(static_cast<int>(std::floor(li)), 0, kLightnessCount - 2);
|
||||
const double lf = li - l0;
|
||||
const double hi = (hue + kPi) / hueStep;
|
||||
const int floorHue = static_cast<int>(std::floor(hi));
|
||||
const int h0 = (floorHue % kHueCount + kHueCount) % kHueCount;
|
||||
const int h1 = (h0 + 1) % kHueCount;
|
||||
const double hf = hi - std::floor(hi);
|
||||
return cmax[l0 * kHueCount + h0] * (1.0 - lf) * (1.0 - hf) +
|
||||
cmax[l0 * kHueCount + h1] * (1.0 - lf) * hf +
|
||||
cmax[(l0 + 1) * kHueCount + h0] * lf * (1.0 - hf) +
|
||||
cmax[(l0 + 1) * kHueCount + h1] * lf * hf;
|
||||
}
|
||||
GamutBoundary()
|
||||
: cmax(makeOutputBoundary(1, 110, 150, [this](const Vec3& jab) { return cam.inverse(jab); })),
|
||||
whiteJp(cam.forward({0.3457 / 0.3585, 1, (1 - 0.3457 - 0.3585) / 0.3585})[0]) {}
|
||||
};
|
||||
|
||||
const GamutBoundary& boundary() {
|
||||
@@ -216,9 +355,56 @@ const GamutBoundary& boundary() {
|
||||
|
||||
} // namespace
|
||||
|
||||
OutputGamut::OutputGamut() { (void) boundary(); }
|
||||
InputOklchGamut::InputOklchGamut(const std::vector<double>& locus)
|
||||
: boundary_(makeBoundary(0.05, 1, 0.5, [&](const Vec3& lab) { return inLocus(xyzToXy(fromOklab(lab)), locus); })) {}
|
||||
|
||||
Chromaticity InputOklchGamut::compress(const Chromaticity& xy, const Vec3& chromaKnee) const {
|
||||
const double y = std::max(xy[1], 1e-12);
|
||||
Vec3 lab = toOklab({xy[0] / y, 1, (1 - xy[0] - xy[1]) / y});
|
||||
compressChroma(lab, chromaKnee, boundary_, lab[0], 0.05, 1);
|
||||
return xyzToXy(fromOklab(lab));
|
||||
}
|
||||
|
||||
OutputGamut::OutputGamut(OutputGamutAlgorithm algorithm, const Vec3& chromaKnee)
|
||||
: algorithm_(algorithm), knee_(chromaKnee) {
|
||||
if (algorithm < OutputGamutAlgorithm::Cam16 || algorithm > OutputGamutAlgorithm::Jzazbz ||
|
||||
knee_[0] < 0 || knee_[0] >= 1 || knee_[1] <= knee_[0] || knee_[2] <= 0)
|
||||
throw std::invalid_argument("Invalid Spektrafilm output gamut parameters");
|
||||
if (algorithm_ == OutputGamutAlgorithm::Cam16) (void) boundary();
|
||||
else if (algorithm_ != OutputGamutAlgorithm::Off && algorithm_ != OutputGamutAlgorithm::AcesRgc)
|
||||
(void) outputBoundary(algorithm_);
|
||||
}
|
||||
|
||||
Vec3 OutputGamut::compress(const Vec3& linearProPhoto) const {
|
||||
if (algorithm_ == OutputGamutAlgorithm::Off) return linearProPhoto;
|
||||
if (algorithm_ == OutputGamutAlgorithm::AcesRgc) {
|
||||
const double maximum = *std::max_element(linearProPhoto.begin(), linearProPhoto.end());
|
||||
if (maximum <= 1e-12) return linearProPhoto;
|
||||
Vec3 result{};
|
||||
for (int c = 0; c < 3; ++c) {
|
||||
const double distance = (maximum - linearProPhoto[c]) / maximum;
|
||||
result[c] = maximum * (1 - knee(distance, knee_[0], knee_[1], knee_[2]));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
if (algorithm_ != OutputGamutAlgorithm::Cam16) {
|
||||
const Vec3 xyz = multiply(kRgbToXyz, linearProPhoto);
|
||||
const auto& table = outputBoundary(algorithm_);
|
||||
if (algorithm_ == OutputGamutAlgorithm::Jzazbz) {
|
||||
static const double white = toJzazbz({0.3457 / 0.3585, 1, (1 - 0.3457 - 0.3585) / 0.3585})[0];
|
||||
Vec3 lab = toJzazbz(xyz);
|
||||
if (!std::all_of(lab.begin(), lab.end(), [](double value) { return std::isfinite(value); }))
|
||||
throw std::runtime_error("Non-finite JzAzBz color");
|
||||
lab[0] = knee(lab[0] / white, 0.7, 1, 2.2) * white;
|
||||
compressChroma(lab, knee_, table, lab[0], 0.002, 0.18);
|
||||
return multiply(kXyzToRgb, fromJzazbz(lab));
|
||||
}
|
||||
Vec3 lab = toOklab(xyz);
|
||||
lab[0] = knee(lab[0], 0.7, 1, 2.2);
|
||||
const double lightness = algorithm_ == OutputGamutAlgorithm::Oklrab ? toLr(lab[0]) : lab[0];
|
||||
compressChroma(lab, knee_, table, lightness, 0.02, 1);
|
||||
return multiply(kXyzToRgb, fromOklab(lab));
|
||||
}
|
||||
const GamutBoundary& state = boundary();
|
||||
Vec3 jab = state.cam.forward(multiply(kRgbToXyz, linearProPhoto));
|
||||
jab[0] = knee(jab[0] / state.whiteJp, 0.7, 1.0, 2.2) * state.whiteJp;
|
||||
@@ -232,8 +418,8 @@ Vec3 OutputGamut::compress(const Vec3& linearProPhoto) const {
|
||||
const double invalid = std::numeric_limits<double>::quiet_NaN();
|
||||
return multiply(kXyzToRgb, state.cam.inverse({jab[0], invalid, invalid}));
|
||||
}
|
||||
const double maxChroma = std::fmax(state.lookup(jab[0], hue), 1e-9);
|
||||
const double newChroma = knee(chroma / maxChroma, 0.0, 1.0, 6.0) * maxChroma;
|
||||
const double maxChroma = std::fmax(boundaryLookup(state.cmax, jab[0], hue, 1, 110), 1e-9);
|
||||
const double newChroma = knee(chroma / maxChroma, knee_[0], knee_[1], knee_[2]) * maxChroma;
|
||||
jab[1] = newChroma * std::cos(hue);
|
||||
jab[2] = newChroma * std::sin(hue);
|
||||
return multiply(kXyzToRgb, state.cam.inverse(jab));
|
||||
|
||||
@@ -4,13 +4,31 @@
|
||||
|
||||
namespace spektrafilm {
|
||||
|
||||
// Spektrafilm 0.3.4's default output gamut compressor, fixed to linear
|
||||
// ProPhoto RGB. The shared 64 x 720 chroma boundary is generated from the
|
||||
// CAM16 inverse on first use; it is not a pre-baked colour transform.
|
||||
using Chromaticity = std::array<double, 2>;
|
||||
|
||||
class InputOklchGamut {
|
||||
public:
|
||||
explicit InputOklchGamut(const std::vector<double>& locus);
|
||||
Chromaticity compress(const Chromaticity& xy, const Vec3& knee) const;
|
||||
private:
|
||||
std::vector<double> boundary_;
|
||||
};
|
||||
|
||||
enum class OutputGamutAlgorithm { Cam16, Off, Oklch, AcesRgc, Oklrab, Jzazbz };
|
||||
|
||||
// Spektrafilm 0.3.4 output gamut mapping in linear ProPhoto RGB. Each
|
||||
// perceptual mode builds its chroma boundary on first use.
|
||||
class OutputGamut {
|
||||
public:
|
||||
OutputGamut();
|
||||
explicit OutputGamut(OutputGamutAlgorithm algorithm = OutputGamutAlgorithm::Cam16,
|
||||
const Vec3& knee = {0, 1, 6});
|
||||
Vec3 compress(const Vec3& linearProPhoto) const;
|
||||
bool unbounded() const {
|
||||
return algorithm_ == OutputGamutAlgorithm::Off || algorithm_ == OutputGamutAlgorithm::AcesRgc;
|
||||
}
|
||||
private:
|
||||
OutputGamutAlgorithm algorithm_;
|
||||
Vec3 knee_;
|
||||
};
|
||||
|
||||
} // namespace spektrafilm
|
||||
@@ -55,10 +55,13 @@ DensityWire measureDensityWire(const Filming& film) {
|
||||
}
|
||||
|
||||
std::vector<float> generateFilmLut(const Filming& film, const DensityWire& wire,
|
||||
const Scanner* positiveScanner, int size) {
|
||||
const Scanner* scanner, int size, double exposureEv) {
|
||||
const double exposure = std::exp2(exposureEv);
|
||||
return generate(size, [&](int r, int g, int b) {
|
||||
Vec3 value = film.develop(linearInput(r, g, b, size));
|
||||
if (positiveScanner) return positiveScanner->scan(value);
|
||||
Vec3 input = linearInput(r, g, b, size);
|
||||
for (double& channel : input) channel *= exposure;
|
||||
Vec3 value = film.develop(input);
|
||||
if (scanner) return scanner->scan(value);
|
||||
for (int c = 0; c < 3; ++c)
|
||||
value[c] = (value[c] - wire.minimum[c]) / (wire.maximum[c] - wire.minimum[c]);
|
||||
return value;
|
||||
|
||||
@@ -6,7 +6,7 @@ namespace spektrafilm {
|
||||
struct DensityWire { Vec3 minimum, maximum; };
|
||||
DensityWire measureDensityWire(const Filming& film);
|
||||
std::vector<float> generateFilmLut(const Filming& film, const DensityWire& wire,
|
||||
const Scanner* positiveScanner, int size);
|
||||
const Scanner* scanner, int size, double exposureEv = 0);
|
||||
std::vector<float> generatePrintLut(const Printing& printing, const Scanner& scanner,
|
||||
const DensityWire& wire, int size);
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
#include "spectral_graph.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <exception>
|
||||
#include <mutex>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace spektrafilm {
|
||||
namespace {
|
||||
constexpr int size = 65;
|
||||
constexpr int paperCurveSize = 4096;
|
||||
constexpr double paperLogMin = -10;
|
||||
constexpr double paperLogMax = 6;
|
||||
|
||||
template<class Evaluate>
|
||||
std::vector<float> lattice(const Evaluate& evaluate) {
|
||||
std::vector<float> result(size * size * size * 4);
|
||||
std::exception_ptr failure;
|
||||
std::mutex mutex;
|
||||
#pragma omp parallel for num_threads(2) schedule(static)
|
||||
for (int z = 0; z < size; ++z) {
|
||||
try {
|
||||
for (int y = 0; y < size; ++y) {
|
||||
for (int x = 0; x < size; ++x) {
|
||||
const auto value = evaluate(Vec3{double(x)/(size-1), double(y)/(size-1), double(z)/(size-1)});
|
||||
const size_t i = ((z * size + y) * size + x) * 4;
|
||||
for (int c = 0; c < 3; ++c) result[i + c] = static_cast<float>(value[c]);
|
||||
result[i + 3] = 1;
|
||||
}
|
||||
}
|
||||
} catch (...) {
|
||||
std::lock_guard lock(mutex);
|
||||
if (!failure) failure = std::current_exception();
|
||||
}
|
||||
}
|
||||
if (failure) std::rethrow_exception(failure);
|
||||
if (std::any_of(result.begin(), result.end(), [](float v) { return !std::isfinite(v); }))
|
||||
throw std::runtime_error("Non-finite Spektrafilm stage lattice");
|
||||
return result;
|
||||
}
|
||||
|
||||
Vec3 toDomain(const Vec3& code, const Vec3& low, const Vec3& high) {
|
||||
return {low[0] + code[0] * (high[0] - low[0]), low[1] + code[1] * (high[1] - low[1]),
|
||||
low[2] + code[2] * (high[2] - low[2])};
|
||||
}
|
||||
|
||||
void append(std::vector<float>& target, const Vec3& values) {
|
||||
for (double v : values) target.push_back(static_cast<float>(v));
|
||||
}
|
||||
}
|
||||
|
||||
SpectralGraph buildSpectralGraph(const Filming& film, const DataSet& filmData,
|
||||
const Printing* print, const Scanner& scanner,
|
||||
bool needsGlare, bool needsGrain) {
|
||||
SpectralGraph graph;
|
||||
auto& [filmRaw, filmCurves, paperRaw, paperCurves, scan, gamut, config] = graph;
|
||||
filmRaw = lattice([&](const Vec3& code) {
|
||||
Vec3 linear{};
|
||||
for (int c = 0; c < 3; ++c) linear[c] = static_cast<float>(2.88 * proPhotoDecode(code[c]));
|
||||
return film.exposeProPhoto(linear);
|
||||
});
|
||||
|
||||
const auto& axis = film.logExposure();
|
||||
const auto& stock = film.normalizedCurves();
|
||||
const auto& beforeDir = film.dirActive() ? film.beforeDirCurves() : stock;
|
||||
const auto* layers = needsGrain ? &filmData.at("filming_layer_curves") : nullptr;
|
||||
if (layers && layers->size() != axis.size() * 9) throw std::invalid_argument("Invalid Spektrafilm grain layer curves");
|
||||
filmCurves.resize(axis.size() * 4 * (layers ? 5 : 2));
|
||||
std::array<Vec3, 3> layerMax{};
|
||||
for (size_t i = 0; i < axis.size(); ++i) {
|
||||
for (int c = 0; c < 3; ++c) {
|
||||
filmCurves[i * 4 + c] = static_cast<float>(stock[i * 3 + c]);
|
||||
filmCurves[(axis.size() + i) * 4 + c] = static_cast<float>(beforeDir[i * 3 + c]);
|
||||
if (layers) for (size_t layer = 0; layer < 3; ++layer) {
|
||||
const double density = (*layers)[i * 9 + layer * 3 + c];
|
||||
layerMax[layer][c] = std::max(layerMax[layer][c], density);
|
||||
filmCurves[(axis.size() * (layer + 2) + i) * 4 + c] = static_cast<float>(density);
|
||||
}
|
||||
}
|
||||
filmCurves[i * 4 + 3] = static_cast<float>(axis[i]);
|
||||
}
|
||||
|
||||
const Vec3 filmLow{-1, -1, -1};
|
||||
Vec3 filmHigh = film.densityMax();
|
||||
for (double& v : filmHigh) v = v * 1.5 + 1;
|
||||
Vec3 scanLow = filmLow, scanHigh = filmHigh;
|
||||
if (print) {
|
||||
paperRaw = lattice([&](const Vec3& code) {
|
||||
return print->expose(toDomain(code, filmLow, filmHigh));
|
||||
});
|
||||
paperCurves.resize(paperCurveSize * 4);
|
||||
for (int i = 0; i < paperCurveSize; ++i) {
|
||||
const double e = paperLogMin + i * (paperLogMax-paperLogMin) / (paperCurveSize-1);
|
||||
const auto density = print->develop({e, e, e});
|
||||
for (int c = 0; c < 3; ++c) paperCurves[i * 4 + c] = static_cast<float>(density[c]);
|
||||
}
|
||||
scanLow = print->develop({paperLogMin, paperLogMin, paperLogMin});
|
||||
scanHigh = print->develop({paperLogMax, paperLogMax, paperLogMax});
|
||||
}
|
||||
const bool unbounded = scanner.unboundedGamut();
|
||||
scan = lattice([&](const Vec3& code) {
|
||||
const auto density = toDomain(code, scanLow, scanHigh);
|
||||
if (needsGlare) return scanner.linearRgb(density);
|
||||
if (unbounded) return scanner.gamutRgb(scanner.linearRgb(density));
|
||||
return scanner.scan(density);
|
||||
});
|
||||
Vec3 gamutLow{}, gamutHigh{1, 1, 1};
|
||||
const auto white = scanner.whiteRgb();
|
||||
if (needsGlare) {
|
||||
for (size_t i = 0; i < scan.size(); i += 4) for (int c = 0; c < 3; ++c) {
|
||||
gamutLow[c] = std::min(gamutLow[c], double(scan[i+c]));
|
||||
gamutHigh[c] = std::max(gamutHigh[c], double(scan[i+c]));
|
||||
}
|
||||
for (int c = 0; c < 3; ++c) gamutHigh[c] += std::max(white[c], 0.0) * 0.25;
|
||||
gamut = lattice([&](const Vec3& code) {
|
||||
Vec3 rgb = scanner.gamutRgb(toDomain(code, gamutLow, gamutHigh));
|
||||
if (!unbounded) for (double& v : rgb) v = proPhotoEncode(v);
|
||||
return rgb;
|
||||
});
|
||||
}
|
||||
|
||||
config = {float(axis.size()), layers ? 5.f : 2.f, film.positive() ? 1.f : 0.f,
|
||||
static_cast<float>(film.exposureMultiplier())};
|
||||
append(config, film.gamma()); // 4
|
||||
append(config, film.densityMax()); // 7
|
||||
for (double v : film.dirMatrix()) config.push_back(film.dirActive() ? static_cast<float>(v) : 0.f); // 10
|
||||
append(config, filmLow); // 19
|
||||
append(config, filmHigh); // 22
|
||||
append(config, scanLow); // 25
|
||||
append(config, scanHigh); // 28
|
||||
append(config, white); // 31
|
||||
append(config, gamutLow); // 34
|
||||
append(config, gamutHigh); // 37
|
||||
for (const auto& v : layerMax) append(config, v); // 40
|
||||
config.push_back(unbounded ? 1.f : 0.f); // 49
|
||||
return graph;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
#pragma once
|
||||
|
||||
#include "spectral_filming.h"
|
||||
#include "spectral_printing.h"
|
||||
|
||||
namespace spektrafilm {
|
||||
|
||||
// Film exposure, film curves, paper exposure, paper curves, scan, gamut, and constants.
|
||||
using SpectralGraph = std::array<std::vector<float>, 7>;
|
||||
SpectralGraph buildSpectralGraph(const Filming& film, const DataSet& filmData,
|
||||
const Printing* print, const Scanner& scanner,
|
||||
bool needsGlare, bool needsGrain);
|
||||
|
||||
}
|
||||
@@ -1,17 +1,26 @@
|
||||
#include "spectral_generator.h"
|
||||
#include "spectral_graph.h"
|
||||
#include <jni.h>
|
||||
#include <android/log.h>
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace {
|
||||
using namespace spektrafilm;
|
||||
using FilmOptions = std::array<float, 25>;
|
||||
using PrintOptions = std::array<float, 15>;
|
||||
using ScanOptions = std::array<float, 11>;
|
||||
constexpr FilmOptions stockFilmOptions{0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 6};
|
||||
|
||||
struct RuntimeModel {
|
||||
std::string sharedKey, filmKey;
|
||||
DataSet shared, filmData;
|
||||
std::unique_ptr<Filming> film;
|
||||
FilmOptions filmOptions = stockFilmOptions;
|
||||
DensityWire wire{};
|
||||
};
|
||||
RuntimeModel model;
|
||||
@@ -47,19 +56,70 @@ jfloatArray output(JNIEnv* env, const std::vector<float>& values) {
|
||||
if (env->ExceptionCheck()) throw std::runtime_error("Unable to copy spectral lattice");
|
||||
return array;
|
||||
}
|
||||
|
||||
template<size_t N>
|
||||
std::array<float, N> options(JNIEnv* env, jfloatArray input) {
|
||||
if (!input || env->GetArrayLength(input) != N)
|
||||
throw std::invalid_argument("Invalid Spektrafilm option count");
|
||||
std::array<float, N> values{};
|
||||
env->GetFloatArrayRegion(input, 0, N, values.data());
|
||||
if (env->ExceptionCheck() || !std::all_of(values.begin(), values.end(), [](float v) { return std::isfinite(v); }))
|
||||
throw std::invalid_argument("Invalid Spektrafilm options");
|
||||
return values;
|
||||
}
|
||||
|
||||
void configureFilm(const FilmOptions& values, bool directScan) {
|
||||
const bool rebuild = !model.film ||
|
||||
!std::equal(values.begin() + 6, values.begin() + 15, model.filmOptions.begin() + 6);
|
||||
if (rebuild) {
|
||||
const SpectralOptics optics{values[6] != 0, values[7] != 0, values[8], values[9] != 0,
|
||||
values[10] != 0, values[11] != 0, {values[12], values[13], values[14]}};
|
||||
model.film = std::make_unique<Filming>(model.shared, model.filmData, optics);
|
||||
}
|
||||
if (rebuild || !std::equal(values.begin() + 1, values.begin() + 6, model.filmOptions.begin() + 1) ||
|
||||
!std::equal(values.begin() + 15, values.end(), model.filmOptions.begin() + 15)) {
|
||||
FilmDevelopment development{values[1], values[2] != 0, values[3], values[4], values[5], values[15] != 0};
|
||||
std::copy(values.begin() + 16, values.end(), development.dirCoefficients.begin());
|
||||
model.film->configureDevelopment(development);
|
||||
}
|
||||
|
||||
model.film->setScanExposureMultiplier(1);
|
||||
if (!directScan) {
|
||||
// The stock wire preserves cached stock LUTs. Tuned development and
|
||||
// exposure can reach the whole emulsion curve, including its plateau.
|
||||
model.wire = values == stockFilmOptions ? measureDensityWire(*model.film) :
|
||||
DensityWire{{-0.2, -0.2, -0.2}, model.film->densityMax()};
|
||||
}
|
||||
model.filmOptions = values;
|
||||
}
|
||||
|
||||
PrintControls printControls(const PrintOptions& values) {
|
||||
return {values[0], values[1], values[2] != 0,
|
||||
values[3], values[4], values[5], values[6], values[7], values[8], values[9], values[10],
|
||||
{values[11], values[12], values[13]}, values[14]};
|
||||
}
|
||||
|
||||
OutputGamutAlgorithm outputAlgorithm(float value) {
|
||||
if (value < 0 || value > 5 || value != std::floor(value))
|
||||
throw std::invalid_argument("Invalid Spektrafilm output gamut algorithm");
|
||||
return static_cast<OutputGamutAlgorithm>(static_cast<int>(value));
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" JNIEXPORT jobjectArray JNICALL
|
||||
Java_com_hinnka_mycamera_raw_SpektrafilmNativeBridge_generate(
|
||||
JNIEnv* env, jobject, jstring sharedKeyValue, jstring filmKeyValue,
|
||||
jbyteArray sharedData, jbyteArray filmData, jstring paperNameValue,
|
||||
jbyteArray paperData, jboolean positive, jboolean buildFilm, jboolean buildPrint) {
|
||||
jbyteArray paperData, jboolean positive, jboolean directScan, jboolean buildFilm, jboolean buildPrint,
|
||||
jfloatArray filmOptions, jfloatArray printOptions, jint filmDyeOrder, jint paperDyeOrder,
|
||||
jfloatArray scanOptions, jboolean buildGraph, jboolean needsGlare, jboolean needsGrain) {
|
||||
std::lock_guard<std::mutex> lock(modelMutex);
|
||||
try {
|
||||
const auto started = std::chrono::steady_clock::now();
|
||||
const std::string sharedKey = string(env, sharedKeyValue);
|
||||
const std::string filmKey = string(env, filmKeyValue);
|
||||
const std::string paperName = string(env, paperNameValue);
|
||||
const auto filmValues = options<25>(env, filmOptions);
|
||||
if (model.sharedKey != sharedKey) {
|
||||
model = RuntimeModel{};
|
||||
model.shared = data(env, sharedData);
|
||||
@@ -70,42 +130,58 @@ Java_com_hinnka_mycamera_raw_SpektrafilmNativeBridge_generate(
|
||||
model.filmData.clear();
|
||||
model.filmKey.clear();
|
||||
model.filmData = data(env, filmData);
|
||||
model.film = std::make_unique<Filming>(model.shared, model.filmData);
|
||||
model.wire = measureDensityWire(*model.film);
|
||||
model.filmKey = filmKey;
|
||||
}
|
||||
if (!model.film || model.film->positive() != bool(positive) || (positive && buildPrint))
|
||||
configureFilm(filmValues, directScan);
|
||||
if (model.film->positive() != bool(positive) || (positive && !directScan) || (directScan && buildPrint))
|
||||
throw std::invalid_argument("Spectral model topology mismatch");
|
||||
static const OutputGamut gamut;
|
||||
std::vector<float> filmTable, printTable;
|
||||
const auto scanValues = options<11>(env, scanOptions);
|
||||
const ScanControls scanControls{scanValues[0] != 0, scanValues[1], scanValues[2] != 0, scanValues[3]};
|
||||
const OutputGamut gamut(outputAlgorithm(scanValues[4]), {scanValues[5], scanValues[6], scanValues[7]});
|
||||
std::unique_ptr<Printing> printing;
|
||||
std::unique_ptr<Scanner> scanner;
|
||||
if (directScan) {
|
||||
scanner = std::make_unique<Scanner>(model.shared, model.filmData, gamut, filmDyeOrder);
|
||||
const auto correction = positiveScanCorrection(*scanner, *model.film, model.filmData, scanControls);
|
||||
scanner->configureBlackWhite(correction);
|
||||
model.film->setScanExposureMultiplier(correction.exposure);
|
||||
} else if (buildPrint || buildGraph) {
|
||||
const DataSet paper = data(env, paperData);
|
||||
const auto controls = printControls(options<15>(env, printOptions));
|
||||
printing = std::make_unique<Printing>(model.shared, model.filmData, paper, paperName,
|
||||
model.film->midgrayDensity(), model.film->midgrayDensity(controls.compensationEv), controls, filmDyeOrder);
|
||||
scanner = std::make_unique<Scanner>(model.shared, paper, gamut, paperDyeOrder);
|
||||
const auto correction = printScanCorrection(*scanner, *printing, *model.film, paper, scanControls,
|
||||
{scanValues[8], scanValues[9], scanValues[10]});
|
||||
scanner->configureBlackWhite(correction);
|
||||
printing->setScanExposureCorrection(correction.exposure);
|
||||
}
|
||||
|
||||
std::array<std::vector<float>, 9> tables;
|
||||
if (buildFilm) {
|
||||
if (positive) {
|
||||
const Scanner scanner(model.shared, model.filmData, gamut);
|
||||
filmTable = generateFilmLut(*model.film, model.wire, &scanner, 65);
|
||||
} else {
|
||||
filmTable = generateFilmLut(*model.film, model.wire, nullptr, 65);
|
||||
}
|
||||
tables[0] = generateFilmLut(*model.film, model.wire, directScan ? scanner.get() : nullptr, 65, filmValues[0]);
|
||||
}
|
||||
if (buildPrint) {
|
||||
const DataSet paper = data(env, paperData);
|
||||
const Printing printing(model.shared, model.filmData, paper, paperName, model.film->midgrayDensity());
|
||||
const Scanner scanner(model.shared, paper, gamut);
|
||||
printTable = generatePrintLut(printing, scanner, model.wire, 65);
|
||||
tables[1] = generatePrintLut(*printing, *scanner, model.wire, 65);
|
||||
}
|
||||
if (buildGraph) {
|
||||
auto graph = buildSpectralGraph(*model.film, model.filmData, printing.get(), *scanner, needsGlare, needsGrain);
|
||||
std::move(graph.begin(), graph.end(), tables.begin() + 2);
|
||||
}
|
||||
jclass floatArrayClass = env->FindClass("[F");
|
||||
if (!floatArrayClass) throw std::runtime_error("Missing float array class");
|
||||
jobjectArray result = env->NewObjectArray(2, floatArrayClass, nullptr);
|
||||
const int tableCount = buildGraph ? 9 : 2;
|
||||
jobjectArray result = env->NewObjectArray(tableCount, floatArrayClass, nullptr);
|
||||
env->DeleteLocalRef(floatArrayClass);
|
||||
if (!result) throw std::runtime_error("Unable to allocate spectral result");
|
||||
jfloatArray filmOutput = output(env, filmTable);
|
||||
env->SetObjectArrayElement(result, 0, filmOutput);
|
||||
env->DeleteLocalRef(filmOutput);
|
||||
// Release native arrays before constructing the next Java result.
|
||||
std::vector<float>().swap(filmTable);
|
||||
jfloatArray printOutput = output(env, printTable);
|
||||
env->SetObjectArrayElement(result, 1, printOutput);
|
||||
env->DeleteLocalRef(printOutput);
|
||||
if (env->ExceptionCheck()) throw std::runtime_error("Unable to return spectral result");
|
||||
for (int i = 0; i < tableCount; ++i) {
|
||||
jfloatArray payload = output(env, tables[i]);
|
||||
env->SetObjectArrayElement(result, i, payload);
|
||||
env->DeleteLocalRef(payload);
|
||||
if (env->ExceptionCheck()) throw std::runtime_error("Unable to return spectral result");
|
||||
// Release each native array before constructing the next Java array.
|
||||
std::vector<float>().swap(tables[i]);
|
||||
}
|
||||
const auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
std::chrono::steady_clock::now() - started).count();
|
||||
__android_log_print(ANDROID_LOG_DEBUG, "SpektrafilmNative", "Generated on demand: film=%d print=%d size=65 elapsed=%lldms model=%s",
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
// Mallett and Yuksel (2019) sRGB basis at 380..780 nm in 5 nm steps.
|
||||
// Values from Colour 0.4.7, BSD 3-Clause (see LICENSE.colour-science).
|
||||
#pragma once
|
||||
|
||||
#include "spectral_data.h"
|
||||
|
||||
namespace spektrafilm {
|
||||
constexpr std::array<Vec3, 81> kMallettBasis{{
|
||||
{0.32745741382705496, 0.33186171308587409, 0.34068079154805259},
|
||||
{0.32375057827054088, 0.32968818775939884, 0.34656118662485247},
|
||||
{0.31343946125157696, 0.32786002162469746, 0.35870049314035107},
|
||||
{0.28887938275526504, 0.31917358023175579, 0.39194702658819536},
|
||||
{0.23920568115888621, 0.29432258369484215, 0.4664717305873326},
|
||||
{0.1897020368905348, 0.25869706476873616, 0.5516008955986017},
|
||||
{0.12174606795921804, 0.18889431925476508, 0.68935961094892773},
|
||||
{0.074578270669465999, 0.12538838199168881, 0.80003334687860739},
|
||||
{0.04443315863403368, 0.078687060310621643, 0.87687978093531527},
|
||||
{0.028928632128502923, 0.053143270865945391, 0.91792809744395432},
|
||||
{0.022316653484751165, 0.042288146031342053, 0.93539520066963233},
|
||||
{0.01691130729263177, 0.033318345502917082, 0.94977034711518282},
|
||||
{0.014181107117966704, 0.029755948185972408, 0.95606294480524134},
|
||||
{0.013053142677487284, 0.030331250536904743, 0.95661560689031577},
|
||||
{0.011986163627845008, 0.030988571897300716, 0.95702526493132678},
|
||||
{0.011288714712404804, 0.03168635518883809, 0.95702493053471194},
|
||||
{0.010906066465651698, 0.034669961502997448, 0.95442397273706503},
|
||||
{0.01040071348100419, 0.034551957443674994, 0.95504732902020451},
|
||||
{0.010637360254146499, 0.040684806194829642, 0.94867783309333298},
|
||||
{0.010907662533774086, 0.054460037369405565, 0.93463229984232876},
|
||||
{0.011032712448098796, 0.080905287420473662, 0.9080619998522701},
|
||||
{0.011310656591226801, 0.14634830285704414, 0.84234103946372529},
|
||||
{0.011154642056940301, 0.37967964329661669, 0.60916571536564623},
|
||||
{0.010148770406212197, 0.76674426865403356, 0.22310696095953297},
|
||||
{0.0089185821188384352, 0.87621474761336915, 0.11486667029133635},
|
||||
{0.0076855763384710545, 0.91849165561384172, 0.073822767895743588},
|
||||
{0.0067057082846952521, 0.94065556253443738, 0.05263872879105555},
|
||||
{0.0059958059876442493, 0.95373188453302005, 0.04027230901688874},
|
||||
{0.005537256642341881, 0.96164327984023734, 0.032819462650959121},
|
||||
{0.0051937842412066127, 0.96720001968507863, 0.027606195927045614},
|
||||
{0.0050253622652233348, 0.97098974639004576, 0.023984891127039387},
|
||||
{0.0051363627696750843, 0.97285230356355235, 0.022011333352792189},
|
||||
{0.0054332002605398293, 0.97311659407644469, 0.021450205255996595},
|
||||
{0.0058199859024353467, 0.97335106915414316, 0.020828944509568487},
|
||||
{0.0064005727746241246, 0.97335111554436826, 0.020248311388808723},
|
||||
{0.0074495286834087796, 0.97226107973172538, 0.020289391451206597},
|
||||
{0.0085836358193765797, 0.97335102174691701, 0.018065342335913018},
|
||||
{0.010395762465167397, 0.97314849518569391, 0.016455742234468513},
|
||||
{0.01356543353864921, 0.97106130630091336, 0.015373260134095498},
|
||||
{0.019384515839974213, 0.96637130595518261, 0.014244178484551688},
|
||||
{0.032084071202002372, 0.95494196750254978, 0.012973961554334683},
|
||||
{0.074356037845941136, 0.91357898955126249, 0.012064974134521811},
|
||||
{0.62439372417807526, 0.36434880390768665, 0.011257478160390093},
|
||||
{0.91831003276871925, 0.071507242540885474, 0.01018272467169418},
|
||||
{0.94925303017505236, 0.04123043447137506, 0.0095165353872374171},
|
||||
{0.95818783332924651, 0.032423874183668433, 0.0093882927286681756},
|
||||
{0.95818775133269674, 0.031924629798200349, 0.0098876190906702858},
|
||||
{0.95818762508778199, 0.031276033173096851, 0.010536342006458907},
|
||||
{0.95567906077174436, 0.0326303704290574, 0.011690568837444798},
|
||||
{0.95800615489342877, 0.029530872149073878, 0.012462972887103695},
|
||||
{0.95410157345656355, 0.031561761170246415, 0.014336665177420315},
|
||||
{0.94760760623723805, 0.035674218270820374, 0.016718175327544296},
|
||||
{0.93868132844754826, 0.041403005395567259, 0.019915666075002499},
|
||||
{0.92446668275143273, 0.050604260448956113, 0.024929056163280981},
|
||||
{0.90460602533305623, 0.063434300381700351, 0.031959673586040245},
|
||||
{0.88041219892793265, 0.07891824529392294, 0.040669554095248382},
|
||||
{0.84778787315169901, 0.099542742665374689, 0.052669382421939547},
|
||||
{0.8057791266230182, 0.12559576009328699, 0.068625110514194759},
|
||||
{0.75253185387142119, 0.15759091044167994, 0.089877232300013488},
|
||||
{0.68643939684457922, 0.19539823904421003, 0.11816235892643404},
|
||||
{0.61869457086060986, 0.23147447477217839, 0.14983094744213307},
|
||||
{0.54026444395911066, 0.26885213609526182, 0.19088340934183395},
|
||||
{0.47296441629383768, 0.2960291642179278, 0.2310064030252168},
|
||||
{0.43270159670404923, 0.30975499444194515, 0.25754338542220212},
|
||||
{0.40535804552839211, 0.31781588338382211, 0.27682603872153577},
|
||||
{0.38549183497490269, 0.32299034738989785, 0.291517772810795},
|
||||
{0.37098358455106073, 0.32635384793800987, 0.30266250608323281},
|
||||
{0.35760870152308138, 0.32914390227897955, 0.31324730130288597},
|
||||
{0.3487128001083929, 0.33080872680368223, 0.32047832512463287},
|
||||
{0.34488011934469143, 0.3314826899222435, 0.32363699470796087},
|
||||
{0.34191787732329126, 0.33198455035238889, 0.32609730884690047},
|
||||
{0.33953109298712919, 0.33234117252254514, 0.32812736934018433},
|
||||
{0.33716950377436733, 0.33291200941553917, 0.32991797595888855},
|
||||
{0.33617201852771689, 0.33291927969521379, 0.33090790121664942},
|
||||
{0.33516744343336291, 0.33302767257885618, 0.33180363309599514},
|
||||
{0.33442162530646313, 0.3331797046732603, 0.33239662725536129},
|
||||
{0.33400876037640209, 0.33324703097454911, 0.33274078072682411},
|
||||
{0.33391579279008204, 0.3332593492106008, 0.33282085708148867},
|
||||
{0.3338184549463668, 0.33327505027938309, 0.33290173128344441},
|
||||
{0.33367277492845626, 0.33329432844873186, 0.33302596748863178},
|
||||
{0.33356951340559104, 0.33330942495777494, 0.33311108308149701}
|
||||
}};
|
||||
}
|
||||
@@ -1,8 +1,11 @@
|
||||
// Pointwise printing/scanning port of Spektrafilm 0.3.4 (3bb2c2d).
|
||||
// See LICENSE.spektrafilm and docs/spektrafilm-luts.md for provenance.
|
||||
#include "spectral_printing.h"
|
||||
#include "spectral_filming.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
#include <numeric>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace spektrafilm {
|
||||
@@ -12,12 +15,142 @@ const std::vector<double>& sized(const DataSet& d, const std::string& name, size
|
||||
if (v.size() != count) throw std::invalid_argument("Invalid spectral tensor: " + name);
|
||||
return v;
|
||||
}
|
||||
|
||||
std::vector<double> orderedDyes(const DataSet& medium, size_t wavelengthCount, int order) {
|
||||
constexpr int permutations[][3] = {
|
||||
{0, 1, 2}, {0, 2, 1}, {1, 0, 2}, {1, 2, 0}, {2, 0, 1}, {2, 1, 0},
|
||||
};
|
||||
if (order < 0 || order >= 6) throw std::invalid_argument("Invalid spectral dye order");
|
||||
auto dyes = sized(medium, "spectral.channelDensity", wavelengthCount * 3);
|
||||
if (order == 0) return dyes;
|
||||
for (size_t w = 0; w < wavelengthCount; ++w) {
|
||||
const size_t i = w * 3;
|
||||
const Vec3 stock{dyes[i], dyes[i + 1], dyes[i + 2]};
|
||||
for (int c = 0; c < 3; ++c) dyes[i + c] = stock[permutations[order][c]];
|
||||
}
|
||||
return dyes;
|
||||
}
|
||||
double spectralDensity(const std::vector<double>& dyes, const std::vector<double>& base,
|
||||
size_t wavelength, const Vec3& cmy) {
|
||||
double d = base[wavelength];
|
||||
for (int c = 0; c < 3; ++c) d += cmy[c] * dyes[wavelength * 3 + c];
|
||||
return d;
|
||||
}
|
||||
|
||||
Vec3 filterTransmittance(const std::vector<double>& neutral, double magenta, double yellow) {
|
||||
return {std::pow(10.0, -neutral[0] / 100.0),
|
||||
std::pow(10.0, -(neutral[1] + magenta) / 100.0),
|
||||
std::pow(10.0, -(neutral[2] + yellow) / 100.0)};
|
||||
}
|
||||
|
||||
double filteredLight(double source, const std::vector<double>& filters, size_t wavelength,
|
||||
const Vec3& transmittance) {
|
||||
for (int c = 0; c < 3; ++c)
|
||||
source *= 1.0 - (1.0 - filters[wavelength * 3 + c]) * (1.0 - transmittance[c]);
|
||||
return source;
|
||||
}
|
||||
|
||||
double geometricExposure(const Vec3& raw) {
|
||||
double logMean = 0;
|
||||
for (double value : raw) logMean += std::log(std::max(value, 1e-10)) / 3.0;
|
||||
return std::exp(-logMean);
|
||||
}
|
||||
|
||||
double layerCdf(double z, double exhaustion) {
|
||||
const double normal = 0.5 * std::erfc(-z / std::sqrt(2.0));
|
||||
if (exhaustion == 0) return normal;
|
||||
const double location = -std::log(std::log(2.0));
|
||||
const double width = 0.5 * std::log(2.0) * std::sqrt(2.0 * std::acos(-1.0));
|
||||
const double gumbel = std::exp(-std::exp(-(z / width + location)));
|
||||
return normal + exhaustion * (gumbel - normal);
|
||||
}
|
||||
|
||||
double printDensity(double x, const double* centers, const double* sigmas,
|
||||
const double* amplitudes, size_t layers, double exhaustion) {
|
||||
double result = 0;
|
||||
for (size_t layer = 0; layer < layers; ++layer)
|
||||
result += amplitudes[layer] * layerCdf((x - centers[layer]) / sigmas[layer], exhaustion);
|
||||
return result;
|
||||
}
|
||||
|
||||
double exhaustionOffset(const double* centers, const double* sigmas, const double* amplitudes,
|
||||
size_t layers, double exhaustion) {
|
||||
if (exhaustion == 0) return 0;
|
||||
const double target = printDensity(0, centers, sigmas, amplitudes, layers, 0);
|
||||
auto residual = [&](double offset) {
|
||||
return printDensity(-offset, centers, sigmas, amplitudes, layers, exhaustion) - target;
|
||||
};
|
||||
if (std::abs(residual(0)) <= 1e-12) return 0;
|
||||
for (double bound = 0.25; bound <= 512; bound *= 2) {
|
||||
double low = -bound, high = bound;
|
||||
double lowValue = residual(low), highValue = residual(high);
|
||||
if (lowValue == 0) return low;
|
||||
if (highValue == 0) return high;
|
||||
if ((lowValue > 0) == (highValue > 0)) continue;
|
||||
while (high - low > 1e-10) {
|
||||
const double mid = (low + high) * 0.5;
|
||||
if ((residual(mid) > 0) == (lowValue > 0)) low = mid;
|
||||
else high = mid;
|
||||
}
|
||||
return (low + high) * 0.5;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
double interpolate(double x, const std::vector<double>& axis, const std::vector<double>& values,
|
||||
size_t channel, size_t stride) {
|
||||
if (x <= axis.front()) return values[channel];
|
||||
if (x >= axis.back()) return values[(axis.size() - 1) * stride + channel];
|
||||
const size_t upper = std::upper_bound(axis.begin(), axis.end(), x) - axis.begin();
|
||||
const size_t lower = upper - 1;
|
||||
const double width = axis[upper] - axis[lower];
|
||||
const double t = width != 0 ? (x - axis[lower]) / width : 0;
|
||||
return values[lower * stride + channel] + t * (values[upper * stride + channel] - values[lower * stride + channel]);
|
||||
}
|
||||
|
||||
double srgbDecode(double encoded) {
|
||||
return encoded <= 0.04045 ? encoded / 12.92 : std::pow((encoded + 0.055) / 1.055, 2.4);
|
||||
}
|
||||
|
||||
ScanCorrection scanCorrection(double black, double white, const ScanControls& controls) {
|
||||
const double targetBlack = controls.blackCorrection ? srgbDecode(controls.blackLevel) : black;
|
||||
const double targetWhite = controls.whiteCorrection ? srgbDecode(controls.whiteLevel) : white;
|
||||
const double slope = (targetWhite - targetBlack) / (white - black + 1e-10);
|
||||
return {true, slope, targetBlack - slope * black, 1};
|
||||
}
|
||||
|
||||
double midgrayExposure(const ScanCorrection& correction, const DataSet& medium,
|
||||
const std::vector<double>& exposure, const std::vector<double>& curves, bool positive) {
|
||||
// A constant output transform has no inverse and no exposure dependence.
|
||||
if (correction.slope == 0) return 1;
|
||||
constexpr double kMidgray = 0.184;
|
||||
const double target = (kMidgray - correction.offset) / correction.slope;
|
||||
// Zero light is the infinite-density endpoint of the characteristic curve.
|
||||
const double targetDensity = target > 0 ? -std::log10(target) : std::numeric_limits<double>::infinity();
|
||||
const auto& base = medium.at("spectral.baseDensity");
|
||||
const double meanBase = std::accumulate(base.begin(), base.end(), 0.0) / base.size();
|
||||
const double sign = positive ? -1 : 1;
|
||||
std::vector<double> meanDensity(exposure.size());
|
||||
for (size_t i = 0; i < exposure.size(); ++i) {
|
||||
meanDensity[i] = sign * (curves[i * 3] + curves[i * 3 + 1] + curves[i * 3 + 2]) / 3;
|
||||
}
|
||||
// Characteristic curves can taper back near saturation. Use the first
|
||||
// exposure that attains a target instead of binary-searching the density
|
||||
// samples as though they were a monotonic coordinate axis.
|
||||
const auto findExposure = [&](double density) {
|
||||
const auto high = std::find_if(meanDensity.begin(), meanDensity.end(), [density](double value) {
|
||||
return value >= density;
|
||||
});
|
||||
if (high == meanDensity.begin()) return exposure.front();
|
||||
if (high == meanDensity.end()) return exposure.back();
|
||||
const size_t i = high - meanDensity.begin();
|
||||
const double t = (density - meanDensity[i - 1]) / (meanDensity[i] - meanDensity[i - 1]);
|
||||
return exposure[i - 1] + t * (exposure[i] - exposure[i - 1]);
|
||||
};
|
||||
const double reference = findExposure(sign * (-std::log10(kMidgray) - meanBase));
|
||||
const double adjusted = findExposure(sign * (targetDensity - meanBase));
|
||||
return std::pow(10.0, adjusted - reference);
|
||||
}
|
||||
}
|
||||
|
||||
double proPhotoDecode(double v) {
|
||||
@@ -28,21 +161,27 @@ double proPhotoEncode(double v) {
|
||||
return v < 0.001953125 ? v * 16.0 : std::pow(v, 1.0 / 1.8);
|
||||
}
|
||||
|
||||
Scanner::Scanner(const DataSet& shared, const DataSet& medium, const OutputGamut& gamut)
|
||||
Scanner::Scanner(const DataSet& shared, const DataSet& medium, const OutputGamut& gamut, int dyeOrder)
|
||||
: base_(medium.at("spectral.baseDensity")), gamut_(gamut) {
|
||||
const size_t n = base_.size();
|
||||
if (n == 0 || n > 1024) throw std::invalid_argument("Invalid scan wavelengths");
|
||||
dyes_ = sized(medium, "spectral.channelDensity", n * 3);
|
||||
dyes_ = orderedDyes(medium, n, dyeOrder);
|
||||
valid_ = sized(medium, "spectral.valid", n);
|
||||
illuminant_ = sized(medium, "scan.illuminant", n);
|
||||
observer_ = sized(shared, "scan.observer", n * 3);
|
||||
matrix_ = sized(medium, "scan.xyzToProPhoto", 9);
|
||||
for (size_t w = 0; w < n; ++w) normalization_ += illuminant_[w] * observer_[w * 3 + 1];
|
||||
Vec3 whiteXyz{};
|
||||
for (size_t w = 0; w < n; ++w) {
|
||||
normalization_ += illuminant_[w] * observer_[w * 3 + 1];
|
||||
for (int c = 0; c < 3; ++c) whiteXyz[c] += illuminant_[w] * observer_[w * 3 + c];
|
||||
}
|
||||
if (!(normalization_ > 0)) throw std::invalid_argument("Invalid scanner illuminant");
|
||||
for (double& component : whiteXyz) component /= normalization_;
|
||||
whiteRgb_ = toRgb(whiteXyz);
|
||||
}
|
||||
|
||||
Vec3 Scanner::scan(const Vec3& density) const {
|
||||
Vec3 xyz{}, rgb{};
|
||||
Vec3 Scanner::scanXyz(const Vec3& density) const {
|
||||
Vec3 xyz{};
|
||||
for (size_t w = 0; w < base_.size(); ++w) {
|
||||
if (valid_[w] == 0) continue;
|
||||
const double light = std::pow(10.0, -spectralDensity(dyes_, base_, w, density)) * illuminant_[w];
|
||||
@@ -52,9 +191,32 @@ Vec3 Scanner::scan(const Vec3& density) const {
|
||||
// Match the upstream cmy_to_log_xyz -> pow(10, log_xyz) tap contract.
|
||||
v = std::pow(10.0, std::log10(std::max(v / normalization_, 0.0) + 1e-10));
|
||||
}
|
||||
return xyz;
|
||||
}
|
||||
|
||||
Vec3 Scanner::toRgb(const Vec3& xyz) const {
|
||||
Vec3 rgb{};
|
||||
for (int r = 0; r < 3; ++r)
|
||||
for (int c = 0; c < 3; ++c) rgb[r] += matrix_[r * 3 + c] * xyz[c];
|
||||
rgb = gamut_.compress(rgb);
|
||||
return rgb;
|
||||
}
|
||||
|
||||
double Scanner::luminance(const Vec3& density) const {
|
||||
return scanXyz(density)[1];
|
||||
}
|
||||
|
||||
Vec3 Scanner::linearRgb(const Vec3& density) const {
|
||||
Vec3 xyz = scanXyz(density);
|
||||
if (correction_.active) {
|
||||
const double y = xyz[1];
|
||||
const double corrected = std::clamp(correction_.slope * y + correction_.offset, 0.0, 1.0);
|
||||
for (double& value : xyz) value *= corrected / (y + 1e-10);
|
||||
}
|
||||
return toRgb(xyz);
|
||||
}
|
||||
|
||||
Vec3 Scanner::scan(const Vec3& density) const {
|
||||
Vec3 rgb = gamutRgb(linearRgb(density));
|
||||
for (double& v : rgb) {
|
||||
if (!std::isfinite(v)) throw std::runtime_error("Non-finite spectral scanner result");
|
||||
v = proPhotoEncode(v);
|
||||
@@ -63,96 +225,126 @@ Vec3 Scanner::scan(const Vec3& density) const {
|
||||
}
|
||||
|
||||
Printing::Printing(const DataSet& shared, const DataSet& film, const DataSet& paper,
|
||||
const std::string& paperName, const Vec3& midgrayDensity)
|
||||
const std::string& paperName, const Vec3& midgrayDensity,
|
||||
const Vec3& compensatedMidgray, const PrintControls& controls, int dyeOrder)
|
||||
: filmBase_(film.at("spectral.baseDensity")), axis_(paper.at("print.logExposure")) {
|
||||
const size_t n = filmBase_.size();
|
||||
if (n == 0 || n > 1024 || axis_.size() < 2 || axis_.size() > 65536)
|
||||
throw std::invalid_argument("Invalid print model dimensions");
|
||||
filmDyes_ = sized(film, "spectral.channelDensity", n * 3);
|
||||
filmDyes_ = orderedDyes(film, n, dyeOrder);
|
||||
valid_ = sized(film, "spectral.valid", n);
|
||||
const auto& filters = sized(shared, "print.dichroicFilters", n * 3);
|
||||
const auto& light = sized(shared, "print.lightSource", n);
|
||||
const auto& sensitivity = sized(paper, "print.sensitivity", n * 3);
|
||||
const auto& cc = sized(film, "print.neutral." + paperName, 3);
|
||||
exposure_ = sized(paper, "print.exposure", 1)[0];
|
||||
const bool normalize = sized(paper, "print.normalizeExposure", 1)[0] != 0;
|
||||
if (!(exposure_ > 0)) throw std::invalid_argument("Invalid print exposure");
|
||||
Vec3 transmittance{};
|
||||
for (int c = 0; c < 3; ++c) transmittance[c] = std::pow(10.0, -cc[c] / 100.0);
|
||||
exposure_ = controls.exposure;
|
||||
const auto transmittance = filterTransmittance(cc, controls.magentaShift, controls.yellowShift);
|
||||
const auto preflashTransmittance = filterTransmittance(
|
||||
cc, controls.preflashMagentaShift, controls.preflashYellowShift);
|
||||
weights_.resize(n * 3);
|
||||
Vec3 rawMidgray{};
|
||||
Vec3 rawMidgray{}, rawCompensated{};
|
||||
for (size_t w = 0; w < n; ++w) {
|
||||
if (valid_[w] == 0) continue;
|
||||
double source = light[w];
|
||||
for (int c = 0; c < 3; ++c)
|
||||
source *= 1.0 - (1.0 - filters[w * 3 + c]) * (1.0 - transmittance[c]);
|
||||
const double source = filteredLight(light[w], filters, w, transmittance);
|
||||
const double transmission = std::pow(10.0, -spectralDensity(filmDyes_, filmBase_, w, midgrayDensity));
|
||||
const double compensated = controls.compensationEv == 0 ? transmission :
|
||||
std::pow(10.0, -spectralDensity(filmDyes_, filmBase_, w, compensatedMidgray));
|
||||
const double flash = controls.preflashExposure == 0 ? 0 : controls.preflashExposure *
|
||||
filteredLight(light[w], filters, w, preflashTransmittance) * std::pow(10.0, -filmBase_[w]);
|
||||
for (int c = 0; c < 3; ++c) {
|
||||
weights_[w * 3 + c] = source * sensitivity[w * 3 + c];
|
||||
rawMidgray[c] += transmission * weights_[w * 3 + c];
|
||||
rawCompensated[c] += compensated * weights_[w * 3 + c];
|
||||
preflash_[c] += flash * sensitivity[w * 3 + c];
|
||||
}
|
||||
}
|
||||
// Default camera EV=0: compensated and uncompensated reference exposures
|
||||
// coincide, preserving all normalize/compensate branches of this preset.
|
||||
if (normalize) {
|
||||
double logMean = 0;
|
||||
for (double v : rawMidgray) logMean += std::log(std::max(v, 1e-10)) / 3.0;
|
||||
normalization_ = std::exp(-logMean);
|
||||
}
|
||||
const auto& centers = paper.at("print.centers");
|
||||
if (controls.normalizeExposure) normalization_ = geometricExposure(rawCompensated);
|
||||
else if (controls.compensationEv != 0)
|
||||
normalization_ = geometricExposure(rawCompensated) / geometricExposure(rawMidgray);
|
||||
|
||||
auto centers = paper.at("print.centers");
|
||||
if (centers.empty() || centers.size() % 3 != 0 || centers.size() > 96)
|
||||
throw std::invalid_argument("Invalid print density layers");
|
||||
const size_t layers = centers.size() / 3;
|
||||
const auto& sigmas = sized(paper, "print.sigmas", centers.size());
|
||||
auto sigmas = sized(paper, "print.sigmas", centers.size());
|
||||
const auto& amplitudes = sized(paper, "print.amplitudes", centers.size());
|
||||
if (!std::is_sorted(axis_.begin(), axis_.end())) throw std::invalid_argument("Unsorted print curve");
|
||||
curves_.resize(axis_.size() * 3);
|
||||
// LUT mode disables creative s023 morphing: evaluate the fitted normal
|
||||
// CDF layers on the stock exposure axis, then interpolate as upstream.
|
||||
if (std::any_of(sigmas.begin(), sigmas.end(), [](double v) { return !(v > 0); }))
|
||||
throw std::invalid_argument("Invalid print layer sigma");
|
||||
for (size_t i = 0; i < axis_.size(); ++i) {
|
||||
for (int c = 0; c < 3; ++c) {
|
||||
double density = 0;
|
||||
for (int c = 0; c < 3; ++c) {
|
||||
const size_t start = c * layers;
|
||||
const double gamma = controls.gamma * controls.channelGamma[c];
|
||||
if (gamma != 1 || controls.gammaFast != 1 || controls.gammaSlow != 1) {
|
||||
const auto first = centers.begin() + start;
|
||||
const size_t fast = std::min_element(first, first + layers) - first;
|
||||
for (size_t layer = 0; layer < layers; ++layer) {
|
||||
const size_t k = c * layers + layer;
|
||||
const double sigma = sigmas[k];
|
||||
const double z = (axis_[i] - centers[k]) / sigma;
|
||||
density += amplitudes[k] * 0.5 * std::erfc(-z / std::sqrt(2.0));
|
||||
const size_t k = start + layer;
|
||||
const double effectiveGamma = gamma * (layer == fast ? controls.gammaFast : controls.gammaSlow);
|
||||
centers[k] /= effectiveGamma;
|
||||
sigmas[k] = std::max(0.05, sigmas[k] / effectiveGamma);
|
||||
}
|
||||
curves_[i * 3 + c] = density;
|
||||
}
|
||||
const double offset = exhaustionOffset(
|
||||
centers.data() + start, sigmas.data() + start, amplitudes.data() + start,
|
||||
layers, controls.developerExhaustion);
|
||||
for (size_t i = 0; i < axis_.size(); ++i)
|
||||
curves_[i * 3 + c] = printDensity(axis_[i] - offset, centers.data() + start,
|
||||
sigmas.data() + start, amplitudes.data() + start, layers, controls.developerExhaustion);
|
||||
}
|
||||
}
|
||||
|
||||
Vec3 Printing::expose(const Vec3& filmDensity) const {
|
||||
Vec3 Printing::modelExposure(const Vec3& filmDensity) const {
|
||||
Vec3 raw{};
|
||||
for (size_t w = 0; w < filmBase_.size(); ++w) {
|
||||
if (valid_[w] == 0) continue;
|
||||
const double transmission = std::pow(10.0, -spectralDensity(filmDyes_, filmBase_, w, filmDensity));
|
||||
for (int c = 0; c < 3; ++c) raw[c] += transmission * weights_[w * 3 + c];
|
||||
}
|
||||
for (double& v : raw) {
|
||||
const double logRaw = std::log10(std::max(v * normalization_, 0.0) + 1e-10);
|
||||
v = std::log10(std::max(std::pow(10.0, logRaw) * exposure_, 0.0) + 1e-10);
|
||||
}
|
||||
for (int c = 0; c < 3; ++c)
|
||||
raw[c] = std::log10(std::max(raw[c] * normalization_ + preflash_[c], 0.0) + 1e-10);
|
||||
return raw;
|
||||
}
|
||||
|
||||
Vec3 Printing::expose(const Vec3& filmDensity) const {
|
||||
Vec3 raw = modelExposure(filmDensity);
|
||||
for (double& value : raw)
|
||||
value = std::log10(std::max(std::pow(10.0, value) * exposure_ * scanExposureCorrection_, 0.0) + 1e-10);
|
||||
return raw;
|
||||
}
|
||||
|
||||
Vec3 Printing::develop(const Vec3& logExposure) const {
|
||||
Vec3 result{};
|
||||
for (int c = 0; c < 3; ++c) {
|
||||
const double x = logExposure[c];
|
||||
if (x <= axis_.front()) result[c] = curves_[c];
|
||||
else if (x >= axis_.back()) result[c] = curves_[(axis_.size() - 1) * 3 + c];
|
||||
else {
|
||||
const size_t upper = std::upper_bound(axis_.begin(), axis_.end(), x) - axis_.begin();
|
||||
const size_t lower = upper - 1;
|
||||
const double width = axis_[upper] - axis_[lower];
|
||||
const double t = width != 0 ? (x - axis_[lower]) / width : 0.0;
|
||||
result[c] = curves_[lower * 3 + c] + t * (curves_[upper * 3 + c] - curves_[lower * 3 + c]);
|
||||
}
|
||||
result[c] = interpolate(logExposure[c], axis_, curves_, c, 3);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
ScanCorrection positiveScanCorrection(const Scanner& scanner, const Filming& filming,
|
||||
const DataSet& film, const ScanControls& controls) {
|
||||
if ((!controls.blackCorrection && !controls.whiteCorrection) || !filming.positive()) return {};
|
||||
ScanCorrection correction = scanCorrection(scanner.luminance(filming.curveMax()),
|
||||
scanner.luminance({0, 0, 0}), controls);
|
||||
correction.exposure = midgrayExposure(correction, film, filming.logExposure(), filming.originalCurves(), true);
|
||||
return correction;
|
||||
}
|
||||
|
||||
ScanCorrection printScanCorrection(const Scanner& scanner, const Printing& printing,
|
||||
const Filming& filming, const DataSet& paper, const ScanControls& controls,
|
||||
const Vec3& grainMinimum) {
|
||||
if (!controls.blackCorrection && !controls.whiteCorrection) return {};
|
||||
const auto& axis = paper.at("print.logExposure");
|
||||
const auto& curves = sized(paper, "print.stockCurves", axis.size() * 3);
|
||||
const Vec3 blackRaw = printing.modelExposure({-grainMinimum[0], -grainMinimum[1], -grainMinimum[2]});
|
||||
const Vec3 whiteRaw = printing.modelExposure(filming.curveMax());
|
||||
Vec3 blackDensity{}, whiteDensity{};
|
||||
for (int c = 0; c < 3; ++c) {
|
||||
blackDensity[c] = interpolate(blackRaw[c], axis, curves, c, 3);
|
||||
whiteDensity[c] = interpolate(whiteRaw[c], axis, curves, c, 3);
|
||||
}
|
||||
ScanCorrection correction = scanCorrection(scanner.luminance(blackDensity), scanner.luminance(whiteDensity), controls);
|
||||
correction.exposure = midgrayExposure(correction, paper, axis, curves, false);
|
||||
return correction;
|
||||
}
|
||||
}
|
||||
@@ -5,28 +5,73 @@
|
||||
|
||||
namespace spektrafilm {
|
||||
|
||||
// Pointwise LUT-mode scanning. The medium can be a print or a positive film.
|
||||
struct ScanControls {
|
||||
bool whiteCorrection = false;
|
||||
double whiteLevel = 0.98;
|
||||
bool blackCorrection = false;
|
||||
double blackLevel = 0.01;
|
||||
};
|
||||
|
||||
struct ScanCorrection {
|
||||
bool active = false;
|
||||
double slope = 1, offset = 0;
|
||||
double exposure = 1;
|
||||
};
|
||||
|
||||
// Pointwise scanning from film or print dye densities.
|
||||
class Scanner {
|
||||
public:
|
||||
Scanner(const DataSet& shared, const DataSet& medium, const OutputGamut& gamut);
|
||||
Scanner(const DataSet& shared, const DataSet& medium, const OutputGamut& gamut, int dyeOrder = 0);
|
||||
void configureBlackWhite(const ScanCorrection& correction) { correction_ = correction; }
|
||||
double luminance(const Vec3& density) const;
|
||||
Vec3 linearRgb(const Vec3& density) const;
|
||||
const Vec3& whiteRgb() const { return whiteRgb_; }
|
||||
Vec3 gamutRgb(const Vec3& linearProPhoto) const { return gamut_.compress(linearProPhoto); }
|
||||
bool unboundedGamut() const { return gamut_.unbounded(); }
|
||||
Vec3 scan(const Vec3& density) const;
|
||||
private:
|
||||
Vec3 scanXyz(const Vec3& density) const;
|
||||
Vec3 toRgb(const Vec3& xyz) const;
|
||||
std::vector<double> dyes_, base_, valid_, illuminant_, observer_, matrix_;
|
||||
double normalization_ = 0;
|
||||
const OutputGamut& gamut_;
|
||||
Vec3 whiteRgb_{};
|
||||
ScanCorrection correction_{};
|
||||
};
|
||||
|
||||
struct PrintControls {
|
||||
double exposure = 1;
|
||||
double compensationEv = 0;
|
||||
bool normalizeExposure = true;
|
||||
double magentaShift = 0, yellowShift = 0;
|
||||
double preflashExposure = 0, preflashMagentaShift = 0, preflashYellowShift = 0;
|
||||
double gamma = 1, gammaFast = 1, gammaSlow = 1;
|
||||
Vec3 channelGamma{1, 1, 1};
|
||||
double developerExhaustion = 0;
|
||||
};
|
||||
|
||||
class Printing {
|
||||
public:
|
||||
Printing(const DataSet& shared, const DataSet& film, const DataSet& paper,
|
||||
const std::string& paperName, const Vec3& midgrayDensity);
|
||||
const std::string& paperName, const Vec3& midgrayDensity,
|
||||
const Vec3& compensatedMidgray, const PrintControls& controls, int dyeOrder = 0);
|
||||
Vec3 expose(const Vec3& filmDensity) const;
|
||||
Vec3 modelExposure(const Vec3& filmDensity) const;
|
||||
void setScanExposureCorrection(double correction) { scanExposureCorrection_ = correction; }
|
||||
Vec3 develop(const Vec3& logExposure) const;
|
||||
private:
|
||||
std::vector<double> filmDyes_, filmBase_, valid_, weights_, axis_, curves_;
|
||||
double normalization_ = 1, exposure_ = 1;
|
||||
Vec3 preflash_{};
|
||||
double normalization_ = 1, exposure_ = 1, scanExposureCorrection_ = 1;
|
||||
};
|
||||
|
||||
class Filming;
|
||||
ScanCorrection positiveScanCorrection(const Scanner& scanner, const Filming& filming,
|
||||
const DataSet& film, const ScanControls& controls);
|
||||
ScanCorrection printScanCorrection(const Scanner& scanner, const Printing& printing,
|
||||
const Filming& filming, const DataSet& paper, const ScanControls& controls,
|
||||
const Vec3& grainMinimum = {0.03, 0.03, 0.03});
|
||||
|
||||
double proPhotoDecode(double value);
|
||||
double proPhotoEncode(double value);
|
||||
|
||||
|
||||
@@ -612,7 +612,7 @@ class UserPreferences internal constructor(
|
||||
}) { p, v -> p[K.HIDDEN_FOCAL_LENGTHS] = v.joinToString(",") }
|
||||
var rawSpectralFilmTuningsByStock: Map<String, SpectralFilmTuning> by stored({ p ->
|
||||
parseSpectralFilmTunings(p[K.RAW_SPECTRAL_FILM_TUNINGS_BY_STOCK_KEY])
|
||||
}) { p, v -> p[K.RAW_SPECTRAL_FILM_TUNINGS_BY_STOCK_KEY] = serializeSpectralFilmTunings(v.mapValues { it.value.normalized() }) }
|
||||
}) { p, v -> p[K.RAW_SPECTRAL_FILM_TUNINGS_BY_STOCK_KEY] = serializeSpectralFilmTunings(v) }
|
||||
|
||||
var customCaptureSettings by json(
|
||||
"custom_capture_settings_v1",
|
||||
|
||||
@@ -118,32 +118,23 @@ internal fun serializeMapFloat(map: Map<String, Float>): String {
|
||||
|
||||
internal fun parseSpectralFilmTunings(value: String?): Map<String, SpectralFilmTuning> {
|
||||
if (value.isNullOrEmpty()) return emptyMap()
|
||||
return value.split(",")
|
||||
.mapNotNull { entry ->
|
||||
val parts = entry.split(":")
|
||||
if (parts.size == 4) {
|
||||
val c = parts[1].toFloatOrNull()
|
||||
val m = parts[2].toFloatOrNull()
|
||||
val y = parts[3].toFloatOrNull()
|
||||
if (c != null && m != null && y != null) {
|
||||
parts[0] to SpectralFilmTuning(c, m, y).normalized()
|
||||
} else {
|
||||
null
|
||||
}
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val stocks = runCatching { JSONObject(value) }.getOrNull() ?: return emptyMap()
|
||||
return buildMap {
|
||||
for (stock in stocks.keys()) {
|
||||
val parameters = stocks.optJSONObject(stock)?.optString("parameters")?.takeIf { it.isNotEmpty() }
|
||||
val tuning = SpectralFilmTuning.decodeParameters(parameters)
|
||||
if (tuning != SpectralFilmTuning.DEFAULT) put(stock, tuning)
|
||||
}
|
||||
.toMap()
|
||||
}
|
||||
|
||||
internal fun serializeSpectralFilmTunings(map: Map<String, SpectralFilmTuning>): String {
|
||||
return map.entries.joinToString(",") { (stock, tuning) ->
|
||||
val t = tuning.normalized()
|
||||
"$stock:${t.cDensityGain}:${t.mDensityGain}:${t.yDensityGain}"
|
||||
}
|
||||
}
|
||||
|
||||
internal fun serializeSpectralFilmTunings(map: Map<String, SpectralFilmTuning>): String = JSONObject().apply {
|
||||
map.forEach { (stock, tuning) ->
|
||||
val parameters = tuning.encodeParameters() ?: return@forEach
|
||||
put(stock, JSONObject().put("parameters", parameters))
|
||||
}
|
||||
}.toString()
|
||||
|
||||
internal fun parseLensIds(value: String?): List<String> {
|
||||
if (value.isNullOrBlank()) return emptyList()
|
||||
return value.split(",")
|
||||
|
||||
@@ -334,9 +334,7 @@ object GalleryManager {
|
||||
manualHdrEffectEnabled = preferences?.ultraHdrGainMapEnabled ?: false,
|
||||
spectralFilmStock = spectralFilmStock,
|
||||
spectralFilmPrint = preferences?.rawSpectralFilmPrint ?: "kodak_portra_endura",
|
||||
spectralFilmCDensityGain = spectralFilmTuning.cDensityGain,
|
||||
spectralFilmMDensityGain = spectralFilmTuning.mDensityGain,
|
||||
spectralFilmYDensityGain = spectralFilmTuning.yDensityGain,
|
||||
spectralFilmParameters = spectralFilmTuning.encodeParameters(),
|
||||
fotufilmDocument = FotufilmDocumentStorage.encode(fotufilmDocument),
|
||||
)
|
||||
|
||||
@@ -2479,11 +2477,7 @@ object GalleryManager {
|
||||
rawPhysicalOutputSize = RawDigitalZoomResampling.readPhysicalSize(updatedMetadata.customProperties),
|
||||
spectralFilmStock = updatedMetadata.spectralFilmStock,
|
||||
spectralFilmPrint = updatedMetadata.spectralFilmPrint,
|
||||
spectralFilmTuning = SpectralFilmTuning(
|
||||
cDensityGain = updatedMetadata.spectralFilmCDensityGain,
|
||||
mDensityGain = updatedMetadata.spectralFilmMDensityGain,
|
||||
yDensityGain = updatedMetadata.spectralFilmYDensityGain,
|
||||
),
|
||||
spectralFilmTuning = updatedMetadata.decodeSpectralFilmTuning(),
|
||||
fotufilmDocument = FotufilmDocumentStorage.decode(updatedMetadata.fotufilmDocument, "photo metadata"),
|
||||
onMetadata = { raw -> updatedMetadata = updatedMetadata.merge(raw) },
|
||||
)
|
||||
@@ -2574,11 +2568,7 @@ object GalleryManager {
|
||||
rawPhysicalOutputSize = RawDigitalZoomResampling.readPhysicalSize(updatedMetadata.customProperties),
|
||||
spectralFilmStock = updatedMetadata.spectralFilmStock,
|
||||
spectralFilmPrint = updatedMetadata.spectralFilmPrint,
|
||||
spectralFilmTuning = SpectralFilmTuning(
|
||||
cDensityGain = updatedMetadata.spectralFilmCDensityGain,
|
||||
mDensityGain = updatedMetadata.spectralFilmMDensityGain,
|
||||
yDensityGain = updatedMetadata.spectralFilmYDensityGain,
|
||||
),
|
||||
spectralFilmTuning = updatedMetadata.decodeSpectralFilmTuning(),
|
||||
fotufilmDocument = FotufilmDocumentStorage.decode(updatedMetadata.fotufilmDocument, "photo metadata"),
|
||||
onMetadata = { raw -> updatedMetadata = updatedMetadata.merge(raw) },
|
||||
)
|
||||
@@ -3840,11 +3830,7 @@ object GalleryManager {
|
||||
rawPhysicalOutputSize = RawDigitalZoomResampling.readPhysicalSize(updatedMetadata.customProperties),
|
||||
spectralFilmStock = updatedMetadata.spectralFilmStock,
|
||||
spectralFilmPrint = updatedMetadata.spectralFilmPrint,
|
||||
spectralFilmTuning = SpectralFilmTuning(
|
||||
cDensityGain = updatedMetadata.spectralFilmCDensityGain,
|
||||
mDensityGain = updatedMetadata.spectralFilmMDensityGain,
|
||||
yDensityGain = updatedMetadata.spectralFilmYDensityGain,
|
||||
),
|
||||
spectralFilmTuning = updatedMetadata.decodeSpectralFilmTuning(),
|
||||
fotufilmDocument = FotufilmDocumentStorage.decode(updatedMetadata.fotufilmDocument, "photo metadata"),
|
||||
onMetadata = { raw -> updatedMetadata = updatedMetadata.merge(raw) },
|
||||
)
|
||||
@@ -3934,11 +3920,7 @@ object GalleryManager {
|
||||
rawPhysicalOutputSize = RawDigitalZoomResampling.readPhysicalSize(updatedMetadata.customProperties),
|
||||
spectralFilmStock = updatedMetadata.spectralFilmStock,
|
||||
spectralFilmPrint = updatedMetadata.spectralFilmPrint,
|
||||
spectralFilmTuning = SpectralFilmTuning(
|
||||
cDensityGain = updatedMetadata.spectralFilmCDensityGain,
|
||||
mDensityGain = updatedMetadata.spectralFilmMDensityGain,
|
||||
yDensityGain = updatedMetadata.spectralFilmYDensityGain,
|
||||
),
|
||||
spectralFilmTuning = updatedMetadata.decodeSpectralFilmTuning(),
|
||||
fotufilmDocument = FotufilmDocumentStorage.decode(updatedMetadata.fotufilmDocument, "photo metadata"),
|
||||
onMetadata = { raw -> updatedMetadata = updatedMetadata.merge(raw) },
|
||||
)
|
||||
@@ -4218,11 +4200,7 @@ object GalleryManager {
|
||||
rawPhysicalOutputSize = RawDigitalZoomResampling.readPhysicalSize(updatedMetadata.customProperties),
|
||||
spectralFilmStock = updatedMetadata.spectralFilmStock,
|
||||
spectralFilmPrint = updatedMetadata.spectralFilmPrint,
|
||||
spectralFilmTuning = SpectralFilmTuning(
|
||||
cDensityGain = updatedMetadata.spectralFilmCDensityGain,
|
||||
mDensityGain = updatedMetadata.spectralFilmMDensityGain,
|
||||
yDensityGain = updatedMetadata.spectralFilmYDensityGain
|
||||
),
|
||||
spectralFilmTuning = updatedMetadata.decodeSpectralFilmTuning(),
|
||||
fotufilmDocument = FotufilmDocumentStorage.decode(updatedMetadata.fotufilmDocument, "photo metadata"),
|
||||
onMetadata = { raw ->
|
||||
updatedMetadata = updatedMetadata.merge(raw)
|
||||
@@ -5678,11 +5656,7 @@ object GalleryManager {
|
||||
rawPhysicalOutputSize = RawDigitalZoomResampling.readPhysicalSize(updatedMetadata.customProperties),
|
||||
spectralFilmStock = updatedMetadata.spectralFilmStock,
|
||||
spectralFilmPrint = updatedMetadata.spectralFilmPrint,
|
||||
spectralFilmTuning = SpectralFilmTuning(
|
||||
cDensityGain = updatedMetadata.spectralFilmCDensityGain,
|
||||
mDensityGain = updatedMetadata.spectralFilmMDensityGain,
|
||||
yDensityGain = updatedMetadata.spectralFilmYDensityGain
|
||||
),
|
||||
spectralFilmTuning = updatedMetadata.decodeSpectralFilmTuning(),
|
||||
fotufilmDocument = FotufilmDocumentStorage.decode(updatedMetadata.fotufilmDocument, "photo metadata"),
|
||||
onMetadata = { raw ->
|
||||
updatedMetadata = updatedMetadata.merge(raw)
|
||||
@@ -5870,11 +5844,7 @@ object GalleryManager {
|
||||
rawPhysicalOutputSize = RawDigitalZoomResampling.readPhysicalSize(rawMetadata.customProperties),
|
||||
spectralFilmStock = updatedMetadata?.spectralFilmStock,
|
||||
spectralFilmPrint = updatedMetadata?.spectralFilmPrint,
|
||||
spectralFilmTuning = SpectralFilmTuning(
|
||||
cDensityGain = updatedMetadata?.spectralFilmCDensityGain ?: 1f,
|
||||
mDensityGain = updatedMetadata?.spectralFilmMDensityGain ?: 1f,
|
||||
yDensityGain = updatedMetadata?.spectralFilmYDensityGain ?: 1f
|
||||
),
|
||||
spectralFilmTuning = updatedMetadata?.decodeSpectralFilmTuning() ?: SpectralFilmTuning.DEFAULT,
|
||||
fotufilmDocument = FotufilmDocumentStorage.decode(updatedMetadata?.fotufilmDocument, "photo metadata"),
|
||||
onMetadata = { raw ->
|
||||
updatedMetadata = updatedMetadata?.merge(raw) ?: MediaMetadata().merge(raw)
|
||||
|
||||
@@ -23,6 +23,7 @@ import com.hinnka.mycamera.raw.RawRenderingEngine
|
||||
import com.hinnka.mycamera.raw.RawToneMappingParameters
|
||||
import com.hinnka.mycamera.raw.RawOutputUpscaleMode
|
||||
import com.hinnka.mycamera.raw.RawCaptureExposureCompensationMetadata
|
||||
import com.hinnka.mycamera.raw.SpectralFilmTuning
|
||||
import com.hinnka.mycamera.utils.DeviceUtil
|
||||
import org.json.JSONObject
|
||||
import java.text.SimpleDateFormat
|
||||
@@ -154,10 +155,10 @@ data class MediaMetadata(
|
||||
val spectralFilmStock: String? = null,
|
||||
val spectralFilmPrint: String? = null,
|
||||
val fotufilmDocument: String? = null,
|
||||
val spectralFilmCDensityGain: Float = 1f,
|
||||
val spectralFilmMDensityGain: Float = 1f,
|
||||
val spectralFilmYDensityGain: Float = 1f,
|
||||
val spectralFilmParameters: String? = null,
|
||||
) {
|
||||
fun decodeSpectralFilmTuning(): SpectralFilmTuning = SpectralFilmTuning.decodeParameters(spectralFilmParameters)
|
||||
|
||||
/**
|
||||
* 将元数据转换为 CaptureInfo,用于写入 EXIF
|
||||
*
|
||||
@@ -511,9 +512,7 @@ data class MediaMetadata(
|
||||
spectralFilmStock = if (obj.isNull("spectralFilmStock")) null else obj.optString("spectralFilmStock"),
|
||||
spectralFilmPrint = if (obj.isNull("spectralFilmPrint")) null else obj.optString("spectralFilmPrint"),
|
||||
fotufilmDocument = if (obj.isNull("fotufilmDocument")) null else obj.optString("fotufilmDocument"),
|
||||
spectralFilmCDensityGain = if (obj.isNull("spectralFilmCDensityGain")) 1f else obj.optDouble("spectralFilmCDensityGain").toFloat(),
|
||||
spectralFilmMDensityGain = if (obj.isNull("spectralFilmMDensityGain")) 1f else obj.optDouble("spectralFilmMDensityGain").toFloat(),
|
||||
spectralFilmYDensityGain = if (obj.isNull("spectralFilmYDensityGain")) 1f else obj.optDouble("spectralFilmYDensityGain").toFloat(),
|
||||
spectralFilmParameters = if (obj.isNull("spectralFilmParameters")) null else obj.optString("spectralFilmParameters"),
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Failed to parse JSON", e)
|
||||
|
||||
@@ -33,7 +33,6 @@ import com.hinnka.mycamera.raw.RawMetadata
|
||||
import com.hinnka.mycamera.raw.RawPhotonHdrMetadata
|
||||
import com.hinnka.mycamera.raw.RawMgcTuningSnr
|
||||
import com.hinnka.mycamera.raw.RawNoiseProfileManager
|
||||
import com.hinnka.mycamera.raw.SpectralFilmTuning
|
||||
import com.hinnka.mycamera.utils.BitmapUtils
|
||||
import com.hinnka.mycamera.raw.fotufilm.FotufilmDocumentStorage
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
@@ -761,11 +760,7 @@ class PhotoProcessor(
|
||||
rawPhysicalOutputSize = RawDigitalZoomResampling.readPhysicalSize(metadata.customProperties),
|
||||
spectralFilmStock = metadata.spectralFilmStock,
|
||||
spectralFilmPrint = metadata.spectralFilmPrint,
|
||||
spectralFilmTuning = SpectralFilmTuning(
|
||||
cDensityGain = metadata.spectralFilmCDensityGain,
|
||||
mDensityGain = metadata.spectralFilmMDensityGain,
|
||||
yDensityGain = metadata.spectralFilmYDensityGain
|
||||
),
|
||||
spectralFilmTuning = metadata.decodeSpectralFilmTuning(),
|
||||
fotufilmDocument = FotufilmDocumentStorage.decode(metadata.fotufilmDocument, "photo metadata")
|
||||
) ?: return@withContext null
|
||||
prepareUltraHdrSourceFromRawResult(
|
||||
@@ -827,11 +822,7 @@ class PhotoProcessor(
|
||||
rawPhysicalOutputSize = RawDigitalZoomResampling.readPhysicalSize(metadata.customProperties),
|
||||
spectralFilmStock = metadata.spectralFilmStock,
|
||||
spectralFilmPrint = metadata.spectralFilmPrint,
|
||||
spectralFilmTuning = SpectralFilmTuning(
|
||||
cDensityGain = metadata.spectralFilmCDensityGain,
|
||||
mDensityGain = metadata.spectralFilmMDensityGain,
|
||||
yDensityGain = metadata.spectralFilmYDensityGain
|
||||
),
|
||||
spectralFilmTuning = metadata.decodeSpectralFilmTuning(),
|
||||
fotufilmDocument = FotufilmDocumentStorage.decode(metadata.fotufilmDocument, "photo metadata"),
|
||||
onMetadata = onRawMetadata
|
||||
)
|
||||
|
||||
@@ -8,7 +8,7 @@ import com.hinnka.mycamera.raw.RawToneMappingParameters
|
||||
|
||||
@Database(
|
||||
entities = [GalleryMediaEntity::class],
|
||||
version = 51,
|
||||
version = 52,
|
||||
exportSchema = false
|
||||
)
|
||||
@androidx.room.TypeConverters(GalleryConverters::class)
|
||||
@@ -877,6 +877,12 @@ abstract class GalleryDatabase : RoomDatabase() {
|
||||
}
|
||||
}
|
||||
|
||||
private val MIGRATION_51_52 = object : androidx.room.migration.Migration(51, 52) {
|
||||
override fun migrate(db: androidx.sqlite.db.SupportSQLiteDatabase) {
|
||||
db.execSQL("ALTER TABLE gallery_media ADD COLUMN spectralFilmParameters TEXT")
|
||||
}
|
||||
}
|
||||
|
||||
fun getInstance(context: Context): GalleryDatabase {
|
||||
return INSTANCE ?: synchronized(this) {
|
||||
INSTANCE ?: Room.databaseBuilder(
|
||||
@@ -934,7 +940,8 @@ abstract class GalleryDatabase : RoomDatabase() {
|
||||
MIGRATION_47_48,
|
||||
MIGRATION_48_49,
|
||||
MIGRATION_49_50,
|
||||
MIGRATION_50_51
|
||||
MIGRATION_50_51,
|
||||
MIGRATION_51_52
|
||||
)
|
||||
.fallbackToDestructiveMigrationOnDowngrade(false)
|
||||
.fallbackToDestructiveMigration(false)
|
||||
|
||||
@@ -166,8 +166,10 @@ data class GalleryMediaEntity(
|
||||
val spectralFilmEnabled: Boolean,
|
||||
val spectralFilmStock: String?,
|
||||
val spectralFilmPrint: String?,
|
||||
val spectralFilmCDensityGain: Float,
|
||||
val spectralFilmMDensityGain: Float,
|
||||
val spectralFilmYDensityGain: Float,
|
||||
// Retained for compatibility with the existing Gallery Room schema.
|
||||
val spectralFilmCDensityGain: Float = 1f,
|
||||
val spectralFilmMDensityGain: Float = 1f,
|
||||
val spectralFilmYDensityGain: Float = 1f,
|
||||
val spectralFilmParameters: String?,
|
||||
val fotufilmDocument: String?
|
||||
)
|
||||
@@ -338,9 +338,7 @@ object GalleryMediaStore {
|
||||
spectralFilmEnabled = false,
|
||||
spectralFilmStock = metadata.spectralFilmStock,
|
||||
spectralFilmPrint = metadata.spectralFilmPrint,
|
||||
spectralFilmCDensityGain = metadata.spectralFilmCDensityGain,
|
||||
spectralFilmMDensityGain = metadata.spectralFilmMDensityGain,
|
||||
spectralFilmYDensityGain = metadata.spectralFilmYDensityGain,
|
||||
spectralFilmParameters = metadata.spectralFilmParameters,
|
||||
fotufilmDocument = metadata.fotufilmDocument
|
||||
)
|
||||
}
|
||||
@@ -542,9 +540,7 @@ object GalleryMediaStore {
|
||||
applyEffectsToVideo = applyEffectsToVideo,
|
||||
spectralFilmStock = spectralFilmStock,
|
||||
spectralFilmPrint = spectralFilmPrint,
|
||||
spectralFilmCDensityGain = spectralFilmCDensityGain,
|
||||
spectralFilmMDensityGain = spectralFilmMDensityGain,
|
||||
spectralFilmYDensityGain = spectralFilmYDensityGain,
|
||||
spectralFilmParameters = spectralFilmParameters,
|
||||
fotufilmDocument = fotufilmDocument
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1545,10 +1545,16 @@ class RawDemosaicProcessor {
|
||||
* MGC GuidedUpsample develops the tone stage on its box-downsampled grid and regresses the
|
||||
* result back onto the full-resolution camera guide. Fotufilm's grain is film-plane texture
|
||||
* that no function of the guide carries, so the regression would average it away (and the
|
||||
* smaller virtual frame would lay it at that grid's pitch); Fotufilm develops on the native grid.
|
||||
* smaller virtual frame would lay it at that grid's pitch). Spektrafilm's spatial graph and
|
||||
* scanner optics also operate at native pixel pitch, independently of the camera guide.
|
||||
*/
|
||||
private fun usesGuidedToneUpsample(geometry: RawOutputGeometry, colorEngine: RawRenderingEngine) =
|
||||
geometry.mgcFinishResolution.needsGuidedUpsample && !colorEngine.isFotufilm
|
||||
private fun usesGuidedToneUpsample(
|
||||
geometry: RawOutputGeometry,
|
||||
colorEngine: RawRenderingEngine,
|
||||
spectralFilmLut: SpectralFilmLut?,
|
||||
) = geometry.mgcFinishResolution.needsGuidedUpsample && !colorEngine.isFotufilm &&
|
||||
(spectralFilmLut == null ||
|
||||
(spectralFilmLut.graph == null && SpektrafilmScannerPass.support(spectralFilmLut.tuning) == 0))
|
||||
|
||||
private data class RawTileRenderConfig(
|
||||
val context: Context,
|
||||
@@ -2622,7 +2628,8 @@ class RawDemosaicProcessor {
|
||||
context,
|
||||
spectralFilmStock,
|
||||
spectralFilmPrint,
|
||||
spectralFilmTuning
|
||||
spectralFilmTuning,
|
||||
buildSpatialGraph = true,
|
||||
)
|
||||
} else {
|
||||
null
|
||||
@@ -2673,7 +2680,10 @@ class RawDemosaicProcessor {
|
||||
else -> requestedColorEngine
|
||||
}
|
||||
// Fotufilm prints onto SDR media (upstream: paper output is SDR); it has no HDR reference.
|
||||
val renderHdrReference = includeHdrReference && !colorEngine.isFotufilm
|
||||
// A direct negative scan darkens as scene exposure increases. The synthesized HDR
|
||||
// reference fits an increasing highlight response and cannot extend a negative scan.
|
||||
val scansNegative = spektrafilmLut?.let { it.type == "negative" && it.tuning.scanFilm } == true
|
||||
val renderHdrReference = includeHdrReference && !colorEngine.isFotufilm && !scansNegative
|
||||
val normalizedToneMappingParameters = rawToneMappingParameters.normalized()
|
||||
val photonHdrRequested = normalizedToneMappingParameters.usePhotonHdr
|
||||
val hasReusablePhotonPgtm = if (dngFile != null) {
|
||||
@@ -2837,7 +2847,14 @@ class RawDemosaicProcessor {
|
||||
measureFlareOnDevice = false,
|
||||
).frame.spatialSupport
|
||||
} ?: 0
|
||||
val tileSupport = maxOf(RAW_TILE_SUPPORT_PX, fotufilmSupport)
|
||||
val spektrafilmSupport = spektrafilmLut?.let { lut ->
|
||||
if (lut.graph != null) {
|
||||
SpektrafilmGraphToneStage.support(lut, actualWidth, actualHeight)
|
||||
} else {
|
||||
SpektrafilmScannerPass.support(lut.tuning)
|
||||
}
|
||||
} ?: 0
|
||||
val tileSupport = maxOf(RAW_TILE_SUPPORT_PX + spektrafilmSupport, fotufilmSupport)
|
||||
val tileCoreEdge = maxOf(
|
||||
RAW_TILE_MAX_CORE_EDGE_PX - 2 * (tileSupport - RAW_TILE_SUPPORT_PX),
|
||||
RAW_TILE_MIN_FOTUFILM_CORE_EDGE_PX,
|
||||
@@ -2855,7 +2872,7 @@ class RawDemosaicProcessor {
|
||||
coreEdgePx = (tileCoreEdge / restoredOutputScale).toInt(),
|
||||
supportPx = tileSupport + if (outputGeometry.resample) 3 else 0,
|
||||
cfaPeriod = RawCfaCorrection.repeatPatternDim(actualMetadata.cfaPattern)[0],
|
||||
processingPeriod = if (usesGuidedToneUpsample(outputGeometry, colorEngine)) {
|
||||
processingPeriod = if (usesGuidedToneUpsample(outputGeometry, colorEngine, spektrafilmLut)) {
|
||||
outputGeometry.mgcFinishResolution.processingPeriod
|
||||
} else 1,
|
||||
)
|
||||
@@ -3917,7 +3934,7 @@ class RawDemosaicProcessor {
|
||||
// the exact post-matrix 2^EV gain.
|
||||
checkGlError("Before LinearRcdPass")
|
||||
|
||||
if (usesGuidedToneUpsample(outputGeometry, colorEngine)) {
|
||||
if (usesGuidedToneUpsample(outputGeometry, colorEngine, spektrafilmLut)) {
|
||||
mgcSharpen.guided.prepare(denoiseProfileTextureId, actualWidth, actualHeight,
|
||||
actualMetadata.whiteBalanceGains, outputGeometry.mgcFinishResolution)
|
||||
renderLinearRcdPass(
|
||||
@@ -4492,8 +4509,6 @@ class RawDemosaicProcessor {
|
||||
} else {
|
||||
1f
|
||||
}
|
||||
setupOutputFramebuffer(maximumOutputWidth, maximumOutputHeight)
|
||||
|
||||
// One tile's source, developed up to the tone stage's input: CFA upload, demosaic,
|
||||
// denoise and the linear profile pass, leaving the result in demosaicTextureId.
|
||||
suspend fun prepareTileSource(tile: RawRenderTile) {
|
||||
@@ -4562,7 +4577,7 @@ class RawDemosaicProcessor {
|
||||
fullImageWidth = config.fullWidth,
|
||||
fullImageHeight = config.fullHeight,
|
||||
)
|
||||
if (usesGuidedToneUpsample(config.outputGeometry, config.colorEngine)) {
|
||||
if (usesGuidedToneUpsample(config.outputGeometry, config.colorEngine, config.spectralFilmLut)) {
|
||||
val resolution = config.outputGeometry.mgcFinishResolution
|
||||
check(working.left % resolution.processingPeriod == 0 &&
|
||||
working.top % resolution.processingPeriod == 0)
|
||||
@@ -4612,6 +4627,59 @@ class RawDemosaicProcessor {
|
||||
linearOutputFramebufferId = tempFramebuffer
|
||||
}
|
||||
|
||||
val tileSpektrafilm = config.spectralFilmLut?.let { lut ->
|
||||
if (lut.graph == null || lut.tuning.halation.boostEv <= 0f) {
|
||||
lut
|
||||
} else {
|
||||
val meteringStartNs = System.nanoTime()
|
||||
val fullSource = RawTileRect(0, 0, config.fullWidth, config.fullHeight)
|
||||
val outputBounds = config.outputSourceBounds
|
||||
val meteringTiles = if (outputBounds == Rect(0, 0, config.fullWidth, config.fullHeight)) {
|
||||
config.tiles
|
||||
} else {
|
||||
// The highlight reference belongs to the entire exposed frame. Each
|
||||
// core is measured once, with a RAW apron around the demosaic input.
|
||||
RawTilePlanner.plan(
|
||||
sourceWidth = config.fullWidth,
|
||||
sourceHeight = config.fullHeight,
|
||||
outputSourceBounds = fullSource,
|
||||
rotation = 0,
|
||||
coreEdgePx = RAW_TILE_MAX_CORE_EDGE_PX,
|
||||
supportPx = RAW_TILE_SUPPORT_PX,
|
||||
cfaPeriod = RawCfaCorrection.repeatPatternDim(config.metadata.cfaPattern)[0],
|
||||
)
|
||||
}
|
||||
var maximum = 0f
|
||||
for (tile in meteringTiles) {
|
||||
currentCoroutineContext().ensureActive()
|
||||
prepareTileSource(tile)
|
||||
val working = tile.sourceWorking
|
||||
val core = tile.sourceCore
|
||||
maximum = maxOf(
|
||||
maximum,
|
||||
engineTonePass.measureSpectralMaximum(
|
||||
tileToneInput(config, demosaicTextureId, working),
|
||||
core.left - working.left,
|
||||
core.top - working.top,
|
||||
core.width,
|
||||
core.height,
|
||||
),
|
||||
)
|
||||
}
|
||||
check(maximum.isFinite()) { "Invalid Spektrafilm frame maximum: $maximum" }
|
||||
if (rawTileTextureWidth != firstWorking.width || rawTileTextureHeight != firstWorking.height) {
|
||||
releaseTiledRenderFramebuffers()
|
||||
vgnDemosaicAlgorithm.setTileTexturePoolingEnabled(true)
|
||||
}
|
||||
PLog.i(
|
||||
TAG,
|
||||
"Spektrafilm tiled highlight reference: tiles=${meteringTiles.size} maximum=$maximum " +
|
||||
"elapsed=${(System.nanoTime() - meteringStartNs) / 1_000_000}ms",
|
||||
)
|
||||
lut.copy(frameMaximum = maximum)
|
||||
}
|
||||
}
|
||||
|
||||
// Fotufilm meters the whole frame before any tile develops (Auto Levels, Lab Scan,
|
||||
// regional tone): every tile's core is developed to the tone input once and folded
|
||||
// into a reduced whole-frame image, then the frame is built from it for all tiles.
|
||||
@@ -4629,10 +4697,8 @@ class RawDemosaicProcessor {
|
||||
currentCoroutineContext().ensureActive()
|
||||
prepareTileSource(tile)
|
||||
val working = tile.sourceWorking
|
||||
val cells = meterFotufilmTile(
|
||||
config = config,
|
||||
inputTextureId = demosaicTextureId,
|
||||
working = working,
|
||||
val cells = engineTonePass.meterFotufilmTile(
|
||||
input = tileToneInput(config, demosaicTextureId, working),
|
||||
coreLeft = tile.sourceCore.left - working.left,
|
||||
coreTop = tile.sourceCore.top - working.top,
|
||||
coreWidth = tile.sourceCore.width,
|
||||
@@ -4651,37 +4717,18 @@ class RawDemosaicProcessor {
|
||||
}
|
||||
}
|
||||
|
||||
for (tile in config.tiles) {
|
||||
currentCoroutineContext().ensureActive()
|
||||
val tileStartNs = System.nanoTime()
|
||||
val scaledCore = config.outputGeometry.scaleRegion(tile.outputCore)
|
||||
suspend fun developWorkingTile(tile: RawRenderTile): Boolean {
|
||||
val working = tile.sourceWorking
|
||||
val workWidth = working.width
|
||||
val workHeight = working.height
|
||||
prepareTileSource(tile)
|
||||
val localSourceCore = Rect(
|
||||
tile.sourceCore.left - working.left,
|
||||
tile.sourceCore.top - working.top,
|
||||
tile.sourceCore.right - working.left,
|
||||
tile.sourceCore.bottom - working.top,
|
||||
)
|
||||
val localOutputBounds = localSourceCore.toOutputBounds(config.rotation)
|
||||
check(
|
||||
localOutputBounds.width() == tile.outputCore.width &&
|
||||
localOutputBounds.height() == tile.outputCore.height
|
||||
) {
|
||||
"RAW tile rotation mapping mismatch: output=${tile.outputCore} " +
|
||||
"source=${tile.sourceCore}"
|
||||
}
|
||||
|
||||
|
||||
val combinedOutput = renderCombinedPass(
|
||||
metadata = config.metadata,
|
||||
inputTextureId = if (mgcSharpen.guided.isPrepared) mgcSharpen.guided.profileTexture else demosaicTextureId,
|
||||
dcpRenderPlan = config.activeDcpRenderPlan,
|
||||
applyDcpHueSatMap = config.deferDcpHueSatUntilAfterPgtm,
|
||||
profileExposureUniforms = config.profileExposureUniforms,
|
||||
spectralFilmLut = config.spectralFilmLut,
|
||||
spectralFilmLut = tileSpektrafilm,
|
||||
fotufilm = tileFotufilm,
|
||||
hncsRenderPlan = config.hncsRenderPlan,
|
||||
lumixRenderPlan = config.lumixRenderPlan,
|
||||
@@ -4706,7 +4753,7 @@ class RawDemosaicProcessor {
|
||||
)
|
||||
if (combinedOutput == null) {
|
||||
PLog.e(TAG, "Combined tile pass failed at tile=${tile.index}")
|
||||
return null
|
||||
return false
|
||||
}
|
||||
setupSharpenFramebuffer(workWidth, workHeight)
|
||||
renderFinalSharpenPass(
|
||||
@@ -4720,7 +4767,7 @@ class RawDemosaicProcessor {
|
||||
metadata = config.metadata,
|
||||
inputTextureId = demosaicTextureId,
|
||||
dcpRenderPlan = config.activeDcpRenderPlan,
|
||||
spectralFilmLut = config.spectralFilmLut,
|
||||
spectralFilmLut = tileSpektrafilm,
|
||||
hncsRenderPlan = config.hncsRenderPlan,
|
||||
lumixRenderPlan = config.lumixRenderPlan,
|
||||
canonRenderPlan = config.canonRenderPlan,
|
||||
@@ -4740,6 +4787,55 @@ class RawDemosaicProcessor {
|
||||
viewportWidth = workWidth,
|
||||
viewportHeight = workHeight,
|
||||
)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// A large optical apron can make distinct output cores share one source rectangle.
|
||||
// Keep those cores consecutive so they can read the same sharpened and HDR textures.
|
||||
val canReuseWorkingTile = tileSpektrafilm?.let { lut ->
|
||||
lut.graph?.let { graph ->
|
||||
lut.tuning.cameraDiffusion.active || (graph.printing && lut.tuning.enlargerDiffusion.active)
|
||||
}
|
||||
} == true
|
||||
val outputTiles = if (canReuseWorkingTile) {
|
||||
config.tiles.groupBy { it.sourceWorking }.values.flatten()
|
||||
} else {
|
||||
config.tiles
|
||||
}
|
||||
var lastDevelopedWorking: RawTileRect? = null
|
||||
var developedWorkingTiles = 0
|
||||
val tileRenderingStartNs = System.nanoTime()
|
||||
setupOutputFramebuffer(maximumOutputWidth, maximumOutputHeight)
|
||||
for (tile in outputTiles) {
|
||||
currentCoroutineContext().ensureActive()
|
||||
val tileStartNs = System.nanoTime()
|
||||
val scaledCore = config.outputGeometry.scaleRegion(tile.outputCore)
|
||||
val working = tile.sourceWorking
|
||||
val workWidth = working.width
|
||||
val workHeight = working.height
|
||||
val localSourceCore = Rect(
|
||||
tile.sourceCore.left - working.left,
|
||||
tile.sourceCore.top - working.top,
|
||||
tile.sourceCore.right - working.left,
|
||||
tile.sourceCore.bottom - working.top,
|
||||
)
|
||||
val localOutputBounds = localSourceCore.toOutputBounds(config.rotation)
|
||||
check(
|
||||
localOutputBounds.width() == tile.outputCore.width &&
|
||||
localOutputBounds.height() == tile.outputCore.height
|
||||
) {
|
||||
"RAW tile rotation mapping mismatch: output=${tile.outputCore} " +
|
||||
"source=${tile.sourceCore}"
|
||||
}
|
||||
val developWorking = !canReuseWorkingTile || working != lastDevelopedWorking
|
||||
if (developWorking) {
|
||||
if (!developWorkingTile(tile)) return null
|
||||
lastDevelopedWorking = working
|
||||
developedWorkingTiles++
|
||||
}
|
||||
|
||||
if (config.includeHdrReference) {
|
||||
renderOutputPass(
|
||||
rotation = config.rotation,
|
||||
width = workWidth,
|
||||
@@ -4872,6 +4968,7 @@ class RawDemosaicProcessor {
|
||||
"RAW_TILE_DONE index=${tile.index + 1}/${config.tiles.size} " +
|
||||
"output=${tile.outputCore} source=${tile.sourceCore} work=$working " +
|
||||
"scaled=$scaledCore localCore=$localSourceCore " +
|
||||
"developed=$developWorking " +
|
||||
"upscale=${if (config.outputGeometry.raisrUpsample) "raisr" else "lanczos"} " +
|
||||
"tookMs=${(System.nanoTime() - tileStartNs) / 1_000_000}",
|
||||
)
|
||||
@@ -4879,7 +4976,9 @@ class RawDemosaicProcessor {
|
||||
completed = true
|
||||
PLog.i(
|
||||
TAG,
|
||||
"RAW_TILE_COMPLETE tiles=${config.tiles.size} output=${outputWidth}x$outputHeight",
|
||||
"RAW_TILE_COMPLETE tiles=${config.tiles.size} output=${outputWidth}x$outputHeight " +
|
||||
"developedWorkingTiles=$developedWorkingTiles reusedCores=${config.tiles.size - developedWorkingTiles} " +
|
||||
"elapsedMs=${(System.nanoTime() - tileRenderingStartNs) / 1_000_000}",
|
||||
)
|
||||
return RawTileBitmapResult(
|
||||
sdrBitmap = sdrBitmap,
|
||||
@@ -7296,51 +7395,40 @@ class RawDemosaicProcessor {
|
||||
) != null
|
||||
}
|
||||
|
||||
/** One tile's Fotufilm metering cells, from the same tone input the tile develops from. */
|
||||
private fun meterFotufilmTile(
|
||||
/** Meter from the same profile-corrected source used to develop the tile. */
|
||||
private fun tileToneInput(
|
||||
config: RawTileRenderConfig,
|
||||
inputTextureId: Int,
|
||||
working: RawTileRect,
|
||||
coreLeft: Int,
|
||||
coreTop: Int,
|
||||
coreWidth: Int,
|
||||
coreHeight: Int,
|
||||
cellSize: Int,
|
||||
): FotufilmMeterCells? {
|
||||
val metadata = config.metadata
|
||||
return engineTonePass.meterFotufilmTile(
|
||||
RawEngineTonePass.Input(
|
||||
textureId = inputTextureId,
|
||||
targetFramebufferId = engineToneFramebufferId,
|
||||
targetTextureId = engineToneTextureId,
|
||||
colorEngine = config.colorEngine,
|
||||
profileToEngineTransform = config.profileToEngineTransform,
|
||||
outputTransform = computeWorkingToOutputTransform(config.engineWorkingColorSpace, ColorSpace.SRGB),
|
||||
globalOriginX = working.left,
|
||||
globalOriginY = working.top,
|
||||
fullImageWidth = config.fullWidth,
|
||||
fullImageHeight = config.fullHeight,
|
||||
width = working.width,
|
||||
height = working.height,
|
||||
toneMappingParameters = config.rawToneMappingParameters,
|
||||
profileExposure = config.profileExposureUniforms,
|
||||
dcpRenderPlan = config.activeDcpRenderPlan,
|
||||
applyDcpHueSatMap = config.deferDcpHueSatUntilAfterPgtm,
|
||||
spectralFilmLut = null,
|
||||
hncsRenderPlan = null,
|
||||
fotufilm = config.fotufilm,
|
||||
bindProfileGainTable = { program ->
|
||||
bindProfileGainTableMap(
|
||||
program = program,
|
||||
metadata = metadata,
|
||||
applyProfileGainTableMap = config.hasProfileGainTableMap,
|
||||
profileBaselineExposureOffsetEv = dcpBaselineExposureOffsetOrZero(config.activeDcpRenderPlan),
|
||||
)
|
||||
},
|
||||
),
|
||||
coreLeft, coreTop, coreWidth, coreHeight, cellSize,
|
||||
)
|
||||
}
|
||||
): RawEngineTonePass.Input = RawEngineTonePass.Input(
|
||||
textureId = inputTextureId,
|
||||
targetFramebufferId = engineToneFramebufferId,
|
||||
targetTextureId = engineToneTextureId,
|
||||
colorEngine = config.colorEngine,
|
||||
profileToEngineTransform = config.profileToEngineTransform,
|
||||
outputTransform = computeWorkingToOutputTransform(config.engineWorkingColorSpace, ColorSpace.SRGB),
|
||||
globalOriginX = working.left,
|
||||
globalOriginY = working.top,
|
||||
fullImageWidth = config.fullWidth,
|
||||
fullImageHeight = config.fullHeight,
|
||||
width = working.width,
|
||||
height = working.height,
|
||||
toneMappingParameters = config.rawToneMappingParameters,
|
||||
profileExposure = config.profileExposureUniforms,
|
||||
dcpRenderPlan = config.activeDcpRenderPlan,
|
||||
applyDcpHueSatMap = config.deferDcpHueSatUntilAfterPgtm,
|
||||
spectralFilmLut = config.spectralFilmLut,
|
||||
hncsRenderPlan = null,
|
||||
fotufilm = config.fotufilm,
|
||||
bindProfileGainTable = { program ->
|
||||
bindProfileGainTableMap(
|
||||
program = program,
|
||||
metadata = config.metadata,
|
||||
applyProfileGainTableMap = config.hasProfileGainTableMap,
|
||||
profileBaselineExposureOffsetEv = dcpBaselineExposureOffsetOrZero(config.activeDcpRenderPlan),
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
private fun needsAdjustmentPass(
|
||||
shadowsHighlightsParams: ShadowsHighlightsParams,
|
||||
|
||||
@@ -62,6 +62,8 @@ internal class RawEngineTonePass(
|
||||
private val adobeCurveAlgorithm = AdobeCurveToneAlgorithm(quad, dcpTextures, curveTextures)
|
||||
private val agxAlgorithm = AgXToneAlgorithm(quad)
|
||||
private val spektrafilmAlgorithm = SpektrafilmToneAlgorithm(quad)
|
||||
private val spektrafilmScannerPass = SpektrafilmScannerPass(quad)
|
||||
private val spektrafilmGraph = SpektrafilmGraphToneStage(quad)
|
||||
private val darktableSigmoidAlgorithm = DarktableSigmoidToneAlgorithm(quad)
|
||||
private val darktableFilmicAlgorithm = DarktableFilmicToneAlgorithm(quad)
|
||||
private val hncsAlgorithm = HncsToneAlgorithm(quad)
|
||||
@@ -70,12 +72,22 @@ internal class RawEngineTonePass(
|
||||
private val leicaAlgorithm = LeicaToneAlgorithm(quad)
|
||||
private val fotufilmStage = FotufilmToneStage(quad)
|
||||
|
||||
fun render(input: Input): Output? = if (input.colorEngine.isFotufilm) {
|
||||
fotufilmStage.render(input)
|
||||
} else {
|
||||
algorithmFor(input.colorEngine).render(input)
|
||||
fun render(input: Input): Output? {
|
||||
if (input.colorEngine == RawRenderingEngine.Spektrafilm && input.spectralFilmLut?.graph != null) {
|
||||
return spektrafilmGraph.render(input)
|
||||
}
|
||||
spektrafilmGraph.discardInactiveGraph()
|
||||
return when {
|
||||
input.colorEngine.isFotufilm -> fotufilmStage.render(input)
|
||||
input.colorEngine == RawRenderingEngine.Spektrafilm && input.spectralFilmLut != null ->
|
||||
spektrafilmScannerPass.render(input, spektrafilmAlgorithm)
|
||||
else -> algorithmFor(input.colorEngine).render(input)
|
||||
}
|
||||
}
|
||||
|
||||
internal fun measureSpectralMaximum(input: Input, left: Int, top: Int, width: Int, height: Int): Float =
|
||||
spektrafilmGraph.measureMaximum(input, left, top, width, height)
|
||||
|
||||
/** Whole-frame metering contribution of one full-resolution tile; see [FotufilmToneStage.meterTile]. */
|
||||
internal fun meterFotufilmTile(
|
||||
input: Input,
|
||||
@@ -112,6 +124,8 @@ internal class RawEngineTonePass(
|
||||
adobeCurveAlgorithm.release()
|
||||
agxAlgorithm.release()
|
||||
spektrafilmAlgorithm.release()
|
||||
spektrafilmScannerPass.release()
|
||||
spektrafilmGraph.release()
|
||||
darktableSigmoidAlgorithm.release()
|
||||
darktableFilmicAlgorithm.release()
|
||||
hncsAlgorithm.release()
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import com.google.gson.annotations.SerializedName
|
||||
|
||||
data class SpectralRgb(
|
||||
@SerializedName("r") val r: Float,
|
||||
@SerializedName("g") val g: Float,
|
||||
@SerializedName("b") val b: Float,
|
||||
) {
|
||||
internal fun values() = floatArrayOf(r, g, b)
|
||||
|
||||
internal fun bounded(range: ClosedFloatingPointRange<Float>, defaults: SpectralRgb) = SpectralRgb(
|
||||
r.spectralBound(range, defaults.r), g.spectralBound(range, defaults.g), b.spectralBound(range, defaults.b),
|
||||
)
|
||||
}
|
||||
|
||||
data class SpectralKnee(
|
||||
@SerializedName("threshold") val threshold: Float = 0f,
|
||||
@SerializedName("limit") val limit: Float = 1f,
|
||||
@SerializedName("power") val power: Float = 6f,
|
||||
) {
|
||||
internal fun normalized(): SpectralKnee {
|
||||
val start = threshold.spectralBound(0f..0.99f, 0f)
|
||||
return SpectralKnee(start, limit.spectralBound((start + 0.01f)..4f, 1f), power.spectralBound(0.1f..16f, 6f))
|
||||
}
|
||||
}
|
||||
|
||||
data class SpectralDirMatrix(
|
||||
@SerializedName("r") val r: SpectralRgb,
|
||||
@SerializedName("g") val g: SpectralRgb,
|
||||
@SerializedName("b") val b: SpectralRgb,
|
||||
) {
|
||||
internal fun values() = r.values() + g.values() + b.values()
|
||||
|
||||
internal fun bounded(stock: SpectralDirMatrix): SpectralDirMatrix {
|
||||
fun row(value: SpectralRgb, stockRow: SpectralRgb) = SpectralRgb(
|
||||
value.r.spectralBound(0f..stockRow.r, stockRow.r),
|
||||
value.g.spectralBound(0f..stockRow.g, stockRow.g),
|
||||
value.b.spectralBound(0f..stockRow.b, stockRow.b),
|
||||
)
|
||||
return SpectralDirMatrix(row(r, stock.r), row(g, stock.g), row(b, stock.b))
|
||||
}
|
||||
}
|
||||
|
||||
data class SpectralDiffusion(
|
||||
@SerializedName("enabled") val enabled: Boolean = false,
|
||||
@SerializedName("family") val family: Int = 0,
|
||||
@SerializedName("strength") val strength: Float = 0.5f,
|
||||
@SerializedName("spatialScale") val spatialScale: Float = 1f,
|
||||
@SerializedName("haloWarmth") val haloWarmth: Float = 0f,
|
||||
@SerializedName("coreIntensity") val coreIntensity: Float = 1f,
|
||||
@SerializedName("coreSize") val coreSize: Float = 1f,
|
||||
@SerializedName("haloIntensity") val haloIntensity: Float = 1f,
|
||||
@SerializedName("haloSize") val haloSize: Float = 1f,
|
||||
@SerializedName("bloomIntensity") val bloomIntensity: Float = 1f,
|
||||
@SerializedName("bloomSize") val bloomSize: Float = 1f,
|
||||
) {
|
||||
internal val active get() = enabled && strength > 0f && spatialScale > 0f
|
||||
|
||||
internal fun normalized() = copy(
|
||||
family = family.coerceIn(0, 3),
|
||||
strength = strength.spectralBound(0f..2f, 0.5f),
|
||||
spatialScale = spatialScale.spectralBound(0f..4f, 1f),
|
||||
haloWarmth = haloWarmth.spectralBound(-1.5f..1.5f, 0f),
|
||||
coreIntensity = coreIntensity.spectralBound(0f..4f, 1f),
|
||||
coreSize = coreSize.spectralBound(0.1f..4f, 1f),
|
||||
haloIntensity = haloIntensity.spectralBound(0f..4f, 1f),
|
||||
haloSize = haloSize.spectralBound(0.1f..4f, 1f),
|
||||
bloomIntensity = bloomIntensity.spectralBound(0f..4f, 1f),
|
||||
bloomSize = bloomSize.spectralBound(0.1f..4f, 1f),
|
||||
)
|
||||
}
|
||||
|
||||
data class SpectralHalation(
|
||||
@SerializedName("enabled") val enabled: Boolean = false,
|
||||
@SerializedName("scatterAmount") val scatterAmount: Float = 1f,
|
||||
@SerializedName("scatterSpatialScale") val scatterSpatialScale: Float = 1f,
|
||||
@SerializedName("halationAmount") val halationAmount: Float = 1f,
|
||||
@SerializedName("halationSpatialScale") val halationSpatialScale: Float = 1f,
|
||||
@SerializedName("scatterCoreUm") val scatterCoreUm: SpectralRgb = SpectralRgb(2.2f, 2f, 1.6f),
|
||||
@SerializedName("scatterTailUm") val scatterTailUm: SpectralRgb = SpectralRgb(9.3f, 9.7f, 9.1f),
|
||||
@SerializedName("scatterTailWeight") val scatterTailWeight: SpectralRgb = SpectralRgb(0.78f, 0.65f, 0.67f),
|
||||
@SerializedName("boostEv") val boostEv: Float = 0f,
|
||||
@SerializedName("boostRange") val boostRange: Float = 0.3f,
|
||||
@SerializedName("protectEv") val protectEv: Float = 4f,
|
||||
@SerializedName("strength") val strength: SpectralRgb? = null,
|
||||
@SerializedName("firstSigmaUm") val firstSigmaUm: SpectralRgb? = null,
|
||||
@SerializedName("bounces") val bounces: Int = 3,
|
||||
@SerializedName("bounceDecay") val bounceDecay: Float = 0.5f,
|
||||
@SerializedName("renormalize") val renormalize: Boolean = true,
|
||||
) {
|
||||
internal fun normalized() = copy(
|
||||
scatterAmount = scatterAmount.spectralBound(0f..4f, 1f),
|
||||
scatterSpatialScale = scatterSpatialScale.spectralBound(0f..4f, 1f),
|
||||
halationAmount = halationAmount.spectralBound(0f..4f, 1f),
|
||||
halationSpatialScale = halationSpatialScale.spectralBound(0f..4f, 1f),
|
||||
scatterCoreUm = scatterCoreUm.bounded(0f..30f, SpectralRgb(2.2f, 2f, 1.6f)),
|
||||
scatterTailUm = scatterTailUm.bounded(0f..100f, SpectralRgb(9.3f, 9.7f, 9.1f)),
|
||||
scatterTailWeight = scatterTailWeight.bounded(0f..1f, SpectralRgb(0.78f, 0.65f, 0.67f)),
|
||||
strength = strength?.bounded(0f..1f, SpectralRgb(0.015f, 0.005f, 0f)),
|
||||
firstSigmaUm = firstSigmaUm?.bounded(0f..200f, SpectralRgb(65f, 65f, 65f)),
|
||||
bounces = bounces.coerceIn(1, 8),
|
||||
bounceDecay = bounceDecay.spectralBound(0f..1f, 0.5f),
|
||||
boostEv = boostEv.spectralBound(0f..12f, 0f),
|
||||
boostRange = boostRange.spectralBound(0f..1f, 0.3f),
|
||||
protectEv = protectEv.spectralBound(0f..12f, 4f),
|
||||
)
|
||||
}
|
||||
|
||||
data class SpectralGrain(
|
||||
@SerializedName("enabled") val enabled: Boolean = false,
|
||||
@SerializedName("sublayers") val sublayers: Boolean = true,
|
||||
@SerializedName("particleAreaUm2") val particleAreaUm2: Float = 0.2f,
|
||||
@SerializedName("particleScale") val particleScale: SpectralRgb = SpectralRgb(1.6f, 1.6f, 3.2f),
|
||||
@SerializedName("particleScaleLayers") val particleScaleLayers: SpectralRgb = SpectralRgb(2f, 1f, 0.5f),
|
||||
@SerializedName("densityMin") val densityMin: SpectralRgb = SpectralRgb(0.03f, 0.03f, 0.03f),
|
||||
@SerializedName("uniformity") val uniformity: SpectralRgb = SpectralRgb(0.97f, 0.99f, 0.97f),
|
||||
@SerializedName("blur") val blur: Float = 0.65f,
|
||||
@SerializedName("blurDyeCloudsUm") val blurDyeCloudsUm: Float = 1f,
|
||||
@SerializedName("microBlurUm") val microBlurUm: Float = 0.2f,
|
||||
@SerializedName("microClumpNm") val microClumpNm: Float = 30f,
|
||||
@SerializedName("subLayerCount") val subLayerCount: Int = 1,
|
||||
) {
|
||||
internal val active get() = enabled && particleAreaUm2 > 0f
|
||||
|
||||
internal fun normalized() = copy(
|
||||
particleAreaUm2 = particleAreaUm2.spectralBound(0f..4f, 0.2f),
|
||||
particleScale = particleScale.bounded(0.01f..8f, SpectralRgb(1.6f, 1.6f, 3.2f)),
|
||||
particleScaleLayers = particleScaleLayers.bounded(0.01f..8f, SpectralRgb(2f, 1f, 0.5f)),
|
||||
densityMin = densityMin.bounded(0f..1f, SpectralRgb(0.03f, 0.03f, 0.03f)),
|
||||
uniformity = uniformity.bounded(0f..1f, SpectralRgb(0.97f, 0.99f, 0.97f)),
|
||||
blur = blur.spectralBound(0f..4f, 0.65f),
|
||||
blurDyeCloudsUm = blurDyeCloudsUm.spectralBound(0f..8f, 1f),
|
||||
microBlurUm = microBlurUm.spectralBound(0f..8f, 0.2f),
|
||||
microClumpNm = microClumpNm.spectralBound(0f..200f, 30f),
|
||||
subLayerCount = subLayerCount.coerceIn(1, 8),
|
||||
)
|
||||
}
|
||||
|
||||
data class SpectralGlare(
|
||||
@SerializedName("enabled") val enabled: Boolean = false,
|
||||
@SerializedName("percent") val percent: Float = 0.03f,
|
||||
@SerializedName("roughness") val roughness: Float = 0.7f,
|
||||
@SerializedName("blur") val blur: Float = 0.5f,
|
||||
) {
|
||||
internal val active get() = enabled && percent > 0f
|
||||
|
||||
internal fun normalized() = copy(
|
||||
percent = percent.spectralBound(0f..1f, 0.03f),
|
||||
roughness = roughness.spectralBound(0f..1f, 0.7f),
|
||||
blur = blur.spectralBound(0f..8f, 0.5f),
|
||||
)
|
||||
}
|
||||
|
||||
object SpectralFilmStockDefaults {
|
||||
fun dirMatrix(stock: String): SpectralDirMatrix {
|
||||
val positive = FilmStockRegistry.get(stock).type == "positive"
|
||||
if (!positive) return SpectralDirMatrix(
|
||||
SpectralRgb(0.336f, 0.353f, 0.302f),
|
||||
SpectralRgb(0.154f, 0.319f, 0.353f),
|
||||
SpectralRgb(0.168f, 0.226f, 0.273f),
|
||||
)
|
||||
return when (stock) {
|
||||
"fujifilm_velvia_100" -> SpectralDirMatrix(
|
||||
SpectralRgb(0.108f, 0.108f, 0.054f),
|
||||
SpectralRgb(0.072f, 0.072f, 0.054f),
|
||||
SpectralRgb(0.054f, 0.054f, 0.054f),
|
||||
)
|
||||
"fujifilm_provia_100f" -> SpectralDirMatrix(
|
||||
SpectralRgb(0.156f, 0.156f, 0.078f),
|
||||
SpectralRgb(0.104f, 0.104f, 0.078f),
|
||||
SpectralRgb(0.078f, 0.078f, 0.078f),
|
||||
)
|
||||
else -> SpectralDirMatrix(
|
||||
SpectralRgb(0.12f, 0.12f, 0.06f),
|
||||
SpectralRgb(0.08f, 0.08f, 0.06f),
|
||||
SpectralRgb(0.06f, 0.06f, 0.06f),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun halation(stock: String, parameters: SpectralHalation = SpectralHalation()): SpectralHalation {
|
||||
val sigma = if (stock.startsWith("kodak_vision3_") || stock == "kodak_verita_200d") 50f else 65f
|
||||
val weak = stock in weakAntihalation
|
||||
return parameters.copy(
|
||||
strength = parameters.strength ?: if (weak) SpectralRgb(0.08f, 0.02f, 0f) else SpectralRgb(0.015f, 0.005f, 0f),
|
||||
firstSigmaUm = parameters.firstSigmaUm ?: SpectralRgb(sigma, sigma, sigma),
|
||||
)
|
||||
}
|
||||
|
||||
private val weakAntihalation = setOf(
|
||||
"fujifilm_c200", "fujifilm_xtra_400", "kodak_gold_200", "kodak_kodachrome_64", "kodak_ultramax_400",
|
||||
)
|
||||
}
|
||||
|
||||
internal fun Float.spectralBound(range: ClosedFloatingPointRange<Float>, default: Float): Float =
|
||||
(if (isFinite()) this else default).coerceIn(range)
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
/** CPU tables produced by the same spectral model as the realtime point transform. */
|
||||
class SpectralFilmGraph internal constructor(
|
||||
internal val sourceKey: String,
|
||||
internal val size: Int,
|
||||
stages: Array<FloatArray>,
|
||||
) {
|
||||
internal val filmExposure = stages[2]
|
||||
internal val filmCurves = stages[3]
|
||||
internal val paperExposure = stages[4]
|
||||
internal val paperCurves = stages[5]
|
||||
internal val scan = stages[6]
|
||||
internal val gamut = stages[7]
|
||||
|
||||
private val parameters = stages[8].also {
|
||||
require(it.size == 50 && it.all(Float::isFinite)) { "Invalid native Spektrafilm graph metadata" }
|
||||
}
|
||||
internal val filmCurveSize = parameters[0].toInt()
|
||||
internal val filmCurveRows = parameters[1].toInt()
|
||||
internal val positive = parameters[2] == 1f
|
||||
internal val filmExposureCorrection = parameters[3]
|
||||
internal val gamma = parameters.vec(4)
|
||||
internal val densityMax = parameters.vec(7)
|
||||
internal val dirMatrix = parameters.copyOfRange(10, 19)
|
||||
internal val filmLow = parameters.vec(19)
|
||||
internal val filmHigh = parameters.vec(22)
|
||||
internal val scanLow = parameters.vec(25)
|
||||
internal val scanHigh = parameters.vec(28)
|
||||
internal val glareWhite = parameters.vec(31)
|
||||
internal val gamutLow = parameters.vec(34)
|
||||
internal val gamutHigh = parameters.vec(37)
|
||||
internal val layerMax = List(3) { parameters.vec(40 + 3 * it) }
|
||||
internal val linearScan = parameters[49] == 1f
|
||||
|
||||
internal val printing get() = paperExposure.isNotEmpty()
|
||||
internal val usesGlare get() = gamut.isNotEmpty()
|
||||
internal val usesDir get() = dirMatrix.any { it != 0f }
|
||||
|
||||
init {
|
||||
val cube = size * size * size * 4
|
||||
require(filmCurveSize in 2..4096 && filmCurveRows in setOf(2, 5))
|
||||
require(filmExposure.size == cube && scan.size == cube)
|
||||
require(filmCurves.size == filmCurveSize * filmCurveRows * 4)
|
||||
require(paperExposure.isEmpty() || paperExposure.size == cube)
|
||||
require(paperCurves.size == if (printing) 4096 * 4 else 0)
|
||||
require(gamut.isEmpty() || gamut.size == cube)
|
||||
}
|
||||
|
||||
private fun FloatArray.vec(offset: Int) = SpectralRgb(this[offset], this[offset + 1], this[offset + 2])
|
||||
}
|
||||
@@ -22,7 +22,9 @@ data class SpectralFilmLut(
|
||||
val printTable: SpectralLutTable?,
|
||||
val inputScale: Float,
|
||||
val printInputScale: Float,
|
||||
val negativeDensityGains: FloatArray,
|
||||
val tuning: SpectralFilmTuning,
|
||||
val graph: SpectralFilmGraph? = null,
|
||||
val frameMaximum: Float? = null,
|
||||
) {
|
||||
val size: Int get() = filmTable.size
|
||||
val values: FloatArray get() = filmTable.values
|
||||
@@ -34,41 +36,6 @@ data class FilmStockInfo(
|
||||
val viewingIlluminant: String,
|
||||
)
|
||||
|
||||
data class SpectralFilmTuning(
|
||||
val cDensityGain: Float = 1f,
|
||||
val mDensityGain: Float = 1f,
|
||||
val yDensityGain: Float = 1f
|
||||
) {
|
||||
fun normalized(): SpectralFilmTuning {
|
||||
return SpectralFilmTuning(
|
||||
cDensityGain = cDensityGain.coerceIn(MIN_DENSITY_GAIN, MAX_DENSITY_GAIN),
|
||||
mDensityGain = mDensityGain.coerceIn(MIN_DENSITY_GAIN, MAX_DENSITY_GAIN),
|
||||
yDensityGain = yDensityGain.coerceIn(MIN_DENSITY_GAIN, MAX_DENSITY_GAIN)
|
||||
)
|
||||
}
|
||||
|
||||
fun cacheKey(): String {
|
||||
val t = normalized()
|
||||
return "${t.cDensityGain}:${t.mDensityGain}:${t.yDensityGain}"
|
||||
}
|
||||
|
||||
fun negativeFilmDensityGainC(): Float = userFacingDensityToNegativeFilmGain(normalized().cDensityGain)
|
||||
|
||||
fun negativeFilmDensityGainM(): Float = userFacingDensityToNegativeFilmGain(normalized().mDensityGain)
|
||||
|
||||
fun negativeFilmDensityGainY(): Float = userFacingDensityToNegativeFilmGain(normalized().yDensityGain)
|
||||
|
||||
companion object {
|
||||
const val MIN_DENSITY_GAIN = 0.5f
|
||||
const val MAX_DENSITY_GAIN = 1.5f
|
||||
val DEFAULT = SpectralFilmTuning()
|
||||
|
||||
private fun userFacingDensityToNegativeFilmGain(gain: Float): Float {
|
||||
return 2f - gain
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data class SpectralFilmSelection(
|
||||
val id: String,
|
||||
val tuning: SpectralFilmTuning = SpectralFilmTuning.DEFAULT
|
||||
@@ -159,7 +126,7 @@ object SpectralFilmProfile {
|
||||
)
|
||||
|
||||
// All access is serialized, including native model lifetime and disk eviction.
|
||||
// Tuning changes reuse these exact arrays and only update shader uniforms.
|
||||
// Reuse each stage by its optical/development settings, independently of scanner blur.
|
||||
private var cachedManifest: Manifest? = null
|
||||
private var cachedFilm: SpectralLutTable? = null
|
||||
private var cachedPrint: SpectralLutTable? = null
|
||||
@@ -175,19 +142,15 @@ object SpectralFilmProfile {
|
||||
filmStock: String,
|
||||
printPaper: String,
|
||||
tuning: SpectralFilmTuning = SpectralFilmTuning.DEFAULT,
|
||||
buildSpatialGraph: Boolean = false,
|
||||
): SpectralFilmLut? = try {
|
||||
val manifest = cachedManifest ?: loadManifest(context).also { cachedManifest = it }
|
||||
val film = requireNotNull(manifest.films[filmStock]) { "Unknown Spektrafilm stock: $filmStock" }
|
||||
val print = if (film.type == "negative") {
|
||||
val normalized = tuning.normalized()
|
||||
val positive = film.type == "positive"
|
||||
val print = if (!positive && !normalized.scanFilm) {
|
||||
requireNotNull(manifest.prints[printPaper]) { "Unknown Spektrafilm print: $printPaper" }
|
||||
} else null
|
||||
val normalized = tuning.normalized()
|
||||
val gains = if (print != null) floatArrayOf(
|
||||
normalized.negativeFilmDensityGainC(),
|
||||
normalized.negativeFilmDensityGainM(),
|
||||
normalized.negativeFilmDensityGainY(),
|
||||
) else floatArrayOf(1f, 1f, 1f)
|
||||
require(gains.all { it.isFinite() && it in 0.5f..1.5f }) { "Invalid Spektrafilm density gains" }
|
||||
val request = SpectralRuntimeRequest(
|
||||
algorithm = manifest.algorithm,
|
||||
upstreamCommit = manifest.upstreamCommit,
|
||||
@@ -198,10 +161,15 @@ object SpectralFilmProfile {
|
||||
film = film.model,
|
||||
paperName = if (print != null) printPaper else "",
|
||||
paper = print?.model,
|
||||
positive = print == null,
|
||||
positive = positive,
|
||||
stock = filmStock,
|
||||
tuning = normalized,
|
||||
buildSpatialGraph = buildSpatialGraph,
|
||||
)
|
||||
val selectionKey = "${request.filmKey}:${request.printKey}:${gains.joinToString()}"
|
||||
cachedSelection?.takeIf { it.sourceKey == selectionKey } ?: run {
|
||||
val selectionKey = "${request.filmKey}:${request.printKey}"
|
||||
cachedSelection?.takeIf {
|
||||
it.sourceKey == selectionKey && it.tuning == normalized && it.graph?.sourceKey == request.graphKey
|
||||
} ?: run {
|
||||
// Release the old selection before loading another pair; otherwise its
|
||||
// references would keep obsolete LUT arrays alive during generation.
|
||||
cachedSelection = null
|
||||
@@ -221,12 +189,13 @@ object SpectralFilmProfile {
|
||||
printTable = stages.second,
|
||||
inputScale = manifest.inputScale,
|
||||
printInputScale = manifest.printInputScale,
|
||||
negativeDensityGains = gains,
|
||||
tuning = normalized,
|
||||
graph = stages.third,
|
||||
).also {
|
||||
cachedSelection = it
|
||||
PLog.d(TAG, "Selected Spektrafilm ${it.name}, pipeline=native-spectral-two-stage, " +
|
||||
PLog.d(TAG, "Selected Spektrafilm ${it.name}, spatial=${it.graph != null}, " +
|
||||
"filmSize=${it.size}, printSize=${it.printTable?.size ?: 0}, " +
|
||||
"densityGains=${gains.joinToString()}, upstream=${manifest.upstreamCommit}")
|
||||
"upstream=${manifest.upstreamCommit}")
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import com.google.gson.Gson
|
||||
import com.google.gson.JsonObject
|
||||
import com.google.gson.JsonParseException
|
||||
import com.google.gson.annotations.SerializedName
|
||||
|
||||
enum class SpectralDyeOrder(internal val nativeIndex: Int) {
|
||||
@SerializedName("CMY") CMY(0),
|
||||
@SerializedName("CYM") CYM(1),
|
||||
@SerializedName("MCY") MCY(2),
|
||||
@SerializedName("MYC") MYC(3),
|
||||
@SerializedName("YCM") YCM(4),
|
||||
@SerializedName("YMC") YMC(5),
|
||||
}
|
||||
|
||||
data class SpectralFilmTuning(
|
||||
@SerializedName("cameraExposureEv") val cameraExposureEv: Float = 0f,
|
||||
@SerializedName("filmGamma") val filmGamma: Float = 1f,
|
||||
@SerializedName("filmDyeOrder") val filmDyeOrder: SpectralDyeOrder = SpectralDyeOrder.CMY,
|
||||
@SerializedName("dirEnabled") val dirEnabled: Boolean = true,
|
||||
@SerializedName("dirAmount") val dirAmount: Float = 1f,
|
||||
@SerializedName("dirSameLayer") val dirSameLayer: Float = 1f,
|
||||
@SerializedName("dirInterLayer") val dirInterLayer: Float = 1f,
|
||||
@SerializedName("spectralAdaptationWindow") val spectralAdaptationWindow: Boolean = true,
|
||||
@SerializedName("spectralAdaptationSurface") val spectralAdaptationSurface: Boolean = false,
|
||||
@SerializedName("spectralBlur") val spectralBlur: Float = 0f,
|
||||
@SerializedName("inputGamutCompression") val inputGamutCompression: Boolean = true,
|
||||
@SerializedName("scanFilm") val scanFilm: Boolean = false,
|
||||
@SerializedName("printExposure") val printExposure: Float = 1f,
|
||||
@SerializedName("printDyeOrder") val printDyeOrder: SpectralDyeOrder = SpectralDyeOrder.CMY,
|
||||
@SerializedName("printExposureCompensation") val printExposureCompensation: Boolean = true,
|
||||
@SerializedName("printNormalizeExposure") val printNormalizeExposure: Boolean = true,
|
||||
@SerializedName("printYellowShift") val printYellowShift: Float = 0f,
|
||||
@SerializedName("printMagentaShift") val printMagentaShift: Float = 0f,
|
||||
@SerializedName("preflashExposure") val preflashExposure: Float = 0f,
|
||||
@SerializedName("preflashYellowShift") val preflashYellowShift: Float = 0f,
|
||||
@SerializedName("preflashMagentaShift") val preflashMagentaShift: Float = 0f,
|
||||
@SerializedName("printChemistryEnabled") val printChemistryEnabled: Boolean = false,
|
||||
@SerializedName("printGamma") val printGamma: Float = 1f,
|
||||
@SerializedName("printGammaFast") val printGammaFast: Float = 1f,
|
||||
@SerializedName("printGammaSlow") val printGammaSlow: Float = 1f,
|
||||
@SerializedName("printGammaRed") val printGammaRed: Float = 1f,
|
||||
@SerializedName("printGammaGreen") val printGammaGreen: Float = 1f,
|
||||
@SerializedName("printGammaBlue") val printGammaBlue: Float = 1f,
|
||||
@SerializedName("printDeveloperExhaustion") val printDeveloperExhaustion: Float = 0f,
|
||||
@SerializedName("scannerLensBlur") val scannerLensBlur: Float = 0f,
|
||||
@SerializedName("scannerUnsharpSigma") val scannerUnsharpSigma: Float = 0.7f,
|
||||
@SerializedName("scannerUnsharpAmount") val scannerUnsharpAmount: Float = 0f,
|
||||
@SerializedName("filmFormatMm") val filmFormatMm: Float = 35f,
|
||||
@SerializedName("cameraLensBlurUm") val cameraLensBlurUm: Float = 0f,
|
||||
@SerializedName("cameraDiffusion") val cameraDiffusion: SpectralDiffusion = SpectralDiffusion(),
|
||||
@SerializedName("enlargerDiffusion") val enlargerDiffusion: SpectralDiffusion = SpectralDiffusion(),
|
||||
@SerializedName("halation") val halation: SpectralHalation = SpectralHalation(),
|
||||
@SerializedName("grain") val grain: SpectralGrain = SpectralGrain(),
|
||||
@SerializedName("glare") val glare: SpectralGlare = SpectralGlare(),
|
||||
@SerializedName("dirMatrix") val dirMatrix: SpectralDirMatrix? = null,
|
||||
@SerializedName("dirDiffusionUm") val dirDiffusionUm: Float = 0f,
|
||||
@SerializedName("dirTailUm") val dirTailUm: Float = 200f,
|
||||
@SerializedName("dirTailWeight") val dirTailWeight: Float = 0.06f,
|
||||
@SerializedName("scanWhiteCorrection") val scanWhiteCorrection: Boolean = false,
|
||||
@SerializedName("scanWhiteLevel") val scanWhiteLevel: Float = 0.98f,
|
||||
@SerializedName("scanBlackCorrection") val scanBlackCorrection: Boolean = false,
|
||||
@SerializedName("scanBlackLevel") val scanBlackLevel: Float = 0.01f,
|
||||
@SerializedName("spectralMethod") val spectralMethod: Int = 0,
|
||||
@SerializedName("inputGamutMethod") val inputGamutMethod: Int = 0,
|
||||
@SerializedName("outputGamutMethod") val outputGamutMethod: Int = 0,
|
||||
@SerializedName("inputGamutKnee") val inputGamutKnee: SpectralKnee = SpectralKnee(),
|
||||
@SerializedName("outputGamutKnee") val outputGamutKnee: SpectralKnee = SpectralKnee(),
|
||||
) {
|
||||
fun normalized(): SpectralFilmTuning = copy(
|
||||
cameraExposureEv = cameraExposureEv.bounded(-5f, 5f, 0f),
|
||||
filmGamma = filmGamma.bounded(0.1f, 3f, 1f),
|
||||
dirAmount = dirAmount.bounded(0f, 1f, 1f),
|
||||
dirSameLayer = dirSameLayer.bounded(0f, 1f, 1f),
|
||||
dirInterLayer = dirInterLayer.bounded(0f, 1f, 1f),
|
||||
spectralBlur = spectralBlur.bounded(0f, 5f, 0f),
|
||||
printExposure = printExposure.bounded(0f, 4f, 1f),
|
||||
printYellowShift = printYellowShift.bounded(-200f, 200f, 0f),
|
||||
printMagentaShift = printMagentaShift.bounded(-200f, 200f, 0f),
|
||||
preflashExposure = preflashExposure.bounded(0f, 1f, 0f),
|
||||
preflashYellowShift = preflashYellowShift.bounded(-200f, 200f, 0f),
|
||||
preflashMagentaShift = preflashMagentaShift.bounded(-200f, 200f, 0f),
|
||||
printGamma = printGamma.bounded(0.5f, 2f, 1f),
|
||||
printGammaFast = printGammaFast.bounded(0.5f, 2f, 1f),
|
||||
printGammaSlow = printGammaSlow.bounded(0.5f, 2f, 1f),
|
||||
printGammaRed = printGammaRed.bounded(0.5f, 2f, 1f),
|
||||
printGammaGreen = printGammaGreen.bounded(0.5f, 2f, 1f),
|
||||
printGammaBlue = printGammaBlue.bounded(0.5f, 2f, 1f),
|
||||
printDeveloperExhaustion = printDeveloperExhaustion.bounded(0f, 1f, 0f),
|
||||
scannerLensBlur = scannerLensBlur.bounded(0f, 8f, 0f),
|
||||
scannerUnsharpSigma = scannerUnsharpSigma.bounded(0f, 8f, 0.7f),
|
||||
scannerUnsharpAmount = scannerUnsharpAmount.bounded(0f, 3f, 0f),
|
||||
filmFormatMm = filmFormatMm.spectralBound(8f..120f, 35f),
|
||||
cameraLensBlurUm = cameraLensBlurUm.spectralBound(0f..30f, 0f),
|
||||
cameraDiffusion = cameraDiffusion.normalized(),
|
||||
enlargerDiffusion = enlargerDiffusion.normalized(),
|
||||
halation = halation.normalized(),
|
||||
grain = grain.normalized(),
|
||||
glare = glare.normalized(),
|
||||
dirDiffusionUm = dirDiffusionUm.spectralBound(0f..40f, 0f),
|
||||
dirTailUm = dirTailUm.spectralBound(0f..400f, 200f),
|
||||
dirTailWeight = dirTailWeight.spectralBound(0f..1f, 0.06f),
|
||||
scanWhiteLevel = scanWhiteLevel.spectralBound(0f..1f, 0.98f),
|
||||
scanBlackLevel = scanBlackLevel.spectralBound(0f..1f, 0.01f),
|
||||
spectralMethod = spectralMethod.coerceIn(0, 1),
|
||||
inputGamutMethod = inputGamutMethod.coerceIn(0, 1),
|
||||
outputGamutMethod = outputGamutMethod.coerceIn(0, 5),
|
||||
inputGamutKnee = inputGamutKnee.normalized(),
|
||||
outputGamutKnee = outputGamutKnee.normalized(),
|
||||
)
|
||||
|
||||
fun encodeParameters(): String? {
|
||||
val tuning = normalized()
|
||||
return if (tuning == DEFAULT) null else gson.toJson(tuning)
|
||||
}
|
||||
|
||||
internal val hasDir: Boolean
|
||||
get() = dirEnabled && dirAmount > 0f && (dirSameLayer > 0f || dirInterLayer > 0f)
|
||||
|
||||
internal fun needsSpatialGraph(print: Boolean): Boolean =
|
||||
cameraLensBlurUm > 0f || cameraDiffusion.active || halation.enabled || grain.active ||
|
||||
halation.boostEv > 0f || (hasDir && dirDiffusionUm > 0f) ||
|
||||
(print && (enlargerDiffusion.active || glare.active)) ||
|
||||
outputGamutMethod == 1 || outputGamutMethod == 3
|
||||
|
||||
internal fun filmOptions(stock: String): FloatArray {
|
||||
val matrix = dirMatrix?.takeIf { hasDir }?.bounded(SpectralFilmStockDefaults.dirMatrix(stock))
|
||||
return floatArrayOf(
|
||||
cameraExposureEv, filmGamma, hasDir.flag,
|
||||
if (hasDir) dirAmount else 0f,
|
||||
if (hasDir) dirSameLayer else 0f,
|
||||
if (hasDir) dirInterLayer else 0f,
|
||||
spectralAdaptationWindow.flag, spectralAdaptationSurface.flag, spectralBlur, inputGamutCompression.flag,
|
||||
spectralMethod.toFloat(),
|
||||
inputGamutMethod.toFloat(), inputGamutKnee.threshold, inputGamutKnee.limit, inputGamutKnee.power,
|
||||
(matrix != null).flag,
|
||||
) + (matrix?.values() ?: FloatArray(9))
|
||||
}
|
||||
|
||||
internal fun scanOptions(correctionAvailable: Boolean): FloatArray {
|
||||
val white = correctionAvailable && scanWhiteCorrection
|
||||
val black = correctionAvailable && scanBlackCorrection
|
||||
return floatArrayOf(
|
||||
white.flag, if (white) scanWhiteLevel else 0.98f,
|
||||
black.flag, if (black) scanBlackLevel else 0.01f,
|
||||
outputGamutMethod.toFloat(), outputGamutKnee.threshold, outputGamutKnee.limit, outputGamutKnee.power,
|
||||
) + if (white || black) grain.densityMin.values() else DEFAULT.grain.densityMin.values()
|
||||
}
|
||||
|
||||
internal fun printOptions(): FloatArray = floatArrayOf(
|
||||
printExposure, if (printExposureCompensation) cameraExposureEv else 0f, printNormalizeExposure.flag,
|
||||
printMagentaShift, printYellowShift, preflashExposure,
|
||||
if (preflashExposure > 0f) preflashMagentaShift else 0f,
|
||||
if (preflashExposure > 0f) preflashYellowShift else 0f,
|
||||
if (printChemistryEnabled) printGamma else 1f,
|
||||
if (printChemistryEnabled) printGammaFast else 1f,
|
||||
if (printChemistryEnabled) printGammaSlow else 1f,
|
||||
if (printChemistryEnabled) printGammaRed else 1f,
|
||||
if (printChemistryEnabled) printGammaGreen else 1f,
|
||||
if (printChemistryEnabled) printGammaBlue else 1f,
|
||||
if (printChemistryEnabled) printDeveloperExhaustion else 0f,
|
||||
)
|
||||
|
||||
companion object {
|
||||
val DEFAULT = SpectralFilmTuning()
|
||||
private val gson = Gson()
|
||||
|
||||
fun decodeParameters(value: String?): SpectralFilmTuning {
|
||||
if (value == null) return DEFAULT
|
||||
val tuning = try {
|
||||
val parameters = gson.fromJson(value, JsonObject::class.java) ?: return DEFAULT
|
||||
parameters.removeNullFields()
|
||||
for (key in listOf("filmDyeOrder", "printDyeOrder")) {
|
||||
val dyeOrder = parameters.get(key)
|
||||
if (dyeOrder != null && (!dyeOrder.isJsonPrimitive ||
|
||||
SpectralDyeOrder.entries.none { order -> order.name == dyeOrder.asString })) {
|
||||
parameters.remove(key)
|
||||
}
|
||||
}
|
||||
gson.fromJson(parameters, SpectralFilmTuning::class.java)
|
||||
} catch (_: JsonParseException) {
|
||||
null
|
||||
}
|
||||
return tuning?.normalized() ?: DEFAULT
|
||||
}
|
||||
|
||||
private fun Float.bounded(min: Float, max: Float, default: Float): Float =
|
||||
if (isFinite()) coerceIn(min, max) else default
|
||||
|
||||
private fun JsonObject.removeNullFields() {
|
||||
val iterator = entrySet().iterator()
|
||||
while (iterator.hasNext()) {
|
||||
val field = iterator.next().value
|
||||
if (field.isJsonNull) iterator.remove()
|
||||
else if (field.isJsonObject) field.asJsonObject.removeNullFields()
|
||||
}
|
||||
}
|
||||
|
||||
private val Boolean.flag: Float get() = if (this) 1f else 0f
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import com.hinnka.mycamera.raw.SpektrafilmGraphGl.Companion.texture
|
||||
import com.hinnka.mycamera.raw.SpektrafilmGraphGl.Companion.xy
|
||||
import com.hinnka.mycamera.raw.SpektrafilmOpticsPass.FrameDiffusion
|
||||
import com.hinnka.mycamera.raw.SpektrafilmOpticsPass.Region
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
|
||||
/** Stitches the staged irradiance reductions on the global pixel grid before broad diffusion. */
|
||||
internal class SpektrafilmDiffusionAtlas(
|
||||
private val gl: SpektrafilmGraphGl,
|
||||
private val optics: SpektrafilmOpticsPass,
|
||||
) {
|
||||
/** [prepare] supplies a work-sized FP32 irradiance texture starting at texel (0, 0). */
|
||||
fun build(
|
||||
frame: Region,
|
||||
stride: Int,
|
||||
params: SpectralDiffusion,
|
||||
nativeSupport: Int,
|
||||
halation: SpectralHalation? = null,
|
||||
maxRaw: Float? = null,
|
||||
prepare: (work: RawTileRect, region: Region) -> Int?,
|
||||
): FrameDiffusion? {
|
||||
require(stride > 0 && (stride and (stride - 1)) == 0 && SEED_EDGE % stride == 0)
|
||||
require(nativeSupport >= 0)
|
||||
val atlasOriginX = frame.originX / stride
|
||||
val atlasOriginY = frame.originY / stride
|
||||
val atlasWidth = ceilDiv(frame.originX + frame.width, stride) - atlasOriginX
|
||||
val atlasHeight = ceilDiv(frame.originY + frame.height, stride) - atlasOriginY
|
||||
val columns = seedBoundaries(frame.originX, frame.width, stride)
|
||||
val rows = seedBoundaries(frame.originY, frame.height, stride)
|
||||
val startNs = System.nanoTime()
|
||||
|
||||
try {
|
||||
val atlas = gl.target(ATLAS_TARGET, atlasWidth, atlasHeight)
|
||||
try {
|
||||
for (y in 0 until rows.lastIndex) for (x in 0 until columns.lastIndex) {
|
||||
val seed = RawTileRect(columns[x], rows[y], columns[x + 1], rows[y + 1])
|
||||
val work = expand(frame, seed, nativeSupport)
|
||||
val source = prepare(work, frame.regionFor(work)) ?: return null
|
||||
val seedTexture = if (work == seed) source else trim(source, work, seed)
|
||||
val seedRegion = frame.regionFor(seed)
|
||||
val reduced = optics.reduceDiffusionInput(seedTexture, seedRegion, stride, halation, maxRaw)
|
||||
val reducedX = seedRegion.originX / stride
|
||||
val reducedY = seedRegion.originY / stride
|
||||
check(reduced.originX == reducedX && reduced.originY == reducedY && reduced.stride == stride &&
|
||||
reduced.width == ceilDiv(seedRegion.originX + seed.width, stride) - reducedX &&
|
||||
reduced.height == ceilDiv(seedRegion.originY + seed.height, stride) - reducedY
|
||||
) { "Spektrafilm reduced diffusion seed does not match its global grid" }
|
||||
val left = reducedX - atlasOriginX
|
||||
val top = reducedY - atlasOriginY
|
||||
gl.draw(
|
||||
COPY_PROGRAM, COPY_WINDOW, atlas.framebuffer, left, top, reduced.width, reduced.height,
|
||||
) { program ->
|
||||
texture(program, "uSource", 0, reduced.texture)
|
||||
xy(program, "uOffset", -left, -top)
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
gl.releaseTarget(TRIM_TARGET)
|
||||
}
|
||||
|
||||
return optics.buildFrameDiffusion(atlas.texture, frame, stride, params).also {
|
||||
PLog.i(
|
||||
TAG,
|
||||
"Spektrafilm diffusion atlas=${atlasWidth}x$atlasHeight stride=$stride " +
|
||||
"seeds=${columns.lastIndex * rows.lastIndex} input=${frame.width}x${frame.height} " +
|
||||
"origin=${frame.originX},${frame.originY} nativeSupport=$nativeSupport " +
|
||||
"submitMs=${(System.nanoTime() - startNs) / 1_000_000}",
|
||||
)
|
||||
}
|
||||
} finally {
|
||||
gl.releaseTarget(ATLAS_TARGET)
|
||||
}
|
||||
}
|
||||
|
||||
private fun trim(source: Int, work: RawTileRect, seed: RawTileRect): Int {
|
||||
val target = gl.target(TRIM_TARGET, seed.width, seed.height)
|
||||
gl.draw(COPY_PROGRAM, COPY_WINDOW, target) { program ->
|
||||
texture(program, "uSource", 0, source)
|
||||
xy(program, "uOffset", seed.left - work.left, seed.top - work.top)
|
||||
}
|
||||
return target.texture
|
||||
}
|
||||
|
||||
private fun Region.regionFor(rect: RawTileRect): Region = copy(
|
||||
width = rect.width, height = rect.height, originX = originX + rect.left, originY = originY + rect.top,
|
||||
)
|
||||
|
||||
private fun expand(frame: Region, seed: RawTileRect, support: Int): RawTileRect = RawTileRect(
|
||||
seed.left - minOf(seed.left, support),
|
||||
seed.top - minOf(seed.top, support),
|
||||
seed.right + minOf(frame.width - seed.right, support),
|
||||
seed.bottom + minOf(frame.height - seed.bottom, support),
|
||||
)
|
||||
|
||||
private fun seedBoundaries(origin: Int, length: Int, stride: Int): List<Int> = buildList {
|
||||
add(0)
|
||||
var cut = SEED_EDGE - origin % SEED_EDGE
|
||||
while (cut < length) {
|
||||
// Whole-sample BOX reflection at an odd frame edge may read into the adjacent cell.
|
||||
// Keep a clipped edge fragment with its neighbor if it is shorter than one cell.
|
||||
if (cut >= stride && length - cut >= stride) add(cut)
|
||||
cut += SEED_EDGE
|
||||
}
|
||||
add(length)
|
||||
}
|
||||
|
||||
private fun ceilDiv(value: Int, divisor: Int): Int =
|
||||
value / divisor + if (value % divisor == 0) 0 else 1
|
||||
|
||||
companion object {
|
||||
private const val TAG = "SpektrafilmDiffusionAtlas"
|
||||
private const val SEED_EDGE = 768
|
||||
private const val ATLAS_TARGET = "diffusionSeedAtlas"
|
||||
private const val TRIM_TARGET = "diffusionSeedTrim"
|
||||
private const val COPY_PROGRAM = "diffusionSeedCopy"
|
||||
private const val COPY_WINDOW = """
|
||||
uniform sampler2D uSource;
|
||||
uniform ivec2 uOffset;
|
||||
|
||||
void main() {
|
||||
fragColor = texelFetch(uSource, ivec2(gl_FragCoord.xy) + uOffset, 0);
|
||||
}
|
||||
"""
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import android.opengl.GLES30
|
||||
import com.hinnka.mycamera.raw.SpektrafilmGraphGl.Companion.float
|
||||
import com.hinnka.mycamera.raw.SpektrafilmGraphGl.Companion.int
|
||||
import com.hinnka.mycamera.raw.SpektrafilmGraphGl.Companion.rgb
|
||||
import com.hinnka.mycamera.raw.SpektrafilmGraphGl.Companion.texture
|
||||
import com.hinnka.mycamera.raw.SpektrafilmGraphGl.Companion.xy
|
||||
import com.hinnka.mycamera.raw.SpektrafilmOpticsKernels.ZERO
|
||||
import kotlin.math.sqrt
|
||||
|
||||
/** Develops grain in the film density domain before the enlarger or direct scan. */
|
||||
internal class SpektrafilmGrainPass(
|
||||
private val gl: SpektrafilmGraphGl,
|
||||
private val optics: SpektrafilmOpticsPass,
|
||||
) {
|
||||
fun render(
|
||||
density: SpektrafilmGraphGl.Surface,
|
||||
region: SpektrafilmOpticsPass.Region,
|
||||
graph: SpectralFilmGraph,
|
||||
params: SpectralGrain,
|
||||
): Int {
|
||||
if (!params.active) return density.texture
|
||||
val plan = GrainPlan.from(region, graph, params)
|
||||
val particles = gl.target("grainParticles", region.width, region.height, GLES30.GL_RGBA16F)
|
||||
val sumA = gl.target("grainSumA", region.width, region.height, GLES30.GL_RGBA16F)
|
||||
val prepared = if (params.sublayers) {
|
||||
val sumB = gl.target("grainSumB", region.width, region.height, GLES30.GL_RGBA16F)
|
||||
var sum = sumA
|
||||
for ((index, layer) in plan.layers.withIndex()) {
|
||||
drawParticles(density, particles, region, graph, params, layer, index, subLayers = 1)
|
||||
val blurred = optics.gaussian(particles.texture, region, layer.dyeSigma)
|
||||
if (index == 0) {
|
||||
gl.copy(blurred, sum)
|
||||
} else {
|
||||
val next = if (sum === sumA) sumB else sumA
|
||||
gl.draw("grainCombine", SpektrafilmGraphShaders.GRAIN_COMBINE, next) { program ->
|
||||
texture(program, "uAccumulated", 0, sum.texture)
|
||||
texture(program, "uLayer", 1, blurred)
|
||||
}
|
||||
sum = next
|
||||
}
|
||||
}
|
||||
val noise = if (plan.microSigma > 0f) {
|
||||
val noiseTarget = if (sum === sumA) sumB else sumA
|
||||
gl.draw("grainMicro", SpektrafilmGraphShaders.GRAIN_MICRO, noiseTarget) { program ->
|
||||
xy(program, "uOrigin", region.originX, region.originY)
|
||||
float(program, "uSigma", plan.microSigma)
|
||||
}
|
||||
optics.gaussian(noiseTarget.texture, region, plan.microBlur)
|
||||
} else 0
|
||||
finish(sum.texture, noise, particles, params.densityMin)
|
||||
particles.texture
|
||||
} else {
|
||||
gl.releaseTarget("grainSumB")
|
||||
drawParticles(density, particles, region, graph, params, plan.layers.single(), -1, params.subLayerCount)
|
||||
finish(particles.texture, 0, sumA, params.densityMin)
|
||||
sumA.texture
|
||||
}
|
||||
return optics.gaussian(prepared, region, plan.finalBlur)
|
||||
}
|
||||
|
||||
fun releaseTargets() {
|
||||
gl.releaseTarget("grainParticles")
|
||||
gl.releaseTarget("grainSumA")
|
||||
gl.releaseTarget("grainSumB")
|
||||
}
|
||||
|
||||
private fun drawParticles(
|
||||
source: SpektrafilmGraphGl.Surface,
|
||||
destination: SpektrafilmGraphGl.Surface,
|
||||
region: SpektrafilmOpticsPass.Region,
|
||||
graph: SpectralFilmGraph,
|
||||
params: SpectralGrain,
|
||||
layer: Layer,
|
||||
index: Int,
|
||||
subLayers: Int,
|
||||
) {
|
||||
gl.draw("grainParticles", SpektrafilmGraphShaders.GRAIN, destination) { program ->
|
||||
texture(program, "uSource", 0, source.texture)
|
||||
gl.tables.filmCurves.bind(program, "uCurves", 1)
|
||||
int(program, "uCurveWidth", graph.filmCurveSize)
|
||||
rgb(program, "uMin", layer.minimum)
|
||||
rgb(program, "uMax", layer.maximum)
|
||||
rgb(program, "uCount", layer.particleCount)
|
||||
rgb(program, "uUniformity", params.uniformity)
|
||||
float(program, "uSign", if (graph.positive) -1f else 1f)
|
||||
int(program, "uLayer", index)
|
||||
int(program, "uSubLayerCount", subLayers)
|
||||
xy(program, "uOrigin", region.originX, region.originY)
|
||||
}
|
||||
}
|
||||
|
||||
private fun finish(source: Int, noise: Int, target: SpektrafilmGraphGl.Surface, minimum: SpectralRgb) {
|
||||
gl.draw("grainFinish", SpektrafilmGraphShaders.GRAIN_FINISH, target) { program ->
|
||||
texture(program, "uSource", 0, source)
|
||||
texture(program, "uMicro", 1, if (noise != 0) noise else source)
|
||||
rgb(program, "uMinimum", minimum)
|
||||
int(program, "uUseMicro", if (noise != 0) 1 else 0)
|
||||
}
|
||||
}
|
||||
|
||||
private data class Layer(
|
||||
val minimum: SpectralRgb,
|
||||
val maximum: SpectralRgb,
|
||||
val particleCount: SpectralRgb,
|
||||
val dyeSigma: SpectralRgb,
|
||||
)
|
||||
|
||||
private data class GrainPlan(
|
||||
val layers: List<Layer>,
|
||||
val microSigma: Float,
|
||||
val microBlur: Float,
|
||||
val finalBlur: Float,
|
||||
) {
|
||||
companion object {
|
||||
fun from(region: SpektrafilmOpticsPass.Region, graph: SpectralFilmGraph, params: SpectralGrain): GrainPlan {
|
||||
val pitch = region.pixelSizeUm
|
||||
val area = pitch * pitch / params.particleAreaUm2
|
||||
val scale = params.particleScale.values()
|
||||
val minimum = params.densityMin.values()
|
||||
if (!params.sublayers) {
|
||||
val maximum = graph.densityMax.values()
|
||||
val layer = Layer(
|
||||
params.densityMin,
|
||||
rgbByChannel { maximum[it] + minimum[it] },
|
||||
rgbByChannel { area / (scale[it] * params.subLayerCount) },
|
||||
ZERO,
|
||||
)
|
||||
return GrainPlan(listOf(layer), 0f, 0f, params.blur.takeIf { it > 0.4f } ?: 0f)
|
||||
}
|
||||
|
||||
check(graph.filmCurveRows == 5) { "Spektrafilm grain layer tables are missing" }
|
||||
val maxima = graph.layerMax.map(SpectralRgb::values)
|
||||
val totals = FloatArray(3) { c -> maxima[0][c] + maxima[1][c] + maxima[2][c] }
|
||||
val layerScales = params.particleScaleLayers.values()
|
||||
val layers = maxima.mapIndexed { index, maximum ->
|
||||
val fractions = FloatArray(3) { c -> if (totals[c] > 0f) maximum[c] / totals[c] else 0f }
|
||||
val floor = FloatArray(3) { c -> minimum[c] * fractions[c] }
|
||||
val ceiling = FloatArray(3) { c -> maximum[c] + floor[c] }
|
||||
val counts = FloatArray(3) { c -> area * fractions[c] / (scale[c] * layerScales[index]) }
|
||||
Layer(
|
||||
rgbByChannel { floor[it] },
|
||||
rgbByChannel { ceiling[it] },
|
||||
rgbByChannel { counts[it] },
|
||||
rgbByChannel { c ->
|
||||
if (counts[c] > 0f) params.blurDyeCloudsUm * sqrt(ceiling[c] / counts[c]) else 0f
|
||||
},
|
||||
)
|
||||
}
|
||||
val microSigma = (params.microClumpNm * 0.001f / pitch).takeIf { it > 0.05f } ?: 0f
|
||||
val microBlur = (params.microBlurUm / pitch).takeIf { microSigma > 0f && it > 0.4f } ?: 0f
|
||||
return GrainPlan(layers, microSigma, microBlur, params.blur)
|
||||
}
|
||||
|
||||
private inline fun rgbByChannel(value: (Int) -> Float) = SpectralRgb(value(0), value(1), value(2))
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun support(region: SpektrafilmOpticsPass.Region, graph: SpectralFilmGraph, params: SpectralGrain): Int {
|
||||
if (!params.active) return 0
|
||||
val plan = GrainPlan.from(region, graph, params)
|
||||
val dyeSupport = plan.layers.maxOf { SpektrafilmOpticsPass.gaussianSupport(it.dyeSigma) }
|
||||
return maxOf(dyeSupport, SpektrafilmOpticsPass.gaussianSupport(plan.microBlur)) +
|
||||
SpektrafilmOpticsPass.gaussianSupport(plan.finalBlur)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import android.opengl.GLES30
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
|
||||
internal class SpektrafilmGraphGl(private val quad: RawFullscreenQuad) {
|
||||
private val programs = mutableMapOf<String, Int>()
|
||||
private val targets = mutableMapOf<String, Surface>()
|
||||
val tables = Tables()
|
||||
|
||||
fun target(name: String, width: Int, height: Int, format: Int = GLES30.GL_RGBA32F): Surface =
|
||||
targets.getOrPut(name) { Surface() }.apply { ensure(width, height, format) }
|
||||
|
||||
fun draw(
|
||||
name: String, shader: String, surface: Surface,
|
||||
bind: (Int) -> Unit,
|
||||
) = draw(name, shader, surface.framebuffer, 0, 0, surface.width, surface.height, bind)
|
||||
|
||||
fun draw(
|
||||
name: String, shader: String, framebuffer: Int, x: Int, y: Int, width: Int, height: Int,
|
||||
bind: (Int) -> Unit,
|
||||
) {
|
||||
val program = programs.getOrPut(name) {
|
||||
quad.createProgram("$HEADER\n$shader", "Spektrafilm $name").also {
|
||||
check(it != 0) { "Cannot create Spektrafilm $name shader" }
|
||||
}
|
||||
}
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, framebuffer)
|
||||
GLES30.glViewport(x, y, width, height)
|
||||
GLES30.glUseProgram(program)
|
||||
GLES30.glDisable(GLES30.GL_BLEND)
|
||||
bind(program)
|
||||
quad.bindIdentityTextureMatrix(program)
|
||||
quad.draw(program)
|
||||
val error = GLES30.glGetError()
|
||||
check(error == GLES30.GL_NO_ERROR) { "Spektrafilm $name draw failed, GL error=0x${error.toString(16)}" }
|
||||
}
|
||||
|
||||
fun copy(source: Int, target: Surface) {
|
||||
if (source == target.texture) return
|
||||
draw("copy", COPY, target) { texture(it, "uSource", 0, source) }
|
||||
}
|
||||
|
||||
fun release() {
|
||||
programs.values.forEach(GLES30::glDeleteProgram)
|
||||
programs.clear()
|
||||
releaseTargets()
|
||||
tables.release()
|
||||
}
|
||||
|
||||
fun releaseTargets() {
|
||||
targets.values.forEach(Surface::release)
|
||||
targets.clear()
|
||||
}
|
||||
|
||||
fun releaseTarget(name: String) {
|
||||
targets.remove(name)?.release()
|
||||
}
|
||||
|
||||
class Surface {
|
||||
var texture = 0
|
||||
private set
|
||||
var framebuffer = 0
|
||||
private set
|
||||
var width = 0
|
||||
private set
|
||||
var height = 0
|
||||
private set
|
||||
private var internalFormat = 0
|
||||
|
||||
fun ensure(width: Int, height: Int, format: Int) {
|
||||
if (this.width == width && this.height == height && internalFormat == format) return
|
||||
release()
|
||||
try {
|
||||
texture = IntArray(1).also { GLES30.glGenTextures(1, it, 0) }[0]
|
||||
framebuffer = IntArray(1).also { GLES30.glGenFramebuffers(1, it, 0) }[0]
|
||||
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, texture)
|
||||
GLES30.glTexStorage2D(GLES30.GL_TEXTURE_2D, 1, format, width, height)
|
||||
configure(GLES30.GL_TEXTURE_2D, GLES30.GL_NEAREST)
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, framebuffer)
|
||||
GLES30.glFramebufferTexture2D(
|
||||
GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, texture, 0,
|
||||
)
|
||||
val error = GLES30.glGetError()
|
||||
check(texture != 0 && framebuffer != 0 && error == GLES30.GL_NO_ERROR &&
|
||||
GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER) == GLES30.GL_FRAMEBUFFER_COMPLETE
|
||||
) { "Unable to allocate Spektrafilm ${width}x$height target, GL error=$error" }
|
||||
this.width = width
|
||||
this.height = height
|
||||
internalFormat = format
|
||||
} catch (failure: Throwable) {
|
||||
release()
|
||||
throw failure
|
||||
}
|
||||
}
|
||||
|
||||
fun release() {
|
||||
if (texture != 0) GLES30.glDeleteTextures(1, intArrayOf(texture), 0)
|
||||
if (framebuffer != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(framebuffer), 0)
|
||||
texture = 0
|
||||
framebuffer = 0
|
||||
width = 0
|
||||
height = 0
|
||||
internalFormat = 0
|
||||
}
|
||||
}
|
||||
|
||||
class Tables {
|
||||
val filmExposure = Table(GLES30.GL_TEXTURE_3D)
|
||||
val filmCurves = Table(GLES30.GL_TEXTURE_2D)
|
||||
val paperExposure = Table(GLES30.GL_TEXTURE_3D)
|
||||
val paperCurves = Table(GLES30.GL_TEXTURE_2D)
|
||||
val scan = Table(GLES30.GL_TEXTURE_3D)
|
||||
val gamut = Table(GLES30.GL_TEXTURE_3D)
|
||||
private var key: String? = null
|
||||
|
||||
fun prepare(graph: SpectralFilmGraph) {
|
||||
if (key == graph.sourceKey) return
|
||||
release()
|
||||
try {
|
||||
filmExposure.upload(graph.filmExposure, graph.size)
|
||||
filmCurves.upload(graph.filmCurves, graph.filmCurveSize, graph.filmCurveRows)
|
||||
if (graph.printing) {
|
||||
paperExposure.upload(graph.paperExposure, graph.size)
|
||||
paperCurves.upload(graph.paperCurves, graph.paperCurves.size / 4, 1)
|
||||
}
|
||||
scan.upload(graph.scan, graph.size)
|
||||
if (graph.usesGlare) gamut.upload(graph.gamut, graph.size)
|
||||
key = graph.sourceKey
|
||||
} catch (failure: Throwable) {
|
||||
release()
|
||||
throw failure
|
||||
}
|
||||
}
|
||||
|
||||
fun release() {
|
||||
listOf(filmExposure, filmCurves, paperExposure, paperCurves, scan, gamut).forEach(Table::release)
|
||||
key = null
|
||||
}
|
||||
}
|
||||
|
||||
class Table(private val target: Int) {
|
||||
private var texture = 0
|
||||
|
||||
fun bind(program: Int, label: String, unit: Int) {
|
||||
check(texture != 0)
|
||||
texture(program, label, unit, texture, target)
|
||||
}
|
||||
|
||||
fun upload(values: FloatArray, width: Int, height: Int = width) {
|
||||
val cube = target == GLES30.GL_TEXTURE_3D
|
||||
texture = IntArray(1).also { GLES30.glGenTextures(1, it, 0) }[0]
|
||||
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
|
||||
GLES30.glBindTexture(target, texture)
|
||||
configure(target, if (cube) GLES30.GL_LINEAR else GLES30.GL_NEAREST)
|
||||
GLES30.glBindBuffer(GLES30.GL_PIXEL_UNPACK_BUFFER, 0)
|
||||
GLES30.glPixelStorei(GLES30.GL_UNPACK_ALIGNMENT, 4)
|
||||
GLES30.glPixelStorei(GLES30.GL_UNPACK_ROW_LENGTH, 0)
|
||||
GLES30.glPixelStorei(GLES30.GL_UNPACK_IMAGE_HEIGHT, 0)
|
||||
GLES30.glPixelStorei(GLES30.GL_UNPACK_SKIP_PIXELS, 0)
|
||||
GLES30.glPixelStorei(GLES30.GL_UNPACK_SKIP_ROWS, 0)
|
||||
GLES30.glPixelStorei(GLES30.GL_UNPACK_SKIP_IMAGES, 0)
|
||||
val data = ByteBuffer.allocateDirect(values.size * Float.SIZE_BYTES).order(ByteOrder.nativeOrder())
|
||||
.asFloatBuffer().apply { put(values); position(0) }
|
||||
if (cube) {
|
||||
GLES30.glTexImage3D(target, 0, GLES30.GL_RGBA16F, width, width, width, 0, GLES30.GL_RGBA, GLES30.GL_FLOAT, data)
|
||||
} else {
|
||||
GLES30.glTexImage2D(target, 0, GLES30.GL_RGBA32F, width, height, 0, GLES30.GL_RGBA, GLES30.GL_FLOAT, data)
|
||||
}
|
||||
val error = GLES30.glGetError()
|
||||
check(texture != 0 && error == GLES30.GL_NO_ERROR) { "Unable to upload Spektrafilm table, GL error=$error" }
|
||||
}
|
||||
|
||||
fun release() {
|
||||
if (texture != 0) GLES30.glDeleteTextures(1, intArrayOf(texture), 0)
|
||||
texture = 0
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val HEADER = """#version 300 es
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
precision highp sampler2D;
|
||||
precision highp sampler3D;
|
||||
out vec4 fragColor;"""
|
||||
|
||||
private val COPY = """
|
||||
uniform sampler2D uSource;
|
||||
void main() {
|
||||
fragColor = texelFetch(uSource, ivec2(gl_FragCoord.xy), 0);
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
fun location(program: Int, name: String) = GLES30.glGetUniformLocation(program, name)
|
||||
fun float(program: Int, name: String, value: Float) = GLES30.glUniform1f(location(program, name), value)
|
||||
fun int(program: Int, name: String, value: Int) = GLES30.glUniform1i(location(program, name), value)
|
||||
fun xy(program: Int, name: String, x: Int, y: Int) = GLES30.glUniform2i(location(program, name), x, y)
|
||||
fun rgb(program: Int, name: String, value: SpectralRgb) =
|
||||
GLES30.glUniform3f(location(program, name), value.r, value.g, value.b)
|
||||
fun matrix(program: Int, name: String, rowMajor: FloatArray) = GLES30.glUniformMatrix3fv(
|
||||
location(program, name), 1, false, RawToneMappingGl.transposeMatrix3x3(rowMajor), 0,
|
||||
)
|
||||
|
||||
fun texture(program: Int, name: String, unit: Int, texture: Int, target: Int = GLES30.GL_TEXTURE_2D) {
|
||||
GLES30.glActiveTexture(GLES30.GL_TEXTURE0 + unit)
|
||||
GLES30.glBindTexture(target, texture)
|
||||
int(program, name, unit)
|
||||
}
|
||||
|
||||
private fun configure(target: Int, filter: Int) {
|
||||
GLES30.glTexParameteri(target, GLES30.GL_TEXTURE_MIN_FILTER, filter)
|
||||
GLES30.glTexParameteri(target, GLES30.GL_TEXTURE_MAG_FILTER, filter)
|
||||
GLES30.glTexParameteri(target, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_CLAMP_TO_EDGE)
|
||||
GLES30.glTexParameteri(target, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE)
|
||||
if (target == GLES30.GL_TEXTURE_3D) GLES30.glTexParameteri(target, GLES30.GL_TEXTURE_WRAP_R, GLES30.GL_CLAMP_TO_EDGE)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
internal object SpektrafilmGraphShaders {
|
||||
private val SOURCE = """
|
||||
uniform sampler2D uSource;
|
||||
ivec2 pixel() { return ivec2(gl_FragCoord.xy); }
|
||||
vec3 source() { return texelFetch(uSource, pixel(), 0).rgb; }
|
||||
""".trimIndent()
|
||||
|
||||
private val CUBE = """
|
||||
uniform sampler3D uCube;
|
||||
uniform float uSize;
|
||||
vec3 sampleCube(sampler3D data, vec3 code) {
|
||||
return texture(data, (clamp(code, 0.0, 1.0) * (uSize - 1.0) + 0.5) / uSize).rgb;
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
private val FILM_CURVE = """
|
||||
uniform sampler2D uCurves;
|
||||
uniform int uCurveWidth;
|
||||
|
||||
vec4 filmCurve(int i, int row) {
|
||||
return texelFetch(uCurves, ivec2(i, row), 0);
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
private val DEVELOPMENT = """
|
||||
$SOURCE
|
||||
$FILM_CURVE
|
||||
uniform vec3 uGamma;
|
||||
uniform float uExposureCorrection;
|
||||
|
||||
float density(float exposure, int channel, int row) {
|
||||
int low = 0;
|
||||
int high = uCurveWidth - 1;
|
||||
if (exposure <= filmCurve(low, 0).a) return filmCurve(low, row)[channel];
|
||||
if (exposure >= filmCurve(high, 0).a) return filmCurve(high, row)[channel];
|
||||
while (high - low > 1) {
|
||||
int middle = (high + low) / 2;
|
||||
if (filmCurve(middle, 0).a <= exposure) low = middle;
|
||||
else high = middle;
|
||||
}
|
||||
float x0 = filmCurve(low, 0).a;
|
||||
float x1 = filmCurve(high, 0).a;
|
||||
return mix(filmCurve(low, row)[channel], filmCurve(high, row)[channel], (exposure - x0) / (x1 - x0));
|
||||
}
|
||||
|
||||
vec3 develop(vec3 logExposure, int row) {
|
||||
vec3 x = uGamma * logExposure;
|
||||
return vec3(density(x.r, 0, row), density(x.g, 1, row), density(x.b, 2, row));
|
||||
}
|
||||
|
||||
vec3 logRaw() {
|
||||
return log2(max(source() * uExposureCorrection, 0.0) + 1.0e-10) * 0.30102999566;
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
val DIR = """
|
||||
$DEVELOPMENT
|
||||
uniform vec3 uDensityMax;
|
||||
uniform mat3 uDirMatrix;
|
||||
uniform int uPositive;
|
||||
|
||||
void main() {
|
||||
vec3 density = develop(logRaw(), 0);
|
||||
vec3 silver = uPositive != 0 ? uDensityMax - density : density;
|
||||
fragColor = vec4(silver * uDirMatrix, 1.0);
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
val DEVELOP = """
|
||||
$DEVELOPMENT
|
||||
uniform sampler2D uInhibitor;
|
||||
uniform int uUseDir;
|
||||
|
||||
void main() {
|
||||
vec3 exposure = logRaw();
|
||||
if (uUseDir != 0) exposure -= texelFetch(uInhibitor, pixel(), 0).rgb;
|
||||
fragColor = vec4(develop(exposure, uUseDir), 1.0);
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
val ENLARGE = """
|
||||
$SOURCE
|
||||
$CUBE
|
||||
uniform vec3 uLow;
|
||||
uniform vec3 uHigh;
|
||||
|
||||
void main() {
|
||||
vec3 logExposure = sampleCube(uCube, (source() - uLow) / (uHigh - uLow));
|
||||
fragColor = vec4(pow(vec3(10.0), logExposure), 1.0);
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
val PAPER = """
|
||||
$SOURCE
|
||||
uniform sampler2D uCurves;
|
||||
|
||||
float curve(float logExposure, int channel) {
|
||||
// The native paper table spans log10 exposure [-10, 6].
|
||||
float position = 4095.0 * clamp((logExposure + 10.0) / 16.0, 0.0, 1.0);
|
||||
int index = int(position);
|
||||
float a = texelFetch(uCurves, ivec2(index, 0), 0)[channel];
|
||||
float b = texelFetch(uCurves, ivec2(min(index + 1, 4095), 0), 0)[channel];
|
||||
return mix(a, b, fract(position));
|
||||
}
|
||||
|
||||
void main() {
|
||||
vec3 logExposure = log2(max(source(), vec3(1.0e-10))) * 0.30102999566;
|
||||
fragColor = vec4(curve(logExposure.r, 0), curve(logExposure.g, 1), curve(logExposure.b, 2), 1.0);
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
fun scan(glare: Boolean, linear: Boolean): String = """
|
||||
$SOURCE
|
||||
$CUBE
|
||||
uniform vec3 uLow;
|
||||
uniform vec3 uHigh;
|
||||
${if (glare) """
|
||||
uniform sampler2D uGlare;
|
||||
uniform sampler3D uGamut;
|
||||
uniform vec3 uWhite;
|
||||
uniform vec3 uGamutLow;
|
||||
uniform vec3 uGamutHigh;
|
||||
""" else ""}
|
||||
|
||||
vec3 decode(vec3 code) {
|
||||
return mix(code / 16.0, pow(code, vec3(1.8)), step(vec3(0.03125), code));
|
||||
}
|
||||
|
||||
void main() {
|
||||
vec3 result = sampleCube(uCube, (source() - uLow) / max(uHigh - uLow, vec3(1.0e-10)));
|
||||
${if (glare) """
|
||||
result += texelFetch(uGlare, pixel(), 0).r * uWhite;
|
||||
result = sampleCube(uGamut, (result - uGamutLow) / (uGamutHigh - uGamutLow));
|
||||
""" else ""}
|
||||
fragColor = vec4(${if (linear) "result" else "decode(result)"}, 1.0);
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
val FINISH = """
|
||||
uniform sampler2D uSource;
|
||||
uniform sampler2D uUnsharp;
|
||||
uniform ivec2 uSourceOffset;
|
||||
uniform mat3 uOutputTransform;
|
||||
uniform float uUnsharpAmount;
|
||||
|
||||
void main() {
|
||||
ivec2 p = ivec2(gl_FragCoord.xy) + uSourceOffset;
|
||||
vec3 value = texelFetch(uSource, p, 0).rgb;
|
||||
if (uUnsharpAmount > 0.0) value += uUnsharpAmount * (value - texelFetch(uUnsharp, p, 0).rgb);
|
||||
fragColor = vec4(uOutputTransform * value, 1.0);
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
val FILM_EXPOSURE = RawEngineToneShaderDefinition(
|
||||
engineUniforms = """
|
||||
uniform highp sampler3D uFilmExposure;
|
||||
uniform float uSpectralInputScale;
|
||||
uniform float uCameraExposureGain;
|
||||
uniform float uSize;
|
||||
""".trimIndent(),
|
||||
engineFunctions = """
|
||||
vec3 applyEngineTone(vec3 color) {
|
||||
vec3 linear = max(color / uSpectralInputScale, vec3(0.0));
|
||||
vec3 code = mix(linear * 16.0, pow(linear, vec3(1.0 / 1.8)), step(vec3(0.001953125), linear));
|
||||
vec3 p = (clamp(code, 0.0, 1.0) * (uSize - 1.0) + 0.5) / uSize;
|
||||
return texture(uFilmExposure, p).rgb * uCameraExposureGain;
|
||||
}
|
||||
""".trimIndent(),
|
||||
includeAdobeProfilePipeline = false,
|
||||
)
|
||||
|
||||
val GRAIN = """
|
||||
$SOURCE
|
||||
$FILM_CURVE
|
||||
uniform vec3 uMin;
|
||||
uniform vec3 uMax;
|
||||
uniform vec3 uCount;
|
||||
uniform vec3 uUniformity;
|
||||
uniform float uSign;
|
||||
uniform int uLayer;
|
||||
uniform int uSubLayerCount;
|
||||
uniform ivec2 uOrigin;
|
||||
|
||||
uint hash(uint n) {
|
||||
n = (n ^ (n >> 16u)) * 0x7feb352du;
|
||||
n = (n ^ (n >> 15u)) * 0x846ca68bu;
|
||||
return n ^ (n >> 16u);
|
||||
}
|
||||
|
||||
float random(inout uint state) {
|
||||
state = hash(state + 0x9e3779b9u);
|
||||
return (float(state >> 9u) + 0.5) * (1.0 / 8388608.0);
|
||||
}
|
||||
|
||||
float logFactorial(float n) {
|
||||
if (n < 2.0) return 0.0;
|
||||
if (n < 8.0) {
|
||||
float result = 0.0;
|
||||
for (float k = 2.0; k <= n; k++) result += log(k);
|
||||
return result;
|
||||
}
|
||||
float inv = 1.0 / n;
|
||||
return (n + 0.5) * log(n) - n + 0.9189385332 + inv / 12.0 - inv * inv * inv / 360.0;
|
||||
}
|
||||
|
||||
// Binomial thinning of a Poisson population is itself Poisson.
|
||||
// Inverse transform at low rates and transformed rejection at high rates.
|
||||
float poisson(float mean, inout uint state) {
|
||||
if (mean < 10.0) {
|
||||
float stop = exp(-mean);
|
||||
float product = random(state);
|
||||
float count = 0.0;
|
||||
while (product > stop) {
|
||||
count += 1.0;
|
||||
product *= random(state);
|
||||
}
|
||||
return count;
|
||||
}
|
||||
float b = 0.931 + 2.53 * sqrt(mean);
|
||||
float a = -0.059 + 0.02483 * b;
|
||||
float invAlpha = 1.1239 + 1.1328 / (b - 3.4);
|
||||
float vr = 0.9277 - 3.6224 / (b - 2.0);
|
||||
while (true) {
|
||||
float u = random(state) - 0.5;
|
||||
float v = random(state);
|
||||
float us = 0.5 - abs(u);
|
||||
float k = floor((2.0 * a / us + b) * u + mean + 0.43);
|
||||
if (k < 0.0 || (us < 0.013 && v > us)) continue;
|
||||
if (us >= 0.07 && v <= vr) return k;
|
||||
// Centered form avoids cancellation when individual log terms are large.
|
||||
float base = -mean + k * log(mean) - logFactorial(k);
|
||||
if (k >= 64.0) {
|
||||
float ratio = (k - mean) / mean;
|
||||
float logRatio = abs(ratio) < 0.02 ?
|
||||
ratio * (1.0 + ratio * (-0.5 + ratio / 3.0)) : log(k / mean);
|
||||
base = (k - mean) - k * logRatio - 0.5 * log(k) - 0.9189385332 - 1.0 / (12.0 * k);
|
||||
}
|
||||
if (log(v * invAlpha / (a / (us * us) + b)) <= base) return k;
|
||||
}
|
||||
}
|
||||
|
||||
float layerDensity(float density, int channel) {
|
||||
int row = 2 + uLayer;
|
||||
float value = uSign * density;
|
||||
int low = 0;
|
||||
int high = uCurveWidth - 1;
|
||||
if (value <= uSign * filmCurve(low, 0)[channel]) return filmCurve(low, row)[channel];
|
||||
if (value >= uSign * filmCurve(high, 0)[channel]) return filmCurve(high, row)[channel];
|
||||
while (high - low > 1) {
|
||||
int middle = (high + low) / 2;
|
||||
if (uSign * filmCurve(middle, 0)[channel] <= value) low = middle;
|
||||
else high = middle;
|
||||
}
|
||||
float x0 = uSign * filmCurve(low, 0)[channel];
|
||||
float x1 = uSign * filmCurve(high, 0)[channel];
|
||||
return mix(filmCurve(low, row)[channel], filmCurve(high, row)[channel], (value - x0) / max(x1 - x0, 1.0e-10));
|
||||
}
|
||||
|
||||
void main() {
|
||||
vec3 density = source();
|
||||
ivec2 position = pixel() + uOrigin;
|
||||
vec3 result = vec3(0.0);
|
||||
for (int c = 0; c < 3; ++c) {
|
||||
if (uLayer >= 0) density[c] = layerDensity(density[c], c);
|
||||
float total = uMax[c];
|
||||
if (total <= 0.0 || uCount[c] <= 0.0) continue;
|
||||
float p = clamp((density[c] + uMin[c]) / total, 0.000001, 0.999999);
|
||||
float saturation = 1.0 - p * uUniformity[c] * 0.999999;
|
||||
float rate = uCount[c] * (p / saturation);
|
||||
for (int s = 0; s < uSubLayerCount; ++s) {
|
||||
uint state = hash(uint(position.x) ^ hash(uint(position.y)) ^
|
||||
hash(uint(c + 3 * s + 31 * (uLayer + 1))));
|
||||
if (rate < 8388608.0) {
|
||||
result[c] += poisson(rate, state) * (total / uCount[c]) * saturation;
|
||||
} else {
|
||||
float u1 = random(state);
|
||||
float u2 = random(state);
|
||||
float normal = sqrt(-2.0 * log(u1)) * cos(6.28318530718 * u2);
|
||||
result[c] += total * (p + normal * sqrt(p * saturation / uCount[c]));
|
||||
}
|
||||
}
|
||||
}
|
||||
fragColor = vec4(result / float(uSubLayerCount), 1.0);
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
val GRAIN_COMBINE = """
|
||||
uniform sampler2D uAccumulated;
|
||||
uniform sampler2D uLayer;
|
||||
void main() {
|
||||
ivec2 p = ivec2(gl_FragCoord.xy);
|
||||
fragColor = vec4(texelFetch(uAccumulated, p, 0).rgb + texelFetch(uLayer, p, 0).rgb, 1.0);
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
val GRAIN_MICRO = """
|
||||
uniform ivec2 uOrigin;
|
||||
uniform float uSigma;
|
||||
uint hash(uint n) {
|
||||
n = (n ^ (n >> 16u)) * 0x7feb352du;
|
||||
n = (n ^ (n >> 15u)) * 0x846ca68bu;
|
||||
return n ^ (n >> 16u);
|
||||
}
|
||||
float unit(uint n) { return (float(hash(n) >> 9u) + 0.5) * (1.0 / 8388608.0); }
|
||||
float noise(uint state) {
|
||||
float variance = log(1.0 + uSigma * uSigma);
|
||||
float normal = sqrt(-2.0 * log(unit(state))) * cos(6.28318530718 * unit(state + 1u));
|
||||
return exp(sqrt(variance) * normal - 0.5 * variance);
|
||||
}
|
||||
void main() {
|
||||
ivec2 p = ivec2(gl_FragCoord.xy) + uOrigin;
|
||||
uint seed = hash(uint(p.x) ^ hash(uint(p.y) + 1009u));
|
||||
fragColor = vec4(noise(seed), noise(seed+2u), noise(seed+4u), 1.0);
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
val GRAIN_FINISH = """
|
||||
$SOURCE
|
||||
uniform sampler2D uMicro;
|
||||
uniform vec3 uMinimum;
|
||||
uniform int uUseMicro;
|
||||
void main() {
|
||||
vec3 density = source();
|
||||
if (uUseMicro != 0) density *= texelFetch(uMicro, pixel(), 0).rgb;
|
||||
fragColor = vec4(density - uMinimum, 1.0);
|
||||
}
|
||||
""".trimIndent()
|
||||
}
|
||||
@@ -0,0 +1,464 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import android.opengl.GLES30
|
||||
import com.hinnka.mycamera.raw.SpektrafilmGraphGl.Companion.float
|
||||
import com.hinnka.mycamera.raw.SpektrafilmGraphGl.Companion.int
|
||||
import com.hinnka.mycamera.raw.SpektrafilmGraphGl.Companion.matrix
|
||||
import com.hinnka.mycamera.raw.SpektrafilmGraphGl.Companion.rgb
|
||||
import com.hinnka.mycamera.raw.SpektrafilmGraphGl.Companion.texture
|
||||
import com.hinnka.mycamera.raw.SpektrafilmGraphGl.Companion.xy
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
import kotlin.math.pow
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/**
|
||||
* RAW graph for processing that samples neighboring pixels or adds stochastic film effects.
|
||||
* Intermediates retain film irradiance, developed CMY, and paper irradiance in that order.
|
||||
*/
|
||||
internal class SpektrafilmGraphToneStage(private val quad: RawFullscreenQuad) {
|
||||
private val gl = SpektrafilmGraphGl(quad)
|
||||
private val optics = SpektrafilmOpticsPass(quad)
|
||||
private val diffusionAtlas = SpektrafilmDiffusionAtlas(gl, optics)
|
||||
private val grain = SpektrafilmGrainPass(gl, optics)
|
||||
private val filmExposure = FilmExposureAlgorithm(quad, gl.tables)
|
||||
private var sourceSampler = 0
|
||||
private var graphRetained = false
|
||||
|
||||
private data class Development(
|
||||
val graph: SpectralFilmGraph,
|
||||
val tuning: SpectralFilmTuning,
|
||||
val halation: SpectralHalation,
|
||||
val frameMaximum: Float?,
|
||||
)
|
||||
|
||||
fun render(input: RawEngineTonePass.Input): RawEngineTonePass.Output? {
|
||||
val selection = requireNotNull(input.spectralFilmLut)
|
||||
val graph = requireNotNull(selection.graph)
|
||||
val tuning = selection.tuning
|
||||
val halation = SpectralFilmStockDefaults.halation(selection.stock, tuning.halation)
|
||||
graphRetained = true
|
||||
val full = frame(input)
|
||||
val frameMaximum = if (tuning.halation.boostEv > 0f) selection.frameMaximum ?: run {
|
||||
check(full.originX == 0 && full.originY == 0 && full.width == full.frameWidth && full.height == full.frameHeight) {
|
||||
"Spektrafilm highlight boost requires the whole frame irradiance maximum"
|
||||
}
|
||||
measureMaximum(input, 0, 0, input.width, input.height)
|
||||
} else null
|
||||
releaseMeterTargets()
|
||||
|
||||
gl.tables.prepare(graph)
|
||||
if (!tuning.grain.active) grain.releaseTargets()
|
||||
if (!graph.usesDir) gl.releaseTarget("inhibitor")
|
||||
|
||||
val development = Development(graph, tuning, halation, frameMaximum)
|
||||
val shareWideLobes = shouldShareWideDiffusion(full, support(selection, full))
|
||||
var cameraField: SpektrafilmOpticsPass.FrameDiffusion? = null
|
||||
var paperField: SpektrafilmOpticsPass.FrameDiffusion? = null
|
||||
try {
|
||||
if (shareWideLobes && SpektrafilmOpticsPass.usesFrameDiffusion(full, tuning.cameraDiffusion, DIFFUSION_STRIDE)) {
|
||||
cameraField = diffusionAtlas.build(
|
||||
full, DIFFUSION_STRIDE, tuning.cameraDiffusion, nativeSupport = 0,
|
||||
halation = halation, maxRaw = frameMaximum,
|
||||
) { work, _ ->
|
||||
val exposure = gl.target("exposure", work.width, work.height)
|
||||
if (prepare(input, exposure, work.left, work.top)) exposure.texture else null
|
||||
} ?: return null
|
||||
}
|
||||
if (graph.printing && shareWideLobes &&
|
||||
SpektrafilmOpticsPass.usesFrameDiffusion(full, tuning.enlargerDiffusion, DIFFUSION_STRIDE)
|
||||
) {
|
||||
val filmApron = filmSupport(selection, full, cameraField?.stride)
|
||||
paperField = diffusionAtlas.build(
|
||||
full, DIFFUSION_STRIDE, tuning.enlargerDiffusion, nativeSupport = filmApron,
|
||||
) { work, workRegion ->
|
||||
val exposure = gl.target("exposure", work.width, work.height)
|
||||
if (!prepare(input, exposure, work.left, work.top)) {
|
||||
null
|
||||
} else {
|
||||
val density = gl.target("density", work.width, work.height, GLES30.GL_RGBA16F)
|
||||
val developed = developFilm(development, workRegion, exposure, density, cameraField)
|
||||
enlarge(graph, developed, exposure)
|
||||
exposure.texture
|
||||
}
|
||||
} ?: return null
|
||||
}
|
||||
|
||||
val apron = support(selection, full, cameraField?.stride, paperField?.stride)
|
||||
return renderWindows(input, full, development, apron, cameraField, paperField)
|
||||
} finally {
|
||||
paperField?.release()
|
||||
cameraField?.release()
|
||||
}
|
||||
}
|
||||
|
||||
private fun renderWindows(
|
||||
input: RawEngineTonePass.Input,
|
||||
full: SpektrafilmOpticsPass.Region,
|
||||
development: Development,
|
||||
support: Int,
|
||||
cameraField: SpektrafilmOpticsPass.FrameDiffusion?,
|
||||
paperField: SpektrafilmOpticsPass.FrameDiffusion?,
|
||||
): RawEngineTonePass.Output? {
|
||||
val (graph, tuning) = development
|
||||
val workEdge = maxOf(WORK_EDGE, 2 * support + MIN_CORE)
|
||||
val w = minOf(input.width, workEdge)
|
||||
val h = minOf(input.height, workEdge)
|
||||
val columns = workAxis(input.width, w, support)
|
||||
val rows = workAxis(input.height, h, support)
|
||||
PLog.d(
|
||||
TAG, "Spatial render ${input.width}x${input.height}: ${columns.size}x${rows.size} windows, " +
|
||||
"work=${w}x${h}, apron=${support}px, cameraDiffusionStride=${cameraField?.stride ?: 0}, " +
|
||||
"paperDiffusionStride=${paperField?.stride ?: 0}",
|
||||
)
|
||||
val exposure = gl.target("exposure", w, h)
|
||||
val density = gl.target("density", w, h, GLES30.GL_RGBA16F)
|
||||
val scanOutput = gl.target("scan", w, h, GLES30.GL_RGBA16F)
|
||||
for (row in rows) {
|
||||
for (column in columns) {
|
||||
val workLeft = column.workStart
|
||||
val workTop = row.workStart
|
||||
val region = full.copy(width = w, height = h, originX = full.originX + workLeft, originY = full.originY + workTop)
|
||||
if (!prepare(input, exposure, workLeft, workTop)) return null
|
||||
|
||||
val developed = developFilm(development, region, exposure, density, cameraField)
|
||||
val scanDensity = if (graph.printing) {
|
||||
enlarge(graph, developed, exposure)
|
||||
val paperExposure = optics.diffusion(exposure.texture, region, tuning.enlargerDiffusion, paperField)
|
||||
developPaper(paperExposure, density)
|
||||
density.texture
|
||||
} else developed
|
||||
|
||||
val glare = if (graph.usesGlare) optics.glare(region, tuning.glare, GLARE_SEED) else 0
|
||||
gl.draw(
|
||||
"scan-${graph.usesGlare}-${graph.linearScan}",
|
||||
SpektrafilmGraphShaders.scan(graph.usesGlare, graph.linearScan), scanOutput,
|
||||
) { program ->
|
||||
texture(program, "uSource", 0, scanDensity)
|
||||
gl.tables.scan.bind(program, "uCube", 1)
|
||||
float(program, "uSize", graph.size.toFloat())
|
||||
rgb(program, "uLow", graph.scanLow)
|
||||
rgb(program, "uHigh", graph.scanHigh)
|
||||
if (graph.usesGlare) {
|
||||
texture(program, "uGlare", 2, glare)
|
||||
gl.tables.gamut.bind(program, "uGamut", 3)
|
||||
rgb(program, "uWhite", graph.glareWhite)
|
||||
rgb(program, "uGamutLow", graph.gamutLow)
|
||||
rgb(program, "uGamutHigh", graph.gamutHigh)
|
||||
}
|
||||
}
|
||||
|
||||
val scanBlurred = optics.gaussian(scanOutput.texture, region, tuning.scannerLensBlur)
|
||||
val unsharp = tuning.scannerUnsharpAmount > 0f && tuning.scannerUnsharpSigma > 0f
|
||||
val unsharpSource = if (unsharp) optics.gaussian(scanBlurred, region, tuning.scannerUnsharpSigma) else scanBlurred
|
||||
gl.draw(
|
||||
"finish", SpektrafilmGraphShaders.FINISH, input.targetFramebufferId,
|
||||
column.coreStart, row.coreStart, column.coreLength, row.coreLength,
|
||||
) { program ->
|
||||
texture(program, "uSource", 0, scanBlurred)
|
||||
texture(program, "uUnsharp", 1, unsharpSource)
|
||||
xy(program, "uSourceOffset", -workLeft, -workTop)
|
||||
matrix(program, "uOutputTransform", input.outputTransform)
|
||||
float(program, "uUnsharpAmount", if (unsharp) tuning.scannerUnsharpAmount else 0f)
|
||||
}
|
||||
}
|
||||
}
|
||||
RawGlesProgram.logErrors("Spektrafilm spatial tone stage")
|
||||
return RawEngineTonePass.Output(input.targetTextureId, input.width, input.height)
|
||||
}
|
||||
|
||||
private fun developFilm(
|
||||
development: Development,
|
||||
region: SpektrafilmOpticsPass.Region,
|
||||
exposure: SpektrafilmGraphGl.Surface,
|
||||
density: SpektrafilmGraphGl.Surface,
|
||||
cameraField: SpektrafilmOpticsPass.FrameDiffusion?,
|
||||
): Int {
|
||||
val (graph, tuning, halation, frameMaximum) = development
|
||||
val camera = optics.camera(
|
||||
exposure.texture, region, tuning.cameraLensBlurUm, tuning.cameraDiffusion, halation, frameMaximum, cameraField,
|
||||
)
|
||||
// Spatial DIR uses the same optics scratch, so keep the exposure while its inhibitor is filtered.
|
||||
val cameraExposure = if (graph.usesDir && tuning.dirDiffusionUm > 0f) {
|
||||
gl.copy(camera, exposure)
|
||||
exposure.texture
|
||||
} else camera
|
||||
val inhibitor = inhibitors(graph, tuning, region, cameraExposure)
|
||||
gl.draw("develop", SpektrafilmGraphShaders.DEVELOP, density) { program ->
|
||||
bindDevelopment(program, cameraExposure, graph)
|
||||
texture(program, "uInhibitor", 2, if (inhibitor != 0) inhibitor else cameraExposure)
|
||||
int(program, "uUseDir", if (graph.usesDir) 1 else 0)
|
||||
}
|
||||
return if (tuning.grain.active) grain.render(density, region, graph, tuning.grain) else density.texture
|
||||
}
|
||||
|
||||
fun measureMaximum(input: RawEngineTonePass.Input, left: Int, top: Int, width: Int, height: Int): Float {
|
||||
graphRetained = true
|
||||
gl.tables.prepare(requireNotNull(input.spectralFilmLut?.graph))
|
||||
val w = minOf(width, WORK_EDGE)
|
||||
val h = minOf(height, WORK_EDGE)
|
||||
val maximumInput = gl.target("meterExposure", w, h)
|
||||
val buffer = ByteBuffer.allocateDirect(4 * Float.SIZE_BYTES).order(ByteOrder.nativeOrder()).asFloatBuffer()
|
||||
var maximum = 0f
|
||||
for (y in 0 until height step h) for (x in 0 until width step w) {
|
||||
var sw = minOf(w, width - x)
|
||||
var sh = minOf(h, height - y)
|
||||
check(prepare(input, maximumInput, left + x, top + y, sw, sh)) { "Spektrafilm irradiance reduction input failed" }
|
||||
var source = maximumInput
|
||||
var reduction = 0
|
||||
do {
|
||||
val ow = (sw + 3) / 4
|
||||
val oh = (sh + 3) / 4
|
||||
val target = gl.target("meter${reduction and 1}", ow, oh)
|
||||
gl.draw("maximum", MAXIMUM, target) { program ->
|
||||
texture(program, "uSource", 0, source.texture)
|
||||
xy(program, "uSize", sw, sh)
|
||||
}
|
||||
source = target
|
||||
sw = ow
|
||||
sh = oh
|
||||
reduction++
|
||||
} while (sw > 1 || sh > 1)
|
||||
GLES30.glBindFramebuffer(GLES30.GL_READ_FRAMEBUFFER, source.framebuffer)
|
||||
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, 0)
|
||||
GLES30.glPixelStorei(GLES30.GL_PACK_ALIGNMENT, 4)
|
||||
GLES30.glPixelStorei(GLES30.GL_PACK_ROW_LENGTH, 0)
|
||||
GLES30.glPixelStorei(GLES30.GL_PACK_SKIP_ROWS, 0)
|
||||
GLES30.glPixelStorei(GLES30.GL_PACK_SKIP_PIXELS, 0)
|
||||
buffer.position(0)
|
||||
GLES30.glReadPixels(0, 0, 1, 1, GLES30.GL_RGBA, GLES30.GL_FLOAT, buffer)
|
||||
val value = buffer[0]
|
||||
val error = GLES30.glGetError()
|
||||
check(error == GLES30.GL_NO_ERROR && value.isFinite()) { "Spektrafilm irradiance maximum read failed, GL error=$error" }
|
||||
maximum = maxOf(maximum, value)
|
||||
}
|
||||
return maximum
|
||||
}
|
||||
|
||||
fun release() {
|
||||
filmExposure.release()
|
||||
gl.release()
|
||||
optics.release()
|
||||
if (sourceSampler != 0) GLES30.glDeleteSamplers(1, intArrayOf(sourceSampler), 0)
|
||||
sourceSampler = 0
|
||||
graphRetained = false
|
||||
}
|
||||
|
||||
fun discardInactiveGraph() {
|
||||
if (!graphRetained) return
|
||||
gl.releaseTargets()
|
||||
gl.tables.release()
|
||||
optics.releaseTargets()
|
||||
graphRetained = false
|
||||
}
|
||||
|
||||
private fun releaseMeterTargets() {
|
||||
gl.releaseTarget("meterExposure")
|
||||
gl.releaseTarget("meter0")
|
||||
gl.releaseTarget("meter1")
|
||||
}
|
||||
|
||||
private fun prepare(
|
||||
input: RawEngineTonePass.Input,
|
||||
target: SpektrafilmGraphGl.Surface,
|
||||
left: Int,
|
||||
top: Int,
|
||||
width: Int = target.width,
|
||||
height: Int = target.height,
|
||||
): Boolean {
|
||||
if (sourceSampler == 0) {
|
||||
sourceSampler = IntArray(1).also { GLES30.glGenSamplers(1, it, 0) }[0]
|
||||
check(sourceSampler != 0)
|
||||
GLES30.glSamplerParameteri(sourceSampler, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_NEAREST)
|
||||
GLES30.glSamplerParameteri(sourceSampler, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_NEAREST)
|
||||
GLES30.glSamplerParameteri(sourceSampler, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_CLAMP_TO_EDGE)
|
||||
GLES30.glSamplerParameteri(sourceSampler, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE)
|
||||
}
|
||||
GLES30.glDisable(GLES30.GL_BLEND)
|
||||
GLES30.glBindSampler(0, sourceSampler)
|
||||
try {
|
||||
return filmExposure.render(
|
||||
input.copy(targetFramebufferId = target.framebuffer, targetTextureId = target.texture),
|
||||
left, top, width, height,
|
||||
) != null
|
||||
} finally {
|
||||
GLES30.glBindSampler(0, 0)
|
||||
}
|
||||
}
|
||||
|
||||
private fun inhibitors(
|
||||
graph: SpectralFilmGraph,
|
||||
tuning: SpectralFilmTuning,
|
||||
region: SpektrafilmOpticsPass.Region,
|
||||
exposure: Int,
|
||||
): Int {
|
||||
if (!graph.usesDir) return 0
|
||||
val inhibitor = gl.target("inhibitor", region.width, region.height, GLES30.GL_RGBA16F)
|
||||
gl.draw("inhibitors", SpektrafilmGraphShaders.DIR, inhibitor) { program ->
|
||||
bindDevelopment(program, exposure, graph)
|
||||
rgb(program, "uDensityMax", graph.densityMax)
|
||||
matrix(program, "uDirMatrix", graph.dirMatrix)
|
||||
int(program, "uPositive", if (graph.positive) 1 else 0)
|
||||
}
|
||||
if (tuning.dirDiffusionUm <= 0f) return inhibitor.texture
|
||||
return optics.gaussianWithExponential(
|
||||
inhibitor.texture, region, tuning.dirDiffusionUm / region.pixelSizeUm,
|
||||
tuning.dirTailUm / region.pixelSizeUm, tuning.dirTailWeight,
|
||||
)
|
||||
}
|
||||
|
||||
private fun bindDevelopment(program: Int, exposure: Int, graph: SpectralFilmGraph) {
|
||||
texture(program, "uSource", 0, exposure)
|
||||
gl.tables.filmCurves.bind(program, "uCurves", 1)
|
||||
int(program, "uCurveWidth", graph.filmCurveSize)
|
||||
rgb(program, "uGamma", graph.gamma)
|
||||
float(program, "uExposureCorrection", graph.filmExposureCorrection)
|
||||
}
|
||||
|
||||
private fun enlarge(
|
||||
graph: SpectralFilmGraph,
|
||||
developed: Int,
|
||||
exposure: SpektrafilmGraphGl.Surface,
|
||||
) {
|
||||
gl.draw("enlarger", SpektrafilmGraphShaders.ENLARGE, exposure) { program ->
|
||||
texture(program, "uSource", 0, developed)
|
||||
gl.tables.paperExposure.bind(program, "uCube", 1)
|
||||
float(program, "uSize", graph.size.toFloat())
|
||||
rgb(program, "uLow", graph.filmLow)
|
||||
rgb(program, "uHigh", graph.filmHigh)
|
||||
}
|
||||
}
|
||||
|
||||
private fun developPaper(paperExposure: Int, density: SpektrafilmGraphGl.Surface) {
|
||||
gl.draw("paper", SpektrafilmGraphShaders.PAPER, density) { program ->
|
||||
texture(program, "uSource", 0, paperExposure)
|
||||
gl.tables.paperCurves.bind(program, "uCurves", 1)
|
||||
}
|
||||
}
|
||||
|
||||
private class FilmExposureAlgorithm(
|
||||
quad: RawFullscreenQuad,
|
||||
private val tables: SpektrafilmGraphGl.Tables,
|
||||
) : RawRenderingEngineToneAlgorithm(quad, SpektrafilmGraphShaders.FILM_EXPOSURE) {
|
||||
override fun bindEngineResources(program: Int, input: RawEngineColorResources) {
|
||||
super.bindEngineResources(program, input)
|
||||
val selection = requireNotNull(input.spectralFilmLut)
|
||||
tables.filmExposure.bind(program, "uFilmExposure", 1)
|
||||
float(program, "uSpectralInputScale", selection.inputScale)
|
||||
float(program, "uCameraExposureGain", 2f.pow(selection.tuning.cameraExposureEv))
|
||||
float(program, "uSize", requireNotNull(selection.graph).size.toFloat())
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "SpektrafilmGraphToneStage"
|
||||
private const val WORK_EDGE = 768
|
||||
private const val MIN_CORE = 192
|
||||
private const val DIFFUSION_STRIDE = 8
|
||||
private const val GLARE_SEED = 0x3e4420
|
||||
|
||||
private data class WorkAxis(val workStart: Int, val coreStart: Int, val coreEnd: Int) {
|
||||
val coreLength: Int get() = coreEnd - coreStart
|
||||
}
|
||||
|
||||
private fun workAxis(length: Int, workLength: Int, support: Int): List<WorkAxis> = buildList {
|
||||
var start = 0
|
||||
while (start < length) {
|
||||
val origin = (start - support).coerceIn(0, length - workLength)
|
||||
val workEnd = origin + workLength
|
||||
// A window touching the input edge already has the same boundary condition as
|
||||
// a full render. Consume that entire valid span before moving the window.
|
||||
val end = if (workEnd == length) length else workEnd - support
|
||||
check(end > start) { "Spektrafilm work window is smaller than its apron" }
|
||||
add(WorkAxis(origin, start, end))
|
||||
start = end
|
||||
}
|
||||
}
|
||||
|
||||
fun support(selection: SpectralFilmLut, width: Int, height: Int): Int = support(
|
||||
selection,
|
||||
region(width, height, 0, 0, width, height, selection.tuning.filmFormatMm),
|
||||
)
|
||||
|
||||
private fun support(
|
||||
selection: SpectralFilmLut,
|
||||
region: SpektrafilmOpticsPass.Region,
|
||||
cameraStride: Int? = null,
|
||||
paperStride: Int? = null,
|
||||
): Int {
|
||||
val tuning = selection.tuning
|
||||
val graph = selection.graph ?: return SpektrafilmScannerPass.support(tuning)
|
||||
val printDiffusion = if (graph.printing) {
|
||||
SpektrafilmOpticsPass.diffusionSupport(region, tuning.enlargerDiffusion, paperStride)
|
||||
} else 0
|
||||
val glare = if (graph.usesGlare) SpektrafilmOpticsPass.glareSupport(tuning.glare) else 0
|
||||
val unsharp = if (tuning.scannerUnsharpAmount > 0f) {
|
||||
SpektrafilmOpticsPass.gaussianSupport(tuning.scannerUnsharpSigma)
|
||||
} else 0
|
||||
return maxOf(filmSupport(selection, region, cameraStride) + printDiffusion, glare) +
|
||||
SpektrafilmOpticsPass.gaussianSupport(tuning.scannerLensBlur) + unsharp
|
||||
}
|
||||
|
||||
private fun filmSupport(
|
||||
selection: SpectralFilmLut,
|
||||
region: SpektrafilmOpticsPass.Region,
|
||||
cameraStride: Int?,
|
||||
): Int {
|
||||
val tuning = selection.tuning
|
||||
val graph = requireNotNull(selection.graph)
|
||||
val spatialDir = if (graph.usesDir && tuning.dirDiffusionUm > 0f) {
|
||||
SpektrafilmOpticsPass.gaussianExponentialSupport(
|
||||
tuning.dirDiffusionUm / region.pixelSizeUm, tuning.dirTailUm / region.pixelSizeUm, tuning.dirTailWeight,
|
||||
)
|
||||
} else 0
|
||||
return SpektrafilmOpticsPass.cameraSupport(
|
||||
region, tuning.cameraLensBlurUm, tuning.cameraDiffusion,
|
||||
SpectralFilmStockDefaults.halation(selection.stock, tuning.halation),
|
||||
cameraStride,
|
||||
) + spatialDir + SpektrafilmGrainPass.support(region, graph, tuning.grain)
|
||||
}
|
||||
|
||||
private fun shouldShareWideDiffusion(region: SpektrafilmOpticsPass.Region, apron: Int): Boolean {
|
||||
val workEdge = maxOf(WORK_EDGE, 2 * apron + MIN_CORE)
|
||||
val width = minOf(region.width, workEdge)
|
||||
val height = minOf(region.height, workEdge)
|
||||
val workPixels = width.toLong() * height * workAxis(region.width, width, apron).size *
|
||||
workAxis(region.height, height, apron).size
|
||||
// For small crops a local convolution already fits in one or two windows.
|
||||
// Sharing pays when the old apron causes at least a second image of repeated work.
|
||||
return workPixels >= 2L * region.width * region.height
|
||||
}
|
||||
|
||||
private fun frame(input: RawEngineTonePass.Input): SpektrafilmOpticsPass.Region {
|
||||
val sx = input.width.toDouble() / input.globalWidth
|
||||
val sy = input.height.toDouble() / input.globalHeight
|
||||
val x = (input.globalOriginX * sx).roundToInt()
|
||||
val y = (input.globalOriginY * sy).roundToInt()
|
||||
val w = maxOf((input.fullImageWidth * sx).roundToInt(), input.width + x)
|
||||
val h = maxOf((input.fullImageHeight * sy).roundToInt(), input.height + y)
|
||||
return region(input.width, input.height, x, y, w, h, requireNotNull(input.spectralFilmLut).tuning.filmFormatMm)
|
||||
}
|
||||
|
||||
private fun region(w: Int, h: Int, x: Int, y: Int, fullW: Int, fullH: Int, filmFormatMm: Float) =
|
||||
SpektrafilmOpticsPass.Region(w, h, x, y, fullW, fullH, filmFormatMm * 1000f / maxOf(fullW, fullH))
|
||||
|
||||
private val MAXIMUM = """
|
||||
uniform sampler2D uSource;
|
||||
uniform ivec2 uSize;
|
||||
|
||||
void main() {
|
||||
ivec2 p = ivec2(gl_FragCoord.xy) * 4;
|
||||
float result = 0.0;
|
||||
for (int y = 0; y < 4; ++y) for (int x = 0; x < 4; ++x) {
|
||||
ivec2 q = p + ivec2(x, y);
|
||||
if (all(lessThan(q, uSize))) {
|
||||
vec3 value = texelFetch(uSource, q, 0).rgb;
|
||||
result = max(result, max(value.r, max(value.g, value.b)));
|
||||
}
|
||||
}
|
||||
fragColor = vec4(result, 0.0, 0.0, 1.0);
|
||||
}
|
||||
""".trimIndent()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.ceil
|
||||
import kotlin.math.exp
|
||||
import kotlin.math.log2
|
||||
import kotlin.math.pow
|
||||
import kotlin.math.roundToInt
|
||||
import kotlin.math.sqrt
|
||||
|
||||
/** Optical kernels expressed in the native film sampling grid, before any display transform. */
|
||||
internal object SpektrafilmOpticsKernels {
|
||||
data class Gaussian(
|
||||
val stride: Int,
|
||||
val weights: FloatArray,
|
||||
val amplitude: SpectralRgb,
|
||||
) {
|
||||
val radius: Int get() = weights.size / 3 - 1
|
||||
val support: Int get() = stride * radius + 2 * (stride - 1)
|
||||
}
|
||||
|
||||
data class Mixture(
|
||||
val direct: SpectralRgb,
|
||||
val lobes: List<Gaussian>,
|
||||
val wholeSampleReflection: Boolean = false,
|
||||
) {
|
||||
val support: Int get() = lobes.maxOfOrNull(Gaussian::support) ?: 0
|
||||
val identity: Boolean get() = lobes.isEmpty() && abs(direct.r - 1f) < 1e-6f &&
|
||||
abs(direct.g - 1f) < 1e-6f && abs(direct.b - 1f) < 1e-6f
|
||||
}
|
||||
|
||||
private data class Lobe(val sigma: SpectralRgb, val amplitude: SpectralRgb)
|
||||
private data class Footprint(val stride: Int, val sigma: Double, val radius: Int)
|
||||
private data class DiffusionKey(val params: SpectralDiffusion, val pixelSizeUm: Float, val shortEdge: Int)
|
||||
|
||||
// Camera and enlarger each reuse their frame's plan across support queries and working windows.
|
||||
private val diffusionPlans = object : LinkedHashMap<DiffusionKey, Mixture>(2, 0.75f, true) {
|
||||
override fun removeEldestEntry(eldest: MutableMap.MutableEntry<DiffusionKey, Mixture>?) = size > 2
|
||||
}
|
||||
|
||||
fun gaussian(sigma: SpectralRgb): Mixture = mixture(ZERO, listOf(Lobe(sigma, ONE)))
|
||||
|
||||
fun gaussianWithExponential(sigma: Float, decay: Float, tailWeight: Float): Mixture = mixture(
|
||||
ZERO,
|
||||
listOf(Lobe(scalar(sigma), scalar(1f - tailWeight))) +
|
||||
exponential(scalar(decay), scalar(tailWeight)),
|
||||
)
|
||||
|
||||
fun scatter(params: SpectralHalation, pixelSizeUm: Float): Mixture {
|
||||
if (!params.enabled || params.scatterAmount <= 0f || params.scatterSpatialScale <= 0f) return IDENTITY
|
||||
val scale = params.scatterSpatialScale / pixelSizeUm
|
||||
val core = scale(params.scatterCoreUm, scale)
|
||||
val tail = scale(params.scatterTailUm, scale)
|
||||
if (!core.anyPositive() && !tail.anyPositive()) return IDENTITY
|
||||
val tailAmplitude = scale(params.scatterTailWeight, params.scatterAmount)
|
||||
return mixture(
|
||||
scalar(1f - params.scatterAmount),
|
||||
listOf(Lobe(core, subtract(scalar(params.scatterAmount), tailAmplitude))) + exponential(tail, tailAmplitude),
|
||||
)
|
||||
}
|
||||
|
||||
fun halation(params: SpectralHalation, pixelSizeUm: Float): Mixture {
|
||||
if (!params.enabled || params.halationAmount <= 0f || params.halationSpatialScale <= 0f) return IDENTITY
|
||||
val strength = scale(requireNotNull(params.strength), params.halationAmount)
|
||||
val first = scale(requireNotNull(params.firstSigmaUm), params.halationSpatialScale / pixelSizeUm)
|
||||
if (!strength.anyPositive() || !first.anyPositive()) return IDENTITY
|
||||
val direct = if (params.renormalize) {
|
||||
SpectralRgb(1f / (1f + strength.r), 1f / (1f + strength.g), 1f / (1f + strength.b))
|
||||
} else ONE
|
||||
val amplitude = multiply(strength, direct)
|
||||
val decay = FloatArray(params.bounces) { params.bounceDecay.pow(it) }
|
||||
val total = decay.sum()
|
||||
return mixture(direct, decay.mapIndexed { bounce, value ->
|
||||
Lobe(scale(first, sqrt(bounce + 1f)), scale(amplitude, value / total))
|
||||
})
|
||||
}
|
||||
|
||||
fun diffusion(params: SpectralDiffusion, pixelSizeUm: Float, frameWidth: Int, frameHeight: Int): Mixture {
|
||||
if (!params.active) return IDENTITY
|
||||
val shortEdge = minOf(frameWidth, frameHeight)
|
||||
val key = DiffusionKey(params, pixelSizeUm, shortEdge)
|
||||
return synchronized(diffusionPlans) {
|
||||
diffusionPlans[key] ?: buildDiffusion(params, pixelSizeUm, shortEdge).also { plan ->
|
||||
if (!plan.identity) diffusionPlans[key] = plan
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildDiffusion(params: SpectralDiffusion, pixelSizeUm: Float, shortEdge: Int): Mixture {
|
||||
val family = families[params.family]
|
||||
val amount = (scatterFraction(params.strength) * family.gain).coerceIn(0f, 0.99f)
|
||||
val groupScales = floatArrayOf(params.coreSize, params.haloSize, params.bloomSize)
|
||||
val groupWeights = floatArrayOf(
|
||||
family.groups[0].weight * params.coreIntensity,
|
||||
family.groups[1].weight * params.haloIntensity,
|
||||
family.groups[2].weight * params.bloomIntensity,
|
||||
)
|
||||
if (groupWeights.sum() == 0f) family.groups.forEachIndexed { index, group ->
|
||||
groupScales[index] = 1f
|
||||
groupWeights[index] = group.weight
|
||||
}
|
||||
val weightSum = groupWeights.sum()
|
||||
val expansion = params.spatialScale / pixelSizeUm
|
||||
val warmth = (family.warmth + params.haloWarmth).coerceIn(-1.5f, 1.5f)
|
||||
val lobes = family.groups.flatMapIndexed { index, group ->
|
||||
val lambdas = FloatArray(group.components) { i ->
|
||||
val fraction = i.toFloat() / (group.components - 1)
|
||||
group.lambda * groupScales[index] * expansion * group.spread.pow(2f * fraction - 1f)
|
||||
}
|
||||
val componentWeights = if (index == 2) {
|
||||
FloatArray(group.components) { lambdas[it].pow(2f - group.alpha) }
|
||||
} else FloatArray(group.components) { 1f }
|
||||
val targetEnergy = amount * groupWeights[index] / weightSum
|
||||
val channelWeights = Array(3) { channel ->
|
||||
val weights = if (index == 1) {
|
||||
FloatArray(group.components) { i ->
|
||||
val gradient = 2f * i / (group.components - 1) - 1f
|
||||
(1f + warmth * WARMTH_AXIS[channel] * gradient).coerceAtLeast(0f)
|
||||
}
|
||||
} else componentWeights
|
||||
val sum = weights.sum()
|
||||
FloatArray(group.components) { weights[it] * targetEnergy / sum }
|
||||
}
|
||||
lambdas.flatMapIndexed { i, lambda ->
|
||||
val weight = SpectralRgb(channelWeights[0][i], channelWeights[1][i], channelWeights[2][i])
|
||||
exponential(scalar(lambda), weight)
|
||||
}
|
||||
}
|
||||
val bloom = family.groups[2]
|
||||
val maxLambda = bloom.lambda * groupScales[2] * bloom.spread * expansion
|
||||
val maxRadius = minOf(
|
||||
ceil(maxOf(8f * maxLambda, 5f)).toInt(),
|
||||
(shortEdge / 2 - 1).coerceAtLeast(1),
|
||||
)
|
||||
return mixture(scalar(1f - amount), lobes, maxRadius, wholeSampleReflection = true)
|
||||
}
|
||||
|
||||
private fun exponential(decay: SpectralRgb, amplitude: SpectralRgb): List<Lobe> =
|
||||
exponentialWeights.mapIndexed { i, weight ->
|
||||
Lobe(scale(decay, exponentialSigmas[i]), scale(amplitude, weight))
|
||||
}
|
||||
|
||||
private fun mixture(
|
||||
initial: SpectralRgb,
|
||||
lobes: List<Lobe>,
|
||||
maxRadius: Int = Int.MAX_VALUE,
|
||||
wholeSampleReflection: Boolean = false,
|
||||
): Mixture {
|
||||
val direct = initial.channels()
|
||||
val result = mutableListOf<Gaussian>()
|
||||
for (lobe in lobes) {
|
||||
val sigmas = lobe.sigma.channels()
|
||||
val amplitudes = lobe.amplitude.channels()
|
||||
val filters = amplitudes.indices.mapNotNull { channel ->
|
||||
if (amplitudes[channel] == 0f) return@mapNotNull null
|
||||
val footprint = footprint(sigmas[channel], maxRadius)
|
||||
if (footprint.radius == 0) {
|
||||
direct[channel] += amplitudes[channel]
|
||||
null
|
||||
} else channel to footprint
|
||||
}.groupBy { it.second.stride }
|
||||
for ((stride, filtered) in filters) {
|
||||
val radius = filtered.maxOf { it.second.radius }
|
||||
val weights = FloatArray((radius + 1) * 3)
|
||||
val amplitude = FloatArray(3)
|
||||
for ((channel, shape) in filtered) {
|
||||
val taps = DoubleArray(shape.radius + 1) { offset -> exp(-0.5 * (offset / shape.sigma).pow(2)) }
|
||||
val sum = 2.0 * taps.sum() - taps[0]
|
||||
taps.forEachIndexed { offset, weight -> weights[offset * 3 + channel] = (weight / sum).toFloat() }
|
||||
amplitude[channel] = amplitudes[channel]
|
||||
}
|
||||
result += Gaussian(stride, weights, amplitude.rgb())
|
||||
}
|
||||
}
|
||||
return Mixture(direct.rgb(), result, wholeSampleReflection)
|
||||
}
|
||||
|
||||
private fun footprint(sigma: Float, maxRadius: Int): Footprint {
|
||||
var stride = 1
|
||||
val radiusNative = (3f * sigma).roundToInt().coerceAtMost(maxRadius)
|
||||
while (radiusNative > MAX_RADIUS.toLong() * stride ||
|
||||
(sigma / stride > 5f && radiusNative / (2 * stride) >= 8)
|
||||
) stride *= 2
|
||||
// Account for blur already introduced by box reduction and tent reconstruction.
|
||||
val boxVariance = (stride.toDouble() * stride - 1) / 12
|
||||
val tentVariance = if (stride > 1) stride.toDouble() * stride / 6 + 1.0 / 12 else 0.0
|
||||
val coarseSigma = sqrt((sigma.toDouble() * sigma - boxVariance - tentVariance).coerceAtLeast(0.0)) / stride
|
||||
val maxCoarseRadius = (maxRadius - 2 * (stride - 1)) / stride
|
||||
val radius = (3 * coarseSigma).roundToInt().coerceAtMost(maxCoarseRadius)
|
||||
check(radius <= MAX_RADIUS) { "Spektrafilm Gaussian kernel exceeds $MAX_RADIUS taps per side" }
|
||||
return Footprint(stride, coarseSigma, radius)
|
||||
}
|
||||
|
||||
private fun scatterFraction(strength: Float): Float {
|
||||
val stop = (log2(strength) + 3f).coerceIn(0f, 4f)
|
||||
val lower = stop.toInt()
|
||||
val upper = minOf(lower + 1, SCATTER_FRACTIONS.lastIndex)
|
||||
return SCATTER_FRACTIONS[lower] + (SCATTER_FRACTIONS[upper] - SCATTER_FRACTIONS[lower]) * (stop - lower)
|
||||
}
|
||||
|
||||
private data class Family(val gain: Float, val warmth: Float, val groups: List<Group>)
|
||||
private data class Group(val lambda: Float, val spread: Float, val components: Int, val weight: Float, val alpha: Float = 0f)
|
||||
|
||||
private val families = listOf(
|
||||
Family(0.65f, 0f, listOf(Group(10f, 1.5f, 2, 0.60f), Group(50f, 2f, 3, 0.30f), Group(260f, 2.5f, 4, 0.10f, 3.2f))),
|
||||
Family(0.75f, 0.65f, listOf(Group(16f, 1.5f, 2, 0.40f), Group(95f, 2f, 3, 0.47f), Group(380f, 2.5f, 4, 0.13f, 3.5f))),
|
||||
Family(1.05f, 0.40f, listOf(Group(14f, 1.5f, 2, 0.28f), Group(150f, 2f, 3, 0.42f), Group(650f, 2.5f, 4, 0.30f, 2.9f))),
|
||||
Family(1.00f, 0.85f, listOf(Group(20f, 1.5f, 2, 0.22f), Group(200f, 2f, 3, 0.30f), Group(1000f, 2.5f, 4, 0.48f, 2.5f))),
|
||||
)
|
||||
|
||||
internal const val MAX_RADIUS = 15
|
||||
internal val ZERO = scalar(0f)
|
||||
internal val ONE = scalar(1f)
|
||||
private val IDENTITY = Mixture(ONE, emptyList())
|
||||
private val WARMTH_AXIS = floatArrayOf(1.30f, 0.15f, -1.45f)
|
||||
private val SCATTER_FRACTIONS = floatArrayOf(0.10f, 0.20f, 0.35f, 0.55f, 0.75f)
|
||||
|
||||
// Upstream's three-Gaussian approximation of an isotropic exponential PSF.
|
||||
private val exponentialWeights = floatArrayOf(0.1633f, 0.6496f, 0.1870f).let { weights ->
|
||||
val sum = weights.sum()
|
||||
weights.map { it / sum }
|
||||
}
|
||||
private val exponentialSigmas = floatArrayOf(0.5360f, 1.5236f, 2.7684f)
|
||||
|
||||
internal fun scalar(value: Float) = SpectralRgb(value, value, value)
|
||||
private fun scale(rgb: SpectralRgb, scale: Float) = SpectralRgb(rgb.r * scale, rgb.g * scale, rgb.b * scale)
|
||||
private fun multiply(a: SpectralRgb, b: SpectralRgb) = SpectralRgb(a.r * b.r, a.g * b.g, a.b * b.b)
|
||||
private fun subtract(a: SpectralRgb, b: SpectralRgb) = SpectralRgb(a.r - b.r, a.g - b.g, a.b - b.b)
|
||||
private fun SpectralRgb.channels() = floatArrayOf(r, g, b)
|
||||
private fun FloatArray.rgb() = SpectralRgb(this[0], this[1], this[2])
|
||||
private fun SpectralRgb.anyPositive() = r > 0f || g > 0f || b > 0f
|
||||
}
|
||||
@@ -0,0 +1,517 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import android.opengl.GLES30
|
||||
import com.hinnka.mycamera.raw.SpektrafilmOpticsKernels.ONE
|
||||
import com.hinnka.mycamera.raw.SpektrafilmOpticsKernels.ZERO
|
||||
import com.hinnka.mycamera.raw.SpektrafilmOpticsKernels.scalar
|
||||
import kotlin.math.expm1
|
||||
import kotlin.math.ln
|
||||
import kotlin.math.ln1p
|
||||
import kotlin.math.pow
|
||||
import kotlin.math.sqrt
|
||||
|
||||
/** Camera and enlarger optics in linear film or paper exposure. Every coarse grid is frame aligned. */
|
||||
internal class SpektrafilmOpticsPass(private val quad: RawFullscreenQuad) {
|
||||
data class Region(
|
||||
val width: Int,
|
||||
val height: Int,
|
||||
val originX: Int,
|
||||
val originY: Int,
|
||||
val frameWidth: Int,
|
||||
val frameHeight: Int,
|
||||
val pixelSizeUm: Float,
|
||||
) {
|
||||
init {
|
||||
require(width > 0 && height > 0 && originX >= 0 && originY >= 0)
|
||||
require(originX + width <= frameWidth && originY + height <= frameHeight)
|
||||
require(pixelSizeUm.isFinite() && pixelSizeUm > 0f)
|
||||
}
|
||||
}
|
||||
|
||||
/** A box-reduced tile on the absolute frame grid. The texture uses linear FP32 RGB. */
|
||||
class DiffusionGrid internal constructor(
|
||||
val texture: Int,
|
||||
val width: Int,
|
||||
val height: Int,
|
||||
val originX: Int,
|
||||
val originY: Int,
|
||||
val stride: Int,
|
||||
)
|
||||
|
||||
/** Whole-input coarse convolution results, owned by the caller until [release]. */
|
||||
class FrameDiffusion internal constructor(
|
||||
val stride: Int,
|
||||
private val params: SpectralDiffusion,
|
||||
private val frame: Region,
|
||||
private val levels: List<DiffusionGrid>,
|
||||
private var dispose: (() -> Unit)?,
|
||||
) {
|
||||
internal fun levelsFor(params: SpectralDiffusion, region: Region): List<DiffusionGrid> {
|
||||
check(dispose != null) { "Spektrafilm frame diffusion has been released" }
|
||||
require(params == this.params && region.frameWidth == frame.frameWidth &&
|
||||
region.frameHeight == frame.frameHeight && region.pixelSizeUm == frame.pixelSizeUm &&
|
||||
region.originX >= frame.originX && region.originY >= frame.originY &&
|
||||
region.originX + region.width <= frame.originX + frame.width &&
|
||||
region.originY + region.height <= frame.originY + frame.height
|
||||
) { "Spektrafilm frame diffusion does not match the optical settings or image grid" }
|
||||
return levels
|
||||
}
|
||||
|
||||
fun release() {
|
||||
val release = dispose ?: return
|
||||
dispose = null
|
||||
release()
|
||||
}
|
||||
}
|
||||
|
||||
private val targets = mutableListOf<Target>()
|
||||
private val filterProgram = Program("spektrafilmGaussian", SpektrafilmOpticsShaders.GAUSSIAN)
|
||||
private val boxProgram = Program("spektrafilmOpticalBox", SpektrafilmOpticsShaders.BOX)
|
||||
private val reconstructionPrograms = mutableMapOf<Int, Program>()
|
||||
private val boostProgram = Program("spektrafilmHighlightBoost", SpektrafilmOpticsShaders.BOOST)
|
||||
private val glareProgram = Program("spektrafilmGlare", SpektrafilmOpticsShaders.GLARE)
|
||||
private var format = GLES30.GL_RGBA16F
|
||||
|
||||
/** The returned texture belongs to this pass and can be reused at the next public call. */
|
||||
fun camera(
|
||||
source: Int,
|
||||
region: Region,
|
||||
lensBlurUm: Float,
|
||||
diffusion: SpectralDiffusion,
|
||||
halation: SpectralHalation,
|
||||
maxRaw: Float?,
|
||||
frameDiffusion: FrameDiffusion? = null,
|
||||
): Int {
|
||||
val sourceSurface = begin(region, source, GLES30.GL_RGBA32F)
|
||||
val reconstructed = boost(sourceSurface, halation, maxRaw)
|
||||
var result = applyDiffusion(reconstructed, region, diffusion, frameDiffusion)
|
||||
result = apply(result, SpektrafilmOpticsKernels.gaussian(scalar(lensBlurUm / region.pixelSizeUm)))
|
||||
result = apply(result, SpektrafilmOpticsKernels.scatter(halation, region.pixelSizeUm))
|
||||
return apply(result, SpektrafilmOpticsKernels.halation(halation, region.pixelSizeUm)).texture
|
||||
}
|
||||
|
||||
fun diffusion(source: Int, region: Region, params: SpectralDiffusion, frameDiffusion: FrameDiffusion? = null): Int =
|
||||
applyDiffusion(begin(region, source, GLES30.GL_RGBA32F), region, params, frameDiffusion).texture
|
||||
|
||||
/** Reduces native irradiance with the same frame-aligned box passes used by diffusion. */
|
||||
fun reduceDiffusionInput(
|
||||
source: Int,
|
||||
region: Region,
|
||||
stride: Int,
|
||||
halation: SpectralHalation? = null,
|
||||
maxRaw: Float? = null,
|
||||
): DiffusionGrid {
|
||||
requirePowerOfTwo(stride)
|
||||
val irradiance = boost(begin(region, source, GLES30.GL_RGBA32F), halation, maxRaw)
|
||||
return advance(irradiance, stride, wholeReflection = true).diffusionGrid()
|
||||
}
|
||||
|
||||
/** Builds the broad lobes once from the complete [stride]-pitch grid of the given input region. */
|
||||
fun buildFrameDiffusion(source: Int, frame: Region, stride: Int, params: SpectralDiffusion): FrameDiffusion {
|
||||
requirePowerOfTwo(stride)
|
||||
require(usesFrameDiffusion(frame, params, stride)) { "No coarse Spektrafilm diffusion lobes at pitch $stride" }
|
||||
val nativeGrid = Grid(frame.width, frame.height, frame.originX, frame.originY, 1)
|
||||
val sourceSurface = begin(
|
||||
source, nativeGrid.reducedBy(stride), GLES30.GL_RGBA32F,
|
||||
)
|
||||
val plan = diffusionPlan(frame, params)
|
||||
val levels = mutableListOf<DiffusionGrid>()
|
||||
val owned = mutableListOf<Target>()
|
||||
var coarse = sourceSurface
|
||||
try {
|
||||
for ((levelStride, lobes) in groups(plan)) {
|
||||
if (levelStride < stride) continue
|
||||
coarse = advance(coarse, levelStride, plan.wholeSampleReflection)
|
||||
val filtered = blurGroup(coarse, lobes, ZERO, plan.wholeSampleReflection)
|
||||
val target = checkNotNull(filtered.target)
|
||||
check(targets.remove(target))
|
||||
owned += target
|
||||
levels += filtered.diffusionGrid()
|
||||
}
|
||||
return FrameDiffusion(stride, params, frame, levels) { owned.forEach(Target::release) }
|
||||
} catch (failure: Throwable) {
|
||||
owned.forEach(Target::release)
|
||||
throw failure
|
||||
} finally {
|
||||
coarse.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
fun gaussian(source: Int, region: Region, sigma: Float): Int = gaussian(source, region, scalar(sigma))
|
||||
|
||||
fun gaussian(source: Int, region: Region, sigma: SpectralRgb): Int =
|
||||
apply(begin(region, source), SpektrafilmOpticsKernels.gaussian(sigma)).texture
|
||||
|
||||
fun gaussianWithExponential(source: Int, region: Region, sigma: Float, decay: Float, tailWeight: Float): Int =
|
||||
apply(begin(region, source), SpektrafilmOpticsKernels.gaussianWithExponential(sigma, decay, tailWeight)).texture
|
||||
|
||||
/** A scalar fraction of normalized scanner illuminant, in the red channel. */
|
||||
fun glare(region: Region, params: SpectralGlare, seed: Int): Int {
|
||||
if (!params.enabled || params.percent <= 0f) return 0
|
||||
val source = begin(region, 0)
|
||||
val noise = acquire(source.grid)
|
||||
val variance = ln1p(params.roughness * params.roughness)
|
||||
glareProgram.use(noise) {
|
||||
vector("uOrigin", source.grid.originX, source.grid.originY)
|
||||
float("uLogMean", ln(params.percent / 100f) - 0.5f * variance)
|
||||
float("uLogSigma", sqrt(variance))
|
||||
integer("uSeed", seed)
|
||||
}
|
||||
return if (params.roughness == 0f) noise.texture else {
|
||||
apply(noise, SpektrafilmOpticsKernels.gaussian(scalar(params.blur))).texture
|
||||
}
|
||||
}
|
||||
|
||||
fun release() {
|
||||
listOf(filterProgram, boxProgram, boostProgram, glareProgram).forEach(Program::release)
|
||||
reconstructionPrograms.values.forEach(Program::release)
|
||||
reconstructionPrograms.clear()
|
||||
releaseTargets()
|
||||
}
|
||||
|
||||
fun releaseTargets() {
|
||||
targets.forEach(Target::release)
|
||||
targets.clear()
|
||||
}
|
||||
|
||||
private fun applyDiffusion(
|
||||
source: Surface,
|
||||
region: Region,
|
||||
params: SpectralDiffusion,
|
||||
frameDiffusion: FrameDiffusion?,
|
||||
): Surface {
|
||||
val plan = diffusionPlan(region, params)
|
||||
val levels = frameDiffusion?.levelsFor(params, region).orEmpty()
|
||||
return apply(source, plan, frameDiffusion?.stride, levels)
|
||||
}
|
||||
|
||||
private fun apply(
|
||||
source: Surface,
|
||||
mixture: SpektrafilmOpticsKernels.Mixture,
|
||||
splitStride: Int? = null,
|
||||
sharedLevels: List<DiffusionGrid> = emptyList(),
|
||||
): Surface {
|
||||
if (mixture.identity) return source
|
||||
if (mixture.lobes.isEmpty()) {
|
||||
val output = reconstruct(source, emptyList(), mixture.direct, mixture.wholeSampleReflection)
|
||||
source.recycle()
|
||||
return output
|
||||
}
|
||||
|
||||
var coarse = source
|
||||
var full: Surface? = null
|
||||
val pending = mutableListOf<Surface>()
|
||||
// The FP16 path retains its intermediate rounding at each level. Film and paper
|
||||
// irradiance use FP32, so the same ordered sum can live entirely in one shader.
|
||||
val levelsPerDraw = if (format == GLES30.GL_RGBA32F) MAX_RECONSTRUCTION_LEVELS else 1
|
||||
fun flushReconstruction() {
|
||||
val composite = reconstruct(full ?: source, pending, if (full == null) mixture.direct else ONE, mixture.wholeSampleReflection)
|
||||
full?.recycle()
|
||||
pending.forEach(Surface::recycle)
|
||||
pending.clear()
|
||||
full = composite
|
||||
}
|
||||
for ((stride, lobes) in groups(mixture)) {
|
||||
if (splitStride != null && stride >= splitStride) break
|
||||
// A later reconstruction still reads the native source if no stride-one lobe ran.
|
||||
coarse = advance(coarse, stride, mixture.wholeSampleReflection, retain = source)
|
||||
val direct = if (stride == 1) mixture.direct else ZERO
|
||||
val group = blurGroup(coarse, lobes, direct, mixture.wholeSampleReflection)
|
||||
if (stride == 1) {
|
||||
full = group
|
||||
} else {
|
||||
pending += group
|
||||
if (pending.size == levelsPerDraw) flushReconstruction()
|
||||
}
|
||||
}
|
||||
if (coarse !== source) coarse.recycle()
|
||||
for (level in sharedLevels) {
|
||||
pending += Surface(level.texture, 0, Grid(level.width, level.height, level.originX, level.originY, level.stride))
|
||||
if (pending.size == levelsPerDraw) flushReconstruction()
|
||||
}
|
||||
if (pending.isNotEmpty()) flushReconstruction()
|
||||
source.recycle()
|
||||
return checkNotNull(full)
|
||||
}
|
||||
|
||||
private fun groups(mixture: SpektrafilmOpticsKernels.Mixture) =
|
||||
mixture.lobes.groupBy(SpektrafilmOpticsKernels.Gaussian::stride).toSortedMap()
|
||||
|
||||
private fun advance(source: Surface, stride: Int, wholeReflection: Boolean, retain: Surface? = null): Surface {
|
||||
var coarse = source
|
||||
while (coarse.grid.stride < stride) {
|
||||
val next = downsample(coarse, wholeReflection)
|
||||
if (coarse !== retain) coarse.recycle()
|
||||
coarse = next
|
||||
}
|
||||
return coarse
|
||||
}
|
||||
|
||||
private fun blurGroup(
|
||||
source: Surface,
|
||||
lobes: List<SpektrafilmOpticsKernels.Gaussian>,
|
||||
direct: SpectralRgb,
|
||||
wholeReflection: Boolean,
|
||||
): Surface {
|
||||
var accumulated: Surface? = null
|
||||
for (lobe in lobes) {
|
||||
val horizontal = acquire(source.grid)
|
||||
filter(source, source, horizontal, lobe, vertical = false, wholeReflection, ZERO, ONE)
|
||||
val output = acquire(source.grid)
|
||||
filter(horizontal, accumulated ?: source, output, lobe, vertical = true, wholeReflection,
|
||||
if (accumulated != null) ONE else direct, lobe.amplitude)
|
||||
horizontal.recycle()
|
||||
accumulated?.recycle()
|
||||
accumulated = output
|
||||
}
|
||||
return checkNotNull(accumulated)
|
||||
}
|
||||
|
||||
private fun filter(
|
||||
source: Surface,
|
||||
base: Surface,
|
||||
target: Surface,
|
||||
kernel: SpektrafilmOpticsKernels.Gaussian,
|
||||
vertical: Boolean,
|
||||
wholeReflection: Boolean,
|
||||
baseWeight: SpectralRgb,
|
||||
blurWeight: SpectralRgb,
|
||||
) = filterProgram.use(target) {
|
||||
sampler("uSource", 0, source.texture)
|
||||
sampler("uBase", 1, base.texture)
|
||||
vector("uAxis", if (vertical) 0 else 1, if (vertical) 1 else 0)
|
||||
integer("uRadius", kernel.radius)
|
||||
integer("uWholeReflection", if (wholeReflection) 1 else 0)
|
||||
rgb("uBaseWeight", baseWeight)
|
||||
rgb("uBlurWeight", blurWeight)
|
||||
GLES30.glUniform3fv(location("uWeights[0]"), kernel.radius + 1, kernel.weights, 0)
|
||||
}
|
||||
|
||||
private fun downsample(source: Surface, wholeReflection: Boolean): Surface {
|
||||
val grid = source.grid.reducedBy(2)
|
||||
return acquire(grid).also { target ->
|
||||
boxProgram.use(target) {
|
||||
sampler("uSource", 0, source.texture)
|
||||
vector("uOffset", 2 * grid.originX - source.grid.originX, 2 * grid.originY - source.grid.originY)
|
||||
integer("uWholeReflection", if (wholeReflection) 1 else 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun reconstruct(
|
||||
base: Surface,
|
||||
levels: List<Surface>,
|
||||
baseWeight: SpectralRgb,
|
||||
wholeReflection: Boolean,
|
||||
): Surface = acquire(base.grid).also { output ->
|
||||
val program = reconstructionPrograms.getOrPut(levels.size) {
|
||||
Program("spektrafilmOpticalReconstruction${levels.size}", SpektrafilmOpticsShaders.reconstruction(levels.size))
|
||||
}
|
||||
program.use(output) {
|
||||
sampler("uBase", 0, base.texture)
|
||||
vector("uBaseOrigin", base.grid.originX, base.grid.originY)
|
||||
integer("uWholeReflection", if (wholeReflection) 1 else 0)
|
||||
rgb("uBaseWeight", baseWeight)
|
||||
levels.forEachIndexed { index, level ->
|
||||
sampler("uLevels[$index]", index + 1, level.texture)
|
||||
GLES30.glUniform3i(location("uLevelGrids[$index]"), level.grid.originX, level.grid.originY, level.grid.stride)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun highlightBoost(source: Surface, params: HighlightBoost): Surface = acquire(source.grid).also { output ->
|
||||
boostProgram.use(output) {
|
||||
sampler("uSource", 0, source.texture)
|
||||
float("uThreshold", params.threshold)
|
||||
float("uExponentScale", params.exponentScale)
|
||||
float("uBoostScale", params.boostScale)
|
||||
}
|
||||
source.recycle()
|
||||
}
|
||||
|
||||
private fun boost(source: Surface, halation: SpectralHalation?, maxRaw: Float?): Surface {
|
||||
if (halation == null || halation.boostEv <= 0f) return source
|
||||
val maximum = requireNotNull(maxRaw) { "Spektrafilm highlight boost needs the frame raw maximum" }
|
||||
return HighlightBoost.from(halation, maximum)?.let { highlightBoost(source, it) } ?: source
|
||||
}
|
||||
|
||||
private fun begin(region: Region, texture: Int, format: Int = GLES30.GL_RGBA16F): Surface =
|
||||
begin(texture, Grid(region.width, region.height, region.originX, region.originY, 1), format)
|
||||
|
||||
private fun begin(texture: Int, grid: Grid, format: Int): Surface {
|
||||
// An immediately chained call may read an earlier owned output. Keep it leased
|
||||
// through the new draw and leave both textures available to the caller afterwards.
|
||||
targets.forEach { it.leased = texture != 0 && it.texture == texture }
|
||||
this.format = format
|
||||
return Surface(texture, 0, grid)
|
||||
}
|
||||
|
||||
private fun acquire(grid: Grid): Surface {
|
||||
val target = targets.firstOrNull { !it.leased && it.matches(grid, format) }
|
||||
?: targets.firstOrNull { !it.leased && it.stride == grid.stride }
|
||||
?: Target().also(targets::add)
|
||||
target.ensure(grid, format)
|
||||
target.leased = true
|
||||
return Surface(target.texture, target.framebuffer, grid, target)
|
||||
}
|
||||
|
||||
private data class Grid(val width: Int, val height: Int, val originX: Int, val originY: Int, val stride: Int) {
|
||||
fun reducedBy(factor: Int): Grid = Grid(
|
||||
(originX + width + factor - 1) / factor - originX / factor,
|
||||
(originY + height + factor - 1) / factor - originY / factor,
|
||||
originX / factor, originY / factor, stride * factor,
|
||||
)
|
||||
}
|
||||
|
||||
private class Surface(val texture: Int, val framebuffer: Int, val grid: Grid, val target: Target? = null) {
|
||||
fun recycle() { target?.leased = false }
|
||||
fun diffusionGrid() = DiffusionGrid(texture, grid.width, grid.height, grid.originX, grid.originY, grid.stride)
|
||||
}
|
||||
|
||||
private inner class Program(val name: String, val code: String) {
|
||||
private var id = 0
|
||||
private val uniforms = mutableMapOf<String, Int>()
|
||||
|
||||
fun use(target: Surface, configure: Program.() -> Unit) {
|
||||
if (id == 0) id = quad.createProgram(code, name)
|
||||
check(id != 0) { "$name is unavailable" }
|
||||
GLES30.glUseProgram(id)
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, target.framebuffer)
|
||||
GLES30.glViewport(0, 0, target.grid.width, target.grid.height)
|
||||
GLES30.glDisable(GLES30.GL_BLEND)
|
||||
configure()
|
||||
quad.draw(id)
|
||||
val error = GLES30.glGetError()
|
||||
check(error == GLES30.GL_NO_ERROR) { "$name draw failed, GL error=0x${error.toString(16)}" }
|
||||
}
|
||||
|
||||
fun location(name: String): Int = uniforms.getOrPut(name) { GLES30.glGetUniformLocation(id, name) }
|
||||
fun integer(name: String, value: Int) = GLES30.glUniform1i(location(name), value)
|
||||
fun float(name: String, value: Float) = GLES30.glUniform1f(location(name), value)
|
||||
fun vector(name: String, x: Int, y: Int) = GLES30.glUniform2i(location(name), x, y)
|
||||
fun rgb(name: String, value: SpectralRgb) = GLES30.glUniform3f(location(name), value.r, value.g, value.b)
|
||||
fun sampler(name: String, unit: Int, texture: Int) {
|
||||
GLES30.glActiveTexture(GLES30.GL_TEXTURE0 + unit)
|
||||
GLES30.glBindSampler(unit, 0)
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, texture)
|
||||
integer(name, unit)
|
||||
}
|
||||
|
||||
fun release() {
|
||||
if (id != 0) GLES30.glDeleteProgram(id)
|
||||
id = 0
|
||||
uniforms.clear()
|
||||
}
|
||||
}
|
||||
|
||||
private class Target {
|
||||
var texture = 0
|
||||
private set
|
||||
var framebuffer = 0
|
||||
private set
|
||||
var leased = false
|
||||
var stride = 0
|
||||
private set
|
||||
private var width = 0
|
||||
private var height = 0
|
||||
private var format = 0
|
||||
|
||||
fun matches(grid: Grid, format: Int): Boolean = texture != 0 &&
|
||||
width == grid.width && height == grid.height && this.format == format && stride == grid.stride
|
||||
|
||||
fun ensure(grid: Grid, format: Int) {
|
||||
if (matches(grid, format)) return
|
||||
release()
|
||||
val limit = IntArray(1)
|
||||
GLES30.glGetIntegerv(GLES30.GL_MAX_TEXTURE_SIZE, limit, 0)
|
||||
check(grid.width <= limit[0] && grid.height <= limit[0]) { "Spektrafilm optical surface exceeds GL_MAX_TEXTURE_SIZE" }
|
||||
texture = IntArray(1).also { GLES30.glGenTextures(1, it, 0) }[0]
|
||||
framebuffer = IntArray(1).also { GLES30.glGenFramebuffers(1, it, 0) }[0]
|
||||
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, texture)
|
||||
GLES30.glTexStorage2D(GLES30.GL_TEXTURE_2D, 1, format, grid.width, grid.height)
|
||||
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_NEAREST)
|
||||
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_NEAREST)
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, framebuffer)
|
||||
GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, texture, 0)
|
||||
val status = GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER)
|
||||
val error = GLES30.glGetError()
|
||||
if (status != GLES30.GL_FRAMEBUFFER_COMPLETE || error != GLES30.GL_NO_ERROR || texture == 0 || framebuffer == 0) {
|
||||
release()
|
||||
error("Spektrafilm optical ${grid.width}×${grid.height} format=0x${format.toString(16)} " +
|
||||
"allocation failed: status=0x${status.toString(16)} error=0x${error.toString(16)}")
|
||||
}
|
||||
width = grid.width
|
||||
height = grid.height
|
||||
stride = grid.stride
|
||||
this.format = format
|
||||
}
|
||||
|
||||
fun release() {
|
||||
if (framebuffer != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(framebuffer), 0)
|
||||
if (texture != 0) GLES30.glDeleteTextures(1, intArrayOf(texture), 0)
|
||||
texture = 0
|
||||
framebuffer = 0
|
||||
leased = false
|
||||
}
|
||||
}
|
||||
|
||||
private data class HighlightBoost(val threshold: Float, val exponentScale: Float, val boostScale: Float) {
|
||||
companion object {
|
||||
fun from(params: SpectralHalation, maximum: Float): HighlightBoost? {
|
||||
val threshold = 0.184 * 2.0.pow(params.protectEv.toDouble())
|
||||
if (maximum <= threshold) return null
|
||||
val gain = 2.0.pow(params.boostEv.toDouble())
|
||||
val a = 28.0.pow(1.0 - params.boostRange)
|
||||
val z = a * (maximum - threshold) / maximum
|
||||
val denominator = if (z < 0.05) z * z * (0.5 + z * (1.0 / 6 + z * (1.0 / 24 + z / 120))) else expm1(z) - z
|
||||
return HighlightBoost(threshold.toFloat(), (a / maximum).toFloat(),
|
||||
((gain - 1) * maximum / denominator).toFloat())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
// OpenGL ES 3.0 guarantees at least 16 fragment samplers. One slot holds the base.
|
||||
private const val MAX_RECONSTRUCTION_LEVELS = 15
|
||||
|
||||
fun cameraSupport(
|
||||
region: Region,
|
||||
lensBlurUm: Float,
|
||||
diffusion: SpectralDiffusion,
|
||||
halation: SpectralHalation,
|
||||
frameStride: Int? = null,
|
||||
): Int = diffusionSupport(region, diffusion, frameStride) + gaussianSupport(lensBlurUm / region.pixelSizeUm) +
|
||||
SpektrafilmOpticsKernels.scatter(halation, region.pixelSizeUm).support +
|
||||
SpektrafilmOpticsKernels.halation(halation, region.pixelSizeUm).support
|
||||
|
||||
fun diffusionSupport(region: Region, params: SpectralDiffusion, frameStride: Int? = null): Int {
|
||||
val plan = diffusionPlan(region, params)
|
||||
if (frameStride == null) return plan.support
|
||||
return plan.lobes.asSequence().filter { it.stride < frameStride }
|
||||
.maxOfOrNull(SpektrafilmOpticsKernels.Gaussian::support) ?: 0
|
||||
}
|
||||
|
||||
fun usesFrameDiffusion(frame: Region, params: SpectralDiffusion, stride: Int): Boolean =
|
||||
diffusionPlan(frame, params).lobes.any { it.stride >= stride }
|
||||
|
||||
private fun diffusionPlan(region: Region, params: SpectralDiffusion) = SpektrafilmOpticsKernels.diffusion(
|
||||
params, region.pixelSizeUm, region.frameWidth, region.frameHeight,
|
||||
)
|
||||
|
||||
private fun requirePowerOfTwo(stride: Int) {
|
||||
require(stride > 0 && stride and (stride - 1) == 0) { "Invalid Spektrafilm diffusion grid pitch $stride" }
|
||||
}
|
||||
|
||||
fun glareSupport(params: SpectralGlare): Int = if (params.enabled && params.percent > 0f && params.roughness > 0f) {
|
||||
gaussianSupport(params.blur)
|
||||
} else 0
|
||||
|
||||
fun gaussianSupport(sigma: Float): Int = gaussianSupport(scalar(sigma))
|
||||
|
||||
fun gaussianSupport(sigma: SpectralRgb): Int = SpektrafilmOpticsKernels.gaussian(sigma).support
|
||||
|
||||
fun gaussianExponentialSupport(sigma: Float, decay: Float, tailWeight: Float): Int =
|
||||
SpektrafilmOpticsKernels.gaussianWithExponential(sigma, decay, tailWeight).support
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
internal object SpektrafilmOpticsShaders {
|
||||
private const val HEADER = """#version 300 es
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
precision highp sampler2D;
|
||||
|
||||
out vec4 fragColor;
|
||||
"""
|
||||
|
||||
private const val REFLECTION = """
|
||||
uniform bool uWholeReflection;
|
||||
|
||||
int mirror(int index, int size) {
|
||||
if (index >= 0 && index < size) return index;
|
||||
if (size == 1) return 0;
|
||||
int last = uWholeReflection ? size - 1 : size;
|
||||
int period = 2 * last;
|
||||
int magnitude = index < 0 ? -index - (uWholeReflection ? 0 : 1) : index;
|
||||
int wrapped = magnitude % period;
|
||||
return min(wrapped, period - (uWholeReflection ? 0 : 1) - wrapped);
|
||||
}
|
||||
|
||||
vec3 sampleMirrored(sampler2D source, ivec2 point, ivec2 size) {
|
||||
return texelFetch(source, ivec2(mirror(point.x, size.x), mirror(point.y, size.y)), 0).rgb;
|
||||
}
|
||||
"""
|
||||
|
||||
val GAUSSIAN = HEADER + REFLECTION + """
|
||||
uniform sampler2D uSource;
|
||||
uniform sampler2D uBase;
|
||||
uniform ivec2 uAxis;
|
||||
uniform int uRadius;
|
||||
uniform vec3 uWeights[${SpektrafilmOpticsKernels.MAX_RADIUS + 1}];
|
||||
uniform vec3 uBaseWeight;
|
||||
uniform vec3 uBlurWeight;
|
||||
|
||||
void main() {
|
||||
ivec2 point = ivec2(gl_FragCoord.xy);
|
||||
ivec2 size = textureSize(uSource, 0);
|
||||
vec3 blurred = uWeights[0] * texelFetch(uSource, point, 0).rgb;
|
||||
bool vertical = uAxis.y != 0;
|
||||
int coordinate = vertical ? point.y : point.x;
|
||||
int extent = vertical ? size.y : size.x;
|
||||
if (coordinate >= uRadius && coordinate + uRadius < extent) {
|
||||
for (int i = 1; i <= uRadius; ++i) {
|
||||
ivec2 offset = uAxis * i;
|
||||
blurred += uWeights[i] * (texelFetch(uSource, point - offset, 0).rgb +
|
||||
texelFetch(uSource, point + offset, 0).rgb);
|
||||
}
|
||||
} else {
|
||||
for (int i = 1; i <= uRadius; ++i) {
|
||||
ivec2 left = point + uAxis * (mirror(coordinate - i, extent) - coordinate);
|
||||
ivec2 right = point + uAxis * (mirror(coordinate + i, extent) - coordinate);
|
||||
blurred += uWeights[i] * (texelFetch(uSource, left, 0).rgb + texelFetch(uSource, right, 0).rgb);
|
||||
}
|
||||
}
|
||||
vec3 base = vec3(0.0);
|
||||
if (any(notEqual(uBaseWeight, vec3(0.0)))) base = texelFetch(uBase, point, 0).rgb;
|
||||
fragColor = vec4(base * uBaseWeight + blurred * uBlurWeight, 1.0);
|
||||
}
|
||||
"""
|
||||
|
||||
val BOX = HEADER + REFLECTION + """
|
||||
uniform sampler2D uSource;
|
||||
uniform ivec2 uOffset;
|
||||
|
||||
void main() {
|
||||
ivec2 point = 2 * ivec2(gl_FragCoord.xy) + uOffset;
|
||||
ivec2 size = textureSize(uSource, 0);
|
||||
vec3 value = sampleMirrored(uSource, point, size) + sampleMirrored(uSource, point + ivec2(1, 0), size) +
|
||||
sampleMirrored(uSource, point + ivec2(0, 1), size) + sampleMirrored(uSource, point + ivec2(1, 1), size);
|
||||
fragColor = vec4(value * 0.25, 1.0);
|
||||
}
|
||||
"""
|
||||
|
||||
fun reconstruction(levelCount: Int): String = buildString {
|
||||
append(HEADER)
|
||||
append(REFLECTION)
|
||||
append("""
|
||||
uniform sampler2D uBase;
|
||||
uniform ivec2 uBaseOrigin;
|
||||
uniform vec3 uBaseWeight;
|
||||
""")
|
||||
if (levelCount > 0) {
|
||||
append("""
|
||||
uniform sampler2D uLevels[$levelCount];
|
||||
uniform ivec3 uLevelGrids[$levelCount];
|
||||
|
||||
vec3 interpolateLevel(sampler2D level, vec2 framePoint, ivec3 grid) {
|
||||
vec2 reduced = framePoint / float(grid.z) - 0.5 - vec2(grid.xy);
|
||||
ivec2 cell = ivec2(floor(reduced));
|
||||
vec2 ratio = fract(reduced);
|
||||
ivec2 size = textureSize(level, 0);
|
||||
vec3 low = mix(sampleMirrored(level, cell, size),
|
||||
sampleMirrored(level, cell + ivec2(1, 0), size), ratio.x);
|
||||
vec3 high = mix(sampleMirrored(level, cell + ivec2(0, 1), size),
|
||||
sampleMirrored(level, cell + ivec2(1, 1), size), ratio.x);
|
||||
return mix(low, high, ratio.y);
|
||||
}
|
||||
""")
|
||||
}
|
||||
append("""
|
||||
void main() {
|
||||
ivec2 point = ivec2(gl_FragCoord.xy);
|
||||
vec3 value = texelFetch(uBase, point, 0).rgb * uBaseWeight;
|
||||
vec2 framePoint = vec2(point + uBaseOrigin) + 0.5;
|
||||
""")
|
||||
// Sampler array indices are integer constant expressions in GLSL ES 3.00.
|
||||
repeat(levelCount) { level ->
|
||||
append(" value += interpolateLevel(uLevels[$level], framePoint, uLevelGrids[$level]);\n")
|
||||
}
|
||||
append("""
|
||||
fragColor = vec4(value, 1.0);
|
||||
}
|
||||
""")
|
||||
}
|
||||
|
||||
val BOOST = HEADER + """
|
||||
uniform sampler2D uSource;
|
||||
uniform float uThreshold;
|
||||
uniform float uExponentScale;
|
||||
uniform float uBoostScale;
|
||||
|
||||
float boost(float raw) {
|
||||
float z = max(raw - uThreshold, 0.0) * uExponentScale;
|
||||
float curve = z < 0.05 ? z * z * (0.5 + z * (1.0 / 6.0 + z * (1.0 / 24.0 + z / 120.0)))
|
||||
: exp(z) - z - 1.0;
|
||||
return raw + uBoostScale * curve;
|
||||
}
|
||||
|
||||
void main() {
|
||||
vec3 raw = texelFetch(uSource, ivec2(gl_FragCoord.xy), 0).rgb;
|
||||
fragColor = vec4(boost(raw.r), boost(raw.g), boost(raw.b), 1.0);
|
||||
}
|
||||
"""
|
||||
|
||||
val GLARE = HEADER + """
|
||||
uniform ivec2 uOrigin;
|
||||
uniform int uSeed;
|
||||
uniform float uLogMean;
|
||||
uniform float uLogSigma;
|
||||
|
||||
uint hash(uint value) {
|
||||
value = value * 747796405u + 2891336453u;
|
||||
uint word = ((value >> ((value >> 28u) + 4u)) ^ value) * 277803737u;
|
||||
return (word >> 22u) ^ word;
|
||||
}
|
||||
|
||||
float uniformSample(uint value) {
|
||||
return (float(value & 0x007fffffu) + 0.5) * (1.0 / 8388608.0);
|
||||
}
|
||||
|
||||
void main() {
|
||||
uvec2 point = uvec2(ivec2(gl_FragCoord.xy) + uOrigin);
|
||||
uint state = hash(point.x ^ hash(point.y + uint(uSeed)));
|
||||
float normal = sqrt(-2.0 * log(uniformSample(state))) * cos(6.28318530718 * uniformSample(hash(state)));
|
||||
float glare = exp(uLogMean + uLogSigma * normal);
|
||||
fragColor = vec4(vec3(glare), 1.0);
|
||||
}
|
||||
"""
|
||||
}
|
||||
@@ -23,7 +23,7 @@ internal data class SpectralModelAsset(
|
||||
val uncompressedBytes: Int,
|
||||
)
|
||||
|
||||
internal data class SpectralRuntimeRequest(
|
||||
internal class SpectralRuntimeRequest(
|
||||
val algorithm: String,
|
||||
val upstreamCommit: String,
|
||||
val size: Int,
|
||||
@@ -34,12 +34,42 @@ internal data class SpectralRuntimeRequest(
|
||||
val paperName: String,
|
||||
val paper: SpectralModelAsset?,
|
||||
val positive: Boolean,
|
||||
stock: String,
|
||||
tuning: SpectralFilmTuning,
|
||||
val buildSpatialGraph: Boolean,
|
||||
) {
|
||||
private val context = "schema4:$algorithm:$upstreamCommit:ProPhoto RGB:$size:$inputScale:$printInputScale"
|
||||
val sharedKey = digest("$context:shared:${shared.sha256}")
|
||||
val modelFilmKey = digest("$sharedKey:film:${film.sha256}:positive=$positive")
|
||||
val filmKey = digest("$modelFilmKey:film-stage")
|
||||
val printKey: String? = paper?.let { digest("$modelFilmKey:print-stage:$paperName:${it.sha256}") }
|
||||
val filmOptions = tuning.filmOptions(stock)
|
||||
val printOptions = tuning.printOptions()
|
||||
val scanOptions = tuning.scanOptions(positive || paper != null)
|
||||
val filmDyeOrder = tuning.filmDyeOrder.nativeIndex
|
||||
val paperDyeOrder = tuning.printDyeOrder.nativeIndex
|
||||
private val stockFilm = filmOptions.contentEquals(SpectralFilmTuning.DEFAULT.filmOptions(stock))
|
||||
private val filmVariant = if (stockFilm) "" else ":film=${filmOptions.joinToString()}"
|
||||
private val directNegative = if (!positive && paper == null) ":direct-scan" else ""
|
||||
private val filmDyeVariant = if (filmDyeOrder == 0) "" else ":film-dyes=$filmDyeOrder"
|
||||
private val scanVariant = if (scanOptions.contentEquals(SpectralFilmTuning.DEFAULT.scanOptions(true))) "" else
|
||||
":scan=${scanOptions.joinToString()}"
|
||||
val filmKey = digest("$modelFilmKey:film-stage$filmVariant$directNegative" +
|
||||
if (paper == null) filmDyeVariant + scanVariant else "")
|
||||
val printKey: String? = paper?.let {
|
||||
val printVariant = if (printOptions.contentEquals(SpectralFilmTuning.DEFAULT.printOptions())) "" else
|
||||
":print=${printOptions.joinToString()}"
|
||||
// A tuned film uses the stock's full density range. DIR does not enter
|
||||
// the enlarger's uncorrected midgray reference.
|
||||
val printFilmVariant = if (stockFilm) "" else ":full-density-wire:gamma=${tuning.filmGamma}" +
|
||||
":optics=${filmOptions.sliceArray(6..14).joinToString()}"
|
||||
val paperDyeVariant = if (paperDyeOrder == 0) "" else ":paper-dyes=$paperDyeOrder"
|
||||
digest("$modelFilmKey:print-stage:$paperName:${it.sha256}$printFilmVariant$printVariant$filmDyeVariant$paperDyeVariant$scanVariant")
|
||||
}
|
||||
val needsGlare = paper != null && tuning.glare.active
|
||||
val needsGrain = tuning.grain.active && tuning.grain.sublayers
|
||||
val spatialTablesKey = if (buildSpatialGraph) {
|
||||
digest("$filmKey:$printKey:stages:glare=$needsGlare:grainLayers=$needsGrain")
|
||||
} else null
|
||||
val graphKey = spatialTablesKey?.takeIf { tuning.needsSpatialGraph(paper != null) }
|
||||
}
|
||||
|
||||
private fun digest(value: String): String = hex(MessageDigest.getInstance("SHA-256").digest(value.toByteArray(Charsets.UTF_8)))
|
||||
@@ -57,8 +87,17 @@ internal object SpektrafilmNativeBridge {
|
||||
paperName: String,
|
||||
paperData: ByteArray?,
|
||||
positive: Boolean,
|
||||
directScan: Boolean,
|
||||
buildFilm: Boolean,
|
||||
buildPrint: Boolean,
|
||||
filmOptions: FloatArray,
|
||||
printOptions: FloatArray,
|
||||
filmDyeOrder: Int,
|
||||
paperDyeOrder: Int,
|
||||
scanOptions: FloatArray,
|
||||
buildGraph: Boolean,
|
||||
needsGlare: Boolean,
|
||||
needsGrain: Boolean,
|
||||
): Array<FloatArray>
|
||||
}
|
||||
|
||||
@@ -75,6 +114,7 @@ internal object SpektrafilmRuntime {
|
||||
private const val MAX_CACHE_FILE_BYTES = 65L * 65 * 65 * 4 * 4 + 64 * 1024
|
||||
private var loadedSharedKey: String? = null
|
||||
private var loadedFilmKey: String? = null
|
||||
private var cachedGraph: SpectralFilmGraph? = null
|
||||
|
||||
@Synchronized
|
||||
fun load(
|
||||
@@ -82,7 +122,7 @@ internal object SpektrafilmRuntime {
|
||||
request: SpectralRuntimeRequest,
|
||||
currentFilm: SpectralLutTable?,
|
||||
currentPrint: SpectralLutTable?,
|
||||
): Pair<SpectralLutTable, SpectralLutTable?> {
|
||||
): Triple<SpectralLutTable, SpectralLutTable?, SpectralFilmGraph?> {
|
||||
val started = SystemClock.elapsedRealtime()
|
||||
val directory = File(context.cacheDir, CACHE_DIRECTORY)
|
||||
val film = currentFilm?.takeIf { it.sourceKey == request.filmKey }
|
||||
@@ -97,10 +137,14 @@ internal object SpektrafilmRuntime {
|
||||
print?.let { cacheFile(directory, it.sourceKey).setLastModified(accessedAt) }
|
||||
val buildFilm = film == null
|
||||
val buildPrint = request.paper != null && print == null
|
||||
if (!buildFilm && !buildPrint) {
|
||||
// A bypass of the same film and paper can reuse its spatial tables if optics is re-enabled.
|
||||
if (request.spatialTablesKey != null && request.spatialTablesKey != cachedGraph?.sourceKey) cachedGraph = null
|
||||
val graph = request.graphKey?.let { key -> cachedGraph?.takeIf { it.sourceKey == key } }
|
||||
val buildGraph = request.graphKey != null && graph == null
|
||||
if (!buildFilm && !buildPrint && !buildGraph) {
|
||||
PLog.d(TAG, "Spektrafilm cacheHit, filmKey=${request.filmKey}, printKey=${request.printKey}, " +
|
||||
"elapsed=${SystemClock.elapsedRealtime() - started}ms, upstream=${request.upstreamCommit}")
|
||||
return requireNotNull(film) to print
|
||||
return Triple(requireNotNull(film), print, graph)
|
||||
}
|
||||
|
||||
// These temporary arrays live only through generate(). In particular the
|
||||
@@ -111,12 +155,15 @@ internal object SpektrafilmRuntime {
|
||||
val filmBytes = if (sharedChanged || loadedFilmKey != request.modelFilmKey) {
|
||||
loadModel(context, request.film)
|
||||
} else null
|
||||
val paperBytes = if (buildPrint) loadModel(context, requireNotNull(request.paper)) else null
|
||||
val paperBytes = if (buildPrint || buildGraph) request.paper?.let { loadModel(context, it) } else null
|
||||
val result = SpektrafilmNativeBridge.generate(
|
||||
request.sharedKey, request.modelFilmKey, sharedBytes, filmBytes,
|
||||
request.paperName, paperBytes, request.positive, buildFilm, buildPrint,
|
||||
request.paperName, paperBytes, request.positive, request.paper == null, buildFilm, buildPrint,
|
||||
request.filmOptions, request.printOptions,
|
||||
request.filmDyeOrder, request.paperDyeOrder,
|
||||
request.scanOptions, buildGraph, request.needsGlare, request.needsGrain,
|
||||
)
|
||||
require(result.size == 2) { "Invalid native Spektrafilm stage count" }
|
||||
require(result.size == if (buildGraph) 9 else 2) { "Invalid native Spektrafilm stage count" }
|
||||
validateGenerated(result[0], request.size, buildFilm)
|
||||
validateGenerated(result[1], request.size, buildPrint)
|
||||
loadedSharedKey = request.sharedKey
|
||||
@@ -135,10 +182,13 @@ internal object SpektrafilmRuntime {
|
||||
val printResult = print ?: request.printKey?.let { key ->
|
||||
SpectralLutTable(key, request.size, generated[1]).also { writeCache(directory, it) }
|
||||
}
|
||||
PLog.d(TAG, "Spektrafilm generated, film=$buildFilm, print=$buildPrint, " +
|
||||
val graphResult = if (buildGraph) SpectralFilmGraph(
|
||||
requireNotNull(request.graphKey), request.size, generated,
|
||||
).also { cachedGraph = it } else graph
|
||||
PLog.d(TAG, "Spektrafilm generated, film=$buildFilm, print=$buildPrint, spatial=$buildGraph, " +
|
||||
"filmKey=${request.filmKey}, printKey=${request.printKey}, " +
|
||||
"elapsed=${SystemClock.elapsedRealtime() - started}ms, upstream=${request.upstreamCommit}")
|
||||
return filmResult to printResult
|
||||
return Triple(filmResult, printResult, graphResult)
|
||||
}
|
||||
|
||||
private fun validateGenerated(values: FloatArray, size: Int, built: Boolean) {
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import android.opengl.GLES30
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import kotlin.math.exp
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/** Scanner optics in linear output RGB, after scan/gamut mapping and before the app's RAW finish. */
|
||||
internal class SpektrafilmScannerPass(private val quad: RawFullscreenQuad) {
|
||||
private var program = 0
|
||||
private var sourceSampler = 0
|
||||
private val developed = Target()
|
||||
private val horizontal = Target()
|
||||
|
||||
fun render(input: RawEngineTonePass.Input, algorithm: SpektrafilmToneAlgorithm): RawEngineTonePass.Output? {
|
||||
val tuning = requireNotNull(input.spectralFilmLut).tuning
|
||||
val lens = Kernel.fromSigma(tuning.scannerLensBlur)
|
||||
val unsharp = if (tuning.scannerUnsharpAmount > 0f) Kernel.fromSigma(tuning.scannerUnsharpSigma) else null
|
||||
val support = (lens?.radius ?: 0) + (unsharp?.radius ?: 0)
|
||||
if (support == 0) return algorithm.render(input)
|
||||
|
||||
if (program == 0) program = quad.createProgram(FRAGMENT_SHADER, "spektrafilmScanner")
|
||||
if (program == 0) return null
|
||||
val workWidth = minOf(input.width, WORK_EDGE)
|
||||
val workHeight = minOf(input.height, WORK_EDGE)
|
||||
val coreWidth = if (input.width == workWidth) workWidth else workWidth - 2 * support
|
||||
val coreHeight = if (input.height == workHeight) workHeight else workHeight - 2 * support
|
||||
val work = Rect(0, 0, workWidth, workHeight)
|
||||
val last = unsharp ?: checkNotNull(lens)
|
||||
val unsharpAmount = if (unsharp != null) tuning.scannerUnsharpAmount else 0f
|
||||
|
||||
try {
|
||||
if (!ensureSourceSampler() || !developed.ensure(workWidth, workHeight) ||
|
||||
!horizontal.ensure(workWidth, workHeight)
|
||||
) return null
|
||||
val workInput = input.copy(targetFramebufferId = developed.framebuffer, targetTextureId = developed.texture)
|
||||
GLES30.glDisable(GLES30.GL_BLEND)
|
||||
// The aligned window needs exact source texels. Nearest sampling avoids mixing an
|
||||
// adjacent texel when the window's interpolated UV rounds off the texel center.
|
||||
GLES30.glBindSampler(0, sourceSampler)
|
||||
for (top in 0 until input.height step coreHeight) {
|
||||
val workTop = (top - support).coerceIn(0, input.height - workHeight)
|
||||
for (left in 0 until input.width step coreWidth) {
|
||||
val workLeft = (left - support).coerceIn(0, input.width - workWidth)
|
||||
val core = Rect(left, top, minOf(coreWidth, input.width - left), minOf(coreHeight, input.height - top))
|
||||
if (algorithm.render(workInput, workLeft, workTop, workWidth, workHeight) == null) return null
|
||||
if (lens != null && unsharp != null) {
|
||||
if (!filter(developed.texture, horizontal.framebuffer, work, lens, vertical = false)) return null
|
||||
if (!filter(horizontal.texture, developed.framebuffer, work, lens, vertical = true)) return null
|
||||
}
|
||||
if (!filter(developed.texture, horizontal.framebuffer, work, last, vertical = false)) return null
|
||||
if (!filter(
|
||||
source = horizontal.texture,
|
||||
targetFramebuffer = input.targetFramebufferId,
|
||||
target = core,
|
||||
kernel = last,
|
||||
vertical = true,
|
||||
coordinateOffsetX = -workLeft,
|
||||
coordinateOffsetY = -workTop,
|
||||
original = developed.texture,
|
||||
unsharpAmount = unsharpAmount,
|
||||
)
|
||||
) return null
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
GLES30.glBindSampler(0, 0)
|
||||
GLES30.glActiveTexture(GLES30.GL_TEXTURE1)
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
|
||||
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
|
||||
}
|
||||
return RawEngineTonePass.Output(input.targetTextureId, input.width, input.height)
|
||||
}
|
||||
|
||||
fun release() {
|
||||
if (program != 0) GLES30.glDeleteProgram(program)
|
||||
program = 0
|
||||
if (sourceSampler != 0) GLES30.glDeleteSamplers(1, intArrayOf(sourceSampler), 0)
|
||||
sourceSampler = 0
|
||||
developed.release()
|
||||
horizontal.release()
|
||||
}
|
||||
|
||||
private fun ensureSourceSampler(): Boolean {
|
||||
if (sourceSampler != 0) return true
|
||||
val sampler = IntArray(1).also { GLES30.glGenSamplers(1, it, 0) }[0]
|
||||
GLES30.glSamplerParameteri(sampler, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_NEAREST)
|
||||
GLES30.glSamplerParameteri(sampler, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_NEAREST)
|
||||
GLES30.glSamplerParameteri(sampler, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_CLAMP_TO_EDGE)
|
||||
GLES30.glSamplerParameteri(sampler, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE)
|
||||
val error = GLES30.glGetError()
|
||||
if (sampler == 0 || error != GLES30.GL_NO_ERROR) {
|
||||
if (sampler != 0) GLES30.glDeleteSamplers(1, intArrayOf(sampler), 0)
|
||||
PLog.e(TAG, "Scanner source sampler allocation failed: error=$error")
|
||||
return false
|
||||
}
|
||||
sourceSampler = sampler
|
||||
return true
|
||||
}
|
||||
|
||||
private fun filter(
|
||||
source: Int,
|
||||
targetFramebuffer: Int,
|
||||
target: Rect,
|
||||
kernel: Kernel,
|
||||
vertical: Boolean,
|
||||
coordinateOffsetX: Int = 0,
|
||||
coordinateOffsetY: Int = 0,
|
||||
original: Int = source,
|
||||
unsharpAmount: Float = 0f,
|
||||
): Boolean {
|
||||
GLES30.glUseProgram(program)
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, targetFramebuffer)
|
||||
GLES30.glViewport(target.x, target.y, target.width, target.height)
|
||||
bindTexture("uSource", 0, source)
|
||||
bindTexture("uOriginal", 1, original)
|
||||
GLES30.glUniform2i(uniform("uSourceOffset"), coordinateOffsetX, coordinateOffsetY)
|
||||
GLES30.glUniform2i(uniform("uAxis"), if (vertical) 0 else 1, if (vertical) 1 else 0)
|
||||
GLES30.glUniform1i(uniform("uRadius"), kernel.radius)
|
||||
GLES30.glUniform1fv(uniform("uWeights[0]"), kernel.weights.size, kernel.weights, 0)
|
||||
GLES30.glUniform1f(uniform("uUnsharpAmount"), unsharpAmount)
|
||||
quad.draw(program)
|
||||
val error = GLES30.glGetError()
|
||||
if (error != GLES30.GL_NO_ERROR) {
|
||||
PLog.e(TAG, "Scanner filter failed: vertical=$vertical radius=${kernel.radius} " +
|
||||
"size=${target.width}x${target.height} RGBA16F error=$error")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private fun bindTexture(name: String, unit: Int, texture: Int) {
|
||||
GLES30.glActiveTexture(GLES30.GL_TEXTURE0 + unit)
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, texture)
|
||||
GLES30.glUniform1i(uniform(name), unit)
|
||||
}
|
||||
|
||||
private fun uniform(name: String) = GLES30.glGetUniformLocation(program, name)
|
||||
|
||||
private data class Rect(val x: Int, val y: Int, val width: Int, val height: Int)
|
||||
|
||||
private class Kernel(val weights: FloatArray) {
|
||||
val radius: Int get() = weights.lastIndex
|
||||
|
||||
companion object {
|
||||
fun fromSigma(sigma: Float): Kernel? {
|
||||
val radius = radius(sigma)
|
||||
if (radius == 0) return null
|
||||
val samples = DoubleArray(radius + 1) { offset ->
|
||||
val deviation = offset / sigma.toDouble()
|
||||
exp(-0.5 * deviation * deviation)
|
||||
}
|
||||
val normalization = 2.0 * samples.sum() - samples[0]
|
||||
return Kernel(FloatArray(samples.size) { (samples[it] / normalization).toFloat() })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class Target {
|
||||
var texture = 0
|
||||
private set
|
||||
var framebuffer = 0
|
||||
private set
|
||||
private var width = 0
|
||||
private var height = 0
|
||||
|
||||
fun ensure(width: Int, height: Int): Boolean {
|
||||
if (texture != 0 && this.width == width && this.height == height) return true
|
||||
release()
|
||||
val limit = IntArray(1)
|
||||
GLES30.glGetIntegerv(GLES30.GL_MAX_TEXTURE_SIZE, limit, 0)
|
||||
require(width in 1..limit[0] && height in 1..limit[0]) { "Invalid scanner target ${width}x$height, limit=${limit[0]}" }
|
||||
texture = IntArray(1).also { GLES30.glGenTextures(1, it, 0) }[0]
|
||||
framebuffer = IntArray(1).also { GLES30.glGenFramebuffers(1, it, 0) }[0]
|
||||
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, texture)
|
||||
GLES30.glTexStorage2D(GLES30.GL_TEXTURE_2D, 1, GLES30.GL_RGBA16F, width, height)
|
||||
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_NEAREST)
|
||||
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_NEAREST)
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, framebuffer)
|
||||
GLES30.glFramebufferTexture2D(
|
||||
GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, texture, 0,
|
||||
)
|
||||
val status = GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER)
|
||||
val error = GLES30.glGetError()
|
||||
if (texture == 0 || framebuffer == 0 || status != GLES30.GL_FRAMEBUFFER_COMPLETE || error != GLES30.GL_NO_ERROR) {
|
||||
PLog.e(TAG, "Scanner RGBA16F target allocation failed: size=${width}x$height status=$status error=$error")
|
||||
release()
|
||||
return false
|
||||
}
|
||||
this.width = width
|
||||
this.height = height
|
||||
return true
|
||||
}
|
||||
|
||||
fun release() {
|
||||
if (texture != 0) GLES30.glDeleteTextures(1, intArrayOf(texture), 0)
|
||||
if (framebuffer != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(framebuffer), 0)
|
||||
texture = 0
|
||||
framebuffer = 0
|
||||
width = 0
|
||||
height = 0
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "SpektrafilmScanner"
|
||||
private const val WORK_EDGE = 768
|
||||
private const val MAX_RADIUS = 24
|
||||
|
||||
fun support(tuning: SpectralFilmTuning): Int = radius(tuning.scannerLensBlur) +
|
||||
if (tuning.scannerUnsharpAmount > 0f) radius(tuning.scannerUnsharpSigma) else 0
|
||||
|
||||
// Upstream's 3-sigma FIR footprint gives a finite apron across RAW tile and window boundaries.
|
||||
private fun radius(sigma: Float): Int = (3f * sigma).roundToInt().also { require(it in 0..MAX_RADIUS) }
|
||||
|
||||
internal val FRAGMENT_SHADER = """
|
||||
#version 300 es
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
precision highp sampler2D;
|
||||
|
||||
out vec4 fragColor;
|
||||
uniform sampler2D uSource;
|
||||
uniform sampler2D uOriginal;
|
||||
uniform ivec2 uSourceOffset;
|
||||
uniform ivec2 uAxis;
|
||||
uniform int uRadius;
|
||||
uniform float uWeights[${MAX_RADIUS + 1}];
|
||||
uniform float uUnsharpAmount;
|
||||
|
||||
int reflectPixel(int index, int size) {
|
||||
if (index >= 0 && index < size) return index;
|
||||
int period = 2 * size;
|
||||
int wrapped = (index < 0 ? -index - 1 : index) % period;
|
||||
return min(wrapped, period - 1 - wrapped);
|
||||
}
|
||||
|
||||
vec3 sampleReflected(ivec2 pixel, ivec2 size) {
|
||||
ivec2 position = ivec2(reflectPixel(pixel.x, size.x), reflectPixel(pixel.y, size.y));
|
||||
return texelFetch(uSource, position, 0).rgb;
|
||||
}
|
||||
|
||||
void main() {
|
||||
ivec2 pixel = ivec2(gl_FragCoord.xy) + uSourceOffset;
|
||||
ivec2 size = textureSize(uSource, 0);
|
||||
vec3 filtered = texelFetch(uSource, pixel, 0).rgb * uWeights[0];
|
||||
for (int tap = 1; tap <= uRadius; ++tap) {
|
||||
ivec2 offset = tap * uAxis;
|
||||
filtered += uWeights[tap] * (sampleReflected(pixel - offset, size) +
|
||||
sampleReflected(pixel + offset, size));
|
||||
}
|
||||
if (uUnsharpAmount > 0.0) {
|
||||
vec3 original = texelFetch(uOriginal, pixel, 0).rgb;
|
||||
filtered = original + uUnsharpAmount * (original - filtered);
|
||||
}
|
||||
fragColor = vec4(filtered, 1.0);
|
||||
}
|
||||
""".trimIndent()
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,6 @@ internal object SpektrafilmToneShader {
|
||||
uniform int uSpectralPrintSize;
|
||||
uniform float uSpectralInputScale;
|
||||
uniform float uSpectralPrintInputScale;
|
||||
uniform vec3 uSpectralNegativeDensityGains;
|
||||
""".trimIndent()
|
||||
|
||||
/** Maps linear ProPhoto RGB through the film (and print) stages back to linear ProPhoto RGB. */
|
||||
@@ -51,16 +50,15 @@ internal object SpektrafilmToneShader {
|
||||
spectralLutCoordinate(encodedColor, uSpectralFilmSize)
|
||||
).rgb;
|
||||
if (uSpectralPrintSize > 1) {
|
||||
// The film LUT contains normalized CMY densities. Apply the user's
|
||||
// negative-density gain before the independent print/scanner LUT.
|
||||
// Its lattice spans 0..1.5 to cover every supported density gain.
|
||||
vec3 printInput = filmResult * uSpectralNegativeDensityGains / uSpectralPrintInputScale;
|
||||
// The film LUT contains normalized CMY densities. Map those
|
||||
// directly to the independent print/scanner lattice's domain.
|
||||
vec3 printInput = filmResult / uSpectralPrintInputScale;
|
||||
filmResult = texture(
|
||||
uSpectralPrintTexture,
|
||||
spectralLutCoordinate(printInput, uSpectralPrintSize)
|
||||
).rgb;
|
||||
}
|
||||
// Positive film LUTs already include scanning; both paths end in
|
||||
// Direct film LUTs already include scanning; both paths end in
|
||||
// encoded ProPhoto RGB and share the same linear output contract.
|
||||
return proPhotoToLinear(filmResult);
|
||||
}
|
||||
@@ -109,7 +107,6 @@ internal data class SpectralFilmUniformLocations(
|
||||
val printSize: Int,
|
||||
val inputScale: Int,
|
||||
val printInputScale: Int,
|
||||
val negativeDensityGains: Int,
|
||||
) {
|
||||
companion object {
|
||||
fun query(program: Int) = SpectralFilmUniformLocations(
|
||||
@@ -119,14 +116,13 @@ internal data class SpectralFilmUniformLocations(
|
||||
printSize = GLES30.glGetUniformLocation(program, "uSpectralPrintSize"),
|
||||
inputScale = GLES30.glGetUniformLocation(program, "uSpectralInputScale"),
|
||||
printInputScale = GLES30.glGetUniformLocation(program, "uSpectralPrintInputScale"),
|
||||
negativeDensityGains = GLES30.glGetUniformLocation(program, "uSpectralNegativeDensityGains"),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Owns the film and print 3D textures of one GL context. Stages are uploaded only when
|
||||
* their source asset changes; density tuning only updates uniforms.
|
||||
* their source table changes.
|
||||
*/
|
||||
internal class SpectralFilmStageTextures(filmUnit: Int, printUnit: Int) {
|
||||
private val filmTexture = LutTexture(filmUnit, "film")
|
||||
@@ -139,11 +135,6 @@ internal class SpectralFilmStageTextures(filmUnit: Int, printUnit: Int) {
|
||||
GLES30.glUniform1i(locations.printSize, lut?.printTable?.size ?: 1)
|
||||
GLES30.glUniform1f(locations.inputScale, lut?.inputScale ?: 1f)
|
||||
GLES30.glUniform1f(locations.printInputScale, lut?.printInputScale ?: 1f)
|
||||
val gains = lut?.negativeDensityGains
|
||||
GLES30.glUniform3f(
|
||||
locations.negativeDensityGains,
|
||||
gains?.get(0) ?: 1f, gains?.get(1) ?: 1f, gains?.get(2) ?: 1f,
|
||||
)
|
||||
}
|
||||
|
||||
fun release() {
|
||||
@@ -193,8 +184,7 @@ internal class SpectralFilmStageTextures(filmUnit: Int, printUnit: Int) {
|
||||
check(textureId != 0) { "Unable to allocate Spektrafilm $stage texture" }
|
||||
}
|
||||
textureKey = null
|
||||
// Only allocate/upload when the source asset changes, never for density
|
||||
// adjustments or subsequent frames. Null stages bind a valid 1³ texture.
|
||||
// Only allocate/upload when the source table changes. Null stages bind a valid 1³ texture.
|
||||
val buffer = ByteBuffer.allocateDirect(values.size * Float.SIZE_BYTES)
|
||||
.order(ByteOrder.nativeOrder()).asFloatBuffer().apply {
|
||||
put(values)
|
||||
|
||||
@@ -18,7 +18,6 @@ import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.draw.rotate
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
@@ -51,7 +50,6 @@ import com.hinnka.mycamera.raw.RawWhiteLevelCorrection
|
||||
import com.hinnka.mycamera.raw.RawNoiseProfileInfo
|
||||
import com.hinnka.mycamera.raw.SpectralFilmSelection
|
||||
import com.hinnka.mycamera.raw.SpectralFilmUiInfo
|
||||
import com.hinnka.mycamera.raw.SpectralFilmTuning
|
||||
import com.hinnka.mycamera.raw.fotufilm.FotufilmDocument
|
||||
import kotlin.math.roundToInt
|
||||
import com.hinnka.mycamera.ui.settings.DropdownSettingItem
|
||||
@@ -481,13 +479,32 @@ fun RawRenderingEngineSettingsPanel(
|
||||
},
|
||||
)
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
if (!isPositiveFilm) {
|
||||
if (!isPositiveFilm && spectralFilmSelection != null) {
|
||||
SwitchSettingItem(
|
||||
title = stringResource(R.string.spektrafilm_scan_film),
|
||||
description = stringResource(R.string.spektrafilm_scan_film_description),
|
||||
checked = spectralFilmSelection.tuning.scanFilm,
|
||||
onCheckedChange = { scanFilm ->
|
||||
onSpectralFilmSelectionChange(
|
||||
spectralFilmSelection.copy(tuning = spectralFilmSelection.tuning.copy(scanFilm = scanFilm))
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
if (!isPositiveFilm && spectralFilmSelection?.tuning?.scanFilm != true) {
|
||||
RawSpectralPrintSelector(
|
||||
selectedPrint = spectralFilmPrint,
|
||||
onSelectPrint = onSpectralFilmPrintChange,
|
||||
)
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
}
|
||||
if (showToneMappingControls && spectralFilmSelection != null) {
|
||||
SpektrafilmControls(
|
||||
selection = spectralFilmSelection,
|
||||
onSelectionChange = onSpectralFilmSelectionChange,
|
||||
)
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
}
|
||||
}
|
||||
|
||||
if (rawRenderingEngine.isFotufilm && fotufilmDocument != null) {
|
||||
@@ -504,9 +521,7 @@ fun RawRenderingEngineSettingsPanel(
|
||||
RawToneMappingControls(
|
||||
rawRenderingEngine = rawRenderingEngine,
|
||||
params = rawToneMappingParameters.normalized(),
|
||||
spectralFilmSelection = spectralFilmSelection,
|
||||
onParamsChange = onRawToneMappingParametersChange,
|
||||
onSpectralFilmSelectionChange = onSpectralFilmSelectionChange,
|
||||
onAdjustmentStart = onAdjustmentStart,
|
||||
onAdjustmentEnd = onAdjustmentEnd,
|
||||
)
|
||||
@@ -1073,39 +1088,11 @@ fun RawEngineToneCurveControls(
|
||||
private fun RawToneMappingControls(
|
||||
rawRenderingEngine: RawRenderingEngine,
|
||||
params: RawToneMappingParameters,
|
||||
spectralFilmSelection: SpectralFilmSelection?,
|
||||
onParamsChange: (RawToneMappingParameters) -> Unit,
|
||||
onSpectralFilmSelectionChange: (SpectralFilmSelection?) -> Unit,
|
||||
onAdjustmentStart: () -> Unit,
|
||||
onAdjustmentEnd: () -> Unit
|
||||
) {
|
||||
var localSpectralFilmTuning by remember(spectralFilmSelection?.id) {
|
||||
mutableStateOf(spectralFilmSelection?.tuning ?: SpectralFilmTuning.DEFAULT)
|
||||
}
|
||||
var spectralFilmTuningExpanded by remember(spectralFilmSelection?.id) { mutableStateOf(false) }
|
||||
|
||||
LaunchedEffect(spectralFilmSelection) {
|
||||
localSpectralFilmTuning = spectralFilmSelection?.tuning ?: SpectralFilmTuning.DEFAULT
|
||||
}
|
||||
|
||||
fun updateSpectralFilmTuning(value: SpectralFilmTuning) {
|
||||
onAdjustmentStart()
|
||||
localSpectralFilmTuning = value
|
||||
}
|
||||
|
||||
fun commitSpectralFilmDensityGains() {
|
||||
val selection = spectralFilmSelection ?: return
|
||||
onSpectralFilmSelectionChange(selection.copy(tuning = localSpectralFilmTuning.normalized()))
|
||||
onAdjustmentEnd()
|
||||
}
|
||||
|
||||
when (rawRenderingEngine) {
|
||||
RawRenderingEngine.AdobeCurve,
|
||||
RawRenderingEngine.Hncs,
|
||||
RawRenderingEngine.Lumix,
|
||||
RawRenderingEngine.Canon,
|
||||
RawRenderingEngine.Leica -> Unit
|
||||
|
||||
RawRenderingEngine.AgX,
|
||||
RawRenderingEngine.DarktableFilmic -> {
|
||||
RawEngineToneCurveControls(
|
||||
@@ -1117,94 +1104,10 @@ private fun RawToneMappingControls(
|
||||
)
|
||||
}
|
||||
|
||||
RawRenderingEngine.Spektrafilm -> {
|
||||
if (!SpectralFilmUiInfo.isPositiveFilm(spectralFilmSelection?.id)) {
|
||||
RawSpectralFilmTuningHeader(
|
||||
expanded = spectralFilmTuningExpanded,
|
||||
onClick = { spectralFilmTuningExpanded = !spectralFilmTuningExpanded }
|
||||
)
|
||||
if (spectralFilmTuningExpanded) {
|
||||
SliderSettingItem(
|
||||
title = stringResource(R.string.settings_spectral_film_c_density_gain),
|
||||
value = localSpectralFilmTuning.cDensityGain,
|
||||
valueRange = SpectralFilmTuning.MIN_DENSITY_GAIN..SpectralFilmTuning.MAX_DENSITY_GAIN,
|
||||
resetValue = 1f,
|
||||
valueTextFormatter = { "${(it * 100f).roundToInt()}%" },
|
||||
onValueChange = {
|
||||
updateSpectralFilmTuning(localSpectralFilmTuning.copy(cDensityGain = it))
|
||||
},
|
||||
onValueChangeFinished = ::commitSpectralFilmDensityGains
|
||||
)
|
||||
SliderSettingItem(
|
||||
title = stringResource(R.string.settings_spectral_film_m_density_gain),
|
||||
value = localSpectralFilmTuning.mDensityGain,
|
||||
valueRange = SpectralFilmTuning.MIN_DENSITY_GAIN..SpectralFilmTuning.MAX_DENSITY_GAIN,
|
||||
resetValue = 1f,
|
||||
valueTextFormatter = { "${(it * 100f).roundToInt()}%" },
|
||||
onValueChange = {
|
||||
updateSpectralFilmTuning(localSpectralFilmTuning.copy(mDensityGain = it))
|
||||
},
|
||||
onValueChangeFinished = ::commitSpectralFilmDensityGains
|
||||
)
|
||||
SliderSettingItem(
|
||||
title = stringResource(R.string.settings_spectral_film_y_density_gain),
|
||||
value = localSpectralFilmTuning.yDensityGain,
|
||||
valueRange = SpectralFilmTuning.MIN_DENSITY_GAIN..SpectralFilmTuning.MAX_DENSITY_GAIN,
|
||||
resetValue = 1f,
|
||||
valueTextFormatter = { "${(it * 100f).roundToInt()}%" },
|
||||
onValueChange = {
|
||||
updateSpectralFilmTuning(localSpectralFilmTuning.copy(yDensityGain = it))
|
||||
},
|
||||
onValueChangeFinished = ::commitSpectralFilmDensityGains
|
||||
)
|
||||
}
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
}
|
||||
}
|
||||
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RawSpectralFilmTuningHeader(
|
||||
expanded: Boolean,
|
||||
onClick: () -> Unit
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.clickable(onClick = onClick)
|
||||
.padding(vertical = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = stringResource(R.string.settings_spectral_film_tuning),
|
||||
color = Color.White,
|
||||
fontSize = 16.sp,
|
||||
fontWeight = FontWeight.Normal
|
||||
)
|
||||
Spacer(modifier = Modifier.height(4.dp))
|
||||
Text(
|
||||
text = stringResource(R.string.settings_spectral_film_tuning_description),
|
||||
color = Color.White.copy(alpha = 0.55f),
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 18.sp
|
||||
)
|
||||
}
|
||||
Icon(
|
||||
imageVector = AppIcons.ChevronRight,
|
||||
contentDescription = null,
|
||||
tint = Color.White.copy(alpha = 0.75f),
|
||||
modifier = Modifier
|
||||
.size(22.dp)
|
||||
.rotate(if (expanded) 90f else 0f)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RawDROModeSettingItem(
|
||||
title: String,
|
||||
@@ -2366,8 +2269,8 @@ fun RawSpectralFilmSelector(
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(if (isSelected) AccentColor.copy(alpha = 0.15f) else Color.Transparent)
|
||||
.clickable {
|
||||
onSelectFilm(film)
|
||||
showSheet = false
|
||||
if (!isSelected) onSelectFilm(film)
|
||||
}
|
||||
.padding(16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
@@ -2475,8 +2378,8 @@ fun RawSpectralPrintSelector(
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(if (isSelected) AccentColor.copy(alpha = 0.15f) else Color.Transparent)
|
||||
.clickable {
|
||||
onSelectPrint(print)
|
||||
showSheet = false
|
||||
if (!isSelected) onSelectPrint(print)
|
||||
}
|
||||
.padding(16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
package com.hinnka.mycamera.ui.components
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import com.hinnka.mycamera.R
|
||||
import com.hinnka.mycamera.raw.SpectralFilmTuning
|
||||
import com.hinnka.mycamera.raw.SpectralKnee
|
||||
|
||||
@Composable
|
||||
internal fun SpektrafilmScannerLevels(
|
||||
tuning: SpectralFilmTuning,
|
||||
onCommit: (SpectralFilmTuning) -> Unit,
|
||||
) {
|
||||
SwitchSettingItem(
|
||||
title = stringResource(R.string.spektrafilm_scanner_white_correction),
|
||||
checked = tuning.scanWhiteCorrection,
|
||||
onCheckedChange = { onCommit(tuning.copy(scanWhiteCorrection = it)) },
|
||||
)
|
||||
if (tuning.scanWhiteCorrection) {
|
||||
SpektrafilmNumberSetting(
|
||||
R.string.spektrafilm_scanner_white_level, tuning.scanWhiteLevel, 0f..1f, 0.005f,
|
||||
SpectralFilmTuning.DEFAULT.scanWhiteLevel, R.string.spektrafilm_value_precise,
|
||||
) { onCommit(tuning.copy(scanWhiteLevel = it)) }
|
||||
}
|
||||
SwitchSettingItem(
|
||||
title = stringResource(R.string.spektrafilm_scanner_black_correction),
|
||||
checked = tuning.scanBlackCorrection,
|
||||
onCheckedChange = { onCommit(tuning.copy(scanBlackCorrection = it)) },
|
||||
)
|
||||
if (tuning.scanBlackCorrection) {
|
||||
SpektrafilmNumberSetting(
|
||||
R.string.spektrafilm_scanner_black_level, tuning.scanBlackLevel, 0f..1f, 0.005f,
|
||||
SpectralFilmTuning.DEFAULT.scanBlackLevel, R.string.spektrafilm_value_precise,
|
||||
) { onCommit(tuning.copy(scanBlackLevel = it)) }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun SpektrafilmSpectralAndGamutControls(
|
||||
tuning: SpectralFilmTuning,
|
||||
onCommit: (SpectralFilmTuning) -> Unit,
|
||||
) {
|
||||
SpektrafilmSection(R.string.spektrafilm_section_spectral) {
|
||||
SpektrafilmChoiceSetting(
|
||||
title = R.string.spektrafilm_spectral_method,
|
||||
value = tuning.spectralMethod,
|
||||
choices = listOf(
|
||||
0 to stringResource(R.string.spektrafilm_spectral_hanatos),
|
||||
1 to stringResource(R.string.spektrafilm_spectral_mallett),
|
||||
),
|
||||
onCommit = { onCommit(tuning.copy(spectralMethod = it)) },
|
||||
)
|
||||
if (tuning.spectralMethod == 0) {
|
||||
SwitchSettingItem(
|
||||
title = stringResource(R.string.spektrafilm_spectral_adaptation_window),
|
||||
checked = tuning.spectralAdaptationWindow,
|
||||
onCheckedChange = { onCommit(tuning.copy(spectralAdaptationWindow = it)) },
|
||||
)
|
||||
SwitchSettingItem(
|
||||
title = stringResource(R.string.spektrafilm_spectral_adaptation_surface),
|
||||
checked = tuning.spectralAdaptationSurface,
|
||||
onCheckedChange = { onCommit(tuning.copy(spectralAdaptationSurface = it)) },
|
||||
)
|
||||
SpektrafilmNumberSetting(
|
||||
R.string.spektrafilm_spectral_blur, tuning.spectralBlur, 0f..5f, 0.1f,
|
||||
SpectralFilmTuning.DEFAULT.spectralBlur, R.string.spektrafilm_value_nm,
|
||||
) { onCommit(tuning.copy(spectralBlur = it)) }
|
||||
}
|
||||
}
|
||||
if (tuning.spectralMethod == 0) {
|
||||
SpektrafilmSection(R.string.spektrafilm_input_gamut_compression) {
|
||||
SwitchSettingItem(
|
||||
title = stringResource(R.string.spektrafilm_gamut_enabled),
|
||||
description = stringResource(R.string.spektrafilm_input_gamut_compression_description),
|
||||
checked = tuning.inputGamutCompression,
|
||||
onCheckedChange = { onCommit(tuning.copy(inputGamutCompression = it)) },
|
||||
)
|
||||
if (tuning.inputGamutCompression) {
|
||||
SpektrafilmChoiceSetting(
|
||||
title = R.string.spektrafilm_gamut_algorithm,
|
||||
value = tuning.inputGamutMethod,
|
||||
choices = listOf(
|
||||
0 to stringResource(R.string.spektrafilm_gamut_xy),
|
||||
1 to stringResource(R.string.spektrafilm_gamut_oklch),
|
||||
),
|
||||
onCommit = { onCommit(tuning.copy(inputGamutMethod = it)) },
|
||||
)
|
||||
SpektrafilmGamutKnee(tuning.inputGamutKnee) { onCommit(tuning.copy(inputGamutKnee = it)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
SpektrafilmSection(R.string.spektrafilm_section_output_gamut) {
|
||||
SpektrafilmChoiceSetting(
|
||||
title = R.string.spektrafilm_gamut_algorithm,
|
||||
value = tuning.outputGamutMethod,
|
||||
choices = listOf(
|
||||
0 to stringResource(R.string.spektrafilm_gamut_cam16ucs),
|
||||
1 to stringResource(R.string.spektrafilm_gamut_off),
|
||||
2 to stringResource(R.string.spektrafilm_gamut_oklch),
|
||||
3 to stringResource(R.string.spektrafilm_gamut_acesrgc),
|
||||
4 to stringResource(R.string.spektrafilm_gamut_oklrab),
|
||||
5 to stringResource(R.string.spektrafilm_gamut_jzazbz),
|
||||
),
|
||||
onCommit = { onCommit(tuning.copy(outputGamutMethod = it)) },
|
||||
)
|
||||
if (tuning.outputGamutMethod != 1) {
|
||||
SpektrafilmGamutKnee(tuning.outputGamutKnee) { onCommit(tuning.copy(outputGamutKnee = it)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SpektrafilmGamutKnee(settings: SpectralKnee, onCommit: (SpectralKnee) -> Unit) {
|
||||
SpektrafilmSection(R.string.recipe_panel_advanced) {
|
||||
SpektrafilmNumberControls(gamutKneeControls, settings, gamutKneeDefaults, onCommit)
|
||||
SpektrafilmNumberSetting(
|
||||
R.string.spektrafilm_gamut_limit, settings.limit, (settings.threshold + 0.01f)..4f, 0.01f,
|
||||
gamutKneeDefaults.limit,
|
||||
) { onCommit(settings.copy(limit = it)) }
|
||||
}
|
||||
}
|
||||
|
||||
private val gamutKneeDefaults = SpectralKnee()
|
||||
private val gamutKneeControls = listOf(
|
||||
SpektrafilmNumberSpec(R.string.spektrafilm_gamut_threshold, 0f..0.99f, 0.01f, SpectralKnee::threshold) {
|
||||
copy(threshold = it)
|
||||
},
|
||||
SpektrafilmNumberSpec(R.string.spektrafilm_gamut_power, 0.1f..16f, 0.1f, SpectralKnee::power) {
|
||||
copy(power = it)
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,227 @@
|
||||
package com.hinnka.mycamera.ui.components
|
||||
|
||||
import androidx.annotation.StringRes
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.key
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.draw.rotate
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.hinnka.mycamera.R
|
||||
import com.hinnka.mycamera.raw.SpectralRgb
|
||||
import com.hinnka.mycamera.ui.icons.AppIcons
|
||||
import com.hinnka.mycamera.ui.settings.DropdownSettingItem
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.expm1
|
||||
import kotlin.math.ln1p
|
||||
import kotlin.math.roundToInt
|
||||
import kotlin.math.sign
|
||||
|
||||
@Composable
|
||||
internal fun SpektrafilmSection(
|
||||
@StringRes title: Int,
|
||||
content: @Composable () -> Unit,
|
||||
) {
|
||||
var expanded by rememberSaveable { mutableStateOf(false) }
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.clickable { expanded = !expanded }
|
||||
.padding(vertical = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(title),
|
||||
modifier = Modifier.weight(1f),
|
||||
color = Color.White,
|
||||
fontSize = 16.sp,
|
||||
)
|
||||
Icon(
|
||||
imageVector = AppIcons.ChevronRight,
|
||||
contentDescription = null,
|
||||
tint = Color.White.copy(alpha = 0.75f),
|
||||
modifier = Modifier.size(22.dp).rotate(if (expanded) 90f else 0f),
|
||||
)
|
||||
}
|
||||
if (expanded) {
|
||||
Column(Modifier.fillMaxWidth().padding(start = 12.dp)) { content() }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun SpektrafilmNumberSetting(
|
||||
@StringRes title: Int,
|
||||
value: Float,
|
||||
range: ClosedFloatingPointRange<Float>,
|
||||
step: Float,
|
||||
resetValue: Float,
|
||||
@StringRes format: Int = R.string.spektrafilm_value_decimal,
|
||||
logarithmicScale: Float? = null,
|
||||
onCommit: (Float) -> Unit,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
var pending by remember { mutableStateOf<Float?>(null) }
|
||||
val number = pending ?: value
|
||||
fun toPosition(number: Float): Float = logarithmicScale?.let { scale ->
|
||||
sign(number) * ln1p(abs(number) / scale)
|
||||
} ?: number
|
||||
val positionRange = toPosition(range.start)..toPosition(range.endInclusive)
|
||||
SliderSettingItem(
|
||||
title = stringResource(title),
|
||||
value = toPosition(number),
|
||||
valueRange = positionRange,
|
||||
resetValue = toPosition(resetValue),
|
||||
valueTextFormatter = {
|
||||
val displayValue = if (format == R.string.spektrafilm_value_percent) number * 100f else number
|
||||
context.getString(format, displayValue)
|
||||
},
|
||||
onResetValue = {
|
||||
pending = null
|
||||
onCommit(resetValue)
|
||||
},
|
||||
onValueChange = { position ->
|
||||
pending = when {
|
||||
position <= positionRange.start -> range.start
|
||||
position >= positionRange.endInclusive -> range.endInclusive
|
||||
else -> {
|
||||
val adjusted = logarithmicScale?.let { scale ->
|
||||
sign(position) * expm1(abs(position)) * scale
|
||||
} ?: position
|
||||
((adjusted / step).roundToInt() * step).coerceIn(range)
|
||||
}
|
||||
}
|
||||
},
|
||||
onValueChangeFinished = {
|
||||
pending?.let(onCommit)
|
||||
pending = null
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
internal class SpektrafilmNumberSpec<T>(
|
||||
@param:StringRes val title: Int,
|
||||
val range: ClosedFloatingPointRange<Float>,
|
||||
val step: Float,
|
||||
val read: (T) -> Float,
|
||||
@param:StringRes val format: Int = R.string.spektrafilm_value_decimal,
|
||||
val logarithmicScale: Float? = null,
|
||||
val write: T.(Float) -> T,
|
||||
)
|
||||
|
||||
@Composable
|
||||
internal fun <T> SpektrafilmNumberControls(
|
||||
specs: List<SpektrafilmNumberSpec<T>>,
|
||||
settings: T,
|
||||
defaults: T,
|
||||
onCommit: (T) -> Unit,
|
||||
) {
|
||||
for (spec in specs) {
|
||||
SpektrafilmNumberControl(spec, settings, defaults, onCommit)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun <T> SpektrafilmNumberControl(
|
||||
spec: SpektrafilmNumberSpec<T>,
|
||||
settings: T,
|
||||
defaults: T,
|
||||
onCommit: (T) -> Unit,
|
||||
) {
|
||||
key(spec.title) {
|
||||
SpektrafilmNumberSetting(
|
||||
title = spec.title,
|
||||
value = spec.read(settings),
|
||||
range = spec.range,
|
||||
step = spec.step,
|
||||
resetValue = spec.read(defaults),
|
||||
format = spec.format,
|
||||
logarithmicScale = spec.logarithmicScale,
|
||||
onCommit = { onCommit(spec.write(settings, it)) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private data class RgbChannel(
|
||||
val title: Int,
|
||||
val read: (SpectralRgb) -> Float,
|
||||
val write: SpectralRgb.(Float) -> SpectralRgb,
|
||||
)
|
||||
|
||||
private val rgbChannels = listOf(
|
||||
RgbChannel(R.string.recipe_lch_red, SpectralRgb::r) { copy(r = it) },
|
||||
RgbChannel(R.string.recipe_lch_green, SpectralRgb::g) { copy(g = it) },
|
||||
RgbChannel(R.string.recipe_lch_blue, SpectralRgb::b) { copy(b = it) },
|
||||
)
|
||||
|
||||
@Composable
|
||||
internal fun SpektrafilmRgbSetting(
|
||||
@StringRes title: Int,
|
||||
value: SpectralRgb,
|
||||
defaults: SpectralRgb,
|
||||
range: ClosedFloatingPointRange<Float>,
|
||||
step: Float,
|
||||
@StringRes format: Int = R.string.spektrafilm_value_decimal,
|
||||
@StringRes redTitle: Int = R.string.recipe_lch_red,
|
||||
@StringRes greenTitle: Int = R.string.recipe_lch_green,
|
||||
@StringRes blueTitle: Int = R.string.recipe_lch_blue,
|
||||
maxAtDefault: Boolean = false,
|
||||
onCommit: (SpectralRgb) -> Unit,
|
||||
) {
|
||||
SpektrafilmSection(title) {
|
||||
val titles = intArrayOf(redTitle, greenTitle, blueTitle)
|
||||
rgbChannels.forEachIndexed { index, channel ->
|
||||
key(channel.title) {
|
||||
val resetValue = channel.read(defaults)
|
||||
val maximum = if (maxAtDefault) resetValue else range.endInclusive
|
||||
if (maximum > range.start) {
|
||||
SpektrafilmNumberSetting(
|
||||
title = titles[index],
|
||||
value = channel.read(value),
|
||||
range = range.start..maximum,
|
||||
step = step,
|
||||
resetValue = resetValue,
|
||||
format = format,
|
||||
onCommit = { onCommit(channel.write(value, it)) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun <T> SpektrafilmChoiceSetting(
|
||||
@StringRes title: Int,
|
||||
value: T,
|
||||
choices: List<Pair<T, String>>,
|
||||
onCommit: (T) -> Unit,
|
||||
) {
|
||||
DropdownSettingItem(
|
||||
title = stringResource(title),
|
||||
value = choices.first { it.first == value }.second,
|
||||
options = choices.map { it.second },
|
||||
isLoading = false,
|
||||
onExpanded = {},
|
||||
onOptionSelected = { label -> onCommit(choices.first { it.second == label }.first) },
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
package com.hinnka.mycamera.ui.components
|
||||
|
||||
import androidx.annotation.StringRes
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.key
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import com.hinnka.mycamera.R
|
||||
import com.hinnka.mycamera.raw.SpectralDyeOrder
|
||||
import com.hinnka.mycamera.raw.SpectralFilmSelection
|
||||
import com.hinnka.mycamera.raw.SpectralFilmTuning
|
||||
import com.hinnka.mycamera.raw.SpectralFilmUiInfo
|
||||
import java.text.DecimalFormatSymbols
|
||||
|
||||
@Composable
|
||||
internal fun SpektrafilmControls(
|
||||
selection: SpectralFilmSelection,
|
||||
onSelectionChange: (SpectralFilmSelection) -> Unit,
|
||||
) {
|
||||
val tuning = selection.tuning
|
||||
val positive = SpectralFilmUiInfo.isPositiveFilm(selection.id)
|
||||
val printsToPaper = !positive && !tuning.scanFilm
|
||||
fun commit(next: SpectralFilmTuning) {
|
||||
if (next != tuning) onSelectionChange(selection.copy(tuning = next.normalized()))
|
||||
}
|
||||
|
||||
val slider: @Composable (SliderSpec) -> Unit = { spec ->
|
||||
SpektrafilmNumberControl(spec, tuning, SpectralFilmTuning.DEFAULT, ::commit)
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxWidth()) {
|
||||
key(selection.id) {
|
||||
SpektrafilmSection(R.string.spektrafilm_section_film) {
|
||||
filmSliders.forEach { slider(it) }
|
||||
DyeOrderSetting(
|
||||
title = R.string.spektrafilm_film_dye_order,
|
||||
order = tuning.filmDyeOrder,
|
||||
onOrderChange = { commit(tuning.copy(filmDyeOrder = it)) },
|
||||
)
|
||||
}
|
||||
SpektrafilmDiffusionSection(R.string.spektrafilm_section_camera_diffusion, tuning.cameraDiffusion) {
|
||||
commit(tuning.copy(cameraDiffusion = it))
|
||||
}
|
||||
SpektrafilmHalationSection(selection.id, tuning.halation) { commit(tuning.copy(halation = it)) }
|
||||
SpektrafilmSection(R.string.spektrafilm_section_couplers) {
|
||||
SwitchSettingItem(
|
||||
title = stringResource(R.string.spektrafilm_dir_enabled),
|
||||
description = stringResource(R.string.spektrafilm_dir_description),
|
||||
checked = tuning.dirEnabled,
|
||||
onCheckedChange = { commit(tuning.copy(dirEnabled = it)) },
|
||||
)
|
||||
if (tuning.dirEnabled) {
|
||||
couplerSliders.forEach { slider(it) }
|
||||
SpektrafilmDirAdvancedControls(selection.id, tuning, ::commit)
|
||||
}
|
||||
}
|
||||
SpektrafilmGrainSection(tuning.grain) { commit(tuning.copy(grain = it)) }
|
||||
if (printsToPaper) {
|
||||
SpektrafilmSection(R.string.spektrafilm_section_enlarger) {
|
||||
SwitchSettingItem(
|
||||
title = stringResource(R.string.spektrafilm_print_exposure_compensation),
|
||||
description = stringResource(R.string.spektrafilm_print_exposure_compensation_description),
|
||||
checked = tuning.printExposureCompensation,
|
||||
onCheckedChange = { commit(tuning.copy(printExposureCompensation = it)) },
|
||||
)
|
||||
SwitchSettingItem(
|
||||
title = stringResource(R.string.spektrafilm_print_normalize_exposure),
|
||||
description = stringResource(R.string.spektrafilm_print_normalize_exposure_description),
|
||||
checked = tuning.printNormalizeExposure,
|
||||
onCheckedChange = { commit(tuning.copy(printNormalizeExposure = it)) },
|
||||
)
|
||||
printSliders.forEach { slider(it) }
|
||||
DyeOrderSetting(
|
||||
title = R.string.spektrafilm_print_dye_order,
|
||||
order = tuning.printDyeOrder,
|
||||
onOrderChange = { commit(tuning.copy(printDyeOrder = it)) },
|
||||
)
|
||||
}
|
||||
SpektrafilmDiffusionSection(R.string.spektrafilm_section_enlarger_diffusion, tuning.enlargerDiffusion) {
|
||||
commit(tuning.copy(enlargerDiffusion = it))
|
||||
}
|
||||
SpektrafilmSection(R.string.spektrafilm_section_preflash) {
|
||||
PreflashExposureSetting(tuning.preflashExposure) {
|
||||
commit(tuning.copy(preflashExposure = it))
|
||||
}
|
||||
if (tuning.preflashExposure > 0f) preflashFilterSliders.forEach { slider(it) }
|
||||
}
|
||||
SpektrafilmSection(R.string.spektrafilm_section_chemistry) {
|
||||
SwitchSettingItem(
|
||||
title = stringResource(R.string.spektrafilm_print_chemistry_enabled),
|
||||
description = stringResource(R.string.spektrafilm_print_chemistry_description),
|
||||
checked = tuning.printChemistryEnabled,
|
||||
onCheckedChange = { commit(tuning.copy(printChemistryEnabled = it)) },
|
||||
)
|
||||
if (tuning.printChemistryEnabled) chemistrySliders.forEach { slider(it) }
|
||||
}
|
||||
SpektrafilmGlareSection(tuning.glare) { commit(tuning.copy(glare = it)) }
|
||||
}
|
||||
SpektrafilmSection(R.string.spektrafilm_section_scanner) {
|
||||
scannerSliders.forEach { slider(it) }
|
||||
if (tuning.scannerUnsharpAmount > 0f) slider(scannerUnsharpSigmaSlider)
|
||||
if (positive || printsToPaper) SpektrafilmScannerLevels(tuning, ::commit)
|
||||
}
|
||||
SpektrafilmSpectralAndGamutControls(tuning, ::commit)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private const val PREFLASH_SLIDER_MAX = 0.04f
|
||||
|
||||
@Composable
|
||||
private fun PreflashExposureSetting(value: Float, onCommit: (Float) -> Unit) {
|
||||
var draft by rememberSaveable { mutableStateOf<String?>(null) }
|
||||
val inSliderRange = value <= PREFLASH_SLIDER_MAX
|
||||
if (inSliderRange) {
|
||||
SpektrafilmNumberSetting(
|
||||
title = R.string.spektrafilm_preflash_exposure,
|
||||
value = value,
|
||||
range = 0f..PREFLASH_SLIDER_MAX,
|
||||
step = 0.0001f,
|
||||
resetValue = 0f,
|
||||
format = R.string.spektrafilm_value_preflash_exposure,
|
||||
onCommit = onCommit,
|
||||
)
|
||||
} else {
|
||||
Text(
|
||||
text = stringResource(R.string.spektrafilm_preflash_high_value, value),
|
||||
color = Color.White,
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
)
|
||||
}
|
||||
Row {
|
||||
TextButton(onClick = { draft = value.toBigDecimal().toPlainString() }) {
|
||||
Text(stringResource(R.string.spektrafilm_preflash_enter_value))
|
||||
}
|
||||
if (!inSliderRange) {
|
||||
TextButton(onClick = { onCommit(0f) }) {
|
||||
Text(stringResource(R.string.spektrafilm_preflash_reset))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val input = draft ?: return
|
||||
val separator = DecimalFormatSymbols.getInstance(LocalConfiguration.current.locales[0]).decimalSeparator
|
||||
val dose = input.trim().map { character ->
|
||||
when (character) {
|
||||
separator, ',' -> '.'
|
||||
else -> character.digitToIntOrNull()?.digitToChar() ?: character
|
||||
}
|
||||
}.joinToString("").toFloatOrNull()?.takeIf { it in 0f..1f }
|
||||
fun applyDose() {
|
||||
val amount = dose ?: return
|
||||
draft = null
|
||||
onCommit(if (amount == 0f) 0f else amount)
|
||||
}
|
||||
AlertDialog(
|
||||
onDismissRequest = { draft = null },
|
||||
title = { Text(stringResource(R.string.spektrafilm_preflash_exposure)) },
|
||||
text = {
|
||||
OutlinedTextField(
|
||||
value = input,
|
||||
onValueChange = { draft = it },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
label = { Text(stringResource(R.string.spektrafilm_preflash_enter_value)) },
|
||||
supportingText = { Text(stringResource(R.string.spektrafilm_preflash_input_range)) },
|
||||
isError = input.isNotBlank() && dose == null,
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal, imeAction = ImeAction.Done),
|
||||
keyboardActions = KeyboardActions(onDone = { applyDose() }),
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(enabled = dose != null, onClick = ::applyDose) { Text(stringResource(R.string.confirm)) }
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { draft = null }) { Text(stringResource(R.string.cancel)) }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun DyeOrderSetting(
|
||||
@StringRes title: Int,
|
||||
order: SpectralDyeOrder,
|
||||
onOrderChange: (SpectralDyeOrder) -> Unit,
|
||||
) {
|
||||
SpektrafilmChoiceSetting(title, order, SpectralDyeOrder.entries.map { it to it.name }, onOrderChange)
|
||||
}
|
||||
|
||||
private typealias SliderSpec = SpektrafilmNumberSpec<SpectralFilmTuning>
|
||||
|
||||
private val filmSliders = listOf(
|
||||
SliderSpec(
|
||||
R.string.spektrafilm_film_format, 8f..120f, 1f,
|
||||
SpectralFilmTuning::filmFormatMm, R.string.spektrafilm_value_mm,
|
||||
) { copy(filmFormatMm = it) },
|
||||
SliderSpec(
|
||||
R.string.spektrafilm_camera_lens_blur, 0f..30f, 0.05f,
|
||||
SpectralFilmTuning::cameraLensBlurUm, R.string.spektrafilm_value_um,
|
||||
) { copy(cameraLensBlurUm = it) },
|
||||
SliderSpec(
|
||||
R.string.spektrafilm_camera_exposure, -5f..5f, 0.25f,
|
||||
SpectralFilmTuning::cameraExposureEv, R.string.spektrafilm_value_ev,
|
||||
) { copy(cameraExposureEv = it) },
|
||||
SliderSpec(
|
||||
R.string.spektrafilm_film_gamma, 0.1f..3f, 0.05f, SpectralFilmTuning::filmGamma,
|
||||
) { copy(filmGamma = it) },
|
||||
)
|
||||
|
||||
private val couplerSliders = listOf(
|
||||
SliderSpec(R.string.spektrafilm_dir_amount, 0f..1f, 0.05f, SpectralFilmTuning::dirAmount) {
|
||||
copy(dirAmount = it)
|
||||
},
|
||||
SliderSpec(R.string.spektrafilm_dir_same_layer, 0f..1f, 0.05f, SpectralFilmTuning::dirSameLayer) {
|
||||
copy(dirSameLayer = it)
|
||||
},
|
||||
SliderSpec(R.string.spektrafilm_dir_inter_layer, 0f..1f, 0.05f, SpectralFilmTuning::dirInterLayer) {
|
||||
copy(dirInterLayer = it)
|
||||
},
|
||||
)
|
||||
|
||||
private val printSliders = listOf(
|
||||
SliderSpec(R.string.spektrafilm_print_exposure, 0f..4f, 0.02f, SpectralFilmTuning::printExposure) {
|
||||
copy(printExposure = it)
|
||||
},
|
||||
SliderSpec(
|
||||
R.string.spektrafilm_yellow_filter, -200f..200f, 1f,
|
||||
SpectralFilmTuning::printYellowShift, R.string.spektrafilm_value_cc,
|
||||
) { copy(printYellowShift = it) },
|
||||
SliderSpec(
|
||||
R.string.spektrafilm_magenta_filter, -200f..200f, 1f,
|
||||
SpectralFilmTuning::printMagentaShift, R.string.spektrafilm_value_cc,
|
||||
) { copy(printMagentaShift = it) },
|
||||
)
|
||||
|
||||
private val preflashFilterSliders = listOf(
|
||||
SliderSpec(
|
||||
R.string.spektrafilm_yellow_filter, -200f..200f, 1f,
|
||||
SpectralFilmTuning::preflashYellowShift, R.string.spektrafilm_value_cc,
|
||||
logarithmicScale = 2f,
|
||||
) { copy(preflashYellowShift = it) },
|
||||
SliderSpec(
|
||||
R.string.spektrafilm_magenta_filter, -200f..200f, 1f,
|
||||
SpectralFilmTuning::preflashMagentaShift, R.string.spektrafilm_value_cc,
|
||||
logarithmicScale = 2f,
|
||||
) { copy(preflashMagentaShift = it) },
|
||||
)
|
||||
|
||||
private val chemistrySliders = listOf(
|
||||
SliderSpec(R.string.spektrafilm_print_gamma, 0.5f..2f, 0.05f, SpectralFilmTuning::printGamma) {
|
||||
copy(printGamma = it)
|
||||
},
|
||||
SliderSpec(R.string.spektrafilm_print_gamma_fast, 0.5f..2f, 0.05f, SpectralFilmTuning::printGammaFast) {
|
||||
copy(printGammaFast = it)
|
||||
},
|
||||
SliderSpec(R.string.spektrafilm_print_gamma_slow, 0.5f..2f, 0.05f, SpectralFilmTuning::printGammaSlow) {
|
||||
copy(printGammaSlow = it)
|
||||
},
|
||||
SliderSpec(R.string.spektrafilm_print_gamma_red, 0.5f..2f, 0.02f, SpectralFilmTuning::printGammaRed) {
|
||||
copy(printGammaRed = it)
|
||||
},
|
||||
SliderSpec(R.string.spektrafilm_print_gamma_green, 0.5f..2f, 0.02f, SpectralFilmTuning::printGammaGreen) {
|
||||
copy(printGammaGreen = it)
|
||||
},
|
||||
SliderSpec(R.string.spektrafilm_print_gamma_blue, 0.5f..2f, 0.02f, SpectralFilmTuning::printGammaBlue) {
|
||||
copy(printGammaBlue = it)
|
||||
},
|
||||
SliderSpec(
|
||||
R.string.spektrafilm_print_developer_exhaustion, 0f..1f, 0.02f,
|
||||
SpectralFilmTuning::printDeveloperExhaustion, R.string.spektrafilm_value_percent,
|
||||
) { copy(printDeveloperExhaustion = it) },
|
||||
)
|
||||
|
||||
private val scannerSliders = listOf(
|
||||
SliderSpec(
|
||||
R.string.spektrafilm_scanner_lens_blur, 0f..8f, 0.05f,
|
||||
SpectralFilmTuning::scannerLensBlur, R.string.spektrafilm_value_px,
|
||||
) { copy(scannerLensBlur = it) },
|
||||
SliderSpec(
|
||||
R.string.spektrafilm_scanner_unsharp_amount, 0f..3f, 0.05f, SpectralFilmTuning::scannerUnsharpAmount,
|
||||
) { copy(scannerUnsharpAmount = it) },
|
||||
)
|
||||
|
||||
private val scannerUnsharpSigmaSlider = SliderSpec(
|
||||
R.string.spektrafilm_scanner_unsharp_sigma, 0f..8f, 0.05f,
|
||||
SpectralFilmTuning::scannerUnsharpSigma, R.string.spektrafilm_value_px,
|
||||
) { copy(scannerUnsharpSigma = it) }
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
package com.hinnka.mycamera.ui.components
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import com.hinnka.mycamera.R
|
||||
import com.hinnka.mycamera.raw.SpectralDirMatrix
|
||||
import com.hinnka.mycamera.raw.SpectralFilmStockDefaults
|
||||
import com.hinnka.mycamera.raw.SpectralFilmTuning
|
||||
import com.hinnka.mycamera.raw.SpectralGrain
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
@Composable
|
||||
internal fun SpektrafilmGrainSection(
|
||||
settings: SpectralGrain,
|
||||
onCommit: (SpectralGrain) -> Unit,
|
||||
) {
|
||||
SpektrafilmSection(R.string.recipe_param_film_grain) {
|
||||
SwitchSettingItem(
|
||||
title = stringResource(R.string.spektrafilm_grain_enabled),
|
||||
checked = settings.enabled,
|
||||
onCheckedChange = { onCommit(settings.copy(enabled = it)) },
|
||||
)
|
||||
if (settings.enabled) {
|
||||
SwitchSettingItem(
|
||||
title = stringResource(R.string.spektrafilm_grain_sublayers),
|
||||
checked = settings.sublayers,
|
||||
onCheckedChange = { onCommit(settings.copy(sublayers = it)) },
|
||||
)
|
||||
SpektrafilmNumberControls(grainControls, settings, grainDefaults, onCommit)
|
||||
SpektrafilmSection(R.string.recipe_panel_advanced) {
|
||||
SpektrafilmRgbSetting(
|
||||
R.string.spektrafilm_grain_particle_scale, settings.particleScale, grainDefaults.particleScale,
|
||||
0.01f..8f, 0.05f,
|
||||
) { onCommit(settings.copy(particleScale = it)) }
|
||||
SpektrafilmRgbSetting(
|
||||
R.string.spektrafilm_grain_density_min, settings.densityMin, grainDefaults.densityMin,
|
||||
0f..1f, 0.005f, R.string.spektrafilm_value_precise,
|
||||
) { onCommit(settings.copy(densityMin = it)) }
|
||||
SpektrafilmRgbSetting(
|
||||
R.string.spektrafilm_grain_uniformity, settings.uniformity, grainDefaults.uniformity,
|
||||
0f..1f, 0.01f,
|
||||
) { onCommit(settings.copy(uniformity = it)) }
|
||||
if (settings.sublayers) {
|
||||
SpektrafilmRgbSetting(
|
||||
title = R.string.spektrafilm_grain_sublayer_scale,
|
||||
value = settings.particleScaleLayers,
|
||||
defaults = grainDefaults.particleScaleLayers,
|
||||
range = 0.01f..8f,
|
||||
step = 0.05f,
|
||||
redTitle = R.string.spektrafilm_layer_fast,
|
||||
greenTitle = R.string.spektrafilm_layer_mid,
|
||||
blueTitle = R.string.spektrafilm_layer_slow,
|
||||
) { onCommit(settings.copy(particleScaleLayers = it)) }
|
||||
SpektrafilmNumberControls(grainSublayerControls, settings, grainDefaults, onCommit)
|
||||
} else {
|
||||
SpektrafilmNumberSetting(
|
||||
title = R.string.spektrafilm_grain_layer_count,
|
||||
value = settings.subLayerCount.toFloat(),
|
||||
range = 1f..8f,
|
||||
step = 1f,
|
||||
resetValue = grainDefaults.subLayerCount.toFloat(),
|
||||
format = R.string.spektrafilm_value_integer,
|
||||
) { onCommit(settings.copy(subLayerCount = it.roundToInt())) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun SpektrafilmDirAdvancedControls(
|
||||
stock: String,
|
||||
tuning: SpectralFilmTuning,
|
||||
onCommit: (SpectralFilmTuning) -> Unit,
|
||||
) {
|
||||
val stockMatrix = SpectralFilmStockDefaults.dirMatrix(stock)
|
||||
val currentMatrix = tuning.dirMatrix?.bounded(stockMatrix) ?: stockMatrix
|
||||
fun commitMatrix(value: SpectralDirMatrix) {
|
||||
onCommit(tuning.copy(dirMatrix = value.takeUnless { it == stockMatrix }))
|
||||
}
|
||||
|
||||
SpektrafilmSection(R.string.recipe_panel_advanced) {
|
||||
SpektrafilmNumberControls(dirDiffusionControls, tuning, SpectralFilmTuning.DEFAULT, onCommit)
|
||||
SpektrafilmRgbSetting(
|
||||
R.string.spektrafilm_dir_from_red, currentMatrix.r, stockMatrix.r,
|
||||
0f..1f, 0.005f, R.string.spektrafilm_value_precise, maxAtDefault = true,
|
||||
) { commitMatrix(currentMatrix.copy(r = it)) }
|
||||
SpektrafilmRgbSetting(
|
||||
R.string.spektrafilm_dir_from_green, currentMatrix.g, stockMatrix.g,
|
||||
0f..1f, 0.005f, R.string.spektrafilm_value_precise, maxAtDefault = true,
|
||||
) { commitMatrix(currentMatrix.copy(g = it)) }
|
||||
SpektrafilmRgbSetting(
|
||||
R.string.spektrafilm_dir_from_blue, currentMatrix.b, stockMatrix.b,
|
||||
0f..1f, 0.005f, R.string.spektrafilm_value_precise, maxAtDefault = true,
|
||||
) { commitMatrix(currentMatrix.copy(b = it)) }
|
||||
}
|
||||
}
|
||||
|
||||
private val grainDefaults = SpectralGrain()
|
||||
|
||||
private val grainControls = listOf(
|
||||
SpektrafilmNumberSpec(
|
||||
R.string.spektrafilm_grain_particle_area, 0f..4f, 0.02f, SpectralGrain::particleAreaUm2,
|
||||
R.string.spektrafilm_value_um2,
|
||||
) { copy(particleAreaUm2 = it) },
|
||||
SpektrafilmNumberSpec(
|
||||
R.string.spektrafilm_grain_blur, 0f..4f, 0.05f, SpectralGrain::blur,
|
||||
R.string.spektrafilm_value_px,
|
||||
) { copy(blur = it) },
|
||||
)
|
||||
|
||||
private val grainSublayerControls = listOf(
|
||||
SpektrafilmNumberSpec(
|
||||
R.string.spektrafilm_grain_dye_blur, 0f..8f, 0.1f, SpectralGrain::blurDyeCloudsUm,
|
||||
R.string.spektrafilm_value_um,
|
||||
) { copy(blurDyeCloudsUm = it) },
|
||||
SpektrafilmNumberSpec(
|
||||
R.string.spektrafilm_grain_micro_blur, 0f..8f, 0.1f, SpectralGrain::microBlurUm,
|
||||
R.string.spektrafilm_value_um,
|
||||
) { copy(microBlurUm = it) },
|
||||
SpektrafilmNumberSpec(
|
||||
R.string.spektrafilm_grain_clump, 0f..200f, 1f, SpectralGrain::microClumpNm,
|
||||
R.string.spektrafilm_value_nm,
|
||||
) { copy(microClumpNm = it) },
|
||||
)
|
||||
|
||||
private val dirDiffusionControls = listOf(
|
||||
SpektrafilmNumberSpec(
|
||||
R.string.spektrafilm_dir_diffusion, 0f..40f, 1f, SpectralFilmTuning::dirDiffusionUm,
|
||||
R.string.spektrafilm_value_um,
|
||||
) { copy(dirDiffusionUm = it) },
|
||||
SpektrafilmNumberSpec(
|
||||
R.string.spektrafilm_dir_tail, 0f..400f, 5f, SpectralFilmTuning::dirTailUm,
|
||||
R.string.spektrafilm_value_um,
|
||||
) { copy(dirTailUm = it) },
|
||||
SpektrafilmNumberSpec(
|
||||
R.string.spektrafilm_dir_tail_weight, 0f..1f, 0.01f, SpectralFilmTuning::dirTailWeight,
|
||||
) { copy(dirTailWeight = it) },
|
||||
)
|
||||
@@ -0,0 +1,205 @@
|
||||
package com.hinnka.mycamera.ui.components
|
||||
|
||||
import androidx.annotation.StringRes
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import com.hinnka.mycamera.R
|
||||
import com.hinnka.mycamera.raw.SpectralDiffusion
|
||||
import com.hinnka.mycamera.raw.SpectralFilmStockDefaults
|
||||
import com.hinnka.mycamera.raw.SpectralGlare
|
||||
import com.hinnka.mycamera.raw.SpectralHalation
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
@Composable
|
||||
internal fun SpektrafilmDiffusionSection(
|
||||
@StringRes title: Int,
|
||||
settings: SpectralDiffusion,
|
||||
onCommit: (SpectralDiffusion) -> Unit,
|
||||
) {
|
||||
SpektrafilmSection(title) {
|
||||
SwitchSettingItem(
|
||||
title = stringResource(R.string.spektrafilm_diffusion_enabled),
|
||||
checked = settings.enabled,
|
||||
onCheckedChange = { onCommit(settings.copy(enabled = it)) },
|
||||
)
|
||||
if (settings.enabled) {
|
||||
SpektrafilmChoiceSetting(
|
||||
title = R.string.spektrafilm_diffusion_family,
|
||||
value = settings.family,
|
||||
choices = listOf(
|
||||
0 to stringResource(R.string.spektrafilm_diffusion_black_pro_mist),
|
||||
1 to stringResource(R.string.spektrafilm_diffusion_pro_mist),
|
||||
2 to stringResource(R.string.spektrafilm_diffusion_glimmerglass),
|
||||
3 to stringResource(R.string.spektrafilm_diffusion_cinebloom),
|
||||
),
|
||||
onCommit = { onCommit(settings.copy(family = it)) },
|
||||
)
|
||||
SpektrafilmNumberControls(diffusionControls, settings, diffusionDefaults, onCommit)
|
||||
SpektrafilmSection(R.string.recipe_panel_advanced) {
|
||||
SpektrafilmNumberControls(diffusionAdvancedControls, settings, diffusionDefaults, onCommit)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun SpektrafilmHalationSection(
|
||||
stock: String,
|
||||
settings: SpectralHalation,
|
||||
onCommit: (SpectralHalation) -> Unit,
|
||||
) {
|
||||
SpektrafilmSection(R.string.recipe_param_halation) {
|
||||
SwitchSettingItem(
|
||||
title = stringResource(R.string.spektrafilm_halation_enabled),
|
||||
checked = settings.enabled,
|
||||
onCheckedChange = { onCommit(settings.copy(enabled = it)) },
|
||||
)
|
||||
SpektrafilmNumberControl(halationBoostControl, settings, halationDefaults, onCommit)
|
||||
if (settings.boostEv > 0f) {
|
||||
SpektrafilmNumberControls(halationBoostShapeControls, settings, halationDefaults, onCommit)
|
||||
}
|
||||
if (settings.enabled) {
|
||||
val defaults = SpectralFilmStockDefaults.halation(stock, halationDefaults)
|
||||
SpektrafilmNumberControls(halationControls, settings, defaults, onCommit)
|
||||
SpektrafilmSection(R.string.recipe_panel_advanced) {
|
||||
SpektrafilmRgbSetting(
|
||||
R.string.spektrafilm_scatter_core, settings.scatterCoreUm, defaults.scatterCoreUm,
|
||||
0f..30f, 0.5f, R.string.spektrafilm_value_um,
|
||||
) { onCommit(settings.copy(scatterCoreUm = it)) }
|
||||
SpektrafilmRgbSetting(
|
||||
R.string.spektrafilm_scatter_tail, settings.scatterTailUm, defaults.scatterTailUm,
|
||||
0f..100f, 1f, R.string.spektrafilm_value_um,
|
||||
) { onCommit(settings.copy(scatterTailUm = it)) }
|
||||
SpektrafilmRgbSetting(
|
||||
R.string.spektrafilm_scatter_tail_weight, settings.scatterTailWeight, defaults.scatterTailWeight,
|
||||
0f..1f, 0.01f,
|
||||
) { onCommit(settings.copy(scatterTailWeight = it)) }
|
||||
|
||||
val strength = requireNotNull(defaults.strength)
|
||||
val sigma = requireNotNull(defaults.firstSigmaUm)
|
||||
SpektrafilmRgbSetting(
|
||||
R.string.spektrafilm_halation_channel_strength, settings.strength ?: strength, strength,
|
||||
0f..1f, 0.005f, R.string.spektrafilm_value_precise,
|
||||
) { onCommit(settings.copy(strength = it.takeUnless { value -> value == strength })) }
|
||||
SpektrafilmRgbSetting(
|
||||
R.string.spektrafilm_halation_first_sigma, settings.firstSigmaUm ?: sigma, sigma,
|
||||
0f..200f, 1f, R.string.spektrafilm_value_um,
|
||||
) { onCommit(settings.copy(firstSigmaUm = it.takeUnless { value -> value == sigma })) }
|
||||
SpektrafilmNumberControls(halationAdvancedControls, settings, defaults, onCommit)
|
||||
SwitchSettingItem(
|
||||
title = stringResource(R.string.spektrafilm_halation_renormalize),
|
||||
checked = settings.renormalize,
|
||||
onCheckedChange = { onCommit(settings.copy(renormalize = it)) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun SpektrafilmGlareSection(
|
||||
settings: SpectralGlare,
|
||||
onCommit: (SpectralGlare) -> Unit,
|
||||
) {
|
||||
SpektrafilmSection(R.string.spektrafilm_section_glare) {
|
||||
SwitchSettingItem(
|
||||
title = stringResource(R.string.spektrafilm_glare_enabled),
|
||||
checked = settings.enabled,
|
||||
onCheckedChange = { onCommit(settings.copy(enabled = it)) },
|
||||
)
|
||||
if (settings.enabled) {
|
||||
SpektrafilmNumberControls(glareControls, settings, glareDefaults, onCommit)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private val diffusionDefaults = SpectralDiffusion()
|
||||
private val halationDefaults = SpectralHalation()
|
||||
private val glareDefaults = SpectralGlare()
|
||||
|
||||
private val diffusionControls = listOf(
|
||||
SpektrafilmNumberSpec(
|
||||
R.string.spektrafilm_diffusion_strength, 0f..2f, 0.125f, SpectralDiffusion::strength,
|
||||
) { copy(strength = it) },
|
||||
)
|
||||
|
||||
private val diffusionAdvancedControls = listOf(
|
||||
SpektrafilmNumberSpec(
|
||||
R.string.spektrafilm_diffusion_spatial_scale, 0f..4f, 0.1f, SpectralDiffusion::spatialScale,
|
||||
) { copy(spatialScale = it) },
|
||||
SpektrafilmNumberSpec(
|
||||
R.string.spektrafilm_diffusion_halo_warmth, -1.5f..1.5f, 0.05f, SpectralDiffusion::haloWarmth,
|
||||
) { copy(haloWarmth = it) },
|
||||
SpektrafilmNumberSpec(
|
||||
R.string.spektrafilm_diffusion_core_intensity, 0f..4f, 0.05f, SpectralDiffusion::coreIntensity,
|
||||
) { copy(coreIntensity = it) },
|
||||
SpektrafilmNumberSpec(
|
||||
R.string.spektrafilm_diffusion_core_size, 0.1f..4f, 0.05f, SpectralDiffusion::coreSize,
|
||||
) { copy(coreSize = it) },
|
||||
SpektrafilmNumberSpec(
|
||||
R.string.spektrafilm_diffusion_halo_intensity, 0f..4f, 0.05f, SpectralDiffusion::haloIntensity,
|
||||
) { copy(haloIntensity = it) },
|
||||
SpektrafilmNumberSpec(
|
||||
R.string.spektrafilm_diffusion_halo_size, 0.1f..4f, 0.05f, SpectralDiffusion::haloSize,
|
||||
) { copy(haloSize = it) },
|
||||
SpektrafilmNumberSpec(
|
||||
R.string.spektrafilm_diffusion_bloom_intensity, 0f..4f, 0.05f, SpectralDiffusion::bloomIntensity,
|
||||
) { copy(bloomIntensity = it) },
|
||||
SpektrafilmNumberSpec(
|
||||
R.string.spektrafilm_diffusion_bloom_size, 0.1f..4f, 0.05f, SpectralDiffusion::bloomSize,
|
||||
) { copy(bloomSize = it) },
|
||||
)
|
||||
|
||||
private val halationControls = listOf(
|
||||
SpektrafilmNumberSpec(
|
||||
R.string.spektrafilm_scatter_amount, 0f..4f, 0.05f, SpectralHalation::scatterAmount,
|
||||
) { copy(scatterAmount = it) },
|
||||
SpektrafilmNumberSpec(
|
||||
R.string.spektrafilm_scatter_spatial_scale, 0f..4f, 0.1f, SpectralHalation::scatterSpatialScale,
|
||||
) { copy(scatterSpatialScale = it) },
|
||||
SpektrafilmNumberSpec(
|
||||
R.string.spektrafilm_halation_amount, 0f..4f, 0.05f, SpectralHalation::halationAmount,
|
||||
) { copy(halationAmount = it) },
|
||||
SpektrafilmNumberSpec(
|
||||
R.string.spektrafilm_halation_spatial_scale, 0f..4f, 0.1f, SpectralHalation::halationSpatialScale,
|
||||
) { copy(halationSpatialScale = it) },
|
||||
)
|
||||
|
||||
private val halationBoostControl = SpektrafilmNumberSpec(
|
||||
R.string.spektrafilm_halation_boost_ev, 0f..12f, 0.5f, SpectralHalation::boostEv,
|
||||
R.string.spektrafilm_value_ev,
|
||||
) { copy(boostEv = it) }
|
||||
|
||||
private val halationBoostShapeControls = listOf(
|
||||
SpektrafilmNumberSpec(
|
||||
R.string.spektrafilm_halation_protect_ev, 0f..12f, 0.5f, SpectralHalation::protectEv,
|
||||
R.string.spektrafilm_value_ev,
|
||||
) { copy(protectEv = it) },
|
||||
SpektrafilmNumberSpec(
|
||||
R.string.spektrafilm_halation_boost_range, 0f..1f, 0.05f, SpectralHalation::boostRange,
|
||||
) { copy(boostRange = it) },
|
||||
)
|
||||
|
||||
private val halationAdvancedControls = listOf(
|
||||
SpektrafilmNumberSpec(
|
||||
R.string.spektrafilm_halation_bounces, 1f..5f, 1f, { optics: SpectralHalation -> optics.bounces.toFloat() },
|
||||
R.string.spektrafilm_value_integer,
|
||||
) { copy(bounces = it.roundToInt()) },
|
||||
SpektrafilmNumberSpec(
|
||||
R.string.spektrafilm_halation_bounce_decay, 0f..1f, 0.05f, SpectralHalation::bounceDecay,
|
||||
) { copy(bounceDecay = it) },
|
||||
)
|
||||
|
||||
private val glareControls = listOf(
|
||||
SpektrafilmNumberSpec(
|
||||
R.string.spektrafilm_glare_percent, 0f..1f, 0.01f, SpectralGlare::percent,
|
||||
R.string.spektrafilm_value_percent,
|
||||
) { copy(percent = it) },
|
||||
SpektrafilmNumberSpec(
|
||||
R.string.spektrafilm_glare_roughness, 0f..1f, 0.05f, SpectralGlare::roughness,
|
||||
) { copy(roughness = it) },
|
||||
SpektrafilmNumberSpec(
|
||||
R.string.spektrafilm_glare_blur, 0f..8f, 0.1f, SpectralGlare::blur,
|
||||
R.string.spektrafilm_value_px,
|
||||
) { copy(blur = it) },
|
||||
)
|
||||
@@ -84,7 +84,6 @@ import com.hinnka.mycamera.ml.HfModelSource
|
||||
import com.hinnka.mycamera.ml.AiDenoiseModelManager
|
||||
import com.hinnka.mycamera.ml.HfModelState
|
||||
import com.hinnka.mycamera.raw.SpectralFilmSelection
|
||||
import com.hinnka.mycamera.raw.SpectralFilmTuning
|
||||
import com.hinnka.mycamera.raw.DngEmbeddedProfile
|
||||
import com.hinnka.mycamera.raw.RawAdaptiveExposureMode
|
||||
import com.hinnka.mycamera.processor.DenoiseStrength
|
||||
@@ -316,9 +315,7 @@ fun GalleryEditScreen(
|
||||
val editRawSpectralFilmStock by viewModel.editRawSpectralFilmStock.collectAsState()
|
||||
val editRawSpectralFilmPrint by viewModel.editRawSpectralFilmPrint.collectAsState()
|
||||
val editRawFotufilmDocument by viewModel.editRawFotufilmDocument.collectAsState()
|
||||
val editRawSpectralFilmCDensityGain by viewModel.editRawSpectralFilmCDensityGain.collectAsState()
|
||||
val editRawSpectralFilmMDensityGain by viewModel.editRawSpectralFilmMDensityGain.collectAsState()
|
||||
val editRawSpectralFilmYDensityGain by viewModel.editRawSpectralFilmYDensityGain.collectAsState()
|
||||
val editRawSpectralFilmTuning by viewModel.editRawSpectralFilmTuning.collectAsState()
|
||||
val availableDcps = viewModel.availableDcps
|
||||
|
||||
val editComputationalAperture by viewModel.editComputationalAperture.collectAsState()
|
||||
@@ -1950,11 +1947,7 @@ fun GalleryEditScreen(
|
||||
spectralFilmSelection = editRawSpectralFilmStock?.let { stock ->
|
||||
SpectralFilmSelection(
|
||||
id = stock,
|
||||
tuning = SpectralFilmTuning(
|
||||
cDensityGain = editRawSpectralFilmCDensityGain,
|
||||
mDensityGain = editRawSpectralFilmMDensityGain,
|
||||
yDensityGain = editRawSpectralFilmYDensityGain
|
||||
)
|
||||
tuning = editRawSpectralFilmTuning
|
||||
)
|
||||
},
|
||||
spectralFilmPrint = editRawSpectralFilmPrint,
|
||||
|
||||
@@ -556,6 +556,7 @@ private data class CameraFeatureUpdate(
|
||||
/** 仅消费 AgX / Filmic 曲线参数。 */
|
||||
val rawEngineToneCurve: SettingValue<RawToneMappingParameters>? = null,
|
||||
val rawSpectralFilmStock: SettingValue<String?>? = null,
|
||||
val rawSpectralFilmTuning: SpectralFilmSelection? = null,
|
||||
val rawSpectralFilmPrint: SettingValue<String?>? = null,
|
||||
val rawFotufilmDocument: SettingValue<FotufilmDocument?>? = null,
|
||||
val droMode: SettingValue<String>? = null,
|
||||
@@ -1194,6 +1195,12 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
update.rawShadowsAdjustment?.let { rawShadowsAdjustment = it.value }
|
||||
update.rawBlackPointCorrection?.let { rawBlackPointCorrection = it.value }
|
||||
update.rawWhitePointCorrection?.let { rawWhitePointCorrection = it.value }
|
||||
update.rawSpectralFilmTuning?.let { selection ->
|
||||
val previousStock = rawSpectralFilmStock ?: "kodak_portra_400"
|
||||
if (selection.id == previousStock || selection.tuning != SpectralFilmTuning.DEFAULT) {
|
||||
rawSpectralFilmTuningsByStock = rawSpectralFilmTuningsByStock + (selection.id to selection.tuning)
|
||||
}
|
||||
}
|
||||
update.rawSpectralFilmStock?.let { rawSpectralFilmStock = it.value }
|
||||
update.rawSpectralFilmPrint?.let { rawSpectralFilmPrint = it.value }
|
||||
update.rawFotufilmDocument?.let { rawFotufilmDocument = FotufilmDocumentStorage.encode(it.value) }
|
||||
@@ -2320,16 +2327,12 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
}
|
||||
fun setRawSpectralFilmSelection(selection: SpectralFilmSelection?) {
|
||||
viewModelScope.launch {
|
||||
val prefs = userPreferencesRepository.userPreferences.first()
|
||||
val previousStock = prefs.rawSpectralFilmStock
|
||||
applyCameraFeatureUpdate(
|
||||
CameraFeatureUpdate(rawSpectralFilmStock = SettingValue(selection?.id))
|
||||
CameraFeatureUpdate(
|
||||
rawSpectralFilmStock = SettingValue(selection?.id),
|
||||
rawSpectralFilmTuning = selection?.normalized(),
|
||||
)
|
||||
)
|
||||
if (selection != null && selection.id == previousStock) {
|
||||
userPreferencesRepository.update {
|
||||
rawSpectralFilmTuningsByStock = rawSpectralFilmTuningsByStock + (selection.id to selection.tuning)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2801,9 +2804,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
rawOutputUpscaleMode = userPrefs?.rawOutputUpscaleMode ?: RawOutputUpscaleMode.DEFAULT,
|
||||
spectralFilmStock = spectralFilmSettings.stock,
|
||||
spectralFilmPrint = spectralFilmSettings.print,
|
||||
spectralFilmCDensityGain = spectralFilmSettings.tuning.cDensityGain,
|
||||
spectralFilmMDensityGain = spectralFilmSettings.tuning.mDensityGain,
|
||||
spectralFilmYDensityGain = spectralFilmSettings.tuning.yDensityGain,
|
||||
spectralFilmParameters = spectralFilmSettings.tuning.encodeParameters(),
|
||||
fotufilmDocument = resolveRawFotufilmDocument(userPrefs)?.toJson(),
|
||||
width = width,
|
||||
height = height,
|
||||
@@ -5343,9 +5344,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
rawOutputUpscaleMode = userPrefs?.rawOutputUpscaleMode ?: RawOutputUpscaleMode.DEFAULT,
|
||||
spectralFilmStock = spectralFilmSettings.stock,
|
||||
spectralFilmPrint = spectralFilmSettings.print,
|
||||
spectralFilmCDensityGain = spectralFilmSettings.tuning.cDensityGain,
|
||||
spectralFilmMDensityGain = spectralFilmSettings.tuning.mDensityGain,
|
||||
spectralFilmYDensityGain = spectralFilmSettings.tuning.yDensityGain,
|
||||
spectralFilmParameters = spectralFilmSettings.tuning.encodeParameters(),
|
||||
fotufilmDocument = resolveRawFotufilmDocument(userPrefs)?.toJson(),
|
||||
width = image.width,
|
||||
height = image.height,
|
||||
@@ -5502,9 +5501,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
rawToneMappingParameters = resolveCaptureRawToneMappingParameters(userPrefs),
|
||||
spectralFilmStock = spectralFilmSettings.stock,
|
||||
spectralFilmPrint = spectralFilmSettings.print,
|
||||
spectralFilmCDensityGain = spectralFilmSettings.tuning.cDensityGain,
|
||||
spectralFilmMDensityGain = spectralFilmSettings.tuning.mDensityGain,
|
||||
spectralFilmYDensityGain = spectralFilmSettings.tuning.yDensityGain,
|
||||
spectralFilmParameters = spectralFilmSettings.tuning.encodeParameters(),
|
||||
fotufilmDocument = resolveRawFotufilmDocument(userPrefs)?.toJson(),
|
||||
width = bitmap.width,
|
||||
height = bitmap.height,
|
||||
@@ -5775,9 +5772,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
rawOutputUpscaleMode = userPrefs?.rawOutputUpscaleMode ?: RawOutputUpscaleMode.DEFAULT,
|
||||
spectralFilmStock = spectralFilmSettings.stock,
|
||||
spectralFilmPrint = spectralFilmSettings.print,
|
||||
spectralFilmCDensityGain = spectralFilmSettings.tuning.cDensityGain,
|
||||
spectralFilmMDensityGain = spectralFilmSettings.tuning.mDensityGain,
|
||||
spectralFilmYDensityGain = spectralFilmSettings.tuning.yDensityGain,
|
||||
spectralFilmParameters = spectralFilmSettings.tuning.encodeParameters(),
|
||||
fotufilmDocument = resolveRawFotufilmDocument(userPrefs)?.toJson(),
|
||||
width = MultiFrameConfig.scaledRawOutputDimension(images[0].width, superResScale),
|
||||
height = MultiFrameConfig.scaledRawOutputDimension(images[0].height, superResScale),
|
||||
@@ -6097,9 +6092,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
rawOutputUpscaleMode = userPrefs?.rawOutputUpscaleMode ?: RawOutputUpscaleMode.DEFAULT,
|
||||
spectralFilmStock = spectralFilmSettings.stock,
|
||||
spectralFilmPrint = spectralFilmSettings.print,
|
||||
spectralFilmCDensityGain = spectralFilmSettings.tuning.cDensityGain,
|
||||
spectralFilmMDensityGain = spectralFilmSettings.tuning.mDensityGain,
|
||||
spectralFilmYDensityGain = spectralFilmSettings.tuning.yDensityGain,
|
||||
spectralFilmParameters = spectralFilmSettings.tuning.encodeParameters(),
|
||||
fotufilmDocument = resolveRawFotufilmDocument(userPrefs)?.toJson(),
|
||||
width = image.width,
|
||||
height = image.height,
|
||||
|
||||
@@ -457,11 +457,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
private set
|
||||
var editRawSpectralFilmPrint = MutableStateFlow<String?>(null)
|
||||
private set
|
||||
var editRawSpectralFilmCDensityGain = MutableStateFlow(1f)
|
||||
private set
|
||||
var editRawSpectralFilmMDensityGain = MutableStateFlow(1f)
|
||||
private set
|
||||
var editRawSpectralFilmYDensityGain = MutableStateFlow(1f)
|
||||
var editRawSpectralFilmTuning = MutableStateFlow(SpectralFilmTuning.DEFAULT)
|
||||
private set
|
||||
val editRawFotufilmDocument = MutableStateFlow<FotufilmDocument?>(null)
|
||||
|
||||
@@ -1533,9 +1529,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
editRawToneMappingParameters.value = m.rawToneMappingParameters
|
||||
editRawSpectralFilmStock.value = m.spectralFilmStock ?: "kodak_portra_400"
|
||||
editRawSpectralFilmPrint.value = m.spectralFilmPrint ?: "kodak_portra_endura"
|
||||
editRawSpectralFilmCDensityGain.value = m.spectralFilmCDensityGain
|
||||
editRawSpectralFilmMDensityGain.value = m.spectralFilmMDensityGain
|
||||
editRawSpectralFilmYDensityGain.value = m.spectralFilmYDensityGain
|
||||
editRawSpectralFilmTuning.value = m.decodeSpectralFilmTuning()
|
||||
editRawFotufilmDocument.value = resolveEditFotufilmDocument(m)
|
||||
editRotationDegrees.value = PostEditGeometry.normalizeRotation(m.postRotationDegrees)
|
||||
editStraightenDegrees.value =
|
||||
@@ -2192,9 +2186,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
editRawToneMappingParameters.value = metadata.rawToneMappingParameters
|
||||
editRawSpectralFilmStock.value = metadata.spectralFilmStock ?: "kodak_portra_400"
|
||||
editRawSpectralFilmPrint.value = metadata.spectralFilmPrint ?: "kodak_portra_endura"
|
||||
editRawSpectralFilmCDensityGain.value = metadata.spectralFilmCDensityGain
|
||||
editRawSpectralFilmMDensityGain.value = metadata.spectralFilmMDensityGain
|
||||
editRawSpectralFilmYDensityGain.value = metadata.spectralFilmYDensityGain
|
||||
editRawSpectralFilmTuning.value = metadata.decodeSpectralFilmTuning()
|
||||
editRawFotufilmDocument.value = resolveEditFotufilmDocument(metadata)
|
||||
editRotationDegrees.value =
|
||||
PostEditGeometry.normalizeRotation(metadata.postRotationDegrees)
|
||||
@@ -2265,9 +2257,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
editRawToneMappingParameters.value = RawToneMappingParameters.DEFAULT
|
||||
editRawSpectralFilmStock.value = "kodak_portra_400"
|
||||
editRawSpectralFilmPrint.value = "kodak_portra_endura"
|
||||
editRawSpectralFilmCDensityGain.value = 1f
|
||||
editRawSpectralFilmMDensityGain.value = 1f
|
||||
editRawSpectralFilmYDensityGain.value = 1f
|
||||
editRawSpectralFilmTuning.value = SpectralFilmTuning.DEFAULT
|
||||
editRawFotufilmDocument.value = null
|
||||
editRotationDegrees.value = 0
|
||||
editStraightenDegrees.value = 0f
|
||||
@@ -2405,9 +2395,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
editRawToneMappingParameters.value = RawToneMappingParameters.DEFAULT
|
||||
editRawSpectralFilmStock.value = null
|
||||
editRawSpectralFilmPrint.value = null
|
||||
editRawSpectralFilmCDensityGain.value = 1f
|
||||
editRawSpectralFilmMDensityGain.value = 1f
|
||||
editRawSpectralFilmYDensityGain.value = 1f
|
||||
editRawSpectralFilmTuning.value = SpectralFilmTuning.DEFAULT
|
||||
editRawFotufilmDocument.value = null
|
||||
}
|
||||
|
||||
@@ -2981,9 +2969,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
val rawToneMappingParameters = editRawToneMappingParameters.value.normalized()
|
||||
val spectralFilmStock = editRawSpectralFilmStock.value
|
||||
val spectralFilmPrint = editRawSpectralFilmPrint.value
|
||||
val spectralFilmCDensityGain = editRawSpectralFilmCDensityGain.value
|
||||
val spectralFilmMDensityGain = editRawSpectralFilmMDensityGain.value
|
||||
val spectralFilmYDensityGain = editRawSpectralFilmYDensityGain.value
|
||||
val spectralFilmTuning = editRawSpectralFilmTuning.value
|
||||
val fotufilmDocument = editRawFotufilmDocument.value
|
||||
|
||||
viewModelScope.launch {
|
||||
@@ -3025,9 +3011,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
rawToneMappingParameters = rawToneMappingParameters,
|
||||
spectralFilmStock = spectralFilmStock,
|
||||
spectralFilmPrint = spectralFilmPrint,
|
||||
spectralFilmCDensityGain = spectralFilmCDensityGain,
|
||||
spectralFilmMDensityGain = spectralFilmMDensityGain,
|
||||
spectralFilmYDensityGain = spectralFilmYDensityGain,
|
||||
spectralFilmParameters = spectralFilmTuning.encodeParameters(),
|
||||
fotufilmDocument = FotufilmDocumentStorage.encode(fotufilmDocument)
|
||||
)
|
||||
}
|
||||
@@ -3246,10 +3230,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
onComplete: ((Boolean) -> Unit)? = null
|
||||
) {
|
||||
editRawSpectralFilmStock.value = selection?.id
|
||||
val tuning = selection?.tuning?.normalized() ?: SpectralFilmTuning.DEFAULT
|
||||
editRawSpectralFilmCDensityGain.value = tuning.cDensityGain
|
||||
editRawSpectralFilmMDensityGain.value = tuning.mDensityGain
|
||||
editRawSpectralFilmYDensityGain.value = tuning.yDensityGain
|
||||
editRawSpectralFilmTuning.value = selection?.tuning?.normalized() ?: SpectralFilmTuning.DEFAULT
|
||||
persistRawEditMetadata(mediaData, onComplete)
|
||||
}
|
||||
|
||||
@@ -3687,6 +3668,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
?: MediaMetadata()
|
||||
|
||||
if (useGlobalEdit) {
|
||||
val spectralFilmTuning = editRawSpectralFilmTuning.value
|
||||
finalMetadata = (currentMediaMetadata ?: metadata).copy(
|
||||
lutId = editLutId.value,
|
||||
frameId = editFrameId.value,
|
||||
@@ -3720,9 +3702,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
rawToneMappingParameters = editRawToneMappingParameters.value.normalized(),
|
||||
spectralFilmStock = editRawSpectralFilmStock.value,
|
||||
spectralFilmPrint = editRawSpectralFilmPrint.value,
|
||||
spectralFilmCDensityGain = editRawSpectralFilmCDensityGain.value,
|
||||
spectralFilmMDensityGain = editRawSpectralFilmMDensityGain.value,
|
||||
spectralFilmYDensityGain = editRawSpectralFilmYDensityGain.value,
|
||||
spectralFilmParameters = spectralFilmTuning.encodeParameters(),
|
||||
fotufilmDocument = FotufilmDocumentStorage.encode(editRawFotufilmDocument.value),
|
||||
computationalAperture = editComputationalAperture.value,
|
||||
computationalBokehStyle = editBokehStyle.value.persistedName,
|
||||
@@ -4044,6 +4024,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
)
|
||||
}
|
||||
|
||||
val spectralFilmTuning = editRawSpectralFilmTuning.value
|
||||
val success = GalleryManager.updateMetadata(context, targetPhotoId) { current ->
|
||||
current.copy(
|
||||
lutId = editLutId.value,
|
||||
@@ -4083,9 +4064,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
rawToneMappingParameters = editRawToneMappingParameters.value.normalized(),
|
||||
spectralFilmStock = editRawSpectralFilmStock.value,
|
||||
spectralFilmPrint = editRawSpectralFilmPrint.value,
|
||||
spectralFilmCDensityGain = editRawSpectralFilmCDensityGain.value,
|
||||
spectralFilmMDensityGain = editRawSpectralFilmMDensityGain.value,
|
||||
spectralFilmYDensityGain = editRawSpectralFilmYDensityGain.value,
|
||||
spectralFilmParameters = spectralFilmTuning.encodeParameters(),
|
||||
fotufilmDocument = FotufilmDocumentStorage.encode(editRawFotufilmDocument.value),
|
||||
computationalAperture = editComputationalAperture.value,
|
||||
computationalBokehStyle = editBokehStyle.value.persistedName,
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="spektrafilm_section_film">底片曝光與沖洗</string>
|
||||
<string name="spektrafilm_section_couplers">DIR 成色劑</string>
|
||||
<string name="spektrafilm_section_enlarger">放大機</string>
|
||||
<string name="spektrafilm_section_preflash">相紙預曝光</string>
|
||||
<string name="spektrafilm_section_chemistry">相紙顯影</string>
|
||||
<string name="spektrafilm_section_scanner">掃描器</string>
|
||||
<string name="spektrafilm_section_spectral">光譜重建</string>
|
||||
|
||||
<string name="spektrafilm_camera_exposure">底片曝光補償</string>
|
||||
<string name="spektrafilm_film_gamma">底片密度曲線 Gamma</string>
|
||||
<string name="spektrafilm_film_dye_order">底片染料色版順序</string>
|
||||
<string name="spektrafilm_dir_enabled">DIR 顯影抑制</string>
|
||||
<string name="spektrafilm_dir_description">調整影響反差和色彩分離的顯影抑制。數值為 1 時使用底片本身的設定。</string>
|
||||
<string name="spektrafilm_dir_amount">抑制強度</string>
|
||||
<string name="spektrafilm_dir_same_layer">同層抑制</string>
|
||||
<string name="spektrafilm_dir_inter_layer">層間抑制</string>
|
||||
<string name="spektrafilm_scan_film">直接掃描底片</string>
|
||||
<string name="spektrafilm_scan_film_description">直接掃描顯影後的負片,跳過相紙放印。</string>
|
||||
|
||||
<string name="spektrafilm_print_exposure_compensation">自動放印補償</string>
|
||||
<string name="spektrafilm_print_exposure_compensation_description">根據底片曝光設定補償放大機曝光。</string>
|
||||
<string name="spektrafilm_print_normalize_exposure">正規化放印曝光</string>
|
||||
<string name="spektrafilm_print_normalize_exposure_description">以底片的參考中灰為基準設定放印曝光。</string>
|
||||
<string name="spektrafilm_print_exposure">放印曝光</string>
|
||||
<string name="spektrafilm_print_dye_order">相紙染料色版順序</string>
|
||||
<string name="spektrafilm_yellow_filter">黃色濾鏡偏移</string>
|
||||
<string name="spektrafilm_magenta_filter">洋紅濾鏡偏移</string>
|
||||
<string name="spektrafilm_preflash_exposure">預曝光量</string>
|
||||
<string name="spektrafilm_value_preflash_exposure">%1$.6f</string>
|
||||
<string name="spektrafilm_preflash_high_value">預曝光量 %1$.6f(超出滑桿範圍)</string>
|
||||
<string name="spektrafilm_preflash_enter_value">輸入精確值</string>
|
||||
<string name="spektrafilm_preflash_input_range">請輸入 0 到 1 之間的數值。</string>
|
||||
<string name="spektrafilm_preflash_reset">歸零</string>
|
||||
<string name="spektrafilm_print_chemistry_enabled">調整相紙密度曲線</string>
|
||||
<string name="spektrafilm_print_chemistry_description">調整相紙乳劑層的反差,模擬顯影液耗竭。</string>
|
||||
<string name="spektrafilm_print_gamma">整體 Gamma</string>
|
||||
<string name="spektrafilm_print_gamma_fast">高感度子層 Gamma</string>
|
||||
<string name="spektrafilm_print_gamma_slow">中、低感度子層 Gamma</string>
|
||||
<string name="spektrafilm_print_gamma_red">紅色 Gamma</string>
|
||||
<string name="spektrafilm_print_gamma_green">綠色 Gamma</string>
|
||||
<string name="spektrafilm_print_gamma_blue">藍色 Gamma</string>
|
||||
<string name="spektrafilm_print_developer_exhaustion">顯影液耗竭</string>
|
||||
|
||||
<string name="spektrafilm_scanner_lens_blur">掃描鏡頭模糊</string>
|
||||
<string name="spektrafilm_scanner_unsharp_amount">USM 銳化強度</string>
|
||||
<string name="spektrafilm_scanner_unsharp_sigma">USM 銳化 Sigma</string>
|
||||
<string name="spektrafilm_input_gamut_compression">輸入色域壓縮</string>
|
||||
<string name="spektrafilm_input_gamut_compression_description">重建光譜之前,將輸入色度向可見光譜軌跡壓縮。</string>
|
||||
<string name="spektrafilm_spectral_adaptation_window">Hanatos2025 適應視窗</string>
|
||||
<string name="spektrafilm_spectral_adaptation_surface">Hanatos2025 適應曲面</string>
|
||||
<string name="spektrafilm_spectral_blur">光譜高斯模糊</string>
|
||||
|
||||
<string name="spektrafilm_section_camera_diffusion">拍攝擴散濾鏡</string>
|
||||
<string name="spektrafilm_section_enlarger_diffusion">放大機擴散濾鏡</string>
|
||||
<string name="spektrafilm_section_glare">相紙眩光</string>
|
||||
<string name="spektrafilm_gamut_enabled">啟用壓縮</string>
|
||||
<string name="spektrafilm_section_output_gamut">輸出色域壓縮</string>
|
||||
<string name="spektrafilm_camera_lens_blur">拍攝鏡頭模糊</string>
|
||||
<string name="spektrafilm_film_format">底片片幅長邊</string>
|
||||
<string name="spektrafilm_diffusion_enabled">啟用擴散濾鏡</string>
|
||||
<string name="spektrafilm_diffusion_family">濾鏡類型</string>
|
||||
<string name="spektrafilm_diffusion_strength">濾鏡強度</string>
|
||||
<string name="spektrafilm_diffusion_spatial_scale">擴散尺度</string>
|
||||
<string name="spektrafilm_diffusion_halo_warmth">光暈暖度</string>
|
||||
<string name="spektrafilm_diffusion_core_intensity">核心權重</string>
|
||||
<string name="spektrafilm_diffusion_core_size">核心大小</string>
|
||||
<string name="spektrafilm_diffusion_halo_intensity">光暈權重</string>
|
||||
<string name="spektrafilm_diffusion_halo_size">光暈大小</string>
|
||||
<string name="spektrafilm_diffusion_bloom_intensity">泛光權重</string>
|
||||
<string name="spektrafilm_diffusion_bloom_size">泛光大小</string>
|
||||
<string name="spektrafilm_halation_enabled">啟用光暈和散射</string>
|
||||
<string name="spektrafilm_scatter_amount">乳劑散射</string>
|
||||
<string name="spektrafilm_scatter_spatial_scale">散射尺度</string>
|
||||
<string name="spektrafilm_halation_amount">光暈強度</string>
|
||||
<string name="spektrafilm_halation_spatial_scale">光暈尺度</string>
|
||||
<string name="spektrafilm_halation_boost_ev">高光增強</string>
|
||||
<string name="spektrafilm_halation_protect_ev">高光保護範圍</string>
|
||||
<string name="spektrafilm_halation_boost_range">高光增強過渡</string>
|
||||
<string name="spektrafilm_scatter_core">散射核心 Sigma</string>
|
||||
<string name="spektrafilm_scatter_tail">散射長尾衰減長度</string>
|
||||
<string name="spektrafilm_scatter_tail_weight">散射長尾權重</string>
|
||||
<string name="spektrafilm_halation_channel_strength">按色版調節光暈強度</string>
|
||||
<string name="spektrafilm_halation_first_sigma">按色版調節首次反射 Sigma</string>
|
||||
<string name="spektrafilm_halation_bounces">反射次數</string>
|
||||
<string name="spektrafilm_halation_bounce_decay">反射衰減</string>
|
||||
<string name="spektrafilm_halation_renormalize">維持中間調</string>
|
||||
<string name="spektrafilm_grain_enabled">啟用底片顆粒</string>
|
||||
<string name="spektrafilm_grain_sublayers">模擬乳劑子層</string>
|
||||
<string name="spektrafilm_grain_particle_area">顆粒面積</string>
|
||||
<string name="spektrafilm_grain_particle_scale">按色版調節顆粒面積倍率</string>
|
||||
<string name="spektrafilm_grain_sublayer_scale">按子層調節顆粒面積倍率</string>
|
||||
<string name="spektrafilm_grain_density_min">按色版調節顆粒最低密度</string>
|
||||
<string name="spektrafilm_grain_uniformity">按色版調節顆粒均勻度</string>
|
||||
<string name="spektrafilm_grain_blur">顆粒模糊</string>
|
||||
<string name="spektrafilm_grain_dye_blur">染料雲模糊</string>
|
||||
<string name="spektrafilm_grain_micro_blur">微結構模糊</string>
|
||||
<string name="spektrafilm_grain_clump">分子團簇尺寸</string>
|
||||
<string name="spektrafilm_grain_layer_count">顆粒子層數</string>
|
||||
<string name="spektrafilm_layer_fast">高感度子層</string>
|
||||
<string name="spektrafilm_layer_mid">中感度子層</string>
|
||||
<string name="spektrafilm_layer_slow">低感度子層</string>
|
||||
<string name="spektrafilm_dir_diffusion">DIR 擴散 Sigma</string>
|
||||
<string name="spektrafilm_dir_tail">DIR 長尾衰減長度</string>
|
||||
<string name="spektrafilm_dir_tail_weight">DIR 長尾權重</string>
|
||||
<string name="spektrafilm_dir_from_red">紅感層產生的抑制</string>
|
||||
<string name="spektrafilm_dir_from_green">綠感層產生的抑制</string>
|
||||
<string name="spektrafilm_dir_from_blue">藍感層產生的抑制</string>
|
||||
<string name="spektrafilm_glare_enabled">啟用相紙眩光</string>
|
||||
<string name="spektrafilm_glare_percent">眩光強度</string>
|
||||
<string name="spektrafilm_glare_roughness">眩光粗糙度</string>
|
||||
<string name="spektrafilm_glare_blur">眩光模糊</string>
|
||||
<string name="spektrafilm_scanner_white_correction">校正掃描白點</string>
|
||||
<string name="spektrafilm_scanner_white_level">目標白位</string>
|
||||
<string name="spektrafilm_scanner_black_correction">校正掃描黑點</string>
|
||||
<string name="spektrafilm_scanner_black_level">目標黑位</string>
|
||||
<string name="spektrafilm_spectral_method">光譜升採樣方法</string>
|
||||
<string name="spektrafilm_gamut_algorithm">壓縮演算法</string>
|
||||
<string name="spektrafilm_gamut_threshold">壓縮曲線閾值</string>
|
||||
<string name="spektrafilm_gamut_limit">壓縮曲線上限</string>
|
||||
<string name="spektrafilm_gamut_power">壓縮曲線指數</string>
|
||||
<string name="spektrafilm_gamut_off">關閉</string>
|
||||
</resources>
|
||||
@@ -925,9 +925,6 @@
|
||||
<string name="settings_print_paper">印相介質</string>
|
||||
<string name="settings_spectral_film_tuning">膠卷微調</string>
|
||||
<string name="settings_spectral_film_tuning_description">微調當前膠卷的色彩響應。</string>
|
||||
<string name="settings_spectral_film_c_density_gain">青色密度</string>
|
||||
<string name="settings_spectral_film_m_density_gain">品紅密度</string>
|
||||
<string name="settings_spectral_film_y_density_gain">黃色密度</string>
|
||||
<string name="settings_raw_auto_exposure">自動曝光</string>
|
||||
<string name="settings_raw_auto_exposure_description">顯影時對 RAW 線性資料自動測光并應用曝光補償。</string>
|
||||
<string name="settings_raw_min_shutter_speed">最低快門速度</string>
|
||||
|
||||
@@ -1127,9 +1127,6 @@
|
||||
<string name="settings_print_paper">Support d\'impression</string>
|
||||
<string name="settings_spectral_film_tuning">Réglage de la pellicule</string>
|
||||
<string name="settings_spectral_film_tuning_description">Affine la réponse colorimétrique de la pellicule sélectionnée.</string>
|
||||
<string name="settings_spectral_film_c_density_gain">Densité cyan</string>
|
||||
<string name="settings_spectral_film_m_density_gain">Densité magenta</string>
|
||||
<string name="settings_spectral_film_y_density_gain">Densité jaune</string>
|
||||
<string name="settings_raw_auto_exposure">Exposition automatique</string>
|
||||
<string name="settings_raw_auto_exposure_description">Mesure automatiquement les données RAW linéaires pendant le développement et applique une correction d\'exposition.</string>
|
||||
<string name="settings_raw_min_shutter_speed">Vitesse d\'obturation minimale</string>
|
||||
|
||||
@@ -817,9 +817,6 @@
|
||||
<string name="settings_print_paper">プリント媒体</string>
|
||||
<string name="settings_spectral_film_tuning">フィルム調整</string>
|
||||
<string name="settings_spectral_film_tuning_description">選択したフィルムストックの色応答を微調整</string>
|
||||
<string name="settings_spectral_film_c_density_gain">シアン濃度</string>
|
||||
<string name="settings_spectral_film_m_density_gain">マゼンタ濃度</string>
|
||||
<string name="settings_spectral_film_y_density_gain">イエロー濃度</string>
|
||||
<string name="settings_raw_auto_exposure">自動露出</string>
|
||||
<string name="settings_raw_auto_exposure_description">現像時にRAWリニアデータを自動測光し、露出補正を適用</string>
|
||||
<string name="settings_raw_min_shutter_speed">低速限界</string>
|
||||
|
||||
@@ -657,9 +657,6 @@
|
||||
<string name="settings_print_paper">สื่อสิ่งพิมพ์</string>
|
||||
<string name="settings_spectral_film_tuning">การปรับแต่งฟิล์มอย่างละเอียด</string>
|
||||
<string name="settings_spectral_film_tuning_description">ปรับการตอบสนองสีของม้วนฟิล์มปัจจุบันอย่างละเอียด</string>
|
||||
<string name="settings_spectral_film_c_density_gain">ความหนาแน่นของสีฟ้า</string>
|
||||
<string name="settings_spectral_film_m_density_gain">ความหนาแน่นของสีม่วงแดง</string>
|
||||
<string name="settings_spectral_film_y_density_gain">ความหนาแน่นสีเหลือง</string>
|
||||
<string name="settings_raw_auto_exposure">การเปิดรับแสงอัตโนมัติ</string>
|
||||
<string name="settings_raw_auto_exposure_description">การวัดแสงอัตโนมัติและการประยุกต์ใช้การชดเชยแสงกับข้อมูลเชิงเส้น RAW ขณะกำลังพัฒนา</string>
|
||||
<string name="settings_raw_min_shutter_speed">ความเร็วชัตเตอร์ขั้นต่ำ</string>
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="spektrafilm_section_film">胶片曝光与冲洗</string>
|
||||
<string name="spektrafilm_section_couplers">DIR 成色剂</string>
|
||||
<string name="spektrafilm_section_enlarger">放大机</string>
|
||||
<string name="spektrafilm_section_preflash">相纸预曝光</string>
|
||||
<string name="spektrafilm_section_chemistry">相纸显影</string>
|
||||
<string name="spektrafilm_section_scanner">扫描仪</string>
|
||||
<string name="spektrafilm_section_spectral">光谱重建</string>
|
||||
|
||||
<string name="spektrafilm_camera_exposure">胶片曝光补偿</string>
|
||||
<string name="spektrafilm_film_gamma">胶片密度曲线 Gamma</string>
|
||||
<string name="spektrafilm_film_dye_order">胶片染料通道顺序</string>
|
||||
<string name="spektrafilm_dir_enabled">DIR 显影抑制</string>
|
||||
<string name="spektrafilm_dir_description">调整影响反差和色彩分离的显影抑制。数值为 1 时使用胶片自身的设置。</string>
|
||||
<string name="spektrafilm_dir_amount">抑制强度</string>
|
||||
<string name="spektrafilm_dir_same_layer">同层抑制</string>
|
||||
<string name="spektrafilm_dir_inter_layer">层间抑制</string>
|
||||
<string name="spektrafilm_scan_film">直接扫描胶片</string>
|
||||
<string name="spektrafilm_scan_film_description">直接扫描显影后的底片,跳过相纸放印。</string>
|
||||
|
||||
<string name="spektrafilm_print_exposure_compensation">自动放印补偿</string>
|
||||
<string name="spektrafilm_print_exposure_compensation_description">根据胶片曝光设置补偿放大机曝光。</string>
|
||||
<string name="spektrafilm_print_normalize_exposure">归一化放印曝光</string>
|
||||
<string name="spektrafilm_print_normalize_exposure_description">以胶片的参考中灰为基准设定放印曝光。</string>
|
||||
<string name="spektrafilm_print_exposure">放印曝光</string>
|
||||
<string name="spektrafilm_print_dye_order">相纸染料通道顺序</string>
|
||||
<string name="spektrafilm_yellow_filter">黄色滤镜偏移</string>
|
||||
<string name="spektrafilm_magenta_filter">品红滤镜偏移</string>
|
||||
<string name="spektrafilm_preflash_exposure">预曝光量</string>
|
||||
<string name="spektrafilm_value_preflash_exposure">%1$.6f</string>
|
||||
<string name="spektrafilm_preflash_high_value">预曝光量 %1$.6f(超出滑块范围)</string>
|
||||
<string name="spektrafilm_preflash_enter_value">输入精确值</string>
|
||||
<string name="spektrafilm_preflash_input_range">请输入 0 到 1 之间的数值。</string>
|
||||
<string name="spektrafilm_preflash_reset">归零</string>
|
||||
<string name="spektrafilm_print_chemistry_enabled">调整相纸密度曲线</string>
|
||||
<string name="spektrafilm_print_chemistry_description">调整相纸乳剂层的反差,模拟显影液耗竭。</string>
|
||||
<string name="spektrafilm_print_gamma">整体 Gamma</string>
|
||||
<string name="spektrafilm_print_gamma_fast">高感度子层 Gamma</string>
|
||||
<string name="spektrafilm_print_gamma_slow">中、低感度子层 Gamma</string>
|
||||
<string name="spektrafilm_print_gamma_red">红色 Gamma</string>
|
||||
<string name="spektrafilm_print_gamma_green">绿色 Gamma</string>
|
||||
<string name="spektrafilm_print_gamma_blue">蓝色 Gamma</string>
|
||||
<string name="spektrafilm_print_developer_exhaustion">显影液耗竭</string>
|
||||
|
||||
<string name="spektrafilm_scanner_lens_blur">扫描镜头模糊</string>
|
||||
<string name="spektrafilm_scanner_unsharp_amount">USM 锐化强度</string>
|
||||
<string name="spektrafilm_scanner_unsharp_sigma">USM 锐化 Sigma</string>
|
||||
<string name="spektrafilm_input_gamut_compression">输入色域压缩</string>
|
||||
<string name="spektrafilm_input_gamut_compression_description">重建光谱之前,将输入色度向可见光谱轨迹压缩。</string>
|
||||
<string name="spektrafilm_spectral_adaptation_window">Hanatos2025 适应窗口</string>
|
||||
<string name="spektrafilm_spectral_adaptation_surface">Hanatos2025 适应曲面</string>
|
||||
<string name="spektrafilm_spectral_blur">光谱高斯模糊</string>
|
||||
|
||||
<string name="spektrafilm_section_camera_diffusion">拍摄扩散滤镜</string>
|
||||
<string name="spektrafilm_section_enlarger_diffusion">放大机扩散滤镜</string>
|
||||
<string name="spektrafilm_section_glare">相纸眩光</string>
|
||||
<string name="spektrafilm_gamut_enabled">启用压缩</string>
|
||||
<string name="spektrafilm_section_output_gamut">输出色域压缩</string>
|
||||
<string name="spektrafilm_camera_lens_blur">拍摄镜头模糊</string>
|
||||
<string name="spektrafilm_film_format">胶片画幅长边</string>
|
||||
<string name="spektrafilm_diffusion_enabled">启用扩散滤镜</string>
|
||||
<string name="spektrafilm_diffusion_family">滤镜类型</string>
|
||||
<string name="spektrafilm_diffusion_strength">滤镜强度</string>
|
||||
<string name="spektrafilm_diffusion_spatial_scale">扩散尺度</string>
|
||||
<string name="spektrafilm_diffusion_halo_warmth">光晕暖度</string>
|
||||
<string name="spektrafilm_diffusion_core_intensity">核心权重</string>
|
||||
<string name="spektrafilm_diffusion_core_size">核心大小</string>
|
||||
<string name="spektrafilm_diffusion_halo_intensity">光晕权重</string>
|
||||
<string name="spektrafilm_diffusion_halo_size">光晕大小</string>
|
||||
<string name="spektrafilm_diffusion_bloom_intensity">泛光权重</string>
|
||||
<string name="spektrafilm_diffusion_bloom_size">泛光大小</string>
|
||||
<string name="spektrafilm_halation_enabled">启用光晕和散射</string>
|
||||
<string name="spektrafilm_scatter_amount">乳剂散射</string>
|
||||
<string name="spektrafilm_scatter_spatial_scale">散射尺度</string>
|
||||
<string name="spektrafilm_halation_amount">光晕强度</string>
|
||||
<string name="spektrafilm_halation_spatial_scale">光晕尺度</string>
|
||||
<string name="spektrafilm_halation_boost_ev">高光增强</string>
|
||||
<string name="spektrafilm_halation_protect_ev">高光保护范围</string>
|
||||
<string name="spektrafilm_halation_boost_range">高光增强过渡</string>
|
||||
<string name="spektrafilm_scatter_core">散射核心 Sigma</string>
|
||||
<string name="spektrafilm_scatter_tail">散射长尾衰减长度</string>
|
||||
<string name="spektrafilm_scatter_tail_weight">散射长尾权重</string>
|
||||
<string name="spektrafilm_halation_channel_strength">按通道调节光晕强度</string>
|
||||
<string name="spektrafilm_halation_first_sigma">按通道调节首次反射 Sigma</string>
|
||||
<string name="spektrafilm_halation_bounces">反射次数</string>
|
||||
<string name="spektrafilm_halation_bounce_decay">反射衰减</string>
|
||||
<string name="spektrafilm_halation_renormalize">保持中间调</string>
|
||||
<string name="spektrafilm_grain_enabled">启用胶片颗粒</string>
|
||||
<string name="spektrafilm_grain_sublayers">模拟乳剂子层</string>
|
||||
<string name="spektrafilm_grain_particle_area">颗粒面积</string>
|
||||
<string name="spektrafilm_grain_particle_scale">按通道调节颗粒面积倍率</string>
|
||||
<string name="spektrafilm_grain_sublayer_scale">按子层调节颗粒面积倍率</string>
|
||||
<string name="spektrafilm_grain_density_min">按通道调节颗粒最低密度</string>
|
||||
<string name="spektrafilm_grain_uniformity">按通道调节颗粒均匀度</string>
|
||||
<string name="spektrafilm_grain_blur">颗粒模糊</string>
|
||||
<string name="spektrafilm_grain_dye_blur">染料云模糊</string>
|
||||
<string name="spektrafilm_grain_micro_blur">微观结构模糊</string>
|
||||
<string name="spektrafilm_grain_clump">分子团簇尺寸</string>
|
||||
<string name="spektrafilm_grain_layer_count">颗粒子层数</string>
|
||||
<string name="spektrafilm_layer_fast">高感度子层</string>
|
||||
<string name="spektrafilm_layer_mid">中感度子层</string>
|
||||
<string name="spektrafilm_layer_slow">低感度子层</string>
|
||||
<string name="spektrafilm_dir_diffusion">DIR 扩散 Sigma</string>
|
||||
<string name="spektrafilm_dir_tail">DIR 长尾衰减长度</string>
|
||||
<string name="spektrafilm_dir_tail_weight">DIR 长尾权重</string>
|
||||
<string name="spektrafilm_dir_from_red">红感层产生的抑制</string>
|
||||
<string name="spektrafilm_dir_from_green">绿感层产生的抑制</string>
|
||||
<string name="spektrafilm_dir_from_blue">蓝感层产生的抑制</string>
|
||||
<string name="spektrafilm_glare_enabled">启用相纸眩光</string>
|
||||
<string name="spektrafilm_glare_percent">眩光强度</string>
|
||||
<string name="spektrafilm_glare_roughness">眩光粗糙度</string>
|
||||
<string name="spektrafilm_glare_blur">眩光模糊</string>
|
||||
<string name="spektrafilm_scanner_white_correction">校正扫描白点</string>
|
||||
<string name="spektrafilm_scanner_white_level">目标白电平</string>
|
||||
<string name="spektrafilm_scanner_black_correction">校正扫描黑点</string>
|
||||
<string name="spektrafilm_scanner_black_level">目标黑电平</string>
|
||||
<string name="spektrafilm_spectral_method">光谱上采样方法</string>
|
||||
<string name="spektrafilm_gamut_algorithm">压缩算法</string>
|
||||
<string name="spektrafilm_gamut_threshold">压缩曲线阈值</string>
|
||||
<string name="spektrafilm_gamut_limit">压缩曲线极限</string>
|
||||
<string name="spektrafilm_gamut_power">压缩曲线指数</string>
|
||||
<string name="spektrafilm_gamut_off">关闭</string>
|
||||
</resources>
|
||||
@@ -946,9 +946,6 @@
|
||||
<string name="settings_print_paper">印相介质</string>
|
||||
<string name="settings_spectral_film_tuning">胶卷微调</string>
|
||||
<string name="settings_spectral_film_tuning_description">微调当前胶卷的色彩响应。</string>
|
||||
<string name="settings_spectral_film_c_density_gain">青色密度</string>
|
||||
<string name="settings_spectral_film_m_density_gain">品红密度</string>
|
||||
<string name="settings_spectral_film_y_density_gain">黄色密度</string>
|
||||
<string name="settings_raw_auto_exposure">自动曝光</string>
|
||||
<string name="settings_raw_auto_exposure_description">显影时对 RAW 线性数据自动测光并应用曝光补偿。</string>
|
||||
<string name="settings_raw_min_shutter_speed">最低快门速度</string>
|
||||
|
||||
@@ -925,9 +925,6 @@
|
||||
<string name="settings_print_paper">印相介質</string>
|
||||
<string name="settings_spectral_film_tuning">膠卷微調</string>
|
||||
<string name="settings_spectral_film_tuning_description">微調當前膠卷的色彩響應。</string>
|
||||
<string name="settings_spectral_film_c_density_gain">青色密度</string>
|
||||
<string name="settings_spectral_film_m_density_gain">品紅密度</string>
|
||||
<string name="settings_spectral_film_y_density_gain">黃色密度</string>
|
||||
<string name="settings_raw_auto_exposure">自動曝光</string>
|
||||
<string name="settings_raw_auto_exposure_description">顯影時對 RAW 線性資料自動測光并應用曝光補償。</string>
|
||||
<string name="settings_raw_min_shutter_speed">最低快門速度</string>
|
||||
|
||||
@@ -925,9 +925,6 @@
|
||||
<string name="settings_print_paper">印相介質</string>
|
||||
<string name="settings_spectral_film_tuning">膠卷微調</string>
|
||||
<string name="settings_spectral_film_tuning_description">微調當前膠卷的色彩響應。</string>
|
||||
<string name="settings_spectral_film_c_density_gain">青色密度</string>
|
||||
<string name="settings_spectral_film_m_density_gain">品紅密度</string>
|
||||
<string name="settings_spectral_film_y_density_gain">黃色密度</string>
|
||||
<string name="settings_raw_auto_exposure">自動曝光</string>
|
||||
<string name="settings_raw_auto_exposure_description">顯影時對 RAW 線性資料自動測光并應用曝光補償。</string>
|
||||
<string name="settings_raw_min_shutter_speed">最低快門速度</string>
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="spektrafilm_section_film">Film Exposure and Development</string>
|
||||
<string name="spektrafilm_section_couplers">DIR Couplers</string>
|
||||
<string name="spektrafilm_section_enlarger">Enlarger</string>
|
||||
<string name="spektrafilm_section_preflash">Paper Preflash</string>
|
||||
<string name="spektrafilm_section_chemistry">Print Chemistry</string>
|
||||
<string name="spektrafilm_section_scanner">Scanner</string>
|
||||
<string name="spektrafilm_section_spectral">Spectral Reconstruction</string>
|
||||
|
||||
<string name="spektrafilm_camera_exposure">Film Exposure Compensation</string>
|
||||
<string name="spektrafilm_film_gamma">Film Density Curve Gamma</string>
|
||||
<string name="spektrafilm_film_dye_order">Film Dye Channel Order</string>
|
||||
<string name="spektrafilm_dir_enabled">DIR Inhibition</string>
|
||||
<string name="spektrafilm_dir_description">Adjust the development inhibition that affects contrast and colour separation. A value of 1 uses the film stock’s original setting.</string>
|
||||
<string name="spektrafilm_dir_amount">Inhibition Strength</string>
|
||||
<string name="spektrafilm_dir_same_layer">Same-Layer Inhibition</string>
|
||||
<string name="spektrafilm_dir_inter_layer">Interlayer Inhibition</string>
|
||||
<string name="spektrafilm_scan_film">Scan Film Directly</string>
|
||||
<string name="spektrafilm_scan_film_description">Scan the developed negative without printing it on paper.</string>
|
||||
|
||||
<string name="spektrafilm_print_exposure_compensation">Automatic Print Compensation</string>
|
||||
<string name="spektrafilm_print_exposure_compensation_description">Adjust the enlarger exposure to compensate for the film exposure setting.</string>
|
||||
<string name="spektrafilm_print_normalize_exposure">Normalize Print Exposure</string>
|
||||
<string name="spektrafilm_print_normalize_exposure_description">Normalize the enlarger exposure against the film stock’s reference mid-gray.</string>
|
||||
<string name="spektrafilm_print_exposure">Print Exposure</string>
|
||||
<string name="spektrafilm_print_dye_order">Print Dye Channel Order</string>
|
||||
<string name="spektrafilm_yellow_filter">Yellow Filter Shift</string>
|
||||
<string name="spektrafilm_magenta_filter">Magenta Filter Shift</string>
|
||||
<string name="spektrafilm_preflash_exposure">Preflash Exposure</string>
|
||||
<string name="spektrafilm_value_preflash_exposure">%1$.6f</string>
|
||||
<string name="spektrafilm_preflash_high_value">Preflash exposure %1$.6f (above slider range)</string>
|
||||
<string name="spektrafilm_preflash_enter_value">Enter exact value</string>
|
||||
<string name="spektrafilm_preflash_input_range">Enter a value from 0 to 1.</string>
|
||||
<string name="spektrafilm_preflash_reset">Reset to zero</string>
|
||||
<string name="spektrafilm_print_chemistry_enabled">Adjust Print Density Curves</string>
|
||||
<string name="spektrafilm_print_chemistry_description">Adjust the contrast of the print emulsion layers and simulate developer exhaustion.</string>
|
||||
<string name="spektrafilm_print_gamma">Overall Gamma</string>
|
||||
<string name="spektrafilm_print_gamma_fast">Fast Sublayer Gamma</string>
|
||||
<string name="spektrafilm_print_gamma_slow">Mid and Slow Sublayer Gamma</string>
|
||||
<string name="spektrafilm_print_gamma_red">Red Gamma</string>
|
||||
<string name="spektrafilm_print_gamma_green">Green Gamma</string>
|
||||
<string name="spektrafilm_print_gamma_blue">Blue Gamma</string>
|
||||
<string name="spektrafilm_print_developer_exhaustion">Developer Exhaustion</string>
|
||||
|
||||
<string name="spektrafilm_scanner_lens_blur">Scanner Lens Blur</string>
|
||||
<string name="spektrafilm_scanner_unsharp_amount">Unsharp Mask Amount</string>
|
||||
<string name="spektrafilm_scanner_unsharp_sigma">Unsharp Mask Sigma</string>
|
||||
<string name="spektrafilm_input_gamut_compression">Input Gamut Compression</string>
|
||||
<string name="spektrafilm_input_gamut_compression_description">Bring input colours toward the visible spectral locus before reconstructing spectra.</string>
|
||||
<string name="spektrafilm_spectral_adaptation_window">Hanatos2025 Adaptation Window</string>
|
||||
<string name="spektrafilm_spectral_adaptation_surface">Hanatos2025 Adaptation Surface</string>
|
||||
<string name="spektrafilm_spectral_blur">Spectral Gaussian Blur</string>
|
||||
|
||||
<string name="spektrafilm_value_decimal" translatable="false">%1$.2f</string>
|
||||
<string name="spektrafilm_value_precise" translatable="false">%1$.3f</string>
|
||||
<string name="spektrafilm_value_ev" translatable="false">%1$+.2f EV</string>
|
||||
<string name="spektrafilm_value_cc" translatable="false">%1$+.0f CC</string>
|
||||
<string name="spektrafilm_value_px" translatable="false">%1$.2f px</string>
|
||||
<string name="spektrafilm_value_nm" translatable="false">%1$.1f nm</string>
|
||||
<string name="spektrafilm_value_percent" translatable="false">%1$.0f%%</string>
|
||||
|
||||
<string name="spektrafilm_section_camera_diffusion">Camera Diffusion</string>
|
||||
<string name="spektrafilm_section_enlarger_diffusion">Enlarger Diffusion</string>
|
||||
<string name="spektrafilm_section_glare">Print Glare</string>
|
||||
<string name="spektrafilm_gamut_enabled">Enable Compression</string>
|
||||
<string name="spektrafilm_section_output_gamut">Output Gamut Compression</string>
|
||||
<string name="spektrafilm_camera_lens_blur">Camera Lens Blur</string>
|
||||
<string name="spektrafilm_film_format">Film Long Edge</string>
|
||||
<string name="spektrafilm_diffusion_enabled">Enable Diffusion Filter</string>
|
||||
<string name="spektrafilm_diffusion_family">Filter Family</string>
|
||||
<string name="spektrafilm_diffusion_strength">Filter Strength</string>
|
||||
<string name="spektrafilm_diffusion_spatial_scale">Diffusion Scale</string>
|
||||
<string name="spektrafilm_diffusion_halo_warmth">Halo Warmth</string>
|
||||
<string name="spektrafilm_diffusion_core_intensity">Core Weight</string>
|
||||
<string name="spektrafilm_diffusion_core_size">Core Size</string>
|
||||
<string name="spektrafilm_diffusion_halo_intensity">Halo Weight</string>
|
||||
<string name="spektrafilm_diffusion_halo_size">Halo Size</string>
|
||||
<string name="spektrafilm_diffusion_bloom_intensity">Bloom Weight</string>
|
||||
<string name="spektrafilm_diffusion_bloom_size">Bloom Size</string>
|
||||
<string name="spektrafilm_halation_enabled">Enable Halation and Scatter</string>
|
||||
<string name="spektrafilm_scatter_amount">Emulsion Scatter</string>
|
||||
<string name="spektrafilm_scatter_spatial_scale">Scatter Scale</string>
|
||||
<string name="spektrafilm_halation_amount">Halation Strength</string>
|
||||
<string name="spektrafilm_halation_spatial_scale">Halation Scale</string>
|
||||
<string name="spektrafilm_halation_boost_ev">Highlight Boost</string>
|
||||
<string name="spektrafilm_halation_protect_ev">Highlight Protection</string>
|
||||
<string name="spektrafilm_halation_boost_range">Highlight Boost Ramp</string>
|
||||
<string name="spektrafilm_scatter_core">Scatter Core Sigma</string>
|
||||
<string name="spektrafilm_scatter_tail">Scatter Tail Decay Length</string>
|
||||
<string name="spektrafilm_scatter_tail_weight">Scatter Tail Weight</string>
|
||||
<string name="spektrafilm_halation_channel_strength">Halation Strength by Channel</string>
|
||||
<string name="spektrafilm_halation_first_sigma">First-Bounce Sigma by Channel</string>
|
||||
<string name="spektrafilm_halation_bounces">Reflection Count</string>
|
||||
<string name="spektrafilm_halation_bounce_decay">Reflection Decay</string>
|
||||
<string name="spektrafilm_halation_renormalize">Preserve Midtones</string>
|
||||
<string name="spektrafilm_grain_enabled">Enable Film Grain</string>
|
||||
<string name="spektrafilm_grain_sublayers">Model Emulsion Sublayers</string>
|
||||
<string name="spektrafilm_grain_particle_area">Grain Particle Area</string>
|
||||
<string name="spektrafilm_grain_particle_scale">Particle Area Scale by Channel</string>
|
||||
<string name="spektrafilm_grain_sublayer_scale">Particle Area Scale by Sublayer</string>
|
||||
<string name="spektrafilm_grain_density_min">Minimum Grain Density by Channel</string>
|
||||
<string name="spektrafilm_grain_uniformity">Grain Uniformity by Channel</string>
|
||||
<string name="spektrafilm_grain_blur">Grain Blur</string>
|
||||
<string name="spektrafilm_grain_dye_blur">Dye Cloud Blur</string>
|
||||
<string name="spektrafilm_grain_micro_blur">Microstructure Blur</string>
|
||||
<string name="spektrafilm_grain_clump">Molecular Clump Size</string>
|
||||
<string name="spektrafilm_grain_layer_count">Grain Sublayer Count</string>
|
||||
<string name="spektrafilm_layer_fast">Fast Sublayer</string>
|
||||
<string name="spektrafilm_layer_mid">Mid Sublayer</string>
|
||||
<string name="spektrafilm_layer_slow">Slow Sublayer</string>
|
||||
<string name="spektrafilm_dir_diffusion">DIR Diffusion Sigma</string>
|
||||
<string name="spektrafilm_dir_tail">DIR Tail Decay Length</string>
|
||||
<string name="spektrafilm_dir_tail_weight">DIR Tail Weight</string>
|
||||
<string name="spektrafilm_dir_from_red">Inhibition from the Red Layer</string>
|
||||
<string name="spektrafilm_dir_from_green">Inhibition from the Green Layer</string>
|
||||
<string name="spektrafilm_dir_from_blue">Inhibition from the Blue Layer</string>
|
||||
<string name="spektrafilm_glare_enabled">Enable Print Glare</string>
|
||||
<string name="spektrafilm_glare_percent">Glare Amount</string>
|
||||
<string name="spektrafilm_glare_roughness">Glare Roughness</string>
|
||||
<string name="spektrafilm_glare_blur">Glare Blur</string>
|
||||
<string name="spektrafilm_scanner_white_correction">Correct Scanner White Point</string>
|
||||
<string name="spektrafilm_scanner_white_level">Target White Level</string>
|
||||
<string name="spektrafilm_scanner_black_correction">Correct Scanner Black Point</string>
|
||||
<string name="spektrafilm_scanner_black_level">Target Black Level</string>
|
||||
<string name="spektrafilm_spectral_method">Spectral Upsampling Method</string>
|
||||
<string name="spektrafilm_gamut_algorithm">Compression Algorithm</string>
|
||||
<string name="spektrafilm_gamut_threshold">Knee Threshold</string>
|
||||
<string name="spektrafilm_gamut_limit">Knee Limit</string>
|
||||
<string name="spektrafilm_gamut_power">Knee Power</string>
|
||||
<string name="spektrafilm_gamut_off">Off</string>
|
||||
|
||||
<string name="spektrafilm_value_integer" translatable="false">%1$.0f</string>
|
||||
<string name="spektrafilm_value_mm" translatable="false">%1$.0f mm</string>
|
||||
<string name="spektrafilm_value_um" translatable="false">%1$.2f µm</string>
|
||||
<string name="spektrafilm_value_um2" translatable="false">%1$.2f µm²</string>
|
||||
<string name="spektrafilm_diffusion_black_pro_mist" translatable="false">Black Pro-Mist</string>
|
||||
<string name="spektrafilm_diffusion_pro_mist" translatable="false">Pro-Mist</string>
|
||||
<string name="spektrafilm_diffusion_glimmerglass" translatable="false">Glimmerglass</string>
|
||||
<string name="spektrafilm_diffusion_cinebloom" translatable="false">CineBloom</string>
|
||||
<string name="spektrafilm_spectral_hanatos" translatable="false">Hanatos 2025</string>
|
||||
<string name="spektrafilm_spectral_mallett" translatable="false">Mallett 2019</string>
|
||||
<string name="spektrafilm_gamut_xy" translatable="false">CIE xy</string>
|
||||
<string name="spektrafilm_gamut_oklch" translatable="false">OKLCh</string>
|
||||
<string name="spektrafilm_gamut_cam16ucs" translatable="false">CAM16-UCS</string>
|
||||
<string name="spektrafilm_gamut_acesrgc" translatable="false">ACES RGC</string>
|
||||
<string name="spektrafilm_gamut_oklrab" translatable="false">Oklrab</string>
|
||||
<string name="spektrafilm_gamut_jzazbz" translatable="false">JzAzBz</string>
|
||||
</resources>
|
||||
@@ -946,9 +946,6 @@
|
||||
<string name="settings_print_paper">Print Medium</string>
|
||||
<string name="settings_spectral_film_tuning">Film Tuning</string>
|
||||
<string name="settings_spectral_film_tuning_description">Fine-tune the selected film stock color response.</string>
|
||||
<string name="settings_spectral_film_c_density_gain">Cyan Density</string>
|
||||
<string name="settings_spectral_film_m_density_gain">Magenta Density</string>
|
||||
<string name="settings_spectral_film_y_density_gain">Yellow Density</string>
|
||||
<string name="settings_raw_auto_exposure">Auto Exposure</string>
|
||||
<string name="settings_raw_auto_exposure_description">Automatically meters RAW linear data during development and applies exposure compensation.</string>
|
||||
<string name="settings_raw_min_shutter_speed">Minimum Shutter Speed</string>
|
||||
|
||||
Reference in new issue
Block a user