summaryrefslogtreecommitdiff
path: root/libraries/daguerre/source/ppm.cpp
diff options
context:
space:
mode:
authorBenji Dial <benji@benjidial.net>2024-07-27 16:57:39 -0400
committerBenji Dial <benji@benjidial.net>2024-07-27 16:57:39 -0400
commitfbfc078e9f44c1c1e95c9c484f1d5650bcf631b7 (patch)
treecab539c8cbbac81d895b6f8be695f3f53bf8f4d5 /libraries/daguerre/source/ppm.cpp
parent9af5588c30c4126a2800aae1afcb0de2c373dc6c (diff)
downloadhilbert-os-fbfc078e9f44c1c1e95c9c484f1d5650bcf631b7.tar.gz
lots and lots of userspace stuff
Diffstat (limited to 'libraries/daguerre/source/ppm.cpp')
-rw-r--r--libraries/daguerre/source/ppm.cpp60
1 files changed, 60 insertions, 0 deletions
diff --git a/libraries/daguerre/source/ppm.cpp b/libraries/daguerre/source/ppm.cpp
new file mode 100644
index 0000000..a4a7e27
--- /dev/null
+++ b/libraries/daguerre/source/ppm.cpp
@@ -0,0 +1,60 @@
+#include <daguerre/ppm.hpp>
+
+namespace daguerre {
+
+ //TODO: make this more robust
+ static unsigned read_text_int(FILE *input) {
+ unsigned n = 0;
+ char ch;
+ fread(&ch, 1, 1, input);
+ if (ch == '#') {
+ do
+ fread(&ch, 1, 1, input);
+ while (ch != '\n');
+ fread(&ch, 1, 1, input);
+ }
+ do {
+ n = n * 10 + ch - '0';
+ fread(&ch, 1, 1, input);
+ } while (ch >= '0' && ch <= '9');
+ return n;
+ }
+
+ //TODO: this only supports p6 format, and assumes max < 256
+ std::optional<image<rgb24>> try_load_ppm(FILE *input) {
+
+ char header[3];
+ if (fread(header, 1, 3, input) != 3)
+ return {};
+
+ if (header[0] != 'P' || header[1] != '6' || header[2] != '\n')
+ return {};
+
+ unsigned width = read_text_int(input);
+ unsigned height = read_text_int(input);
+ unsigned max = read_text_int(input);
+
+ image<rgb24> im(width, height);
+
+ for (unsigned y = 0; y < height; ++y)
+ for (unsigned x = 0; x < width; ++x) {
+ if (fread(&im.buffer[y * width + x].r, 1, 1, input) != 1)
+ return {};
+ if (fread(&im.buffer[y * width + x].g, 1, 1, input) != 1)
+ return {};
+ if (fread(&im.buffer[y * width + x].b, 1, 1, input) != 1)
+ return {};
+ }
+
+ if (max != 255)
+ for (unsigned v = 0; v < width * height; ++v) {
+ im.buffer[v].r = ((uint16_t)im.buffer[v].r * 255) / max;
+ im.buffer[v].g = ((uint16_t)im.buffer[v].g * 255) / max;
+ im.buffer[v].b = ((uint16_t)im.buffer[v].b * 255) / max;
+ }
+
+ return im;
+
+ }
+
+}