URL: https://linuxfr.org/users/serge_ss_paille/journaux/pixel-art-et-c-14 Title: Pixel Art et C++14 Authors: serge_sans_paille Date: 2018年04月03日T11:26:30+02:00 License: CC By-SA Tags: c++14 et frozen Score: 22 Petit délire illustrant l'usage de ``constexpr`` et de la biliothèsque [frozen](https://github.com/serge-sans-paille/frozen). Première étape : faire un dessin en pixel art, par exemple: ```c++ constexpr unsigned char bytes[] = " ### ### " " ##### ########## ##### " " ####### ####### " " #### #### " " ### ### " " # # " " # # " " # ### ### # " " # ##### ##### # " " # #### # # #### # " " # #### # # #### # " " # ##### ##### # " " # ### ## ### # " " # ## # " " #### RRR RRR #### " " ######RRRRR RRRRR###### " " ######RRRRRRRRRRRR###### " " ######RRRRRRRRRRRR###### " " ######RRRRRRRRRRRR###### " " #######RRRRRRRRRR####### " " ##### RRRRRRRR #### " " ### RRRRRR ## " " RRRR "; ``` On remarquera l'énorme code de couleur espace → blanc, ``#`` → noir et ``R`` → rouge. Ensuite on encode cette colormap dans une petite table de hash (oui dans ce cas un tableau de char suffirait) : ```c++ #include constexpr frozen::map, 5> Tans{ {'R', {(char)0xFF, (char)0x00, (char)0x00}}, {'G', {(char)0x00, (char)0xFF, (char)0x00}}, {'B', {(char)0x00, (char)0x00, (char)0xFF}}, {'#', {(char)0x00, (char)0x00, (char)0x00}}, {' ', {(char)0xFF, (char)0xFF, (char)0xFF}}, }; ``` Et comme on est tout foufou, on demande au compilateur C++ de traduire cette image pixel art en image au format PPM, à *compile time* ```c++ constexpr unsigned itoa(unsigned char * start, unsigned i) { constexpr unsigned step = sizeof(unsigned) * 3; for(unsigned k = 0; k < step; ++k) *start++ = ' '; do { *--start = '0' + i % 10; i /= 10; } while(i); return step; } template struct ppm { unsigned char bytes[9 /* fixed header*/ + sizeof(unsigned) * 3 * 2 /* to hold sizes */ + 3 * H * W]; constexpr ppm(unsigned char const *data) : bytes{0} { unsigned j = 0; bytes[j++] = 'P'; bytes[j++] = '6'; bytes[j++] = ' '; j += itoa(bytes + j, H); bytes[j++] = ' '; j += itoa(bytes + j, W); bytes[j++] = ' '; bytes[j++] = '2'; bytes[j++] = '5'; bytes[j++] = '5'; bytes[j++] = '\n'; for (unsigned i = 0; i < H * W; ++i) { auto const code = Tans.find(data[i])->second; bytes[j + 3 * i + 0] = code[0]; bytes[j + 3 * i + 1] = code[1]; bytes[j + 3 * i + 2] = code[2]; } } void save(char const path[]) const { std::ofstream out{path, std::ios::binary}; out.write((char *)bytes, sizeof bytes); } }; ``` On vient donc de créer une image dans un format binaire, en embarquant les sources de cette binaire dans les sources. À quand un encodeur jpeg ``constexpr``? PS: sources complètes [par ici](https://github.com/serge-sans-paille/frozen/blob/master/examples/pixel_art.cpp)

AltStyle によって変換されたページ (->オリジナル) /