ed15de011b93930a58087c9a515d173f150f32bf
[dosdemo] / src / grise.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <math.h>
5 #include <assert.h>
6 #include "imago2.h"
7 #include "demo.h"
8 #include "screen.h"
9
10 /* APPROX. 170 FPS Minimum */
11
12 typedef struct {
13         unsigned int w, h;
14         unsigned char *scans;
15 } RLEBitmap;
16
17 static RLEBitmap rleCreate(unsigned int w, unsigned int h);
18 static void rleDestroy(RLEBitmap b);
19 static void rleBlit(unsigned short *dst, int dstW, int dstH, int dstStride, 
20         RLEBitmap bitmap, int blitX, int blitY);
21 static void rleBlitScale(unsigned short *dst, int dstW, int dstH, int dstStride,
22         RLEBitmap bitmap, int blitX, int blitY, float scaleX, float scaleY);
23 static void rleBlitScaleInv(unsigned short *dst, int dstW, int dstH, int dstStride,
24         RLEBitmap bitmap, int blitX, int blitY, float scaleX, float scaleY);
25 static RLEBitmap rleEncode(unsigned char *pixels, unsigned int w, unsigned int h);
26
27 #define BG_FILENAME "data/grise.png"
28 #define GROBJ_01_FILENAME "data/grobj_01.png"
29
30 #define BB_SIZE 512     /* Let's use a power of 2. Maybe we'll zoom/rotate the effect */
31
32 /* Every backBuffer scanline is guaranteed to have that many dummy pixels before and after */
33 #define PIXEL_PADDING 32
34
35 /* Make sure this is less than PIXEL_PADDING*/
36 #define MAX_DISPLACEMENT 16
37
38 #define MIN_SCROLL PIXEL_PADDING
39 #define MAX_SCROLL (backgroundW - fb_width - MIN_SCROLL)
40
41 #define FAR_SCROLL_SPEED 15.0f
42 #define NEAR_SCROLL_SPEED 120.0f
43
44 #define HORIZON_HEIGHT 100
45 #define REFLECTION_HEIGHT (240 - HORIZON_HEIGHT)
46
47 #define NORMALMAP_SCANLINE 372
48
49 static int init(void);
50 static void destroy(void);
51 static void start(long trans_time);
52 static void stop(long trans_time);
53 static void draw(void);
54
55 static void convert32To16(unsigned int *src32, unsigned short *dst16, unsigned int pixelCount);
56 static void processNormal();
57 static void initScrollTables();
58 static void updateScrollTables(float dt);
59
60
61
62 static unsigned short *background = 0;
63 static unsigned int backgroundW = 0;
64 static unsigned int backgroundH = 0;
65
66 static unsigned int lastFrameTime = 0;
67 static float lastFrameDuration = 0.0f;
68
69 static short *displacementMap;
70
71 static unsigned short *backBuffer;
72
73 static float scrollScaleTable[REFLECTION_HEIGHT];
74 static float scrollTable[REFLECTION_HEIGHT];
75 static int scrollTableRounded[REFLECTION_HEIGHT];
76 static int scrollModTable[REFLECTION_HEIGHT];
77 static float nearScrollAmount = 0.0f;
78
79 static RLEBitmap grobj;
80
81 static struct screen scr = {
82         "galaxyrise",
83         init,
84         destroy,
85         start,
86         stop,
87         draw
88 };
89
90 struct screen *grise_screen(void)
91 {
92         return &scr;
93 }
94
95
96 static int init(void)
97 {
98         unsigned char *tmpBitmap;
99         int tmpBitmapW, tmpBitmapH;
100
101         /* Allocate back buffer */
102         backBuffer = (unsigned short*) calloc(BB_SIZE * BB_SIZE, sizeof(unsigned short));
103
104         /* grise.png contains the background (horizon), baked reflection and normalmap for displacement */
105         if (!(background = img_load_pixels(BG_FILENAME, &backgroundW, &backgroundH, IMG_FMT_RGBA32))) {
106                 fprintf(stderr, "failed to load image " BG_FILENAME "\n");
107                 return -1;
108         }
109
110         /* Convert to 16bpp */
111         convert32To16((unsigned int*)background, background, backgroundW * NORMALMAP_SCANLINE); /* Normalmap will keep its 32 bit color */
112
113         /* Load reflected objects */
114         if (!(tmpBitmap = img_load_pixels(GROBJ_01_FILENAME, &tmpBitmapW, &tmpBitmapH, IMG_FMT_GREY8))) {
115                 fprintf(stderr, "failed to load image " GROBJ_01_FILENAME "\n");
116                 return -1;
117         }
118
119         grobj = rleEncode(tmpBitmap, tmpBitmapW, tmpBitmapH);
120
121         img_free_pixels(tmpBitmap);
122
123         initScrollTables();
124
125         processNormal();
126
127 #ifdef MIKE_PC
128         return 0xCAFE;
129 #else
130         return 0;
131 #endif
132 }
133
134 static void destroy(void)
135 {
136         free(backBuffer);
137         backBuffer = 0;
138
139         img_free_pixels(background);
140
141         rleDestroy(grobj);
142 }
143
144 static void start(long trans_time)
145 {
146         lastFrameTime = time_msec;
147 }
148
149 static void stop(long trans_time)
150 {
151 }
152
153
154 struct {
155         int circleX[3];
156         int circleY[3];
157 } wheelState;
158
159 static void updateWheel(float t) {
160         float x = 0.0f;
161         float y = 18.0f;
162         float nx, ny;
163         float cost, sint;
164         static float sin120 = 0.86602540378f;
165         static float cos120 = -0.5f;
166
167         /* Rotate */
168         sint = sin(t);
169         cost = cos(t);
170         nx = x * cost - y * sint;
171         ny = y * cost + x * sint;
172         x = nx;
173         y = ny;
174         wheelState.circleX[0] = (int)(x + 0.5f) + 16;
175         wheelState.circleY[0] = (int)(y + 0.5f) + 16;
176
177         /* Rotate by 120 degrees, for the second circle */
178         nx = x * cos120 - y * sin120;
179         ny = y * cos120 + x * sin120;
180         x = nx;
181         y = ny;
182         wheelState.circleX[1] = (int)(x + 0.5f) + 16;
183         wheelState.circleY[1] = (int)(y + 0.5f) + 16;
184
185         /* 3rd circle */
186         nx = x * cos120 - y * sin120;
187         ny = y * cos120 + x * sin120;
188         x = nx;
189         y = ny;
190         wheelState.circleX[2] = (int)(x + 0.5f) + 16;
191         wheelState.circleY[2] = (int)(y + 0.5f) + 16;
192 }
193
194 #define WHEEL_CIRCLE_RADIUS 18
195 #define WHEEL_CIRCLE_RADIUS_SQ (WHEEL_CIRCLE_RADIUS * WHEEL_CIRCLE_RADIUS)
196
197 static unsigned short wheel(int x, int y) {
198         int cx, cy, count=0;
199
200         /* First circle */
201         cx = wheelState.circleX[0] - x;
202         cy = wheelState.circleY[0] - y;
203         if (cx*cx + cy*cy < WHEEL_CIRCLE_RADIUS_SQ) count++;
204
205         /* 2nd circle */
206         cx = wheelState.circleX[1] - x;
207         cy = wheelState.circleY[1] - y;
208         if (cx*cx + cy*cy < WHEEL_CIRCLE_RADIUS_SQ) count++;
209
210         /* 3rd circle */
211         cx = wheelState.circleX[2] - x;
212         cy = wheelState.circleY[2] - y;
213         if (cx*cx + cy*cy < WHEEL_CIRCLE_RADIUS_SQ) count++;
214
215         if (count >= 2) return 0xFFFF;
216
217         return 0x000F;
218 }
219
220 static void draw(void)
221 {       
222         int scroll = MIN_SCROLL + (MAX_SCROLL - MIN_SCROLL) * mouse_x / fb_width;
223         unsigned short *dst = backBuffer + PIXEL_PADDING;
224         unsigned short *src = background + scroll;
225         int scanline = 0;
226         int i = 0;
227         short *dispScanline;
228         int d;
229
230         lastFrameDuration = (time_msec - lastFrameTime) / 1000.0f;
231         lastFrameTime = time_msec;
232
233         /* Update mini-effects here */
234         updateWheel(time_msec / 1000.0f);
235
236         /* First, render the horizon */
237         for (scanline = 0; scanline < HORIZON_HEIGHT; scanline++) {
238                 memcpy(dst, src, fb_width * 2);
239                 src += backgroundW;
240                 dst += BB_SIZE;
241         }
242         
243         /* Create scroll offsets for all scanlines of the normalmap */
244         updateScrollTables(lastFrameDuration);
245
246         /* Render the baked reflection one scanline below its place, so that 
247          * the displacement that follows will be done in a cache-friendly way
248          */
249         src -= PIXEL_PADDING; /* We want to also fill the PADDING pixels here */
250         dst = backBuffer + (HORIZON_HEIGHT + 1) * BB_SIZE;
251         for (scanline = 0; scanline < REFLECTION_HEIGHT; scanline++) {
252                 memcpy(dst, src, (fb_width + PIXEL_PADDING) * 2);
253                 src += backgroundW;
254                 dst += BB_SIZE;
255         }
256
257         /* Blit reflections first, to be  displaced */
258         for (i = 0; i < 5; i++) rleBlitScaleInv(backBuffer + PIXEL_PADDING, fb_width, fb_height, BB_SIZE, grobj, 134 + (i-3) * 60, 235, 1.0f, 1.8f);
259
260         /* Perform displacement */
261         dst = backBuffer + HORIZON_HEIGHT * BB_SIZE + PIXEL_PADDING;
262         src = dst + BB_SIZE; /* The pixels to be displaced are 1 scanline below */
263         dispScanline = displacementMap;
264         for (scanline = 0; scanline < REFLECTION_HEIGHT; scanline++) {
265                 for (i = 0; i < fb_width; i++) {
266                         d = dispScanline[(i + scrollTableRounded[scanline]) % scrollModTable[scanline]];
267                         *dst++ = src[i + d];
268                 }
269                 src += backgroundW;
270                 dst += BB_SIZE - fb_width;
271                 dispScanline += backgroundW;
272         }
273
274         /* Then after displacement, blit the objects */
275         for (i = 0; i < 5; i++) rleBlit(backBuffer + PIXEL_PADDING, fb_width, fb_height, BB_SIZE, grobj, 134 + (i-3) * 60, 100);
276
277         for (scanline = 0; scanline < 32; scanline++) {
278                 for (i = 0; i < 32; i++) {
279                         backBuffer[PIXEL_PADDING + scanline * BB_SIZE + i] = wheel(i, scanline);
280                 }
281         }
282
283         /* Blit effect to framebuffer */
284         src = backBuffer + PIXEL_PADDING;
285         dst = vmem_back;
286         for (scanline = 0; scanline < fb_height; scanline++) {
287                 memcpy(dst, src, fb_width * 2);
288                 src += BB_SIZE; 
289                 dst += fb_width;
290         }
291
292         swap_buffers(0);
293 }
294
295 /* src and dst can be the same */
296 static void convert32To16(unsigned int *src32, unsigned short *dst16, unsigned int pixelCount) {
297         unsigned int p;
298         while (pixelCount) {
299                 p = *src32++;
300                 *dst16++ =      ((p << 8) & 0xF800)             /* R */
301                         |               ((p >> 5) & 0x07E0)             /* G */
302                         |               ((p >> 19) & 0x001F);   /* B */
303                 pixelCount--;
304         }
305 }
306
307 /* Normal map preprocessing */
308 /* Scale normal with depth and unpack R component (horizontal component) */
309 static void processNormal() {
310         int scanline;
311         int i;
312         int x;
313         short maxDisplacement = 0;
314         short minDisplacement = 256;
315         unsigned short *dst;
316         short *dst2;
317         unsigned int *normalmap = (unsigned int*)background;
318         normalmap += NORMALMAP_SCANLINE * backgroundW;
319         dst = (unsigned short*)normalmap;
320         displacementMap = (short*)dst;
321         dst2 = displacementMap;
322
323         for (scanline = 0; scanline < REFLECTION_HEIGHT; scanline++) {
324                 scrollModTable[scanline] = (int) (backgroundW / scrollScaleTable[scanline] + 0.5f);
325                 for (i = 0; i < backgroundW; i++) {
326                         x = (int)(i * scrollScaleTable[scanline] + 0.5f);
327                         if (x < backgroundW) {
328                                 *dst = (unsigned short)(normalmap[x] >> 8) & 0xFF;
329                                 if ((short)*dst > maxDisplacement) maxDisplacement = (short)(*dst);
330                                 if ((short)*dst < minDisplacement) minDisplacement = (short)(*dst);
331                         } else {
332                                 *dst = 0;
333                         }
334                         dst++;
335                 }
336                 normalmap += backgroundW;
337         }
338
339         if (maxDisplacement == minDisplacement) {
340                 printf("Warning: grise normalmap fucked up\n");
341                 return;
342         }
343
344         /* Second pass - subtract half maximum displacement to displace in both directions */
345         for (scanline = 0; scanline < REFLECTION_HEIGHT; scanline++) {
346                 for (i = 0; i < backgroundW; i++) {
347                         /* Remember that MIN_SCROLL is the padding around the screen, so ti's the maximum displacement we can get (positive & negative) */
348                         *dst2 = 2 * MAX_DISPLACEMENT * (*dst2 - minDisplacement) / (maxDisplacement - minDisplacement) - MAX_DISPLACEMENT;
349                         *dst2 = (short)((float)*dst2 / scrollScaleTable[scanline] + 0.5f); /* Displacements must also scale with distance*/
350                         dst2++;
351                 }
352         }
353 }
354
355 static float distanceScale(int scanline) {
356         float farScale, t;
357         farScale = (float)NEAR_SCROLL_SPEED / (float)FAR_SCROLL_SPEED;
358         t = (float)scanline / ((float)REFLECTION_HEIGHT - 1);
359         return 1.0f / (1.0f / farScale + (1.0f - 1.0f / farScale) * t);
360 }
361
362 static void initScrollTables() {
363         int i = 0;
364         for (i = 0; i < REFLECTION_HEIGHT; i++) {
365                 scrollScaleTable[i] = distanceScale(i);
366                 scrollTable[i] = 0.0f;
367                 scrollTableRounded[i] = 0;
368         }
369 }
370
371
372 static void updateScrollTables(float dt) {
373         int i = 0;
374         
375         nearScrollAmount += dt * NEAR_SCROLL_SPEED;
376         nearScrollAmount = (float) fmod(nearScrollAmount, 512.0f);
377
378         for (i = 0; i < REFLECTION_HEIGHT; i++) {
379                 scrollTable[i] = nearScrollAmount / scrollScaleTable[i];
380                 scrollTableRounded[i] = (int)(scrollTable[i] + 0.5f) % scrollModTable[i];
381         }
382 }
383
384 /* -------------------------------------------------------------------------------------------------
385  *                                   RLE STUFF                                                                           
386  * -------------------------------------------------------------------------------------------------
387  */
388 /* Limit streak count per scanline so we can directly jump to specific scanline */
389 #define RLE_STREAKS_PER_SCANLINE 4
390 /* Every streak is encoded by 2 bytes: offset and count of black pixels in the streak */
391 #define RLE_BYTES_PER_SCANLINE RLE_STREAKS_PER_SCANLINE * 2
392 #define RLE_FILL_COLOR 0
393 #define RLE_FILL_COLOR_32 ((RLE_FILL_COLOR << 16) | RLE_FILL_COLOR)
394
395 #define RLE_FIXED_BITS 16
396
397 static RLEBitmap rleCreate(unsigned int w, unsigned int h) {
398         RLEBitmap ret;
399         ret.w = w;
400         ret.h = h;
401
402         /* Add some padding at the end of the buffer, with the worst case for a scanline (w/2 streaks) */
403         ret.scans = (unsigned char*) calloc(h * RLE_BYTES_PER_SCANLINE + w, 1);
404
405         return ret;
406 }
407
408 static void rleDestroy(RLEBitmap b) {
409         free(b.scans);
410 }
411
412 static RLEBitmap rleEncode(unsigned char *pixels, unsigned int w, unsigned int h) {
413         int scanline;
414         int i;
415         int penActive = 0;
416         int counter = 0;
417         int accum = 0;
418         RLEBitmap ret;
419         unsigned char *output;
420
421         /* https://www.youtube.com/watch?v=RKMR02o1I88&feature=youtu.be&t=55 */
422         ret = rleCreate(w, h);
423
424         for (scanline = 0; scanline < h; scanline++) {
425                 output = ret.scans + scanline * RLE_BYTES_PER_SCANLINE;
426                 accum = 0;
427                 for (i = 0; i < w; i++) {
428                         if (*pixels++) {
429                                 if (penActive) {
430                                         if (counter >= PIXEL_PADDING) {
431                                                 *output++ = (unsigned char) counter;
432                                                 counter = 0;
433                                                 *output++ = (unsigned char)accum;
434                                         }
435                                         counter++;
436                                         accum++;
437                                 } else {
438                                         *output++ = (unsigned char)accum;
439                                         counter = 1;
440                                         accum++;
441                                         penActive = 1;
442                                 }
443                         } else {
444                                 if (penActive) {
445                                         *output++ = (unsigned char)counter;
446                                         counter = 1;
447                                         accum++;
448                                         penActive = 0;
449                                 } else {
450                                         counter++;
451                                         accum++;
452                                 }
453                         }
454                 }
455
456                 if (penActive) {
457                         *output++ = (unsigned char)counter;
458                 }
459                 penActive = 0;
460                 counter = 0;
461         }
462
463         return ret;
464 }
465
466 static void rleBlit(unsigned short *dst, int dstW, int dstH, int dstStride,
467         RLEBitmap bitmap, int blitX, int blitY) 
468 {
469         int scanline = 0;
470         int streakPos = 0;
471         int streakLength = 0;
472         int streak = 0;
473         unsigned char *input = bitmap.scans;
474         unsigned short *output;
475         unsigned int *output32;
476
477         dst += blitX + blitY * dstStride;
478
479         for (scanline = blitY; scanline < blitY + bitmap.h; scanline++) {
480                 if (scanline < 0 || scanline >= dstH) continue;
481                 for (streak = 0; streak < RLE_STREAKS_PER_SCANLINE; streak++) {
482                         streakPos = *input++;
483                         streakLength = *input++;
484
485                         if ((streakPos + blitX) <= 0) continue;
486
487                         output = dst + streakPos;
488
489                         /* Check if we need to write the first pixel as 16bit */
490                         if (streakLength % 2) {
491                                 *output++ = RLE_FILL_COLOR;
492                         }
493
494                         /* Then, write 2 pixels at a time */
495                         streakLength >>= 1;
496                         output32 = (unsigned int*) output;
497                         while (streakLength--) {
498                                 *output32++ = RLE_FILL_COLOR_32;
499                         }
500                 }
501
502                 dst += dstStride;
503         }
504 }
505
506 static void interpolateScan(unsigned char *output, unsigned char *a, unsigned char *b, float t) {
507         static int div = 1 << 23;
508         int ti, i;
509
510         t += 1.0f;
511         ti = (*((unsigned int*)&t)) & 0x7FFFFF;
512         
513         for (i = 0; i < RLE_BYTES_PER_SCANLINE; i++) {
514                 if (*a == 0) {
515                         *output++ = *b++;
516                         a++;
517                 } else {
518                         if (*b == 0) {
519                                 *output++ = *a++;
520                                 b++;
521                         } else {
522                                 *output++ = ((*b++ * ti) + (*a++ * (div - ti))) >> 23;
523                         }
524                 }
525         }
526 }
527
528 static void rleBlitScale(unsigned short *dst, int dstW, int dstH, int dstStride,
529         RLEBitmap bitmap, int blitX, int blitY, float scaleX, float scaleY)
530 {
531         int scanline = 0;
532         int streakPos = 0;
533         int streakLength = 0;
534         int streak = 0;
535         unsigned short *output;
536         unsigned int *output32;
537         unsigned char *input;
538         int scanlineCounter = 0;
539         static unsigned char scan[512];
540
541         int blitW = (int) (bitmap.w * scaleX + 0.5f);
542         int blitH = (int)(bitmap.h * scaleY + 0.5f);
543
544         /* From this point on, scaleY will be inverted */
545         scaleY = 1.0f / scaleY;
546
547         int scaleXFixed = (int)(scaleX * (float)(1 << RLE_FIXED_BITS) + 0.5f);
548         
549         dst += blitX + blitY * dstStride;
550
551         for (scanline = blitY; scanline < blitY + blitH; scanline++) {
552                 float normalScan = scanlineCounter * scaleY; /* ScaleY  is inverted */
553                 unsigned char *scan0 = bitmap.scans + RLE_BYTES_PER_SCANLINE * (int)normalScan;
554                 unsigned char *scan1 = scan0 + RLE_BYTES_PER_SCANLINE;
555                 normalScan -= (int)normalScan;
556                 interpolateScan(scan, scan0, scan1, normalScan);
557                 input = scan;
558                 scanlineCounter++;
559
560                 if (scanline < 0 || scanline >= dstH) continue;
561                 for (streak = 0; streak < RLE_STREAKS_PER_SCANLINE; streak++) {
562                         streakPos = (*input++ * scaleXFixed) >> RLE_FIXED_BITS;
563                         streakLength = (*input++ * scaleXFixed) >> RLE_FIXED_BITS;
564
565                         if ((streakPos + blitX) <= 0) continue;
566
567                         output = dst + streakPos;
568
569                         /* Check if we need to write the first pixel as 16bit */
570                         if (streakLength % 2) {
571                                 *output++ = RLE_FILL_COLOR;
572                         }
573
574                         /* Then, write 2 pixels at a time */
575                         streakLength >>= 1;
576                         output32 = (unsigned int*)output;
577                         while (streakLength--) {
578                                 *output32++ = RLE_FILL_COLOR_32;
579                         }
580                 }
581
582                 dst += dstStride;
583         }
584 }
585
586
587
588 static void rleBlitScaleInv(unsigned short *dst, int dstW, int dstH, int dstStride,
589         RLEBitmap bitmap, int blitX, int blitY, float scaleX, float scaleY)
590 {
591         int scanline = 0;
592         int streakPos = 0;
593         int streakLength = 0;
594         int streak = 0;
595         unsigned short *output;
596         unsigned int *output32;
597         unsigned char *input;
598         int scanlineCounter = 0;
599         static unsigned char scan[512];
600
601         int blitW = (int)(bitmap.w * scaleX + 0.5f);
602         int blitH = (int)(bitmap.h * scaleY + 0.5f);
603
604         /* From this point on, scaleY will be inverted */
605         scaleY = 1.0f / scaleY;
606
607         int scaleXFixed = (int)(scaleX * (float)(1 << RLE_FIXED_BITS) + 0.5f);
608
609         dst += blitX + blitY * dstStride;
610
611         for (scanline = blitY; scanline > blitY - blitH; scanline--) {
612                 float normalScan = scanlineCounter * scaleY; /* ScaleY is inverted */
613                 unsigned char *scan0 = bitmap.scans + RLE_BYTES_PER_SCANLINE * (int)normalScan;
614                 unsigned char *scan1 = scan0 + RLE_BYTES_PER_SCANLINE;
615                 normalScan -= (int)normalScan;
616                 interpolateScan(scan, scan0, scan1, normalScan);
617                 input = scan;
618                 scanlineCounter++;
619
620                 if (scanline < 0 || scanline >= dstH) continue;
621                 for (streak = 0; streak < RLE_STREAKS_PER_SCANLINE; streak++) {
622                         streakPos = (*input++ * scaleXFixed) >> RLE_FIXED_BITS;
623                         streakLength = (*input++ * scaleXFixed) >> RLE_FIXED_BITS;
624
625                         if ((streakPos + blitX) <= 0) continue;
626
627                         output = dst + streakPos;
628
629                         /* Check if we need to write the first pixel as 16bit */
630                         if (streakLength % 2) {
631                                 *output++ = RLE_FILL_COLOR;
632                         }
633
634                         /* Then, write 2 pixels at a time */
635                         streakLength >>= 1;
636                         output32 = (unsigned int*)output;
637                         while (streakLength--) {
638                                 *output32++ = RLE_FILL_COLOR_32;
639                         }
640                 }
641
642                 dst -= dstStride;
643         }
644 }