<?php
$s = fopen("stars.inc", "wt");
$m1 = fopen("morph1.inc", "wt");
$m2 = fopen("morph2.inc", "wt");
$m3 = fopen("morph3.inc", "wt");

$x = file_get_contents("sphere.obj");
$f = file_get_contents("sonic.obj");
//$h = file_get_contents("head.obj");
$h = file_get_contents("TTN.obj.new");


// Get SONICs vertices
$object = array();
foreach(explode("\n", $f) as $l) {
	if(substr($l, 0, 2) != 'v ') continue;
	$object[] = explode(" ", $l);
}

// Get sphere vertices
$sphere = array();
foreach(explode("\n", $x) as $l) {
	if(substr($l, 0, 2) != 'v ') continue;
	$sphere[] = explode(" ", $l);
}

// Get head vertices
$head = array();
$min0 = 1e10; $max0 = -1e10;
$min1 = 1e10; $max1 = -1e10;
foreach(explode("\n", $h) as $l) {
	if(substr($l, 0, 2) != 'v ') continue;
	$x = explode(" ", $l);
	$x = array($x[1],$x[3]);
	$head[] = $x;
	$min0 = min($min0,floatval($x[0]));
	$max0 = max($max0,floatval($x[0]));
	$min1 = min($min1,floatval($x[1]));
	$max1 = max($max1,floatval($x[1]));
}
$headsize = max($max0-$min0,$max1-$min1);
$c0 = ($min0+$max0)/2;
$c1 = ($min1+$max1)/2;

for($i = 0; $i < 80; $i++) {
	// Star between -127 - 128, otherwise we'll possibly be out of range for fpm
	$star_x = rand(0, 255) - 127; 
	$star_y = rand(0, 255) - 127; 
	$star_z = rand(0, 255) - 127; 
	
	// Get Sonic
	$object_x = floatval($object[$i][2]) * -1;
	$object_y = floatval($object[$i][1]);
	$object_z = floatval($object[$i][3]);
	
	// Get sphere
	$sphere_x = floatval($sphere[$i][1]);
	$sphere_y = floatval($sphere[$i][2]);
	$sphere_z = floatval($sphere[$i][3]);
	
	// Get head
	$head_x = (floatval($head[$i][0])-$c0)/$headsize*255;
	$head_y = 0;
	$head_z = (floatval($head[$i][1])-$c1)/$headsize*255;
	
	// Morph 1 from star -> sphere
	$m1x = ($sphere_x - $star_x) / 32.0;
	$m1y = ($sphere_y - $star_y) / 32.0;
	$m1z = ($sphere_z - $star_z) / 32.0;
	
	// Morph 2 from sphere -> ttn
	$m2x = ($object_x - $sphere_x) / 32.0;
	$m2y = ($object_y - $sphere_y) / 32.0;
	$m2z = ($object_z - $sphere_z) / 32.0;
	
	// Morph 3 from ttn -> head
	$m3x = ($head_x - $object_x) / 32.0;
	$m3y = ($head_y - $object_y) / 32.0;
	$m3z = ($head_z - $object_z) / 32.0;
	
	// Upscale
	$star_x *= 256; $star_y *= 256; $star_z *= 256;
	$m1x    *= 256; $m1y    *= 256; $m1z    *= 256;
	$m2x    *= 256; $m2y    *= 256; $m2z    *= 256;
	$m3x    *= 256; $m3y    *= 256; $m3z    *= 256;
	
	// Write data file
	fprintf($s,  "\tdc.w ".join(",", array(intval($star_x), intval($star_y), intval($star_z), 0))."\n");
	fprintf($m1, "\tdc.w ".join(",", array(round ($m1x),    round ($m1y),    round ($m1z),    0))."\n");
	fprintf($m2, "\tdc.w ".join(",", array(round ($m2x),    round ($m2y),    round ($m2z),    0))."\n");
	fprintf($m3, "\tdc.w ".join(",", array(round ($m3x),    round ($m3y),    round ($m3z),    0))."\n");
}

fclose($s);
fclose($m1);
fclose($m2);
fclose($m3);