// Render Handler.
// Worthless Bums 2013.


// Called every time a unit moves to reorder all units.
function orderRenderedUnits ()
{//echo("orderRenderedUnits()");
	// All units includes player and AI units.
	%unitList = new SimSet();
	// Add player units.
	if ($leaderPersist)
	{
		%unitList.add($playerSquad[0]);
	}
	if ($scoutPersist)
	{
		%unitList.add($playerSquad[1]);
	}
	if ($grenadierPersist)
	{
		%unitList.add($playerSquad[2]);
	}
	if ($supportPersist)
	{
		%unitList.add($playerSquad[3]);
	}
	// Add AI units.
	for (%i = 0; %i < $monsterList.getCount(); %i++)
	{
		%unitList.add($monsterList.getObject(%i));
	}
	// Clear invisible/hidden units.
	for (%i = 0; %i < %unitList.getCount(); %i++)
	{
		%unit = %unitList.getObject(%i);
		if (!%unit.visible)
		{
			%unitList.remove(%unit);
		}
	}
	// Now we have a proper unit list.
	if (%unitList.getCount() > 1)
	{
		// Sort it!
		do
		{
			%sorted = true;
			for (%i = 0; %i < %unitList.getCount() - 2; %i++)
			{
				%unit1 = %unitList.getObject(%i);
				%unit2 = %unitList.getObject(%i + 1);
				if (getWord(%unit1.position, 1) > getWord(%unit2.position, 1))
				{
					%unitList.reorderChild(%unit1.getId(), %unit2.getId());  
				}
			}
		} while (!%sorted)
		// Render it!
		// For testing purposes start render layers at 4! - Wtf is this for?
		for (%i = 0; %i < %unitList.getCount(); %i++)
		{
			%unit = %unitList.getObject(%i);
			%unit.SceneLayer = 4 + %i;
		}
	}
	%unitList.safeDelete();
}
function echoMarineRenderLayers ()
{//echo("echoMarineRenderLayers()");
	echo($playerSquad[0].layer SPC $playerSquad[1].layer SPC $playerSquad[2].layer SPC $playerSquad[3].layer);
}