swf2ass/src/BitmapDefinition.php

96 lines
3.3 KiB
PHP

<?php
namespace swf2ass;
class BitmapDefinition implements ObjectDefinition {
public int $id;
public Vector2 $size;
/** @var Color[][] */
public $pixels;
private DrawPathList $drawPathList;
public function __construct(int $id, Vector2 $size, array $pixels) {
$this->id = $id;
$this->size = $size;
$this->pixels = $pixels;
$converter = new BitmapConverter($this->pixels);
$this->drawPathList = $converter->render(true);
}
public function getObjectId(): int {
return $this->id;
}
public function getShapeList(): DrawPathList {
return $this->drawPathList;
}
static function fromXML(\DOMElement $element): BitmapDefinition {
//Utils::dump_element($element);
$size = new Vector2((int)$element->getAttribute("width"), (int)$element->getAttribute("height"));
$pixels = array_fill(0, $size->y, array_fill(0, $size->x, new Color(0, 0, 0)));
$format = (int)$element->getAttribute("format");
switch ($format) {
default:
throw new \Exception("Not supported format $format");
break;
//ALPHACOLORMAPDATA
case 3:
//TODO implement
//$content = zlib_decode(base64_decode(trim($element->textContent)));
$i = 0;
for ($y = 0; $y < $size->y; ++$y) {
for ($x = 0; $x < $size->x; ++$x) {
$pixel = unpack("Ca/Cr/Cg/Cb", "\x60\x00\x00\x00");
$pixels[$y][$x] = new Color($pixel["r"], $pixel["g"], $pixel["b"], $pixel["a"] !== 255 ? $pixel["a"] : null);
$i++;
}
}
var_dump("not implemented ALPHACOLORMAPDATA");
Utils::dump_element($element);
break;
//ALPHABITMAPDATA
case 5:
$content = zlib_decode(base64_decode(trim($element->textContent)));
$i = 0;
for ($y = 0; $y < $size->y; ++$y) {
for ($x = 0; $x < $size->x; ++$x) {
$pixel = unpack("Ca/Cr/Cg/Cb", substr($content, $i * 4, 4));
$pixels[$y][$x] = new Color($pixel["r"], $pixel["g"], $pixel["b"], $pixel["a"] !== 255 ? $pixel["a"] : null);
$i++;
}
}
break;
}
return new BitmapDefinition($element->getAttribute("objectID"), $size, $pixels);
}
public function getPixel(Vector2 $c) {
return $this->pixels[$c->y][$c->x];
}
public function toPNG() {
$im = new \Imagick();
$im->newImage($this->size->x, $this->size->y, new \ImagickPixel("#000000ff"));
$im->setImageFormat("png");
$iterator = $im->getPixelIterator();
foreach ($iterator as $row => $pixels) {
foreach ($pixels as $col => $pixel) {
$c = $this->getPixel(new Vector2($col, $row));
$colorStr = "#" . bin2hex(chr($c->r)) . bin2hex(chr($c->g)) . bin2hex(chr($c->b)) . bin2hex(chr(255 - ($c->a ?? 0)));
$pixel->setColor($colorStr);
}
$iterator->syncIterator();
}
return (string)$im;
}
}