#include <fabgl.h>
#include <Math.h>

#include "hsdk_logo.raw.h"
#include "font_32x32.raw.h"
#include "musa.pcm.h"

fabgl::VGAController DisplayController;
fabgl::Canvas        canvas(&DisplayController);
SoundGenerator       soundGenerator;


#define DOUBLEBUFFERING 1

uint8_t scrollbuf[320*32];
uint8_t letterbuf[1*32];

Bitmap backpic = Bitmap(320, 240, &bgpic, PixelFormat::Native);
Bitmap clearpic = Bitmap(320, 160, bgpic+320*40, PixelFormat::Native);
Bitmap letbuf = Bitmap(1, 32, &letterbuf, PixelFormat::RGBA2222);

int varri = 0;
int scrlpnt = 0;

unsigned char sine[1024];

//unsigned char teksti[] = "HELSINGFORS SVENSKA DEMOSCENSKLUBBEN RF RULLAR!!  ] [ \\         ";
unsigned char teksti[] = "                      HELLO AND GREETINGS FROM HELSINGFORS SVENSKA DEMOSCENSKLUBBEN! COME TO 68K INSIDE 2024: HTTPS://68K-INSIDE.PARTY - NU [R RESTEN AV TEXTEN S] KLART P] SVENSKA. DENNA PRODUKTION GJORDES AV BRITELITE, BRACKET, OCH RICKY MARTIN. NU LITE INFORMATION OM V]R KLUBB: HSDK [R EN NYLIGEN GRUNDAD F\\RENING SKAPAD F\\R ATT FR[MJA DEMOSCENE-KULTUR I FINLAND P] SVENSKA. V]R VERKSAMHET BEST]R FR[MST AV ATT ORDNA DIVERSE EVENEMANG, BL.A. DEMOPARTIES OCH DEMOKV[LLAR. VI [R OCKS] MED OM ATT ORDNA 68K INSIDE 2024! [N S] L[NGE HAR VI INTE S] MYCKET ATT BER[TTA OM. DET KOMMER MERA INFORMATION INOM KORT! TACK SKA NI HA OCH VI SES IGEN!               ";
int textlen = sizeof(teksti);

void setup()
{
  DisplayController.begin();
  DisplayController.setResolution(QVGA_320x240_60Hz, 320, 240, DOUBLEBUFFERING);

  for (int i = 0; i < 1024; i++)
    sine[i] = int(127.5*sin(3.14159*(float)i/512)+128);

  canvas.setBrushColor(RGB888(0, 0, 0));
  for (int i = 0; i < 100; i++) {
    canvas.clear();
    canvas.swapBuffers();
    canvas.clear();
    canvas.swapBuffers();
  }
  canvas.drawBitmap(0, 0, &backpic);
  canvas.swapBuffers();
  canvas.drawBitmap(0, 0, &backpic);
  canvas.swapBuffers();
  
  soundGenerator.playSamples(musa, sizeof(musa), 100, -1);
}


void loop()
{

  unsigned short* tmpbuf2 = (unsigned short*)scrollbuf;
  unsigned short* tmpfont = (unsigned short*)font;
  unsigned int txtpnt = ((teksti[((scrlpnt>>4) % textlen)]-32)&0x3f)*16 + (scrlpnt & 15);
  for (int y = 0; y < 32; y++) {
    int newx = y*160;
    int newx2 = newx+1;
    for (int x = 0; x < 159; x++) {
      tmpbuf2[newx++] = tmpbuf2[newx2++];
    }
    tmpbuf2[newx] = tmpfont[(y<<10) + txtpnt];
  }

  canvas.drawBitmap(0, 40, &clearpic);

  int pnt = -scrlpnt*7;
  for (int x = 0; x < 320; x++) {
    int newy = 40 + (sine[pnt & 0x3ff]>>1);
    int newy2 = x;
    int i = 0;
    for (int y = 0; y < 32; y++) {
      letterbuf[i++] = scrollbuf[newy2];
      newy2+=320;
    };
    canvas.drawBitmap(x, newy, &letbuf);
    pnt+=2;
  }

  canvas.swapBuffers();

  scrlpnt++;
}
