User:MichaelFrey/geom2D.scad

From Wikimedia Commons, the free media repository
Jump to navigation Jump to search
//created by Michael Frey
//released on Wikimedia commons under
//CC-BY-SA 3.0 license
//(c) Michael Frey

function add2D(v1,v2) = [v1[0]+v2[0], v1[1]+v2[1]];
function sub2D(v1,v2) = [v1[0]-v2[0], v1[1]-v2[1]];
function addAngle2D(v1,ang,l) = 
  [
    v1[0]+cos(ang)*l,
    v1[1]-sin(ang)*l,
  ];

function negativ(val) = (val==abs(val)) ? false: true;

function getAngle2D(v1,v2=[0,0]) =
  let(dx=v2[0]-v1[0])
  let(dy=v2[1]-v1[1])
  let(ang=atan((dx)/(dy)))
  (negativ(dy) ) ? ang-180 : ang;

function getAngle2Ds(v1,v2=[0,0]) =
  let(dx=v2[0]-v1[0])
  let(dy=v2[1]-v1[1])
  atan((dx)/(dy));

function getAngle2D2(v1,v2=[0,0]) =
  let(dx=v2[0]-v1[0])
  let(dy=v2[1]-v1[1])
  atan2((dx),(dy));

function scale2D(v1,c=1)= 
  [
    v1[0]*c,
    v1[1]*c,
  ];
  
 function midpoint2D(v1,v2)=
 [
    (v1[0]+v2[0])/2,
    (v1[1]+v2[1])/2
 ];
  
function scaleToLength2D(v1,v2,l)= 
  let(c=l/length2D(v1,v2))
  [
    (v2[0]-v1[0])*c+v1[0],
    (v2[1]-v1[1])*c+v1[1],
  ];

//Calculating the crossing point of two vectors,
//defined by two coordinates each
function crossPoint(v1,v2,v3,v4) =
[
  
	   ( (v4[0]-v3[0])*(v2[0]*v1[1]-v1[0]*v2[1]) - (v2[0]-v1[0])*(v4[0]*v3[1]-v3[0]*v4[1]) ) /
	   ( (v4[1]-v3[1])*(v2[0]-v1[0])       - (v2[1]-v1[1])*(v4[0]-v3[0]) )
  ,
   
	   ( (v1[1]-v2[1])*(v4[0]*v3[1]-v3[0]*v4[1]) - (v3[1]-v4[1])*(v2[0]*v1[1]-v1[0]*v2[1]) ) /
	   ( (v4[1]-v3[1])*(v2[0]-v1[0])       - (v2[1]-v1[1])*(v4[0]-v3[0]) )
  
];

function length2D(v1,v2=[0,0])=
  sqrt(
      (v1[0]-v2[0])*(v1[0]-v2[0])
      +
      (v1[1]-v2[1])*(v1[1]-v2[1])
    );

//Law of cosines
function VVLL2D(v1,v2,l1,l2) =
  let(sAB = length2D(v1,v2))
  let(ang12=getAngle2D(v2,v1))
  let(ang0=
        acos(
          (l2*l2-l1*l1-sAB*sAB)/
          (-abs(2*sAB*l1))
        ))
        
  addAngle2D(
    v1=v1,
    ang=ang0+ang12-90,
    l=-l1
  );