{ Apophysis AV "Phoenix Edition" Copyright (C) 2021 Alice V. Koryagina }

unit varEx;

interface
uses
  BaseVariation, XFormMan;

type
  TVariationEx = class(TBaseVariation)
  private
    old: byte;
	procedure CalcPlugin;
  public
    constructor Create;

    class function GetName: string; override;
    class function GetInstance: TBaseVariation; override;

    function GetNrVariables: integer; override;
    function GetVariableNameAt(const Index: integer): string; override;

    function SetVariable(const Name: string; var value: double): boolean; override;
    function GetVariable(const Name: string; var value: double): boolean; override;
    function ResetVariable(const Name: string): boolean; override;

    procedure CalcFunction; override;
	  procedure GetCalcFunction(var f: TCalcFunction); override;
  end;


implementation

uses
  Math;
////////////////////////
procedure TVariationEx.GetCalcFunction(var f: TCalcFunction);
begin
	if old = 1 then f := CalcFunction
	else f := CalcPlugin;
end;

procedure TVariationEx.CalcFunction;
var
  r: double;
  n0, n1, m0, m1: double;
  FAngle: double;
begin
  FAngle := arctan2(FTx^, FTy^);
  r := sqrt(sqr(FTx^) + sqr(FTy^));
  n0 := sin(FAngle + r);
  n1 := cos(FAngle - r);
  m0 := sqr(n0) * n0;
  m1 := sqr(n1) * n1;
  r := r * vvar;
  FPx^ := FPx^ + r * (m0 + m1);
  FPy^ := FPy^ + r * (m0 - m1);
end;

procedure TVariationEx.CalcPlugin;
var
  r: double;
  n0, n1, m0, m1: double;
  FAngle: double;
begin
  FAngle := arctan2(FTy^, FTx^);
  r := sqrt(sqr(FTx^) + sqr(FTy^));
  n0 := sin(FAngle + r);
  n1 := cos(FAngle - r);
  m0 := sqr(n0) * n0;
  m1 := sqr(n1) * n1;
  r := r * vvar;
  FPx^ := FPx^ + r * (m0 + m1);
  FPy^ := FPy^ + r * (m0 - m1);
end;

constructor TVariationEx.Create;
begin
  old := 1;
end;

class function TVariationEx.GetInstance: TBaseVariation;
begin
   Result := TVariationEx.Create;
end;

class function TVariationEx.GetName: string;
begin
   Result := 'ex';
end;

function TVariationEx.GetNrVariables: integer;
begin
   Result := 1;
end;

function TVariationEx.GetVariable(const Name: string;
  var value: double): boolean;
begin
  Result := False;
  if Name = 'ex_old' then begin
    value := old;
    Result := True;
  end;
end;

function TVariationEx.GetVariableNameAt(const Index: integer): string;
begin
  case Index of
    0: Result := 'ex_old';
  else
    Result := '';
  end;
end;

function TVariationEx.SetVariable(const Name: string;
  var value: double): boolean;
begin
  Result := False;
  if Name = 'ex_old' then begin
    if Value < 0 then Value := 0;
	if Value > 1 then Value := 1;
    old := Round(value);
    Result := True;
  end;
end;

function TVariationEx.ResetVariable(const Name: string): boolean;
begin
  Result := False;
  if Name = 'ex_old' then begin
    old := 1;
    Result := True;
  end;
end;

//////////////////////////////
initialization
  RegisterVariation(TVariationClassLoader.Create(TVariationEx), false, false);

end.
