/******************************************************
 *  JS_FBGL - Javascript Framebuffer Graphics Library 
 *  
 * 	JS_FBGL_Core.js 
 * 
 *  Licencesed under the creative common licence
 * 
 *  (c) 2oo6 - benny!weltenkonstrukeur.de
 *  Visit: http://www.weltenkonstrukteur.de
 *  Version 1.0
 */

function jsfbgl_open(x_res, y_res, pixel_width, pixel_height) {
/**
 * 	open (screenX, screenY) sets up demo-system and variables.
 *
 *  @return	void
 *  @author: benny!weltenkonstrukteur.de
 */	
 	jsfbgl_x 		= x_res;	// x-resolution of the framebuffer (i.e. table)
	jsfbgl_y 		= y_res;	// y-resolution of the framebuffer (i.e. table)
	
	document.writeln("<table id='table_frame' class=\"jsfbgl_frame\">");

	for ( y=0; y < jsfbgl_y; y++)
	{
		document.writeln("<tr>");		
		for ( x=0; x < jsfbgl_x; x++)
		{
			document.writeln("<td><img src='jsfbgl/trPix.gif' width='"+pixel_width+"' height='"+pixel_height+"' /></td>");
			jsfbgl_buffer[ x + (jsfbgl_x * y) ] = '#000000';
		}
		document.writeln("</tr>");	
	}

	document.writeln("</table>");

	jsfbgl_frame = document.getElementById('table_frame');
}


function jsfbgl_memcpy() {
/**
 *  jsfbgl_memcpy()
 *  Copies the whole jsfbgl_buffer to the jsfbgl_frame
 * 
 *  @return void
 *  @author benny!weltenkonstrukteur.de
 * 
 */	
	for (y=0; y < jsfbgl_y; y++) {
		for (x=0; x < jsfbgl_x; x++) {
			// update cells
			jsfbgl_frame.rows[y].cells[x].style.backgroundColor = 
				jsfbgl_buffer[x + (jsfbgl_x * y)];
		}
	}	
}


function jsfbgl_clearScr(col) {
/**
 *  jsfbgl_clearScr(col)
 *  Fills the buffer with given color col.
 * 
 *  @return void
 *  @author benny!weltenkonstrukteur.de
 * 
 */	
	for (y=0; y < jsfbgl_y; y++) {
		for (x=0; x < jsfbgl_x; x++) {
			jsfbgl_frame.rows[y].cells[x].style.backgroundColor = 
				col
		}
	}	
}

function jsfbgl_plot( xco, yco, col) {
/**
 *  jsfbgl_plot(xco, yco, col)
 *  Puts a pixel at xco,yco with color col. Be aware that
 *  xco and yco values starts at zero.
 *  
 * 	WARNING!
 *  There is no check if the coordinates are within the
 *  frame size due to performance reasons.
 * 
 *  @return void
 *  @author benny!weltenkonstrukteur.de
 * 
 */	
	
	jsfbgl_frame.rows[yco].cells[xco].style.backgroundColor =
		col;
}


function jsfbgl_line( x1, y1, x2, y2, col) {
/**
 *  jsfbgl_line( x1, y1, x2, y2, col)
 *  Draw a line starting from x1, y1 to x2,y2.
 *  col represents the line's color. Be aware that the co-
 *  ordinates values start at zero.
 *  
 * 	WARNING!
 *  There is no check if the coordinates are within the
 *  frame size due to performance reasons.
 * 
 *  @return void
 *  @author benny!weltenkonstrukteur.de
 * 
 */
	var	dx	= x2 - x1;
	var dy	= y2 - y1;
	var y	= y1;
	var	eps	= 0;
	
	for ( x = x1; x <= x2; x++) {
		jsfbgl_plot( x, y, col);
		eps += dy;
		if ( (eps << 1) >= dx ) {
			y++; eps -= dx;
		}		
	}	
}
