/*
 * Display.h
 *
 *  Created on: 03.12.2020
 *      Author: willy
 */
#ifndef DISPLAY_H_
#define DISPLAY_H_

// Definition of Screen resolution in pixel
#define COLS 12
#define ROWS 8

/*
 * virtual screen,
 * The screen is regarded as a Matrix with 8 rows and 12 collums. 
 * Each field inside the matrix represent one pixel on the screen
 * consists of a one dimensional array with integer values.
 * Each row on the screen is represented by one field of the array.
 * The Integer filling the field convertet to binary state wich pixels are active
 * Exp.:
 *																			 __					              __
 *																			|  1,0,0,0,0,0,0,0,0,0,0,0  |
 *																			|  1,0,0,0,0,0,0,0,0,0,0,0  |
 *																			|  1,0,0,0,0,0,0,0,0,0,0,0  |
 *	 [2048,2048,2048,64,0,1,1,1]   ==> 	|  0,0,0,0,0,1,0,0,0,0,0,0  | 
 *																			|  0,0,0,0,0,0,0,0,0,0,0,0  |
 *																			|  0,0,0,0,0,0,0,0,0,0,0,1  |
 *																			|  0,0,0,0,0,0,0,0,0,0,0,1  |
 *																			|__0,0,0,0,0,0,0,0,0,0,0,1__|
 *
 * 1-> pixel light up
 * 0-> pixel is dark
*/
int screen[ROWS];

/*
 * helper function to print integer values as binary.
 * only used for debugging to display the screen on the console
 * found at: https://www.geeksforgeeks.org/binary-representation-of-a-given-number/
*/
void bin(unsigned n)
{
    if (n > 1)
        bin(n >> 1);
    printf("%d", n & 1);
}

/*
 * actual drawing function. It will output the screen variabe on the designated registers.
 * every Row of the screen is written to the register one after another in the following format:
 *  
 *	0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0
 *	|______||_____________________|
 *	 Row-ID		   Row-Data
 *
 * Row-ID: 	state which row the data is from. Values from 1 to 8. 0 is an invalid value
 * Row-Data:	a binary value for each pixel in the row
*/
void draw() {
	int row,i,j;
	for (i=0; i<ROWS; i++) {
		row = screen[i] | ((i+1)<<12); //send format: (4bits row indicator, 12bits data)
		IOWR_ALTERA_AVALON_PIO_DATA(PIO_MATRIX_BASE, row);
	}
}


/*
 * function to draw the virtual screen on a console. Only used for debugging. 
*/
void draw_console() {
	int i;
	for (i=0; i<ROWS; i++) {
		bin(screen[i]);
		printf("\n");
	}
}


/*
 * function to set the given pixel 1.
 * x and y are the coordinates, x is collumn number, y row number.
*/
void set_pixel(int x, int y) {
	//constrain x and y
	x = MAX(MIN(x, 0), COLS - 1);
	y = MAX(MIN(y, 0), ROWS - 1);

	screen[y] = screen[y] & ~(1<<x) | (1<<x);
}


/*
 * reset the screen, all pixels are set to 0. 
*/
void reset_screen() {
	int i;
	for (i=0; i<ROWS; i++) {
		screen[i] = 0;
	}

}



#endif /* DISPLAY_H_ */
