Source of sc.plp

<(common.inc.plp)><:
use List::Util qw(max sum);

my %scvers = (
	bw => {
		name => 'Brood War',
		title => 'starcraft',
		game => 'StarCraft BW',
		major => 1,
	},
	hots => {
		name => 'Heart of the Swarm',
		title => 'starcraft2 hots',
		game => 'StarCraft II HotS',
		major => 2,
	},
	lotv => {
		name => 'Legacy of the Void',
		title => 'starcraft2 lotv',
		game => 'StarCraft II LotV',
		major => 2,
	},
	index => 'bw',
	1     => 'bw',
	2     => 'lotv',
);

my $requestver = $scvers{$Request ||= 'index'}
	or Html(), Abort("Requested version <q>$Request</q> not available", '404 request not found');

if (ref $requestver ne 'HASH') {
	$header{Location} = "/sc/$requestver";
	Abort("Canonical URL for $Request is at $requestver", '302 subpage alias');
}

my %scver = %{$requestver};
my $datafile = "sc-units-$Request";

Html({
	title => "$scver{title} unit cheat sheet",
	version => '1.4',
	description => [
		"Reference of $scver{game} unit properties,"
		. " comparing various statistics of all the units in $scver{name}"
		. ' including costs, damage, defense, speed, ranges, and abilities.',
	],
	keywords => [
		qw'
		starcraft game unit statistics stats comparison table sheet cheat
		reference software attributes properties patch attribute multiplayer
		',
		$scver{major} < 2 ? qw' bw broodwar brood war ' :
		qw' starcraft2 lotv hots wol ',
	],
	stylesheet => [qw( light dark )],
	raw => '<link rel="stylesheet" type="text/css" media="all" href="/sc.css?1.2">',
	data => ["$datafile.inc.pl"],
});

say "<h1>$scver{game} units</h1>\n";

my $units = Data($datafile);
my $patch = shift @{$units}
	or Abort("Cannot open unit data: metadata not found", 501);

say "<p>Unit properties as seen or measured in $scver{name}\n$patch.";
say "Also see the $_ tables." for join(' and ',
	(showlink('StarCraft 2: LotV', '/sc/lotv'))    x ($Request ne 'lotv'),
	(showlink(             'HotS', '/sc/hots'))    x ($Request ne 'hots'),
	(showlink('original SC: Brood War', '/sc/bw')) x ($Request ne 'bw'),
);
say "</p>\n";

sub addupgrade {
	my ($ref, $increase, $org) = @_;
	if (ref $increase eq 'HASH') {
		addupgrade(\${$ref}->{$_}, $increase->{$_}, $org->{$_}) for keys %{$increase};
	}
	elsif (ref $increase eq 'ARRAY') {
		addupgrade(\${$ref}->[$_], $increase->[$_], $org->[$_]) for 0 .. $#{$increase};
	}
	${$ref} //= $org;
	${$ref} += $increase if $increase =~ /^-?[0-9.]+/;
}

for my $unit (@{$units}) {
	for my $upgrade (@{ $unit->{upgrade} }) {
		while (my ($col, $increase) = each %{$upgrade}) {
			defined $unit->{$col} or next;
			addupgrade(\$unit->{upgraded}->{$col}, $increase, $unit->{$col});
		}
	}
	for my $special (@{ $unit->{special} }) {
		for my $upgrade (@{ $special->{upgrade} }) {
			while (my ($col, $increase) = each %{$upgrade}) {
				defined $special->{$col} or next;
				addupgrade(\$special->{upgraded}->{$col}, $increase, $special->{$col});
			}
		}
	}
}

sub coltoggle {
	my ($name, $id, $nolink) = @_;
	return "$name ▼" if defined $get{order} ? $get{order} eq $id : !$id;
	return $name if $nolink;
	return showlink($name, '?'.($id && "order=$id"));
}
:><table class="units">
<thead><tr>
	<th><:= coltoggle(exists $get{order} ? 'race' : 'source' => '') :></th>
	<th class="unit-name"><:= coltoggle(name => 'name') :></th>
	<th class="val unit-min" title=minerals><:= coltoggle(cost => 'cost') :></th>
	<th class="val unit-gas">gas</th>
	<th class="val time"><:= coltoggle(build => 'build') :></th>
	<th class="unit" colspan="2"><:= coltoggle(qw'size size') :></th>
	<th class="unit unit-attr" colspan="2">attr</th>
	<th class="val unit-hp"><:= coltoggle(HP => 'hp') :></th>
	<th class="val unit-shield">shield</th>
	<th class="val unit-armor" title="armor"></th>
	<th class="val hurt"><:= coltoggle(attack => 'attack') :></th>
	<th class="hurt hurtrel">dps</th>
	<th class="val unit-range" colspan=3>range</th>
	<th class="val unit-sight">sight</th>
	<th class="val unit-speed"><:= coltoggle(speed => 'speed') :></th>
	<th class="unit-magic">specials</th>
</tr></thead>
<:
sub showrange {
	my ($min, $max) = @_;
	return '' if not defined $min;
	return $min || '-' if !$max or $min == $max;
	return "$min-$max";
}

sub showrangeint {
	$_ &&= int($_ + .5) for @_;  # round halves up
	return showrange(@_);
}

	sub showcost {
		my ($row, $unit) = @_;
		return join(' ',
			sprintf('cost %s%%', join '-',
				map { $_ && sprintf '%.0f', 100 * $row->{cost} / $_ } grep { defined $_ }
				$unit->{energy},
				$unit->{upgraded}->{energy},
				$unit->{capacity},
				$unit->{upgraded}->{capacity},
			),
			!defined $row->{maint} ? () : sprintf('+%s%%/s', join '-',
				map { sprintf '%.1f', 100 * $row->{maint} / $_ } grep $_,
				$unit->{capacity},
				$unit->{upgraded}->{capacity},
			),
		);
	}

	sub showattack {
		my ($row, $area) = @_;
		my $attack = $row->{attack}->[$area]
			or return '<td colspan=5 class="hurt">';

		my $upattack = $row->{upgraded}->{attack}->[$area];
		my $damage = $attack->{damage};
		my $maxdamage = $upattack->{damage} // $damage;
		$maxdamage += ($upattack->{upgrade} // $attack->{upgrade}) * 3;

		my $out = '<td class="val hurt">';
		$out .= sprintf '<span title="%s">¤</span> ', showcost($attack, $row)
			if $attack->{cost};
		$out .= sprintf('<small>%s× </small>',
			showrangeint($attack->{count}, $upattack->{count}),
		) if $attack->{count} > 1;
		$out .= '<span class="unit-l" title="explosive">*</span>'
			if $attack->{type} eq 'explosive';
		$out .= '<span class="unit-s" title="implosive">~</span>'
			if $attack->{type} eq 'implosive';
	if (my @bonus = sort grep { !/^-/ } keys %{ $attack->{bonus} }) {
		$out .= sprintf('<span class="%s" title="%s">&ge;</span>',
			(
				$_ eq 'light' ? 'unit-s' :
				$_ eq 'armored' ? 'unit-l' :
				$_ eq 'organic' ? 'unit-o' :
				$_ eq 'massive' ? 'unit-h' :
				$_ eq 'shields' ? 'unit-shield' :
				$_ eq 'structure' ? 'unit-x' :
				'',
			),
			(
				sprintf('+%s vs %s',
					showrangeint(
						$attack->{bonus}->{$_},
						($upattack->{bonus} // $attack->{bonus})->{$_}
							+ ($upattack->{bonus} // $attack->{bonus})->{"-$_"} * 3,
					),
					$_,
				),
			),
		) for @bonus;
	}
		$out .= '<span class="unit-pdd" title="projectile">•</span>'
			if $attack->{type} eq 'projectile';

		$out .= sprintf '<span title="%s">', $attack->{name} if $attack->{name};
		$out .= showrangeint($damage, $maxdamage);
		$out .= '</span>' if $attack->{name};
		$out .= sprintf('<span class="unit-splash" title="%s">%s</span>',
			$attack->{splash} eq 'line' ? ('linear', '+') : ('splash', '⁜')
		) if $attack->{splash};

		$out .= '<td class="val hurt hurtrel">';
		if ($attack->{dps}) {
			# precalculated dps, do not touch
			$out .= showrangeint($attack->{dps}->[0],
				$upattack->{dps}->[-1] // $attack->{dps}->[-1]
			);
		}
		elsif ($attack->{cooldown}) {
			if (my $type = $attack->{type}) {
				if ($type eq 'explosive') {
					$damage /= 2;
				}
				elsif ($type eq 'implosive') {
					$damage /= 4;
				}
			}
			$damage *= ($attack->{count} // 1) / $attack->{cooldown};
			if (my $bonus = $upattack->{bonus} // $attack->{bonus}) {
				$maxdamage += $_ for max(
					map { $bonus->{$_} + $bonus->{"-$_"} * 3 }
					grep { !/^-/ } keys %{$bonus}
				);
			}
			$maxdamage *= ($upattack->{count} // $attack->{count} // 1)
			            / ($upattack->{cooldown} // $attack->{cooldown});
			$out .= showrangeint($damage, $maxdamage);
		}

		$out .= '<td class="unit hurt-g">' . '▽' x !!($attack->{anti} & 1);
		$out .= '<td class="unit hurt-a">' . '△' x !!($attack->{anti} & 2);

		$out .= '<td class="val unit-range">' .
			showrangeint($attack->{range}, $upattack->{range});

		return $out;
	}

	sub showmagic {
		my ($row) = @_;
		my $specials = $row->{special} or return '';
		return join ' ', map {
			sprintf '<span%s title="%s">%s</span>',
				join('',
					$_->{duration} < 0 && ' class="magic-perma"',
					$_->{detect} && ' class="unit-detect"',
				),
				join('',
					$_->{name} // $_->{alt},
					$_->{desc} ? ": $_->{desc}" : '',
					(map { $_ && " ($_)" } join ', ',
						#TODO: apply upgrades
						$_->{range} ? "range $_->{range}" : (),
						$_->{cost} ? showcost($_, $row) :
						$_->{cooldown} ? "cooldown $_->{cooldown}s" : (),
					),
				),
				sprintf($_->{build} ? '(%s)' : '%s', $_->{abbr}),
		} grep { defined $_->{abbr} } @{$specials};
	}

	sub showunitcols {
		my ($row) = @_;
		local $_ = $row;
		$_->{hp} += $_->{shield} if $_->{shield};

		return (
			'<td class="val unit-min">' . ($_->{min} // ''),
			'<td class="val unit-gas">' . ($_->{gas} || ''),
			defined $_->{transform} ? sprintf('<td class="val time">%.0f',
				$_->{transform},
			) :
			!defined $_->{build} ? '<td>' : sprintf('<td class="val time"%s>%s%.0f',
				defined $_->{warp} && sprintf(' title="%.0f without warpgate"', $_->{build}),
				!!$_->{base} && sprintf(
					'<span class="unit-composed" title="%s">+</span>',
					'from '.join('+', @{ $_->{base} }),
				),
				$_->{warp} // $_->{build} || '0',
			),
			sprintf('<td class="unit unit-%s" title="%4$s%3$s">%s',
				$_->            {cargo} < 0 ? ('supply',           T => 'transport') :
				$_->{upgraded}->{cargo} < 0 ? ('supply magic-opt', T => 'optional transport') :
				$_->            {attr}->{flying} ? ('air',           F => 'flying') :
				$_->{upgraded}->{attr}->{flying} ? ('air magic-opt', F => 'potentially flying') :
				$_->{attr}->{structure} ? ('x',   B => 'building') :
				(
					[qw( x s m l l h h h h )]->[ $_->{cargo} ],
					$_->{cargo} || '-',
					$_->{cargo} ? 'transportable' : 'untransportable',
				),
				defined $_->{size} && sprintf('⌀%.1f ', $_->{size}),
			),
			sprintf('<td class="val unit unit-pop%s">%s',
				defined $_->{pop} && $_->{pop} < 0 && ' unit-supply',
				defined $_->{pop} && $_->{pop} == .5 ? '½' : $_->{pop},
			),
			'<td class="unit unit-type">' . join('', grep { $_ }
				(defined $_->{organic} ? !$_->{organic} : $_->{attr}->{mech})
					&& '<span class="unit-u" title="mechanic">m</span>',
				($_->{organic} || $_->{attr}->{organic})
					&& '<span class="unit-o" title="organic">o</span>',
				$_->{attr}->{psionic}
					&& '<span class="unit-p" title="psionic">ψ</span>',
			),
			'<td class="unit unit-attr">' . join('', grep { $_ }
				$_->{attr}->{armored}
					&& '<span class="unit unit-l" title="armored">A</span>',
				$_->{attr}->{light}
					&& '<span class="unit unit-s" title="light">L</span>',
				$_->{suit} && sprintf(
					'<span class="unit unit-%s" title="%3$s">%s</span>',
					map { @{$_} } [
						[qw( x ? unknown )],
						[qw( s S small )],
						[qw( m M medium )],
						[qw( l L large )],
					]->[ $_->{suit} ],
				),
				$_->{attr}->{massive}
					&& '<span class="unit-massive" title="massive">⚓</span>',
			),
			$_->{hp} < 0 ? '<td class="val unit-hp" title="invulnerable">∞' :
			'<td class="val unit-hp">' . showrangeint($_->{hp}, $_->{upgraded}->{hp}),
			$_->{shield} ? sprintf('<td class="val unit-shield">%.0f%%<td',
				100 * $_->{shield} / $_->{hp}
			) : '<td colspan=2',
			' class="val unit-armor">' .
				showrangeint($_->{armor}, $_->{upgraded}->{armor}),
			showattack($_, 0),
			'<td class="val unit-sight">' . sprintf(
				$_->{detect} ? '<strong class="unit-detect">%s</strong>' : '%s',
				showrangeint($_->{sight}, $_->{upgraded}->{sight})
			),
			sprintf('<td class="val unit-speed"%2$s>%s',
				showrange(
					map { $_ && sprintf '%.1f', $_ }
					$_->{speed}, $_->{upgraded}->{speed}
				),
				defined $_->{creep} && sprintf(' title="%s on creep"',
					$_->{creep} == 1 ? 'same' : showrange(
						map { $_ && sprintf '%.1f', $_ }
						$_->{speed} * $_->{creep},
						$_->{upgraded}->{speed} && $_->{upgraded}->{speed} *
							($_->{upgraded}->{creep} // $_->{creep}),
					),
				),
			),
			$_->{attr}->{jump}
				&& qq'<span class="unit unit-jump" title="$_->{attr}->{jump}">↕</span>',
			'<td class="unit-magic">' . showmagic($_),
			(map {(
				'<tr class="sub"><th class="cat"><td><td colspan=10>',
				showattack($row, $_),
				'<td colspan=3>',
			)} 1 .. $#{ $_->{attack} }),
			"\n"
		);
	}

	my @rows = @{$units};
	my $grouped = 1;  # race headers
	if (exists $get{order}) {
		$grouped = 0;
		$get{order} ||= '';
		if ($get{order} eq 'name') {
			@rows = sort {$a->{name} cmp $b->{name}} @rows;
		}
		elsif ($get{order} eq 'cost') {
			$_->{order} = (
				$_->{gas}*1.5 + $_->{min} + $_->{pop}/8 + $_->{build}/256/8
			) for @rows;
		}
		elsif ($get{order} eq 'build') {
			my %unittime = map { ($_->{name} => $_->{warp} // $_->{build}) } @rows;
			$unittime{Templar} = $unittime{'High Templar'};
			$_->{order} = (
				($_->{warp} // $_->{build})
				+ ($_->{gas}*1.5 + $_->{min} + $_->{pop}/8)/1024
				+ ($_->{base} ? ($unittime{$_->{base}->[0]} // 100) + 1 : 0)
			) for @rows;
		}
		elsif ($get{order} eq 'size') {
			$_->{order} = (
				$_->{pop}*16 + ($_->{size} // $_->{suit}) + $_->{cargo}/8
				+ $_->{hp}/512 + $_->{min}/8192
			) for @rows;
		}
		elsif ($get{order} eq 'hp') {
			$_->{order} = (
				$_->{hp}*1.01 + $_->{armor} + $_->{shield} + $_->{size}/1024,
			) for @rows;
		}
		elsif ($get{order} eq 'attack') {
			$_->{order} = $_->{hp} / 16384 + max(
				map {
					($_->{dps} ? $_->{dps}->[-1] :
						($_->{damage} + $_->{upgrade} * 3)
						* ($_->{count} // 1) / ($_->{cooldown} // 1)
					)
					* ($_->{splash} ? 1.01 : 1)
					* ($_->{type} eq 'implosive' ? .96 : 1)
					* ($_->{type} eq 'explosive' ? .98 : 1)
				} @{ $_->{attack} }
			) for @rows;
		}
		elsif ($get{order} eq 'speed') {
			$_->{order} = (
				($_->{upgraded}->{speed} // $_->{speed}*1.01)
				+ $_->{sight}/1024 + $_->{detect}/2048
			) for @rows;
		}
		@rows = sort {$a->{order} <=> $b->{order}} @rows if exists $rows[0]->{order};
	}

	my ($race, $cat) = ('', '');
	for (@rows) {
		if ($grouped) {
			say sprintf '<tbody id="%s"><tr class="race"><th colspan="20"><h2>%s</h2>',
				$race = $_->{race}, ucfirst $race
					unless $race eq $_->{race};
		}
		else {
			$_->{cat} = $_->{race};
		}

		print(
			'<tr>',
			'<th class="cat">', $cat ne $_->{cat} && ($cat = $_->{cat}),
			'<td>', $_->{name},
			showunitcols($_),
		);

		for my $subrow (@{ $_->{special} }) {
			$subrow->{alt} or next;
			print(
				'<tr class="alt"><th class="cat"><td>', $subrow->{alt},
				showunitcols($subrow),
			);
		}
	}
:>
</table>

<div class="legend">
<h2>Legend</h2>

<dl>
<dt>cost
	<dd><span class="unit-min">minerals</span> and
		<span class="unit-gas">gas</span> required to create one unit
	<dd>includes total expenses if based on existing units
<dt>build
	<dd>relative time needed to create at least one unit
	<dd>excludes construction of dependencies such as buildings
		and <span class="unit-composed">+</span>parent units
<dt>size
	<dd><span class="unit unit-supply">T</span>ransports can fit upto
		8 non-<span class="unit unit-air">F</span>lying cargo units
	<dd>number of command points taken while alive
	<dd><:
if ($scver{major} > 1) {
		:>received damage depends on
		<span class="unit unit-o">o</span>rganic,
		<span class="unit unit-u">m</span>echanic,
		<span class="unit unit-p">ψ</span>(ps)ionic,
		<span class="unit unit-s">L</span>ight, and
		<span class="unit unit-l">A</span>rmored
		attributes
	<dd>massive <span class="unit-massive"></span> units
		cannot be lifted or slowed and can break force fields<:
} else {
		:>abilities may hit only <span class="unit unit-o">o</span>rganic
		or <span class="unit unit-u">m</span>echanic targets
	<dd>affected by <span class="unit unit-s">S</span>mall,
		<span class="unit unit-m">M</span>edium, or
		<span class="unit unit-l">L</span>arge damage<:
} :>
<dt>HP
	<dd>total number of hitpoints (including shields)
	<dd>everything zerg (except for eggs) regenerates one point every
		<:= $scver{major} == 1 ? '4½' : '3.7' :> seconds
<dt>shield
	<dd>percentage of HP in shields
	<dd><:
if ($scver{major} > 1) {
		:>shields always take full damage, irrelevant of unit size
	<dd><:
}
		:>does not take armor bonuses,
		but upgrades can decrease damage to any shield hit by upto 3
	<dd><:
if ($scver{major} > 1) {
		:>after 10 seconds out of combat, 2 points are recharged per game second<:
} else {
		:>recharges one point every 2½ seconds<:
} :>
<dt>armor
	<dd>base unit armor
	<dd>can be increased by upto 3 at various facilities
	<dd>each point decreases damage per hit by one, upto a minimum of ½
	<dd>reduction applies to initial damage, before size penalties
		<small>(so a plasma hit of 12 to 4 armor large deals 2 damage, not ½)</small>
<dt>attack
	<dd>damage per single hit
	<dd>some weapons fire multiple × times, multiplying armor penalties
	<dd>splash damage hits all objects nearby <span class="unit-splash"></span>
		or in a straight line <span class="unit-splash">+</span>.
	<dd><:
if ($scver{major} > 1) {
		:>does not include <span>&ge;</span>bonus damage
		dealt to susceptible unit types
	<dd><span class="unit-pdd"></span>projectile shots are negated by
		Point Defense Drones<:
} else {
		:><span class="unit-l">*</span>explosive damage does only
		50% damage to <span class="unit unit-s">S</span>mall units,
		75% to <span class="unit unit-m">M</span>edium,
		100% to <span class="unit unit-l">L</span>arge
	<dd><span class="unit-s">~</span>concussive/plasma damage does
		25% to <span class="unit unit-l">L</span>arge,
		50% <span class="unit unit-m">M</span>edium,
		100% to <span class="unit unit-s">S</span>mall units<:
} :>
	<dd><span class="hurtrel">dps</span> indicates relative total amount of damage
		done in 1 second of <:= $scver{major} > 1 ? '<em>Normal</em> in-game time' :
		'time on <em>Fast</em> game speed' :>
	<dd>targets <span class="hurt-g"></span>&nbsp;ground
		and/or  <span class="hurt-a"></span>&nbsp;air
<dt>range
	<dd>maximum hex distance a weapon can fire (note Sieged Tank also has a minimum)
<dt>sight
	<dd>range in which the unit detects other units
	<dd><strong class="unit-detect">emphasis</strong> indicates ability to detect cloaked units
<dt>speed
	<dd>top movement speed in hex per second
	<dd>acceleration and deceleration ignored
<dt>specials
	<dd>parentheses () indicate that it needs to be researched first
	<dd><span class="magic-perma">passive</span> abilities are always enabled
	<dd>hover for description
	<dd>range is maximum distance allowed to activate
	<dd>cost describes energy loss percentage on spawn and when fully charged
</dl>

<p>
When two values are given (1-2), the second value indicates the attribute
after all possible upgrades.
</p>

</div>