/*
* Copyright (C) 2004 TES Electronic Solutions GmbH,
* All Rights Reserved.
* This source code and any compilation or derivative thereof is the
* proprietary information of TES Electronic Solutions GmbH
* and is confidential in nature.
* Under no circumstances is this software to be exposed to or placed
* under an Open Source License of any type without the expressed
* written permission of TES Electronic Solutions GmbH
*
*############################################################
*/

/******************************************************************************
 Includes   <System Includes> , "Project Includes"
 ******************************************************************************/

#include <stdint.h>
#include <string.h>

extern "C"
{
#include "m13_rza2m_ek_led.h"
#include "m13_rza2m_ek_vcom.h"
#include "m13_rza2m_ek_acc.h"
#include "m13_rza2m_ek_ethernet.h"
#include "m13_rza2m_ek_touch.h"
#include "m13_rza2m_ek_lcd.h"

// External task definitions
extern void ethernet_task(void *parameters);
extern void accelerometer_task(void *parameters);
extern void adc_task(void *parameters);
extern void lcd_task(void *parameters);
extern void touch_task(void *pvParameters);
extern void audio_task(void *pvParameters);
}

#define LCD_BYTES_PER_PIXEL (DISPLAY_BITS_PER_PIXEL_INPUT0 >> 3)

/******************************************************************************
 Private global variables and functions
 ******************************************************************************/

/******************************************************************************
 Imported global variables and functions (from other files)
 ******************************************************************************/

uint8_t BytesPerPixel = LCD_BYTES_PER_PIXEL;
uint16_t m_uiWidth = LCD_WIDTH;
uint16_t m_uiHeight = LCD_HEIGHT;

extern uint8_t frame_buffer_1[];
extern uint8_t frame_buffer_2[];

volatile uint8_t *RZAFrameBuffers[] =
{
		frame_buffer_1,
		frame_buffer_2
};

int fb_index = 0;

volatile uint8_t* GetFrameBuffer()
{
    return RZAFrameBuffers[fb_index];
}

extern "C" void FlipFramebuffer()
{
	bsp_lcd_swap_buffer();

	fb_index++;
	if (fb_index > 1)
		fb_index = 0;

    vTaskDelay(1);
}

extern "C" void CopyBuffer(int iX1, int iY1, int iRectWidth, int iRectHeight)
{
	int next_index = fb_index + 1;
	if (next_index > 1)
		next_index = 0;
    uint8_t* pubSource = (uint8_t*)RZAFrameBuffers[next_index] + (iY1 * m_uiWidth + iX1) * BytesPerPixel;
    uint8_t* pubDest = (uint8_t*)RZAFrameBuffers[fb_index] + (iY1 * m_uiWidth + iX1) * BytesPerPixel;
    for (uint16_t iLineIndex = 0; iLineIndex < iRectHeight; ++iLineIndex)
    {
        memcpy(pubDest, pubSource, iRectWidth * BytesPerPixel);

        pubSource += m_uiWidth * BytesPerPixel;
        pubDest += m_uiWidth * BytesPerPixel;
    }
}
