function area(const a: array of TV2): single
provides you the area of any convex point-field. Its determined
by splitting the field into a triangle fan and summing the discrete
triangle-areas.
Did it mainly to escape boredom; got the idea when I saw a document
by some bank calculating the value of a parcel with a computer (in a
hand-drawn polygon).
Code:
unit uGeo;
interface
type
TV2 = record
x, y: single;
end;
// cut out the function declarations here to reduce post size
implementation
function v2(const x, y: single): TV2;
begin
result.x := x;
result.y := y;
end;
function dist(const p1, p2: TV2): single;
begin
result := sqrt(sqr(p2.x-p1.x)+sqr(p2.y-p1.y));
end;
function area(const p1, p2, p3: TV2): single;
var
a, b, c, s: single;
begin
a := dist(p1, p2);
b := dist(p2, p3);
c := dist(p3, p1);
s := (a + b + c) / 2;
result := sqrt(s * (s-a) * (s-b) * (s-c));
end;
function center(const a: array of TV2): TV2;
var
i: dword;
begin
if length(a) = 0 then result := v2(0,0)
else
begin
result.x := a[0].x;
result.y := a[0].y;
for i := 1 to high(a) do
begin
result.x := result.x + a[i].x;
result.y := result.y + a[i].y;
end;
result.x := result.x / length(a);
result.y := result.y / length(a);
end;
end;
function area(const a: array of TV2): single;
var
m: TV2;
i: dword;
begin
if length(a) < 3 then
result := 0
else
if length(a) = 3 then
result := area(a[0], a[1], a[2])
else
begin
result := 0;
m := center(a);
for i := 0 to high(a)-1 do
result := result + area(a[i], a[i+1], m);
result := result + area(a[high(a)], a[0], m);
end;
end;
end.
Bookmarks