// tunnel2.js



w = 96;
h = 72;

var texW = 64;
var texH = 64;

var t2_texture = Array();

rows = texW; cols = texH;
t2_texture = new Array(cols);
for (var i = 0; i < rows; i++)
t2_texture[i] = new Array(cols);

rows = w*2; cols = h*2;
t2_distanceTable = new Array(cols);
for (var i = 0; i < rows; i++)
t2_distanceTable[i] = new Array(cols);

rows = w*2; cols = h*2;
t2_angleTable = new Array(cols);
for (var i = 0; i < rows; i++)
t2_angleTable[i] = new Array(cols);

rows = w; cols = h;
buffer = new Array(cols);
for (var i = 0; i < rows; i++)
buffer[i] = new Array(cols);

rows = texW; cols = texH;

noise = new Array(cols);
for (var i = 0; i < rows; i++)
noise[i] = new Array(cols);

    for (var x = 0; x < texW; x++)
    for (var y = 0; y < texH; y++)
    {
        noise[x][y] = Math.random();
    }

for(var x = 0; x < texW; x++)
{
	for(var y = 0; y < texH; y++)
	{
		t2_texture[x][y] = Math.round(turbulence(x, y, 128)/2);
	}
}



for(var x = 0; x < w*2; x++)
{
	for(var y = 0; y < h*2; y++)
	{
		var angle, distance;
		var ratio = 16.0;
		
		distance = Math.round(ratio * texH / Math.sqrt((x - w) * (x - w) + (y - h) * (y - h)) % texH);
		angle = Math.round(0.5 * texW * Math.atan2((y - h), (x - w)) / 3.1415);		
		
		t2_distanceTable[x][y] = distance; 
		t2_angleTable[x][y] = angle;
	}
}


function smoothNoise(x, y)
{  
   
   var fractX = x - Math.round(x);
   var fractY = y - Math.round(y);
   
   
   var x1 = (Math.round(x) + texW) % texW;
   var y1 = (Math.round(y) + texH) % texH;
   
   
   var x2 = (x1 + texW - 1) % texW;
   var y2 = (y1 + texH - 1) % texH;

   
   var value = 0.0;
   value += fractX       * fractY       * noise[x1][y1];
   value += fractX       * (1 - fractY) * noise[x1][y2];
   value += (1 - fractX) * fractY       * noise[x2][y1];
   value += (1 - fractX) * (1 - fractY) * noise[x2][y2];

   return value;
}

function turbulence(x, y, size)
{
    var value = 0.0, initialSize = size;
    
    while(size >= 1)
    {
        value += smoothNoise(x / size, y / size) * size;
        size /= 2.0;
    }
    
    return(128.0 * value / initialSize);
}

function init_tunnel2()
{
	w = 96;
	h = 72;
	
	texW = 64;
	texH = 64;
	
	kuvahead = bmp8(w,h);
	
	move = 10000;
}

var move;

function render_tunnel2()
{
	kuva = "";
	
	move += 0.05;
	y=0;
	x=0;
	
	var distest = 0;
	var angtext = 0;
	
	var shiftX = Math.round(texW * move);
	var shiftY = Math.round(texH * move);
	
	var shiftLookX =  w / 2 + Math.round(w / 2 * Math.sin(move));
	var shiftLookY =  h / 2 + Math.round(h / 2 * Math.sin(move * 2.0));
	
	for (var y=0; y<h; y++)
	{
		for(var x=0; x<w; x++)
		{
			distest = (t2_distanceTable[x + shiftLookX][y + shiftLookY] + shiftX) % texW;
			angtest = (t2_angleTable[x + shiftLookX][y + shiftLookY] + shiftY) % texH;
				
			if (!isNaN(distest))
				color = dec2hex[t2_texture[distest][angtest]];
			else
				color = "%00";
			
			kuva+=color;
		}
	}
	
	return kuva;
}

