Search code examples
phprotationgeometryprojectionrotational-matrices

3D projection to screen PHP


I am trying to get 3d object position on screen.

I have studied this wiki atricle https://en.wikipedia.org/wiki/3D_projection (and many others) but it seems like I am getting incorrect answers.

$center =array(0,0,0);
$point = array(0, 30, 30);
$rot = array(90,0,0);
$A=array(
    array(             1,             0,             0),
    array(             0,  cos($rot[0]),  sin($rot[0])),
    array(             0, -sin($rot[0]),  cos($rot[0]))
);
$B=array(
    array(  cos($rot[1]),             0, -sin($rot[1])),
    array(             0,             1,             0),
    array(  sin($rot[1]),             0,  cos($rot[1]))
);
$C=array(
    array(  cos($rot[2]),  sin($rot[2]),             0),
    array( -sin($rot[2]),  cos($rot[2]),             0),
    array(             0,             0,             1)
);
$a=array(
    array($point[0]),
    array($point[1]),
    array($point[2])
);
$help = matrixmult(matrixmult($A,$B),$C);
$c = matrixmult($help, $a);
var_dump($c);

function matrixmult($m1,$m2){
    $r=count($m1);
    $c=count($m2[0]);
    $p=count($m2);
    if(count($m1[0])!=$p){throw new Exception('Incompatible matrixes');}
    $m3=array();
    for ($i=0;$i< $r;$i++){
        for($j=0;$j<$c;$j++){
            $m3[$i][$j]=0;
            for($k=0;$k<$p;$k++){
                $m3[$i][$j]+=$m1[$i][$k]*$m2[$k][$j];
            }
        }
    }
    return($m3);
}

matrixmulti function I got online and tested it to get correct answer when multipling matrices (answers were correct) and I am getting :

array(3) {
  [0]=>
  array(1) {
    [0]=>
    float(0)
  }
  [1]=>
  array(1) {
    [0]=>
    float(13.377691424142)
  }
  [2]=>
  array(1) {
    [0]=>
    float(-40.262108391892)
  }
}

but this seems to be incorrect answer, since point is on y,z plane and rotating x by 90 degrees should give me answer (0,30,-30) or (0,-30,30) depending on sign. Am I wrong somewhere or is something missing?


Solution

  • PHP trigonometric functions take angles in radians not degrees, this is also the case in a majority of languages.

    $rot = array(90,0,0);
    

    should be:

    $rot = array(M_PI/2,0,0);