Made RLE streak width/position scaling use fixed point + updated RLE scanline interpo...
[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*) malloc(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 static void draw(void)
154 {       
155         int scroll = MIN_SCROLL + (MAX_SCROLL - MIN_SCROLL) * mouse_x / fb_width;
156         unsigned short *dst = backBuffer + PIXEL_PADDING;
157         unsigned short *src = background + scroll;
158         int scanline = 0;
159         int i = 0;
160         short *dispScanline;
161         int d;
162
163         lastFrameDuration = (time_msec - lastFrameTime) / 1000.0f;
164         lastFrameTime = time_msec;
165
166         /* First, render the horizon */
167         for (scanline = 0; scanline < HORIZON_HEIGHT; scanline++) {
168                 memcpy(dst, src, fb_width * 2);
169                 src += backgroundW;
170                 dst += BB_SIZE;
171         }
172         
173         /* Create scroll offsets for all scanlines of the normalmap */
174         updateScrollTables(lastFrameDuration);
175
176         /* Render the baked reflection one scanline below its place, so that 
177          * the displacement that follows will be done in a cache-friendly way
178          */
179         src -= PIXEL_PADDING; /* We want to also fill the PADDING pixels here */
180         dst = backBuffer + (HORIZON_HEIGHT + 1) * BB_SIZE;
181         for (scanline = 0; scanline < REFLECTION_HEIGHT; scanline++) {
182                 memcpy(dst, src, (fb_width + PIXEL_PADDING) * 2);
183                 src += backgroundW;
184                 dst += BB_SIZE;
185         }
186
187         /* Blit reflections first, to be  displaced */
188         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);
189
190         /* Perform displacement */
191         dst = backBuffer + HORIZON_HEIGHT * BB_SIZE + PIXEL_PADDING;
192         src = dst + BB_SIZE; /* The pixels to be displaced are 1 scanline below */
193         dispScanline = displacementMap;
194         for (scanline = 0; scanline < REFLECTION_HEIGHT; scanline++) {
195                 for (i = 0; i < fb_width; i++) {
196                         d = dispScanline[(i + scrollTableRounded[scanline]) % scrollModTable[scanline]];
197                         *dst++ = src[i + d];
198                 }
199                 src += backgroundW;
200                 dst += BB_SIZE - fb_width;
201                 dispScanline += backgroundW;
202         }
203
204         /* Then after displacement, blit the objects */
205         //for (i = 0; i < 5; i++) rleBlit(backBuffer + PIXEL_PADDING, fb_width, fb_height, BB_SIZE, grobj, 134 + (i-3) * 60, 100);
206         for (i = 0; i < 5; i++) rleBlitScale(backBuffer + PIXEL_PADDING, fb_width, fb_height, BB_SIZE, grobj, 134 + (i - 3) * 120, 0, 1.8f, 1.8f);
207
208         /* Blit effect to framebuffer */
209         src = backBuffer + PIXEL_PADDING;
210         dst = fb_pixels;
211         for (scanline = 0; scanline < fb_height; scanline++) {
212                 memcpy(dst, src, fb_width * 2);
213                 src += BB_SIZE; 
214                 dst += fb_width;
215         }
216
217         swap_buffers(fb_pixels);
218 }
219
220 /* src and dst can be the same */
221 static void convert32To16(unsigned int *src32, unsigned short *dst16, unsigned int pixelCount) {
222         unsigned int p;
223         while (pixelCount) {
224                 p = *src32++;
225                 *dst16++ =      ((p << 8) & 0xF800)             /* R */
226                         |               ((p >> 5) & 0x07E0)             /* G */
227                         |               ((p >> 19) & 0x001F);   /* B */
228                 pixelCount--;
229         }
230 }
231
232 /* Normal map preprocessing */
233 /* Scale normal with depth and unpack R component (horizontal component) */
234 static void processNormal() {
235         int scanline;
236         int i;
237         int x;
238         short maxDisplacement = 0;
239         short minDisplacement = 256;
240         unsigned short *dst;
241         short *dst2;
242         unsigned int *normalmap = (unsigned int*)background;
243         normalmap += NORMALMAP_SCANLINE * backgroundW;
244         dst = (unsigned short*)normalmap;
245         displacementMap = (short*)dst;
246         dst2 = displacementMap;
247
248         for (scanline = 0; scanline < REFLECTION_HEIGHT; scanline++) {
249                 scrollModTable[scanline] = (int) (backgroundW / scrollScaleTable[scanline] + 0.5f);
250                 for (i = 0; i < backgroundW; i++) {
251                         x = (int)(i * scrollScaleTable[scanline] + 0.5f);
252                         if (x < backgroundW) {
253                                 *dst = (unsigned short)(normalmap[x] >> 8) & 0xFF;
254                                 if ((short)*dst > maxDisplacement) maxDisplacement = (short)(*dst);
255                                 if ((short)*dst < minDisplacement) minDisplacement = (short)(*dst);
256                         } else {
257                                 *dst = 0;
258                         }
259                         dst++;
260                 }
261                 normalmap += backgroundW;
262         }
263
264         if (maxDisplacement == minDisplacement) {
265                 printf("Warning: grise normalmap fucked up\n");
266                 return;
267         }
268
269         /* Second pass - subtract half maximum displacement to displace in both directions */
270         for (scanline = 0; scanline < REFLECTION_HEIGHT; scanline++) {
271                 for (i = 0; i < backgroundW; i++) {
272                         /* Remember that MIN_SCROLL is the padding around the screen, so ti's the maximum displacement we can get (positive & negative) */
273                         *dst2 = 2 * MAX_DISPLACEMENT * (*dst2 - minDisplacement) / (maxDisplacement - minDisplacement) - MAX_DISPLACEMENT;
274                         *dst2 = (short)((float)*dst2 / scrollScaleTable[scanline] + 0.5f); /* Displacements must also scale with distance*/
275                         dst2++;
276                 }
277         }
278 }
279
280 static float distanceScale(int scanline) {
281         float farScale, t;
282         farScale = (float)NEAR_SCROLL_SPEED / (float)FAR_SCROLL_SPEED;
283         t = (float)scanline / ((float)REFLECTION_HEIGHT - 1);
284         return 1.0f / (1.0f / farScale + (1.0f - 1.0f / farScale) * t);
285 }
286
287 static void initScrollTables() {
288         int i = 0;
289         for (i = 0; i < REFLECTION_HEIGHT; i++) {
290                 scrollScaleTable[i] = distanceScale(i);
291                 scrollTable[i] = 0.0f;
292                 scrollTableRounded[i] = 0;
293         }
294 }
295
296
297 static void updateScrollTables(float dt) {
298         int i = 0;
299         
300         nearScrollAmount += dt * NEAR_SCROLL_SPEED;
301         nearScrollAmount = (float) fmod(nearScrollAmount, 512.0f);
302
303         for (i = 0; i < REFLECTION_HEIGHT; i++) {
304                 scrollTable[i] = nearScrollAmount / scrollScaleTable[i];
305                 scrollTableRounded[i] = (int)(scrollTable[i] + 0.5f) % scrollModTable[i];
306         }
307 }
308
309 /* -------------------------------------------------------------------------------------------------
310  *                                   RLE STUFF                                                                           
311  * -------------------------------------------------------------------------------------------------
312  */
313 /* Limit streak count per scanline so we can directly jump to specific scanline */
314 #define RLE_STREAKS_PER_SCANLINE 4
315 /* Every streak is encoded by 2 bytes: offset and count of black pixels in the streak */
316 #define RLE_BYTES_PER_SCANLINE RLE_STREAKS_PER_SCANLINE * 2
317 #define RLE_FILL_COLOR 0xFF00 
318 #define RLE_FILL_COLOR_32 ((RLE_FILL_COLOR << 16) | RLE_FILL_COLOR)
319
320 #define RLE_FIXED_BITS 16
321
322 static RLEBitmap rleCreate(unsigned int w, unsigned int h) {
323         RLEBitmap ret;
324         ret.w = w;
325         ret.h = h;
326
327         /* Add some padding at the end of the buffer, with the worst case for a scanline (w/2 streaks) */
328         ret.scans = (unsigned char*) calloc(h * RLE_BYTES_PER_SCANLINE + w, 1);
329
330         return ret;
331 }
332
333 static void rleDestroy(RLEBitmap b) {
334         free(b.scans);
335 }
336
337 static RLEBitmap rleEncode(unsigned char *pixels, unsigned int w, unsigned int h) {
338         int scanline;
339         int i;
340         int penActive = 0;
341         int counter = 0;
342         int accum = 0;
343         RLEBitmap ret;
344         unsigned char *output;
345
346         /* https://www.youtube.com/watch?v=RKMR02o1I88&feature=youtu.be&t=55 */
347         ret = rleCreate(w, h);
348
349         for (scanline = 0; scanline < h; scanline++) {
350                 output = ret.scans + scanline * RLE_BYTES_PER_SCANLINE;
351                 accum = 0;
352                 for (i = 0; i < w; i++) {
353                         if (*pixels++) {
354                                 if (penActive) {
355                                         if (counter >= PIXEL_PADDING) {
356                                                 *output++ = (unsigned char) counter;
357                                                 counter = 0;
358                                                 *output++ = (unsigned char)accum;
359                                         }
360                                         counter++;
361                                         accum++;
362                                 } else {
363                                         *output++ = (unsigned char)accum;
364                                         counter = 1;
365                                         accum++;
366                                         penActive = 1;
367                                 }
368                         } else {
369                                 if (penActive) {
370                                         *output++ = (unsigned char)counter;
371                                         counter = 1;
372                                         accum++;
373                                         penActive = 0;
374                                 } else {
375                                         counter++;
376                                         accum++;
377                                 }
378                         }
379                 }
380
381                 if (penActive) {
382                         *output++ = (unsigned char)counter;
383                 }
384                 penActive = 0;
385                 counter = 0;
386         }
387
388         return ret;
389 }
390
391 static void rleBlit(unsigned short *dst, int dstW, int dstH, int dstStride,
392         RLEBitmap bitmap, int blitX, int blitY) 
393 {
394         int scanline = 0;
395         int streakPos = 0;
396         int streakLength = 0;
397         int streak = 0;
398         unsigned char *input = bitmap.scans;
399         unsigned short *output;
400         unsigned int *output32;
401
402         dst += blitX + blitY * dstStride;
403
404         for (scanline = blitY; scanline < blitY + bitmap.h; scanline++) {
405                 if (scanline < 0 || scanline >= dstH) continue;
406                 for (streak = 0; streak < RLE_STREAKS_PER_SCANLINE; streak++) {
407                         streakPos = *input++;
408                         streakLength = *input++;
409
410                         if ((streakPos + blitX) <= 0) continue;
411
412                         output = dst + streakPos;
413
414                         /* Check if we need to write the first pixel as 16bit */
415                         if (streakLength % 2) {
416                                 *output++ = RLE_FILL_COLOR;
417                         }
418
419                         /* Then, write 2 pixels at a time */
420                         streakLength >>= 1;
421                         output32 = (unsigned int*) output;
422                         while (streakLength--) {
423                                 *output32++ = RLE_FILL_COLOR_32;
424                         }
425                 }
426
427                 dst += dstStride;
428         }
429 }
430
431 static void interpolateScan(unsigned char *output, unsigned char *a, unsigned char *b, float t) {
432         static int div = 1 << 23;
433         int ti, i;
434
435         t += 1.0f;
436         ti = (*((unsigned int*)&t)) & 0x7FFFFF;
437         
438         for (i = 0; i < RLE_BYTES_PER_SCANLINE; i++) {
439                 if (*a == 0) {
440                         *output++ = *b++;
441                         a++;
442                 } else {
443                         if (*b == 0) {
444                                 *output++ = *a++;
445                                 b++;
446                         } else {
447                                 *output++ = ((*b++ * ti) + (*a++ * (div - ti))) >> 23;
448                         }
449                 }
450         }
451 }
452
453 static void rleBlitScale(unsigned short *dst, int dstW, int dstH, int dstStride,
454         RLEBitmap bitmap, int blitX, int blitY, float scaleX, float scaleY)
455 {
456         int scanline = 0;
457         int streakPos = 0;
458         int streakLength = 0;
459         int streak = 0;
460         unsigned short *output;
461         unsigned int *output32;
462         unsigned char *input;
463         int scanlineCounter = 0;
464         static unsigned char scan[512];
465
466         int blitW = (int) (bitmap.w * scaleX + 0.5f);
467         int blitH = (int)(bitmap.h * scaleY + 0.5f);
468
469         /* From this point on, scaleY will be inverted */
470         scaleY = 1.0f / scaleY;
471
472         int scaleXFixed = (int)(scaleX * (float)(1 << RLE_FIXED_BITS) + 0.5f);
473         
474         dst += blitX + blitY * dstStride;
475
476         for (scanline = blitY; scanline < blitY + blitH; scanline++) {
477                 float normalScan = scanlineCounter * scaleY; /* ScaleY  is inverted */
478                 unsigned char *scan0 = bitmap.scans + RLE_BYTES_PER_SCANLINE * (int)normalScan;
479                 unsigned char *scan1 = scan0 + RLE_BYTES_PER_SCANLINE;
480                 normalScan -= (int)normalScan;
481                 interpolateScan(scan, scan0, scan1, normalScan);
482                 input = scan;
483                 scanlineCounter++;
484
485                 if (scanline < 0 || scanline >= dstH) continue;
486                 for (streak = 0; streak < RLE_STREAKS_PER_SCANLINE; streak++) {
487                         streakPos = (*input++ * scaleXFixed) >> RLE_FIXED_BITS;
488                         streakLength = (*input++ * scaleXFixed) >> RLE_FIXED_BITS;
489
490                         if ((streakPos + blitX) <= 0) continue;
491
492                         output = dst + streakPos;
493
494                         /* Check if we need to write the first pixel as 16bit */
495                         if (streakLength % 2) {
496                                 *output++ = RLE_FILL_COLOR;
497                         }
498
499                         /* Then, write 2 pixels at a time */
500                         streakLength >>= 1;
501                         output32 = (unsigned int*)output;
502                         while (streakLength--) {
503                                 *output32++ = RLE_FILL_COLOR_32;
504                         }
505                 }
506
507                 dst += dstStride;
508         }
509 }
510
511
512
513 static void rleBlitScaleInv(unsigned short *dst, int dstW, int dstH, int dstStride,
514         RLEBitmap bitmap, int blitX, int blitY, float scaleX, float scaleY)
515 {
516         int scanline = 0;
517         int streakPos = 0;
518         int streakLength = 0;
519         int streak = 0;
520         unsigned short *output;
521         unsigned int *output32;
522         unsigned char *input;
523         int scanlineCounter = 0;
524         static unsigned char scan[512];
525
526         int blitW = (int)(bitmap.w * scaleX + 0.5f);
527         int blitH = (int)(bitmap.h * scaleY + 0.5f);
528
529         /* From this point on, scaleY will be inverted */
530         scaleY = 1.0f / scaleY;
531
532         int scaleXFixed = (int)(scaleX * (float)(1 << RLE_FIXED_BITS) + 0.5f);
533
534         dst += blitX + blitY * dstStride;
535
536         for (scanline = blitY; scanline > blitY - blitH; scanline--) {
537                 float normalScan = scanlineCounter * scaleY; /* ScaleY is inverted */
538                 unsigned char *scan0 = bitmap.scans + RLE_BYTES_PER_SCANLINE * (int)normalScan;
539                 unsigned char *scan1 = scan0 + RLE_BYTES_PER_SCANLINE;
540                 normalScan -= (int)normalScan;
541                 interpolateScan(scan, scan0, scan1, normalScan);
542                 input = scan;
543                 scanlineCounter++;
544
545                 if (scanline < 0 || scanline >= dstH) continue;
546                 for (streak = 0; streak < RLE_STREAKS_PER_SCANLINE; streak++) {
547                         streakPos = (*input++ * scaleXFixed) >> RLE_FIXED_BITS;
548                         streakLength = (*input++ * scaleXFixed) >> RLE_FIXED_BITS;
549
550                         if ((streakPos + blitX) <= 0) continue;
551
552                         output = dst + streakPos;
553
554                         /* Check if we need to write the first pixel as 16bit */
555                         if (streakLength % 2) {
556                                 *output++ = RLE_FILL_COLOR;
557                         }
558
559                         /* Then, write 2 pixels at a time */
560                         streakLength >>= 1;
561                         output32 = (unsigned int*)output;
562                         while (streakLength--) {
563                                 *output32++ = RLE_FILL_COLOR_32;
564                         }
565                 }
566
567                 dst -= dstStride;
568         }
569 }