unit BodaMaths;

interface
 type
  Vector3f = record
              x, y, z: Extended;
             end;
 function SubstractVectors(VectorA, VectorB: Vector3f): Vector3f;
 function CalcCrossProduct(VectorA, VectorB: Vector3f): Vector3f;
 function Normalize(Vector: Vector3f): Vector3f;
 function CalcNormalOfTriangle(Vertex1, Vertex2, Vertex3: Vector3f): Vector3f;

implementation

uses Dialogs,
     SysUtils;

function CalcNormalOfTriangle(Vertex1, Vertex2, Vertex3: Vector3f): Vector3f;
 var VectorA, VectorB, tmp: Vector3f;
begin
 VectorA:= SubstractVectors(Vertex1, Vertex2);
 VectorB:= SubstractVectors(Vertex2, Vertex3);
 tmp:= CalcCrossProduct(VectorA, VectorB);
 tmp:= Normalize(tmp);
 Result:= tmp;
end;

function CalcCrossProduct(VectorA, VectorB: Vector3f): Vector3f;
begin
 Result.x:= VectorA.y*VectorB.z - VectorA.z*VectorB.y;
 Result.y:= VectorA.z*VectorB.x - VectorA.x*VectorB.z;
 Result.z:= VectorA.x*VectorB.y - VectorA.y*VectorB.x;
end;

function Normalize(Vector: Vector3f): Vector3f;
 var
  Length: Extended;
begin
 Length:= sqrt(Vector.x*Vector.x + Vector.y*Vector.y + Vector.z*Vector.z);
 Result.x:= Vector.x/Length;
 Result.y:= Vector.y/Length;
 Result.z:= Vector.z/Length;
end;

function SubstractVectors(VectorA, VectorB: Vector3f): Vector3f;
begin
 Result.x:= VectorA.x-VectorB.x;
 Result.y:= VectorA.y-VectorB.y;
 Result.z:= VectorA.z-VectorB.z;
end;

end.
