xref: /f-stack/app/redis-5.0.5/src/lolwut5.c (revision 572c4311)
1 /*
2  * Copyright (c) 2018, Salvatore Sanfilippo <antirez at gmail dot com>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are met:
7  *
8  *   * Redistributions of source code must retain the above copyright notice,
9  *     this list of conditions and the following disclaimer.
10  *   * Redistributions in binary form must reproduce the above copyright
11  *     notice, this list of conditions and the following disclaimer in the
12  *     documentation and/or other materials provided with the distribution.
13  *   * Neither the name of Redis nor the names of its contributors may be used
14  *     to endorse or promote products derived from this software without
15  *     specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
21  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27  * POSSIBILITY OF SUCH DAMAGE.
28  *
29  * ----------------------------------------------------------------------------
30  *
31  * This file implements the LOLWUT command. The command should do something
32  * fun and interesting, and should be replaced by a new implementation at
33  * each new version of Redis.
34  */
35 
36 #include "server.h"
37 #include <math.h>
38 
39 /* This structure represents our canvas. Drawing functions will take a pointer
40  * to a canvas to write to it. Later the canvas can be rendered to a string
41  * suitable to be printed on the screen, using unicode Braille characters. */
42 typedef struct lwCanvas {
43     int width;
44     int height;
45     char *pixels;
46 } lwCanvas;
47 
48 /* Translate a group of 8 pixels (2x4 vertical rectangle) to the corresponding
49  * braille character. The byte should correspond to the pixels arranged as
50  * follows, where 0 is the least significant bit, and 7 the most significant
51  * bit:
52  *
53  *   0 3
54  *   1 4
55  *   2 5
56  *   6 7
57  *
58  * The corresponding utf8 encoded character is set into the three bytes
59  * pointed by 'output'.
60  */
61 #include <stdio.h>
lwTranslatePixelsGroup(int byte,char * output)62 void lwTranslatePixelsGroup(int byte, char *output) {
63     int code = 0x2800 + byte;
64     /* Convert to unicode. This is in the U0800-UFFFF range, so we need to
65      * emit it like this in three bytes:
66      * 1110xxxx 10xxxxxx 10xxxxxx. */
67     output[0] = 0xE0 | (code >> 12);          /* 1110-xxxx */
68     output[1] = 0x80 | ((code >> 6) & 0x3F);  /* 10-xxxxxx */
69     output[2] = 0x80 | (code & 0x3F);         /* 10-xxxxxx */
70 }
71 
72 /* Allocate and return a new canvas of the specified size. */
lwCreateCanvas(int width,int height)73 lwCanvas *lwCreateCanvas(int width, int height) {
74     lwCanvas *canvas = zmalloc(sizeof(*canvas));
75     canvas->width = width;
76     canvas->height = height;
77     canvas->pixels = zmalloc(width*height);
78     memset(canvas->pixels,0,width*height);
79     return canvas;
80 }
81 
82 /* Free the canvas created by lwCreateCanvas(). */
lwFreeCanvas(lwCanvas * canvas)83 void lwFreeCanvas(lwCanvas *canvas) {
84     zfree(canvas->pixels);
85     zfree(canvas);
86 }
87 
88 /* Set a pixel to the specified color. Color is 0 or 1, where zero means no
89  * dot will be displyed, and 1 means dot will be displayed.
90  * Coordinates are arranged so that left-top corner is 0,0. You can write
91  * out of the size of the canvas without issues. */
lwDrawPixel(lwCanvas * canvas,int x,int y,int color)92 void lwDrawPixel(lwCanvas *canvas, int x, int y, int color) {
93     if (x < 0 || x >= canvas->width ||
94         y < 0 || y >= canvas->height) return;
95     canvas->pixels[x+y*canvas->width] = color;
96 }
97 
98 /* Return the value of the specified pixel on the canvas. */
lwGetPixel(lwCanvas * canvas,int x,int y)99 int lwGetPixel(lwCanvas *canvas, int x, int y) {
100     if (x < 0 || x >= canvas->width ||
101         y < 0 || y >= canvas->height) return 0;
102     return canvas->pixels[x+y*canvas->width];
103 }
104 
105 /* Draw a line from x1,y1 to x2,y2 using the Bresenham algorithm. */
lwDrawLine(lwCanvas * canvas,int x1,int y1,int x2,int y2,int color)106 void lwDrawLine(lwCanvas *canvas, int x1, int y1, int x2, int y2, int color) {
107     int dx = abs(x2-x1);
108     int dy = abs(y2-y1);
109     int sx = (x1 < x2) ? 1 : -1;
110     int sy = (y1 < y2) ? 1 : -1;
111     int err = dx-dy, e2;
112 
113     while(1) {
114         lwDrawPixel(canvas,x1,y1,color);
115         if (x1 == x2 && y1 == y2) break;
116         e2 = err*2;
117         if (e2 > -dy) {
118             err -= dy;
119             x1 += sx;
120         }
121         if (e2 < dx) {
122             err += dx;
123             y1 += sy;
124         }
125     }
126 }
127 
128 /* Draw a square centered at the specified x,y coordinates, with the specified
129  * rotation angle and size. In order to write a rotated square, we use the
130  * trivial fact that the parametric equation:
131  *
132  *  x = sin(k)
133  *  y = cos(k)
134  *
135  * Describes a circle for values going from 0 to 2*PI. So basically if we start
136  * at 45 degrees, that is k = PI/4, with the first point, and then we find
137  * the other three points incrementing K by PI/2 (90 degrees), we'll have the
138  * points of the square. In order to rotate the square, we just start with
139  * k = PI/4 + rotation_angle, and we are done.
140  *
141  * Of course the vanilla equations above will describe the square inside a
142  * circle of radius 1, so in order to draw larger squares we'll have to
143  * multiply the obtained coordinates, and then translate them. However this
144  * is much simpler than implementing the abstract concept of 2D shape and then
145  * performing the rotation/translation transformation, so for LOLWUT it's
146  * a good approach. */
lwDrawSquare(lwCanvas * canvas,int x,int y,float size,float angle)147 void lwDrawSquare(lwCanvas *canvas, int x, int y, float size, float angle) {
148     int px[4], py[4];
149 
150     /* Adjust the desired size according to the fact that the square inscribed
151      * into a circle of radius 1 has the side of length SQRT(2). This way
152      * size becomes a simple multiplication factor we can use with our
153      * coordinates to magnify them. */
154     size /= 1.4142135623;
155     size = round(size);
156 
157     /* Compute the four points. */
158     float k = M_PI/4 + angle;
159     for (int j = 0; j < 4; j++) {
160         px[j] = round(sin(k) * size + x);
161         py[j] = round(cos(k) * size + y);
162         k += M_PI/2;
163     }
164 
165     /* Draw the square. */
166     for (int j = 0; j < 4; j++)
167         lwDrawLine(canvas,px[j],py[j],px[(j+1)%4],py[(j+1)%4],1);
168 }
169 
170 /* Schotter, the output of LOLWUT of Redis 5, is a computer graphic art piece
171  * generated by Georg Nees in the 60s. It explores the relationship between
172  * caos and order.
173  *
174  * The function creates the canvas itself, depending on the columns available
175  * in the output display and the number of squares per row and per column
176  * requested by the caller. */
lwDrawSchotter(int console_cols,int squares_per_row,int squares_per_col)177 lwCanvas *lwDrawSchotter(int console_cols, int squares_per_row, int squares_per_col) {
178     /* Calculate the canvas size. */
179     int canvas_width = console_cols*2;
180     int padding = canvas_width > 4 ? 2 : 0;
181     float square_side = (float)(canvas_width-padding*2) / squares_per_row;
182     int canvas_height = square_side * squares_per_col + padding*2;
183     lwCanvas *canvas = lwCreateCanvas(canvas_width, canvas_height);
184 
185     for (int y = 0; y < squares_per_col; y++) {
186         for (int x = 0; x < squares_per_row; x++) {
187             int sx = x * square_side + square_side/2 + padding;
188             int sy = y * square_side + square_side/2 + padding;
189             /* Rotate and translate randomly as we go down to lower
190              * rows. */
191             float angle = 0;
192             if (y > 1) {
193                 float r1 = (float)rand() / RAND_MAX / squares_per_col * y;
194                 float r2 = (float)rand() / RAND_MAX / squares_per_col * y;
195                 float r3 = (float)rand() / RAND_MAX / squares_per_col * y;
196                 if (rand() % 2) r1 = -r1;
197                 if (rand() % 2) r2 = -r2;
198                 if (rand() % 2) r3 = -r3;
199                 angle = r1;
200                 sx += r2*square_side/3;
201                 sy += r3*square_side/3;
202             }
203             lwDrawSquare(canvas,sx,sy,square_side,angle);
204         }
205     }
206 
207     return canvas;
208 }
209 
210 /* Converts the canvas to an SDS string representing the UTF8 characters to
211  * print to the terminal in order to obtain a graphical representaiton of the
212  * logical canvas. The actual returned string will require a terminal that is
213  * width/2 large and height/4 tall in order to hold the whole image without
214  * overflowing or scrolling, since each Barille character is 2x4. */
lwRenderCanvas(lwCanvas * canvas)215 sds lwRenderCanvas(lwCanvas *canvas) {
216     sds text = sdsempty();
217     for (int y = 0; y < canvas->height; y += 4) {
218         for (int x = 0; x < canvas->width; x += 2) {
219             /* We need to emit groups of 8 bits according to a specific
220              * arrangement. See lwTranslatePixelsGroup() for more info. */
221             int byte = 0;
222             if (lwGetPixel(canvas,x,y)) byte |= (1<<0);
223             if (lwGetPixel(canvas,x,y+1)) byte |= (1<<1);
224             if (lwGetPixel(canvas,x,y+2)) byte |= (1<<2);
225             if (lwGetPixel(canvas,x+1,y)) byte |= (1<<3);
226             if (lwGetPixel(canvas,x+1,y+1)) byte |= (1<<4);
227             if (lwGetPixel(canvas,x+1,y+2)) byte |= (1<<5);
228             if (lwGetPixel(canvas,x,y+3)) byte |= (1<<6);
229             if (lwGetPixel(canvas,x+1,y+3)) byte |= (1<<7);
230             char unicode[3];
231             lwTranslatePixelsGroup(byte,unicode);
232             text = sdscatlen(text,unicode,3);
233         }
234         if (y != canvas->height-1) text = sdscatlen(text,"\n",1);
235     }
236     return text;
237 }
238 
239 /* The LOLWUT command:
240  *
241  * LOLWUT [terminal columns] [squares-per-row] [squares-per-col]
242  *
243  * By default the command uses 66 columns, 8 squares per row, 12 squares
244  * per column.
245  */
lolwut5Command(client * c)246 void lolwut5Command(client *c) {
247     long cols = 66;
248     long squares_per_row = 8;
249     long squares_per_col = 12;
250 
251     /* Parse the optional arguments if any. */
252     if (c->argc > 1 &&
253         getLongFromObjectOrReply(c,c->argv[1],&cols,NULL) != C_OK)
254         return;
255 
256     if (c->argc > 2 &&
257         getLongFromObjectOrReply(c,c->argv[2],&squares_per_row,NULL) != C_OK)
258         return;
259 
260     if (c->argc > 3 &&
261         getLongFromObjectOrReply(c,c->argv[3],&squares_per_col,NULL) != C_OK)
262         return;
263 
264     /* Limits. We want LOLWUT to be always reasonably fast and cheap to execute
265      * so we have maximum number of columns, rows, and output resulution. */
266     if (cols < 1) cols = 1;
267     if (cols > 1000) cols = 1000;
268     if (squares_per_row < 1) squares_per_row = 1;
269     if (squares_per_row > 200) squares_per_row = 200;
270     if (squares_per_col < 1) squares_per_col = 1;
271     if (squares_per_col > 200) squares_per_col = 200;
272 
273     /* Generate some computer art and reply. */
274     lwCanvas *canvas = lwDrawSchotter(cols,squares_per_row,squares_per_col);
275     sds rendered = lwRenderCanvas(canvas);
276     rendered = sdscat(rendered,
277         "\nGeorg Nees - schotter, plotter on paper, 1968. Redis ver. ");
278     rendered = sdscat(rendered,REDIS_VERSION);
279     rendered = sdscatlen(rendered,"\n",1);
280     addReplyBulkSds(c,rendered);
281     lwFreeCanvas(canvas);
282 }
283