swf2ass/src/LineRecord.php

74 lines
2.1 KiB
PHP

<?php
namespace swf2ass;
class LineRecord implements Record {
public Vector2 $start;
public Vector2 $to;
public function __construct(Vector2 $to, Vector2 $start) {
$this->to = $to;
$this->start = $start;
}
public function getStart(): Vector2 {
return $this->start;
}
public function getEnd(): Vector2 {
return $this->to;
}
public function reverse(): LineRecord {
return new LineRecord($this->start, $this->to);
}
private function delta() : Vector2 {
return $this->to->sub($this->start);
}
private static function Fake2DCross(Vector2 $a, Vector2 $b){
return $a->x * $b->y - $a->y * $b->x;
}
/**
* @param LineRecord $other
* @return Vector2|LineRecord|null
*/
public function intersect(LineRecord $other) : ?object {
$p = $this->start;
$q = $other->start;
$r = $this->delta();
$s = $other->delta();
$denom = self::Fake2DCross($r, $s);
if(abs($denom) < Constants::EPSILON){
//parallel
return new LineRecord($this->to->add($this->to->sub($other->to)), $p->add($p->sub($q)));
}
$tNumer = self::Fake2DCross($q->sub($p), $s);
$uNumer = self::Fake2DCross($q->sub($p), $r);
$t = $tNumer / $denom;
$u = $uNumer / $denom;
if($t < 0 or $t > 1 or $u < 0 or $u > 1){
//No intersection
return null;
}
return $p->add($r->multiply($t));
}
public static function fromArray(array $element, Vector2 $cursor): LineRecord {
return new LineRecord($cursor->add(new Vector2($element["deltaX"] ?? 0, $element["deltaY"] ?? 0)), $cursor);
}
public function applyMatrixTransform(MatrixTransform $transform, bool $applyTranslation = true): LineRecord {
return new LineRecord($transform->applyToVector($this->to, $applyTranslation), $transform->applyToVector($this->start, $applyTranslation));
}
public function equals(Record $other): bool {
return $other instanceof $this and $this->start->equals($other->start) and $this->to->equals($other->to);
}
}