unit g_Utils;

interface
uses
  SysUtils,
  {$INCLUDE uses.inc};

function GetAngle(Pos, dPos : izPosition_f) : float;
function Distance_2D(Pos1, Pos2 : izPosition_f) : float;
function Distance_fast2DQuad(pos,pos2 : izPosition_i) : int;
function Distance_fast2Di(pos,pos2 : izPosition_i) : int;
function Distance_fast2Df(pos,pos2 : izPosition_f) : float;

procedure DelDir(cDir : string);
implementation

function GetAngle(Pos, dPos : izPosition_f) : float;
begin
  if (Pos[0] = dPos[0]) and (Pos[1] = dPos[1]) then
  begin
    Result := -1;
    exit;
  end;
  Result := ArcTan((dPos[1]-Pos[1])/(dPos[0]-Pos[0]))*180/3.14;
  if (dPos[0] >= Pos[0]) then
    Result := -(Result-90)+180
  else
    Result := 180-Result-90;
end;

function Distance_2D(Pos1, Pos2 : izPosition_f) : float;
begin
  Result := sqrt((Pos2[0]-Pos1[0])*(Pos2[0]-Pos1[0])+(Pos2[1]-Pos1[1])*(Pos2[1]-Pos1[1]));
end;

function Distance_fast2Di(pos,pos2 : izPosition_i) : int;
var
  dx,dy : int;
begin
  dx := pos[0]-pos2[0];
  dy := pos[1]-pos2[1];

  if ( dx < 0 ) then dx := -dx;
  if ( dy < 0 ) then dy := -dy;
  if ( dx < dy ) then result := (123*dy+51*dx) div 128
  else result := (123*dx+51*dy) div 128;
end;

function Distance_fast2Df(pos,pos2 : izPosition_f) : float;
var
  dx,dy : float;
begin
  dx := pos[0]-pos2[0];
  dy := pos[1]-pos2[1];
  if ( dx < 0 ) then dx := -dx;
  if ( dy < 0 ) then dy := -dy;
  if ( dx < dy ) then result := 0.961*dy+0.398*dx
  else result := 0.961*dx+0.398*dy;
end;

function Distance_fast2DQuad(pos,pos2 : izPosition_i) : int;
var
  dx,dy : int;
begin
  dx := pos[0]-pos2[0];
  dy := pos[1]-pos2[1];

  if ( dx < 0 ) then dx := -dx;
  if ( dy < 0 ) then dy := -dy;
  if ( dx < dy ) then result := dy
   else result := dx;
end;

procedure DelDir(cDir : string);
var
 h : THandle;
 fd : _WIN32_FIND_DATAA;
 fn, s : string;
begin
 h := FindFirstFile(PChar(cDir + '\*'), fd);
 if h = INVALID_HANDLE_VALUE then
   RaiseLastOSError;
 repeat
   fn := fd.cFileName;
   s := cDir + '\' + fn;
   if (fd.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) = 0 then
     begin
       if not Windows.DeleteFile(PChar(s)) then
         RaiseLastOSError;
     end
   else if (string(fn) <> '.') and (string(fn) <> '..') then
     DelDir(s);
 until not FindNextFile(h, fd);
 Windows.FindClose(h);
 if not RemoveDirectory(PChar(cDir)) then
   RaiseLastOSError;
end;

end.
