Debian Codegraph @

examples/pixel_art.cpp

raw
1 #if 0
2 g++ $0 -std=c++14 -Iinclude && ./a.out && rm -f a.out && qiv panda.ppm 1up.ppm
3 exit
4 #else
5
6 #include <array>
7 #include <frozen/map.h>
8 #include <fstream>
9
10 constexpr frozen::map<char, std::array<char, 3>, 5> Tans{
11 {'R', {(char)0xFF, (char)0x00, (char)0x00}},
12 {'G', {(char)0x00, (char)0xFF, (char)0x00}},
13 {'B', {(char)0x00, (char)0x00, (char)0xFF}},
14 {'#', {(char)0x00, (char)0x00, (char)0x00}},
15 {' ', {(char)0xFF, (char)0xFF, (char)0xFF}},
16 };
17
18 constexpr unsigned itoa(unsigned char * start, unsigned i) {
19 constexpr unsigned step = sizeof(unsigned) * 3;
20 for(unsigned k = 0; k < step; ++k)
21 *start++ = ' ';
22 do {
23 *--start = '0' + i % 10;
24 i /= 10;
25 } while(i);
26 return step;
27 }
28
29 template <unsigned H, unsigned W> struct ppm {
30 unsigned char bytes[9 /* fixed header*/ + sizeof(unsigned) * 3 * 2 /* to hold sizes */ + 3 * H * W];
31
32 constexpr ppm(unsigned char const *data) : bytes{0} {
33 unsigned j = 0;
34 bytes[j++] = 'P';
35 bytes[j++] = '6';
36 bytes[j++] = ' ';
37
38 j += itoa(bytes + j, H);
39
40 bytes[j++] = ' ';
41
42 j += itoa(bytes + j, W);
43
44 bytes[j++] = ' ';
45 bytes[j++] = '2';
46 bytes[j++] = '5';
47 bytes[j++] = '5';
48 bytes[j++] = '\n';
49 for (unsigned i = 0; i < H * W; ++i) {
50 auto const code = Tans.find(data[i])->second;
51 bytes[j + 3 * i + 0] = code[0];
52 bytes[j + 3 * i + 1] = code[1];
53 bytes[j + 3 * i + 2] = code[2];
54 }
55 }
56
57 void save(char const path[]) const {
58 std::ofstream out{path, std::ios::binary};
59 out.write((char *)bytes, sizeof bytes);
60 }
61 };
62
63 void make_panda() {
64 constexpr unsigned char bytes[] = " ### ### "
65 " ##### ########## ##### "
66 " ####### ####### "
67 " #### #### "
68 " ### ### "
69 " # # "
70 " # # "
71 " # ### ### # "
72 " # ##### ##### # "
73 " # #### # # #### # "
74 " # #### # # #### # "
75 " # ##### ##### # "
76 " # ### ## ### # "
77 " # ## # "
78 " #### RRR RRR #### "
79 " ######RRRRR RRRRR###### "
80 " ######RRRRRRRRRRRR###### "
81 " ######RRRRRRRRRRRR###### "
82 " ######RRRRRRRRRRRR###### "
83 " #######RRRRRRRRRR####### "
84 " ##### RRRRRRRR #### "
85 " ### RRRRRR ## "
86 " RRRR ";
87 constexpr ppm<26, 22> some{bytes};
88 some.save("panda.ppm");
89 }
90
91 void make_1up() {
92 constexpr unsigned char bytes[] = " ###### "
93 " ##GGGG ## "
94 " # GGGG # "
95 " # GGGGGG # "
96 " # GG GG # "
97 " #GGG GGGGG# "
98 " #GGG GG G# "
99 " # GG G # "
100 " # GG GG # "
101 " # GGGGGGGGG G# "
102 " # GG########GGG# "
103 " ### # # ### "
104 " # # # # "
105 " # # "
106 " # # "
107 " ######## "
108
109 ;
110 constexpr ppm<18, 16> some{bytes};
111 some.save("1up.ppm");
112 }
113
114 int main() {
115 make_panda();
116 make_1up();
117 return 0;
118 }
119
120 #endif