text stringlengths 14 6.51M |
|---|
unit nxPopupNotice;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, StdCtrls;
type
//弹出通知窗口控件
{ TnxPopupNotice }
TnxPopupNotice = class(TComponent)
private
FFormHeight: integer;
FFormWidth: integer;
FList:TList;
public
constructor Create(AOwner:TComponent);override;
destructor Destroy;override;
procedure CreateForm(ATtile,AMessage:string);
published
property FormWidth:integer read FFormWidth write FFormWidth;
property FormHeight:integer read FFormHeight write FFormHeight;
end;
procedure Register;
implementation
procedure Register;
begin
//RegisterComponents('Additional',[TnxPopupNotice]);
end;
{ TnxPopupNotice }
procedure TnxPopupNotice.CreateForm(ATtile,AMessage:string);
var
mForm:TForm;
mTitle:TLabel;
begin
//创建窗体
mForm:=TForm.Create(nil);
mForm.Width:=FFormWidth;
mForm.Height:=FFormHeight;
mForm.BorderStyle:=bsNone;
//创建标题对象
mTitle:=TLabel.Create(mForm);
mTitle.Parent:=mForm;
mTitle.Top:=20;
mTitle.Left:=20;
//创建消息对象
end;
constructor TnxPopupNotice.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FList:=TList.Create;
FFormWidth:=400;
FFormHeight:=300;
end;
destructor TnxPopupNotice.Destroy;
begin
FList.Clear;
FList.Free;
inherited Destroy;
end;
end.
|
unit fOrdersHold;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
fAutoSz, StdCtrls, ORFn, ORCtrls, VA508AccessibilityManager;
type
TfrmHoldOrders = class(TfrmAutoSz)
lstOrders: TCaptionListBox;
Label1: TLabel;
cmdOK: TButton;
cmdCancel: TButton;
procedure FormCreate(Sender: TObject);
procedure cmdOKClick(Sender: TObject);
procedure cmdCancelClick(Sender: TObject);
private
OKPressed: Boolean;
end;
function ExecuteHoldOrders(SelectedList: TList): Boolean;
implementation
{$R *.DFM}
uses rOrders, uConst, uCore;
function ExecuteHoldOrders(SelectedList: TList): Boolean;
var
frmHoldOrders: TfrmHoldOrders;
OriginalID: string;
i: Integer;
begin
Result := False;
if SelectedList.Count = 0 then Exit;
frmHoldOrders := TfrmHoldOrders.Create(Application);
try
ResizeFormToFont(TForm(frmHoldOrders));
with SelectedList do for i := 0 to Count - 1 do
frmHoldOrders.lstOrders.Items.Add(TOrder(Items[i]).Text);
frmHoldOrders.ShowModal;
if frmHoldOrders.OKPressed then
begin
with SelectedList do for i := 0 to Count - 1 do
begin
OriginalID := TOrder(Items[i]).ID;
HoldOrder(TOrder(Items[i]));
TOrder(Items[i]).ActionOn := OriginalID + '=HD';
SendMessage(Application.MainForm.Handle, UM_NEWORDER, ORDER_ACT, Integer(Items[i]));
end;
Result := True;
end
else with SelectedList do for i := 0 to Count - 1 do UnlockOrder(TOrder(Items[i]).ID);
finally
frmHoldOrders.Release;
end;
end;
procedure TfrmHoldOrders.FormCreate(Sender: TObject);
begin
inherited;
OKPressed := False;
end;
procedure TfrmHoldOrders.cmdOKClick(Sender: TObject);
begin
inherited;
OKPressed := True;
Close;
end;
procedure TfrmHoldOrders.cmdCancelClick(Sender: TObject);
begin
inherited;
Close;
end;
end.
|
{ ***************************************************************************
Copyright (c) 2016-2020 Kike Pérez
Unit : Quick.DAO.Engine.FireDAC
Description : DAODatabase FireDAC Provider
Author : Kike Pérez
Version : 1.1
Created : 31/08/2018
Modified : 14/04/2020
This file is part of QuickDAO: https://github.com/exilon/QuickDAO
***************************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.DAO.Engine.FireDAC;
{$i QuickDAO.inc}
interface
uses
Classes,
System.SysUtils,
//Winapi.ActiveX,
FireDAC.Comp.Client,
FireDAC.Stan.Def,
FireDAC.Stan.Intf,
FireDAC.Stan.Pool,
FireDAC.Stan.Async,
FireDAC.DApt,
FireDAC.Phys,
FireDAC.Phys.Intf,
FireDAC.Phys.SQLite,
{$IFDEF FPC}
only Delphi/Firemonkey compatible
{$ENDIF}
{$IFDEF MSWINDOWS}
FireDAC.Phys.MSAcc,
{$ENDIF}
//FireDAC.Phys.MSSQL,
{$IFDEF CONSOLE}
FireDAC.ConsoleUI.Wait,
{$ELSE}
FireDAC.UI.Intf,
{$IFDEF VCL}
FireDAC.VCLUI.Wait,
{$ELSE}
FireDAC.FMXUI.Wait,
{$ENDIF}
FireDAC.Comp.UI,
{$ENDIF}
Quick.Commons,
Quick.DAO,
Quick.DAO.Database,
Quick.DAO.Query;
type
TDAODataBaseFireDAC = class(TDAODatabase)
private
fFireDACConnection : TFDConnection;
fInternalQuery : TFDQuery;
function GetDriverID(aDBProvider : TDBProvider) : string;
protected
function CreateConnectionString: string; override;
procedure ExecuteSQLQuery(const aQueryText : string); override;
procedure OpenSQLQuery(const aQueryText: string); override;
function ExistsTable(aModel : TDAOModel) : Boolean; override;
function ExistsColumn(aModel: TDAOModel; const aFieldName: string): Boolean; override;
public
constructor Create; override;
constructor CreateFromConnection(aConnection: TFDConnection; aOwnsConnection : Boolean);
destructor Destroy; override;
function CreateQuery(aModel : TDAOModel) : IDAOQuery<TDAORecord>; override;
function Connect : Boolean; override;
procedure Disconnect; override;
function GetTableNames : TArray<string>; override;
function GetFieldNames(const aTableName : string) : TArray<string>; override;
function IsConnected : Boolean; override;
function From<T : class, constructor> : IDAOLinqQuery<T>;
function Clone : TDAODatabase; override;
end;
TDAOQueryFireDAC<T : class, constructor> = class(TDAOQuery<T>)
private
fConnection : TDBConnectionSettings;
fQuery : TFDQuery;
protected
function GetCurrent : T; override;
function MoveNext : Boolean; override;
function GetFieldValue(const aName : string) : Variant; override;
function OpenQuery(const aQuery : string) : Integer; override;
function ExecuteQuery(const aQuery : string) : Boolean; override;
public
constructor Create(aDAODataBase : TDAODataBase; aModel : TDAOModel; aQueryGenerator : IDAOQueryGenerator); override;
destructor Destroy; override;
function CountResults : Integer; override;
function Eof : Boolean; override;
end;
{$IFNDEF CONSOLE}
var
FDGUIxWaitCursor : TFDGUIxWaitCursor;
{$ENDIF}
implementation
{ TDAODataBaseADO }
constructor TDAODataBaseFireDAC.Create;
begin
inherited;
fFireDACConnection := TFDConnection.Create(nil);
fInternalQuery := TFDQuery.Create(nil);
end;
constructor TDAODataBaseFireDAC.CreateFromConnection(aConnection: TFDConnection; aOwnsConnection : Boolean);
begin
Create;
if OwnsConnection then fFireDACConnection.Free;
OwnsConnection := aOwnsConnection;
fFireDACConnection := aConnection;
end;
destructor TDAODataBaseFireDAC.Destroy;
begin
if Assigned(fInternalQuery) then fInternalQuery.Free;
if fFireDACConnection.Connected then fFireDACConnection.Connected := False;
if OwnsConnection then fFireDACConnection.Free;
inherited;
end;
function TDAODataBaseFireDAC.Clone: TDAODatabase;
begin
Result := TDAODataBaseFireDAC.CreateFromConnection(fFireDACConnection,False);
Result.Connection.Free;
Result.Connection := Connection.Clone;
end;
function TDAODataBaseFireDAC.Connect: Boolean;
begin
//creates connection string based on parameters of connection property
inherited;
fFireDACConnection.ConnectionString := CreateConnectionString;
fFireDACConnection.Connected := True;
fInternalQuery.Connection := fFireDACConnection;
Result := IsConnected;
CreateTables;
CreateIndexes;
end;
function TDAODataBaseFireDAC.CreateConnectionString: string;
begin
if Connection.IsCustomConnectionString then Result := Format('DriverID=%s;%s',[GetDriverID(Connection.Provider),Connection.GetCustomConnectionString])
else
begin
Result := Format('DriverID=%s;User_Name=%s;Password=%s;Database=%s;Server=%s',[
GetDriverID(Connection.Provider),
Connection.UserName,
Connection.Password,
Connection.Database,
Connection.Server]);
end;
end;
function TDAODataBaseFireDAC.CreateQuery(aModel: TDAOModel): IDAOQuery<TDAORecord>;
begin
Result := TDAOQueryFireDAC<TDAORecord>.Create(Self,aModel,QueryGenerator);
end;
procedure TDAODataBaseFireDAC.Disconnect;
begin
inherited;
fFireDACConnection.Connected := False;
end;
procedure TDAODataBaseFireDAC.ExecuteSQLQuery(const aQueryText: string);
begin
fInternalQuery.SQL.Text := aQueryText;
fInternalQuery.ExecSQL;
end;
procedure TDAODataBaseFireDAC.OpenSQLQuery(const aQueryText: string);
begin
fInternalQuery.SQL.Text := aQueryText;
fInternalQuery.Open;
end;
function TDAODataBaseFireDAC.ExistsColumn(aModel: TDAOModel; const aFieldName: string): Boolean;
begin
Result := False;
OpenSQLQuery(QueryGenerator.ExistsColumn(aModel,aFieldName));
while not fInternalQuery.Eof do
begin
if CompareText(fInternalQuery.FieldByName('name').AsString,aFieldName) = 0 then
begin
Result := True;
Break;
end;
fInternalQuery.Next;
end;
fInternalQuery.SQL.Clear;
end;
function TDAODataBaseFireDAC.ExistsTable(aModel: TDAOModel): Boolean;
begin
Result := False;
OpenSQLQuery(QueryGenerator.ExistsTable(aModel));
while not fInternalQuery.Eof do
begin
if CompareText(fInternalQuery.FieldByName('name').AsString,aModel.TableName) = 0 then
begin
Result := True;
Break;
end;
fInternalQuery.Next;
end;
fInternalQuery.SQL.Clear;
end;
function TDAODataBaseFireDAC.From<T>: IDAOLinqQuery<T>;
var
daoclass : TDAORecordclass;
begin
daoclass := TDAORecordClass(Pointer(T));
Result := TDAOQueryFireDAC<T>.Create(Self,Models.Get(daoclass),QueryGenerator);
end;
function TDAODataBaseFireDAC.GetDriverID(aDBProvider: TDBProvider): string;
begin
case aDBProvider of
TDBProvider.daoMSAccess2007 : Result := 'MSAcc';
TDBProvider.daoMSSQL : Result := 'MSSQL';
TDBProvider.daoMySQL : Result := 'MySQL';
TDBProvider.daoSQLite : Result := 'SQLite';
else raise Exception.Create('Unknow DBProvider or not supported by this engine');
end;
end;
function TDAODataBaseFireDAC.GetFieldNames(const aTableName: string): TArray<string>;
var
sl : TStrings;
begin
sl := TStringList.Create;
try
fInternalQuery.Connection.GetFieldNames('','',aTableName,'',sl);
Result := StringsToArray(sl);
finally
sl.Free;
end;
end;
function TDAODataBaseFireDAC.GetTableNames: TArray<string>;
var
sl : TStrings;
begin
sl := TStringList.Create;
try
fInternalQuery.Connection.GetTableNames(Connection.Database,'dbo','',sl,[osMy],[tkTable],True);
Result := StringsToArray(sl);
finally
sl.Free;
end;
end;
function TDAODataBaseFireDAC.IsConnected: Boolean;
begin
Result := fFireDACConnection.Connected;
end;
{ TDAOQueryFireDAC<T> }
function TDAOQueryFireDAC<T>.CountResults: Integer;
begin
Result := fQuery.RecordCount;
end;
constructor TDAOQueryFireDAC<T>.Create(aDAODataBase : TDAODataBase; aModel : TDAOModel; aQueryGenerator : IDAOQueryGenerator);
begin
inherited;
fQuery := TFDQuery.Create(nil);
fQuery.Connection := TDAODataBaseFireDAC(aDAODataBase).fFireDACConnection;
fConnection := aDAODataBase.Connection;
end;
destructor TDAOQueryFireDAC<T>.Destroy;
begin
if Assigned(fQuery) then fQuery.Free;
inherited;
end;
function TDAOQueryFireDAC<T>.Eof: Boolean;
begin
Result := fQuery.Eof;
end;
function TDAOQueryFireDAC<T>.OpenQuery(const aQuery : string) : Integer;
begin
fFirstIteration := True;
fQuery.Close;
fQuery.SQL.Text := aQuery;
fQuery.Open;
fHasResults := fQuery.RecordCount > 0;
Result := fQuery.RecordCount;
end;
function TDAOQueryFireDAC<T>.ExecuteQuery(const aQuery : string) : Boolean;
begin
fQuery.SQL.Text := aQuery;
fQuery.ExecSQL;
fHasResults := False;
Result := fQuery.RowsAffected > 0;
end;
function TDAOQueryFireDAC<T>.GetFieldValue(const aName: string): Variant;
begin
Result := fQuery.FieldByName(aName).AsVariant;
end;
function TDAOQueryFireDAC<T>.GetCurrent: T;
begin
if fQuery.Eof then Exit(nil);
Result := fModel.Table.Create as T;
Self.FillRecordFromDB(Result);
end;
function TDAOQueryFireDAC<T>.MoveNext: Boolean;
begin
if not fFirstIteration then fQuery.Next;
fFirstIteration := False;
Result := not fQuery.Eof;
end;
initialization
//if (IsConsole) or (IsService) then CoInitialize(nil);
{$IFNDEF CONSOLE}
FDGUIxWaitCursor := TFDGUIxWaitCursor.Create(nil);
{$ENDIF}
finalization
//if (IsConsole) or (IsService) then CoUninitialize;
{$IFNDEF CONSOLE}
FDGUIxWaitCursor.Free;
{$ENDIF}
end.
|
unit uBarChart;
interface
uses
FMX.Objects, System.Generics.Collections,
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics,
FMX.Layouts, FMX.Controls.Presentation, FMX.StdCtrls,
FMX.PlatForm,FMX.Effects,
FMX.Dialogs;
type
TTipo = (vertical,horizontal);
type
TSerie = class
Valor,
Cor :Integer;
Hint :String;
end;
type
TGrafico = class
private
FValores: TDictionary<String, TSerie>;
FMax: Integer;
FTipo: TTipo;
FTitulo: String;
FCor: TAlphaColor;
FCorFundo: TAlphaColor;
procedure SetValores(const Value: TDictionary<String, TSerie>);
procedure SetMax(const Value: Integer);
procedure SetTipo(const Value: TTipo);
procedure SetTitulo(const Value: String);
procedure SetCor(const Value: TAlphaColor);
procedure SetCorFundo(const Value: TAlphaColor);
procedure Serie(Comp :TVertScrollBox; Por1 :Integer;
Texto :String); overload;
procedure Serie(Comp :THorzScrollBox); overload;
protected
property Valores : TDictionary<String,TSerie> read FValores write SetValores;
property Tipo :TTipo read FTipo write SetTipo;
public
property Max :Integer read FMax write SetMax;
property Titulo :String read FTitulo write SetTitulo;
property Cor :TAlphaColor read FCor write SetCor;
property CorFundo :TAlphaColor read FCorFundo write SetCorFundo;
constructor Create(Comp : TRectangle;Tipo :TTipo);
destructor Destroy; override;
procedure AddSerie(int1 : Integer ;Hint :string);
procedure CardMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
procedure CardDragOver(Sender: TObject; const Data: TDragObject;
const Point: TPointF; var Operation: TDragOperation);
procedure CardDragDrop(Sender: TObject; const Data: TDragObject;
const Point: TPointF);
// procedure AddSerie()
end;
implementation
var
Serie :TSerie;
i :Integer;
Vert : TVertScrollBox;
horz : THorzScrollBox;
rFundo,
rBar : TRectangle;
sTitulo : TText;
Sombra: TShadowEffect;
topo : TLayout;
{ TGrafico }
procedure TGrafico.AddSerie(int1 : Integer ;Hint :string);
begin
if Tipo = vertical then begin
Serie(Vert,int1,Hint);
end else begin
rFundo := TRectangle.Create(Horz);
rFUndo.Parent := Horz;
rFundo.Align := TAlignLayout.Left;
rFundo.Margins.Left := 5;
rFundo.Margins.Top := 10;
rFundo.Margins.Right := 5;
rFundo.Height := Horz.Height;
rFundo.Width := Horz.Width / Max -20 ;
rFundo.Position.X := 0;
rFundo.Position.Y := 170;
//rFundo.Size.Width := 15 ;
rFundo.Size.PlatformDefault := False;
rFundo.Stroke.Kind := TBrushKind.None;
rBar := TRectangle.Create(rFundo);
rBar.Align := TAlignLayout.Bottom;
rBar.Fill.Color := TAlphaColors.Cornflowerblue;
rBar.Name := 'Ret_'+Inttostr(i);
rBar.Size.Height := 0;
rBar.Size.PlatformDefault := False;
rBar.Parent := rFundo;
rBar.Stroke.Kind := TBrushKind.None;
rBar.AnimateFloat('Height',(rFundo.Height / 100) * int1,1, TAnimationType.In,TInterpolationType.Cubic);
end;
inc(i)
end;
procedure TGrafico.CardDragDrop(Sender: TObject; const Data: TDragObject;
const Point: TPointF);
begin
if Sender is TVertScrollBox then begin
TControl(Data.Source).Position.Y:= Point.Y;
TControl(Sender).AddObject(TControl(Data.Source));
end;
end;
procedure TGrafico.CardDragOver(Sender: TObject; const Data: TDragObject;
const Point: TPointF; var Operation: TDragOperation);
begin
Operation := TDragOperation.Copy;
end;
procedure TGrafico.CardMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
var Svc: IFMXDragDropService;
DragData: TDragObject;
DragImage: TBitmap;
begin
if TPlatformServices.Current.SupportsPlatformService(IFMXDragDropService, Svc) then begin
DragImage := TControl(Sender).MakeScreenshot;
DragData.Source := Sender;
DragData.Data := DragImage;
try
Svc.BeginDragDrop(Application.MainForm, DragData, DragImage);
finally
DragImage.Free;
end;
end;
end;
constructor TGrafico.Create(Comp : TRectangle;Tipo :TTipo);
var Line1: TLine;
begin
for I := Comp.ComponentCount - 1 downto 0 do
Comp.Components[I].Free;
Cor := TAlphaColors.Cornflowerblue;
CorFundo := Comp.Fill.Color;
Max := 0;
// Titulo := 'Gráfico Delphi Creative';
Sombra := TShadowEffect.Create(Comp);
Sombra.Distance := 3;
Sombra.Direction := 45;
Sombra.Softness := 0.3;
Sombra.Opacity := 0.6;
Sombra.ShadowColor := TAlphaColors.Black;
Sombra.Parent := Comp;
topo := TLayout.Create(Comp);
topo.Align := TAlignLayout.Top;
topo.Size.Height := 33;
topo.Size.PlatformDefault := False;
topo.Parent := Comp;
i := 0;
Self.Tipo := Tipo;
if Tipo = vertical then begin
Vert := TVertScrollBox.Create(topo);
Vert.Parent := Comp;
Vert.Align := TAlignLayout.Client;
vert.Height := Comp.Height - 60 ;
vert.Width := Comp.Width ;
Vert.Margins.Top := 5;
Vert.Margins.Left := 15;
Vert.Margins.Right := 15;
Vert.Margins.Bottom := 5;
Vert.OnDragOver := CardDragOver;
Vert.OnDragDrop := CardDragDrop;
end else begin
Line1 := TLine.Create(Comp);
Line1.LineType := TLineType.Top;
Line1.Position.X := 368;
Line1.Position.Y := 352;
Line1.Size.Width := 146;
Line1.Size.Height := 30;
Line1.Size.PlatformDefault := False;
Line1.Align := TAlignLayout.Bottom;
Line1.Parent := Comp;
horz := THorzScrollBox.Create(topo);
horz.Parent := Comp;
horz.Align := TAlignLayout.Client;
horz.Margins.Top := 5;
horz.Margins.Left := 5;
horz.Margins.Right := 5;
horz.Margins.Bottom := 0;
end;
end;
destructor TGrafico.Destroy;
begin
inherited;
Valores.Free;
end;
procedure TGrafico.Serie(Comp: TVertScrollBox; Por1 :Integer;
Texto :String);
begin
rFundo := TRectangle.Create(Comp);
rFundo.Parent := Comp;
rFundo.Align := TAlignLayout.Top;
rFundo.Fill.Color := CorFundo ;
rFundo.Margins.Top := 2;
rFundo.Width := Comp.Width;
rFundo.Position.X := 5;
rFundo.Position.Y := 170;
rFundo.Height := Comp.Height / Max -5 ;
rFundo.Size.PlatformDefault := False;
rFundo.Stroke.Kind := TBrushKind.None;
rFundo.OnDragOver := CardDragOver;
rFundo.OnDragDrop := CardDragDrop;
rFundo.OnMouseDown := CardMouseDown;
rBar := TRectangle.Create(rFundo);
rBar.Align := TAlignLayout.Left;
//rBar.Fill.Kind := TBrushKind.Gradient ;
rBar.Fill.Color := Cor ;
rBar.HitTest := False;
rBar.Size.Width := 0;//(rFundo.Width / 100) * int1;
rBar.Size.PlatformDefault := False;
rBar.Parent := rFundo;
rBar.Stroke.Kind := TBrushKind.None;
{Sombra := TShadowEffect.Create(rBar);
Sombra.Distance := 3;
Sombra.Direction := 45;
Sombra.Softness := 0.3;
Sombra.Opacity := 0.6;
Sombra.ShadowColor := Cor;
Sombra.Parent := rBar;}
sTitulo := TText.Create(rFundo);
sTitulo.Parent := rFundo;
sTitulo.Align := TAlignLayout.Contents;
sTitulo.Position.X := 0;
sTitulo.Position.Y := 0;
sTitulo.TextSettings.HorzAlign := TTextAlign.Leading;
sTitulo.Width := rFundo.Width;
sTitulo.HitTest := False;
sTitulo.Text := Texto;
rBar.AnimateFloat('Width',(rFundo.Width / 100) * Por1,1, TAnimationType.In,TInterpolationType.Cubic);
end;
procedure TGrafico.Serie(Comp: THorzScrollBox);
begin
end;
procedure TGrafico.SetCor(const Value: TAlphaColor);
begin
FCor := Value;
end;
procedure TGrafico.SetCorFundo(const Value: TAlphaColor);
begin
FCorFundo := Value;
end;
procedure TGrafico.SetMax(const Value: Integer);
begin
FMax := Value;
end;
procedure TGrafico.SetTipo(const Value: TTipo);
begin
FTipo := Value;
end;
procedure TGrafico.SetTitulo(const Value: String);
begin
FTitulo := Value;
sTitulo := TText.Create(Topo);
sTitulo.Align := TAlignLayout.Client;
sTitulo.Parent := Topo;
sTitulo.Text := Titulo;
end;
procedure TGrafico.SetValores(const Value: TDictionary<String, TSerie>);
begin
FValores := Value;
end;
end.
|
unit variant_array_2;
interface
implementation
var
I: int32;
S: string;
F: float64;
procedure P(const A: array of variant);
begin
I := A[0];
S := A[1];
F := A[2];
end;
procedure Test;
begin
P([11, 'abcdef', 4.6]);
end;
initialization
Test();
finalization
Assert(I = 11);
Assert(S = 'abcdef');
Assert(F = 4.6);
end. |
unit unJData;
interface
uses
System.Classes, System.SysUtils;
const
Delim : string = ':-:-:';
type
TJDataRec = record
name, val: string;
end;
TJData = array of TJDataRec;
function JDR(jname, jval: string): string;
function JValByName(jname: string; j_data:TJData): string;
procedure WriteJDFile(dest, fname: string; re_write: boolean = False);
procedure ReadJDFile(fname: string; var j_data: TJData);
implementation
function JDR(jname, jval: string): string;
begin
Result := '{'+jname+Delim+jval+'}';
end;
procedure DecodeJD(dest: string; var j_data: TJData);
var
pos1, pos2: integer;
str1: string;
jdr: TJDataRec;
begin
SetLength(j_data, 0);
repeat
pos1 := Pos('{', dest);
if pos1 > 0 then
begin
Delete(dest, 1, pos1);
pos2 := Pos('}', dest);
if pos2 > 0 then
begin
str1 := Copy(dest, 1, pos2-1);
Delete(dest, 1, pos2);
pos2 := Pos(Delim, str1);
if pos2 > 0 then
begin
jdr.name := Copy(str1, 1, pos2-1);
jdr.val := Copy(str1, pos2+5, Length(str1)-pos2-4);
end
else
begin
jdr.name := 'error0';
jdr.val := 'corrupted data';
end;
end
else
begin
jdr.name := 'error1';
jdr.val := 'corrupted file';
pos1 := 0;
end;
Insert(jdr, j_data, Length(j_data));
end;
until pos1 = 0;
end;
function JValByName(jname: string; j_data:TJData): string;
var
i1: integer;
begin
Result := '';
for i1 := 0 to Length(j_data)-1 do
if j_data[i1].name = jname then
begin
Result := j_data[i1].val;
Break
end;
end;
procedure WriteJDFile(dest, fname: string; re_write: boolean = False);
var
fs1: TFileStream;
i1, L1: integer;
buf1: char;
begin
if re_write or (not FileExists(fname)) then
fs1 := TFileStream.Create(fname, fmCreate)
else
fs1 := TFileStream.Create(fname, fmOpenWrite);
fs1.Seek(0, soEnd);
L1 := Length(dest);
fs1.Write(L1, SizeOf(integer));
for i1 := 1 to L1 do
begin
fs1.Seek(0, soEnd);
buf1 := dest[i1];
fs1.Write(buf1, SizeOf(char));
end;
fs1.Free;
end;
procedure ReadJDFile(fname: string; var j_data: TJData);
var
fs1: TFileStream;
str1: string;
cnt1, i1, L1: integer;
buf1: char;
begin
fs1 := TFileStream.Create(fname, fmOpenRead);
cnt1 := 0;
str1 := '';
repeat
fs1.Seek(cnt1, soBeginning);
fs1.Read(L1, SizeOf(integer));
cnt1 := cnt1+SizeOf(integer);
for i1 := 1 to L1 do
begin
fs1.Seek(cnt1, soBeginning);
fs1.Read(buf1, SizeOf(char));
str1 := str1+buf1;
cnt1 := cnt1+SizeOf(char);
end;
until cnt1 >= fs1.Size;
DecodeJD(str1, j_data);
fs1.Free;
end;
end.
|
unit uLog;
{.$Define USELOG}
interface
uses System.Classes;
type
TLog = Procedure (const AMsg: string) of object;
Procedure BufferLog(const AMsg: string);
implementation
uses System.SysUtils;
{.$IFDEF USELOG}
var gLog: TStringList;
{.$ENDIF}
Procedure BufferLog(const AMsg: string);
Begin
{.$IFDEF USELOG}
if Assigned(gLog) then
gLog.Add( Concat( DateTimeToStr(Now), ' ', AMsg ) );
{.$ENDIF}
End;
{.$IFDEF USELOG}
initialization
gLog:= TStringList.Create;
finalization
if gLog.Count > 0 then
gLog.SaveToFile( ChangeFileExt(ParamStr(0), '.log') );
gLog.Free;
{.$ENDIF}
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC fetch options editing frame }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.VCLUI.FetchOptions;
interface
uses
{$IFDEF MSWINDOWS}
Winapi.Messages,
{$ENDIF}
System.SysUtils, System.Classes, Vcl.Controls, Vcl.Forms, Vcl.StdCtrls, Vcl.ExtCtrls,
FireDAC.Stan.Option,
FireDAC.VCLUI.Controls;
type
TfrmFDGUIxFormsFetchOptions = class(TFrame)
fo_gbItems: TPanel;
fo_cbIBlobs: TCheckBox;
fo_cbIDetails: TCheckBox;
fo_cbIMeta: TCheckBox;
fo_gbCache: TPanel;
fo_cbCBlobs: TCheckBox;
fo_cbCDetails: TCheckBox;
fo_cbCMeta: TCheckBox;
fo_GroupBox1: TPanel;
fo_Label1: TLabel;
fo_Label3: TLabel;
fo_Label2: TLabel;
fo_edtRecsMax: TEdit;
fo_edtRowSetSize: TEdit;
fo_cbxMode: TComboBox;
fo_cbAutoClose: TCheckBox;
fo_Label4: TLabel;
fo_cbxRecordCountMode: TComboBox;
fo_cbUnidirectional: TCheckBox;
Label1: TLabel;
fo_cbxCursor: TComboBox;
fo_cbxFetchAll: TComboBox;
fo_Label5: TLabel;
fo_gbMasterDetail: TPanel;
Label2: TLabel;
fo_edtDetailDelay: TEdit;
fo_cbDetailOptimize: TCheckBox;
fo_cbDetailCascade: TCheckBox;
fo_gbLiveDataWindow: TPanel;
fo_cbLiveWindowParanoic: TCheckBox;
fo_cbLiveWindowFastFirst: TCheckBox;
procedure fo_Change(Sender: TObject);
private
FOnModified: TNotifyEvent;
FModifiedLocked: Boolean;
public
procedure LoadFrom(AOpts: TFDFetchOptions);
procedure SaveTo(AOpts: TFDFetchOptions);
published
property OnModified: TNotifyEvent read FOnModified write FOnModified;
end;
implementation
{$R *.dfm}
{ --------------------------------------------------------------------------- }
procedure TfrmFDGUIxFormsFetchOptions.LoadFrom(AOpts: TFDFetchOptions);
begin
FModifiedLocked := True;
try
fo_cbxMode.ItemIndex := Integer(AOpts.Mode);
fo_cbxCursor.ItemIndex := Integer(AOpts.CursorKind);
fo_cbUnidirectional.Checked := AOpts.Unidirectional;
fo_edtRowSetSize.Text := IntToStr(AOpts.RowsetSize);
fo_edtRecsMax.Text := IntToStr(AOpts.RecsMax);
fo_cbAutoClose.Checked := AOpts.AutoClose;
fo_cbxFetchAll.ItemIndex := Integer(AOpts.AutoFetchAll);
fo_cbxRecordCountMode.ItemIndex := Integer(AOpts.RecordCountMode);
fo_cbIBlobs.Checked := fiBlobs in AOpts.Items;
fo_cbIDetails.Checked := fiDetails in AOpts.Items;
fo_cbIMeta.Checked := fiMeta in AOpts.Items;
fo_cbCBlobs.Checked := fiBlobs in AOpts.Cache;
fo_cbCDetails.Checked := fiDetails in AOpts.Cache;
fo_cbCMeta.Checked := fiMeta in AOpts.Cache;
fo_edtDetailDelay.Text := IntToStr(AOpts.DetailDelay);
fo_cbDetailOptimize.Checked := AOpts.DetailOptimize;
fo_cbDetailCascade.Checked := AOpts.DetailCascade;
fo_cbLiveWindowParanoic.Checked := AOpts.LiveWindowParanoic;
fo_cbLiveWindowFastFirst.Checked := AOpts.LiveWindowFastFirst;
finally
FModifiedLocked := False;
end;
end;
{ --------------------------------------------------------------------------- }
procedure TfrmFDGUIxFormsFetchOptions.SaveTo(AOpts: TFDFetchOptions);
var
i: TFDFetchItems;
j: Integer;
begin
if AOpts.Mode <> TFDFetchMode(fo_cbxMode.ItemIndex) then
AOpts.Mode := TFDFetchMode(fo_cbxMode.ItemIndex);
if AOpts.CursorKind <> TFDCursorKind(fo_cbxCursor.ItemIndex) then
AOpts.CursorKind := TFDCursorKind(fo_cbxCursor.ItemIndex);
if AOpts.Unidirectional <> fo_cbUnidirectional.Checked then
AOpts.Unidirectional := fo_cbUnidirectional.Checked;
j := StrToInt(fo_edtRowSetSize.Text);
if AOpts.RowsetSize <> j then
AOpts.RowsetSize := j;
j := StrToInt(fo_edtRecsMax.Text);
if AOpts.RecsMax <> j then
AOpts.RecsMax := j;
if AOpts.AutoClose <> fo_cbAutoClose.Checked then
AOpts.AutoClose := fo_cbAutoClose.Checked;
if AOpts.AutoFetchAll <> TFDAutoFetchAll(fo_cbxFetchAll.ItemIndex) then
AOpts.AutoFetchAll := TFDAutoFetchAll(fo_cbxFetchAll.ItemIndex);
if AOpts.RecordCountMode <> TFDRecordCountMode(fo_cbxRecordCountMode.ItemIndex) then
AOpts.RecordCountMode := TFDRecordCountMode(fo_cbxRecordCountMode.ItemIndex);
i := [];
if fo_cbIBlobs.Checked then
Include(i, fiBlobs);
if fo_cbIDetails.Checked then
Include(i, fiDetails);
if fo_cbIMeta.Checked then
Include(i, fiMeta);
if AOpts.Items <> i then
AOpts.Items := i;
i := [];
if fo_cbCBlobs.Checked then
Include(i, fiBlobs);
if fo_cbCDetails.Checked then
Include(i, fiDetails);
if fo_cbCMeta.Checked then
Include(i, fiMeta);
if AOpts.Cache <> i then
AOpts.Cache := i;
j := StrToInt(fo_edtDetailDelay.Text);
if AOpts.DetailDelay <> j then
AOpts.DetailDelay := j;
if AOpts.DetailOptimize <> fo_cbDetailOptimize.Checked then
AOpts.DetailOptimize := fo_cbDetailOptimize.Checked;
if AOpts.DetailCascade <> fo_cbDetailCascade.Checked then
AOpts.DetailCascade := fo_cbDetailCascade.Checked;
if AOpts.LiveWindowParanoic <> fo_cbLiveWindowParanoic.Checked then
AOpts.LiveWindowParanoic := fo_cbLiveWindowParanoic.Checked;
if AOpts.LiveWindowFastFirst <> fo_cbLiveWindowFastFirst.Checked then
AOpts.LiveWindowFastFirst := fo_cbLiveWindowFastFirst.Checked;
end;
{ --------------------------------------------------------------------------- }
procedure TfrmFDGUIxFormsFetchOptions.fo_Change(Sender: TObject);
begin
if not FModifiedLocked and Assigned(FOnModified) then
FOnModified(Self);
end;
end.
|
procedure writeInFixedFormat(n: real);
const
wholeNumberPlaces = 5;
fractionalPlaces = 3;
zeroDigit = '0';
negative = '-';
var
signPresent: boolean;
i: integer;
begin
// NOTE: This does not catch “negative” zero.
signPresent := n < 0.0;
if signPresent then
begin
write(negative);
n := abs(n);
end;
// determine number of leading zeros
i := wholeNumberPlaces;
if n > 0 then
begin
i := i - trunc(ln(n) / ln(10));
end;
for i := i - 1 downto succ(ord(signPresent)) do
begin
write(zeroDigit);
end;
// writes n with
// - at least 0 characters in total
// - exactly fractionalPlaces post-radix digits
// rounded
write(n:0:fractionalPlaces);
end;
|
unit UScript;
interface
uses FireDAC.Comp.Script;
procedure CreateTableBabys;
procedure BuildTable;
procedure CreateTableLog;
implementation
uses
MainModule;
procedure CreateData_Table;
var
tmpScript: TFDScript;
begin
tmpScript := TFDScript.Create(nil);
tmpScript.Connection := DMMainModule.SqlitConnection();
with tmpScript.SQLScripts do
begin
Clear;
with Add do
begin
Name := 'Data_Table';
SQL.Add('DROP TABLE IF EXISTS Data_Table ;');
SQL.Add('create table Data_Table(');
SQL.Add('Id INT NOT NULL AUTO_INCREMENT,');
SQL.Add('VTYPE INT,');
SQL.Add('KIND_ID INT,');
SQL.Add('PRIMARY KEY ( Id )');
SQL.Add(');');
end;
end;
try
tmpScript.ValidateAll;
tmpScript.ExecuteAll;
finally
tmpScript.free;
end;
end;
procedure CreateTableLog;
var
tmpScript: TFDScript;
begin
tmpScript := TFDScript.Create(nil);
tmpScript.Connection := DMMainModule.SqlitConnection();
with tmpScript.SQLScripts do
begin
Clear;
with Add do
begin
Name := 'LogConnec';
SQL.Add('CREATE TABLE IF NOT EXISTS LogConnec(');
SQL.Add('Id INT NOT NULL AUTO_INCREMENT,');
SQL.Add('APPID INT,');
SQL.Add('EVN_TYPE INT,');
SQL.Add('EMSG VARCHAR(255),');
SQL.Add('PRIMARY KEY ( Id )');
SQL.Add(');');
end;
end;
try
tmpScript.ValidateAll;
tmpScript.ExecuteAll;
finally
tmpScript.free;
end;
end;
procedure CreateTableBabys;
var
tmpScript: TFDScript;
begin
tmpScript := TFDScript.Create(nil);
tmpScript.Connection := DMMainModule.SqlitConnection();
with tmpScript.SQLScripts do
begin
Clear;
with Add do
begin
Name := 'Babys';
SQL.Add('CREATE TABLE IF NOT EXISTS Babys(');
SQL.Add('Id INTEGER NOT NULL PRIMARY KEY,');
SQL.Add('FirstName VARCHAR(255) NOT NULL,');
SQL.Add('LastName VARCHAR(255) NOT NULL,');
SQL.Add('Age INTERGER NOT NULL,');
SQL.Add('Present Boolean DEFAULT 1,');
SQl.Add('ProfileImage blob');
SQL.Add(');');
end;
end;
try
tmpScript.ValidateAll;
tmpScript.ExecuteAll;
finally
tmpScript.free;
end;
end;
procedure InsertTableBabys;
var
tmpScript: TFDScript;
begin
tmpScript := TFDScript.Create(nil);
tmpScript.Connection := DMMainModule.SqlitConnection();
with tmpScript.SQLScripts do
begin
Clear;
with Add do
begin
SQL.Add('INSERT INTO Babys (Id,LastName,FirstName,Age,Present,ProfileImage)');
SQL.Add('VALUES');
SQL.Add('(1,"ALex","Alex",30,true,'');');
end;
end;
try
tmpScript.ValidateAll;
tmpScript.ExecuteAll;
finally
tmpScript.free;
end;
end;
procedure BuildTable;
begin
CreateTableBabys;
// InsertTable;
// CreateData_Table;
end;
end.
|
Unit frm_MainWindow;
Interface
Uses
Windows,
Messages,
SysUtils,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
mxWebUpdate,
StdCtrls,
ComCtrls,
ExtCtrls;
Type
Tform_MainWindow = Class( TForm )
mxWebUpdate: TmxWebUpdate;
grp_ComponentUpdate: TGroupBox;
btn_Update: TButton;
btn_Exit: TButton;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
lbl_ProductName: TLabel;
lbl_Author: TLabel;
lbl_Email: TLabel;
lbl_YourVersion: TLabel;
lbl_WebVersion: TLabel;
ProgressBar: TProgressBar;
Bevel: TBevel;
lbl_File: TLabel;
chk1: TCheckBox;
Procedure btn_ExitClick( Sender: TObject );
Procedure btn_UpdateClick( Sender: TObject );
Procedure mxWebUpdateAfterGetInfo( Sender: TObject );
Procedure mxWebUpdateDownloadError( Sender: TObject );
Procedure mxWebUpdateNoUpdateFound( Sender: TObject );
Procedure mxWebUpdateUpdateAvailable( Sender: TObject; ActualVersion, NewVersion: String; Var CanUpdate: Boolean );
Procedure mxWebUpdateGetClientFileName( Sender: TObject; Var FileName: String );
Procedure mxWebUpdateClientFileExists( Sender: TObject; Var FileName: String; Var Overwrite: Boolean );
Procedure mxWebUpdateAfterDownload( Sender: TObject; FileName: String );
Procedure mxWebUpdateBeforeDownload( Sender: TObject; FileName: String );
Procedure mxWebUpdateBeforeShowInfo( Sender: TObject; Var ShowInfo, CheckForUpdate: Boolean );
Procedure mxWebUpdateBeforeGetInfo( Sender: TObject );
Procedure mxWebUpdateAfterShowInfo( Sender: TObject; CheckForUpdate: Boolean );
procedure mxWebUpdateGetInfo(Sender: TObject);
procedure mxWebUpdateDownload(Sender: TObject; Total,
Downloaded: Integer; UpdataStatus: Boolean);
Private
Public
End;
Var
form_MainWindow: Tform_MainWindow;
Implementation
Uses frm_Message;
{$R *.DFM}
Procedure Tform_MainWindow.btn_ExitClick( Sender: TObject );
Begin
Close;
End;
Procedure Tform_MainWindow.btn_UpdateClick( Sender: TObject );
Begin
if chk1.Checked then
mxWebUpdate.CheckForAnUpdate
else
mxWebUpdate.GetInfo;
End;
Procedure Tform_MainWindow.mxWebUpdateAfterGetInfo( Sender: TObject );
Begin
lbl_ProductName.Caption := mxWebUpdate.ProductName;
lbl_Author.Caption := mxWebUpdate.Author;
lbl_Email.Caption := mxWebUpdate.EMail;
lbl_YourVersion.Caption := mxWebUpdate.ProductInfo.Version;
lbl_WebVersion.Caption := mxWebUpdate.ProductVersion;
form_message.Close;
End;
Procedure Tform_MainWindow.mxWebUpdateDownloadError( Sender: TObject );
Begin
MessageDlg( 'Cannot download data from the web!', mtError, [ mbOK ], 0 );
End;
Procedure Tform_MainWindow.mxWebUpdateNoUpdateFound( Sender: TObject );
Begin
MessageDlg( 'There is no update available!', mtError, [ mbOK ], 0 );
End;
Procedure Tform_MainWindow.mxWebUpdateUpdateAvailable( Sender: TObject; ActualVersion, NewVersion: String; Var CanUpdate: Boolean );
Begin
CanUpdate := MessageDlg( Format( 'You are using version %s, but version %s is available to ' + #13 + #10 + 'download at the author''s website.' + #13 + #10 + 'Do you want to update your application now?', [ ActualVersion, NewVersion ] ), mtWarning, [ mbYes, mbNo ], 0 ) = mrYes;
End;
Procedure Tform_MainWindow.mxWebUpdateGetClientFileName( Sender: TObject; Var FileName: String );
Begin
MessageDlg( Format( 'Update will be downloaded to %s', [ FileName ] ), mtInformation, [ mbOK ], 0 );
// *** You can modify the client side file name here ***
End;
Procedure Tform_MainWindow.mxWebUpdateClientFileExists( Sender: TObject; Var FileName: String; Var Overwrite: Boolean );
Begin
Overwrite := MessageDlg( Format( 'File %s already exists. Do you want to overwrite it?', [ FileName ] ), mtConfirmation, [ mbYes, mbNo ], 0 ) = mrYes;
End;
Procedure Tform_MainWindow.mxWebUpdateAfterDownload( Sender: TObject; FileName: String );
Begin
MessageDlg( 'Update has been downloaded.', mtInformation, [ mbOK ], 0 );
End;
Procedure Tform_MainWindow.mxWebUpdateBeforeDownload( Sender: TObject; FileName: String );
Begin
lbl_File.Caption := Format( 'Downloading file %s', [ ExtractFileName( FileName ) ] );
End;
Procedure Tform_MainWindow.mxWebUpdateBeforeShowInfo( Sender: TObject; Var ShowInfo, CheckForUpdate: Boolean );
Begin
ShowInfo := MessageDlg( 'Would you like to read the information file?', mtConfirmation, [ mbYes, mbNo ], 0 ) = mrYes;
End;
Procedure Tform_MainWindow.mxWebUpdateBeforeGetInfo( Sender: TObject );
Begin
form_message.panel_message.Caption := 'Checking for an update';
form_message.Show;
form_message.Refresh;
End;
Procedure Tform_MainWindow.mxWebUpdateAfterShowInfo( Sender: TObject; CheckForUpdate: Boolean );
Begin
// ** You can save CheckForUpdate checkbox's value for future usage here ***
End;
procedure Tform_MainWindow.mxWebUpdateGetInfo(Sender: TObject);
begin
lbl_ProductName.Caption := mxWebUpdate.ProductName;
lbl_Author.Caption := mxWebUpdate.Author;
lbl_Email.Caption := mxWebUpdate.EMail;
lbl_YourVersion.Caption := mxWebUpdate.ProductInfo.Version;
lbl_WebVersion.Caption := mxWebUpdate.ProductVersion;
form_message.Close;
end;
procedure Tform_MainWindow.mxWebUpdateDownload(Sender: TObject; Total,
Downloaded: Integer; UpdataStatus: Boolean);
begin
if UpdataStatus then
begin
ProgressBar.Max := Total;
ProgressBar.Position := Downloaded;
end;
end;
End.
|
{
Helpers functions for the X2Software XML Data Binding
}
unit XMLDataBindingUtils;
interface
uses
Classes,
SysUtils,
XMLDoc,
xmldom,
XMLIntf;
type
EBase64Error = class(Exception);
EXSDValidationError = class(Exception);
TXMLDateTimeFormat = (xdtDateTime, xdtDate, xdtTime);
TXMLTimeFragment = (xtfMilliseconds, xtfTimezone);
TXMLTimeFragments = set of TXMLTimeFragment;
TDateConvert = (dcToUtc, dcToLocal);
IXSDValidate = interface
['{3BFDC851-7459-403B-87B3-A52E9E85BC8C}']
procedure XSDValidate;
end;
IXSDValidateStrictResult = interface
['{F10E1CB2-ECDF-4215-AF2C-28B5C6C51A90}']
procedure MissingElement(AParent: IXMLNode; const AName: string);
procedure MissingAttribute(AParent: IXMLNode; const AName: string);
end;
IXSDValidateStrict = interface
['{82C3B08E-F327-4D38-9FE2-F99925E7E401}']
procedure XSDValidateStrict(AResult: IXSDValidateStrictResult);
end;
TX2XMLNode = class(TXMLNode)
private
function GetChildNodesNS(const ANodeName, ANamespaceURI: DOMString): IXMLNode;
protected
property ChildNodesNS[const ANodeName, ANamespaceURI: DOMString]: IXMLNode read GetChildNodesNS;
end;
TX2XMLNodeCollection = class(TXMLNodeCollection)
private
function GetChildNodesNS(const ANodeName, ANamespaceURI: DOMString): IXMLNode;
protected
property ChildNodesNS[const ANodeName, ANamespaceURI: DOMString]: IXMLNode read GetChildNodesNS;
end;
TXMLNodeCollectionEnumerator = class(TInterfacedObject)
private
FNodeCollection: IXMLNodeCollection;
FIndex: Integer;
public
constructor Create(ANodeCollection: IXMLNodeCollection);
function GetCurrent: IXMLNode;
function MoveNext: Boolean; virtual;
property Current: IXMLNode read GetCurrent;
end;
const
AllTimeFragments = [Low(TXMLTimeFragment)..High(TXMLTimeFragment)];
function DateTimeToXML(ADate: TDateTime; AFormat: TXMLDateTimeFormat; ATimeFragments: TXMLTimeFragments = AllTimeFragments): string;
function XMLToDateTime(const ADate: string; AFormat: TXMLDateTimeFormat): TDateTime;
function BoolToXML(AValue: Boolean): WideString;
function XMLToBool(const AValue: WideString): Boolean;
function FloatToXML(AValue: Extended): WideString;
function XMLToFloat(const AValue: WideString): Extended;
function GetNodeIsNil(ANode: IXMLNode): Boolean;
procedure SetNodeIsNil(ANode: IXMLNode; ASetNil: Boolean);
procedure XSDValidate(AParent: IXMLNode; ARecurse: Boolean = True; AValidateParent: Boolean = True);
procedure XSDValidateStrict(AParent: IXMLNode; ARecurse: Boolean = True; AValidateParent: Boolean = True); overload;
procedure XSDValidateStrict(AResult: IXSDValidateStrictResult; AParent: IXMLNode; ARecurse: Boolean = True; AValidateParent: Boolean = True); overload;
procedure ValidateRequiredElements(AResult: IXSDValidateStrictResult; AParent: IXMLNode; ANodes: array of string);
procedure ValidateRequiredAttributes(AResult: IXSDValidateStrictResult; AParent: IXMLNode; ANodes: array of string);
procedure CreateRequiredElements(AParent: IXMLNode; ANodes: array of string); overload;
procedure CreateRequiredElements(AParent: IXMLNode; ANodes: array of string; Namespaces: array of string); overload;
procedure CreateRequiredAttributes(AParent: IXMLNode; ANodes: array of string);
procedure SortChildNodes(AParent: IXMLNode; ASortOrder: array of string);
function IsValidXMLChar(AChar: WideChar): Boolean;
function GetValidXMLText(AText: WideString): WideString;
{ Now wraps the JclMime implementation:
Lightening fast Mime (Base64) Encoding and Decoding routines.
Coded by Ralf Junker (ralfjunker@gmx.de).}
function Base64Encode(AValue: String): string;
function Base64Decode(AValue: String): string;
function Base64EncodeFromStream(AStream: TStream): string;
function Base64EncodeFromFile(const AFileName: string): string;
procedure Base64DecodeToStream(AValue: string; AStream: TStream);
procedure Base64DecodeToFile(AValue: string; const AFileName: string);
const
XMLSchemaInstanceURI = 'http://www.w3.org/2001/XMLSchema-instance';
XMLDateFormat = 'yyyy"-"mm"-"dd';
XMLTimeFormat = 'hh":"nn":"ss';
XMLMsecsFormat = '"."zzz';
XMLTimezoneZulu = 'Z';
XMLTimezoneFormat = '%s%.2d:%.2d';
XMLDateTimeFormats: array[TXMLDateTimeFormat] of String =
(
XMLDateFormat + '"T"' + XMLTimeFormat,
XMLDateFormat,
XMLTimeFormat
);
XMLTimezoneSigns: array[Boolean] of Char = ('-', '+');
XMLBoolValues: array[Boolean] of String =
(
'false',
'true'
);
XMLIsNilAttribute = 'nil';
XMLIsNilAttributeNS = 'xsi:nil';
Base64ValidChars = ['A'..'Z', 'a'..'z', '0'..'9', '+', '/'];
Base64LookupTable = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
'abcdefghijklmnopqrstuvwxyz' +
'0123456789+/';
Base64Padding = '=';
implementation
uses
DateUtils,
Math,
Types,
Windows;
type
PSortNodeInfo = ^TSortNodeInfo;
TSortNodeInfo = record
Node: IXMLNode;
SortIndex: Integer;
OriginalIndex: Integer;
end;
TXSDValidateStrictResult = class(TInterfacedPersistent, IXSDValidateStrictResult)
private
FMissingElements: TStrings;
FMissingAttributes: TStrings;
function GetMissingAttributes: TStrings;
function GetMissingElements: TStrings;
protected
function GetNodeTree(AParent: IXMLNode; const AName: string): string;
property MissingElements: TStrings read GetMissingElements;
property MissingAttributes: TStrings read GetMissingAttributes;
public
destructor Destroy; override;
procedure RaiseResult;
{ IXSDValidateStrictResult }
procedure MissingElement(AParent: IXMLNode; const AName: string);
procedure MissingAttribute(AParent: IXMLNode; const AName: string);
end;
function MimeEncodeString(const S: AnsiString): AnsiString; forward;
function MimeDecodeString(const S: AnsiString): AnsiString; forward;
procedure MimeEncodeStream(const InputStream: TStream; const OutputStream: TStream); forward;
procedure MimeDecodeStream(const InputStream: TStream; const OutputStream: TStream); forward;
{ TX2XMLNode }
function TX2XMLNode.GetChildNodesNS(const ANodeName, ANamespaceURI: DOMString): IXMLNode;
begin
Result := ChildNodes.FindNode(ANodeName, ANamespaceURI);
if (not Assigned(Result)) and (doNodeAutoCreate in OwnerDocument.Options) then
Result := AddChild(ANodeName, ANamespaceURI);
end;
{ TX2XMLNodeCollection }
function TX2XMLNodeCollection.GetChildNodesNS(const ANodeName, ANamespaceURI: DOMString): IXMLNode;
begin
Result := ChildNodes.FindNode(ANodeName, ANamespaceURI);
if (not Assigned(Result)) and (doNodeAutoCreate in OwnerDocument.Options) then
Result := AddChild(ANodeName, ANamespaceURI);
end;
{ TXMLNodeCollectionEnumerator }
constructor TXMLNodeCollectionEnumerator.Create(ANodeCollection: IXMLNodeCollection);
begin
inherited Create;
FNodeCollection := ANodeCollection;
FIndex := -1;
end;
function TXMLNodeCollectionEnumerator.GetCurrent: IXMLNode;
begin
if (FIndex >= 0) and (FIndex < FNodeCollection.Count) then
Result := FNodeCollection.Nodes[FIndex]
else
Result := nil;
end;
function TXMLNodeCollectionEnumerator.MoveNext: Boolean;
begin
Inc(FIndex);
Result := (FIndex < FNodeCollection.Count);
end;
function InDSTSpan(ADate: TDateTime; ATimeZoneInfo: TTimeZoneInformation): boolean;
var
lowerDayLight: TDateTime;
upperDayLight: TDateTime;
day: TDateTime;
days: Integer;
function GetDay(AYear, AMonth, ADay, ADayOfWeek: Integer): TDateTime;
var
I, Counter : Integer;
begin
Result := 0;
Counter := 0;
days := DaysInAMonth(AYear, AMonth);
for I := 1 to days do
begin
Result := EncodeDate(AYear, AMonth, I);
// Delphi DayOfWeek 1 = Sunday
// TimeZoneInfo.wDayOfWeek 0 = Sunday
if DayOfWeek(Result) -1 = ADayOfWeek then
begin
inc(Counter);
if (counter = ADay) or ((Counter < Aday) and (I >= days - 6)) then
break;
end;
end;
end;
begin
with ATimeZoneInfo.DaylightDate do
begin
day := GetDay(wYear + YearOf(ADate), wMonth, wDay, wDayOfWeek);
lowerDayLight := day + EncodeTime(wHour, wMinute, wSecond, wMilliseconds);
end;
with ATimeZoneInfo.StandardDate do
begin
day := GetDay(wYear + YearOf(ADate), wMonth, wDay, wDayOfWeek);
upperDayLight := day + EncodeTime(wHour, wMinute, wSecond, wMilliseconds);
end;
Result := (ADate >= lowerDayLight) and (ADate <= upperDayLight);
end;
function ConvertDate(ADate: TDateTime; ADateconvert: TDateConvert): TDateTime;
var
timeZone: TTimeZoneInformation;
timeZoneID: Cardinal;
localOffset: Integer;
begin
FillChar(timeZone, SizeOf(TTimeZoneInformation), #0);
timeZoneID := GetTimeZoneInformation(timeZone);
if timeZoneID in [TIME_ZONE_ID_STANDARD, TIME_ZONE_ID_DAYLIGHT] then
localOffset := -timeZone.Bias - IfThen(InDSTSpan(ADate, timeZone), timeZone.DaylightBias, timeZone.StandardBias)
else
localOffset := 0;
if ADateconvert = dcToUtc then
localOffset := localOffset * -1;
Result := IncMinute(ADate, localOffset);
end;
function DateTimeToXML(ADate: TDateTime; AFormat: TXMLDateTimeFormat; ATimeFragments: TXMLTimeFragments): string;
var
formatSettings: TFormatSettings;
utcDate: TDateTime;
offsetMinutes: Integer;
begin
formatSettings := TFormatSettings.Create;;
Result := FormatDateTime(XMLDateTimeFormats[AFormat], ADate, formatSettings);
if AFormat in [xdtDateTime, xdtTime] then
begin
if xtfMilliseconds in ATimeFragments then
Result := Result + FormatDateTime(XMLMsecsFormat, ADate);
if (xtfTimezone in ATimeFragments) then
begin
utcDate := ConvertDate(ADate, dcToUtc);
offsetMinutes := MinutesBetween(ADate, utcDate);
if offsetMinutes = 0 then
Result := Result + XMLTimezoneZulu
else
Result := Result + Format(XMLTimezoneFormat,
[XMLTimezoneSigns[offsetMinutes > 0], offsetMinutes div 60, offsetMinutes mod 60]);
end;
end;
end;
function XMLToDateTime(const ADate: string; AFormat: TXMLDateTimeFormat): TDateTime;
const
{ yyyy-mm-ddThh:nn:ss.zzz+xx:xx }
XMLTimeSeparatorPos = 11;
XMLTimeSeparator = 'T';
XMLMinTimeLength = 8;
var
date: string;
time: string;
year: Integer;
month: Integer;
day: Integer;
hour: Integer;
minute: Integer;
second: Integer;
msec: Integer;
hasTimezone: Boolean;
xmlOffset: Integer;
endPos: Integer;
begin
Result := 0;
date := '';
time := '';
case AFormat of
xdtDateTime:
begin
if (Length(ADate) < XMLTimeSeparatorPos) or
(ADate[XMLTimeSeparatorPos] <> XMLTimeSeparator) then
Exit;
date := ADate;
time := ADate;
SetLength(date, Pred(XMLTimeSeparatorPos));
Delete(time, 1, XMLTimeSeparatorPos);
end;
xdtDate:
begin
if Length(ADate) < Pred(XMLTimeSeparatorPos) then
Exit;
date := ADate;
end;
xdtTime:
begin
if Length(ADate) < XMLMinTimeLength then
Exit;
time := ADate;
end;
end;
if AFormat in [xdtDateTime, xdtDate] then
begin
{ Parse date (yyyy-mm-hh) }
if TryStrToInt(Copy(date, 1, 4), year) and
TryStrToInt(Copy(date, 6, 2), month) and
TryStrToInt(Copy(date, 9, 2), day) then
Result := EncodeDate(year, month, day);
end;
if AFormat in [xdtDateTime, xdtTime] then
begin
{ Parse time (hh:nn:ss) }
if TryStrToInt(Copy(time, 1, 2), hour) and
TryStrToInt(Copy(time, 4, 2), minute) and
TryStrToInt(Copy(time, 7, 2), second) then
begin
msec := 0;
Delete(time, 1, 8);
if Length(time) > 0 then
begin
if time[1] = '.' then
begin
{ Parse milliseconds (.zzz+) }
Delete(time, 1, 1);
endPos := 1;
while (endPos <= Length(time)) and (CharInSet(time[endPos], ['0'..'9'])) do
Inc(endPos);
Dec(endPos);
if (endPos = 0) or (not TryStrToInt(Copy(time, 1, Min(endPos, 3)), msec)) then
msec := 0;
if endPos > 0 then
Delete(time, 1, endPos);
end;
end;
Result := Result + EncodeTime(hour, minute, second, msec);
if Length(time) > 0 then
begin
hasTimezone := False;
if time[1] = XMLTimezoneZulu then
begin
{ Zulu time }
hasTimezone := True;
end else if CharInSet(time[1], [XMLTimezoneSigns[False], XMLTimezoneSigns[True]]) then
begin
{ Parse timezone ([+|-]xx:xx) }
if TryStrToInt(Copy(time, 2, 2), hour) and
TryStrToInt(Copy(time, 5, 2), minute) then
begin
xmlOffset := (hour * MinsPerHour) + minute;
hasTimezone := True;
if time[1] = XMLTimezoneSigns[False] then
xmlOffset := -xmlOffset;
Result := IncMinute(Result, - xmlOffset);
end;
end;
if hasTimezone then
Result := ConvertDate(Result, dcToLocal);
end;
end;
end;
end;
function BoolToXML(AValue: Boolean): WideString;
begin
Result := XMLBoolValues[AValue];
end;
function XMLToBool(const AValue: WideString): Boolean;
begin
Result := StrToBoolDef(AValue, False);
end;
function GetXMLFloatFormatSettings(): TFormatSettings;
begin
Result.DecimalSeparator := '.';
end;
function FloatToXML(AValue: Extended): WideString;
begin
Result := FloatToStr(AValue, GetXMLFloatFormatSettings());
end;
function XMLToFloat(const AValue: WideString): Extended;
begin
Result := StrToFloat(AValue, GetXMLFloatFormatSettings());
end;
function Base64Encode(AValue: String): String;
begin
Result := string(MimeEncodeString(AnsiString(AValue)));
end;
function Base64Decode(AValue: String): String;
begin
Result := string(MimeDecodeString(AnsiString(AValue)));
end;
function Base64EncodeFromStream(AStream: TStream): string;
var
output: TStringStream;
begin
output := TStringStream.Create('');
try
MimeEncodeStream(AStream, output);
Result := output.DataString;
finally
FreeAndNil(output);
end;
end;
function Base64EncodeFromFile(const AFileName: string): string;
var
input: TFileStream;
begin
input := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite);
try
Result := Base64EncodeFromStream(input);
finally
FreeAndNil(input);
end;
end;
procedure Base64DecodeToStream(AValue: String; AStream: TStream);
var
input: TStringStream;
begin
input := TStringStream.Create(AValue);
try
MimeDecodeStream(input, AStream);
finally
FreeAndNil(input);
end;
end;
procedure Base64DecodeToFile(AValue: String; const AFileName: String);
var
output: TFileStream;
begin
output := TFileStream.Create(AFileName, fmCreate or fmShareDenyWrite);
try
Base64DecodeToStream(AValue, output);
finally
FreeAndNil(output);
end;
end;
function GetNodeIsNil(ANode: IXMLNode): Boolean;
begin
Result := ANode.HasAttribute(XMLIsNilAttribute, XMLSchemaInstanceURI) and
XMLToBool(ANode.GetAttributeNS(XMLIsNilAttribute, XMLSchemaInstanceURI));
end;
procedure SetNodeIsNil(ANode: IXMLNode; ASetNil: Boolean);
var
documentElement: IXMLNode;
begin
if ASetNil then
begin
ANode.ChildNodes.Clear;
documentElement := ANode.OwnerDocument.DocumentElement;
if not documentElement.HasAttribute('xmlns:xsi') then
documentElement.SetAttributeNS('xmlns:xsi', '', XMLSchemaInstanceURI);
ANode.SetAttributeNS(XMLIsNilAttributeNS, XMLSchemaInstanceURI, BoolToXML(True));
end else
ANode.AttributeNodes.Delete(XMLIsNilAttribute, XMLSchemaInstanceURI);
end;
function DoSortNodes(Item1, Item2: Pointer): Integer;
var
nodeInfo1: PSortNodeInfo;
nodeInfo2: PSortNodeInfo;
begin
nodeInfo1 := Item1;
nodeInfo2 := Item2;
if (nodeInfo1^.SortIndex > -1) and (nodeInfo2^.SortIndex = -1) then
Result := GreaterThanValue
else if (nodeInfo1^.SortIndex = -1) and (nodeInfo2^.SortIndex > -1) then
Result := LessThanValue
else if (nodeInfo1^.SortIndex = nodeInfo2^.SortIndex) then
Result := CompareValue(nodeInfo1^.OriginalIndex, nodeInfo2^.OriginalIndex)
else
Result := CompareValue(nodeInfo1^.SortIndex, nodeInfo2^.SortIndex);
end;
procedure XSDValidate(AParent: IXMLNode; ARecurse, AValidateParent: Boolean);
var
validate: IXSDValidate;
childIndex: Integer;
begin
if AValidateParent and Supports(AParent, IXSDValidate, validate) then
validate.XSDValidate;
if ARecurse then
begin
for childIndex := 0 to Pred(AParent.ChildNodes.Count) do
XSDValidate(AParent.ChildNodes[childIndex], ARecurse, True);
end;
end;
procedure XSDValidateStrict(AParent: IXMLNode; ARecurse: Boolean; AValidateParent: Boolean);
var
result: TXSDValidateStrictResult;
begin
result := TXSDValidateStrictResult.Create;
try
XSDValidateStrict(result, AParent, ARecurse, AValidateParent);
result.RaiseResult;
finally
FreeAndNil(result);
end;
end;
procedure XSDValidateStrict(AResult: IXSDValidateStrictResult; AParent: IXMLNode; ARecurse: Boolean; AValidateParent: Boolean);
var
validate: IXSDValidateStrict;
childIndex: Integer;
begin
if AValidateParent and Supports(AParent, IXSDValidateStrict, validate) then
validate.XSDValidateStrict(AResult);
if ARecurse then
begin
for childIndex := 0 to Pred(AParent.ChildNodes.Count) do
XSDValidateStrict(AResult, AParent.ChildNodes[childIndex], ARecurse, True);
end;
end;
procedure ValidateRequiredElements(AResult: IXSDValidateStrictResult; AParent: IXMLNode; ANodes: array of string);
var
nodeIndex: Integer;
begin
for nodeIndex := Low(ANodes) to High(ANodes) do
begin
if not Assigned(AParent.ChildNodes.FindNode(ANodes[nodeIndex])) then
AResult.MissingElement(AParent, ANodes[nodeIndex]);
end;
end;
procedure ValidateRequiredAttributes(AResult: IXSDValidateStrictResult; AParent: IXMLNode; ANodes: array of string);
var
nodeIndex: Integer;
begin
for nodeIndex := Low(ANodes) to High(ANodes) do
begin
if not Assigned(AParent.AttributeNodes.FindNode(ANodes[nodeIndex])) then
AResult.MissingAttribute(AParent, ANodes[nodeIndex]);
end;
end;
procedure CreateRequiredElements(AParent: IXMLNode; ANodes: array of string); overload;
var
nodeIndex: Integer;
node: IXMLNode;
begin
for nodeIndex := Low(ANodes) to High(ANodes) do
begin
if not Assigned(AParent.ChildNodes.FindNode(ANodes[nodeIndex])) then
begin
node := AParent.OwnerDocument.CreateElement(ANodes[nodeIndex], AParent.NamespaceURI);
AParent.ChildNodes.Add(node);
end;
end;
end;
procedure CreateRequiredElements(AParent: IXMLNode; ANodes: array of string; Namespaces: array of string);
var
nodeIndex: Integer;
node: IXMLNode;
begin
for nodeIndex := Low(ANodes) to High(ANodes) do
begin
if not Assigned(AParent.ChildNodes.FindNode(ANodes[nodeIndex], Namespaces[nodeIndex])) then
begin
node := AParent.OwnerDocument.CreateElement(ANodes[nodeIndex], Namespaces[nodeIndex]);
AParent.ChildNodes.Add(node);
end;
end;
end;
procedure CreateRequiredAttributes(AParent: IXMLNode; ANodes: array of string);
var
nodeIndex: Integer;
begin
for nodeIndex := Low(ANodes) to High(ANodes) do
begin
if not Assigned(AParent.AttributeNodes.FindNode(ANodes[nodeIndex])) then
AParent.Attributes[ANodes[nodeIndex]] := '';
end;
end;
procedure SortChildNodes(AParent: IXMLNode; ASortOrder: array of string);
var
sortList: TList;
nodeInfo: PSortNodeInfo;
childIndex: Integer;
sortIndex: Integer;
node: IXMLNode;
begin
sortList := TList.Create;
try
{ Build a list of the child nodes, with their original index and the
index in the ASortOrder array. }
for childIndex := 0 to Pred(AParent.ChildNodes.Count) do
begin
New(nodeInfo);
nodeInfo^.Node := AParent.ChildNodes[childIndex];
nodeInfo^.OriginalIndex := childIndex;
for sortIndex := Low(ASortOrder) to High(ASortOrder) do
begin
if ASortOrder[sortIndex] = nodeInfo^.Node.NodeName then
begin
nodeInfo^.SortIndex := sortIndex;
Break;
end;
end;
sortList.Add(nodeInfo);
end;
sortList.Sort(DoSortNodes);
{ Rebuild the ChildNodes list }
for childIndex := 0 to Pred(sortList.Count) do
begin
node := PSortNodeInfo(sortList[childIndex])^.Node;
AParent.ChildNodes.Remove(node);
AParent.ChildNodes.Insert(childIndex, node);
end;
finally
for sortIndex := 0 to Pred(sortList.Count) do
Dispose(PSortNodeInfo(sortList[sortIndex]));
FreeAndNil(sortList);
end;
end;
function IsValidXMLChar(AChar: WideChar): Boolean;
begin
Result := (Ord(AChar) in [9, 10, 13]) or
(Ord(AChar) >= 32);
end;
function GetValidXMLText(AText: WideString): WideString;
var
validText: WideString;
sourcePos: Integer;
destPos: Integer;
begin
SetLength(validText, Length(AText));
destPos := 0;
for sourcePos := 1 to Length(AText) do
begin
if IsValidXMLChar(AText[sourcePos]) then
begin
Inc(destPos);
validText[destPos] := AText[sourcePos];
end;
end;
SetLength(validText, destPos);
Result := validText;
end;
{ --- JclMime implementation from here. }
type
{$IFDEF WIN64}
SizeInt = NativeInt;
TJclAddr = UInt64;
{$ELSE}
SizeInt = Integer;
TJclAddr = Cardinal;
{$ENDIF}
PByte4 = ^TByte4;
TByte4 = packed record
B1: Byte;
B2: Byte;
B3: Byte;
B4: Byte;
end;
PByte3 = ^TByte3;
TByte3 = packed record
B1: Byte;
B2: Byte;
B3: Byte;
end;
const
MIME_ENCODED_LINE_BREAK = 76;
MIME_DECODED_LINE_BREAK = MIME_ENCODED_LINE_BREAK div 4 * 3;
MIME_BUFFER_SIZE = MIME_DECODED_LINE_BREAK * 3 * 4 * 4;
MIME_ENCODE_TABLE: array [0..63] of Byte = (
065, 066, 067, 068, 069, 070, 071, 072, // 00 - 07
073, 074, 075, 076, 077, 078, 079, 080, // 08 - 15
081, 082, 083, 084, 085, 086, 087, 088, // 16 - 23
089, 090, 097, 098, 099, 100, 101, 102, // 24 - 31
103, 104, 105, 106, 107, 108, 109, 110, // 32 - 39
111, 112, 113, 114, 115, 116, 117, 118, // 40 - 47
119, 120, 121, 122, 048, 049, 050, 051, // 48 - 55
052, 053, 054, 055, 056, 057, 043, 047); // 56 - 63
MIME_PAD_CHAR = Byte('=');
MIME_DECODE_TABLE: array [Byte] of Byte = (
255, 255, 255, 255, 255, 255, 255, 255, // 0 - 7
255, 255, 255, 255, 255, 255, 255, 255, // 8 - 15
255, 255, 255, 255, 255, 255, 255, 255, // 16 - 23
255, 255, 255, 255, 255, 255, 255, 255, // 24 - 31
255, 255, 255, 255, 255, 255, 255, 255, // 32 - 39
255, 255, 255, 062, 255, 255, 255, 063, // 40 - 47
052, 053, 054, 055, 056, 057, 058, 059, // 48 - 55
060, 061, 255, 255, 255, 255, 255, 255, // 56 - 63
255, 000, 001, 002, 003, 004, 005, 006, // 64 - 71
007, 008, 009, 010, 011, 012, 013, 014, // 72 - 79
015, 016, 017, 018, 019, 020, 021, 022, // 80 - 87
023, 024, 025, 255, 255, 255, 255, 255, // 88 - 95
255, 026, 027, 028, 029, 030, 031, 032, // 96 - 103
033, 034, 035, 036, 037, 038, 039, 040, // 104 - 111
041, 042, 043, 044, 045, 046, 047, 048, // 112 - 119
049, 050, 051, 255, 255, 255, 255, 255, // 120 - 127
255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255);
function MimeEncodedSize(const InputSize: SizeInt): SizeInt;
begin
if InputSize > 0 then
Result := (InputSize + 2) div 3 * 4 + (InputSize - 1) div MIME_DECODED_LINE_BREAK * 2
else
Result := InputSize;
end;
procedure MimeEncodeFullLines(const InputBuffer; const InputByteCount: SizeInt; out OutputBuffer);
var
B: Cardinal;
InnerLimit, OuterLimit: TJclAddr;
InPtr: PByte3;
OutPtr: PByte4;
begin
{ Do we have enough input to encode a full line? }
if InputByteCount < MIME_DECODED_LINE_BREAK then
Exit;
InPtr := @InputBuffer;
OutPtr := @OutputBuffer;
InnerLimit := TJclAddr(InPtr);
Inc(InnerLimit, MIME_DECODED_LINE_BREAK);
OuterLimit := TJclAddr(InPtr);
Inc(OuterLimit, InputByteCount);
{ Multiple line loop. }
repeat
{ Single line loop. }
repeat
{ Read 3 bytes from InputBuffer. }
B := InPtr^.B1;
B := B shl 8;
B := B or InPtr^.B2;
B := B shl 8;
B := B or InPtr^.B3;
Inc(InPtr);
{ Write 4 bytes to OutputBuffer (in reverse order). }
OutPtr^.B4 := MIME_ENCODE_TABLE[B and $3F];
B := B shr 6;
OutPtr^.B3 := MIME_ENCODE_TABLE[B and $3F];
B := B shr 6;
OutPtr^.B2 := MIME_ENCODE_TABLE[B and $3F];
B := B shr 6;
OutPtr^.B1 := MIME_ENCODE_TABLE[B];
Inc(OutPtr);
until TJclAddr(InPtr) >= InnerLimit;
{ Write line break (CRLF). }
OutPtr^.B1 := 13;
OutPtr^.B2 := 10;
Inc(TJclAddr(OutPtr), 2);
Inc(InnerLimit, MIME_DECODED_LINE_BREAK);
until InnerLimit > OuterLimit;
end;
procedure MimeEncodeNoCRLF(const InputBuffer; const InputByteCount: SizeInt; out OutputBuffer);
var
B: Cardinal;
InnerLimit, OuterLimit: SizeInt;
InPtr: PByte3;
OutPtr: PByte4;
begin
if InputByteCount = 0 then
Exit;
InPtr := @InputBuffer;
OutPtr := @OutputBuffer;
OuterLimit := InputByteCount div 3 * 3;
InnerLimit := TJclAddr(InPtr);
Inc(InnerLimit, OuterLimit);
{ Last line loop. }
while TJclAddr(InPtr) < TJclAddr(InnerLimit) do
begin
{ Read 3 bytes from InputBuffer. }
B := InPtr^.B1;
B := B shl 8;
B := B or InPtr^.B2;
B := B shl 8;
B := B or InPtr^.B3;
Inc(InPtr);
{ Write 4 bytes to OutputBuffer (in reverse order). }
OutPtr^.B4 := MIME_ENCODE_TABLE[B and $3F];
B := B shr 6;
OutPtr^.B3 := MIME_ENCODE_TABLE[B and $3F];
B := B shr 6;
OutPtr^.B2 := MIME_ENCODE_TABLE[B and $3F];
B := B shr 6;
OutPtr^.B1 := MIME_ENCODE_TABLE[B];
Inc(OutPtr);
end;
{ End of data & padding. }
case InputByteCount - OuterLimit of
1:
begin
B := InPtr^.B1;
B := B shl 4;
OutPtr.B2 := MIME_ENCODE_TABLE[B and $3F];
B := B shr 6;
OutPtr.B1 := MIME_ENCODE_TABLE[B];
OutPtr.B3 := MIME_PAD_CHAR; { Pad remaining 2 bytes. }
OutPtr.B4 := MIME_PAD_CHAR;
end;
2:
begin
B := InPtr^.B1;
B := B shl 8;
B := B or InPtr^.B2;
B := B shl 2;
OutPtr.B3 := MIME_ENCODE_TABLE[B and $3F];
B := B shr 6;
OutPtr.B2 := MIME_ENCODE_TABLE[B and $3F];
B := B shr 6;
OutPtr.B1 := MIME_ENCODE_TABLE[B];
OutPtr.B4 := MIME_PAD_CHAR; { Pad remaining byte. }
end;
end;
end;
procedure MimeEncode(const InputBuffer; const InputByteCount: SizeInt; out OutputBuffer);
var
IDelta, ODelta: SizeInt;
I, O: PByte;
begin
MimeEncodeFullLines(InputBuffer, InputByteCount, OutputBuffer);
IDelta := InputByteCount div MIME_DECODED_LINE_BREAK; // Number of lines processed so far.
ODelta := IDelta * (MIME_ENCODED_LINE_BREAK + 2);
IDelta := IDelta * MIME_DECODED_LINE_BREAK;
I := @InputBuffer;
Inc(I, IDelta);
O := @OutputBuffer;
Inc(O, ODelta);
MimeEncodeNoCRLF(I^, InputByteCount - IDelta, O^);
end;
function MimeDecodePartial(const InputBuffer; const InputByteCount: SizeInt; out OutputBuffer;
var ByteBuffer: Cardinal; var ByteBufferSpace: Cardinal): SizeInt;
var
LByteBuffer, LByteBufferSpace, C: Cardinal;
InPtr, OuterLimit: PByte;
OutPtr: PByte3;
begin
if InputByteCount > 0 then
begin
InPtr := @InputBuffer;
OuterLimit := Pointer(TJclAddr(InPtr) + TJclAddr(InputByteCount));
OutPtr := @OutputBuffer;
LByteBuffer := ByteBuffer;
LByteBufferSpace := ByteBufferSpace;
while InPtr <> OuterLimit do
begin
{ Read from InputBuffer. }
C := MIME_DECODE_TABLE[InPtr^];
Inc(InPtr);
if C = $FF then
Continue;
LByteBuffer := LByteBuffer shl 6;
LByteBuffer := LByteBuffer or C;
Dec(LByteBufferSpace);
{ Have we read 4 bytes from InputBuffer? }
if LByteBufferSpace <> 0 then
Continue;
{ Write 3 bytes to OutputBuffer (in reverse order). }
OutPtr^.B3 := Byte(LByteBuffer);
LByteBuffer := LByteBuffer shr 8;
OutPtr^.B2 := Byte(LByteBuffer);
LByteBuffer := LByteBuffer shr 8;
OutPtr^.B1 := Byte(LByteBuffer);
LByteBuffer := 0;
Inc(OutPtr);
LByteBufferSpace := 4;
end;
ByteBuffer := LByteBuffer;
ByteBufferSpace := LByteBufferSpace;
Result := SizeInt(TJclAddr(OutPtr) - TJclAddr(@OutputBuffer));
end
else
Result := 0;
end;
function MimeDecodePartialEnd(out OutputBuffer; const ByteBuffer: Cardinal;
const ByteBufferSpace: Cardinal): SizeInt;
var
LByteBuffer: Cardinal;
begin
case ByteBufferSpace of
1:
begin
LByteBuffer := ByteBuffer shr 2;
PByte3(@OutputBuffer)^.B2 := Byte(LByteBuffer);
LByteBuffer := LByteBuffer shr 8;
PByte3(@OutputBuffer)^.B1 := Byte(LByteBuffer);
Result := 2;
end;
2:
begin
LByteBuffer := ByteBuffer shr 4;
PByte3(@OutputBuffer)^.B1 := Byte(LByteBuffer);
Result := 1;
end;
else
Result := 0;
end;
end;
function MimeEncodeString(const S: AnsiString): AnsiString;
var
L: SizeInt;
begin
if S <> '' then
begin
L := Length(S);
SetLength(Result, MimeEncodedSize(L));
MimeEncode(PAnsiChar(S)^, L, PAnsiChar(Result)^);
end
else
Result := '';
end;
function MimeDecodedSize(const InputSize: SizeInt): SizeInt;
begin
Result := (InputSize + 3) div 4 * 3;
end;
function MimeDecodeString(const S: AnsiString): AnsiString;
var
ByteBuffer, ByteBufferSpace: Cardinal;
L: SizeInt;
P, R: PAnsiChar;
begin
if S <> '' then
begin
L := Length(S);
SetLength(Result, MimeDecodedSize(L));
ByteBuffer := 0;
ByteBufferSpace := 4;
P := PAnsiChar(S);
R := PAnsiChar(Result);
L := MimeDecodePartial(P^, L, R^, ByteBuffer, ByteBufferSpace);
Inc(R, L);
Inc(L, MimeDecodePartialEnd(R^, ByteBuffer, ByteBufferSpace));
SetLength(Result, L);
end
else
Result := '';
end;
procedure MimeEncodeStream(const InputStream: TStream; const OutputStream: TStream);
var
InputBuffer: array [0..MIME_BUFFER_SIZE - 1] of Byte;
OutputBuffer: array [0..(MIME_BUFFER_SIZE + 2) div 3 * 4 + MIME_BUFFER_SIZE div MIME_DECODED_LINE_BREAK * 2 - 1] of Byte;
BytesRead: SizeInt;
IDelta, ODelta: SizeInt;
I, O: PByte;
begin
InputBuffer[0] := 0;
BytesRead := InputStream.Read(InputBuffer, SizeOf(InputBuffer));
while BytesRead = Length(InputBuffer) do
begin
MimeEncodeFullLines(InputBuffer, Length(InputBuffer), OutputBuffer);
OutputStream.Write(OutputBuffer, Length(OutputBuffer));
BytesRead := InputStream.Read(InputBuffer, Length(InputBuffer));
end;
MimeEncodeFullLines(InputBuffer, BytesRead, OutputBuffer);
IDelta := BytesRead div MIME_DECODED_LINE_BREAK; // Number of lines processed.
ODelta := IDelta * (MIME_ENCODED_LINE_BREAK + 2);
IDelta := IDelta * MIME_DECODED_LINE_BREAK;
I := @InputBuffer;
Inc(I, IDelta);
O := @OutputBuffer;
Inc(O, ODelta);
MimeEncodeNoCRLF(I^, BytesRead - IDelta, O^);
OutputStream.Write(OutputBuffer, MimeEncodedSize(BytesRead));
end;
procedure MimeDecodeStream(const InputStream: TStream; const OutputStream: TStream);
var
ByteBuffer, ByteBufferSpace: Cardinal;
InputBuffer: array [0..MIME_BUFFER_SIZE - 1] of Byte;
OutputBuffer: array [0..(MIME_BUFFER_SIZE + 3) div 4 * 3 - 1] of Byte;
BytesRead: SizeInt;
begin
ByteBuffer := 0;
ByteBufferSpace := 4;
InputBuffer[0] := 0;
BytesRead := InputStream.Read(InputBuffer, SizeOf(InputBuffer));
while BytesRead > 0 do
begin
OutputStream.Write(OutputBuffer, MimeDecodePartial(InputBuffer, BytesRead, OutputBuffer, ByteBuffer, ByteBufferSpace));
BytesRead := InputStream.Read(InputBuffer, Length(InputBuffer));
end;
OutputStream.Write(OutputBuffer, MimeDecodePartialEnd(OutputBuffer, ByteBuffer, ByteBufferSpace));
end;
{ TXSDValidateStrictResult }
destructor TXSDValidateStrictResult.Destroy;
begin
FreeAndNil(FMissingAttributes);
FreeAndNil(FMissingElements);
inherited Destroy;
end;
procedure TXSDValidateStrictResult.MissingElement(AParent: IXMLNode; const AName: string);
begin
MissingElements.Add(GetNodeTree(AParent, AName));
end;
procedure TXSDValidateStrictResult.MissingAttribute(AParent: IXMLNode; const AName: string);
begin
MissingAttributes.Add(GetNodeTree(AParent, AName));
end;
procedure TXSDValidateStrictResult.RaiseResult;
var
msg: string;
procedure AddList(AList: TStrings; const ATitle: string);
var
itemIndex: Integer;
begin
if not Assigned(AList) then
exit;
msg := msg + ATitle + #13#10;
for itemIndex := 0 to Pred(AList.Count) do
msg := msg + '- ' + AList[itemIndex] + #13#10;
msg := msg + #13#10;
end;
begin
msg := '';
AddList(FMissingElements, 'Missing elements:');
AddList(FMissingAttributes, 'Missing attributes:');
if Length(msg) > 0 then
raise EXSDValidationError.Create('XSD validation failed.'#13#10 + Trim(msg));
end;
function TXSDValidateStrictResult.GetMissingElements: TStrings;
begin
if not Assigned(FMissingElements) then
FMissingElements := TStringList.Create;
Result := FMissingElements;
end;
function TXSDValidateStrictResult.GetNodeTree(AParent: IXMLNode; const AName: string): string;
function GetNodeIndex(ANodeCollection: IXMLNodeCollection; ANode: IXMLNode): string;
var
nodeIndex: Integer;
begin
Result := '?';
for nodeIndex := 0 to Pred(ANodeCollection.Count) do
if ANodeCollection[nodeIndex] = ANode then
begin
Result := IntToStr(nodeIndex);
break;
end;
end;
var
node: IXMLNode;
nodeCollection: IXMLNodeCollection;
begin
Result := '';
node := AParent;
while Assigned(node) and Assigned(node.ParentNode) do
begin
if Length(Result) > 0 then
Result := '.' + Result;
if Supports(node.ParentNode, IXMLNodeCollection, nodeCollection) then
Result := Result + '[' + GetNodeIndex(nodeCollection, node) + ']';
Result := node.NodeName + Result;
node := node.ParentNode;
end;
if Length(Result) > 0 then
Result := Result + '.';
Result := Result + AName;
end;
function TXSDValidateStrictResult.GetMissingAttributes: TStrings;
begin
if not Assigned(FMissingAttributes) then
FMissingAttributes := TStringList.Create;
Result := FMissingAttributes;
end;
end.
|
unit IdTunnelCommon;
{*
Indy Tunnel components module
Copyright (C) 1999, 2000, 2001 Gregor Ibic (gregor.ibic@intelicom.si)
Intelicom d.o.o., www.intelicom.si
This component is published under same license like Indy package.
This package is a TCP Tunnel implementation written
by Gregor Ibic (gregor.ibic@intelicom.si).
This notice may not be removed or altered from any source
distribution.
// MAJOR CHANGES
05-January-20001
GI: Major code reorganization and polishing
31-May-2000
GI TunnelHeaders eliminated. Some other code jugling.
29-May-2000
GI Components split in several files to be more compliant
with Indy coding standards.
It consists of:
- IdTunnelHeaders
- IdTunnelCommon
- IdTunnelMaster
- IdTunnelSlave
24-May-2000
GI: Turbo translation mode finished (01:24). It works!
Will draw icons in the morning.
23-May-2000
GI: Turbo translation mode to Indy standard started by
Gregor Ibic (hehe) (now is 23:15)
*}
interface
uses
SysUtils, Classes, SyncObjs,
IdException,
IdStack,
IdCoder, IdResourceStrings,
IdTCPServer;
const
BUFFERLEN = $4000;
// Statistics constants
NumberOfConnectionsType = 1;
NumberOfPacketsType = 2;
CompressionRatioType = 3;
CompressedBytesType = 4;
BytesReadType = 5;
BytesWriteType = 6;
NumberOfClientsType = 7;
NumberOfSlavesType = 8;
NumberOfServicesType = 9;
// Message types
tmError = 0;
tmData = 1;
tmDisconnect = 2;
tmConnect = 3;
tmCustom = 99;
type
TIdStatisticsOperation = (soIncrease,
soDecrease
);
TIdHeader = record
CRC16: Word;
MsgType: Word;
MsgLen: Word;
UserId: Word;
Port: Word;
IpAddr: TIdInAddr;
end;
TIdCoderCRC16 = class(TIdCoder)
private
FSum: Word;
FCheckSumSize: Integer;
FName: string;
function GetString: string;
function GetTheByte(Index: Integer): Byte; virtual;
protected
function GetByte(Index: Integer): Byte;
procedure SetCheckSum(Value: Word);
public
constructor Create(AOwner: TComponent); override;
procedure Reset; override;
procedure Process(const Data; Size: Integer);
property Sum: Word read FSum;
property Name: string read FName;
property Size: Integer read FCheckSumSize;
property Bytes[Index: Integer]: Byte read GetTheByte;
property AsString: string read GetString;
function CalcCRC16(var Buffer; Length: LongInt): Word;
end;
TReceiver = class(TObject)
private
fiPrenosLen: LongInt;
fiMsgLen: LongInt;
fsData: string;
fbNewMessage: Boolean;
fCRCFailed: Boolean;
Locker: TCriticalSection;
CRCCalculator: TIdCoderCRC16;
function FNewMessage: Boolean;
procedure SetData(const Value: string);
public
pBuffer: PChar;
HeaderLen: Integer;
Header: TIdHeader;
MsgLen: Word;
TypeDetected: Boolean;
Msg: PChar;
property Data: string read fsData write SetData;
property NewMessage: Boolean read FNewMessage;
property CRCFailed: Boolean read fCRCFailed;
procedure ShiftData;
constructor Create;
destructor Destroy; override;
end;
TSender = class(TObject)
public
Header: TIdHeader;
DataLen: Word;
HeaderLen: Integer;
pMsg: PChar;
Locker: TCriticalSection;
CRCCalculator: TIdCoderCRC16;
public
Msg: string;
procedure PrepareMsg(var Header: TIdHeader;
buffer: PChar; buflen: Integer);
constructor Create;
destructor Destroy; override;
end;
TLogger = class(TObject)
private
OnlyOneThread: TCriticalSection;
fLogFile: TextFile;
fbActive: Boolean;
public
property Active: Boolean read fbActive default False;
procedure LogEvent(Msg: string);
constructor Create(LogFileName: string);
destructor Destroy; override;
end;
TSendMsgEvent = procedure(Thread: TIdPeerThread; var CustomMsg: string) of
object;
TSendTrnEvent = procedure(Thread: TIdPeerThread; var Header: TIdHeader; var
CustomMsg: string) of object;
TSendTrnEventC = procedure(var Header: TIdHeader; var CustomMsg: string) of
object;
TTunnelEventC = procedure(Receiver: TReceiver) of object;
TSendMsgEventC = procedure(var CustomMsg: string) of object;
EIdTunnelException = class(EIdException);
EIdTunnelTransformErrorBeforeSend = class(EIdTunnelException);
EIdTunnelTransformError = class(EIdTunnelException);
EIdTunnelConnectToMasterFailed = class(EIdTunnelException);
EIdTunnelDontAllowConnections = class(EIdTunnelException);
EIdTunnelCRCFailed = class(EIdTunnelException);
EIdTunnelMessageTypeRecognitionError = class(EIdTunnelException);
EIdTunnelMessageHandlingFailed = class(EIdTunnelException);
EIdTunnelInterpretationOfMessageFailed = class(EIdTunnelException);
EIdTunnelCustomMessageInterpretationFailure = class(EIdTunnelException);
EIdEIdTunnelConnectToMasterFailed = class(EIdTunnelException);
implementation
///////////////////////////////////////////////////////////////////////////////
//
// CRC 16 Class
//
///////////////////////////////////////////////////////////////////////////////
const
CRC16Table: array[Byte] of Word = (
$0000, $C0C1, $C181, $0140, $C301, $03C0, $0280, $C241, $C601, $06C0, $0780,
$C741, $0500, $C5C1, $C481, $0440, $CC01, $0CC0, $0D80, $CD41, $0F00, $CFC1,
$CE81, $0E40, $0A00, $CAC1, $CB81, $0B40, $C901, $09C0, $0880, $C841, $D801,
$18C0, $1980, $D941, $1B00, $DBC1, $DA81, $1A40, $1E00, $DEC1, $DF81, $1F40,
$DD01, $1DC0, $1C80, $DC41, $1400, $D4C1, $D581, $1540, $D701, $17C0, $1680,
$D641, $D201, $12C0, $1380, $D341, $1100, $D1C1, $D081, $1040, $F001, $30C0,
$3180, $F141, $3300, $F3C1, $F281, $3240, $3600, $F6C1, $F781, $3740, $F501,
$35C0, $3480, $F441, $3C00, $FCC1, $FD81, $3D40, $FF01, $3FC0, $3E80, $FE41,
$FA01, $3AC0, $3B80, $FB41, $3900, $F9C1, $F881, $3840, $2800, $E8C1, $E981,
$2940, $EB01, $2BC0, $2A80, $EA41, $EE01, $2EC0, $2F80, $EF41, $2D00, $EDC1,
$EC81, $2C40, $E401, $24C0, $2580, $E541, $2700, $E7C1, $E681, $2640, $2200,
$E2C1, $E381, $2340, $E101, $21C0, $2080, $E041, $A001, $60C0, $6180, $A141,
$6300, $A3C1, $A281, $6240, $6600, $A6C1, $A781, $6740, $A501, $65C0, $6480,
$A441, $6C00, $ACC1, $AD81, $6D40, $AF01, $6FC0, $6E80, $AE41, $AA01, $6AC0,
$6B80, $AB41, $6900, $A9C1, $A881, $6840, $7800, $B8C1, $B981, $7940, $BB01,
$7BC0, $7A80, $BA41, $BE01, $7EC0, $7F80, $BF41, $7D00, $BDC1, $BC81, $7C40,
$B401, $74C0, $7580, $B541, $7700, $B7C1, $B681, $7640, $7200, $B2C1, $B381,
$7340, $B101, $71C0, $7080, $B041, $5000, $90C1, $9181, $5140, $9301, $53C0,
$5280, $9241, $9601, $56C0, $5780, $9741, $5500, $95C1, $9481, $5440, $9C01,
$5CC0, $5D80, $9D41, $5F00, $9FC1, $9E81, $5E40, $5A00, $9AC1, $9B81, $5B40,
$9901, $59C0, $5880, $9841, $8801, $48C0, $4980, $8941, $4B00, $8BC1, $8A81,
$4A40, $4E00, $8EC1, $8F81, $4F40, $8D01, $4DC0, $4C80, $8C41, $4400, $84C1,
$8581, $4540, $8701, $47C0, $4680, $8641, $8201, $42C0, $4380, $8341, $4100,
$81C1, $8081, $4040
);
constructor TIdCoderCRC16.Create;
begin
inherited Create(AOwner);
end;
function TIdCoderCRC16.CalcCRC16(var Buffer; Length: LongInt): Word;
begin
Reset;
Process(Buffer, Length);
Result := Sum;
end;
procedure TIdCoderCRC16.Process(const Data; Size: Integer);
var
S: Word;
i: Integer;
P: PChar;
begin
S := Sum;
P := @Data;
for i := 1 to Size do
S := CRC16Table[(Ord(P[i - 1]) xor S) and 255] xor (S shr 8);
SetCheckSum(S);
end;
procedure TIdCoderCRC16.Reset;
begin
SetCheckSum(0);
end;
procedure TIdCoderCRC16.SetCheckSum(Value: Word);
begin
FSum := Value;
end;
function TIdCoderCRC16.GetString: string;
const
HexDigits: array[0..15] of Char = '0123456789abcdef';
var
i: Integer;
B: Byte;
begin
Result := '';
for i := 1 to Size do
begin
B := Bytes[i - 1];
Result := Result + HexDigits[B shr 4] + HexDigits[B and 15];
end;
end;
function TIdCoderCRC16.GetTheByte(Index: Integer): Byte;
begin
if (Index < 0) or (Index >= FCheckSumSize) then
raise ERangeError.CreateFmt(RSTunnelGetByteRange, [ClassName, 0, Size - 1])
else
Result := GetByte(Index);
end;
function TIdCoderCRC16.GetByte(Index: Integer): Byte;
begin
case Index of
0: Result := (FSum shr 8);
1: Result := FSum and 255;
else
Result := 0;
end;
end;
constructor TSender.Create;
begin
inherited;
Locker := TCriticalSection.Create;
CRCCalculator := TIdCoderCRC16.Create(nil);
HeaderLen := SizeOf(TIdHeader);
GetMem(pMsg, BUFFERLEN);
end;
destructor TSender.Destroy;
begin
FreeMem(pMsg, BUFFERLEN);
Locker.Free;
CRCCalculator.Free;
inherited;
end;
procedure TSender.PrepareMsg(var Header: TIdHeader;
buffer: PChar; buflen: Integer);
begin
Locker.Enter;
try
Header.CRC16 := CRCCalculator.CalcCRC16(buffer^, buflen);
Header.MsgLen := Headerlen + bufLen;
Move(Header, pMsg^, Headerlen);
Move(buffer^, (pMsg + Headerlen)^, bufLen);
SetLength(Msg, Header.MsgLen);
SetString(Msg, pMsg, Header.MsgLen);
finally
Locker.Leave;
end;
end;
constructor TReceiver.Create;
begin
inherited;
Locker := TCriticalSection.Create;
CRCCalculator := TIdCoderCRC16.Create(nil);
fiPrenosLen := 0;
fsData := '';
fiMsgLen := 0;
HeaderLen := SizeOf(TIdHeader);
GetMem(pBuffer, BUFFERLEN);
GetMem(Msg, BUFFERLEN);
end;
destructor TReceiver.Destroy;
begin
FreeMem(pBuffer, BUFFERLEN);
FreeMem(Msg, BUFFERLEN);
Locker.Free;
CRCCalculator.Free;
inherited;
end;
function TReceiver.FNewMessage: Boolean;
begin
Result := fbNewMessage;
end;
procedure TReceiver.SetData(const Value: string);
var
CRC16: Word;
begin
Locker.Enter;
try
try
fsData := Value;
fiMsgLen := Length(fsData);
if fiMsgLen > 0 then
begin
Move(fsData[1], (pBuffer + fiPrenosLen)^, fiMsgLen);
fiPrenosLen := fiPrenosLen + fiMsgLen;
if (fiPrenosLen >= HeaderLen) then
begin
Move(pBuffer^, Header, HeaderLen);
TypeDetected := True;
if Header.MsgLen <= fiPrenosLen then
begin
MsgLen := Header.MsgLen - HeaderLen;
Move((pBuffer + HeaderLen)^, Msg^, MsgLen);
CRC16 := CRCCalculator.CalcCRC16(Msg^, MsgLen);
if CRC16 <> Header.CRC16 then
begin
fCRCFailed := True;
end
else
begin
fCRCFailed := False;
end;
fbNewMessage := True;
end
else
begin
fbNewMessage := False;
end;
end
else
begin
TypeDetected := False;
end;
end
else
begin
fbNewMessage := False;
TypeDetected := False;
end;
except
raise;
end;
finally
Locker.Leave;
end;
end;
procedure TReceiver.ShiftData;
var
CRC16: Word;
begin
Locker.Enter;
try
fiPrenosLen := fiPrenosLen - Header.MsgLen;
if fiPrenosLen > 0 then
begin
Move((pBuffer + Header.MsgLen)^, pBuffer^, fiPrenosLen);
end;
if (fiPrenosLen >= HeaderLen) then
begin
Move(pBuffer^, Header, HeaderLen);
TypeDetected := True;
if Header.MsgLen <= fiPrenosLen then
begin
MsgLen := Header.MsgLen - HeaderLen;
Move((pBuffer + HeaderLen)^, Msg^, MsgLen);
CRC16 := CRCCalculator.CalcCRC16(Msg^, MsgLen);
if CRC16 <> Header.CRC16 then
begin
fCRCFailed := True;
end
else
begin
fCRCFailed := False;
end;
fbNewMessage := True;
end
else
begin
fbNewMessage := False;
end;
end
else
begin
TypeDetected := False;
end;
finally
Locker.Leave;
end;
end;
constructor TLogger.Create(LogFileName: string);
begin
fbActive := False;
OnlyOneThread := TCriticalSection.Create;
try
AssignFile(fLogFile, LogFileName);
Rewrite(fLogFile);
fbActive := True;
except
fbActive := False;
end;
end;
destructor TLogger.Destroy;
begin
if fbActive then
CloseFile(fLogFile);
OnlyOneThread.Free;
inherited;
end;
procedure TLogger.LogEvent(Msg: string);
begin
OnlyOneThread.Enter;
try
WriteLn(fLogFile, Msg);
Flush(fLogFile);
finally
OnlyOneThread.Leave;
end;
end;
end.
|
unit employee_c;
{This file was generated on 11 Aug 2000 20:12:57 GMT by version 03.03.03.C1.06}
{of the Inprise VisiBroker idl2pas CORBA IDL compiler. }
{Please do not edit the contents of this file. You should instead edit and }
{recompile the original IDL which was located in the file employee.idl. }
{Delphi Pascal unit : employee_c }
{derived from IDL module : default }
interface
uses
CORBA,
employee_i;
type
TEmployeeHelper = class;
TEmployeeStub = class;
TEmployeeHelper = class
class procedure Insert (var _A: CORBA.Any; const _Value : employee_i.Employee);
class function Extract(var _A: CORBA.Any) : employee_i.Employee;
class function TypeCode : CORBA.TypeCode;
class function RepositoryId : string;
class function Read (const _Input : CORBA.InputStream) : employee_i.Employee;
class procedure Write(const _Output : CORBA.OutputStream; const _Value : employee_i.Employee);
class function Narrow(const _Obj : CORBA.CORBAObject; _IsA : Boolean = False) : employee_i.Employee;
class function Bind(const _InstanceName : string = ''; _HostName : string = '') : employee_i.Employee; overload;
class function Bind(_Options : BindOptions; const _InstanceName : string = ''; _HostName: string = '') : employee_i.Employee; overload;
end;
TEmployeeStub = class(CORBA.TCORBAObject, employee_i.Employee)
public
function getEmployeesByName ( const name : AnsiString): ANY; virtual;
function getEmployeesByNameXML ( const name : AnsiString): AnsiString; virtual;
end;
implementation
class procedure TEmployeeHelper.Insert(var _A : CORBA.Any; const _Value : employee_i.Employee);
begin
_A := Orb.MakeObjectRef( TEmployeeHelper.TypeCode, _Value as CORBA.CORBAObject);
end;
class function TEmployeeHelper.Extract(var _A : CORBA.Any): employee_i.Employee;
var
_obj : Corba.CorbaObject;
begin
_obj := Orb.GetObjectRef(_A);
Result := TEmployeeHelper.Narrow(_obj, True);
end;
class function TEmployeeHelper.TypeCode : CORBA.TypeCode;
begin
Result := ORB.CreateInterfaceTC(RepositoryId, 'Employee');
end;
class function TEmployeeHelper.RepositoryId : string;
begin
Result := 'IDL:Employee:1.0';
end;
class function TEmployeeHelper.Read(const _Input : CORBA.InputStream) : employee_i.Employee;
var
_Obj : CORBA.CORBAObject;
begin
_Input.ReadObject(_Obj);
Result := Narrow(_Obj, True)
end;
class procedure TEmployeeHelper.Write(const _Output : CORBA.OutputStream; const _Value : employee_i.Employee);
begin
_Output.WriteObject(_Value as CORBA.CORBAObject);
end;
class function TEmployeeHelper.Narrow(const _Obj : CORBA.CORBAObject; _IsA : Boolean) : employee_i.Employee;
begin
Result := nil;
if (_Obj = nil) or (_Obj.QueryInterface(employee_i.Employee, Result) = 0) then
exit;
if _IsA and _Obj._IsA(RepositoryId) then
Result := TEmployeeStub.Create(_Obj);
end;
class function TEmployeeHelper.Bind(const _InstanceName : string = ''; _HostName: string = '') : employee_i.Employee;
begin
Result := Narrow(ORB.bind(RepositoryId, _InstanceName, _HostName), True);
end;
class function TEmployeeHelper.Bind(_Options : BindOptions; const _InstanceName : string = ''; _HostName : string = '') : employee_i.Employee;
begin
Result := Narrow(ORB.bind(RepositoryId, _Options, _InstanceName, _HostName), True);
end;
function TEmployeeStub.getEmployeesByName ( const name : AnsiString): ANY;
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('getEmployeesByName',True, _Output);
_Output.WriteString(name);
inherited _Invoke(_Output, _Input);
_Input.ReadAny(Result);
end;
function TEmployeeStub.getEmployeesByNameXML ( const name : AnsiString): AnsiString;
var
_Output: CORBA.OutputStream;
_Input : CORBA.InputStream;
begin
inherited _CreateRequest('getEmployeesByNameXML',True, _Output);
_Output.WriteString(name);
inherited _Invoke(_Output, _Input);
_Input.ReadString(Result);
end;
initialization
end. |
// ==========================================================================
//
// Copyright(c) 2012-2014 Embarcadero Technologies, Inc.
//
// ==========================================================================
//
// Delphi-C++ Library Bridge
// Interface for library FlatBox2D
//
unit Box2D.Dynamics;
interface
uses
Box2D.Collision,
Box2D.Common,
Box2DTypes;
const
b2_minPulleyLength = 2.000000;
type
{$MinEnumSize 4}
b2BodyType = (b2_staticBody = 0, b2_kinematicBody = 1, b2_dynamicBody = 2);
{$MinEnumSize 1}
Pb2BodyType = ^b2BodyType;
{$MinEnumSize 4}
b2JointType = (e_unknownJoint = 0, e_revoluteJoint = 1, e_prismaticJoint = 2, e_distanceJoint = 3, e_pulleyJoint = 4, e_mouseJoint = 5, e_gearJoint = 6, e_wheelJoint = 7, e_weldJoint = 8, e_frictionJoint = 9, e_ropeJoint = 10, e_motorJoint = 11);
{$MinEnumSize 1}
Pb2JointType = ^b2JointType;
{$MinEnumSize 4}
b2LimitState = (e_inactiveLimit = 0, e_atLowerLimit = 1, e_atUpperLimit = 2, e_equalLimits = 3);
{$MinEnumSize 1}
Pb2LimitState = ^b2LimitState;
b2JointHandle = THandle;
Pb2JointHandle = ^b2JointHandle;
b2ContactHandle = THandle;
Pb2ContactHandle = ^b2ContactHandle;
b2WorldHandle = THandle;
Pb2WorldHandle = ^b2WorldHandle;
b2BodyHandle = THandle;
Pb2BodyHandle = ^b2BodyHandle;
b2ContactFilterHandle = THandle;
Pb2ContactFilterHandle = ^b2ContactFilterHandle;
b2ContactListenerHandle = THandle;
Pb2ContactListenerHandle = ^b2ContactListenerHandle;
b2ContactManagerHandle = THandle;
Pb2ContactManagerHandle = ^b2ContactManagerHandle;
b2IslandHandle = THandle;
Pb2IslandHandle = ^b2IslandHandle;
b2DestructionListenerHandle = THandle;
Pb2DestructionListenerHandle = ^b2DestructionListenerHandle;
b2QueryCallbackHandle = THandle;
Pb2QueryCallbackHandle = ^b2QueryCallbackHandle;
b2RayCastCallbackHandle = THandle;
Pb2RayCastCallbackHandle = ^b2RayCastCallbackHandle;
b2ChainAndCircleContactHandle = THandle;
Pb2ChainAndCircleContactHandle = ^b2ChainAndCircleContactHandle;
b2ChainAndPolygonContactHandle = THandle;
Pb2ChainAndPolygonContactHandle = ^b2ChainAndPolygonContactHandle;
b2CircleContactHandle = THandle;
Pb2CircleContactHandle = ^b2CircleContactHandle;
b2ContactSolverHandle = THandle;
Pb2ContactSolverHandle = ^b2ContactSolverHandle;
b2EdgeAndCircleContactHandle = THandle;
Pb2EdgeAndCircleContactHandle = ^b2EdgeAndCircleContactHandle;
b2EdgeAndPolygonContactHandle = THandle;
Pb2EdgeAndPolygonContactHandle = ^b2EdgeAndPolygonContactHandle;
b2PolygonAndCircleContactHandle = THandle;
Pb2PolygonAndCircleContactHandle = ^b2PolygonAndCircleContactHandle;
b2PolygonContactHandle = THandle;
Pb2PolygonContactHandle = ^b2PolygonContactHandle;
b2DistanceJointHandle = THandle;
Pb2DistanceJointHandle = ^b2DistanceJointHandle;
b2FrictionJointHandle = THandle;
Pb2FrictionJointHandle = ^b2FrictionJointHandle;
b2GearJointHandle = THandle;
Pb2GearJointHandle = ^b2GearJointHandle;
b2MotorJointHandle = THandle;
Pb2MotorJointHandle = ^b2MotorJointHandle;
b2MouseJointHandle = THandle;
Pb2MouseJointHandle = ^b2MouseJointHandle;
b2PrismaticJointHandle = THandle;
Pb2PrismaticJointHandle = ^b2PrismaticJointHandle;
b2PulleyJointHandle = THandle;
Pb2PulleyJointHandle = ^b2PulleyJointHandle;
b2RevoluteJointHandle = THandle;
Pb2RevoluteJointHandle = ^b2RevoluteJointHandle;
b2RopeJointHandle = THandle;
Pb2RopeJointHandle = ^b2RopeJointHandle;
b2WeldJointHandle = THandle;
Pb2WeldJointHandle = ^b2WeldJointHandle;
b2WheelJointHandle = THandle;
Pb2WheelJointHandle = ^b2WheelJointHandle;
Pb2Fixture = ^b2Fixture;
PPb2Fixture = ^Pb2Fixture;
Pb2FixtureDef = ^b2FixtureDef;
PPb2FixtureDef = ^Pb2FixtureDef;
Pb2JointEdge = ^b2JointEdge;
PPb2JointEdge = ^Pb2JointEdge;
Pb2ContactEdge = ^b2ContactEdge;
PPb2ContactEdge = ^Pb2ContactEdge;
Pb2BodyDef = ^b2BodyDef;
PPb2BodyDef = ^Pb2BodyDef;
Pb2Filter = ^b2Filter;
PPb2Filter = ^Pb2Filter;
Pb2FixtureProxy = ^b2FixtureProxy;
PPb2FixtureProxy = ^Pb2FixtureProxy;
Pb2Profile = ^b2Profile;
PPb2Profile = ^Pb2Profile;
Pb2TimeStep = ^b2TimeStep;
PPb2TimeStep = ^Pb2TimeStep;
Pb2Position = ^b2Position;
PPb2Position = ^Pb2Position;
Pb2Velocity = ^b2Velocity;
PPb2Velocity = ^Pb2Velocity;
Pb2SolverData = ^b2SolverData;
PPb2SolverData = ^Pb2SolverData;
Pb2ContactVelocityConstraint = ^b2ContactVelocityConstraint;
PPb2ContactVelocityConstraint = ^Pb2ContactVelocityConstraint;
Pb2ContactImpulse = ^b2ContactImpulse;
PPb2ContactImpulse = ^Pb2ContactImpulse;
Pb2JointDef = ^b2JointDef;
PPb2JointDef = ^Pb2JointDef;
b2ContactCreateFcn = function(param1: Pb2Fixture; param2: Integer; param3: Pb2Fixture; param4: Integer; param5: b2BlockAllocatorHandle): b2ContactHandle; stdcall;
b2ContactDestroyFcn = procedure(param1: b2ContactHandle; param2: b2BlockAllocatorHandle); stdcall;
Pb2ContactRegister = ^b2ContactRegister;
PPb2ContactRegister = ^Pb2ContactRegister;
Pb2VelocityConstraintPoint = ^b2VelocityConstraintPoint;
PPb2VelocityConstraintPoint = ^Pb2VelocityConstraintPoint;
Pb2ContactSolverDef = ^b2ContactSolverDef;
PPb2ContactSolverDef = ^Pb2ContactSolverDef;
Pb2Jacobian = ^b2Jacobian;
PPb2Jacobian = ^Pb2Jacobian;
Pb2DistanceJointDef = ^b2DistanceJointDef;
PPb2DistanceJointDef = ^Pb2DistanceJointDef;
Pb2FrictionJointDef = ^b2FrictionJointDef;
PPb2FrictionJointDef = ^Pb2FrictionJointDef;
Pb2GearJointDef = ^b2GearJointDef;
PPb2GearJointDef = ^Pb2GearJointDef;
Pb2MotorJointDef = ^b2MotorJointDef;
PPb2MotorJointDef = ^Pb2MotorJointDef;
Pb2MouseJointDef = ^b2MouseJointDef;
PPb2MouseJointDef = ^Pb2MouseJointDef;
Pb2PrismaticJointDef = ^b2PrismaticJointDef;
PPb2PrismaticJointDef = ^Pb2PrismaticJointDef;
Pb2PulleyJointDef = ^b2PulleyJointDef;
PPb2PulleyJointDef = ^Pb2PulleyJointDef;
Pb2RevoluteJointDef = ^b2RevoluteJointDef;
PPb2RevoluteJointDef = ^Pb2RevoluteJointDef;
Pb2RopeJointDef = ^b2RopeJointDef;
PPb2RopeJointDef = ^Pb2RopeJointDef;
Pb2WeldJointDef = ^b2WeldJointDef;
PPb2WeldJointDef = ^Pb2WeldJointDef;
Pb2WheelJointDef = ^b2WheelJointDef;
PPb2WheelJointDef = ^Pb2WheelJointDef;
{ ===== Records ===== }
{ A body definition holds all the data needed to construct a rigid body.
You can safely re-use body definitions. Shapes are added to a body after construction.}
b2BodyDef = record
&type: b2BodyType; { The body type: static, kinematic, or dynamic.
Note: if a dynamic body would have zero mass, the mass is set to one.}
position: b2Vec2; { The world position of the body. Avoid creating bodies at the origin
since this can lead to many overlapping shapes.}
angle: Single; { The world angle of the body in radians.}
linearVelocity: b2Vec2; { The linear velocity of the body's origin in world co-ordinates.}
angularVelocity: Single; { The angular velocity of the body.}
linearDamping: Single; { Linear damping is use to reduce the linear velocity. The damping parameter
can be larger than 1.0f but the damping effect becomes sensitive to the
time step when the damping parameter is large.}
angularDamping: Single; { Angular damping is use to reduce the angular velocity. The damping parameter
can be larger than 1.0f but the damping effect becomes sensitive to the
time step when the damping parameter is large.}
allowSleep: Boolean; { Set this flag to false if this body should never fall asleep. Note that
this increases CPU usage.}
awake: Boolean; { Is this body initially awake or sleeping?}
fixedRotation: Boolean; { Should this body be prevented from rotating? Useful for characters.}
bullet: Boolean; { Is this a fast moving body that should be prevented from tunneling through
other moving bodies? Note that all bodies are prevented from tunneling through
kinematic and static bodies. This setting is only considered on dynamic bodies.
@warning You should use this flag sparingly since it increases processing time.}
active: Boolean; { Does this body start out active?}
userData: Pointer; { Use this to store application specific body data.}
gravityScale: Single; { Scale the gravity applied to this body.}
class function Create: b2BodyDef; static; cdecl;
end;
{ A rigid body. These are created via b2World::CreateBody.}
b2BodyWrapper = record
FHandle: b2BodyHandle;
class operator Implicit(handle: b2BodyHandle): b2BodyWrapper; overload;
class operator Implicit(wrapper: b2BodyWrapper): b2BodyHandle; overload;
{ Creates a fixture and attach it to this body. Use this function if you need
to set some fixture parameters, like friction. Otherwise you can create the
fixture directly from a shape.
If the density is non-zero, this function automatically updates the mass of the body.
Contacts are not created until the next time step.
@param def the fixture definition.
@warning This function is locked during callbacks.}
function CreateFixture(def: Pb2FixtureDef): Pb2Fixture; overload; cdecl;
{ Creates a fixture from a shape and attach it to this body.
This is a convenience function. Use b2FixtureDef if you need to set parameters
like friction, restitution, user data, or filtering.
If the density is non-zero, this function automatically updates the mass of the body.
@param shape the shape to be cloned.
@param density the shape density (set to zero for static bodies).
@warning This function is locked during callbacks.}
function CreateFixture(shape: b2ShapeHandle; density: Single): Pb2Fixture; overload; cdecl;
{ Destroy a fixture. This removes the fixture from the broad-phase and
destroys all contacts associated with this fixture. This will
automatically adjust the mass of the body if the body is dynamic and the
fixture has positive density.
All fixtures attached to a body are implicitly destroyed when the body is destroyed.
@param fixture the fixture to be removed.
@warning This function is locked during callbacks.}
procedure DestroyFixture(fixture: Pb2Fixture); cdecl;
{ Set the position of the body's origin and rotation.
Manipulating a body's transform may cause non-physical behavior.
Note: contacts are updated on the next call to b2World::Step.
@param position the world position of the body's local origin.
@param angle the world rotation in radians.}
procedure SetTransform(const [ref] position: b2Vec2; angle: Single); cdecl;
{ Get the body transform for the body's origin.
@return the world transform of the body's origin.}
function GetTransform: Pb2Transform; cdecl;
{ Get the world body origin position.
@return the world position of the body's origin.}
function GetPosition: Pb2Vec2; cdecl;
{ Get the angle in radians.
@return the current world rotation angle in radians.}
function GetAngle: Single; cdecl;
{ Get the world position of the center of mass.}
function GetWorldCenter: Pb2Vec2; cdecl;
{ Get the local position of the center of mass.}
function GetLocalCenter: Pb2Vec2; cdecl;
{ Set the linear velocity of the center of mass.
@param v the new linear velocity of the center of mass.}
procedure SetLinearVelocity(const [ref] v: b2Vec2); cdecl;
{ Get the linear velocity of the center of mass.
@return the linear velocity of the center of mass.}
function GetLinearVelocity: Pb2Vec2; cdecl;
{ Set the angular velocity.
@param omega the new angular velocity in radians/second.}
procedure SetAngularVelocity(omega: Single); cdecl;
{ Get the angular velocity.
@return the angular velocity in radians/second.}
function GetAngularVelocity: Single; cdecl;
{ Apply a force at a world point. If the force is not
applied at the center of mass, it will generate a torque and
affect the angular velocity. This wakes up the body.
@param force the world force vector, usually in Newtons (N).
@param point the world position of the point of application.
@param wake also wake up the body}
procedure ApplyForce(const [ref] force: b2Vec2; const [ref] point: b2Vec2; wake: Boolean); cdecl;
{ Apply a force to the center of mass. This wakes up the body.
@param force the world force vector, usually in Newtons (N).
@param wake also wake up the body}
procedure ApplyForceToCenter(const [ref] force: b2Vec2; wake: Boolean); cdecl;
{ Apply a torque. This affects the angular velocity
without affecting the linear velocity of the center of mass.
This wakes up the body.
@param torque about the z-axis (out of the screen), usually in N-m.
@param wake also wake up the body}
procedure ApplyTorque(torque: Single; wake: Boolean); cdecl;
{ Apply an impulse at a point. This immediately modifies the velocity.
It also modifies the angular velocity if the point of application
is not at the center of mass. This wakes up the body.
@param impulse the world impulse vector, usually in N-seconds or kg-m/s.
@param point the world position of the point of application.
@param wake also wake up the body}
procedure ApplyLinearImpulse(const [ref] impulse: b2Vec2; const [ref] point: b2Vec2; wake: Boolean); cdecl;
{ Apply an angular impulse.
@param impulse the angular impulse in units of kg*m*m/s
@param wake also wake up the body}
procedure ApplyAngularImpulse(impulse: Single; wake: Boolean); cdecl;
{ Get the total mass of the body.
@return the mass, usually in kilograms (kg).}
function GetMass: Single; cdecl;
{ Get the rotational inertia of the body about the local origin.
@return the rotational inertia, usually in kg-m^2.}
function GetInertia: Single; cdecl;
{ Get the mass data of the body.
@return a struct containing the mass, inertia and center of the body.}
procedure GetMassData(data: Pb2MassData); cdecl;
{ Set the mass properties to override the mass properties of the fixtures.
Note that this changes the center of mass position.
Note that creating or destroying fixtures can also alter the mass.
This function has no effect if the body isn't dynamic.
@param massData the mass properties.}
procedure SetMassData(data: Pb2MassData); cdecl;
{ This resets the mass properties to the sum of the mass properties of the fixtures.
This normally does not need to be called unless you called SetMassData to override
the mass and you later want to reset the mass.}
procedure ResetMassData; cdecl;
{ Get the world coordinates of a point given the local coordinates.
@param localPoint a point on the body measured relative the the body's origin.
@return the same point expressed in world coordinates.}
function GetWorldPoint(const [ref] localPoint: b2Vec2): b2Vec2; cdecl;
{ Get the world coordinates of a vector given the local coordinates.
@param localVector a vector fixed in the body.
@return the same vector expressed in world coordinates.}
function GetWorldVector(const [ref] localVector: b2Vec2): b2Vec2; cdecl;
{ Gets a local point relative to the body's origin given a world point.
@param a point in world coordinates.
@return the corresponding local point relative to the body's origin.}
function GetLocalPoint(const [ref] worldPoint: b2Vec2): b2Vec2; cdecl;
{ Gets a local vector given a world vector.
@param a vector in world coordinates.
@return the corresponding local vector.}
function GetLocalVector(const [ref] worldVector: b2Vec2): b2Vec2; cdecl;
{ Get the world linear velocity of a world point attached to this body.
@param a point in world coordinates.
@return the world velocity of a point.}
function GetLinearVelocityFromWorldPoint(const [ref] worldPoint: b2Vec2): b2Vec2; cdecl;
{ Get the world velocity of a local point.
@param a point in local coordinates.
@return the world velocity of a point.}
function GetLinearVelocityFromLocalPoint(const [ref] localPoint: b2Vec2): b2Vec2; cdecl;
{ Get the linear damping of the body.}
function GetLinearDamping: Single; cdecl;
{ Set the linear damping of the body.}
procedure SetLinearDamping(linearDamping: Single); cdecl;
{ Get the angular damping of the body.}
function GetAngularDamping: Single; cdecl;
{ Set the angular damping of the body.}
procedure SetAngularDamping(angularDamping: Single); cdecl;
{ Get the gravity scale of the body.}
function GetGravityScale: Single; cdecl;
{ Set the gravity scale of the body.}
procedure SetGravityScale(scale: Single); cdecl;
{ Set the type of this body. This may alter the mass and velocity.}
procedure SetType(_type: b2BodyType); cdecl;
{ Get the type of this body.}
function GetType: b2BodyType; cdecl;
{ Should this body be treated like a bullet for continuous collision detection?}
procedure SetBullet(flag: Boolean); cdecl;
{ Is this body treated like a bullet for continuous collision detection?}
function IsBullet: Boolean; cdecl;
{ You can disable sleeping on this body. If you disable sleeping, the
body will be woken.}
procedure SetSleepingAllowed(flag: Boolean); cdecl;
{ Is this body allowed to sleep}
function IsSleepingAllowed: Boolean; cdecl;
{ Set the sleep state of the body. A sleeping body has very
low CPU cost.
@param flag set to true to wake the body, false to put it to sleep.}
procedure SetAwake(flag: Boolean); cdecl;
{ Get the sleeping state of this body.
@return true if the body is awake.}
function IsAwake: Boolean; cdecl;
{ Set the active state of the body. An inactive body is not
simulated and cannot be collided with or woken up.
If you pass a flag of true, all fixtures will be added to the
broad-phase.
If you pass a flag of false, all fixtures will be removed from
the broad-phase and all contacts will be destroyed.
Fixtures and joints are otherwise unaffected. You may continue
to create/destroy fixtures and joints on inactive bodies.
Fixtures on an inactive body are implicitly inactive and will
not participate in collisions, ray-casts, or queries.
Joints connected to an inactive body are implicitly inactive.
An inactive body is still owned by a b2World object and remains
in the body list.}
procedure SetActive(flag: Boolean); cdecl;
{ Get the active state of the body.}
function IsActive: Boolean; cdecl;
{ Set this body to have fixed rotation. This causes the mass
to be reset.}
procedure SetFixedRotation(flag: Boolean); cdecl;
{ Does this body have fixed rotation?}
function IsFixedRotation: Boolean; cdecl;
{ Get the list of all fixtures attached to this body.}
function GetFixtureList: Pb2Fixture; cdecl;
{ Get the list of all joints attached to this body.}
function GetJointList: Pb2JointEdge; cdecl;
{ Get the list of all contacts attached to this body.
@warning this list changes during the time step and you may
miss some collisions if you don't use b2ContactListener.}
function GetContactList: Pb2ContactEdge; cdecl;
{ Get the next body in the world's body list.}
function GetNext: b2BodyHandle; cdecl;
{ Get the user data pointer that was provided in the body definition.}
function GetUserData: Pointer; cdecl;
{ Set the user data. Use this to store your application specific data.}
procedure SetUserData(data: Pointer); cdecl;
{ Get the parent world of this body.}
function GetWorld: b2WorldHandle; cdecl;
{ Dump this body to a log file}
procedure Dump; cdecl;
end;
b2ContactManagerWrapper = record
FHandle: b2ContactManagerHandle;
private
function Get_m_broadPhase: b2BroadPhaseHandle; cdecl;
procedure Set_m_broadPhase(aNewValue: b2BroadPhaseHandle); cdecl;
function Get_m_contactList: b2ContactHandle; cdecl;
procedure Set_m_contactList(aNewValue: b2ContactHandle); cdecl;
function Get_m_contactCount: Integer; cdecl;
procedure Set_m_contactCount(aNewValue: Integer); cdecl;
function Get_m_contactFilter: b2ContactFilterHandle; cdecl;
procedure Set_m_contactFilter(aNewValue: b2ContactFilterHandle); cdecl;
function Get_m_contactListener: b2ContactListenerHandle; cdecl;
procedure Set_m_contactListener(aNewValue: b2ContactListenerHandle); cdecl;
function Get_m_allocator: b2BlockAllocatorHandle; cdecl;
procedure Set_m_allocator(aNewValue: b2BlockAllocatorHandle); cdecl;
public
class function Create: b2ContactManagerWrapper; static; cdecl;
procedure Destroy; cdecl;
class operator Implicit(handle: b2ContactManagerHandle): b2ContactManagerWrapper; overload;
class operator Implicit(wrapper: b2ContactManagerWrapper): b2ContactManagerHandle; overload;
procedure AddPair(proxyUserDataA: Pointer; proxyUserDataB: Pointer); cdecl;
procedure FindNewContacts; cdecl;
procedure Destroy_(c: b2ContactHandle); cdecl;
procedure Collide; cdecl;
property m_broadPhase: b2BroadPhaseHandle read Get_m_broadPhase write Set_m_broadPhase;
property m_contactList: b2ContactHandle read Get_m_contactList write Set_m_contactList;
property m_contactCount: Integer read Get_m_contactCount write Set_m_contactCount;
property m_contactFilter: b2ContactFilterHandle read Get_m_contactFilter write Set_m_contactFilter;
property m_contactListener: b2ContactListenerHandle read Get_m_contactListener write Set_m_contactListener;
property m_allocator: b2BlockAllocatorHandle read Get_m_allocator write Set_m_allocator;
end;
{ This holds contact filtering data.}
b2Filter = record
categoryBits: Word; { The collision category bits. Normally you would just set one bit.}
maskBits: Word; { The collision mask bits. This states the categories that this
shape would accept for collision.}
groupIndex: SmallInt; { Collision groups allow a certain group of objects to never collide (negative)
or always collide (positive). Zero means no collision group. Non-zero group
filtering always wins against the mask bits.}
class function Create: b2Filter; static; cdecl;
end;
{ A fixture definition is used to create a fixture. This class defines an
abstract fixture definition. You can reuse fixture definitions safely.}
b2FixtureDef = record
shape: b2ShapeHandle; { The shape, this must be set. The shape will be cloned, so you
can create the shape on the stack.}
userData: Pointer; { Use this to store application specific fixture data.}
friction: Single; { The friction coefficient, usually in the range [0,1].}
restitution: Single; { The restitution (elasticity) usually in the range [0,1].}
density: Single; { The density, usually in kg/m^2.}
isSensor: Boolean; { A sensor shape collects contact information but never generates a collision
response.}
filter: b2Filter; { Contact filtering data.}
class function Create: b2FixtureDef; static; cdecl;
end;
{ This proxy is used internally to connect fixtures to the broad-phase.}
b2FixtureProxy = record
aabb: b2AABB;
fixture: Pb2Fixture;
childIndex: Integer;
proxyId: Integer;
class function Create: b2FixtureProxy; static; cdecl;
end;
{ A fixture is used to attach a shape to a body for collision detection. A fixture
inherits its transform from its parent. Fixtures hold additional non-geometric data
such as friction, collision filters, etc.
Fixtures are created via b2Body::CreateFixture.
@warning you cannot reuse fixtures.}
b2Fixture = record
private
m_density: Single;
m_next: Pb2Fixture;
m_body: b2BodyHandle;
m_shape: b2ShapeHandle;
m_friction: Single;
m_restitution: Single;
m_proxies: Pb2FixtureProxy;
m_proxyCount: Integer;
m_filter: b2Filter;
m_isSensor: Boolean;
m_userData: Pointer;
public
{ Get the type of the child shape. You can use this to down cast to the concrete shape.
@return the shape type.}
function GetType: Integer; cdecl;
{ Get the child shape. You can modify the child shape, however you should not change the
number of vertices because this will crash some collision caching mechanisms.
Manipulating the shape may lead to non-physical behavior.}
function GetShape: b2ShapeHandle; cdecl;
{ Set if this fixture is a sensor.}
procedure SetSensor(sensor: Boolean); cdecl;
{ Is this fixture a sensor (non-solid)?
@return the true if the shape is a sensor.}
function IsSensor: Boolean; cdecl;
{ Set the contact filtering data. This will not update contacts until the next time
step when either parent body is active and awake.
This automatically calls Refilter.}
procedure SetFilterData(const [ref] filter: b2Filter); cdecl;
{ Get the contact filtering data.}
function GetFilterData: Pb2Filter; cdecl;
{ Call this if you want to establish collision that was previously disabled by b2ContactFilter::ShouldCollide.}
procedure Refilter; cdecl;
{ Get the parent body of this fixture. This is NULL if the fixture is not attached.
@return the parent body.}
function GetBody: b2BodyHandle; cdecl;
{ Get the next fixture in the parent body's fixture list.
@return the next shape.}
function GetNext: Pb2Fixture; cdecl;
{ Get the user data that was assigned in the fixture definition. Use this to
store your application specific data.}
function GetUserData: Pointer; cdecl;
{ Set the user data. Use this to store your application specific data.}
procedure SetUserData(data: Pointer); cdecl;
{ Test a point for containment in this fixture.
@param p a point in world coordinates.}
function TestPoint(const [ref] p: b2Vec2): Boolean; cdecl;
{ Cast a ray against this shape.
@param output the ray-cast results.
@param input the ray-cast input parameters.}
function RayCast(output: Pb2RayCastOutput; const [ref] input: b2RayCastInput; childIndex: Integer): Boolean; cdecl;
{ Get the mass data for this fixture. The mass data is based on the density and
the shape. The rotational inertia is about the shape's origin. This operation
may be expensive.}
procedure GetMassData(massData: Pb2MassData); cdecl;
{ Set the density of this fixture. This will _not_ automatically adjust the mass
of the body. You must call b2Body::ResetMassData to update the body's mass.}
procedure SetDensity(density: Single); cdecl;
{ Get the density of this fixture.}
function GetDensity: Single; cdecl;
{ Get the coefficient of friction.}
function GetFriction: Single; cdecl;
{ Set the coefficient of friction. This will _not_ change the friction of
existing contacts.}
procedure SetFriction(friction: Single); cdecl;
{ Get the coefficient of restitution.}
function GetRestitution: Single; cdecl;
{ Set the coefficient of restitution. This will _not_ change the restitution of
existing contacts.}
procedure SetRestitution(restitution: Single); cdecl;
{ Get the fixture's AABB. This AABB may be enlarge and/or stale.
If you need a more accurate AABB, compute it using the shape and
the body transform.}
function GetAABB(childIndex: Integer): Pb2AABB; cdecl;
{ Dump this fixture to the log file.}
procedure Dump(bodyIndex: Integer); cdecl;
end;
{ Profiling data. Times are in milliseconds.}
b2Profile = record
step: Single;
collide: Single;
solve: Single;
solveInit: Single;
solveVelocity: Single;
solvePosition: Single;
broadphase: Single;
solveTOI: Single;
class function Create: b2Profile; static; cdecl;
end;
{ This is an internal structure.}
b2TimeStep = record
dt: Single;
inv_dt: Single;
dtRatio: Single;
velocityIterations: Integer;
positionIterations: Integer;
warmStarting: Boolean;
class function Create: b2TimeStep; static; cdecl;
end;
{ This is an internal structure.}
b2Position = record
c: b2Vec2;
a: Single;
class function Create: b2Position; static; cdecl;
end;
{ This is an internal structure.}
b2Velocity = record
v: b2Vec2;
w: Single;
class function Create: b2Velocity; static; cdecl;
end;
{ Solver Data}
b2SolverData = record
step: b2TimeStep;
positions: Pb2Position;
velocities: Pb2Velocity;
class function Create: b2SolverData; static; cdecl;
end;
{ This is an internal class.}
b2IslandWrapper = record
FHandle: b2IslandHandle;
private
function Get_m_allocator: b2StackAllocatorHandle; cdecl;
procedure Set_m_allocator(aNewValue: b2StackAllocatorHandle); cdecl;
function Get_m_listener: b2ContactListenerHandle; cdecl;
procedure Set_m_listener(aNewValue: b2ContactListenerHandle); cdecl;
function Get_m_bodies: Pb2BodyHandle; cdecl;
procedure Set_m_bodies(aNewValue: Pb2BodyHandle); cdecl;
function Get_m_contacts: Pb2ContactHandle; cdecl;
procedure Set_m_contacts(aNewValue: Pb2ContactHandle); cdecl;
function Get_m_joints: Pb2JointHandle; cdecl;
procedure Set_m_joints(aNewValue: Pb2JointHandle); cdecl;
function Get_m_positions: Pb2Position; cdecl;
procedure Set_m_positions(aNewValue: Pb2Position); cdecl;
function Get_m_velocities: Pb2Velocity; cdecl;
procedure Set_m_velocities(aNewValue: Pb2Velocity); cdecl;
function Get_m_bodyCount: Integer; cdecl;
procedure Set_m_bodyCount(aNewValue: Integer); cdecl;
function Get_m_jointCount: Integer; cdecl;
procedure Set_m_jointCount(aNewValue: Integer); cdecl;
function Get_m_contactCount: Integer; cdecl;
procedure Set_m_contactCount(aNewValue: Integer); cdecl;
function Get_m_bodyCapacity: Integer; cdecl;
procedure Set_m_bodyCapacity(aNewValue: Integer); cdecl;
function Get_m_contactCapacity: Integer; cdecl;
procedure Set_m_contactCapacity(aNewValue: Integer); cdecl;
function Get_m_jointCapacity: Integer; cdecl;
procedure Set_m_jointCapacity(aNewValue: Integer); cdecl;
public
class function Create(bodyCapacity: Integer; contactCapacity: Integer; jointCapacity: Integer; allocator: b2StackAllocatorHandle; listener: b2ContactListenerHandle): b2IslandWrapper; static; cdecl;
procedure Destroy; cdecl;
class operator Implicit(handle: b2IslandHandle): b2IslandWrapper; overload;
class operator Implicit(wrapper: b2IslandWrapper): b2IslandHandle; overload;
procedure Clear; cdecl;
procedure Solve(profile: Pb2Profile; const [ref] step: b2TimeStep; const [ref] gravity: b2Vec2; allowSleep: Boolean); cdecl;
procedure SolveTOI(const [ref] subStep: b2TimeStep; toiIndexA: Integer; toiIndexB: Integer); cdecl;
procedure Add(body: b2BodyHandle); cdecl;
procedure Add2(contact: b2ContactHandle); cdecl;
procedure Add3(joint: b2JointHandle); cdecl;
procedure Report(constraints: Pb2ContactVelocityConstraint); cdecl;
property m_allocator: b2StackAllocatorHandle read Get_m_allocator write Set_m_allocator;
property m_listener: b2ContactListenerHandle read Get_m_listener write Set_m_listener;
property m_bodies: Pb2BodyHandle read Get_m_bodies write Set_m_bodies;
property m_contacts: Pb2ContactHandle read Get_m_contacts write Set_m_contacts;
property m_joints: Pb2JointHandle read Get_m_joints write Set_m_joints;
property m_positions: Pb2Position read Get_m_positions write Set_m_positions;
property m_velocities: Pb2Velocity read Get_m_velocities write Set_m_velocities;
property m_bodyCount: Integer read Get_m_bodyCount write Set_m_bodyCount;
property m_jointCount: Integer read Get_m_jointCount write Set_m_jointCount;
property m_contactCount: Integer read Get_m_contactCount write Set_m_contactCount;
property m_bodyCapacity: Integer read Get_m_bodyCapacity write Set_m_bodyCapacity;
property m_contactCapacity: Integer read Get_m_contactCapacity write Set_m_contactCapacity;
property m_jointCapacity: Integer read Get_m_jointCapacity write Set_m_jointCapacity;
end;
{ Joints and fixtures are destroyed when their associated
body is destroyed. Implement this listener so that you
may nullify references to these joints and shapes.}
b2DestructionListenerWrapper = record
FHandle: b2DestructionListenerHandle;
class operator Implicit(handle: b2DestructionListenerHandle): b2DestructionListenerWrapper; overload;
class operator Implicit(wrapper: b2DestructionListenerWrapper): b2DestructionListenerHandle; overload;
{ Called when any joint is about to be destroyed due
to the destruction of one of its attached bodies.}
procedure SayGoodbye(joint: b2JointHandle); overload; cdecl;
{ Called when any fixture is about to be destroyed due
to the destruction of its parent body.}
procedure SayGoodbye(fixture: Pb2Fixture); overload; cdecl;
end;
{ Implement this class to provide collision filtering. In other words, you can implement
this class if you want finer control over contact creation.}
b2ContactFilterWrapper = record
FHandle: b2ContactFilterHandle;
class function Create: b2ContactFilterWrapper; static; cdecl;
procedure Destroy; cdecl;
class operator Implicit(handle: b2ContactFilterHandle): b2ContactFilterWrapper; overload;
class operator Implicit(wrapper: b2ContactFilterWrapper): b2ContactFilterHandle; overload;
{ Return true if contact calculations should be performed between these two shapes.
@warning for performance reasons this is only called when the AABBs begin to overlap.}
function ShouldCollide(fixtureA: Pb2Fixture; fixtureB: Pb2Fixture): Boolean; cdecl;
end;
{ Contact impulses for reporting. Impulses are used instead of forces because
sub-step forces may approach infinity for rigid body collisions. These
match up one-to-one with the contact points in b2Manifold.}
b2ContactImpulse = record
normalImpulses: array[0..1] of Single;
tangentImpulses: array[0..1] of Single;
count: Integer;
class function Create: b2ContactImpulse; static; cdecl;
end;
{ Implement this class to get contact information. You can use these results for
things like sounds and game logic. You can also get contact results by
traversing the contact lists after the time step. However, you might miss
some contacts because continuous physics leads to sub-stepping.
Additionally you may receive multiple callbacks for the same contact in a
single time step.
You should strive to make your callbacks efficient because there may be
many callbacks per time step.
@warning You cannot create/destroy Box2D entities inside these callbacks.}
b2ContactListenerWrapper = record
FHandle: b2ContactListenerHandle;
class function Create: b2ContactListenerWrapper; static; cdecl;
procedure Destroy; cdecl;
class operator Implicit(handle: b2ContactListenerHandle): b2ContactListenerWrapper; overload;
class operator Implicit(wrapper: b2ContactListenerWrapper): b2ContactListenerHandle; overload;
{ Called when two fixtures begin to touch.}
procedure BeginContact(contact: b2ContactHandle); cdecl;
{ Called when two fixtures cease to touch.}
procedure EndContact(contact: b2ContactHandle); cdecl;
{ This is called after a contact is updated. This allows you to inspect a
contact before it goes to the solver. If you are careful, you can modify the
contact manifold (e.g. disable contact).
A copy of the old manifold is provided so that you can detect changes.
Note: this is called only for awake bodies.
Note: this is called even when the number of contact points is zero.
Note: this is not called for sensors.
Note: if you set the number of contact points to zero, you will not
get an EndContact callback. However, you may get a BeginContact callback
the next step.}
procedure PreSolve(contact: b2ContactHandle; oldManifold: Pb2Manifold); cdecl;
{ This lets you inspect a contact after the solver is finished. This is useful
for inspecting impulses.
Note: the contact manifold does not include time of impact impulses, which can be
arbitrarily large if the sub-step is small. Hence the impulse is provided explicitly
in a separate data structure.
Note: this is only called for contacts that are touching, solid, and awake.}
procedure PostSolve(contact: b2ContactHandle; impulse: Pb2ContactImpulse); cdecl;
end;
{ Callback class for AABB queries.
See b2World::Query}
b2QueryCallbackWrapper = record
FHandle: b2QueryCallbackHandle;
class operator Implicit(handle: b2QueryCallbackHandle): b2QueryCallbackWrapper; overload;
class operator Implicit(wrapper: b2QueryCallbackWrapper): b2QueryCallbackHandle; overload;
{ Called for each fixture found in the query AABB.
@return false to terminate the query.}
function ReportFixture(fixture: Pb2Fixture): Boolean; cdecl;
end;
{ Callback class for ray casts.
See b2World::RayCast}
b2RayCastCallbackWrapper = record
FHandle: b2RayCastCallbackHandle;
class operator Implicit(handle: b2RayCastCallbackHandle): b2RayCastCallbackWrapper; overload;
class operator Implicit(wrapper: b2RayCastCallbackWrapper): b2RayCastCallbackHandle; overload;
{ Called for each fixture found in the query. You control how the ray cast
proceeds by returning a float:
return -1: ignore this fixture and continue
return 0: terminate the ray cast
return fraction: clip the ray to this point
return 1: don't clip the ray and continue
@param fixture the fixture hit by the ray
@param point the point of initial intersection
@param normal the normal vector at the point of intersection
@return -1 to filter, 0 to terminate, fraction to clip the ray for
closest hit, 1 to continue}
function ReportFixture(fixture: Pb2Fixture; const [ref] point: b2Vec2; const [ref] normal: b2Vec2; fraction: Single): Single; cdecl;
end;
{ The world class manages all physics entities, dynamic simulation,
and asynchronous queries. The world also contains efficient memory
management facilities.}
b2WorldWrapper = record
FHandle: b2WorldHandle;
class function Create(const [ref] gravity: b2Vec2): b2WorldWrapper; static; cdecl;
procedure Destroy; cdecl;
class operator Implicit(handle: b2WorldHandle): b2WorldWrapper; overload;
class operator Implicit(wrapper: b2WorldWrapper): b2WorldHandle; overload;
{ Register a destruction listener. The listener is owned by you and must
remain in scope.}
procedure SetDestructionListener(listener: b2DestructionListenerHandle); cdecl;
{ Register a contact filter to provide specific control over collision.
Otherwise the default filter is used (b2_defaultFilter). The listener is
owned by you and must remain in scope.}
procedure SetContactFilter(filter: b2ContactFilterHandle); cdecl;
{ Register a contact event listener. The listener is owned by you and must
remain in scope.}
procedure SetContactListener(listener: b2ContactListenerHandle); cdecl;
{ Register a routine for debug drawing. The debug draw functions are called
inside with b2World::DrawDebugData method. The debug draw object is owned
by you and must remain in scope.}
procedure SetDebugDraw(debugDraw: b2DrawHandle); cdecl;
{ Create a rigid body given a definition. No reference to the definition
is retained.
@warning This function is locked during callbacks.}
function CreateBody(def: Pb2BodyDef): b2BodyHandle; cdecl;
{ Destroy a rigid body given a definition. No reference to the definition
is retained. This function is locked during callbacks.
@warning This automatically deletes all associated shapes and joints.
@warning This function is locked during callbacks.}
procedure DestroyBody(body: b2BodyHandle); cdecl;
{ Create a joint to constrain bodies together. No reference to the definition
is retained. This may cause the connected bodies to cease colliding.
@warning This function is locked during callbacks.}
function CreateJoint(def: Pb2JointDef): b2JointHandle; cdecl;
{ Destroy a joint. This may cause the connected bodies to begin colliding.
@warning This function is locked during callbacks.}
procedure DestroyJoint(joint: b2JointHandle); cdecl;
{ Take a time step. This performs collision detection, integration,
and constraint solution.
@param timeStep the amount of time to simulate, this should not vary.
@param velocityIterations for the velocity constraint solver.
@param positionIterations for the position constraint solver.}
procedure Step(timeStep: Single; velocityIterations: Integer; positionIterations: Integer); cdecl;
{ Manually clear the force buffer on all bodies. By default, forces are cleared automatically
after each call to Step. The default behavior is modified by calling SetAutoClearForces.
The purpose of this function is to support sub-stepping. Sub-stepping is often used to maintain
a fixed sized time step under a variable frame-rate.
When you perform sub-stepping you will disable auto clearing of forces and instead call
ClearForces after all sub-steps are complete in one pass of your game loop.
@see SetAutoClearForces}
procedure ClearForces; cdecl;
{ Call this to draw shapes and other debug draw data. This is intentionally non-const.}
procedure DrawDebugData; cdecl;
{ Query the world for all fixtures that potentially overlap the
provided AABB.
@param callback a user implemented callback class.
@param aabb the query box.}
procedure QueryAABB(callback: b2QueryCallbackHandle; const [ref] aabb: b2AABB); cdecl;
{ Ray-cast the world for all fixtures in the path of the ray. Your callback
controls whether you get the closest point, any point, or n-points.
The ray-cast ignores shapes that contain the starting point.
@param callback a user implemented callback class.
@param point1 the ray starting point
@param point2 the ray ending point}
procedure RayCast(callback: b2RayCastCallbackHandle; const [ref] point1: b2Vec2; const [ref] point2: b2Vec2); cdecl;
{ Get the world body list. With the returned body, use b2Body::GetNext to get
the next body in the world list. A NULL body indicates the end of the list.
@return the head of the world body list.}
function GetBodyList: b2BodyHandle; cdecl;
{ Get the world joint list. With the returned joint, use b2Joint::GetNext to get
the next joint in the world list. A NULL joint indicates the end of the list.
@return the head of the world joint list.}
function GetJointList: b2JointHandle; cdecl;
{ Get the world contact list. With the returned contact, use b2Contact::GetNext to get
the next contact in the world list. A NULL contact indicates the end of the list.
@return the head of the world contact list.
@warning contacts are created and destroyed in the middle of a time step.
Use b2ContactListener to avoid missing contacts.}
function GetContactList: b2ContactHandle; cdecl;
{ Enable/disable sleep.}
procedure SetAllowSleeping(flag: Boolean); cdecl;
function GetAllowSleeping: Boolean; cdecl;
{ Enable/disable warm starting. For testing.}
procedure SetWarmStarting(flag: Boolean); cdecl;
function GetWarmStarting: Boolean; cdecl;
{ Enable/disable continuous physics. For testing.}
procedure SetContinuousPhysics(flag: Boolean); cdecl;
function GetContinuousPhysics: Boolean; cdecl;
{ Enable/disable single stepped continuous physics. For testing.}
procedure SetSubStepping(flag: Boolean); cdecl;
function GetSubStepping: Boolean; cdecl;
{ Get the number of broad-phase proxies.}
function GetProxyCount: Integer; cdecl;
{ Get the number of bodies.}
function GetBodyCount: Integer; cdecl;
{ Get the number of joints.}
function GetJointCount: Integer; cdecl;
{ Get the number of contacts (each may have 0 or more contact points).}
function GetContactCount: Integer; cdecl;
{ Get the height of the dynamic tree.}
function GetTreeHeight: Integer; cdecl;
{ Get the balance of the dynamic tree.}
function GetTreeBalance: Integer; cdecl;
{ Get the quality metric of the dynamic tree. The smaller the better.
The minimum is 1.}
function GetTreeQuality: Single; cdecl;
{ Change the global gravity vector.}
procedure SetGravity(const [ref] gravity: b2Vec2); cdecl;
{ Get the global gravity vector.}
function GetGravity: b2Vec2; cdecl;
{ Is the world locked (in the middle of a time step).}
function IsLocked: Boolean; cdecl;
{ Set flag to control automatic clearing of forces after each time step.}
procedure SetAutoClearForces(flag: Boolean); cdecl;
{ Get the flag that controls automatic clearing of forces after each time step.}
function GetAutoClearForces: Boolean; cdecl;
{ Shift the world origin. Useful for large worlds.
The body shift formula is: position -= newOrigin
@param newOrigin the new origin with respect to the old origin}
procedure ShiftOrigin(const [ref] newOrigin: b2Vec2); cdecl;
{ Get the contact manager for testing.}
function GetContactManager: b2ContactManagerHandle; cdecl;
{ Get the current profile.}
function GetProfile: Pb2Profile; cdecl;
{ Dump the world into the log file.
@warning this should be called outside of a time step.}
procedure Dump; cdecl;
end;
b2ContactRegister = record
createFcn: b2ContactCreateFcn;
destroyFcn: b2ContactDestroyFcn;
primary: Boolean;
class function Create: b2ContactRegister; static; cdecl;
end;
{ A contact edge is used to connect bodies and contacts together
in a contact graph where each body is a node and each contact
is an edge. A contact edge belongs to a doubly linked list
maintained in each attached body. Each contact has two contact
nodes, one for each attached body.}
b2ContactEdge = record
other: b2BodyHandle; {< provides quick access to the other body attached.}
contact: b2ContactHandle; {< the contact}
prev: Pb2ContactEdge; {< the previous contact edge in the body's contact list}
next: Pb2ContactEdge; {< the next contact edge in the body's contact list}
class function Create: b2ContactEdge; static; cdecl;
end;
{ The class manages contact between two shapes. A contact exists for each overlapping
AABB in the broad-phase (except if filtered). Therefore a contact object may exist
that has no contact points.}
b2ContactWrapper = record
FHandle: b2ContactHandle;
class operator Implicit(handle: b2ContactHandle): b2ContactWrapper; overload;
class operator Implicit(wrapper: b2ContactWrapper): b2ContactHandle; overload;
{ Get the contact manifold. Do not modify the manifold unless you understand the
internals of Box2D.}
function GetManifold: Pb2Manifold; cdecl;
{ Get the world manifold.}
procedure GetWorldManifold(worldManifold: Pb2WorldManifold); cdecl;
{ Is this contact touching?}
function IsTouching: Boolean; cdecl;
{ Enable/disable this contact. This can be used inside the pre-solve
contact listener. The contact is only disabled for the current
time step (or sub-step in continuous collisions).}
procedure SetEnabled(flag: Boolean); cdecl;
{ Has this contact been disabled?}
function IsEnabled: Boolean; cdecl;
{ Get the next contact in the world's contact list.}
function GetNext: b2ContactHandle; cdecl;
{ Get fixture A in this contact.}
function GetFixtureA: Pb2Fixture; cdecl;
{ Get the child primitive index for fixture A.}
function GetChildIndexA: Integer; cdecl;
{ Get fixture B in this contact.}
function GetFixtureB: Pb2Fixture; cdecl;
{ Get the child primitive index for fixture B.}
function GetChildIndexB: Integer; cdecl;
{ Override the default friction mixture. You can call this in b2ContactListener::PreSolve.
This value persists until set or reset.}
procedure SetFriction(friction: Single); cdecl;
{ Get the friction.}
function GetFriction: Single; cdecl;
{ Reset the friction mixture to the default value.}
procedure ResetFriction; cdecl;
{ Override the default restitution mixture. You can call this in b2ContactListener::PreSolve.
The value persists until you set or reset.}
procedure SetRestitution(restitution: Single); cdecl;
{ Get the restitution.}
function GetRestitution: Single; cdecl;
{ Reset the restitution to the default value.}
procedure ResetRestitution; cdecl;
{ Set the desired tangent speed for a conveyor belt behavior. In meters per second.}
procedure SetTangentSpeed(speed: Single); cdecl;
{ Get the desired tangent speed. In meters per second.}
function GetTangentSpeed: Single; cdecl;
{ Evaluate this contact with your own manifold and transforms.}
procedure Evaluate(manifold: Pb2Manifold; const [ref] xfA: b2Transform; const [ref] xfB: b2Transform); cdecl;
end;
b2ChainAndCircleContactWrapper = record
FHandle: b2ChainAndCircleContactHandle;
class function Create(fixtureA: Pb2Fixture; indexA: Integer; fixtureB: Pb2Fixture; indexB: Integer): b2ChainAndCircleContactWrapper; static; cdecl;
procedure Destroy; cdecl;
class operator Implicit(handle: b2ChainAndCircleContactHandle): b2ChainAndCircleContactWrapper; overload;
class operator Implicit(wrapper: b2ChainAndCircleContactWrapper): b2ChainAndCircleContactHandle; overload;
{ Get the contact manifold. Do not modify the manifold unless you understand the
internals of Box2D.}
function GetManifold: Pb2Manifold; cdecl;
{ Get the world manifold.}
procedure GetWorldManifold(worldManifold: Pb2WorldManifold); cdecl;
{ Is this contact touching?}
function IsTouching: Boolean; cdecl;
{ Enable/disable this contact. This can be used inside the pre-solve
contact listener. The contact is only disabled for the current
time step (or sub-step in continuous collisions).}
procedure SetEnabled(flag: Boolean); cdecl;
{ Has this contact been disabled?}
function IsEnabled: Boolean; cdecl;
{ Get the next contact in the world's contact list.}
function GetNext: b2ContactHandle; cdecl;
{ Get fixture A in this contact.}
function GetFixtureA: Pb2Fixture; cdecl;
{ Get the child primitive index for fixture A.}
function GetChildIndexA: Integer; cdecl;
{ Get fixture B in this contact.}
function GetFixtureB: Pb2Fixture; cdecl;
{ Get the child primitive index for fixture B.}
function GetChildIndexB: Integer; cdecl;
{ Override the default friction mixture. You can call this in b2ContactListener::PreSolve.
This value persists until set or reset.}
procedure SetFriction(friction: Single); cdecl;
{ Get the friction.}
function GetFriction: Single; cdecl;
{ Reset the friction mixture to the default value.}
procedure ResetFriction; cdecl;
{ Override the default restitution mixture. You can call this in b2ContactListener::PreSolve.
The value persists until you set or reset.}
procedure SetRestitution(restitution: Single); cdecl;
{ Get the restitution.}
function GetRestitution: Single; cdecl;
{ Reset the restitution to the default value.}
procedure ResetRestitution; cdecl;
{ Set the desired tangent speed for a conveyor belt behavior. In meters per second.}
procedure SetTangentSpeed(speed: Single); cdecl;
{ Get the desired tangent speed. In meters per second.}
function GetTangentSpeed: Single; cdecl;
{ Evaluate this contact with your own manifold and transforms.}
procedure Evaluate(manifold: Pb2Manifold; const [ref] xfA: b2Transform; const [ref] xfB: b2Transform); cdecl;
function Create_(fixtureA: Pb2Fixture; indexA: Integer; fixtureB: Pb2Fixture; indexB: Integer; allocator: b2BlockAllocatorHandle): b2ContactHandle; cdecl;
procedure Destroy_(contact: b2ContactHandle; allocator: b2BlockAllocatorHandle); cdecl;
end;
b2ChainAndPolygonContactWrapper = record
FHandle: b2ChainAndPolygonContactHandle;
class function Create(fixtureA: Pb2Fixture; indexA: Integer; fixtureB: Pb2Fixture; indexB: Integer): b2ChainAndPolygonContactWrapper; static; cdecl;
procedure Destroy; cdecl;
class operator Implicit(handle: b2ChainAndPolygonContactHandle): b2ChainAndPolygonContactWrapper; overload;
class operator Implicit(wrapper: b2ChainAndPolygonContactWrapper): b2ChainAndPolygonContactHandle; overload;
{ Get the contact manifold. Do not modify the manifold unless you understand the
internals of Box2D.}
function GetManifold: Pb2Manifold; cdecl;
{ Get the world manifold.}
procedure GetWorldManifold(worldManifold: Pb2WorldManifold); cdecl;
{ Is this contact touching?}
function IsTouching: Boolean; cdecl;
{ Enable/disable this contact. This can be used inside the pre-solve
contact listener. The contact is only disabled for the current
time step (or sub-step in continuous collisions).}
procedure SetEnabled(flag: Boolean); cdecl;
{ Has this contact been disabled?}
function IsEnabled: Boolean; cdecl;
{ Get the next contact in the world's contact list.}
function GetNext: b2ContactHandle; cdecl;
{ Get fixture A in this contact.}
function GetFixtureA: Pb2Fixture; cdecl;
{ Get the child primitive index for fixture A.}
function GetChildIndexA: Integer; cdecl;
{ Get fixture B in this contact.}
function GetFixtureB: Pb2Fixture; cdecl;
{ Get the child primitive index for fixture B.}
function GetChildIndexB: Integer; cdecl;
{ Override the default friction mixture. You can call this in b2ContactListener::PreSolve.
This value persists until set or reset.}
procedure SetFriction(friction: Single); cdecl;
{ Get the friction.}
function GetFriction: Single; cdecl;
{ Reset the friction mixture to the default value.}
procedure ResetFriction; cdecl;
{ Override the default restitution mixture. You can call this in b2ContactListener::PreSolve.
The value persists until you set or reset.}
procedure SetRestitution(restitution: Single); cdecl;
{ Get the restitution.}
function GetRestitution: Single; cdecl;
{ Reset the restitution to the default value.}
procedure ResetRestitution; cdecl;
{ Set the desired tangent speed for a conveyor belt behavior. In meters per second.}
procedure SetTangentSpeed(speed: Single); cdecl;
{ Get the desired tangent speed. In meters per second.}
function GetTangentSpeed: Single; cdecl;
{ Evaluate this contact with your own manifold and transforms.}
procedure Evaluate(manifold: Pb2Manifold; const [ref] xfA: b2Transform; const [ref] xfB: b2Transform); cdecl;
function Create_(fixtureA: Pb2Fixture; indexA: Integer; fixtureB: Pb2Fixture; indexB: Integer; allocator: b2BlockAllocatorHandle): b2ContactHandle; cdecl;
procedure Destroy_(contact: b2ContactHandle; allocator: b2BlockAllocatorHandle); cdecl;
end;
b2CircleContactWrapper = record
FHandle: b2CircleContactHandle;
class function Create(fixtureA: Pb2Fixture; fixtureB: Pb2Fixture): b2CircleContactWrapper; static; cdecl;
procedure Destroy; cdecl;
class operator Implicit(handle: b2CircleContactHandle): b2CircleContactWrapper; overload;
class operator Implicit(wrapper: b2CircleContactWrapper): b2CircleContactHandle; overload;
{ Get the contact manifold. Do not modify the manifold unless you understand the
internals of Box2D.}
function GetManifold: Pb2Manifold; cdecl;
{ Get the world manifold.}
procedure GetWorldManifold(worldManifold: Pb2WorldManifold); cdecl;
{ Is this contact touching?}
function IsTouching: Boolean; cdecl;
{ Enable/disable this contact. This can be used inside the pre-solve
contact listener. The contact is only disabled for the current
time step (or sub-step in continuous collisions).}
procedure SetEnabled(flag: Boolean); cdecl;
{ Has this contact been disabled?}
function IsEnabled: Boolean; cdecl;
{ Get the next contact in the world's contact list.}
function GetNext: b2ContactHandle; cdecl;
{ Get fixture A in this contact.}
function GetFixtureA: Pb2Fixture; cdecl;
{ Get the child primitive index for fixture A.}
function GetChildIndexA: Integer; cdecl;
{ Get fixture B in this contact.}
function GetFixtureB: Pb2Fixture; cdecl;
{ Get the child primitive index for fixture B.}
function GetChildIndexB: Integer; cdecl;
{ Override the default friction mixture. You can call this in b2ContactListener::PreSolve.
This value persists until set or reset.}
procedure SetFriction(friction: Single); cdecl;
{ Get the friction.}
function GetFriction: Single; cdecl;
{ Reset the friction mixture to the default value.}
procedure ResetFriction; cdecl;
{ Override the default restitution mixture. You can call this in b2ContactListener::PreSolve.
The value persists until you set or reset.}
procedure SetRestitution(restitution: Single); cdecl;
{ Get the restitution.}
function GetRestitution: Single; cdecl;
{ Reset the restitution to the default value.}
procedure ResetRestitution; cdecl;
{ Set the desired tangent speed for a conveyor belt behavior. In meters per second.}
procedure SetTangentSpeed(speed: Single); cdecl;
{ Get the desired tangent speed. In meters per second.}
function GetTangentSpeed: Single; cdecl;
{ Evaluate this contact with your own manifold and transforms.}
procedure Evaluate(manifold: Pb2Manifold; const [ref] xfA: b2Transform; const [ref] xfB: b2Transform); cdecl;
function Create_(fixtureA: Pb2Fixture; indexA: Integer; fixtureB: Pb2Fixture; indexB: Integer; allocator: b2BlockAllocatorHandle): b2ContactHandle; cdecl;
procedure Destroy_(contact: b2ContactHandle; allocator: b2BlockAllocatorHandle); cdecl;
end;
b2VelocityConstraintPoint = record
rA: b2Vec2;
rB: b2Vec2;
normalImpulse: Single;
tangentImpulse: Single;
normalMass: Single;
tangentMass: Single;
velocityBias: Single;
class function Create: b2VelocityConstraintPoint; static; cdecl;
end;
b2ContactVelocityConstraint = record
points: array[0..1] of b2VelocityConstraintPoint;
normal: b2Vec2;
normalMass: b2Mat22;
K: b2Mat22;
indexA: Integer;
indexB: Integer;
invMassA: Single;
invMassB: Single;
invIA: Single;
invIB: Single;
friction: Single;
restitution: Single;
tangentSpeed: Single;
pointCount: Integer;
contactIndex: Integer;
class function Create: b2ContactVelocityConstraint; static; cdecl;
end;
b2ContactSolverDef = record
step: b2TimeStep;
contacts: b2ContactHandle;
count: Integer;
positions: Pb2Position;
velocities: Pb2Velocity;
allocator: b2StackAllocatorHandle;
class function Create: b2ContactSolverDef; static; cdecl;
end;
b2ContactSolverWrapper = record
FHandle: b2ContactSolverHandle;
private
function Get_m_step: b2TimeStep; cdecl;
procedure Set_m_step(aNewValue: b2TimeStep); cdecl;
function Get_m_step_P: Pb2TimeStep; cdecl;
function Get_m_positions: Pb2Position; cdecl;
procedure Set_m_positions(aNewValue: Pb2Position); cdecl;
function Get_m_velocities: Pb2Velocity; cdecl;
procedure Set_m_velocities(aNewValue: Pb2Velocity); cdecl;
function Get_m_allocator: b2StackAllocatorHandle; cdecl;
procedure Set_m_allocator(aNewValue: b2StackAllocatorHandle); cdecl;
function Get_m_velocityConstraints: Pb2ContactVelocityConstraint; cdecl;
procedure Set_m_velocityConstraints(aNewValue: Pb2ContactVelocityConstraint); cdecl;
function Get_m_contacts: Pb2ContactHandle; cdecl;
procedure Set_m_contacts(aNewValue: Pb2ContactHandle); cdecl;
function Get_m_count: Integer; cdecl;
procedure Set_m_count(aNewValue: Integer); cdecl;
public
class function Create(def: Pb2ContactSolverDef): b2ContactSolverWrapper; static; cdecl;
procedure Destroy; cdecl;
class operator Implicit(handle: b2ContactSolverHandle): b2ContactSolverWrapper; overload;
class operator Implicit(wrapper: b2ContactSolverWrapper): b2ContactSolverHandle; overload;
procedure InitializeVelocityConstraints; cdecl;
procedure WarmStart; cdecl;
procedure SolveVelocityConstraints; cdecl;
procedure StoreImpulses; cdecl;
function SolvePositionConstraints: Boolean; cdecl;
function SolveTOIPositionConstraints(toiIndexA: Integer; toiIndexB: Integer): Boolean; cdecl;
property m_step: b2TimeStep read Get_m_step write Set_m_step;
property m_step_P: Pb2TimeStep read Get_m_step_P;
property m_positions: Pb2Position read Get_m_positions write Set_m_positions;
property m_velocities: Pb2Velocity read Get_m_velocities write Set_m_velocities;
property m_allocator: b2StackAllocatorHandle read Get_m_allocator write Set_m_allocator;
property m_velocityConstraints: Pb2ContactVelocityConstraint read Get_m_velocityConstraints write Set_m_velocityConstraints;
property m_contacts: Pb2ContactHandle read Get_m_contacts write Set_m_contacts;
property m_count: Integer read Get_m_count write Set_m_count;
end;
b2EdgeAndCircleContactWrapper = record
FHandle: b2EdgeAndCircleContactHandle;
class function Create(fixtureA: Pb2Fixture; fixtureB: Pb2Fixture): b2EdgeAndCircleContactWrapper; static; cdecl;
procedure Destroy; cdecl;
class operator Implicit(handle: b2EdgeAndCircleContactHandle): b2EdgeAndCircleContactWrapper; overload;
class operator Implicit(wrapper: b2EdgeAndCircleContactWrapper): b2EdgeAndCircleContactHandle; overload;
{ Get the contact manifold. Do not modify the manifold unless you understand the
internals of Box2D.}
function GetManifold: Pb2Manifold; cdecl;
{ Get the world manifold.}
procedure GetWorldManifold(worldManifold: Pb2WorldManifold); cdecl;
{ Is this contact touching?}
function IsTouching: Boolean; cdecl;
{ Enable/disable this contact. This can be used inside the pre-solve
contact listener. The contact is only disabled for the current
time step (or sub-step in continuous collisions).}
procedure SetEnabled(flag: Boolean); cdecl;
{ Has this contact been disabled?}
function IsEnabled: Boolean; cdecl;
{ Get the next contact in the world's contact list.}
function GetNext: b2ContactHandle; cdecl;
{ Get fixture A in this contact.}
function GetFixtureA: Pb2Fixture; cdecl;
{ Get the child primitive index for fixture A.}
function GetChildIndexA: Integer; cdecl;
{ Get fixture B in this contact.}
function GetFixtureB: Pb2Fixture; cdecl;
{ Get the child primitive index for fixture B.}
function GetChildIndexB: Integer; cdecl;
{ Override the default friction mixture. You can call this in b2ContactListener::PreSolve.
This value persists until set or reset.}
procedure SetFriction(friction: Single); cdecl;
{ Get the friction.}
function GetFriction: Single; cdecl;
{ Reset the friction mixture to the default value.}
procedure ResetFriction; cdecl;
{ Override the default restitution mixture. You can call this in b2ContactListener::PreSolve.
The value persists until you set or reset.}
procedure SetRestitution(restitution: Single); cdecl;
{ Get the restitution.}
function GetRestitution: Single; cdecl;
{ Reset the restitution to the default value.}
procedure ResetRestitution; cdecl;
{ Set the desired tangent speed for a conveyor belt behavior. In meters per second.}
procedure SetTangentSpeed(speed: Single); cdecl;
{ Get the desired tangent speed. In meters per second.}
function GetTangentSpeed: Single; cdecl;
{ Evaluate this contact with your own manifold and transforms.}
procedure Evaluate(manifold: Pb2Manifold; const [ref] xfA: b2Transform; const [ref] xfB: b2Transform); cdecl;
function Create_(fixtureA: Pb2Fixture; indexA: Integer; fixtureB: Pb2Fixture; indexB: Integer; allocator: b2BlockAllocatorHandle): b2ContactHandle; cdecl;
procedure Destroy_(contact: b2ContactHandle; allocator: b2BlockAllocatorHandle); cdecl;
end;
b2EdgeAndPolygonContactWrapper = record
FHandle: b2EdgeAndPolygonContactHandle;
class function Create(fixtureA: Pb2Fixture; fixtureB: Pb2Fixture): b2EdgeAndPolygonContactWrapper; static; cdecl;
procedure Destroy; cdecl;
class operator Implicit(handle: b2EdgeAndPolygonContactHandle): b2EdgeAndPolygonContactWrapper; overload;
class operator Implicit(wrapper: b2EdgeAndPolygonContactWrapper): b2EdgeAndPolygonContactHandle; overload;
{ Get the contact manifold. Do not modify the manifold unless you understand the
internals of Box2D.}
function GetManifold: Pb2Manifold; cdecl;
{ Get the world manifold.}
procedure GetWorldManifold(worldManifold: Pb2WorldManifold); cdecl;
{ Is this contact touching?}
function IsTouching: Boolean; cdecl;
{ Enable/disable this contact. This can be used inside the pre-solve
contact listener. The contact is only disabled for the current
time step (or sub-step in continuous collisions).}
procedure SetEnabled(flag: Boolean); cdecl;
{ Has this contact been disabled?}
function IsEnabled: Boolean; cdecl;
{ Get the next contact in the world's contact list.}
function GetNext: b2ContactHandle; cdecl;
{ Get fixture A in this contact.}
function GetFixtureA: Pb2Fixture; cdecl;
{ Get the child primitive index for fixture A.}
function GetChildIndexA: Integer; cdecl;
{ Get fixture B in this contact.}
function GetFixtureB: Pb2Fixture; cdecl;
{ Get the child primitive index for fixture B.}
function GetChildIndexB: Integer; cdecl;
{ Override the default friction mixture. You can call this in b2ContactListener::PreSolve.
This value persists until set or reset.}
procedure SetFriction(friction: Single); cdecl;
{ Get the friction.}
function GetFriction: Single; cdecl;
{ Reset the friction mixture to the default value.}
procedure ResetFriction; cdecl;
{ Override the default restitution mixture. You can call this in b2ContactListener::PreSolve.
The value persists until you set or reset.}
procedure SetRestitution(restitution: Single); cdecl;
{ Get the restitution.}
function GetRestitution: Single; cdecl;
{ Reset the restitution to the default value.}
procedure ResetRestitution; cdecl;
{ Set the desired tangent speed for a conveyor belt behavior. In meters per second.}
procedure SetTangentSpeed(speed: Single); cdecl;
{ Get the desired tangent speed. In meters per second.}
function GetTangentSpeed: Single; cdecl;
{ Evaluate this contact with your own manifold and transforms.}
procedure Evaluate(manifold: Pb2Manifold; const [ref] xfA: b2Transform; const [ref] xfB: b2Transform); cdecl;
function Create_(fixtureA: Pb2Fixture; indexA: Integer; fixtureB: Pb2Fixture; indexB: Integer; allocator: b2BlockAllocatorHandle): b2ContactHandle; cdecl;
procedure Destroy_(contact: b2ContactHandle; allocator: b2BlockAllocatorHandle); cdecl;
end;
b2PolygonAndCircleContactWrapper = record
FHandle: b2PolygonAndCircleContactHandle;
class function Create(fixtureA: Pb2Fixture; fixtureB: Pb2Fixture): b2PolygonAndCircleContactWrapper; static; cdecl;
procedure Destroy; cdecl;
class operator Implicit(handle: b2PolygonAndCircleContactHandle): b2PolygonAndCircleContactWrapper; overload;
class operator Implicit(wrapper: b2PolygonAndCircleContactWrapper): b2PolygonAndCircleContactHandle; overload;
{ Get the contact manifold. Do not modify the manifold unless you understand the
internals of Box2D.}
function GetManifold: Pb2Manifold; cdecl;
{ Get the world manifold.}
procedure GetWorldManifold(worldManifold: Pb2WorldManifold); cdecl;
{ Is this contact touching?}
function IsTouching: Boolean; cdecl;
{ Enable/disable this contact. This can be used inside the pre-solve
contact listener. The contact is only disabled for the current
time step (or sub-step in continuous collisions).}
procedure SetEnabled(flag: Boolean); cdecl;
{ Has this contact been disabled?}
function IsEnabled: Boolean; cdecl;
{ Get the next contact in the world's contact list.}
function GetNext: b2ContactHandle; cdecl;
{ Get fixture A in this contact.}
function GetFixtureA: Pb2Fixture; cdecl;
{ Get the child primitive index for fixture A.}
function GetChildIndexA: Integer; cdecl;
{ Get fixture B in this contact.}
function GetFixtureB: Pb2Fixture; cdecl;
{ Get the child primitive index for fixture B.}
function GetChildIndexB: Integer; cdecl;
{ Override the default friction mixture. You can call this in b2ContactListener::PreSolve.
This value persists until set or reset.}
procedure SetFriction(friction: Single); cdecl;
{ Get the friction.}
function GetFriction: Single; cdecl;
{ Reset the friction mixture to the default value.}
procedure ResetFriction; cdecl;
{ Override the default restitution mixture. You can call this in b2ContactListener::PreSolve.
The value persists until you set or reset.}
procedure SetRestitution(restitution: Single); cdecl;
{ Get the restitution.}
function GetRestitution: Single; cdecl;
{ Reset the restitution to the default value.}
procedure ResetRestitution; cdecl;
{ Set the desired tangent speed for a conveyor belt behavior. In meters per second.}
procedure SetTangentSpeed(speed: Single); cdecl;
{ Get the desired tangent speed. In meters per second.}
function GetTangentSpeed: Single; cdecl;
{ Evaluate this contact with your own manifold and transforms.}
procedure Evaluate(manifold: Pb2Manifold; const [ref] xfA: b2Transform; const [ref] xfB: b2Transform); cdecl;
function Create_(fixtureA: Pb2Fixture; indexA: Integer; fixtureB: Pb2Fixture; indexB: Integer; allocator: b2BlockAllocatorHandle): b2ContactHandle; cdecl;
procedure Destroy_(contact: b2ContactHandle; allocator: b2BlockAllocatorHandle); cdecl;
end;
b2PolygonContactWrapper = record
FHandle: b2PolygonContactHandle;
class function Create(fixtureA: Pb2Fixture; fixtureB: Pb2Fixture): b2PolygonContactWrapper; static; cdecl;
procedure Destroy; cdecl;
class operator Implicit(handle: b2PolygonContactHandle): b2PolygonContactWrapper; overload;
class operator Implicit(wrapper: b2PolygonContactWrapper): b2PolygonContactHandle; overload;
{ Get the contact manifold. Do not modify the manifold unless you understand the
internals of Box2D.}
function GetManifold: Pb2Manifold; cdecl;
{ Get the world manifold.}
procedure GetWorldManifold(worldManifold: Pb2WorldManifold); cdecl;
{ Is this contact touching?}
function IsTouching: Boolean; cdecl;
{ Enable/disable this contact. This can be used inside the pre-solve
contact listener. The contact is only disabled for the current
time step (or sub-step in continuous collisions).}
procedure SetEnabled(flag: Boolean); cdecl;
{ Has this contact been disabled?}
function IsEnabled: Boolean; cdecl;
{ Get the next contact in the world's contact list.}
function GetNext: b2ContactHandle; cdecl;
{ Get fixture A in this contact.}
function GetFixtureA: Pb2Fixture; cdecl;
{ Get the child primitive index for fixture A.}
function GetChildIndexA: Integer; cdecl;
{ Get fixture B in this contact.}
function GetFixtureB: Pb2Fixture; cdecl;
{ Get the child primitive index for fixture B.}
function GetChildIndexB: Integer; cdecl;
{ Override the default friction mixture. You can call this in b2ContactListener::PreSolve.
This value persists until set or reset.}
procedure SetFriction(friction: Single); cdecl;
{ Get the friction.}
function GetFriction: Single; cdecl;
{ Reset the friction mixture to the default value.}
procedure ResetFriction; cdecl;
{ Override the default restitution mixture. You can call this in b2ContactListener::PreSolve.
The value persists until you set or reset.}
procedure SetRestitution(restitution: Single); cdecl;
{ Get the restitution.}
function GetRestitution: Single; cdecl;
{ Reset the restitution to the default value.}
procedure ResetRestitution; cdecl;
{ Set the desired tangent speed for a conveyor belt behavior. In meters per second.}
procedure SetTangentSpeed(speed: Single); cdecl;
{ Get the desired tangent speed. In meters per second.}
function GetTangentSpeed: Single; cdecl;
{ Evaluate this contact with your own manifold and transforms.}
procedure Evaluate(manifold: Pb2Manifold; const [ref] xfA: b2Transform; const [ref] xfB: b2Transform); cdecl;
function Create_(fixtureA: Pb2Fixture; indexA: Integer; fixtureB: Pb2Fixture; indexB: Integer; allocator: b2BlockAllocatorHandle): b2ContactHandle; cdecl;
procedure Destroy_(contact: b2ContactHandle; allocator: b2BlockAllocatorHandle); cdecl;
end;
b2Jacobian = record
linear: b2Vec2;
angularA: Single;
angularB: Single;
class function Create: b2Jacobian; static; cdecl;
end;
{ A joint edge is used to connect bodies and joints together
in a joint graph where each body is a node and each joint
is an edge. A joint edge belongs to a doubly linked list
maintained in each attached body. Each joint has two joint
nodes, one for each attached body.}
b2JointEdge = record
other: b2BodyHandle; {< provides quick access to the other body attached.}
joint: b2JointHandle; {< the joint}
prev: Pb2JointEdge; {< the previous joint edge in the body's joint list}
next: Pb2JointEdge; {< the next joint edge in the body's joint list}
class function Create: b2JointEdge; static; cdecl;
end;
{ Joint definitions are used to construct joints.}
b2JointDef = record
&type: b2JointType; { The joint type is set automatically for concrete joint types.}
userData: Pointer; { Use this to attach application specific data to your joints.}
bodyA: b2BodyHandle; { The first attached body.}
bodyB: b2BodyHandle; { The second attached body.}
collideConnected: Boolean; { Set this flag to true if the attached bodies should collide.}
class function Create: b2JointDef; static; cdecl;
end;
{ The base joint class. Joints are used to constraint two bodies together in
various fashions. Some joints also feature limits and motors.}
b2JointWrapper = record
FHandle: b2JointHandle;
class operator Implicit(handle: b2JointHandle): b2JointWrapper; overload;
class operator Implicit(wrapper: b2JointWrapper): b2JointHandle; overload;
{ Get the type of the concrete joint.}
function GetType: b2JointType; cdecl;
{ Get the first body attached to this joint.}
function GetBodyA: b2BodyHandle; cdecl;
{ Get the second body attached to this joint.}
function GetBodyB: b2BodyHandle; cdecl;
{ Get the anchor point on bodyA in world coordinates.}
function GetAnchorA: b2Vec2; cdecl;
{ Get the anchor point on bodyB in world coordinates.}
function GetAnchorB: b2Vec2; cdecl;
{ Get the reaction force on bodyB at the joint anchor in Newtons.}
function GetReactionForce(inv_dt: Single): b2Vec2; cdecl;
{ Get the reaction torque on bodyB in N*m.}
function GetReactionTorque(inv_dt: Single): Single; cdecl;
{ Get the next joint the world joint list.}
function GetNext: b2JointHandle; cdecl;
{ Get the user data pointer.}
function GetUserData: Pointer; cdecl;
{ Set the user data pointer.}
procedure SetUserData(data: Pointer); cdecl;
{ Short-cut function to determine if either body is inactive.}
function IsActive: Boolean; cdecl;
{ Get collide connected.
Note: modifying the collide connect flag won't work correctly because
the flag is only checked when fixture AABBs begin to overlap.}
function GetCollideConnected: Boolean; cdecl;
{ Dump this joint to the log file.}
procedure Dump; cdecl;
{ Shift the origin for any points stored in world coordinates.}
procedure ShiftOrigin(const [ref] newOrigin: b2Vec2); cdecl;
end;
{ Distance joint definition. This requires defining an
anchor point on both bodies and the non-zero length of the
distance joint. The definition uses local anchor points
so that the initial configuration can violate the constraint
slightly. This helps when saving and loading a game.
@warning Do not use a zero or short length.}
b2DistanceJointDef = record
&type: b2JointType; { The joint type is set automatically for concrete joint types.}
userData: Pointer; { Use this to attach application specific data to your joints.}
bodyA: b2BodyHandle; { The first attached body.}
bodyB: b2BodyHandle; { The second attached body.}
collideConnected: Boolean; { Set this flag to true if the attached bodies should collide.}
Filler1 : TDWordFiller;
localAnchorA: b2Vec2; { The local anchor point relative to bodyA's origin.}
localAnchorB: b2Vec2; { The local anchor point relative to bodyB's origin.}
length: Single; { The natural length between the anchor points.}
frequencyHz: Single; { The mass-spring-damper frequency in Hertz. A value of 0
disables softness.}
dampingRatio: Single; { The damping ratio. 0 = no damping, 1 = critical damping.}
Filler2 : TDWordFiller;
class function Create: b2DistanceJointDef; static; cdecl;
{ Initialize the bodies, anchors, and length using the world
anchors.}
procedure Initialize(bodyA: b2BodyHandle; bodyB: b2BodyHandle; const [ref] anchorA: b2Vec2; const [ref] anchorB: b2Vec2); cdecl;
end;
{ A distance joint constrains two points on two bodies
to remain at a fixed distance from each other. You can view
this as a massless, rigid rod.}
b2DistanceJointWrapper = record
FHandle: b2DistanceJointHandle;
procedure Destroy; cdecl;
class operator Implicit(handle: b2DistanceJointHandle): b2DistanceJointWrapper; overload;
class operator Implicit(wrapper: b2DistanceJointWrapper): b2DistanceJointHandle; overload;
{ Get the type of the concrete joint.}
function GetType: b2JointType; cdecl;
{ Get the first body attached to this joint.}
function GetBodyA: b2BodyHandle; cdecl;
{ Get the second body attached to this joint.}
function GetBodyB: b2BodyHandle; cdecl;
{ Get the anchor point on bodyA in world coordinates.}
function GetAnchorA: b2Vec2; cdecl;
{ Get the anchor point on bodyB in world coordinates.}
function GetAnchorB: b2Vec2; cdecl;
{ Get the reaction force on bodyB at the joint anchor in Newtons.}
function GetReactionForce(inv_dt: Single): b2Vec2; cdecl;
{ Get the reaction torque on bodyB in N*m.}
function GetReactionTorque(inv_dt: Single): Single; cdecl;
{ Get the next joint the world joint list.}
function GetNext: b2JointHandle; cdecl;
{ Get the user data pointer.}
function GetUserData: Pointer; cdecl;
{ Set the user data pointer.}
procedure SetUserData(data: Pointer); cdecl;
{ Short-cut function to determine if either body is inactive.}
function IsActive: Boolean; cdecl;
{ Get collide connected.
Note: modifying the collide connect flag won't work correctly because
the flag is only checked when fixture AABBs begin to overlap.}
function GetCollideConnected: Boolean; cdecl;
{ Dump this joint to the log file.}
procedure Dump; cdecl;
{ Shift the origin for any points stored in world coordinates.}
procedure ShiftOrigin(const [ref] newOrigin: b2Vec2); cdecl;
{ The local anchor point relative to bodyA's origin.}
function GetLocalAnchorA: Pb2Vec2; cdecl;
{ The local anchor point relative to bodyB's origin.}
function GetLocalAnchorB: Pb2Vec2; cdecl;
{ Set/get the natural length.
Manipulating the length can lead to non-physical behavior when the frequency is zero.}
procedure SetLength(length: Single); cdecl;
function GetLength: Single; cdecl;
{ Set/get frequency in Hz.}
procedure SetFrequency(hz: Single); cdecl;
function GetFrequency: Single; cdecl;
{ Set/get damping ratio.}
procedure SetDampingRatio(ratio: Single); cdecl;
function GetDampingRatio: Single; cdecl;
end;
{ Friction joint definition.}
b2FrictionJointDef = record
&type: b2JointType; { The joint type is set automatically for concrete joint types.}
userData: Pointer; { Use this to attach application specific data to your joints.}
bodyA: b2BodyHandle; { The first attached body.}
bodyB: b2BodyHandle; { The second attached body.}
collideConnected: Boolean; { Set this flag to true if the attached bodies should collide.}
localAnchorA: b2Vec2; { The local anchor point relative to bodyA's origin.}
localAnchorB: b2Vec2; { The local anchor point relative to bodyB's origin.}
maxForce: Single; { The maximum friction force in N.}
maxTorque: Single; { The maximum friction torque in N-m.}
class function Create: b2FrictionJointDef; static; cdecl;
{ Initialize the bodies, anchors, axis, and reference angle using the world
anchor and world axis.}
procedure Initialize(bodyA: b2BodyHandle; bodyB: b2BodyHandle; const [ref] anchor: b2Vec2); cdecl;
end;
{ Friction joint. This is used for top-down friction.
It provides 2D translational friction and angular friction.}
b2FrictionJointWrapper = record
FHandle: b2FrictionJointHandle;
procedure Destroy; cdecl;
class operator Implicit(handle: b2FrictionJointHandle): b2FrictionJointWrapper; overload;
class operator Implicit(wrapper: b2FrictionJointWrapper): b2FrictionJointHandle; overload;
{ Get the type of the concrete joint.}
function GetType: b2JointType; cdecl;
{ Get the first body attached to this joint.}
function GetBodyA: b2BodyHandle; cdecl;
{ Get the second body attached to this joint.}
function GetBodyB: b2BodyHandle; cdecl;
{ Get the anchor point on bodyA in world coordinates.}
function GetAnchorA: b2Vec2; cdecl;
{ Get the anchor point on bodyB in world coordinates.}
function GetAnchorB: b2Vec2; cdecl;
{ Get the reaction force on bodyB at the joint anchor in Newtons.}
function GetReactionForce(inv_dt: Single): b2Vec2; cdecl;
{ Get the reaction torque on bodyB in N*m.}
function GetReactionTorque(inv_dt: Single): Single; cdecl;
{ Get the next joint the world joint list.}
function GetNext: b2JointHandle; cdecl;
{ Get the user data pointer.}
function GetUserData: Pointer; cdecl;
{ Set the user data pointer.}
procedure SetUserData(data: Pointer); cdecl;
{ Short-cut function to determine if either body is inactive.}
function IsActive: Boolean; cdecl;
{ Get collide connected.
Note: modifying the collide connect flag won't work correctly because
the flag is only checked when fixture AABBs begin to overlap.}
function GetCollideConnected: Boolean; cdecl;
{ Dump this joint to the log file.}
procedure Dump; cdecl;
{ Shift the origin for any points stored in world coordinates.}
procedure ShiftOrigin(const [ref] newOrigin: b2Vec2); cdecl;
{ The local anchor point relative to bodyA's origin.}
function GetLocalAnchorA: Pb2Vec2; cdecl;
{ The local anchor point relative to bodyB's origin.}
function GetLocalAnchorB: Pb2Vec2; cdecl;
{ Set the maximum friction force in N.}
procedure SetMaxForce(force: Single); cdecl;
{ Get the maximum friction force in N.}
function GetMaxForce: Single; cdecl;
{ Set the maximum friction torque in N*m.}
procedure SetMaxTorque(torque: Single); cdecl;
{ Get the maximum friction torque in N*m.}
function GetMaxTorque: Single; cdecl;
end;
{ Gear joint definition. This definition requires two existing
revolute or prismatic joints (any combination will work).}
b2GearJointDef = record
&type: b2JointType; { The joint type is set automatically for concrete joint types.}
userData: Pointer; { Use this to attach application specific data to your joints.}
bodyA: b2BodyHandle; { The first attached body.}
bodyB: b2BodyHandle; { The second attached body.}
collideConnected: Boolean; { Set this flag to true if the attached bodies should collide.}
joint1: b2JointHandle; { The first revolute/prismatic joint attached to the gear joint.}
joint2: b2JointHandle; { The second revolute/prismatic joint attached to the gear joint.}
ratio: Single; { The gear ratio.
@see b2GearJoint for explanation.}
class function Create: b2GearJointDef; static; cdecl;
end;
{ A gear joint is used to connect two joints together. Either joint
can be a revolute or prismatic joint. You specify a gear ratio
to bind the motions together:
coordinate1 + ratio * coordinate2 = constant
The ratio can be negative or positive. If one joint is a revolute joint
and the other joint is a prismatic joint, then the ratio will have units
of length or units of 1/length.
@warning You have to manually destroy the gear joint if joint1 or joint2
is destroyed.}
b2GearJointWrapper = record
FHandle: b2GearJointHandle;
procedure Destroy; cdecl;
class operator Implicit(handle: b2GearJointHandle): b2GearJointWrapper; overload;
class operator Implicit(wrapper: b2GearJointWrapper): b2GearJointHandle; overload;
{ Get the type of the concrete joint.}
function GetType: b2JointType; cdecl;
{ Get the first body attached to this joint.}
function GetBodyA: b2BodyHandle; cdecl;
{ Get the second body attached to this joint.}
function GetBodyB: b2BodyHandle; cdecl;
{ Get the anchor point on bodyA in world coordinates.}
function GetAnchorA: b2Vec2; cdecl;
{ Get the anchor point on bodyB in world coordinates.}
function GetAnchorB: b2Vec2; cdecl;
{ Get the reaction force on bodyB at the joint anchor in Newtons.}
function GetReactionForce(inv_dt: Single): b2Vec2; cdecl;
{ Get the reaction torque on bodyB in N*m.}
function GetReactionTorque(inv_dt: Single): Single; cdecl;
{ Get the next joint the world joint list.}
function GetNext: b2JointHandle; cdecl;
{ Get the user data pointer.}
function GetUserData: Pointer; cdecl;
{ Set the user data pointer.}
procedure SetUserData(data: Pointer); cdecl;
{ Short-cut function to determine if either body is inactive.}
function IsActive: Boolean; cdecl;
{ Get collide connected.
Note: modifying the collide connect flag won't work correctly because
the flag is only checked when fixture AABBs begin to overlap.}
function GetCollideConnected: Boolean; cdecl;
{ Dump this joint to the log file.}
procedure Dump; cdecl;
{ Shift the origin for any points stored in world coordinates.}
procedure ShiftOrigin(const [ref] newOrigin: b2Vec2); cdecl;
{ Get the first joint.}
function GetJoint1: b2JointHandle; cdecl;
{ Get the second joint.}
function GetJoint2: b2JointHandle; cdecl;
{ Set/Get the gear ratio.}
procedure SetRatio(ratio: Single); cdecl;
function GetRatio: Single; cdecl;
end;
{ Motor joint definition.}
b2MotorJointDef = record
&type: b2JointType; { The joint type is set automatically for concrete joint types.}
userData: Pointer; { Use this to attach application specific data to your joints.}
bodyA: b2BodyHandle; { The first attached body.}
bodyB: b2BodyHandle; { The second attached body.}
collideConnected: Boolean; { Set this flag to true if the attached bodies should collide.}
linearOffset: b2Vec2; { Position of bodyB minus the position of bodyA, in bodyA's frame, in meters.}
angularOffset: Single; { The bodyB angle minus bodyA angle in radians.}
maxForce: Single; { The maximum motor force in N.}
maxTorque: Single; { The maximum motor torque in N-m.}
correctionFactor: Single; { Position correction factor in the range [0,1].}
class function Create: b2MotorJointDef; static; cdecl;
{ Initialize the bodies and offsets using the current transforms.}
procedure Initialize(bodyA: b2BodyHandle; bodyB: b2BodyHandle); cdecl;
end;
{ A motor joint is used to control the relative motion
between two bodies. A typical usage is to control the movement
of a dynamic body with respect to the ground.}
b2MotorJointWrapper = record
FHandle: b2MotorJointHandle;
procedure Destroy; cdecl;
class operator Implicit(handle: b2MotorJointHandle): b2MotorJointWrapper; overload;
class operator Implicit(wrapper: b2MotorJointWrapper): b2MotorJointHandle; overload;
{ Get the type of the concrete joint.}
function GetType: b2JointType; cdecl;
{ Get the first body attached to this joint.}
function GetBodyA: b2BodyHandle; cdecl;
{ Get the second body attached to this joint.}
function GetBodyB: b2BodyHandle; cdecl;
{ Get the anchor point on bodyA in world coordinates.}
function GetAnchorA: b2Vec2; cdecl;
{ Get the anchor point on bodyB in world coordinates.}
function GetAnchorB: b2Vec2; cdecl;
{ Get the reaction force on bodyB at the joint anchor in Newtons.}
function GetReactionForce(inv_dt: Single): b2Vec2; cdecl;
{ Get the reaction torque on bodyB in N*m.}
function GetReactionTorque(inv_dt: Single): Single; cdecl;
{ Get the next joint the world joint list.}
function GetNext: b2JointHandle; cdecl;
{ Get the user data pointer.}
function GetUserData: Pointer; cdecl;
{ Set the user data pointer.}
procedure SetUserData(data: Pointer); cdecl;
{ Short-cut function to determine if either body is inactive.}
function IsActive: Boolean; cdecl;
{ Get collide connected.
Note: modifying the collide connect flag won't work correctly because
the flag is only checked when fixture AABBs begin to overlap.}
function GetCollideConnected: Boolean; cdecl;
{ Dump this joint to the log file.}
procedure Dump; cdecl;
{ Shift the origin for any points stored in world coordinates.}
procedure ShiftOrigin(const [ref] newOrigin: b2Vec2); cdecl;
{ Set/get the target linear offset, in frame A, in meters.}
procedure SetLinearOffset(const [ref] linearOffset: b2Vec2); cdecl;
function GetLinearOffset: Pb2Vec2; cdecl;
{ Set/get the target angular offset, in radians.}
procedure SetAngularOffset(angularOffset: Single); cdecl;
function GetAngularOffset: Single; cdecl;
{ Set the maximum friction force in N.}
procedure SetMaxForce(force: Single); cdecl;
{ Get the maximum friction force in N.}
function GetMaxForce: Single; cdecl;
{ Set the maximum friction torque in N*m.}
procedure SetMaxTorque(torque: Single); cdecl;
{ Get the maximum friction torque in N*m.}
function GetMaxTorque: Single; cdecl;
{ Set the position correction factor in the range [0,1].}
procedure SetCorrectionFactor(factor: Single); cdecl;
{ Get the position correction factor in the range [0,1].}
function GetCorrectionFactor: Single; cdecl;
end;
{ Mouse joint definition. This requires a world target point,
tuning parameters, and the time step.}
b2MouseJointDef = record
&type: b2JointType; { The joint type is set automatically for concrete joint types.}
userData: Pointer; { Use this to attach application specific data to your joints.}
bodyA: b2BodyHandle; { The first attached body.}
bodyB: b2BodyHandle; { The second attached body.}
collideConnected: Boolean; { Set this flag to true if the attached bodies should collide.}
Filler1 : TDWordFiller;
target: b2Vec2; { The initial world target point. This is assumed
to coincide with the body anchor initially.}
maxForce: Single; { The maximum constraint force that can be exerted
to move the candidate body. Usually you will express
as some multiple of the weight (multiplier * mass * gravity).}
frequencyHz: Single; { The response speed.}
dampingRatio: Single; { The damping ratio. 0 = no damping, 1 = critical damping.}
Filler2 : TDWordFiller;
class function Create: b2MouseJointDef; static; cdecl;
end;
{ A mouse joint is used to make a point on a body track a
specified world point. This a soft constraint with a maximum
force. This allows the constraint to stretch and without
applying huge forces.
NOTE: this joint is not documented in the manual because it was
developed to be used in the testbed. If you want to learn how to
use the mouse joint, look at the testbed.}
b2MouseJointWrapper = record
FHandle: b2MouseJointHandle;
procedure Destroy; cdecl;
class operator Implicit(handle: b2MouseJointHandle): b2MouseJointWrapper; overload;
class operator Implicit(wrapper: b2MouseJointWrapper): b2MouseJointHandle; overload;
{ Get the type of the concrete joint.}
function GetType: b2JointType; cdecl;
{ Get the first body attached to this joint.}
function GetBodyA: b2BodyHandle; cdecl;
{ Get the second body attached to this joint.}
function GetBodyB: b2BodyHandle; cdecl;
{ Get the anchor point on bodyA in world coordinates.}
function GetAnchorA: b2Vec2; cdecl;
{ Get the anchor point on bodyB in world coordinates.}
function GetAnchorB: b2Vec2; cdecl;
{ Get the reaction force on bodyB at the joint anchor in Newtons.}
function GetReactionForce(inv_dt: Single): b2Vec2; cdecl;
{ Get the reaction torque on bodyB in N*m.}
function GetReactionTorque(inv_dt: Single): Single; cdecl;
{ Get the next joint the world joint list.}
function GetNext: b2JointHandle; cdecl;
{ Get the user data pointer.}
function GetUserData: Pointer; cdecl;
{ Set the user data pointer.}
procedure SetUserData(data: Pointer); cdecl;
{ Short-cut function to determine if either body is inactive.}
function IsActive: Boolean; cdecl;
{ Get collide connected.
Note: modifying the collide connect flag won't work correctly because
the flag is only checked when fixture AABBs begin to overlap.}
function GetCollideConnected: Boolean; cdecl;
{ Dump this joint to the log file.}
procedure Dump; cdecl;
{ Shift the origin for any points stored in world coordinates.}
procedure ShiftOrigin(const [ref] newOrigin: b2Vec2); cdecl;
{ Use this to update the target point.}
procedure SetTarget(const [ref] target: b2Vec2); cdecl;
function GetTarget: Pb2Vec2; cdecl;
{ Set/get the maximum force in Newtons.}
procedure SetMaxForce(force: Single); cdecl;
function GetMaxForce: Single; cdecl;
{ Set/get the frequency in Hertz.}
procedure SetFrequency(hz: Single); cdecl;
function GetFrequency: Single; cdecl;
{ Set/get the damping ratio (dimensionless).}
procedure SetDampingRatio(ratio: Single); cdecl;
function GetDampingRatio: Single; cdecl;
end;
{ Prismatic joint definition. This requires defining a line of
motion using an axis and an anchor point. The definition uses local
anchor points and a local axis so that the initial configuration
can violate the constraint slightly. The joint translation is zero
when the local anchor points coincide in world space. Using local
anchors and a local axis helps when saving and loading a game.}
b2PrismaticJointDef = record
&type: b2JointType; { The joint type is set automatically for concrete joint types.}
userData: Pointer; { Use this to attach application specific data to your joints.}
bodyA: b2BodyHandle; { The first attached body.}
bodyB: b2BodyHandle; { The second attached body.}
collideConnected: Boolean; { Set this flag to true if the attached bodies should collide.}
Filler1 : TDWordFiller;
localAnchorA: b2Vec2; { The local anchor point relative to bodyA's origin.}
localAnchorB: b2Vec2; { The local anchor point relative to bodyB's origin.}
localAxisA: b2Vec2; { The local translation unit axis in bodyA.}
referenceAngle: Single; { The constrained angle between the bodies: bodyB_angle - bodyA_angle.}
enableLimit: Boolean; { Enable/disable the joint limit.}
lowerTranslation: Single; { The lower translation limit, usually in meters.}
upperTranslation: Single; { The upper translation limit, usually in meters.}
enableMotor: Boolean; { Enable/disable the joint motor.}
maxMotorForce: Single; { The maximum motor torque, usually in N-m.}
motorSpeed: Single; { The desired motor speed in radians per second.}
Filler2 : TDWordFiller;
class function Create: b2PrismaticJointDef; static; cdecl;
{ Initialize the bodies, anchors, axis, and reference angle using the world
anchor and unit world axis.}
procedure Initialize(bodyA: b2BodyHandle; bodyB: b2BodyHandle; const [ref] anchor: b2Vec2; const [ref] axis: b2Vec2); cdecl;
end;
{ A prismatic joint. This joint provides one degree of freedom: translation
along an axis fixed in bodyA. Relative rotation is prevented. You can
use a joint limit to restrict the range of motion and a joint motor to
drive the motion or to model joint friction.}
b2PrismaticJointWrapper = record
FHandle: b2PrismaticJointHandle;
procedure Destroy; cdecl;
class operator Implicit(handle: b2PrismaticJointHandle): b2PrismaticJointWrapper; overload;
class operator Implicit(wrapper: b2PrismaticJointWrapper): b2PrismaticJointHandle; overload;
{ Get the type of the concrete joint.}
function GetType: b2JointType; cdecl;
{ Get the first body attached to this joint.}
function GetBodyA: b2BodyHandle; cdecl;
{ Get the second body attached to this joint.}
function GetBodyB: b2BodyHandle; cdecl;
{ Get the anchor point on bodyA in world coordinates.}
function GetAnchorA: b2Vec2; cdecl;
{ Get the anchor point on bodyB in world coordinates.}
function GetAnchorB: b2Vec2; cdecl;
{ Get the reaction force on bodyB at the joint anchor in Newtons.}
function GetReactionForce(inv_dt: Single): b2Vec2; cdecl;
{ Get the reaction torque on bodyB in N*m.}
function GetReactionTorque(inv_dt: Single): Single; cdecl;
{ Get the next joint the world joint list.}
function GetNext: b2JointHandle; cdecl;
{ Get the user data pointer.}
function GetUserData: Pointer; cdecl;
{ Set the user data pointer.}
procedure SetUserData(data: Pointer); cdecl;
{ Short-cut function to determine if either body is inactive.}
function IsActive: Boolean; cdecl;
{ Get collide connected.
Note: modifying the collide connect flag won't work correctly because
the flag is only checked when fixture AABBs begin to overlap.}
function GetCollideConnected: Boolean; cdecl;
{ Dump this joint to the log file.}
procedure Dump; cdecl;
{ Shift the origin for any points stored in world coordinates.}
procedure ShiftOrigin(const [ref] newOrigin: b2Vec2); cdecl;
{ The local anchor point relative to bodyA's origin.}
function GetLocalAnchorA: Pb2Vec2; cdecl;
{ The local anchor point relative to bodyB's origin.}
function GetLocalAnchorB: Pb2Vec2; cdecl;
{ The local joint axis relative to bodyA.}
function GetLocalAxisA: Pb2Vec2; cdecl;
{ Get the reference angle.}
function GetReferenceAngle: Single; cdecl;
{ Get the current joint translation, usually in meters.}
function GetJointTranslation: Single; cdecl;
{ Get the current joint translation speed, usually in meters per second.}
function GetJointSpeed: Single; cdecl;
{ Is the joint limit enabled?}
function IsLimitEnabled: Boolean; cdecl;
{ Enable/disable the joint limit.}
procedure EnableLimit(flag: Boolean); cdecl;
{ Get the lower joint limit, usually in meters.}
function GetLowerLimit: Single; cdecl;
{ Get the upper joint limit, usually in meters.}
function GetUpperLimit: Single; cdecl;
{ Set the joint limits, usually in meters.}
procedure SetLimits(lower: Single; upper: Single); cdecl;
{ Is the joint motor enabled?}
function IsMotorEnabled: Boolean; cdecl;
{ Enable/disable the joint motor.}
procedure EnableMotor(flag: Boolean); cdecl;
{ Set the motor speed, usually in meters per second.}
procedure SetMotorSpeed(speed: Single); cdecl;
{ Get the motor speed, usually in meters per second.}
function GetMotorSpeed: Single; cdecl;
{ Set the maximum motor force, usually in N.}
procedure SetMaxMotorForce(force: Single); cdecl;
function GetMaxMotorForce: Single; cdecl;
{ Get the current motor force given the inverse time step, usually in N.}
function GetMotorForce(inv_dt: Single): Single; cdecl;
end;
{ Pulley joint definition. This requires two ground anchors,
two dynamic body anchor points, and a pulley ratio.}
b2PulleyJointDef = record
&type: b2JointType; { The joint type is set automatically for concrete joint types.}
userData: Pointer; { Use this to attach application specific data to your joints.}
bodyA: b2BodyHandle; { The first attached body.}
bodyB: b2BodyHandle; { The second attached body.}
collideConnected: Boolean; { Set this flag to true if the attached bodies should collide.}
Filler1 : TDWordFiller;
groundAnchorA: b2Vec2; { The first ground anchor in world coordinates. This point never moves.}
groundAnchorB: b2Vec2; { The second ground anchor in world coordinates. This point never moves.}
localAnchorA: b2Vec2; { The local anchor point relative to bodyA's origin.}
localAnchorB: b2Vec2; { The local anchor point relative to bodyB's origin.}
lengthA: Single; { The a reference length for the segment attached to bodyA.}
lengthB: Single; { The a reference length for the segment attached to bodyB.}
ratio: Single; { The pulley ratio, used to simulate a block-and-tackle.}
Filler2 : TDWordFiller;
class function Create: b2PulleyJointDef; static; cdecl;
{ Initialize the bodies, anchors, lengths, max lengths, and ratio using the world anchors.}
procedure Initialize(bodyA: b2BodyHandle; bodyB: b2BodyHandle; const [ref] groundAnchorA: b2Vec2; const [ref] groundAnchorB: b2Vec2; const [ref] anchorA: b2Vec2; const [ref] anchorB: b2Vec2; ratio: Single); cdecl;
end;
{ The pulley joint is connected to two bodies and two fixed ground points.
The pulley supports a ratio such that:
length1 + ratio * length2 <= constant
Yes, the force transmitted is scaled by the ratio.
Warning: the pulley joint can get a bit squirrelly by itself. They often
work better when combined with prismatic joints. You should also cover the
the anchor points with static shapes to prevent one side from going to
zero length.}
b2PulleyJointWrapper = record
FHandle: b2PulleyJointHandle;
procedure Destroy; cdecl;
class operator Implicit(handle: b2PulleyJointHandle): b2PulleyJointWrapper; overload;
class operator Implicit(wrapper: b2PulleyJointWrapper): b2PulleyJointHandle; overload;
{ Get the type of the concrete joint.}
function GetType: b2JointType; cdecl;
{ Get the first body attached to this joint.}
function GetBodyA: b2BodyHandle; cdecl;
{ Get the second body attached to this joint.}
function GetBodyB: b2BodyHandle; cdecl;
{ Get the anchor point on bodyA in world coordinates.}
function GetAnchorA: b2Vec2; cdecl;
{ Get the anchor point on bodyB in world coordinates.}
function GetAnchorB: b2Vec2; cdecl;
{ Get the reaction force on bodyB at the joint anchor in Newtons.}
function GetReactionForce(inv_dt: Single): b2Vec2; cdecl;
{ Get the reaction torque on bodyB in N*m.}
function GetReactionTorque(inv_dt: Single): Single; cdecl;
{ Get the next joint the world joint list.}
function GetNext: b2JointHandle; cdecl;
{ Get the user data pointer.}
function GetUserData: Pointer; cdecl;
{ Set the user data pointer.}
procedure SetUserData(data: Pointer); cdecl;
{ Short-cut function to determine if either body is inactive.}
function IsActive: Boolean; cdecl;
{ Get collide connected.
Note: modifying the collide connect flag won't work correctly because
the flag is only checked when fixture AABBs begin to overlap.}
function GetCollideConnected: Boolean; cdecl;
{ Dump this joint to the log file.}
procedure Dump; cdecl;
{ Shift the origin for any points stored in world coordinates.}
procedure ShiftOrigin(const [ref] newOrigin: b2Vec2); cdecl;
{ Get the first ground anchor.}
function GetGroundAnchorA: b2Vec2; cdecl;
{ Get the second ground anchor.}
function GetGroundAnchorB: b2Vec2; cdecl;
{ Get the current length of the segment attached to bodyA.}
function GetLengthA: Single; cdecl;
{ Get the current length of the segment attached to bodyB.}
function GetLengthB: Single; cdecl;
{ Get the pulley ratio.}
function GetRatio: Single; cdecl;
{ Get the current length of the segment attached to bodyA.}
function GetCurrentLengthA: Single; cdecl;
{ Get the current length of the segment attached to bodyB.}
function GetCurrentLengthB: Single; cdecl;
end;
{ Revolute joint definition. This requires defining an
anchor point where the bodies are joined. The definition
uses local anchor points so that the initial configuration
can violate the constraint slightly. You also need to
specify the initial relative angle for joint limits. This
helps when saving and loading a game.
The local anchor points are measured from the body's origin
rather than the center of mass because:
1. you might not know where the center of mass will be.
2. if you add/remove shapes from a body and recompute the mass,
the joints will be broken.}
b2RevoluteJointDef = record
&type: b2JointType; { The joint type is set automatically for concrete joint types.}
userData: Pointer; { Use this to attach application specific data to your joints.}
bodyA: b2BodyHandle; { The first attached body.}
bodyB: b2BodyHandle; { The second attached body.}
collideConnected: Boolean; { Set this flag to true if the attached bodies should collide.}
Filler1 : TDWordFiller;
localAnchorA: b2Vec2; { The local anchor point relative to bodyA's origin.}
localAnchorB: b2Vec2; { The local anchor point relative to bodyB's origin.}
referenceAngle: Single; { The bodyB angle minus bodyA angle in the reference state (radians).}
enableLimit: Boolean; { A flag to enable joint limits.}
lowerAngle: Single; { The lower angle for the joint limit (radians).}
upperAngle: Single; { The upper angle for the joint limit (radians).}
enableMotor: Boolean; { A flag to enable the joint motor.}
motorSpeed: Single; { The desired motor speed. Usually in radians per second.}
maxMotorTorque: Single; { The maximum motor torque used to achieve the desired motor speed.
Usually in N-m.}
Filler2 : TDWordFiller;
class function Create: b2RevoluteJointDef; static; cdecl;
{ Initialize the bodies, anchors, and reference angle using a world
anchor point.}
procedure Initialize(bodyA: b2BodyHandle; bodyB: b2BodyHandle; const [ref] anchor: b2Vec2); cdecl;
end;
{ A revolute joint constrains two bodies to share a common point while they
are free to rotate about the point. The relative rotation about the shared
point is the joint angle. You can limit the relative rotation with
a joint limit that specifies a lower and upper angle. You can use a motor
to drive the relative rotation about the shared point. A maximum motor torque
is provided so that infinite forces are not generated.}
b2RevoluteJointWrapper = record
FHandle: b2RevoluteJointHandle;
procedure Destroy; cdecl;
class operator Implicit(handle: b2RevoluteJointHandle): b2RevoluteJointWrapper; overload;
class operator Implicit(wrapper: b2RevoluteJointWrapper): b2RevoluteJointHandle; overload;
{ Get the type of the concrete joint.}
function GetType: b2JointType; cdecl;
{ Get the first body attached to this joint.}
function GetBodyA: b2BodyHandle; cdecl;
{ Get the second body attached to this joint.}
function GetBodyB: b2BodyHandle; cdecl;
{ Get the anchor point on bodyA in world coordinates.}
function GetAnchorA: b2Vec2; cdecl;
{ Get the anchor point on bodyB in world coordinates.}
function GetAnchorB: b2Vec2; cdecl;
{ Get the reaction force on bodyB at the joint anchor in Newtons.}
function GetReactionForce(inv_dt: Single): b2Vec2; cdecl;
{ Get the reaction torque on bodyB in N*m.}
function GetReactionTorque(inv_dt: Single): Single; cdecl;
{ Get the next joint the world joint list.}
function GetNext: b2JointHandle; cdecl;
{ Get the user data pointer.}
function GetUserData: Pointer; cdecl;
{ Set the user data pointer.}
procedure SetUserData(data: Pointer); cdecl;
{ Short-cut function to determine if either body is inactive.}
function IsActive: Boolean; cdecl;
{ Get collide connected.
Note: modifying the collide connect flag won't work correctly because
the flag is only checked when fixture AABBs begin to overlap.}
function GetCollideConnected: Boolean; cdecl;
{ Dump this joint to the log file.}
procedure Dump; cdecl;
{ Shift the origin for any points stored in world coordinates.}
procedure ShiftOrigin(const [ref] newOrigin: b2Vec2); cdecl;
{ The local anchor point relative to bodyA's origin.}
function GetLocalAnchorA: Pb2Vec2; cdecl;
{ The local anchor point relative to bodyB's origin.}
function GetLocalAnchorB: Pb2Vec2; cdecl;
{ Get the reference angle.}
function GetReferenceAngle: Single; cdecl;
{ Get the current joint angle in radians.}
function GetJointAngle: Single; cdecl;
{ Get the current joint angle speed in radians per second.}
function GetJointSpeed: Single; cdecl;
{ Is the joint limit enabled?}
function IsLimitEnabled: Boolean; cdecl;
{ Enable/disable the joint limit.}
procedure EnableLimit(flag: Boolean); cdecl;
{ Get the lower joint limit in radians.}
function GetLowerLimit: Single; cdecl;
{ Get the upper joint limit in radians.}
function GetUpperLimit: Single; cdecl;
{ Set the joint limits in radians.}
procedure SetLimits(lower: Single; upper: Single); cdecl;
{ Is the joint motor enabled?}
function IsMotorEnabled: Boolean; cdecl;
{ Enable/disable the joint motor.}
procedure EnableMotor(flag: Boolean); cdecl;
{ Set the motor speed in radians per second.}
procedure SetMotorSpeed(speed: Single); cdecl;
{ Get the motor speed in radians per second.}
function GetMotorSpeed: Single; cdecl;
{ Set the maximum motor torque, usually in N-m.}
procedure SetMaxMotorTorque(torque: Single); cdecl;
function GetMaxMotorTorque: Single; cdecl;
{ Get the current motor torque given the inverse time step.
Unit is N*m.}
function GetMotorTorque(inv_dt: Single): Single; cdecl;
end;
{ Rope joint definition. This requires two body anchor points and
a maximum lengths.
Note: by default the connected objects will not collide.
see collideConnected in b2JointDef.}
b2RopeJointDef = record
&type: b2JointType; { The joint type is set automatically for concrete joint types.}
userData: Pointer; { Use this to attach application specific data to your joints.}
bodyA: b2BodyHandle; { The first attached body.}
bodyB: b2BodyHandle; { The second attached body.}
collideConnected: Boolean; { Set this flag to true if the attached bodies should collide.}
Filler1 : TDWordFiller;
localAnchorA: b2Vec2; { The local anchor point relative to bodyA's origin.}
localAnchorB: b2Vec2; { The local anchor point relative to bodyB's origin.}
maxLength: Single; { The maximum length of the rope.
Warning: this must be larger than b2_linearSlop or
the joint will have no effect.}
Filler2 : TDWordFiller;
class function Create: b2RopeJointDef; static; cdecl;
end;
{ A rope joint enforces a maximum distance between two points
on two bodies. It has no other effect.
Warning: if you attempt to change the maximum length during
the simulation you will get some non-physical behavior.
A model that would allow you to dynamically modify the length
would have some sponginess, so I chose not to implement it
that way. See b2DistanceJoint if you want to dynamically
control length.}
b2RopeJointWrapper = record
FHandle: b2RopeJointHandle;
procedure Destroy; cdecl;
class operator Implicit(handle: b2RopeJointHandle): b2RopeJointWrapper; overload;
class operator Implicit(wrapper: b2RopeJointWrapper): b2RopeJointHandle; overload;
{ Get the type of the concrete joint.}
function GetType: b2JointType; cdecl;
{ Get the first body attached to this joint.}
function GetBodyA: b2BodyHandle; cdecl;
{ Get the second body attached to this joint.}
function GetBodyB: b2BodyHandle; cdecl;
{ Get the anchor point on bodyA in world coordinates.}
function GetAnchorA: b2Vec2; cdecl;
{ Get the anchor point on bodyB in world coordinates.}
function GetAnchorB: b2Vec2; cdecl;
{ Get the reaction force on bodyB at the joint anchor in Newtons.}
function GetReactionForce(inv_dt: Single): b2Vec2; cdecl;
{ Get the reaction torque on bodyB in N*m.}
function GetReactionTorque(inv_dt: Single): Single; cdecl;
{ Get the next joint the world joint list.}
function GetNext: b2JointHandle; cdecl;
{ Get the user data pointer.}
function GetUserData: Pointer; cdecl;
{ Set the user data pointer.}
procedure SetUserData(data: Pointer); cdecl;
{ Short-cut function to determine if either body is inactive.}
function IsActive: Boolean; cdecl;
{ Get collide connected.
Note: modifying the collide connect flag won't work correctly because
the flag is only checked when fixture AABBs begin to overlap.}
function GetCollideConnected: Boolean; cdecl;
{ Dump this joint to the log file.}
procedure Dump; cdecl;
{ Shift the origin for any points stored in world coordinates.}
procedure ShiftOrigin(const [ref] newOrigin: b2Vec2); cdecl;
{ The local anchor point relative to bodyA's origin.}
function GetLocalAnchorA: Pb2Vec2; cdecl;
{ The local anchor point relative to bodyB's origin.}
function GetLocalAnchorB: Pb2Vec2; cdecl;
{ Set/Get the maximum length of the rope.}
procedure SetMaxLength(length: Single); cdecl;
function GetMaxLength: Single; cdecl;
function GetLimitState: b2LimitState; cdecl;
end;
{ Weld joint definition. You need to specify local anchor points
where they are attached and the relative body angle. The position
of the anchor points is important for computing the reaction torque.}
b2WeldJointDef = record
&type: b2JointType; { The joint type is set automatically for concrete joint types.}
userData: Pointer; { Use this to attach application specific data to your joints.}
bodyA: b2BodyHandle; { The first attached body.}
bodyB: b2BodyHandle; { The second attached body.}
collideConnected: Boolean; { Set this flag to true if the attached bodies should collide.}
Filler1 : TDWordFiller;
localAnchorA: b2Vec2; { The local anchor point relative to bodyA's origin.}
localAnchorB: b2Vec2; { The local anchor point relative to bodyB's origin.}
referenceAngle: Single; { The bodyB angle minus bodyA angle in the reference state (radians).}
frequencyHz: Single; { The mass-spring-damper frequency in Hertz. Rotation only.
Disable softness with a value of 0.}
dampingRatio: Single; { The damping ratio. 0 = no damping, 1 = critical damping.}
Filler2 : TDWordFiller;
class function Create: b2WeldJointDef; static; cdecl;
{ Initialize the bodies, anchors, and reference angle using a world
anchor point.}
procedure Initialize(bodyA: b2BodyHandle; bodyB: b2BodyHandle; const [ref] anchor: b2Vec2); cdecl;
end;
{ A weld joint essentially glues two bodies together. A weld joint may
distort somewhat because the island constraint solver is approximate.}
b2WeldJointWrapper = record
FHandle: b2WeldJointHandle;
procedure Destroy; cdecl;
class operator Implicit(handle: b2WeldJointHandle): b2WeldJointWrapper; overload;
class operator Implicit(wrapper: b2WeldJointWrapper): b2WeldJointHandle; overload;
{ Get the type of the concrete joint.}
function GetType: b2JointType; cdecl;
{ Get the first body attached to this joint.}
function GetBodyA: b2BodyHandle; cdecl;
{ Get the second body attached to this joint.}
function GetBodyB: b2BodyHandle; cdecl;
{ Get the anchor point on bodyA in world coordinates.}
function GetAnchorA: b2Vec2; cdecl;
{ Get the anchor point on bodyB in world coordinates.}
function GetAnchorB: b2Vec2; cdecl;
{ Get the reaction force on bodyB at the joint anchor in Newtons.}
function GetReactionForce(inv_dt: Single): b2Vec2; cdecl;
{ Get the reaction torque on bodyB in N*m.}
function GetReactionTorque(inv_dt: Single): Single; cdecl;
{ Get the next joint the world joint list.}
function GetNext: b2JointHandle; cdecl;
{ Get the user data pointer.}
function GetUserData: Pointer; cdecl;
{ Set the user data pointer.}
procedure SetUserData(data: Pointer); cdecl;
{ Short-cut function to determine if either body is inactive.}
function IsActive: Boolean; cdecl;
{ Get collide connected.
Note: modifying the collide connect flag won't work correctly because
the flag is only checked when fixture AABBs begin to overlap.}
function GetCollideConnected: Boolean; cdecl;
{ Dump this joint to the log file.}
procedure Dump; cdecl;
{ Shift the origin for any points stored in world coordinates.}
procedure ShiftOrigin(const [ref] newOrigin: b2Vec2); cdecl;
{ The local anchor point relative to bodyA's origin.}
function GetLocalAnchorA: Pb2Vec2; cdecl;
{ The local anchor point relative to bodyB's origin.}
function GetLocalAnchorB: Pb2Vec2; cdecl;
{ Get the reference angle.}
function GetReferenceAngle: Single; cdecl;
{ Set/get frequency in Hz.}
procedure SetFrequency(hz: Single); cdecl;
function GetFrequency: Single; cdecl;
{ Set/get damping ratio.}
procedure SetDampingRatio(ratio: Single); cdecl;
function GetDampingRatio: Single; cdecl;
end;
{ Wheel joint definition. This requires defining a line of
motion using an axis and an anchor point. The definition uses local
anchor points and a local axis so that the initial configuration
can violate the constraint slightly. The joint translation is zero
when the local anchor points coincide in world space. Using local
anchors and a local axis helps when saving and loading a game.}
b2WheelJointDef = record
&type: b2JointType; { The joint type is set automatically for concrete joint types.}
userData: Pointer; { Use this to attach application specific data to your joints.}
bodyA: b2BodyHandle; { The first attached body.}
bodyB: b2BodyHandle; { The second attached body.}
collideConnected: Boolean; { Set this flag to true if the attached bodies should collide.}
Filler1 : TDWordFiller;
localAnchorA: b2Vec2; { The local anchor point relative to bodyA's origin.}
localAnchorB: b2Vec2; { The local anchor point relative to bodyB's origin.}
localAxisA: b2Vec2; { The local translation axis in bodyA.}
enableMotor: Boolean; { Enable/disable the joint motor.}
maxMotorTorque: Single; { The maximum motor torque, usually in N-m.}
motorSpeed: Single; { The desired motor speed in radians per second.}
frequencyHz: Single; { Suspension frequency, zero indicates no suspension}
dampingRatio: Single; { Suspension damping ratio, one indicates critical damping}
Filler2 : TDWordFiller;
class function Create: b2WheelJointDef; static; cdecl;
{ Initialize the bodies, anchors, axis, and reference angle using the world
anchor and world axis.}
procedure Initialize(bodyA: b2BodyHandle; bodyB: b2BodyHandle; const [ref] anchor: b2Vec2; const [ref] axis: b2Vec2); cdecl;
end;
{ A wheel joint. This joint provides two degrees of freedom: translation
along an axis fixed in bodyA and rotation in the plane. In other words, it is a point to
line constraint with a rotational motor and a linear spring/damper.
This joint is designed for vehicle suspensions.}
b2WheelJointWrapper = record
FHandle: b2WheelJointHandle;
procedure Destroy; cdecl;
class operator Implicit(handle: b2WheelJointHandle): b2WheelJointWrapper; overload;
class operator Implicit(wrapper: b2WheelJointWrapper): b2WheelJointHandle; overload;
{ Get the type of the concrete joint.}
function GetType: b2JointType; cdecl;
{ Get the first body attached to this joint.}
function GetBodyA: b2BodyHandle; cdecl;
{ Get the second body attached to this joint.}
function GetBodyB: b2BodyHandle; cdecl;
{ Get the anchor point on bodyA in world coordinates.}
function GetAnchorA: b2Vec2; cdecl;
{ Get the anchor point on bodyB in world coordinates.}
function GetAnchorB: b2Vec2; cdecl;
{ Get the reaction force on bodyB at the joint anchor in Newtons.}
function GetReactionForce(inv_dt: Single): b2Vec2; cdecl;
{ Get the reaction torque on bodyB in N*m.}
function GetReactionTorque(inv_dt: Single): Single; cdecl;
{ Get the next joint the world joint list.}
function GetNext: b2JointHandle; cdecl;
{ Get the user data pointer.}
function GetUserData: Pointer; cdecl;
{ Set the user data pointer.}
procedure SetUserData(data: Pointer); cdecl;
{ Short-cut function to determine if either body is inactive.}
function IsActive: Boolean; cdecl;
{ Get collide connected.
Note: modifying the collide connect flag won't work correctly because
the flag is only checked when fixture AABBs begin to overlap.}
function GetCollideConnected: Boolean; cdecl;
{ Dump this joint to the log file.}
procedure Dump; cdecl;
{ Shift the origin for any points stored in world coordinates.}
procedure ShiftOrigin(const [ref] newOrigin: b2Vec2); cdecl;
{ The local anchor point relative to bodyA's origin.}
function GetLocalAnchorA: Pb2Vec2; cdecl;
{ The local anchor point relative to bodyB's origin.}
function GetLocalAnchorB: Pb2Vec2; cdecl;
{ The local joint axis relative to bodyA.}
function GetLocalAxisA: Pb2Vec2; cdecl;
{ Get the current joint translation, usually in meters.}
function GetJointTranslation: Single; cdecl;
{ Get the current joint translation speed, usually in meters per second.}
function GetJointSpeed: Single; cdecl;
{ Is the joint motor enabled?}
function IsMotorEnabled: Boolean; cdecl;
{ Enable/disable the joint motor.}
procedure EnableMotor(flag: Boolean); cdecl;
{ Set the motor speed, usually in radians per second.}
procedure SetMotorSpeed(speed: Single); cdecl;
{ Get the motor speed, usually in radians per second.}
function GetMotorSpeed: Single; cdecl;
{ Set/Get the maximum motor force, usually in N-m.}
procedure SetMaxMotorTorque(torque: Single); cdecl;
function GetMaxMotorTorque: Single; cdecl;
{ Get the current motor torque given the inverse time step, usually in N-m.}
function GetMotorTorque(inv_dt: Single): Single; cdecl;
{ Set/Get the spring frequency in hertz. Setting the frequency to zero disables the spring.}
procedure SetSpringFrequencyHz(hz: Single); cdecl;
function GetSpringFrequencyHz: Single; cdecl;
{ Set/Get the spring damping ratio}
procedure SetSpringDampingRatio(ratio: Single); cdecl;
function GetSpringDampingRatio: Single; cdecl;
end;
{ ===== Delegate interfaces ===== }
Ib2DestructionListener = interface
['{2DDB25E4-9B99-E391-EF9A-62D1BDC2ABAC}']
procedure SayGoodbye(joint: b2JointHandle); overload; cdecl;
procedure SayGoodbye(fixture: Pb2Fixture); overload; cdecl;
end;
Ib2ContactFilter = interface
['{9BE3CC10-3001-AA1F-3A69-3AF908806081}']
function ShouldCollide(fixtureA: Pb2Fixture; fixtureB: Pb2Fixture): Boolean; cdecl;
end;
Ib2ContactListener = interface
['{457D45B8-C600-3A28-CE8D-7ED8741412D8}']
procedure BeginContact(contact: b2ContactHandle); cdecl;
procedure EndContact(contact: b2ContactHandle); cdecl;
procedure PreSolve(contact: b2ContactHandle; oldManifold: Pb2Manifold); cdecl;
procedure PostSolve(contact: b2ContactHandle; impulse: Pb2ContactImpulse); cdecl;
end;
Ib2QueryCallback = interface
['{FA12D838-B458-10AB-2E02-61056056D805}']
function ReportFixture(fixture: Pb2Fixture): Boolean; cdecl;
end;
Ib2RayCastCallback = interface
['{8E1114AB-969E-8C96-98C4-41096DDCBFA5}']
function ReportFixture(fixture: Pb2Fixture; const [ref] point: b2Vec2; const [ref] normal: b2Vec2; fraction: Single): Single; cdecl;
end;
{ ===== CreateDestroy of Delegate interfaces ===== }
function Create_b2DestructionListener_delegate(Intf: Ib2DestructionListener): b2DestructionListenerHandle; cdecl;
procedure Destroy_b2DestructionListener_delegate(handle: b2DestructionListenerHandle); cdecl;
function Create_b2ContactFilter_delegate(Intf: Ib2ContactFilter): b2ContactFilterHandle; cdecl;
procedure Destroy_b2ContactFilter_delegate(handle: b2ContactFilterHandle); cdecl;
function Create_b2ContactListener_delegate(Intf: Ib2ContactListener): b2ContactListenerHandle; cdecl;
procedure Destroy_b2ContactListener_delegate(handle: b2ContactListenerHandle); cdecl;
function Create_b2QueryCallback_delegate(Intf: Ib2QueryCallback): b2QueryCallbackHandle; cdecl;
procedure Destroy_b2QueryCallback_delegate(handle: b2QueryCallbackHandle); cdecl;
function Create_b2RayCastCallback_delegate(Intf: Ib2RayCastCallback): b2RayCastCallbackHandle; cdecl;
procedure Destroy_b2RayCastCallback_delegate(handle: b2RayCastCallbackHandle); cdecl;
function b2MixFriction(friction1: Single; friction2: Single): Single; cdecl;
function b2MixRestitution(restitution1: Single; restitution2: Single): Single; cdecl;
implementation
const
{$IFDEF MSWINDOWS}
LIB_NAME = 'FlatBox2DDyn.dll';
{$IFDEF WIN64}
_PU = '';
{$ELSE}
_PU = '_';
{$ENDIF}
{$ENDIF}
{$IFDEF ANDROID}
LIB_NAME = 'libFlatBox2D.a';
_PU = '';
{$ENDIF}
{$IFDEF MACOS}
{$IFDEF IOS}
LIB_NAME = 'libFlatBox2D.a';
{$ELSE}
LIB_NAME = 'libFlatBox2DDyn.dylib';
{$ENDIF}
{$IFDEF UNDERSCOREIMPORTNAME}
_PU = '_';
{$ELSE}
_PU = '';
{$ENDIF}
{$ENDIF}
function Create_b2DestructionListener_delegate; cdecl; external LIB_NAME name _PU + 'Create_b2DestructionListener_delegate'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure Destroy_b2DestructionListener_delegate; cdecl; external LIB_NAME name _PU + 'Destroy_b2DestructionListener_delegate'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function Create_b2ContactFilter_delegate; cdecl; external LIB_NAME name _PU + 'Create_b2ContactFilter_delegate'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure Destroy_b2ContactFilter_delegate; cdecl; external LIB_NAME name _PU + 'Destroy_b2ContactFilter_delegate'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function Create_b2ContactListener_delegate; cdecl; external LIB_NAME name _PU + 'Create_b2ContactListener_delegate'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure Destroy_b2ContactListener_delegate; cdecl; external LIB_NAME name _PU + 'Destroy_b2ContactListener_delegate'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function Create_b2QueryCallback_delegate; cdecl; external LIB_NAME name _PU + 'Create_b2QueryCallback_delegate'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure Destroy_b2QueryCallback_delegate; cdecl; external LIB_NAME name _PU + 'Destroy_b2QueryCallback_delegate'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function Create_b2RayCastCallback_delegate; cdecl; external LIB_NAME name _PU + 'Create_b2RayCastCallback_delegate'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure Destroy_b2RayCastCallback_delegate; cdecl; external LIB_NAME name _PU + 'Destroy_b2RayCastCallback_delegate'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
{ ===== Record methods: import and definition ===== }
function b2BodyDef_Create: b2BodyDef; cdecl; external LIB_NAME name _PU + 'b2BodyDef_b2BodyDef_1'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2BodyDef.Create: b2BodyDef; cdecl;
begin
Result := b2BodyDef_Create;
end;
class operator b2BodyWrapper.Implicit(handle: b2BodyHandle): b2BodyWrapper;
begin
Result.FHandle := handle;
end;
class operator b2BodyWrapper.Implicit(wrapper: b2BodyWrapper): b2BodyHandle;
begin
Result := wrapper.FHandle;
end;
function b2Body_CreateFixture(_self: b2BodyHandle; def: Pb2FixtureDef): Pb2Fixture; overload; cdecl; external LIB_NAME name _PU + 'b2Body_CreateFixture'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2BodyWrapper.CreateFixture(def: Pb2FixtureDef): Pb2Fixture; cdecl;
begin
Result := b2Body_CreateFixture(FHandle, def)
end;
function b2Body_CreateFixture(_self: b2BodyHandle; shape: b2ShapeHandle; density: Single): Pb2Fixture; overload; cdecl; external LIB_NAME name _PU + 'b2Body_CreateFixture2'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2BodyWrapper.CreateFixture(shape: b2ShapeHandle; density: Single): Pb2Fixture; cdecl;
begin
Result := b2Body_CreateFixture(FHandle, shape, density)
end;
procedure b2Body_DestroyFixture(_self: b2BodyHandle; fixture: Pb2Fixture); cdecl; external LIB_NAME name _PU + 'b2Body_DestroyFixture'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2BodyWrapper.DestroyFixture(fixture: Pb2Fixture); cdecl;
begin
b2Body_DestroyFixture(FHandle, fixture)
end;
procedure b2Body_SetTransform(_self: b2BodyHandle; const [ref] position: b2Vec2; angle: Single); cdecl; external LIB_NAME name _PU + 'b2Body_SetTransform'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2BodyWrapper.SetTransform(const [ref] position: b2Vec2; angle: Single); cdecl;
begin
b2Body_SetTransform(FHandle, position, angle)
end;
function b2Body_GetTransform(_self: b2BodyHandle): Pb2Transform; cdecl; external LIB_NAME name _PU + 'b2Body_GetTransform'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2BodyWrapper.GetTransform: Pb2Transform; cdecl;
begin
Result := b2Body_GetTransform(FHandle)
end;
function b2Body_GetPosition(_self: b2BodyHandle): Pb2Vec2; cdecl; external LIB_NAME name _PU + 'b2Body_GetPosition'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2BodyWrapper.GetPosition: Pb2Vec2; cdecl;
begin
Result := b2Body_GetPosition(FHandle)
end;
function b2Body_GetAngle(_self: b2BodyHandle): Single; cdecl; external LIB_NAME name _PU + 'b2Body_GetAngle'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2BodyWrapper.GetAngle: Single; cdecl;
begin
Result := b2Body_GetAngle(FHandle)
end;
function b2Body_GetWorldCenter(_self: b2BodyHandle): Pb2Vec2; cdecl; external LIB_NAME name _PU + 'b2Body_GetWorldCenter'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2BodyWrapper.GetWorldCenter: Pb2Vec2; cdecl;
begin
Result := b2Body_GetWorldCenter(FHandle)
end;
function b2Body_GetLocalCenter(_self: b2BodyHandle): Pb2Vec2; cdecl; external LIB_NAME name _PU + 'b2Body_GetLocalCenter'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2BodyWrapper.GetLocalCenter: Pb2Vec2; cdecl;
begin
Result := b2Body_GetLocalCenter(FHandle)
end;
procedure b2Body_SetLinearVelocity(_self: b2BodyHandle; const [ref] v: b2Vec2); cdecl; external LIB_NAME name _PU + 'b2Body_SetLinearVelocity'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2BodyWrapper.SetLinearVelocity(const [ref] v: b2Vec2); cdecl;
begin
b2Body_SetLinearVelocity(FHandle, v)
end;
function b2Body_GetLinearVelocity(_self: b2BodyHandle): Pb2Vec2; cdecl; external LIB_NAME name _PU + 'b2Body_GetLinearVelocity'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2BodyWrapper.GetLinearVelocity: Pb2Vec2; cdecl;
begin
Result := b2Body_GetLinearVelocity(FHandle)
end;
procedure b2Body_SetAngularVelocity(_self: b2BodyHandle; omega: Single); cdecl; external LIB_NAME name _PU + 'b2Body_SetAngularVelocity'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2BodyWrapper.SetAngularVelocity(omega: Single); cdecl;
begin
b2Body_SetAngularVelocity(FHandle, omega)
end;
function b2Body_GetAngularVelocity(_self: b2BodyHandle): Single; cdecl; external LIB_NAME name _PU + 'b2Body_GetAngularVelocity'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2BodyWrapper.GetAngularVelocity: Single; cdecl;
begin
Result := b2Body_GetAngularVelocity(FHandle)
end;
procedure b2Body_ApplyForce(_self: b2BodyHandle; const [ref] force: b2Vec2; const [ref] point: b2Vec2; wake: Boolean); cdecl; external LIB_NAME name _PU + 'b2Body_ApplyForce'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2BodyWrapper.ApplyForce(const [ref] force: b2Vec2; const [ref] point: b2Vec2; wake: Boolean); cdecl;
begin
b2Body_ApplyForce(FHandle, force, point, wake)
end;
procedure b2Body_ApplyForceToCenter(_self: b2BodyHandle; const [ref] force: b2Vec2; wake: Boolean); cdecl; external LIB_NAME name _PU + 'b2Body_ApplyForceToCenter'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2BodyWrapper.ApplyForceToCenter(const [ref] force: b2Vec2; wake: Boolean); cdecl;
begin
b2Body_ApplyForceToCenter(FHandle, force, wake)
end;
procedure b2Body_ApplyTorque(_self: b2BodyHandle; torque: Single; wake: Boolean); cdecl; external LIB_NAME name _PU + 'b2Body_ApplyTorque'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2BodyWrapper.ApplyTorque(torque: Single; wake: Boolean); cdecl;
begin
b2Body_ApplyTorque(FHandle, torque, wake)
end;
procedure b2Body_ApplyLinearImpulse(_self: b2BodyHandle; const [ref] impulse: b2Vec2; const [ref] point: b2Vec2; wake: Boolean); cdecl; external LIB_NAME name _PU + 'b2Body_ApplyLinearImpulse'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2BodyWrapper.ApplyLinearImpulse(const [ref] impulse: b2Vec2; const [ref] point: b2Vec2; wake: Boolean); cdecl;
begin
b2Body_ApplyLinearImpulse(FHandle, impulse, point, wake)
end;
procedure b2Body_ApplyAngularImpulse(_self: b2BodyHandle; impulse: Single; wake: Boolean); cdecl; external LIB_NAME name _PU + 'b2Body_ApplyAngularImpulse'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2BodyWrapper.ApplyAngularImpulse(impulse: Single; wake: Boolean); cdecl;
begin
b2Body_ApplyAngularImpulse(FHandle, impulse, wake)
end;
function b2Body_GetMass(_self: b2BodyHandle): Single; cdecl; external LIB_NAME name _PU + 'b2Body_GetMass'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2BodyWrapper.GetMass: Single; cdecl;
begin
Result := b2Body_GetMass(FHandle)
end;
function b2Body_GetInertia(_self: b2BodyHandle): Single; cdecl; external LIB_NAME name _PU + 'b2Body_GetInertia'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2BodyWrapper.GetInertia: Single; cdecl;
begin
Result := b2Body_GetInertia(FHandle)
end;
procedure b2Body_GetMassData(_self: b2BodyHandle; data: Pb2MassData); cdecl; external LIB_NAME name _PU + 'b2Body_GetMassData'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2BodyWrapper.GetMassData(data: Pb2MassData); cdecl;
begin
b2Body_GetMassData(FHandle, data)
end;
procedure b2Body_SetMassData(_self: b2BodyHandle; data: Pb2MassData); cdecl; external LIB_NAME name _PU + 'b2Body_SetMassData'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2BodyWrapper.SetMassData(data: Pb2MassData); cdecl;
begin
b2Body_SetMassData(FHandle, data)
end;
procedure b2Body_ResetMassData(_self: b2BodyHandle); cdecl; external LIB_NAME name _PU + 'b2Body_ResetMassData'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2BodyWrapper.ResetMassData; cdecl;
begin
b2Body_ResetMassData(FHandle)
end;
function b2Body_GetWorldPoint(_self: b2BodyHandle; const [ref] localPoint: b2Vec2): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2Body_GetWorldPoint'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2BodyWrapper.GetWorldPoint(const [ref] localPoint: b2Vec2): b2Vec2; cdecl;
begin
Result := b2Body_GetWorldPoint(FHandle, localPoint)
end;
function b2Body_GetWorldVector(_self: b2BodyHandle; const [ref] localVector: b2Vec2): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2Body_GetWorldVector'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2BodyWrapper.GetWorldVector(const [ref] localVector: b2Vec2): b2Vec2; cdecl;
begin
Result := b2Body_GetWorldVector(FHandle, localVector)
end;
function b2Body_GetLocalPoint(_self: b2BodyHandle; const [ref] worldPoint: b2Vec2): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2Body_GetLocalPoint'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2BodyWrapper.GetLocalPoint(const [ref] worldPoint: b2Vec2): b2Vec2; cdecl;
begin
Result := b2Body_GetLocalPoint(FHandle, worldPoint)
end;
function b2Body_GetLocalVector(_self: b2BodyHandle; const [ref] worldVector: b2Vec2): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2Body_GetLocalVector'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2BodyWrapper.GetLocalVector(const [ref] worldVector: b2Vec2): b2Vec2; cdecl;
begin
Result := b2Body_GetLocalVector(FHandle, worldVector)
end;
function b2Body_GetLinearVelocityFromWorldPoint(_self: b2BodyHandle; const [ref] worldPoint: b2Vec2): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2Body_GetLinearVelocityFromWorldPoint'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2BodyWrapper.GetLinearVelocityFromWorldPoint(const [ref] worldPoint: b2Vec2): b2Vec2; cdecl;
begin
Result := b2Body_GetLinearVelocityFromWorldPoint(FHandle, worldPoint)
end;
function b2Body_GetLinearVelocityFromLocalPoint(_self: b2BodyHandle; const [ref] localPoint: b2Vec2): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2Body_GetLinearVelocityFromLocalPoint'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2BodyWrapper.GetLinearVelocityFromLocalPoint(const [ref] localPoint: b2Vec2): b2Vec2; cdecl;
begin
Result := b2Body_GetLinearVelocityFromLocalPoint(FHandle, localPoint)
end;
function b2Body_GetLinearDamping(_self: b2BodyHandle): Single; cdecl; external LIB_NAME name _PU + 'b2Body_GetLinearDamping'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2BodyWrapper.GetLinearDamping: Single; cdecl;
begin
Result := b2Body_GetLinearDamping(FHandle)
end;
procedure b2Body_SetLinearDamping(_self: b2BodyHandle; linearDamping: Single); cdecl; external LIB_NAME name _PU + 'b2Body_SetLinearDamping'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2BodyWrapper.SetLinearDamping(linearDamping: Single); cdecl;
begin
b2Body_SetLinearDamping(FHandle, linearDamping)
end;
function b2Body_GetAngularDamping(_self: b2BodyHandle): Single; cdecl; external LIB_NAME name _PU + 'b2Body_GetAngularDamping'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2BodyWrapper.GetAngularDamping: Single; cdecl;
begin
Result := b2Body_GetAngularDamping(FHandle)
end;
procedure b2Body_SetAngularDamping(_self: b2BodyHandle; angularDamping: Single); cdecl; external LIB_NAME name _PU + 'b2Body_SetAngularDamping'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2BodyWrapper.SetAngularDamping(angularDamping: Single); cdecl;
begin
b2Body_SetAngularDamping(FHandle, angularDamping)
end;
function b2Body_GetGravityScale(_self: b2BodyHandle): Single; cdecl; external LIB_NAME name _PU + 'b2Body_GetGravityScale'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2BodyWrapper.GetGravityScale: Single; cdecl;
begin
Result := b2Body_GetGravityScale(FHandle)
end;
procedure b2Body_SetGravityScale(_self: b2BodyHandle; scale: Single); cdecl; external LIB_NAME name _PU + 'b2Body_SetGravityScale'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2BodyWrapper.SetGravityScale(scale: Single); cdecl;
begin
b2Body_SetGravityScale(FHandle, scale)
end;
procedure b2Body_SetType(_self: b2BodyHandle; _type: b2BodyType); cdecl; external LIB_NAME name _PU + 'b2Body_SetType'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2BodyWrapper.SetType(_type: b2BodyType); cdecl;
begin
b2Body_SetType(FHandle, _type)
end;
function b2Body_GetType(_self: b2BodyHandle): b2BodyType; cdecl; external LIB_NAME name _PU + 'b2Body_GetType'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2BodyWrapper.GetType: b2BodyType; cdecl;
begin
Result := b2Body_GetType(FHandle)
end;
procedure b2Body_SetBullet(_self: b2BodyHandle; flag: Boolean); cdecl; external LIB_NAME name _PU + 'b2Body_SetBullet'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2BodyWrapper.SetBullet(flag: Boolean); cdecl;
begin
b2Body_SetBullet(FHandle, flag)
end;
function b2Body_IsBullet(_self: b2BodyHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2Body_IsBullet'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2BodyWrapper.IsBullet: Boolean; cdecl;
begin
Result := b2Body_IsBullet(FHandle)
end;
procedure b2Body_SetSleepingAllowed(_self: b2BodyHandle; flag: Boolean); cdecl; external LIB_NAME name _PU + 'b2Body_SetSleepingAllowed'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2BodyWrapper.SetSleepingAllowed(flag: Boolean); cdecl;
begin
b2Body_SetSleepingAllowed(FHandle, flag)
end;
function b2Body_IsSleepingAllowed(_self: b2BodyHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2Body_IsSleepingAllowed'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2BodyWrapper.IsSleepingAllowed: Boolean; cdecl;
begin
Result := b2Body_IsSleepingAllowed(FHandle)
end;
procedure b2Body_SetAwake(_self: b2BodyHandle; flag: Boolean); cdecl; external LIB_NAME name _PU + 'b2Body_SetAwake'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2BodyWrapper.SetAwake(flag: Boolean); cdecl;
begin
b2Body_SetAwake(FHandle, flag)
end;
function b2Body_IsAwake(_self: b2BodyHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2Body_IsAwake'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2BodyWrapper.IsAwake: Boolean; cdecl;
begin
Result := b2Body_IsAwake(FHandle)
end;
procedure b2Body_SetActive(_self: b2BodyHandle; flag: Boolean); cdecl; external LIB_NAME name _PU + 'b2Body_SetActive'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2BodyWrapper.SetActive(flag: Boolean); cdecl;
begin
b2Body_SetActive(FHandle, flag)
end;
function b2Body_IsActive(_self: b2BodyHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2Body_IsActive'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2BodyWrapper.IsActive: Boolean; cdecl;
begin
Result := b2Body_IsActive(FHandle)
end;
procedure b2Body_SetFixedRotation(_self: b2BodyHandle; flag: Boolean); cdecl; external LIB_NAME name _PU + 'b2Body_SetFixedRotation'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2BodyWrapper.SetFixedRotation(flag: Boolean); cdecl;
begin
b2Body_SetFixedRotation(FHandle, flag)
end;
function b2Body_IsFixedRotation(_self: b2BodyHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2Body_IsFixedRotation'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2BodyWrapper.IsFixedRotation: Boolean; cdecl;
begin
Result := b2Body_IsFixedRotation(FHandle)
end;
function b2Body_GetFixtureList(_self: b2BodyHandle): Pb2Fixture; cdecl; external LIB_NAME name _PU + 'b2Body_GetFixtureList'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2BodyWrapper.GetFixtureList: Pb2Fixture; cdecl;
begin
Result := b2Body_GetFixtureList(FHandle)
end;
function b2Body_GetJointList(_self: b2BodyHandle): Pb2JointEdge; cdecl; external LIB_NAME name _PU + 'b2Body_GetJointList'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2BodyWrapper.GetJointList: Pb2JointEdge; cdecl;
begin
Result := b2Body_GetJointList(FHandle)
end;
function b2Body_GetContactList(_self: b2BodyHandle): Pb2ContactEdge; cdecl; external LIB_NAME name _PU + 'b2Body_GetContactList'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2BodyWrapper.GetContactList: Pb2ContactEdge; cdecl;
begin
Result := b2Body_GetContactList(FHandle)
end;
function b2Body_GetNext(_self: b2BodyHandle): b2BodyHandle; cdecl; external LIB_NAME name _PU + 'b2Body_GetNext'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2BodyWrapper.GetNext: b2BodyHandle; cdecl;
begin
Result := b2Body_GetNext(FHandle)
end;
function b2Body_GetUserData(_self: b2BodyHandle): Pointer; cdecl; external LIB_NAME name _PU + 'b2Body_GetUserData'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2BodyWrapper.GetUserData: Pointer; cdecl;
begin
Result := b2Body_GetUserData(FHandle)
end;
procedure b2Body_SetUserData(_self: b2BodyHandle; data: Pointer); cdecl; external LIB_NAME name _PU + 'b2Body_SetUserData'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2BodyWrapper.SetUserData(data: Pointer); cdecl;
begin
b2Body_SetUserData(FHandle, data)
end;
function b2Body_GetWorld(_self: b2BodyHandle): b2WorldHandle; cdecl; external LIB_NAME name _PU + 'b2Body_GetWorld'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2BodyWrapper.GetWorld: b2WorldHandle; cdecl;
begin
Result := b2Body_GetWorld(FHandle)
end;
procedure b2Body_Dump(_self: b2BodyHandle); cdecl; external LIB_NAME name _PU + 'b2Body_Dump'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2BodyWrapper.Dump; cdecl;
begin
b2Body_Dump(FHandle)
end;
function b2ContactManager_Create: b2ContactManagerHandle; cdecl; external LIB_NAME name _PU + 'b2ContactManager_b2ContactManager_1'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2ContactManagerWrapper.Create: b2ContactManagerWrapper; cdecl;
begin
Result.FHandle := b2ContactManager_Create;
end;
procedure b2ContactManager_Destroy(_self: b2ContactManagerHandle); cdecl; external LIB_NAME name _PU + 'b2ContactManager_dtor'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ContactManagerWrapper.Destroy; cdecl;
begin
b2ContactManager_Destroy(FHandle);
end;
class operator b2ContactManagerWrapper.Implicit(handle: b2ContactManagerHandle): b2ContactManagerWrapper;
begin
Result.FHandle := handle;
end;
class operator b2ContactManagerWrapper.Implicit(wrapper: b2ContactManagerWrapper): b2ContactManagerHandle;
begin
Result := wrapper.FHandle;
end;
procedure b2ContactManager_AddPair(_self: b2ContactManagerHandle; proxyUserDataA: Pointer; proxyUserDataB: Pointer); cdecl; external LIB_NAME name _PU + 'b2ContactManager_AddPair'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ContactManagerWrapper.AddPair(proxyUserDataA: Pointer; proxyUserDataB: Pointer); cdecl;
begin
b2ContactManager_AddPair(FHandle, proxyUserDataA, proxyUserDataB)
end;
procedure b2ContactManager_FindNewContacts(_self: b2ContactManagerHandle); cdecl; external LIB_NAME name _PU + 'b2ContactManager_FindNewContacts'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ContactManagerWrapper.FindNewContacts; cdecl;
begin
b2ContactManager_FindNewContacts(FHandle)
end;
procedure b2ContactManager_Destroy_(_self: b2ContactManagerHandle; c: b2ContactHandle); cdecl; external LIB_NAME name _PU + 'b2ContactManager_Destroy'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ContactManagerWrapper.Destroy_(c: b2ContactHandle); cdecl;
begin
b2ContactManager_Destroy_(FHandle, c)
end;
procedure b2ContactManager_Collide(_self: b2ContactManagerHandle); cdecl; external LIB_NAME name _PU + 'b2ContactManager_Collide'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ContactManagerWrapper.Collide; cdecl;
begin
b2ContactManager_Collide(FHandle)
end;
function b2ContactManager_Get_m_broadPhase(_self: b2ContactManagerHandle): b2BroadPhaseHandle; cdecl; external LIB_NAME name _PU + 'b2ContactManager_Get_m_broadPhase'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ContactManager_Set_m_broadPhase(_self: b2ContactManagerHandle; aNewValue: b2BroadPhaseHandle); cdecl; external LIB_NAME name _PU + 'b2ContactManager_Set_m_broadPhase'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ContactManagerWrapper.Get_m_broadPhase: b2BroadPhaseHandle; cdecl;
begin
Result := b2ContactManager_Get_m_broadPhase(FHandle);
end;
procedure b2ContactManagerWrapper.Set_m_broadPhase(aNewValue: b2BroadPhaseHandle); cdecl;
begin
b2ContactManager_Set_m_broadPhase(FHandle, aNewValue);
end;
function b2ContactManager_Get_m_contactList(_self: b2ContactManagerHandle): b2ContactHandle; cdecl; external LIB_NAME name _PU + 'b2ContactManager_Get_m_contactList'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ContactManager_Set_m_contactList(_self: b2ContactManagerHandle; aNewValue: b2ContactHandle); cdecl; external LIB_NAME name _PU + 'b2ContactManager_Set_m_contactList'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ContactManagerWrapper.Get_m_contactList: b2ContactHandle; cdecl;
begin
Result := b2ContactManager_Get_m_contactList(FHandle);
end;
procedure b2ContactManagerWrapper.Set_m_contactList(aNewValue: b2ContactHandle); cdecl;
begin
b2ContactManager_Set_m_contactList(FHandle, aNewValue);
end;
function b2ContactManager_Get_m_contactCount(_self: b2ContactManagerHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2ContactManager_Get_m_contactCount'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ContactManager_Set_m_contactCount(_self: b2ContactManagerHandle; aNewValue: Integer); cdecl; external LIB_NAME name _PU + 'b2ContactManager_Set_m_contactCount'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ContactManagerWrapper.Get_m_contactCount: Integer; cdecl;
begin
Result := b2ContactManager_Get_m_contactCount(FHandle);
end;
procedure b2ContactManagerWrapper.Set_m_contactCount(aNewValue: Integer); cdecl;
begin
b2ContactManager_Set_m_contactCount(FHandle, aNewValue);
end;
function b2ContactManager_Get_m_contactFilter(_self: b2ContactManagerHandle): b2ContactFilterHandle; cdecl; external LIB_NAME name _PU + 'b2ContactManager_Get_m_contactFilter'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ContactManager_Set_m_contactFilter(_self: b2ContactManagerHandle; aNewValue: b2ContactFilterHandle); cdecl; external LIB_NAME name _PU + 'b2ContactManager_Set_m_contactFilter'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ContactManagerWrapper.Get_m_contactFilter: b2ContactFilterHandle; cdecl;
begin
Result := b2ContactManager_Get_m_contactFilter(FHandle);
end;
procedure b2ContactManagerWrapper.Set_m_contactFilter(aNewValue: b2ContactFilterHandle); cdecl;
begin
b2ContactManager_Set_m_contactFilter(FHandle, aNewValue);
end;
function b2ContactManager_Get_m_contactListener(_self: b2ContactManagerHandle): b2ContactListenerHandle; cdecl; external LIB_NAME name _PU + 'b2ContactManager_Get_m_contactListener'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ContactManager_Set_m_contactListener(_self: b2ContactManagerHandle; aNewValue: b2ContactListenerHandle); cdecl; external LIB_NAME name _PU + 'b2ContactManager_Set_m_contactListener'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ContactManagerWrapper.Get_m_contactListener: b2ContactListenerHandle; cdecl;
begin
Result := b2ContactManager_Get_m_contactListener(FHandle);
end;
procedure b2ContactManagerWrapper.Set_m_contactListener(aNewValue: b2ContactListenerHandle); cdecl;
begin
b2ContactManager_Set_m_contactListener(FHandle, aNewValue);
end;
function b2ContactManager_Get_m_allocator(_self: b2ContactManagerHandle): b2BlockAllocatorHandle; cdecl; external LIB_NAME name _PU + 'b2ContactManager_Get_m_allocator'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ContactManager_Set_m_allocator(_self: b2ContactManagerHandle; aNewValue: b2BlockAllocatorHandle); cdecl; external LIB_NAME name _PU + 'b2ContactManager_Set_m_allocator'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ContactManagerWrapper.Get_m_allocator: b2BlockAllocatorHandle; cdecl;
begin
Result := b2ContactManager_Get_m_allocator(FHandle);
end;
procedure b2ContactManagerWrapper.Set_m_allocator(aNewValue: b2BlockAllocatorHandle); cdecl;
begin
b2ContactManager_Set_m_allocator(FHandle, aNewValue);
end;
function b2Filter_Create: b2Filter; cdecl; external LIB_NAME name _PU + 'b2Filter_b2Filter_1'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2Filter.Create: b2Filter; cdecl;
begin
Result := b2Filter_Create;
end;
function b2FixtureDef_Create: b2FixtureDef; cdecl; external LIB_NAME name _PU + 'b2FixtureDef_b2FixtureDef_1'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2FixtureDef.Create: b2FixtureDef; cdecl;
begin
Result := b2FixtureDef_Create;
end;
function b2FixtureProxy_Create: b2FixtureProxy; cdecl; external LIB_NAME name _PU + 'b2FixtureProxy_b2FixtureProxy'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2FixtureProxy.Create: b2FixtureProxy; cdecl;
begin
Result := b2FixtureProxy_Create;
end;
function b2Fixture_GetType(_self: Pb2Fixture): Integer; cdecl; external LIB_NAME name _PU + 'b2Fixture_GetType'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2Fixture.GetType: Integer; cdecl;
begin
Result := b2Fixture_GetType(@Self)
end;
function b2Fixture_GetShape(_self: Pb2Fixture): b2ShapeHandle; cdecl; external LIB_NAME name _PU + 'b2Fixture_GetShape'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2Fixture.GetShape: b2ShapeHandle; cdecl;
begin
Result := b2Fixture_GetShape(@Self)
end;
procedure b2Fixture_SetSensor(_self: Pb2Fixture; sensor: Boolean); cdecl; external LIB_NAME name _PU + 'b2Fixture_SetSensor'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2Fixture.SetSensor(sensor: Boolean); cdecl;
begin
b2Fixture_SetSensor(@Self, sensor)
end;
function b2Fixture_IsSensor(_self: Pb2Fixture): Boolean; cdecl; external LIB_NAME name _PU + 'b2Fixture_IsSensor'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2Fixture.IsSensor: Boolean; cdecl;
begin
Result := b2Fixture_IsSensor(@Self)
end;
procedure b2Fixture_SetFilterData(_self: Pb2Fixture; const [ref] filter: b2Filter); cdecl; external LIB_NAME name _PU + 'b2Fixture_SetFilterData'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2Fixture.SetFilterData(const [ref] filter: b2Filter); cdecl;
begin
b2Fixture_SetFilterData(@Self, filter)
end;
function b2Fixture_GetFilterData(_self: Pb2Fixture): Pb2Filter; cdecl; external LIB_NAME name _PU + 'b2Fixture_GetFilterData'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2Fixture.GetFilterData: Pb2Filter; cdecl;
begin
Result := b2Fixture_GetFilterData(@Self)
end;
procedure b2Fixture_Refilter(_self: Pb2Fixture); cdecl; external LIB_NAME name _PU + 'b2Fixture_Refilter'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2Fixture.Refilter; cdecl;
begin
b2Fixture_Refilter(@Self)
end;
function b2Fixture_GetBody(_self: Pb2Fixture): b2BodyHandle; cdecl; external LIB_NAME name _PU + 'b2Fixture_GetBody'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2Fixture.GetBody: b2BodyHandle; cdecl;
begin
Result := b2Fixture_GetBody(@Self)
end;
function b2Fixture_GetNext(_self: Pb2Fixture): Pb2Fixture; cdecl; external LIB_NAME name _PU + 'b2Fixture_GetNext'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2Fixture.GetNext: Pb2Fixture; cdecl;
begin
Result := b2Fixture_GetNext(@Self)
end;
function b2Fixture_GetUserData(_self: Pb2Fixture): Pointer; cdecl; external LIB_NAME name _PU + 'b2Fixture_GetUserData'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2Fixture.GetUserData: Pointer; cdecl;
begin
Result := b2Fixture_GetUserData(@Self)
end;
procedure b2Fixture_SetUserData(_self: Pb2Fixture; data: Pointer); cdecl; external LIB_NAME name _PU + 'b2Fixture_SetUserData'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2Fixture.SetUserData(data: Pointer); cdecl;
begin
b2Fixture_SetUserData(@Self, data)
end;
function b2Fixture_TestPoint(_self: Pb2Fixture; const [ref] p: b2Vec2): Boolean; cdecl; external LIB_NAME name _PU + 'b2Fixture_TestPoint'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2Fixture.TestPoint(const [ref] p: b2Vec2): Boolean; cdecl;
begin
Result := b2Fixture_TestPoint(@Self, p)
end;
function b2Fixture_RayCast(_self: Pb2Fixture; output: Pb2RayCastOutput; const [ref] input: b2RayCastInput; childIndex: Integer): Boolean; cdecl; external LIB_NAME name _PU + 'b2Fixture_RayCast'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2Fixture.RayCast(output: Pb2RayCastOutput; const [ref] input: b2RayCastInput; childIndex: Integer): Boolean; cdecl;
begin
Result := b2Fixture_RayCast(@Self, output, input, childIndex)
end;
procedure b2Fixture_GetMassData(_self: Pb2Fixture; massData: Pb2MassData); cdecl; external LIB_NAME name _PU + 'b2Fixture_GetMassData'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2Fixture.GetMassData(massData: Pb2MassData); cdecl;
begin
b2Fixture_GetMassData(@Self, massData)
end;
procedure b2Fixture_SetDensity(_self: Pb2Fixture; density: Single); cdecl; external LIB_NAME name _PU + 'b2Fixture_SetDensity'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2Fixture.SetDensity(density: Single); cdecl;
begin
b2Fixture_SetDensity(@Self, density)
end;
function b2Fixture_GetDensity(_self: Pb2Fixture): Single; cdecl; external LIB_NAME name _PU + 'b2Fixture_GetDensity'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2Fixture.GetDensity: Single; cdecl;
begin
Result := b2Fixture_GetDensity(@Self)
end;
function b2Fixture_GetFriction(_self: Pb2Fixture): Single; cdecl; external LIB_NAME name _PU + 'b2Fixture_GetFriction'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2Fixture.GetFriction: Single; cdecl;
begin
Result := b2Fixture_GetFriction(@Self)
end;
procedure b2Fixture_SetFriction(_self: Pb2Fixture; friction: Single); cdecl; external LIB_NAME name _PU + 'b2Fixture_SetFriction'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2Fixture.SetFriction(friction: Single); cdecl;
begin
b2Fixture_SetFriction(@Self, friction)
end;
function b2Fixture_GetRestitution(_self: Pb2Fixture): Single; cdecl; external LIB_NAME name _PU + 'b2Fixture_GetRestitution'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2Fixture.GetRestitution: Single; cdecl;
begin
Result := b2Fixture_GetRestitution(@Self)
end;
procedure b2Fixture_SetRestitution(_self: Pb2Fixture; restitution: Single); cdecl; external LIB_NAME name _PU + 'b2Fixture_SetRestitution'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2Fixture.SetRestitution(restitution: Single); cdecl;
begin
b2Fixture_SetRestitution(@Self, restitution)
end;
function b2Fixture_GetAABB(_self: Pb2Fixture; childIndex: Integer): Pb2AABB; cdecl; external LIB_NAME name _PU + 'b2Fixture_GetAABB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2Fixture.GetAABB(childIndex: Integer): Pb2AABB; cdecl;
begin
Result := b2Fixture_GetAABB(@Self, childIndex)
end;
procedure b2Fixture_Dump(_self: Pb2Fixture; bodyIndex: Integer); cdecl; external LIB_NAME name _PU + 'b2Fixture_Dump'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2Fixture.Dump(bodyIndex: Integer); cdecl;
begin
b2Fixture_Dump(@Self, bodyIndex)
end;
function b2Profile_Create: b2Profile; cdecl; external LIB_NAME name _PU + 'b2Profile_b2Profile'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2Profile.Create: b2Profile; cdecl;
begin
Result := b2Profile_Create;
end;
function b2TimeStep_Create: b2TimeStep; cdecl; external LIB_NAME name _PU + 'b2TimeStep_b2TimeStep'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2TimeStep.Create: b2TimeStep; cdecl;
begin
Result := b2TimeStep_Create;
end;
function b2Position_Create: b2Position; cdecl; external LIB_NAME name _PU + 'b2Position_b2Position'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2Position.Create: b2Position; cdecl;
begin
Result := b2Position_Create;
end;
function b2Velocity_Create: b2Velocity; cdecl; external LIB_NAME name _PU + 'b2Velocity_b2Velocity'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2Velocity.Create: b2Velocity; cdecl;
begin
Result := b2Velocity_Create;
end;
function b2SolverData_Create: b2SolverData; cdecl; external LIB_NAME name _PU + 'b2SolverData_b2SolverData'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2SolverData.Create: b2SolverData; cdecl;
begin
Result := b2SolverData_Create;
end;
function b2Island_Create(bodyCapacity: Integer; contactCapacity: Integer; jointCapacity: Integer; allocator: b2StackAllocatorHandle; listener: b2ContactListenerHandle): b2IslandHandle; cdecl; external LIB_NAME name _PU + 'b2Island_b2Island_1'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2IslandWrapper.Create(bodyCapacity: Integer; contactCapacity: Integer; jointCapacity: Integer; allocator: b2StackAllocatorHandle; listener: b2ContactListenerHandle): b2IslandWrapper; cdecl;
begin
Result.FHandle := b2Island_Create(bodyCapacity, contactCapacity, jointCapacity, allocator, listener);
end;
procedure b2Island_Destroy(_self: b2IslandHandle); cdecl; external LIB_NAME name _PU + 'b2Island_dtor'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2IslandWrapper.Destroy; cdecl;
begin
b2Island_Destroy(FHandle);
end;
class operator b2IslandWrapper.Implicit(handle: b2IslandHandle): b2IslandWrapper;
begin
Result.FHandle := handle;
end;
class operator b2IslandWrapper.Implicit(wrapper: b2IslandWrapper): b2IslandHandle;
begin
Result := wrapper.FHandle;
end;
procedure b2Island_Clear(_self: b2IslandHandle); cdecl; external LIB_NAME name _PU + 'b2Island_Clear'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2IslandWrapper.Clear; cdecl;
begin
b2Island_Clear(FHandle)
end;
procedure b2Island_Solve(_self: b2IslandHandle; profile: Pb2Profile; const [ref] step: b2TimeStep; const [ref] gravity: b2Vec2; allowSleep: Boolean); cdecl; external LIB_NAME name _PU + 'b2Island_Solve'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2IslandWrapper.Solve(profile: Pb2Profile; const [ref] step: b2TimeStep; const [ref] gravity: b2Vec2; allowSleep: Boolean); cdecl;
begin
b2Island_Solve(FHandle, profile, step, gravity, allowSleep)
end;
procedure b2Island_SolveTOI(_self: b2IslandHandle; const [ref] subStep: b2TimeStep; toiIndexA: Integer; toiIndexB: Integer); cdecl; external LIB_NAME name _PU + 'b2Island_SolveTOI'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2IslandWrapper.SolveTOI(const [ref] subStep: b2TimeStep; toiIndexA: Integer; toiIndexB: Integer); cdecl;
begin
b2Island_SolveTOI(FHandle, subStep, toiIndexA, toiIndexB)
end;
procedure b2Island_Add(_self: b2IslandHandle; body: b2BodyHandle); cdecl; external LIB_NAME name _PU + 'b2Island_Add'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2IslandWrapper.Add(body: b2BodyHandle); cdecl;
begin
b2Island_Add(FHandle, body)
end;
procedure b2Island_Add2(_self: b2IslandHandle; contact: b2ContactHandle); cdecl; external LIB_NAME name _PU + 'b2Island_Add2'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2IslandWrapper.Add2(contact: b2ContactHandle); cdecl;
begin
b2Island_Add2(FHandle, contact)
end;
procedure b2Island_Add3(_self: b2IslandHandle; joint: b2JointHandle); cdecl; external LIB_NAME name _PU + 'b2Island_Add3'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2IslandWrapper.Add3(joint: b2JointHandle); cdecl;
begin
b2Island_Add3(FHandle, joint)
end;
procedure b2Island_Report(_self: b2IslandHandle; constraints: Pb2ContactVelocityConstraint); cdecl; external LIB_NAME name _PU + 'b2Island_Report'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2IslandWrapper.Report(constraints: Pb2ContactVelocityConstraint); cdecl;
begin
b2Island_Report(FHandle, constraints)
end;
function b2Island_Get_m_allocator(_self: b2IslandHandle): b2StackAllocatorHandle; cdecl; external LIB_NAME name _PU + 'b2Island_Get_m_allocator'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2Island_Set_m_allocator(_self: b2IslandHandle; aNewValue: b2StackAllocatorHandle); cdecl; external LIB_NAME name _PU + 'b2Island_Set_m_allocator'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2IslandWrapper.Get_m_allocator: b2StackAllocatorHandle; cdecl;
begin
Result := b2Island_Get_m_allocator(FHandle);
end;
procedure b2IslandWrapper.Set_m_allocator(aNewValue: b2StackAllocatorHandle); cdecl;
begin
b2Island_Set_m_allocator(FHandle, aNewValue);
end;
function b2Island_Get_m_listener(_self: b2IslandHandle): b2ContactListenerHandle; cdecl; external LIB_NAME name _PU + 'b2Island_Get_m_listener'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2Island_Set_m_listener(_self: b2IslandHandle; aNewValue: b2ContactListenerHandle); cdecl; external LIB_NAME name _PU + 'b2Island_Set_m_listener'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2IslandWrapper.Get_m_listener: b2ContactListenerHandle; cdecl;
begin
Result := b2Island_Get_m_listener(FHandle);
end;
procedure b2IslandWrapper.Set_m_listener(aNewValue: b2ContactListenerHandle); cdecl;
begin
b2Island_Set_m_listener(FHandle, aNewValue);
end;
function b2Island_Get_m_bodies(_self: b2IslandHandle): Pb2BodyHandle; cdecl; external LIB_NAME name _PU + 'b2Island_Get_m_bodies'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2Island_Set_m_bodies(_self: b2IslandHandle; aNewValue: Pb2BodyHandle); cdecl; external LIB_NAME name _PU + 'b2Island_Set_m_bodies'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2IslandWrapper.Get_m_bodies: Pb2BodyHandle; cdecl;
begin
Result := b2Island_Get_m_bodies(FHandle);
end;
procedure b2IslandWrapper.Set_m_bodies(aNewValue: Pb2BodyHandle); cdecl;
begin
b2Island_Set_m_bodies(FHandle, aNewValue);
end;
function b2Island_Get_m_contacts(_self: b2IslandHandle): Pb2ContactHandle; cdecl; external LIB_NAME name _PU + 'b2Island_Get_m_contacts'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2Island_Set_m_contacts(_self: b2IslandHandle; aNewValue: Pb2ContactHandle); cdecl; external LIB_NAME name _PU + 'b2Island_Set_m_contacts'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2IslandWrapper.Get_m_contacts: Pb2ContactHandle; cdecl;
begin
Result := b2Island_Get_m_contacts(FHandle);
end;
procedure b2IslandWrapper.Set_m_contacts(aNewValue: Pb2ContactHandle); cdecl;
begin
b2Island_Set_m_contacts(FHandle, aNewValue);
end;
function b2Island_Get_m_joints(_self: b2IslandHandle): Pb2JointHandle; cdecl; external LIB_NAME name _PU + 'b2Island_Get_m_joints'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2Island_Set_m_joints(_self: b2IslandHandle; aNewValue: Pb2JointHandle); cdecl; external LIB_NAME name _PU + 'b2Island_Set_m_joints'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2IslandWrapper.Get_m_joints: Pb2JointHandle; cdecl;
begin
Result := b2Island_Get_m_joints(FHandle);
end;
procedure b2IslandWrapper.Set_m_joints(aNewValue: Pb2JointHandle); cdecl;
begin
b2Island_Set_m_joints(FHandle, aNewValue);
end;
function b2Island_Get_m_positions(_self: b2IslandHandle): Pb2Position; cdecl; external LIB_NAME name _PU + 'b2Island_Get_m_positions'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2Island_Set_m_positions(_self: b2IslandHandle; aNewValue: Pb2Position); cdecl; external LIB_NAME name _PU + 'b2Island_Set_m_positions'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2IslandWrapper.Get_m_positions: Pb2Position; cdecl;
begin
Result := b2Island_Get_m_positions(FHandle);
end;
procedure b2IslandWrapper.Set_m_positions(aNewValue: Pb2Position); cdecl;
begin
b2Island_Set_m_positions(FHandle, aNewValue);
end;
function b2Island_Get_m_velocities(_self: b2IslandHandle): Pb2Velocity; cdecl; external LIB_NAME name _PU + 'b2Island_Get_m_velocities'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2Island_Set_m_velocities(_self: b2IslandHandle; aNewValue: Pb2Velocity); cdecl; external LIB_NAME name _PU + 'b2Island_Set_m_velocities'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2IslandWrapper.Get_m_velocities: Pb2Velocity; cdecl;
begin
Result := b2Island_Get_m_velocities(FHandle);
end;
procedure b2IslandWrapper.Set_m_velocities(aNewValue: Pb2Velocity); cdecl;
begin
b2Island_Set_m_velocities(FHandle, aNewValue);
end;
function b2Island_Get_m_bodyCount(_self: b2IslandHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2Island_Get_m_bodyCount'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2Island_Set_m_bodyCount(_self: b2IslandHandle; aNewValue: Integer); cdecl; external LIB_NAME name _PU + 'b2Island_Set_m_bodyCount'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2IslandWrapper.Get_m_bodyCount: Integer; cdecl;
begin
Result := b2Island_Get_m_bodyCount(FHandle);
end;
procedure b2IslandWrapper.Set_m_bodyCount(aNewValue: Integer); cdecl;
begin
b2Island_Set_m_bodyCount(FHandle, aNewValue);
end;
function b2Island_Get_m_jointCount(_self: b2IslandHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2Island_Get_m_jointCount'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2Island_Set_m_jointCount(_self: b2IslandHandle; aNewValue: Integer); cdecl; external LIB_NAME name _PU + 'b2Island_Set_m_jointCount'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2IslandWrapper.Get_m_jointCount: Integer; cdecl;
begin
Result := b2Island_Get_m_jointCount(FHandle);
end;
procedure b2IslandWrapper.Set_m_jointCount(aNewValue: Integer); cdecl;
begin
b2Island_Set_m_jointCount(FHandle, aNewValue);
end;
function b2Island_Get_m_contactCount(_self: b2IslandHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2Island_Get_m_contactCount'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2Island_Set_m_contactCount(_self: b2IslandHandle; aNewValue: Integer); cdecl; external LIB_NAME name _PU + 'b2Island_Set_m_contactCount'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2IslandWrapper.Get_m_contactCount: Integer; cdecl;
begin
Result := b2Island_Get_m_contactCount(FHandle);
end;
procedure b2IslandWrapper.Set_m_contactCount(aNewValue: Integer); cdecl;
begin
b2Island_Set_m_contactCount(FHandle, aNewValue);
end;
function b2Island_Get_m_bodyCapacity(_self: b2IslandHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2Island_Get_m_bodyCapacity'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2Island_Set_m_bodyCapacity(_self: b2IslandHandle; aNewValue: Integer); cdecl; external LIB_NAME name _PU + 'b2Island_Set_m_bodyCapacity'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2IslandWrapper.Get_m_bodyCapacity: Integer; cdecl;
begin
Result := b2Island_Get_m_bodyCapacity(FHandle);
end;
procedure b2IslandWrapper.Set_m_bodyCapacity(aNewValue: Integer); cdecl;
begin
b2Island_Set_m_bodyCapacity(FHandle, aNewValue);
end;
function b2Island_Get_m_contactCapacity(_self: b2IslandHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2Island_Get_m_contactCapacity'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2Island_Set_m_contactCapacity(_self: b2IslandHandle; aNewValue: Integer); cdecl; external LIB_NAME name _PU + 'b2Island_Set_m_contactCapacity'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2IslandWrapper.Get_m_contactCapacity: Integer; cdecl;
begin
Result := b2Island_Get_m_contactCapacity(FHandle);
end;
procedure b2IslandWrapper.Set_m_contactCapacity(aNewValue: Integer); cdecl;
begin
b2Island_Set_m_contactCapacity(FHandle, aNewValue);
end;
function b2Island_Get_m_jointCapacity(_self: b2IslandHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2Island_Get_m_jointCapacity'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2Island_Set_m_jointCapacity(_self: b2IslandHandle; aNewValue: Integer); cdecl; external LIB_NAME name _PU + 'b2Island_Set_m_jointCapacity'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2IslandWrapper.Get_m_jointCapacity: Integer; cdecl;
begin
Result := b2Island_Get_m_jointCapacity(FHandle);
end;
procedure b2IslandWrapper.Set_m_jointCapacity(aNewValue: Integer); cdecl;
begin
b2Island_Set_m_jointCapacity(FHandle, aNewValue);
end;
class operator b2DestructionListenerWrapper.Implicit(handle: b2DestructionListenerHandle): b2DestructionListenerWrapper;
begin
Result.FHandle := handle;
end;
class operator b2DestructionListenerWrapper.Implicit(wrapper: b2DestructionListenerWrapper): b2DestructionListenerHandle;
begin
Result := wrapper.FHandle;
end;
procedure b2DestructionListener_SayGoodbye(_self: b2DestructionListenerHandle; joint: b2JointHandle); overload; cdecl; external LIB_NAME name _PU + 'b2DestructionListener_SayGoodbye'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2DestructionListenerWrapper.SayGoodbye(joint: b2JointHandle); cdecl;
begin
b2DestructionListener_SayGoodbye(FHandle, joint)
end;
procedure b2DestructionListener_SayGoodbye(_self: b2DestructionListenerHandle; fixture: Pb2Fixture); overload; cdecl; external LIB_NAME name _PU + 'b2DestructionListener_SayGoodbye2'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2DestructionListenerWrapper.SayGoodbye(fixture: Pb2Fixture); cdecl;
begin
b2DestructionListener_SayGoodbye(FHandle, fixture)
end;
function b2ContactFilter_Create: b2ContactFilterHandle; cdecl; external LIB_NAME name _PU + 'b2ContactFilter_b2ContactFilter'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2ContactFilterWrapper.Create: b2ContactFilterWrapper; cdecl;
begin
Result.FHandle := b2ContactFilter_Create;
end;
procedure b2ContactFilter_Destroy(_self: b2ContactFilterHandle); cdecl; external LIB_NAME name _PU + 'b2ContactFilter_dtor'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ContactFilterWrapper.Destroy; cdecl;
begin
b2ContactFilter_Destroy(FHandle);
end;
class operator b2ContactFilterWrapper.Implicit(handle: b2ContactFilterHandle): b2ContactFilterWrapper;
begin
Result.FHandle := handle;
end;
class operator b2ContactFilterWrapper.Implicit(wrapper: b2ContactFilterWrapper): b2ContactFilterHandle;
begin
Result := wrapper.FHandle;
end;
function b2ContactFilter_ShouldCollide(_self: b2ContactFilterHandle; fixtureA: Pb2Fixture; fixtureB: Pb2Fixture): Boolean; cdecl; external LIB_NAME name _PU + 'b2ContactFilter_ShouldCollide'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ContactFilterWrapper.ShouldCollide(fixtureA: Pb2Fixture; fixtureB: Pb2Fixture): Boolean; cdecl;
begin
Result := b2ContactFilter_ShouldCollide(FHandle, fixtureA, fixtureB)
end;
function b2ContactImpulse_Create: b2ContactImpulse; cdecl; external LIB_NAME name _PU + 'b2ContactImpulse_b2ContactImpulse'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2ContactImpulse.Create: b2ContactImpulse; cdecl;
begin
Result := b2ContactImpulse_Create;
end;
function b2ContactListener_Create: b2ContactListenerHandle; cdecl; external LIB_NAME name _PU + 'b2ContactListener_b2ContactListener'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2ContactListenerWrapper.Create: b2ContactListenerWrapper; cdecl;
begin
Result.FHandle := b2ContactListener_Create;
end;
procedure b2ContactListener_Destroy(_self: b2ContactListenerHandle); cdecl; external LIB_NAME name _PU + 'b2ContactListener_dtor'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ContactListenerWrapper.Destroy; cdecl;
begin
b2ContactListener_Destroy(FHandle);
end;
class operator b2ContactListenerWrapper.Implicit(handle: b2ContactListenerHandle): b2ContactListenerWrapper;
begin
Result.FHandle := handle;
end;
class operator b2ContactListenerWrapper.Implicit(wrapper: b2ContactListenerWrapper): b2ContactListenerHandle;
begin
Result := wrapper.FHandle;
end;
procedure b2ContactListener_BeginContact(_self: b2ContactListenerHandle; contact: b2ContactHandle); cdecl; external LIB_NAME name _PU + 'b2ContactListener_BeginContact'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ContactListenerWrapper.BeginContact(contact: b2ContactHandle); cdecl;
begin
b2ContactListener_BeginContact(FHandle, contact)
end;
procedure b2ContactListener_EndContact(_self: b2ContactListenerHandle; contact: b2ContactHandle); cdecl; external LIB_NAME name _PU + 'b2ContactListener_EndContact'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ContactListenerWrapper.EndContact(contact: b2ContactHandle); cdecl;
begin
b2ContactListener_EndContact(FHandle, contact)
end;
procedure b2ContactListener_PreSolve(_self: b2ContactListenerHandle; contact: b2ContactHandle; oldManifold: Pb2Manifold); cdecl; external LIB_NAME name _PU + 'b2ContactListener_PreSolve'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ContactListenerWrapper.PreSolve(contact: b2ContactHandle; oldManifold: Pb2Manifold); cdecl;
begin
b2ContactListener_PreSolve(FHandle, contact, oldManifold)
end;
procedure b2ContactListener_PostSolve(_self: b2ContactListenerHandle; contact: b2ContactHandle; impulse: Pb2ContactImpulse); cdecl; external LIB_NAME name _PU + 'b2ContactListener_PostSolve'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ContactListenerWrapper.PostSolve(contact: b2ContactHandle; impulse: Pb2ContactImpulse); cdecl;
begin
b2ContactListener_PostSolve(FHandle, contact, impulse)
end;
class operator b2QueryCallbackWrapper.Implicit(handle: b2QueryCallbackHandle): b2QueryCallbackWrapper;
begin
Result.FHandle := handle;
end;
class operator b2QueryCallbackWrapper.Implicit(wrapper: b2QueryCallbackWrapper): b2QueryCallbackHandle;
begin
Result := wrapper.FHandle;
end;
function b2QueryCallback_ReportFixture(_self: b2QueryCallbackHandle; fixture: Pb2Fixture): Boolean; cdecl; external LIB_NAME name _PU + 'b2QueryCallback_ReportFixture'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2QueryCallbackWrapper.ReportFixture(fixture: Pb2Fixture): Boolean; cdecl;
begin
Result := b2QueryCallback_ReportFixture(FHandle, fixture)
end;
class operator b2RayCastCallbackWrapper.Implicit(handle: b2RayCastCallbackHandle): b2RayCastCallbackWrapper;
begin
Result.FHandle := handle;
end;
class operator b2RayCastCallbackWrapper.Implicit(wrapper: b2RayCastCallbackWrapper): b2RayCastCallbackHandle;
begin
Result := wrapper.FHandle;
end;
function b2RayCastCallback_ReportFixture(_self: b2RayCastCallbackHandle; fixture: Pb2Fixture; const [ref] point: b2Vec2; const [ref] normal: b2Vec2; fraction: Single): Single; cdecl; external LIB_NAME name _PU + 'b2RayCastCallback_ReportFixture'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2RayCastCallbackWrapper.ReportFixture(fixture: Pb2Fixture; const [ref] point: b2Vec2; const [ref] normal: b2Vec2; fraction: Single): Single; cdecl;
begin
Result := b2RayCastCallback_ReportFixture(FHandle, fixture, point, normal, fraction)
end;
function b2World_Create(const [ref] gravity: b2Vec2): b2WorldHandle; cdecl; external LIB_NAME name _PU + 'b2World_b2World_1'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2WorldWrapper.Create(const [ref] gravity: b2Vec2): b2WorldWrapper; cdecl;
begin
Result.FHandle := b2World_Create(gravity);
end;
procedure b2World_Destroy(_self: b2WorldHandle); cdecl; external LIB_NAME name _PU + 'b2World_dtor'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2WorldWrapper.Destroy; cdecl;
begin
b2World_Destroy(FHandle);
end;
class operator b2WorldWrapper.Implicit(handle: b2WorldHandle): b2WorldWrapper;
begin
Result.FHandle := handle;
end;
class operator b2WorldWrapper.Implicit(wrapper: b2WorldWrapper): b2WorldHandle;
begin
Result := wrapper.FHandle;
end;
procedure b2World_SetDestructionListener(_self: b2WorldHandle; listener: b2DestructionListenerHandle); cdecl; external LIB_NAME name _PU + 'b2World_SetDestructionListener'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2WorldWrapper.SetDestructionListener(listener: b2DestructionListenerHandle); cdecl;
begin
b2World_SetDestructionListener(FHandle, listener)
end;
procedure b2World_SetContactFilter(_self: b2WorldHandle; filter: b2ContactFilterHandle); cdecl; external LIB_NAME name _PU + 'b2World_SetContactFilter'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2WorldWrapper.SetContactFilter(filter: b2ContactFilterHandle); cdecl;
begin
b2World_SetContactFilter(FHandle, filter)
end;
procedure b2World_SetContactListener(_self: b2WorldHandle; listener: b2ContactListenerHandle); cdecl; external LIB_NAME name _PU + 'b2World_SetContactListener'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2WorldWrapper.SetContactListener(listener: b2ContactListenerHandle); cdecl;
begin
b2World_SetContactListener(FHandle, listener)
end;
procedure b2World_SetDebugDraw(_self: b2WorldHandle; debugDraw: b2DrawHandle); cdecl; external LIB_NAME name _PU + 'b2World_SetDebugDraw'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2WorldWrapper.SetDebugDraw(debugDraw: b2DrawHandle); cdecl;
begin
b2World_SetDebugDraw(FHandle, debugDraw)
end;
function b2World_CreateBody(_self: b2WorldHandle; def: Pb2BodyDef): b2BodyHandle; cdecl; external LIB_NAME name _PU + 'b2World_CreateBody'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WorldWrapper.CreateBody(def: Pb2BodyDef): b2BodyHandle; cdecl;
begin
Result := b2World_CreateBody(FHandle, def)
end;
procedure b2World_DestroyBody(_self: b2WorldHandle; body: b2BodyHandle); cdecl; external LIB_NAME name _PU + 'b2World_DestroyBody'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2WorldWrapper.DestroyBody(body: b2BodyHandle); cdecl;
begin
b2World_DestroyBody(FHandle, body)
end;
function b2World_CreateJoint(_self: b2WorldHandle; def: Pb2JointDef): b2JointHandle; cdecl; external LIB_NAME name _PU + 'b2World_CreateJoint'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WorldWrapper.CreateJoint(def: Pb2JointDef): b2JointHandle; cdecl;
begin
Result := b2World_CreateJoint(FHandle, def)
end;
procedure b2World_DestroyJoint(_self: b2WorldHandle; joint: b2JointHandle); cdecl; external LIB_NAME name _PU + 'b2World_DestroyJoint'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2WorldWrapper.DestroyJoint(joint: b2JointHandle); cdecl;
begin
b2World_DestroyJoint(FHandle, joint)
end;
procedure b2World_Step(_self: b2WorldHandle; timeStep: Single; velocityIterations: Integer; positionIterations: Integer); cdecl; external LIB_NAME name _PU + 'b2World_Step'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2WorldWrapper.Step(timeStep: Single; velocityIterations: Integer; positionIterations: Integer); cdecl;
begin
b2World_Step(FHandle, timeStep, velocityIterations, positionIterations)
end;
procedure b2World_ClearForces(_self: b2WorldHandle); cdecl; external LIB_NAME name _PU + 'b2World_ClearForces'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2WorldWrapper.ClearForces; cdecl;
begin
b2World_ClearForces(FHandle)
end;
procedure b2World_DrawDebugData(_self: b2WorldHandle); cdecl; external LIB_NAME name _PU + 'b2World_DrawDebugData'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2WorldWrapper.DrawDebugData; cdecl;
begin
b2World_DrawDebugData(FHandle)
end;
procedure b2World_QueryAABB(_self: b2WorldHandle; callback: b2QueryCallbackHandle; const [ref] aabb: b2AABB); cdecl; external LIB_NAME name _PU + 'b2World_QueryAABB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2WorldWrapper.QueryAABB(callback: b2QueryCallbackHandle; const [ref] aabb: b2AABB); cdecl;
begin
b2World_QueryAABB(FHandle, callback, aabb)
end;
procedure b2World_RayCast(_self: b2WorldHandle; callback: b2RayCastCallbackHandle; const [ref] point1: b2Vec2; const [ref] point2: b2Vec2); cdecl; external LIB_NAME name _PU + 'b2World_RayCast'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2WorldWrapper.RayCast(callback: b2RayCastCallbackHandle; const [ref] point1: b2Vec2; const [ref] point2: b2Vec2); cdecl;
begin
b2World_RayCast(FHandle, callback, point1, point2)
end;
function b2World_GetBodyList(_self: b2WorldHandle): b2BodyHandle; cdecl; external LIB_NAME name _PU + 'b2World_GetBodyList'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WorldWrapper.GetBodyList: b2BodyHandle; cdecl;
begin
Result := b2World_GetBodyList(FHandle)
end;
function b2World_GetJointList(_self: b2WorldHandle): b2JointHandle; cdecl; external LIB_NAME name _PU + 'b2World_GetJointList'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WorldWrapper.GetJointList: b2JointHandle; cdecl;
begin
Result := b2World_GetJointList(FHandle)
end;
function b2World_GetContactList(_self: b2WorldHandle): b2ContactHandle; cdecl; external LIB_NAME name _PU + 'b2World_GetContactList'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WorldWrapper.GetContactList: b2ContactHandle; cdecl;
begin
Result := b2World_GetContactList(FHandle)
end;
procedure b2World_SetAllowSleeping(_self: b2WorldHandle; flag: Boolean); cdecl; external LIB_NAME name _PU + 'b2World_SetAllowSleeping'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2WorldWrapper.SetAllowSleeping(flag: Boolean); cdecl;
begin
b2World_SetAllowSleeping(FHandle, flag)
end;
function b2World_GetAllowSleeping(_self: b2WorldHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2World_GetAllowSleeping'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WorldWrapper.GetAllowSleeping: Boolean; cdecl;
begin
Result := b2World_GetAllowSleeping(FHandle)
end;
procedure b2World_SetWarmStarting(_self: b2WorldHandle; flag: Boolean); cdecl; external LIB_NAME name _PU + 'b2World_SetWarmStarting'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2WorldWrapper.SetWarmStarting(flag: Boolean); cdecl;
begin
b2World_SetWarmStarting(FHandle, flag)
end;
function b2World_GetWarmStarting(_self: b2WorldHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2World_GetWarmStarting'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WorldWrapper.GetWarmStarting: Boolean; cdecl;
begin
Result := b2World_GetWarmStarting(FHandle)
end;
procedure b2World_SetContinuousPhysics(_self: b2WorldHandle; flag: Boolean); cdecl; external LIB_NAME name _PU + 'b2World_SetContinuousPhysics'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2WorldWrapper.SetContinuousPhysics(flag: Boolean); cdecl;
begin
b2World_SetContinuousPhysics(FHandle, flag)
end;
function b2World_GetContinuousPhysics(_self: b2WorldHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2World_GetContinuousPhysics'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WorldWrapper.GetContinuousPhysics: Boolean; cdecl;
begin
Result := b2World_GetContinuousPhysics(FHandle)
end;
procedure b2World_SetSubStepping(_self: b2WorldHandle; flag: Boolean); cdecl; external LIB_NAME name _PU + 'b2World_SetSubStepping'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2WorldWrapper.SetSubStepping(flag: Boolean); cdecl;
begin
b2World_SetSubStepping(FHandle, flag)
end;
function b2World_GetSubStepping(_self: b2WorldHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2World_GetSubStepping'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WorldWrapper.GetSubStepping: Boolean; cdecl;
begin
Result := b2World_GetSubStepping(FHandle)
end;
function b2World_GetProxyCount(_self: b2WorldHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2World_GetProxyCount'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WorldWrapper.GetProxyCount: Integer; cdecl;
begin
Result := b2World_GetProxyCount(FHandle)
end;
function b2World_GetBodyCount(_self: b2WorldHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2World_GetBodyCount'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WorldWrapper.GetBodyCount: Integer; cdecl;
begin
Result := b2World_GetBodyCount(FHandle)
end;
function b2World_GetJointCount(_self: b2WorldHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2World_GetJointCount'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WorldWrapper.GetJointCount: Integer; cdecl;
begin
Result := b2World_GetJointCount(FHandle)
end;
function b2World_GetContactCount(_self: b2WorldHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2World_GetContactCount'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WorldWrapper.GetContactCount: Integer; cdecl;
begin
Result := b2World_GetContactCount(FHandle)
end;
function b2World_GetTreeHeight(_self: b2WorldHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2World_GetTreeHeight'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WorldWrapper.GetTreeHeight: Integer; cdecl;
begin
Result := b2World_GetTreeHeight(FHandle)
end;
function b2World_GetTreeBalance(_self: b2WorldHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2World_GetTreeBalance'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WorldWrapper.GetTreeBalance: Integer; cdecl;
begin
Result := b2World_GetTreeBalance(FHandle)
end;
function b2World_GetTreeQuality(_self: b2WorldHandle): Single; cdecl; external LIB_NAME name _PU + 'b2World_GetTreeQuality'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WorldWrapper.GetTreeQuality: Single; cdecl;
begin
Result := b2World_GetTreeQuality(FHandle)
end;
procedure b2World_SetGravity(_self: b2WorldHandle; const [ref] gravity: b2Vec2); cdecl; external LIB_NAME name _PU + 'b2World_SetGravity'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2WorldWrapper.SetGravity(const [ref] gravity: b2Vec2); cdecl;
begin
b2World_SetGravity(FHandle, gravity)
end;
function b2World_GetGravity(_self: b2WorldHandle): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2World_GetGravity'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WorldWrapper.GetGravity: b2Vec2; cdecl;
begin
Result := b2World_GetGravity(FHandle)
end;
function b2World_IsLocked(_self: b2WorldHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2World_IsLocked'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WorldWrapper.IsLocked: Boolean; cdecl;
begin
Result := b2World_IsLocked(FHandle)
end;
procedure b2World_SetAutoClearForces(_self: b2WorldHandle; flag: Boolean); cdecl; external LIB_NAME name _PU + 'b2World_SetAutoClearForces'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2WorldWrapper.SetAutoClearForces(flag: Boolean); cdecl;
begin
b2World_SetAutoClearForces(FHandle, flag)
end;
function b2World_GetAutoClearForces(_self: b2WorldHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2World_GetAutoClearForces'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WorldWrapper.GetAutoClearForces: Boolean; cdecl;
begin
Result := b2World_GetAutoClearForces(FHandle)
end;
procedure b2World_ShiftOrigin(_self: b2WorldHandle; const [ref] newOrigin: b2Vec2); cdecl; external LIB_NAME name _PU + 'b2World_ShiftOrigin'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2WorldWrapper.ShiftOrigin(const [ref] newOrigin: b2Vec2); cdecl;
begin
b2World_ShiftOrigin(FHandle, newOrigin)
end;
function b2World_GetContactManager(_self: b2WorldHandle): b2ContactManagerHandle; cdecl; external LIB_NAME name _PU + 'b2World_GetContactManager'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WorldWrapper.GetContactManager: b2ContactManagerHandle; cdecl;
begin
Result := b2World_GetContactManager(FHandle)
end;
function b2World_GetProfile(_self: b2WorldHandle): Pb2Profile; cdecl; external LIB_NAME name _PU + 'b2World_GetProfile'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WorldWrapper.GetProfile: Pb2Profile; cdecl;
begin
Result := b2World_GetProfile(FHandle)
end;
procedure b2World_Dump(_self: b2WorldHandle); cdecl; external LIB_NAME name _PU + 'b2World_Dump'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2WorldWrapper.Dump; cdecl;
begin
b2World_Dump(FHandle)
end;
function b2ContactRegister_Create: b2ContactRegister; cdecl; external LIB_NAME name _PU + 'b2ContactRegister_b2ContactRegister'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2ContactRegister.Create: b2ContactRegister; cdecl;
begin
Result := b2ContactRegister_Create;
end;
function b2ContactEdge_Create: b2ContactEdge; cdecl; external LIB_NAME name _PU + 'b2ContactEdge_b2ContactEdge_1'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2ContactEdge.Create: b2ContactEdge; cdecl;
begin
Result := b2ContactEdge_Create;
end;
class operator b2ContactWrapper.Implicit(handle: b2ContactHandle): b2ContactWrapper;
begin
Result.FHandle := handle;
end;
class operator b2ContactWrapper.Implicit(wrapper: b2ContactWrapper): b2ContactHandle;
begin
Result := wrapper.FHandle;
end;
function b2Contact_GetManifold(_self: b2ContactHandle): Pb2Manifold; cdecl; external LIB_NAME name _PU + 'b2Contact_GetManifold'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ContactWrapper.GetManifold: Pb2Manifold; cdecl;
begin
Result := b2Contact_GetManifold(FHandle)
end;
procedure b2Contact_GetWorldManifold(_self: b2ContactHandle; worldManifold: Pb2WorldManifold); cdecl; external LIB_NAME name _PU + 'b2Contact_GetWorldManifold'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ContactWrapper.GetWorldManifold(worldManifold: Pb2WorldManifold); cdecl;
begin
b2Contact_GetWorldManifold(FHandle, worldManifold)
end;
function b2Contact_IsTouching(_self: b2ContactHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2Contact_IsTouching'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ContactWrapper.IsTouching: Boolean; cdecl;
begin
Result := b2Contact_IsTouching(FHandle)
end;
procedure b2Contact_SetEnabled(_self: b2ContactHandle; flag: Boolean); cdecl; external LIB_NAME name _PU + 'b2Contact_SetEnabled'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ContactWrapper.SetEnabled(flag: Boolean); cdecl;
begin
b2Contact_SetEnabled(FHandle, flag)
end;
function b2Contact_IsEnabled(_self: b2ContactHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2Contact_IsEnabled'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ContactWrapper.IsEnabled: Boolean; cdecl;
begin
Result := b2Contact_IsEnabled(FHandle)
end;
function b2Contact_GetNext(_self: b2ContactHandle): b2ContactHandle; cdecl; external LIB_NAME name _PU + 'b2Contact_GetNext'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ContactWrapper.GetNext: b2ContactHandle; cdecl;
begin
Result := b2Contact_GetNext(FHandle)
end;
function b2Contact_GetFixtureA(_self: b2ContactHandle): Pb2Fixture; cdecl; external LIB_NAME name _PU + 'b2Contact_GetFixtureA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ContactWrapper.GetFixtureA: Pb2Fixture; cdecl;
begin
Result := b2Contact_GetFixtureA(FHandle)
end;
function b2Contact_GetChildIndexA(_self: b2ContactHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2Contact_GetChildIndexA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ContactWrapper.GetChildIndexA: Integer; cdecl;
begin
Result := b2Contact_GetChildIndexA(FHandle)
end;
function b2Contact_GetFixtureB(_self: b2ContactHandle): Pb2Fixture; cdecl; external LIB_NAME name _PU + 'b2Contact_GetFixtureB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ContactWrapper.GetFixtureB: Pb2Fixture; cdecl;
begin
Result := b2Contact_GetFixtureB(FHandle)
end;
function b2Contact_GetChildIndexB(_self: b2ContactHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2Contact_GetChildIndexB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ContactWrapper.GetChildIndexB: Integer; cdecl;
begin
Result := b2Contact_GetChildIndexB(FHandle)
end;
procedure b2Contact_SetFriction(_self: b2ContactHandle; friction: Single); cdecl; external LIB_NAME name _PU + 'b2Contact_SetFriction'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ContactWrapper.SetFriction(friction: Single); cdecl;
begin
b2Contact_SetFriction(FHandle, friction)
end;
function b2Contact_GetFriction(_self: b2ContactHandle): Single; cdecl; external LIB_NAME name _PU + 'b2Contact_GetFriction'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ContactWrapper.GetFriction: Single; cdecl;
begin
Result := b2Contact_GetFriction(FHandle)
end;
procedure b2Contact_ResetFriction(_self: b2ContactHandle); cdecl; external LIB_NAME name _PU + 'b2Contact_ResetFriction'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ContactWrapper.ResetFriction; cdecl;
begin
b2Contact_ResetFriction(FHandle)
end;
procedure b2Contact_SetRestitution(_self: b2ContactHandle; restitution: Single); cdecl; external LIB_NAME name _PU + 'b2Contact_SetRestitution'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ContactWrapper.SetRestitution(restitution: Single); cdecl;
begin
b2Contact_SetRestitution(FHandle, restitution)
end;
function b2Contact_GetRestitution(_self: b2ContactHandle): Single; cdecl; external LIB_NAME name _PU + 'b2Contact_GetRestitution'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ContactWrapper.GetRestitution: Single; cdecl;
begin
Result := b2Contact_GetRestitution(FHandle)
end;
procedure b2Contact_ResetRestitution(_self: b2ContactHandle); cdecl; external LIB_NAME name _PU + 'b2Contact_ResetRestitution'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ContactWrapper.ResetRestitution; cdecl;
begin
b2Contact_ResetRestitution(FHandle)
end;
procedure b2Contact_SetTangentSpeed(_self: b2ContactHandle; speed: Single); cdecl; external LIB_NAME name _PU + 'b2Contact_SetTangentSpeed'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ContactWrapper.SetTangentSpeed(speed: Single); cdecl;
begin
b2Contact_SetTangentSpeed(FHandle, speed)
end;
function b2Contact_GetTangentSpeed(_self: b2ContactHandle): Single; cdecl; external LIB_NAME name _PU + 'b2Contact_GetTangentSpeed'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ContactWrapper.GetTangentSpeed: Single; cdecl;
begin
Result := b2Contact_GetTangentSpeed(FHandle)
end;
procedure b2Contact_Evaluate(_self: b2ContactHandle; manifold: Pb2Manifold; const [ref] xfA: b2Transform; const [ref] xfB: b2Transform); cdecl; external LIB_NAME name _PU + 'b2Contact_Evaluate'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ContactWrapper.Evaluate(manifold: Pb2Manifold; const [ref] xfA: b2Transform; const [ref] xfB: b2Transform); cdecl;
begin
b2Contact_Evaluate(FHandle, manifold, xfA, xfB)
end;
function b2ChainAndCircleContact_Create(fixtureA: Pb2Fixture; indexA: Integer; fixtureB: Pb2Fixture; indexB: Integer): b2ChainAndCircleContactHandle; cdecl; external LIB_NAME name _PU + 'b2ChainAndCircleContact_b2ChainAndCircleContact_1'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2ChainAndCircleContactWrapper.Create(fixtureA: Pb2Fixture; indexA: Integer; fixtureB: Pb2Fixture; indexB: Integer): b2ChainAndCircleContactWrapper; cdecl;
begin
Result.FHandle := b2ChainAndCircleContact_Create(fixtureA, indexA, fixtureB, indexB);
end;
procedure b2ChainAndCircleContact_Destroy(_self: b2ChainAndCircleContactHandle); cdecl; external LIB_NAME name _PU + 'b2ChainAndCircleContact_dtor'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ChainAndCircleContactWrapper.Destroy; cdecl;
begin
b2ChainAndCircleContact_Destroy(FHandle);
end;
class operator b2ChainAndCircleContactWrapper.Implicit(handle: b2ChainAndCircleContactHandle): b2ChainAndCircleContactWrapper;
begin
Result.FHandle := handle;
end;
class operator b2ChainAndCircleContactWrapper.Implicit(wrapper: b2ChainAndCircleContactWrapper): b2ChainAndCircleContactHandle;
begin
Result := wrapper.FHandle;
end;
function b2ChainAndCircleContact_GetManifold(_self: b2ChainAndCircleContactHandle): Pb2Manifold; cdecl; external LIB_NAME name _PU + 'b2ChainAndCircleContact_GetManifold'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ChainAndCircleContactWrapper.GetManifold: Pb2Manifold; cdecl;
begin
Result := b2ChainAndCircleContact_GetManifold(FHandle)
end;
procedure b2ChainAndCircleContact_GetWorldManifold(_self: b2ChainAndCircleContactHandle; worldManifold: Pb2WorldManifold); cdecl; external LIB_NAME name _PU + 'b2ChainAndCircleContact_GetWorldManifold'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ChainAndCircleContactWrapper.GetWorldManifold(worldManifold: Pb2WorldManifold); cdecl;
begin
b2ChainAndCircleContact_GetWorldManifold(FHandle, worldManifold)
end;
function b2ChainAndCircleContact_IsTouching(_self: b2ChainAndCircleContactHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2ChainAndCircleContact_IsTouching'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ChainAndCircleContactWrapper.IsTouching: Boolean; cdecl;
begin
Result := b2ChainAndCircleContact_IsTouching(FHandle)
end;
procedure b2ChainAndCircleContact_SetEnabled(_self: b2ChainAndCircleContactHandle; flag: Boolean); cdecl; external LIB_NAME name _PU + 'b2ChainAndCircleContact_SetEnabled'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ChainAndCircleContactWrapper.SetEnabled(flag: Boolean); cdecl;
begin
b2ChainAndCircleContact_SetEnabled(FHandle, flag)
end;
function b2ChainAndCircleContact_IsEnabled(_self: b2ChainAndCircleContactHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2ChainAndCircleContact_IsEnabled'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ChainAndCircleContactWrapper.IsEnabled: Boolean; cdecl;
begin
Result := b2ChainAndCircleContact_IsEnabled(FHandle)
end;
function b2ChainAndCircleContact_GetNext(_self: b2ChainAndCircleContactHandle): b2ContactHandle; cdecl; external LIB_NAME name _PU + 'b2ChainAndCircleContact_GetNext'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ChainAndCircleContactWrapper.GetNext: b2ContactHandle; cdecl;
begin
Result := b2ChainAndCircleContact_GetNext(FHandle)
end;
function b2ChainAndCircleContact_GetFixtureA(_self: b2ChainAndCircleContactHandle): Pb2Fixture; cdecl; external LIB_NAME name _PU + 'b2ChainAndCircleContact_GetFixtureA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ChainAndCircleContactWrapper.GetFixtureA: Pb2Fixture; cdecl;
begin
Result := b2ChainAndCircleContact_GetFixtureA(FHandle)
end;
function b2ChainAndCircleContact_GetChildIndexA(_self: b2ChainAndCircleContactHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2ChainAndCircleContact_GetChildIndexA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ChainAndCircleContactWrapper.GetChildIndexA: Integer; cdecl;
begin
Result := b2ChainAndCircleContact_GetChildIndexA(FHandle)
end;
function b2ChainAndCircleContact_GetFixtureB(_self: b2ChainAndCircleContactHandle): Pb2Fixture; cdecl; external LIB_NAME name _PU + 'b2ChainAndCircleContact_GetFixtureB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ChainAndCircleContactWrapper.GetFixtureB: Pb2Fixture; cdecl;
begin
Result := b2ChainAndCircleContact_GetFixtureB(FHandle)
end;
function b2ChainAndCircleContact_GetChildIndexB(_self: b2ChainAndCircleContactHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2ChainAndCircleContact_GetChildIndexB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ChainAndCircleContactWrapper.GetChildIndexB: Integer; cdecl;
begin
Result := b2ChainAndCircleContact_GetChildIndexB(FHandle)
end;
procedure b2ChainAndCircleContact_SetFriction(_self: b2ChainAndCircleContactHandle; friction: Single); cdecl; external LIB_NAME name _PU + 'b2ChainAndCircleContact_SetFriction'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ChainAndCircleContactWrapper.SetFriction(friction: Single); cdecl;
begin
b2ChainAndCircleContact_SetFriction(FHandle, friction)
end;
function b2ChainAndCircleContact_GetFriction(_self: b2ChainAndCircleContactHandle): Single; cdecl; external LIB_NAME name _PU + 'b2ChainAndCircleContact_GetFriction'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ChainAndCircleContactWrapper.GetFriction: Single; cdecl;
begin
Result := b2ChainAndCircleContact_GetFriction(FHandle)
end;
procedure b2ChainAndCircleContact_ResetFriction(_self: b2ChainAndCircleContactHandle); cdecl; external LIB_NAME name _PU + 'b2ChainAndCircleContact_ResetFriction'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ChainAndCircleContactWrapper.ResetFriction; cdecl;
begin
b2ChainAndCircleContact_ResetFriction(FHandle)
end;
procedure b2ChainAndCircleContact_SetRestitution(_self: b2ChainAndCircleContactHandle; restitution: Single); cdecl; external LIB_NAME name _PU + 'b2ChainAndCircleContact_SetRestitution'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ChainAndCircleContactWrapper.SetRestitution(restitution: Single); cdecl;
begin
b2ChainAndCircleContact_SetRestitution(FHandle, restitution)
end;
function b2ChainAndCircleContact_GetRestitution(_self: b2ChainAndCircleContactHandle): Single; cdecl; external LIB_NAME name _PU + 'b2ChainAndCircleContact_GetRestitution'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ChainAndCircleContactWrapper.GetRestitution: Single; cdecl;
begin
Result := b2ChainAndCircleContact_GetRestitution(FHandle)
end;
procedure b2ChainAndCircleContact_ResetRestitution(_self: b2ChainAndCircleContactHandle); cdecl; external LIB_NAME name _PU + 'b2ChainAndCircleContact_ResetRestitution'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ChainAndCircleContactWrapper.ResetRestitution; cdecl;
begin
b2ChainAndCircleContact_ResetRestitution(FHandle)
end;
procedure b2ChainAndCircleContact_SetTangentSpeed(_self: b2ChainAndCircleContactHandle; speed: Single); cdecl; external LIB_NAME name _PU + 'b2ChainAndCircleContact_SetTangentSpeed'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ChainAndCircleContactWrapper.SetTangentSpeed(speed: Single); cdecl;
begin
b2ChainAndCircleContact_SetTangentSpeed(FHandle, speed)
end;
function b2ChainAndCircleContact_GetTangentSpeed(_self: b2ChainAndCircleContactHandle): Single; cdecl; external LIB_NAME name _PU + 'b2ChainAndCircleContact_GetTangentSpeed'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ChainAndCircleContactWrapper.GetTangentSpeed: Single; cdecl;
begin
Result := b2ChainAndCircleContact_GetTangentSpeed(FHandle)
end;
procedure b2ChainAndCircleContact_Evaluate(_self: b2ChainAndCircleContactHandle; manifold: Pb2Manifold; const [ref] xfA: b2Transform; const [ref] xfB: b2Transform); cdecl; external LIB_NAME name _PU + 'b2ChainAndCircleContact_Evaluate'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ChainAndCircleContactWrapper.Evaluate(manifold: Pb2Manifold; const [ref] xfA: b2Transform; const [ref] xfB: b2Transform); cdecl;
begin
b2ChainAndCircleContact_Evaluate(FHandle, manifold, xfA, xfB)
end;
function b2ChainAndCircleContact_Create_(_self: b2ChainAndCircleContactHandle; fixtureA: Pb2Fixture; indexA: Integer; fixtureB: Pb2Fixture; indexB: Integer; allocator: b2BlockAllocatorHandle): b2ContactHandle; cdecl; external LIB_NAME name _PU + 'b2ChainAndCircleContact_Create'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ChainAndCircleContactWrapper.Create_(fixtureA: Pb2Fixture; indexA: Integer; fixtureB: Pb2Fixture; indexB: Integer; allocator: b2BlockAllocatorHandle): b2ContactHandle; cdecl;
begin
Result := b2ChainAndCircleContact_Create_(FHandle, fixtureA, indexA, fixtureB, indexB, allocator)
end;
procedure b2ChainAndCircleContact_Destroy_(_self: b2ChainAndCircleContactHandle; contact: b2ContactHandle; allocator: b2BlockAllocatorHandle); cdecl; external LIB_NAME name _PU + 'b2ChainAndCircleContact_Destroy'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ChainAndCircleContactWrapper.Destroy_(contact: b2ContactHandle; allocator: b2BlockAllocatorHandle); cdecl;
begin
b2ChainAndCircleContact_Destroy_(FHandle, contact, allocator)
end;
function b2ChainAndPolygonContact_Create(fixtureA: Pb2Fixture; indexA: Integer; fixtureB: Pb2Fixture; indexB: Integer): b2ChainAndPolygonContactHandle; cdecl; external LIB_NAME name _PU + 'b2ChainAndPolygonContact_b2ChainAndPolygonContact_1'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2ChainAndPolygonContactWrapper.Create(fixtureA: Pb2Fixture; indexA: Integer; fixtureB: Pb2Fixture; indexB: Integer): b2ChainAndPolygonContactWrapper; cdecl;
begin
Result.FHandle := b2ChainAndPolygonContact_Create(fixtureA, indexA, fixtureB, indexB);
end;
procedure b2ChainAndPolygonContact_Destroy(_self: b2ChainAndPolygonContactHandle); cdecl; external LIB_NAME name _PU + 'b2ChainAndPolygonContact_dtor'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ChainAndPolygonContactWrapper.Destroy; cdecl;
begin
b2ChainAndPolygonContact_Destroy(FHandle);
end;
class operator b2ChainAndPolygonContactWrapper.Implicit(handle: b2ChainAndPolygonContactHandle): b2ChainAndPolygonContactWrapper;
begin
Result.FHandle := handle;
end;
class operator b2ChainAndPolygonContactWrapper.Implicit(wrapper: b2ChainAndPolygonContactWrapper): b2ChainAndPolygonContactHandle;
begin
Result := wrapper.FHandle;
end;
function b2ChainAndPolygonContact_GetManifold(_self: b2ChainAndPolygonContactHandle): Pb2Manifold; cdecl; external LIB_NAME name _PU + 'b2ChainAndPolygonContact_GetManifold'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ChainAndPolygonContactWrapper.GetManifold: Pb2Manifold; cdecl;
begin
Result := b2ChainAndPolygonContact_GetManifold(FHandle)
end;
procedure b2ChainAndPolygonContact_GetWorldManifold(_self: b2ChainAndPolygonContactHandle; worldManifold: Pb2WorldManifold); cdecl; external LIB_NAME name _PU + 'b2ChainAndPolygonContact_GetWorldManifold'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ChainAndPolygonContactWrapper.GetWorldManifold(worldManifold: Pb2WorldManifold); cdecl;
begin
b2ChainAndPolygonContact_GetWorldManifold(FHandle, worldManifold)
end;
function b2ChainAndPolygonContact_IsTouching(_self: b2ChainAndPolygonContactHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2ChainAndPolygonContact_IsTouching'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ChainAndPolygonContactWrapper.IsTouching: Boolean; cdecl;
begin
Result := b2ChainAndPolygonContact_IsTouching(FHandle)
end;
procedure b2ChainAndPolygonContact_SetEnabled(_self: b2ChainAndPolygonContactHandle; flag: Boolean); cdecl; external LIB_NAME name _PU + 'b2ChainAndPolygonContact_SetEnabled'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ChainAndPolygonContactWrapper.SetEnabled(flag: Boolean); cdecl;
begin
b2ChainAndPolygonContact_SetEnabled(FHandle, flag)
end;
function b2ChainAndPolygonContact_IsEnabled(_self: b2ChainAndPolygonContactHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2ChainAndPolygonContact_IsEnabled'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ChainAndPolygonContactWrapper.IsEnabled: Boolean; cdecl;
begin
Result := b2ChainAndPolygonContact_IsEnabled(FHandle)
end;
function b2ChainAndPolygonContact_GetNext(_self: b2ChainAndPolygonContactHandle): b2ContactHandle; cdecl; external LIB_NAME name _PU + 'b2ChainAndPolygonContact_GetNext'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ChainAndPolygonContactWrapper.GetNext: b2ContactHandle; cdecl;
begin
Result := b2ChainAndPolygonContact_GetNext(FHandle)
end;
function b2ChainAndPolygonContact_GetFixtureA(_self: b2ChainAndPolygonContactHandle): Pb2Fixture; cdecl; external LIB_NAME name _PU + 'b2ChainAndPolygonContact_GetFixtureA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ChainAndPolygonContactWrapper.GetFixtureA: Pb2Fixture; cdecl;
begin
Result := b2ChainAndPolygonContact_GetFixtureA(FHandle)
end;
function b2ChainAndPolygonContact_GetChildIndexA(_self: b2ChainAndPolygonContactHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2ChainAndPolygonContact_GetChildIndexA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ChainAndPolygonContactWrapper.GetChildIndexA: Integer; cdecl;
begin
Result := b2ChainAndPolygonContact_GetChildIndexA(FHandle)
end;
function b2ChainAndPolygonContact_GetFixtureB(_self: b2ChainAndPolygonContactHandle): Pb2Fixture; cdecl; external LIB_NAME name _PU + 'b2ChainAndPolygonContact_GetFixtureB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ChainAndPolygonContactWrapper.GetFixtureB: Pb2Fixture; cdecl;
begin
Result := b2ChainAndPolygonContact_GetFixtureB(FHandle)
end;
function b2ChainAndPolygonContact_GetChildIndexB(_self: b2ChainAndPolygonContactHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2ChainAndPolygonContact_GetChildIndexB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ChainAndPolygonContactWrapper.GetChildIndexB: Integer; cdecl;
begin
Result := b2ChainAndPolygonContact_GetChildIndexB(FHandle)
end;
procedure b2ChainAndPolygonContact_SetFriction(_self: b2ChainAndPolygonContactHandle; friction: Single); cdecl; external LIB_NAME name _PU + 'b2ChainAndPolygonContact_SetFriction'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ChainAndPolygonContactWrapper.SetFriction(friction: Single); cdecl;
begin
b2ChainAndPolygonContact_SetFriction(FHandle, friction)
end;
function b2ChainAndPolygonContact_GetFriction(_self: b2ChainAndPolygonContactHandle): Single; cdecl; external LIB_NAME name _PU + 'b2ChainAndPolygonContact_GetFriction'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ChainAndPolygonContactWrapper.GetFriction: Single; cdecl;
begin
Result := b2ChainAndPolygonContact_GetFriction(FHandle)
end;
procedure b2ChainAndPolygonContact_ResetFriction(_self: b2ChainAndPolygonContactHandle); cdecl; external LIB_NAME name _PU + 'b2ChainAndPolygonContact_ResetFriction'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ChainAndPolygonContactWrapper.ResetFriction; cdecl;
begin
b2ChainAndPolygonContact_ResetFriction(FHandle)
end;
procedure b2ChainAndPolygonContact_SetRestitution(_self: b2ChainAndPolygonContactHandle; restitution: Single); cdecl; external LIB_NAME name _PU + 'b2ChainAndPolygonContact_SetRestitution'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ChainAndPolygonContactWrapper.SetRestitution(restitution: Single); cdecl;
begin
b2ChainAndPolygonContact_SetRestitution(FHandle, restitution)
end;
function b2ChainAndPolygonContact_GetRestitution(_self: b2ChainAndPolygonContactHandle): Single; cdecl; external LIB_NAME name _PU + 'b2ChainAndPolygonContact_GetRestitution'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ChainAndPolygonContactWrapper.GetRestitution: Single; cdecl;
begin
Result := b2ChainAndPolygonContact_GetRestitution(FHandle)
end;
procedure b2ChainAndPolygonContact_ResetRestitution(_self: b2ChainAndPolygonContactHandle); cdecl; external LIB_NAME name _PU + 'b2ChainAndPolygonContact_ResetRestitution'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ChainAndPolygonContactWrapper.ResetRestitution; cdecl;
begin
b2ChainAndPolygonContact_ResetRestitution(FHandle)
end;
procedure b2ChainAndPolygonContact_SetTangentSpeed(_self: b2ChainAndPolygonContactHandle; speed: Single); cdecl; external LIB_NAME name _PU + 'b2ChainAndPolygonContact_SetTangentSpeed'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ChainAndPolygonContactWrapper.SetTangentSpeed(speed: Single); cdecl;
begin
b2ChainAndPolygonContact_SetTangentSpeed(FHandle, speed)
end;
function b2ChainAndPolygonContact_GetTangentSpeed(_self: b2ChainAndPolygonContactHandle): Single; cdecl; external LIB_NAME name _PU + 'b2ChainAndPolygonContact_GetTangentSpeed'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ChainAndPolygonContactWrapper.GetTangentSpeed: Single; cdecl;
begin
Result := b2ChainAndPolygonContact_GetTangentSpeed(FHandle)
end;
procedure b2ChainAndPolygonContact_Evaluate(_self: b2ChainAndPolygonContactHandle; manifold: Pb2Manifold; const [ref] xfA: b2Transform; const [ref] xfB: b2Transform); cdecl; external LIB_NAME name _PU + 'b2ChainAndPolygonContact_Evaluate'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ChainAndPolygonContactWrapper.Evaluate(manifold: Pb2Manifold; const [ref] xfA: b2Transform; const [ref] xfB: b2Transform); cdecl;
begin
b2ChainAndPolygonContact_Evaluate(FHandle, manifold, xfA, xfB)
end;
function b2ChainAndPolygonContact_Create_(_self: b2ChainAndPolygonContactHandle; fixtureA: Pb2Fixture; indexA: Integer; fixtureB: Pb2Fixture; indexB: Integer; allocator: b2BlockAllocatorHandle): b2ContactHandle; cdecl; external LIB_NAME name _PU + 'b2ChainAndPolygonContact_Create'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ChainAndPolygonContactWrapper.Create_(fixtureA: Pb2Fixture; indexA: Integer; fixtureB: Pb2Fixture; indexB: Integer; allocator: b2BlockAllocatorHandle): b2ContactHandle; cdecl;
begin
Result := b2ChainAndPolygonContact_Create_(FHandle, fixtureA, indexA, fixtureB, indexB, allocator)
end;
procedure b2ChainAndPolygonContact_Destroy_(_self: b2ChainAndPolygonContactHandle; contact: b2ContactHandle; allocator: b2BlockAllocatorHandle); cdecl; external LIB_NAME name _PU + 'b2ChainAndPolygonContact_Destroy'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ChainAndPolygonContactWrapper.Destroy_(contact: b2ContactHandle; allocator: b2BlockAllocatorHandle); cdecl;
begin
b2ChainAndPolygonContact_Destroy_(FHandle, contact, allocator)
end;
function b2CircleContact_Create(fixtureA: Pb2Fixture; fixtureB: Pb2Fixture): b2CircleContactHandle; cdecl; external LIB_NAME name _PU + 'b2CircleContact_b2CircleContact_1'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2CircleContactWrapper.Create(fixtureA: Pb2Fixture; fixtureB: Pb2Fixture): b2CircleContactWrapper; cdecl;
begin
Result.FHandle := b2CircleContact_Create(fixtureA, fixtureB);
end;
procedure b2CircleContact_Destroy(_self: b2CircleContactHandle); cdecl; external LIB_NAME name _PU + 'b2CircleContact_dtor'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2CircleContactWrapper.Destroy; cdecl;
begin
b2CircleContact_Destroy(FHandle);
end;
class operator b2CircleContactWrapper.Implicit(handle: b2CircleContactHandle): b2CircleContactWrapper;
begin
Result.FHandle := handle;
end;
class operator b2CircleContactWrapper.Implicit(wrapper: b2CircleContactWrapper): b2CircleContactHandle;
begin
Result := wrapper.FHandle;
end;
function b2CircleContact_GetManifold(_self: b2CircleContactHandle): Pb2Manifold; cdecl; external LIB_NAME name _PU + 'b2CircleContact_GetManifold'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2CircleContactWrapper.GetManifold: Pb2Manifold; cdecl;
begin
Result := b2CircleContact_GetManifold(FHandle)
end;
procedure b2CircleContact_GetWorldManifold(_self: b2CircleContactHandle; worldManifold: Pb2WorldManifold); cdecl; external LIB_NAME name _PU + 'b2CircleContact_GetWorldManifold'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2CircleContactWrapper.GetWorldManifold(worldManifold: Pb2WorldManifold); cdecl;
begin
b2CircleContact_GetWorldManifold(FHandle, worldManifold)
end;
function b2CircleContact_IsTouching(_self: b2CircleContactHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2CircleContact_IsTouching'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2CircleContactWrapper.IsTouching: Boolean; cdecl;
begin
Result := b2CircleContact_IsTouching(FHandle)
end;
procedure b2CircleContact_SetEnabled(_self: b2CircleContactHandle; flag: Boolean); cdecl; external LIB_NAME name _PU + 'b2CircleContact_SetEnabled'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2CircleContactWrapper.SetEnabled(flag: Boolean); cdecl;
begin
b2CircleContact_SetEnabled(FHandle, flag)
end;
function b2CircleContact_IsEnabled(_self: b2CircleContactHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2CircleContact_IsEnabled'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2CircleContactWrapper.IsEnabled: Boolean; cdecl;
begin
Result := b2CircleContact_IsEnabled(FHandle)
end;
function b2CircleContact_GetNext(_self: b2CircleContactHandle): b2ContactHandle; cdecl; external LIB_NAME name _PU + 'b2CircleContact_GetNext'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2CircleContactWrapper.GetNext: b2ContactHandle; cdecl;
begin
Result := b2CircleContact_GetNext(FHandle)
end;
function b2CircleContact_GetFixtureA(_self: b2CircleContactHandle): Pb2Fixture; cdecl; external LIB_NAME name _PU + 'b2CircleContact_GetFixtureA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2CircleContactWrapper.GetFixtureA: Pb2Fixture; cdecl;
begin
Result := b2CircleContact_GetFixtureA(FHandle)
end;
function b2CircleContact_GetChildIndexA(_self: b2CircleContactHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2CircleContact_GetChildIndexA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2CircleContactWrapper.GetChildIndexA: Integer; cdecl;
begin
Result := b2CircleContact_GetChildIndexA(FHandle)
end;
function b2CircleContact_GetFixtureB(_self: b2CircleContactHandle): Pb2Fixture; cdecl; external LIB_NAME name _PU + 'b2CircleContact_GetFixtureB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2CircleContactWrapper.GetFixtureB: Pb2Fixture; cdecl;
begin
Result := b2CircleContact_GetFixtureB(FHandle)
end;
function b2CircleContact_GetChildIndexB(_self: b2CircleContactHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2CircleContact_GetChildIndexB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2CircleContactWrapper.GetChildIndexB: Integer; cdecl;
begin
Result := b2CircleContact_GetChildIndexB(FHandle)
end;
procedure b2CircleContact_SetFriction(_self: b2CircleContactHandle; friction: Single); cdecl; external LIB_NAME name _PU + 'b2CircleContact_SetFriction'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2CircleContactWrapper.SetFriction(friction: Single); cdecl;
begin
b2CircleContact_SetFriction(FHandle, friction)
end;
function b2CircleContact_GetFriction(_self: b2CircleContactHandle): Single; cdecl; external LIB_NAME name _PU + 'b2CircleContact_GetFriction'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2CircleContactWrapper.GetFriction: Single; cdecl;
begin
Result := b2CircleContact_GetFriction(FHandle)
end;
procedure b2CircleContact_ResetFriction(_self: b2CircleContactHandle); cdecl; external LIB_NAME name _PU + 'b2CircleContact_ResetFriction'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2CircleContactWrapper.ResetFriction; cdecl;
begin
b2CircleContact_ResetFriction(FHandle)
end;
procedure b2CircleContact_SetRestitution(_self: b2CircleContactHandle; restitution: Single); cdecl; external LIB_NAME name _PU + 'b2CircleContact_SetRestitution'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2CircleContactWrapper.SetRestitution(restitution: Single); cdecl;
begin
b2CircleContact_SetRestitution(FHandle, restitution)
end;
function b2CircleContact_GetRestitution(_self: b2CircleContactHandle): Single; cdecl; external LIB_NAME name _PU + 'b2CircleContact_GetRestitution'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2CircleContactWrapper.GetRestitution: Single; cdecl;
begin
Result := b2CircleContact_GetRestitution(FHandle)
end;
procedure b2CircleContact_ResetRestitution(_self: b2CircleContactHandle); cdecl; external LIB_NAME name _PU + 'b2CircleContact_ResetRestitution'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2CircleContactWrapper.ResetRestitution; cdecl;
begin
b2CircleContact_ResetRestitution(FHandle)
end;
procedure b2CircleContact_SetTangentSpeed(_self: b2CircleContactHandle; speed: Single); cdecl; external LIB_NAME name _PU + 'b2CircleContact_SetTangentSpeed'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2CircleContactWrapper.SetTangentSpeed(speed: Single); cdecl;
begin
b2CircleContact_SetTangentSpeed(FHandle, speed)
end;
function b2CircleContact_GetTangentSpeed(_self: b2CircleContactHandle): Single; cdecl; external LIB_NAME name _PU + 'b2CircleContact_GetTangentSpeed'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2CircleContactWrapper.GetTangentSpeed: Single; cdecl;
begin
Result := b2CircleContact_GetTangentSpeed(FHandle)
end;
procedure b2CircleContact_Evaluate(_self: b2CircleContactHandle; manifold: Pb2Manifold; const [ref] xfA: b2Transform; const [ref] xfB: b2Transform); cdecl; external LIB_NAME name _PU + 'b2CircleContact_Evaluate'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2CircleContactWrapper.Evaluate(manifold: Pb2Manifold; const [ref] xfA: b2Transform; const [ref] xfB: b2Transform); cdecl;
begin
b2CircleContact_Evaluate(FHandle, manifold, xfA, xfB)
end;
function b2CircleContact_Create_(_self: b2CircleContactHandle; fixtureA: Pb2Fixture; indexA: Integer; fixtureB: Pb2Fixture; indexB: Integer; allocator: b2BlockAllocatorHandle): b2ContactHandle; cdecl; external LIB_NAME name _PU + 'b2CircleContact_Create'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2CircleContactWrapper.Create_(fixtureA: Pb2Fixture; indexA: Integer; fixtureB: Pb2Fixture; indexB: Integer; allocator: b2BlockAllocatorHandle): b2ContactHandle; cdecl;
begin
Result := b2CircleContact_Create_(FHandle, fixtureA, indexA, fixtureB, indexB, allocator)
end;
procedure b2CircleContact_Destroy_(_self: b2CircleContactHandle; contact: b2ContactHandle; allocator: b2BlockAllocatorHandle); cdecl; external LIB_NAME name _PU + 'b2CircleContact_Destroy'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2CircleContactWrapper.Destroy_(contact: b2ContactHandle; allocator: b2BlockAllocatorHandle); cdecl;
begin
b2CircleContact_Destroy_(FHandle, contact, allocator)
end;
function b2VelocityConstraintPoint_Create: b2VelocityConstraintPoint; cdecl; external LIB_NAME name _PU + 'b2VelocityConstraintPoint_b2VelocityConstraintPoint'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2VelocityConstraintPoint.Create: b2VelocityConstraintPoint; cdecl;
begin
Result := b2VelocityConstraintPoint_Create;
end;
function b2ContactVelocityConstraint_Create: b2ContactVelocityConstraint; cdecl; external LIB_NAME name _PU + 'b2ContactVelocityConstraint_b2ContactVelocityConstraint'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2ContactVelocityConstraint.Create: b2ContactVelocityConstraint; cdecl;
begin
Result := b2ContactVelocityConstraint_Create;
end;
function b2ContactSolverDef_Create: b2ContactSolverDef; cdecl; external LIB_NAME name _PU + 'b2ContactSolverDef_b2ContactSolverDef'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2ContactSolverDef.Create: b2ContactSolverDef; cdecl;
begin
Result := b2ContactSolverDef_Create;
end;
function b2ContactSolver_Create(def: Pb2ContactSolverDef): b2ContactSolverHandle; cdecl; external LIB_NAME name _PU + 'b2ContactSolver_b2ContactSolver_1'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2ContactSolverWrapper.Create(def: Pb2ContactSolverDef): b2ContactSolverWrapper; cdecl;
begin
Result.FHandle := b2ContactSolver_Create(def);
end;
procedure b2ContactSolver_Destroy(_self: b2ContactSolverHandle); cdecl; external LIB_NAME name _PU + 'b2ContactSolver_dtor'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ContactSolverWrapper.Destroy; cdecl;
begin
b2ContactSolver_Destroy(FHandle);
end;
class operator b2ContactSolverWrapper.Implicit(handle: b2ContactSolverHandle): b2ContactSolverWrapper;
begin
Result.FHandle := handle;
end;
class operator b2ContactSolverWrapper.Implicit(wrapper: b2ContactSolverWrapper): b2ContactSolverHandle;
begin
Result := wrapper.FHandle;
end;
procedure b2ContactSolver_InitializeVelocityConstraints(_self: b2ContactSolverHandle); cdecl; external LIB_NAME name _PU + 'b2ContactSolver_InitializeVelocityConstraints'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ContactSolverWrapper.InitializeVelocityConstraints; cdecl;
begin
b2ContactSolver_InitializeVelocityConstraints(FHandle)
end;
procedure b2ContactSolver_WarmStart(_self: b2ContactSolverHandle); cdecl; external LIB_NAME name _PU + 'b2ContactSolver_WarmStart'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ContactSolverWrapper.WarmStart; cdecl;
begin
b2ContactSolver_WarmStart(FHandle)
end;
procedure b2ContactSolver_SolveVelocityConstraints(_self: b2ContactSolverHandle); cdecl; external LIB_NAME name _PU + 'b2ContactSolver_SolveVelocityConstraints'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ContactSolverWrapper.SolveVelocityConstraints; cdecl;
begin
b2ContactSolver_SolveVelocityConstraints(FHandle)
end;
procedure b2ContactSolver_StoreImpulses(_self: b2ContactSolverHandle); cdecl; external LIB_NAME name _PU + 'b2ContactSolver_StoreImpulses'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ContactSolverWrapper.StoreImpulses; cdecl;
begin
b2ContactSolver_StoreImpulses(FHandle)
end;
function b2ContactSolver_SolvePositionConstraints(_self: b2ContactSolverHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2ContactSolver_SolvePositionConstraints'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ContactSolverWrapper.SolvePositionConstraints: Boolean; cdecl;
begin
Result := b2ContactSolver_SolvePositionConstraints(FHandle)
end;
function b2ContactSolver_SolveTOIPositionConstraints(_self: b2ContactSolverHandle; toiIndexA: Integer; toiIndexB: Integer): Boolean; cdecl; external LIB_NAME name _PU + 'b2ContactSolver_SolveTOIPositionConstraints'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ContactSolverWrapper.SolveTOIPositionConstraints(toiIndexA: Integer; toiIndexB: Integer): Boolean; cdecl;
begin
Result := b2ContactSolver_SolveTOIPositionConstraints(FHandle, toiIndexA, toiIndexB)
end;
function b2ContactSolver_Get_m_step(_self: b2ContactSolverHandle): b2TimeStep; cdecl; external LIB_NAME name _PU + 'b2ContactSolver_Get_m_step'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ContactSolver_Set_m_step(_self: b2ContactSolverHandle; aNewValue: b2TimeStep); cdecl; external LIB_NAME name _PU + 'b2ContactSolver_Set_m_step'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ContactSolver_Get_m_step_P(_self: b2ContactSolverHandle): Pb2TimeStep; cdecl; external LIB_NAME name _PU + 'b2ContactSolver_Get_m_step_P'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ContactSolverWrapper.Get_m_step: b2TimeStep; cdecl;
begin
Result := b2ContactSolver_Get_m_step(FHandle);
end;
procedure b2ContactSolverWrapper.Set_m_step(aNewValue: b2TimeStep); cdecl;
begin
b2ContactSolver_Set_m_step(FHandle, aNewValue);
end;
function b2ContactSolverWrapper.Get_m_step_P: Pb2TimeStep; cdecl;
begin
Result := b2ContactSolver_Get_m_step_P(FHandle);
end;
function b2ContactSolver_Get_m_positions(_self: b2ContactSolverHandle): Pb2Position; cdecl; external LIB_NAME name _PU + 'b2ContactSolver_Get_m_positions'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ContactSolver_Set_m_positions(_self: b2ContactSolverHandle; aNewValue: Pb2Position); cdecl; external LIB_NAME name _PU + 'b2ContactSolver_Set_m_positions'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ContactSolverWrapper.Get_m_positions: Pb2Position; cdecl;
begin
Result := b2ContactSolver_Get_m_positions(FHandle);
end;
procedure b2ContactSolverWrapper.Set_m_positions(aNewValue: Pb2Position); cdecl;
begin
b2ContactSolver_Set_m_positions(FHandle, aNewValue);
end;
function b2ContactSolver_Get_m_velocities(_self: b2ContactSolverHandle): Pb2Velocity; cdecl; external LIB_NAME name _PU + 'b2ContactSolver_Get_m_velocities'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ContactSolver_Set_m_velocities(_self: b2ContactSolverHandle; aNewValue: Pb2Velocity); cdecl; external LIB_NAME name _PU + 'b2ContactSolver_Set_m_velocities'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ContactSolverWrapper.Get_m_velocities: Pb2Velocity; cdecl;
begin
Result := b2ContactSolver_Get_m_velocities(FHandle);
end;
procedure b2ContactSolverWrapper.Set_m_velocities(aNewValue: Pb2Velocity); cdecl;
begin
b2ContactSolver_Set_m_velocities(FHandle, aNewValue);
end;
function b2ContactSolver_Get_m_allocator(_self: b2ContactSolverHandle): b2StackAllocatorHandle; cdecl; external LIB_NAME name _PU + 'b2ContactSolver_Get_m_allocator'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ContactSolver_Set_m_allocator(_self: b2ContactSolverHandle; aNewValue: b2StackAllocatorHandle); cdecl; external LIB_NAME name _PU + 'b2ContactSolver_Set_m_allocator'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ContactSolverWrapper.Get_m_allocator: b2StackAllocatorHandle; cdecl;
begin
Result := b2ContactSolver_Get_m_allocator(FHandle);
end;
procedure b2ContactSolverWrapper.Set_m_allocator(aNewValue: b2StackAllocatorHandle); cdecl;
begin
b2ContactSolver_Set_m_allocator(FHandle, aNewValue);
end;
function b2ContactSolver_Get_m_velocityConstraints(_self: b2ContactSolverHandle): Pb2ContactVelocityConstraint; cdecl; external LIB_NAME name _PU + 'b2ContactSolver_Get_m_velocityConstraints'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ContactSolver_Set_m_velocityConstraints(_self: b2ContactSolverHandle; aNewValue: Pb2ContactVelocityConstraint); cdecl; external LIB_NAME name _PU + 'b2ContactSolver_Set_m_velocityConstraints'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ContactSolverWrapper.Get_m_velocityConstraints: Pb2ContactVelocityConstraint; cdecl;
begin
Result := b2ContactSolver_Get_m_velocityConstraints(FHandle);
end;
procedure b2ContactSolverWrapper.Set_m_velocityConstraints(aNewValue: Pb2ContactVelocityConstraint); cdecl;
begin
b2ContactSolver_Set_m_velocityConstraints(FHandle, aNewValue);
end;
function b2ContactSolver_Get_m_contacts(_self: b2ContactSolverHandle): Pb2ContactHandle; cdecl; external LIB_NAME name _PU + 'b2ContactSolver_Get_m_contacts'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ContactSolver_Set_m_contacts(_self: b2ContactSolverHandle; aNewValue: Pb2ContactHandle); cdecl; external LIB_NAME name _PU + 'b2ContactSolver_Set_m_contacts'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ContactSolverWrapper.Get_m_contacts: Pb2ContactHandle; cdecl;
begin
Result := b2ContactSolver_Get_m_contacts(FHandle);
end;
procedure b2ContactSolverWrapper.Set_m_contacts(aNewValue: Pb2ContactHandle); cdecl;
begin
b2ContactSolver_Set_m_contacts(FHandle, aNewValue);
end;
function b2ContactSolver_Get_m_count(_self: b2ContactSolverHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2ContactSolver_Get_m_count'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2ContactSolver_Set_m_count(_self: b2ContactSolverHandle; aNewValue: Integer); cdecl; external LIB_NAME name _PU + 'b2ContactSolver_Set_m_count'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2ContactSolverWrapper.Get_m_count: Integer; cdecl;
begin
Result := b2ContactSolver_Get_m_count(FHandle);
end;
procedure b2ContactSolverWrapper.Set_m_count(aNewValue: Integer); cdecl;
begin
b2ContactSolver_Set_m_count(FHandle, aNewValue);
end;
function b2EdgeAndCircleContact_Create(fixtureA: Pb2Fixture; fixtureB: Pb2Fixture): b2EdgeAndCircleContactHandle; cdecl; external LIB_NAME name _PU + 'b2EdgeAndCircleContact_b2EdgeAndCircleContact_1'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2EdgeAndCircleContactWrapper.Create(fixtureA: Pb2Fixture; fixtureB: Pb2Fixture): b2EdgeAndCircleContactWrapper; cdecl;
begin
Result.FHandle := b2EdgeAndCircleContact_Create(fixtureA, fixtureB);
end;
procedure b2EdgeAndCircleContact_Destroy(_self: b2EdgeAndCircleContactHandle); cdecl; external LIB_NAME name _PU + 'b2EdgeAndCircleContact_dtor'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2EdgeAndCircleContactWrapper.Destroy; cdecl;
begin
b2EdgeAndCircleContact_Destroy(FHandle);
end;
class operator b2EdgeAndCircleContactWrapper.Implicit(handle: b2EdgeAndCircleContactHandle): b2EdgeAndCircleContactWrapper;
begin
Result.FHandle := handle;
end;
class operator b2EdgeAndCircleContactWrapper.Implicit(wrapper: b2EdgeAndCircleContactWrapper): b2EdgeAndCircleContactHandle;
begin
Result := wrapper.FHandle;
end;
function b2EdgeAndCircleContact_GetManifold(_self: b2EdgeAndCircleContactHandle): Pb2Manifold; cdecl; external LIB_NAME name _PU + 'b2EdgeAndCircleContact_GetManifold'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2EdgeAndCircleContactWrapper.GetManifold: Pb2Manifold; cdecl;
begin
Result := b2EdgeAndCircleContact_GetManifold(FHandle)
end;
procedure b2EdgeAndCircleContact_GetWorldManifold(_self: b2EdgeAndCircleContactHandle; worldManifold: Pb2WorldManifold); cdecl; external LIB_NAME name _PU + 'b2EdgeAndCircleContact_GetWorldManifold'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2EdgeAndCircleContactWrapper.GetWorldManifold(worldManifold: Pb2WorldManifold); cdecl;
begin
b2EdgeAndCircleContact_GetWorldManifold(FHandle, worldManifold)
end;
function b2EdgeAndCircleContact_IsTouching(_self: b2EdgeAndCircleContactHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2EdgeAndCircleContact_IsTouching'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2EdgeAndCircleContactWrapper.IsTouching: Boolean; cdecl;
begin
Result := b2EdgeAndCircleContact_IsTouching(FHandle)
end;
procedure b2EdgeAndCircleContact_SetEnabled(_self: b2EdgeAndCircleContactHandle; flag: Boolean); cdecl; external LIB_NAME name _PU + 'b2EdgeAndCircleContact_SetEnabled'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2EdgeAndCircleContactWrapper.SetEnabled(flag: Boolean); cdecl;
begin
b2EdgeAndCircleContact_SetEnabled(FHandle, flag)
end;
function b2EdgeAndCircleContact_IsEnabled(_self: b2EdgeAndCircleContactHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2EdgeAndCircleContact_IsEnabled'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2EdgeAndCircleContactWrapper.IsEnabled: Boolean; cdecl;
begin
Result := b2EdgeAndCircleContact_IsEnabled(FHandle)
end;
function b2EdgeAndCircleContact_GetNext(_self: b2EdgeAndCircleContactHandle): b2ContactHandle; cdecl; external LIB_NAME name _PU + 'b2EdgeAndCircleContact_GetNext'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2EdgeAndCircleContactWrapper.GetNext: b2ContactHandle; cdecl;
begin
Result := b2EdgeAndCircleContact_GetNext(FHandle)
end;
function b2EdgeAndCircleContact_GetFixtureA(_self: b2EdgeAndCircleContactHandle): Pb2Fixture; cdecl; external LIB_NAME name _PU + 'b2EdgeAndCircleContact_GetFixtureA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2EdgeAndCircleContactWrapper.GetFixtureA: Pb2Fixture; cdecl;
begin
Result := b2EdgeAndCircleContact_GetFixtureA(FHandle)
end;
function b2EdgeAndCircleContact_GetChildIndexA(_self: b2EdgeAndCircleContactHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2EdgeAndCircleContact_GetChildIndexA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2EdgeAndCircleContactWrapper.GetChildIndexA: Integer; cdecl;
begin
Result := b2EdgeAndCircleContact_GetChildIndexA(FHandle)
end;
function b2EdgeAndCircleContact_GetFixtureB(_self: b2EdgeAndCircleContactHandle): Pb2Fixture; cdecl; external LIB_NAME name _PU + 'b2EdgeAndCircleContact_GetFixtureB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2EdgeAndCircleContactWrapper.GetFixtureB: Pb2Fixture; cdecl;
begin
Result := b2EdgeAndCircleContact_GetFixtureB(FHandle)
end;
function b2EdgeAndCircleContact_GetChildIndexB(_self: b2EdgeAndCircleContactHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2EdgeAndCircleContact_GetChildIndexB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2EdgeAndCircleContactWrapper.GetChildIndexB: Integer; cdecl;
begin
Result := b2EdgeAndCircleContact_GetChildIndexB(FHandle)
end;
procedure b2EdgeAndCircleContact_SetFriction(_self: b2EdgeAndCircleContactHandle; friction: Single); cdecl; external LIB_NAME name _PU + 'b2EdgeAndCircleContact_SetFriction'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2EdgeAndCircleContactWrapper.SetFriction(friction: Single); cdecl;
begin
b2EdgeAndCircleContact_SetFriction(FHandle, friction)
end;
function b2EdgeAndCircleContact_GetFriction(_self: b2EdgeAndCircleContactHandle): Single; cdecl; external LIB_NAME name _PU + 'b2EdgeAndCircleContact_GetFriction'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2EdgeAndCircleContactWrapper.GetFriction: Single; cdecl;
begin
Result := b2EdgeAndCircleContact_GetFriction(FHandle)
end;
procedure b2EdgeAndCircleContact_ResetFriction(_self: b2EdgeAndCircleContactHandle); cdecl; external LIB_NAME name _PU + 'b2EdgeAndCircleContact_ResetFriction'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2EdgeAndCircleContactWrapper.ResetFriction; cdecl;
begin
b2EdgeAndCircleContact_ResetFriction(FHandle)
end;
procedure b2EdgeAndCircleContact_SetRestitution(_self: b2EdgeAndCircleContactHandle; restitution: Single); cdecl; external LIB_NAME name _PU + 'b2EdgeAndCircleContact_SetRestitution'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2EdgeAndCircleContactWrapper.SetRestitution(restitution: Single); cdecl;
begin
b2EdgeAndCircleContact_SetRestitution(FHandle, restitution)
end;
function b2EdgeAndCircleContact_GetRestitution(_self: b2EdgeAndCircleContactHandle): Single; cdecl; external LIB_NAME name _PU + 'b2EdgeAndCircleContact_GetRestitution'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2EdgeAndCircleContactWrapper.GetRestitution: Single; cdecl;
begin
Result := b2EdgeAndCircleContact_GetRestitution(FHandle)
end;
procedure b2EdgeAndCircleContact_ResetRestitution(_self: b2EdgeAndCircleContactHandle); cdecl; external LIB_NAME name _PU + 'b2EdgeAndCircleContact_ResetRestitution'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2EdgeAndCircleContactWrapper.ResetRestitution; cdecl;
begin
b2EdgeAndCircleContact_ResetRestitution(FHandle)
end;
procedure b2EdgeAndCircleContact_SetTangentSpeed(_self: b2EdgeAndCircleContactHandle; speed: Single); cdecl; external LIB_NAME name _PU + 'b2EdgeAndCircleContact_SetTangentSpeed'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2EdgeAndCircleContactWrapper.SetTangentSpeed(speed: Single); cdecl;
begin
b2EdgeAndCircleContact_SetTangentSpeed(FHandle, speed)
end;
function b2EdgeAndCircleContact_GetTangentSpeed(_self: b2EdgeAndCircleContactHandle): Single; cdecl; external LIB_NAME name _PU + 'b2EdgeAndCircleContact_GetTangentSpeed'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2EdgeAndCircleContactWrapper.GetTangentSpeed: Single; cdecl;
begin
Result := b2EdgeAndCircleContact_GetTangentSpeed(FHandle)
end;
procedure b2EdgeAndCircleContact_Evaluate(_self: b2EdgeAndCircleContactHandle; manifold: Pb2Manifold; const [ref] xfA: b2Transform; const [ref] xfB: b2Transform); cdecl; external LIB_NAME name _PU + 'b2EdgeAndCircleContact_Evaluate'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2EdgeAndCircleContactWrapper.Evaluate(manifold: Pb2Manifold; const [ref] xfA: b2Transform; const [ref] xfB: b2Transform); cdecl;
begin
b2EdgeAndCircleContact_Evaluate(FHandle, manifold, xfA, xfB)
end;
function b2EdgeAndCircleContact_Create_(_self: b2EdgeAndCircleContactHandle; fixtureA: Pb2Fixture; indexA: Integer; fixtureB: Pb2Fixture; indexB: Integer; allocator: b2BlockAllocatorHandle): b2ContactHandle; cdecl; external LIB_NAME name _PU + 'b2EdgeAndCircleContact_Create'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2EdgeAndCircleContactWrapper.Create_(fixtureA: Pb2Fixture; indexA: Integer; fixtureB: Pb2Fixture; indexB: Integer; allocator: b2BlockAllocatorHandle): b2ContactHandle; cdecl;
begin
Result := b2EdgeAndCircleContact_Create_(FHandle, fixtureA, indexA, fixtureB, indexB, allocator)
end;
procedure b2EdgeAndCircleContact_Destroy_(_self: b2EdgeAndCircleContactHandle; contact: b2ContactHandle; allocator: b2BlockAllocatorHandle); cdecl; external LIB_NAME name _PU + 'b2EdgeAndCircleContact_Destroy'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2EdgeAndCircleContactWrapper.Destroy_(contact: b2ContactHandle; allocator: b2BlockAllocatorHandle); cdecl;
begin
b2EdgeAndCircleContact_Destroy_(FHandle, contact, allocator)
end;
function b2EdgeAndPolygonContact_Create(fixtureA: Pb2Fixture; fixtureB: Pb2Fixture): b2EdgeAndPolygonContactHandle; cdecl; external LIB_NAME name _PU + 'b2EdgeAndPolygonContact_b2EdgeAndPolygonContact_1'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2EdgeAndPolygonContactWrapper.Create(fixtureA: Pb2Fixture; fixtureB: Pb2Fixture): b2EdgeAndPolygonContactWrapper; cdecl;
begin
Result.FHandle := b2EdgeAndPolygonContact_Create(fixtureA, fixtureB);
end;
procedure b2EdgeAndPolygonContact_Destroy(_self: b2EdgeAndPolygonContactHandle); cdecl; external LIB_NAME name _PU + 'b2EdgeAndPolygonContact_dtor'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2EdgeAndPolygonContactWrapper.Destroy; cdecl;
begin
b2EdgeAndPolygonContact_Destroy(FHandle);
end;
class operator b2EdgeAndPolygonContactWrapper.Implicit(handle: b2EdgeAndPolygonContactHandle): b2EdgeAndPolygonContactWrapper;
begin
Result.FHandle := handle;
end;
class operator b2EdgeAndPolygonContactWrapper.Implicit(wrapper: b2EdgeAndPolygonContactWrapper): b2EdgeAndPolygonContactHandle;
begin
Result := wrapper.FHandle;
end;
function b2EdgeAndPolygonContact_GetManifold(_self: b2EdgeAndPolygonContactHandle): Pb2Manifold; cdecl; external LIB_NAME name _PU + 'b2EdgeAndPolygonContact_GetManifold'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2EdgeAndPolygonContactWrapper.GetManifold: Pb2Manifold; cdecl;
begin
Result := b2EdgeAndPolygonContact_GetManifold(FHandle)
end;
procedure b2EdgeAndPolygonContact_GetWorldManifold(_self: b2EdgeAndPolygonContactHandle; worldManifold: Pb2WorldManifold); cdecl; external LIB_NAME name _PU + 'b2EdgeAndPolygonContact_GetWorldManifold'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2EdgeAndPolygonContactWrapper.GetWorldManifold(worldManifold: Pb2WorldManifold); cdecl;
begin
b2EdgeAndPolygonContact_GetWorldManifold(FHandle, worldManifold)
end;
function b2EdgeAndPolygonContact_IsTouching(_self: b2EdgeAndPolygonContactHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2EdgeAndPolygonContact_IsTouching'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2EdgeAndPolygonContactWrapper.IsTouching: Boolean; cdecl;
begin
Result := b2EdgeAndPolygonContact_IsTouching(FHandle)
end;
procedure b2EdgeAndPolygonContact_SetEnabled(_self: b2EdgeAndPolygonContactHandle; flag: Boolean); cdecl; external LIB_NAME name _PU + 'b2EdgeAndPolygonContact_SetEnabled'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2EdgeAndPolygonContactWrapper.SetEnabled(flag: Boolean); cdecl;
begin
b2EdgeAndPolygonContact_SetEnabled(FHandle, flag)
end;
function b2EdgeAndPolygonContact_IsEnabled(_self: b2EdgeAndPolygonContactHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2EdgeAndPolygonContact_IsEnabled'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2EdgeAndPolygonContactWrapper.IsEnabled: Boolean; cdecl;
begin
Result := b2EdgeAndPolygonContact_IsEnabled(FHandle)
end;
function b2EdgeAndPolygonContact_GetNext(_self: b2EdgeAndPolygonContactHandle): b2ContactHandle; cdecl; external LIB_NAME name _PU + 'b2EdgeAndPolygonContact_GetNext'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2EdgeAndPolygonContactWrapper.GetNext: b2ContactHandle; cdecl;
begin
Result := b2EdgeAndPolygonContact_GetNext(FHandle)
end;
function b2EdgeAndPolygonContact_GetFixtureA(_self: b2EdgeAndPolygonContactHandle): Pb2Fixture; cdecl; external LIB_NAME name _PU + 'b2EdgeAndPolygonContact_GetFixtureA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2EdgeAndPolygonContactWrapper.GetFixtureA: Pb2Fixture; cdecl;
begin
Result := b2EdgeAndPolygonContact_GetFixtureA(FHandle)
end;
function b2EdgeAndPolygonContact_GetChildIndexA(_self: b2EdgeAndPolygonContactHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2EdgeAndPolygonContact_GetChildIndexA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2EdgeAndPolygonContactWrapper.GetChildIndexA: Integer; cdecl;
begin
Result := b2EdgeAndPolygonContact_GetChildIndexA(FHandle)
end;
function b2EdgeAndPolygonContact_GetFixtureB(_self: b2EdgeAndPolygonContactHandle): Pb2Fixture; cdecl; external LIB_NAME name _PU + 'b2EdgeAndPolygonContact_GetFixtureB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2EdgeAndPolygonContactWrapper.GetFixtureB: Pb2Fixture; cdecl;
begin
Result := b2EdgeAndPolygonContact_GetFixtureB(FHandle)
end;
function b2EdgeAndPolygonContact_GetChildIndexB(_self: b2EdgeAndPolygonContactHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2EdgeAndPolygonContact_GetChildIndexB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2EdgeAndPolygonContactWrapper.GetChildIndexB: Integer; cdecl;
begin
Result := b2EdgeAndPolygonContact_GetChildIndexB(FHandle)
end;
procedure b2EdgeAndPolygonContact_SetFriction(_self: b2EdgeAndPolygonContactHandle; friction: Single); cdecl; external LIB_NAME name _PU + 'b2EdgeAndPolygonContact_SetFriction'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2EdgeAndPolygonContactWrapper.SetFriction(friction: Single); cdecl;
begin
b2EdgeAndPolygonContact_SetFriction(FHandle, friction)
end;
function b2EdgeAndPolygonContact_GetFriction(_self: b2EdgeAndPolygonContactHandle): Single; cdecl; external LIB_NAME name _PU + 'b2EdgeAndPolygonContact_GetFriction'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2EdgeAndPolygonContactWrapper.GetFriction: Single; cdecl;
begin
Result := b2EdgeAndPolygonContact_GetFriction(FHandle)
end;
procedure b2EdgeAndPolygonContact_ResetFriction(_self: b2EdgeAndPolygonContactHandle); cdecl; external LIB_NAME name _PU + 'b2EdgeAndPolygonContact_ResetFriction'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2EdgeAndPolygonContactWrapper.ResetFriction; cdecl;
begin
b2EdgeAndPolygonContact_ResetFriction(FHandle)
end;
procedure b2EdgeAndPolygonContact_SetRestitution(_self: b2EdgeAndPolygonContactHandle; restitution: Single); cdecl; external LIB_NAME name _PU + 'b2EdgeAndPolygonContact_SetRestitution'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2EdgeAndPolygonContactWrapper.SetRestitution(restitution: Single); cdecl;
begin
b2EdgeAndPolygonContact_SetRestitution(FHandle, restitution)
end;
function b2EdgeAndPolygonContact_GetRestitution(_self: b2EdgeAndPolygonContactHandle): Single; cdecl; external LIB_NAME name _PU + 'b2EdgeAndPolygonContact_GetRestitution'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2EdgeAndPolygonContactWrapper.GetRestitution: Single; cdecl;
begin
Result := b2EdgeAndPolygonContact_GetRestitution(FHandle)
end;
procedure b2EdgeAndPolygonContact_ResetRestitution(_self: b2EdgeAndPolygonContactHandle); cdecl; external LIB_NAME name _PU + 'b2EdgeAndPolygonContact_ResetRestitution'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2EdgeAndPolygonContactWrapper.ResetRestitution; cdecl;
begin
b2EdgeAndPolygonContact_ResetRestitution(FHandle)
end;
procedure b2EdgeAndPolygonContact_SetTangentSpeed(_self: b2EdgeAndPolygonContactHandle; speed: Single); cdecl; external LIB_NAME name _PU + 'b2EdgeAndPolygonContact_SetTangentSpeed'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2EdgeAndPolygonContactWrapper.SetTangentSpeed(speed: Single); cdecl;
begin
b2EdgeAndPolygonContact_SetTangentSpeed(FHandle, speed)
end;
function b2EdgeAndPolygonContact_GetTangentSpeed(_self: b2EdgeAndPolygonContactHandle): Single; cdecl; external LIB_NAME name _PU + 'b2EdgeAndPolygonContact_GetTangentSpeed'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2EdgeAndPolygonContactWrapper.GetTangentSpeed: Single; cdecl;
begin
Result := b2EdgeAndPolygonContact_GetTangentSpeed(FHandle)
end;
procedure b2EdgeAndPolygonContact_Evaluate(_self: b2EdgeAndPolygonContactHandle; manifold: Pb2Manifold; const [ref] xfA: b2Transform; const [ref] xfB: b2Transform); cdecl; external LIB_NAME name _PU + 'b2EdgeAndPolygonContact_Evaluate'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2EdgeAndPolygonContactWrapper.Evaluate(manifold: Pb2Manifold; const [ref] xfA: b2Transform; const [ref] xfB: b2Transform); cdecl;
begin
b2EdgeAndPolygonContact_Evaluate(FHandle, manifold, xfA, xfB)
end;
function b2EdgeAndPolygonContact_Create_(_self: b2EdgeAndPolygonContactHandle; fixtureA: Pb2Fixture; indexA: Integer; fixtureB: Pb2Fixture; indexB: Integer; allocator: b2BlockAllocatorHandle): b2ContactHandle; cdecl; external LIB_NAME name _PU + 'b2EdgeAndPolygonContact_Create'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2EdgeAndPolygonContactWrapper.Create_(fixtureA: Pb2Fixture; indexA: Integer; fixtureB: Pb2Fixture; indexB: Integer; allocator: b2BlockAllocatorHandle): b2ContactHandle; cdecl;
begin
Result := b2EdgeAndPolygonContact_Create_(FHandle, fixtureA, indexA, fixtureB, indexB, allocator)
end;
procedure b2EdgeAndPolygonContact_Destroy_(_self: b2EdgeAndPolygonContactHandle; contact: b2ContactHandle; allocator: b2BlockAllocatorHandle); cdecl; external LIB_NAME name _PU + 'b2EdgeAndPolygonContact_Destroy'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2EdgeAndPolygonContactWrapper.Destroy_(contact: b2ContactHandle; allocator: b2BlockAllocatorHandle); cdecl;
begin
b2EdgeAndPolygonContact_Destroy_(FHandle, contact, allocator)
end;
function b2PolygonAndCircleContact_Create(fixtureA: Pb2Fixture; fixtureB: Pb2Fixture): b2PolygonAndCircleContactHandle; cdecl; external LIB_NAME name _PU + 'b2PolygonAndCircleContact_b2PolygonAndCircleContact_1'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2PolygonAndCircleContactWrapper.Create(fixtureA: Pb2Fixture; fixtureB: Pb2Fixture): b2PolygonAndCircleContactWrapper; cdecl;
begin
Result.FHandle := b2PolygonAndCircleContact_Create(fixtureA, fixtureB);
end;
procedure b2PolygonAndCircleContact_Destroy(_self: b2PolygonAndCircleContactHandle); cdecl; external LIB_NAME name _PU + 'b2PolygonAndCircleContact_dtor'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PolygonAndCircleContactWrapper.Destroy; cdecl;
begin
b2PolygonAndCircleContact_Destroy(FHandle);
end;
class operator b2PolygonAndCircleContactWrapper.Implicit(handle: b2PolygonAndCircleContactHandle): b2PolygonAndCircleContactWrapper;
begin
Result.FHandle := handle;
end;
class operator b2PolygonAndCircleContactWrapper.Implicit(wrapper: b2PolygonAndCircleContactWrapper): b2PolygonAndCircleContactHandle;
begin
Result := wrapper.FHandle;
end;
function b2PolygonAndCircleContact_GetManifold(_self: b2PolygonAndCircleContactHandle): Pb2Manifold; cdecl; external LIB_NAME name _PU + 'b2PolygonAndCircleContact_GetManifold'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PolygonAndCircleContactWrapper.GetManifold: Pb2Manifold; cdecl;
begin
Result := b2PolygonAndCircleContact_GetManifold(FHandle)
end;
procedure b2PolygonAndCircleContact_GetWorldManifold(_self: b2PolygonAndCircleContactHandle; worldManifold: Pb2WorldManifold); cdecl; external LIB_NAME name _PU + 'b2PolygonAndCircleContact_GetWorldManifold'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PolygonAndCircleContactWrapper.GetWorldManifold(worldManifold: Pb2WorldManifold); cdecl;
begin
b2PolygonAndCircleContact_GetWorldManifold(FHandle, worldManifold)
end;
function b2PolygonAndCircleContact_IsTouching(_self: b2PolygonAndCircleContactHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2PolygonAndCircleContact_IsTouching'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PolygonAndCircleContactWrapper.IsTouching: Boolean; cdecl;
begin
Result := b2PolygonAndCircleContact_IsTouching(FHandle)
end;
procedure b2PolygonAndCircleContact_SetEnabled(_self: b2PolygonAndCircleContactHandle; flag: Boolean); cdecl; external LIB_NAME name _PU + 'b2PolygonAndCircleContact_SetEnabled'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PolygonAndCircleContactWrapper.SetEnabled(flag: Boolean); cdecl;
begin
b2PolygonAndCircleContact_SetEnabled(FHandle, flag)
end;
function b2PolygonAndCircleContact_IsEnabled(_self: b2PolygonAndCircleContactHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2PolygonAndCircleContact_IsEnabled'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PolygonAndCircleContactWrapper.IsEnabled: Boolean; cdecl;
begin
Result := b2PolygonAndCircleContact_IsEnabled(FHandle)
end;
function b2PolygonAndCircleContact_GetNext(_self: b2PolygonAndCircleContactHandle): b2ContactHandle; cdecl; external LIB_NAME name _PU + 'b2PolygonAndCircleContact_GetNext'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PolygonAndCircleContactWrapper.GetNext: b2ContactHandle; cdecl;
begin
Result := b2PolygonAndCircleContact_GetNext(FHandle)
end;
function b2PolygonAndCircleContact_GetFixtureA(_self: b2PolygonAndCircleContactHandle): Pb2Fixture; cdecl; external LIB_NAME name _PU + 'b2PolygonAndCircleContact_GetFixtureA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PolygonAndCircleContactWrapper.GetFixtureA: Pb2Fixture; cdecl;
begin
Result := b2PolygonAndCircleContact_GetFixtureA(FHandle)
end;
function b2PolygonAndCircleContact_GetChildIndexA(_self: b2PolygonAndCircleContactHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2PolygonAndCircleContact_GetChildIndexA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PolygonAndCircleContactWrapper.GetChildIndexA: Integer; cdecl;
begin
Result := b2PolygonAndCircleContact_GetChildIndexA(FHandle)
end;
function b2PolygonAndCircleContact_GetFixtureB(_self: b2PolygonAndCircleContactHandle): Pb2Fixture; cdecl; external LIB_NAME name _PU + 'b2PolygonAndCircleContact_GetFixtureB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PolygonAndCircleContactWrapper.GetFixtureB: Pb2Fixture; cdecl;
begin
Result := b2PolygonAndCircleContact_GetFixtureB(FHandle)
end;
function b2PolygonAndCircleContact_GetChildIndexB(_self: b2PolygonAndCircleContactHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2PolygonAndCircleContact_GetChildIndexB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PolygonAndCircleContactWrapper.GetChildIndexB: Integer; cdecl;
begin
Result := b2PolygonAndCircleContact_GetChildIndexB(FHandle)
end;
procedure b2PolygonAndCircleContact_SetFriction(_self: b2PolygonAndCircleContactHandle; friction: Single); cdecl; external LIB_NAME name _PU + 'b2PolygonAndCircleContact_SetFriction'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PolygonAndCircleContactWrapper.SetFriction(friction: Single); cdecl;
begin
b2PolygonAndCircleContact_SetFriction(FHandle, friction)
end;
function b2PolygonAndCircleContact_GetFriction(_self: b2PolygonAndCircleContactHandle): Single; cdecl; external LIB_NAME name _PU + 'b2PolygonAndCircleContact_GetFriction'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PolygonAndCircleContactWrapper.GetFriction: Single; cdecl;
begin
Result := b2PolygonAndCircleContact_GetFriction(FHandle)
end;
procedure b2PolygonAndCircleContact_ResetFriction(_self: b2PolygonAndCircleContactHandle); cdecl; external LIB_NAME name _PU + 'b2PolygonAndCircleContact_ResetFriction'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PolygonAndCircleContactWrapper.ResetFriction; cdecl;
begin
b2PolygonAndCircleContact_ResetFriction(FHandle)
end;
procedure b2PolygonAndCircleContact_SetRestitution(_self: b2PolygonAndCircleContactHandle; restitution: Single); cdecl; external LIB_NAME name _PU + 'b2PolygonAndCircleContact_SetRestitution'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PolygonAndCircleContactWrapper.SetRestitution(restitution: Single); cdecl;
begin
b2PolygonAndCircleContact_SetRestitution(FHandle, restitution)
end;
function b2PolygonAndCircleContact_GetRestitution(_self: b2PolygonAndCircleContactHandle): Single; cdecl; external LIB_NAME name _PU + 'b2PolygonAndCircleContact_GetRestitution'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PolygonAndCircleContactWrapper.GetRestitution: Single; cdecl;
begin
Result := b2PolygonAndCircleContact_GetRestitution(FHandle)
end;
procedure b2PolygonAndCircleContact_ResetRestitution(_self: b2PolygonAndCircleContactHandle); cdecl; external LIB_NAME name _PU + 'b2PolygonAndCircleContact_ResetRestitution'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PolygonAndCircleContactWrapper.ResetRestitution; cdecl;
begin
b2PolygonAndCircleContact_ResetRestitution(FHandle)
end;
procedure b2PolygonAndCircleContact_SetTangentSpeed(_self: b2PolygonAndCircleContactHandle; speed: Single); cdecl; external LIB_NAME name _PU + 'b2PolygonAndCircleContact_SetTangentSpeed'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PolygonAndCircleContactWrapper.SetTangentSpeed(speed: Single); cdecl;
begin
b2PolygonAndCircleContact_SetTangentSpeed(FHandle, speed)
end;
function b2PolygonAndCircleContact_GetTangentSpeed(_self: b2PolygonAndCircleContactHandle): Single; cdecl; external LIB_NAME name _PU + 'b2PolygonAndCircleContact_GetTangentSpeed'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PolygonAndCircleContactWrapper.GetTangentSpeed: Single; cdecl;
begin
Result := b2PolygonAndCircleContact_GetTangentSpeed(FHandle)
end;
procedure b2PolygonAndCircleContact_Evaluate(_self: b2PolygonAndCircleContactHandle; manifold: Pb2Manifold; const [ref] xfA: b2Transform; const [ref] xfB: b2Transform); cdecl; external LIB_NAME name _PU + 'b2PolygonAndCircleContact_Evaluate'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PolygonAndCircleContactWrapper.Evaluate(manifold: Pb2Manifold; const [ref] xfA: b2Transform; const [ref] xfB: b2Transform); cdecl;
begin
b2PolygonAndCircleContact_Evaluate(FHandle, manifold, xfA, xfB)
end;
function b2PolygonAndCircleContact_Create_(_self: b2PolygonAndCircleContactHandle; fixtureA: Pb2Fixture; indexA: Integer; fixtureB: Pb2Fixture; indexB: Integer; allocator: b2BlockAllocatorHandle): b2ContactHandle; cdecl; external LIB_NAME name _PU + 'b2PolygonAndCircleContact_Create'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PolygonAndCircleContactWrapper.Create_(fixtureA: Pb2Fixture; indexA: Integer; fixtureB: Pb2Fixture; indexB: Integer; allocator: b2BlockAllocatorHandle): b2ContactHandle; cdecl;
begin
Result := b2PolygonAndCircleContact_Create_(FHandle, fixtureA, indexA, fixtureB, indexB, allocator)
end;
procedure b2PolygonAndCircleContact_Destroy_(_self: b2PolygonAndCircleContactHandle; contact: b2ContactHandle; allocator: b2BlockAllocatorHandle); cdecl; external LIB_NAME name _PU + 'b2PolygonAndCircleContact_Destroy'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PolygonAndCircleContactWrapper.Destroy_(contact: b2ContactHandle; allocator: b2BlockAllocatorHandle); cdecl;
begin
b2PolygonAndCircleContact_Destroy_(FHandle, contact, allocator)
end;
function b2PolygonContact_Create(fixtureA: Pb2Fixture; fixtureB: Pb2Fixture): b2PolygonContactHandle; cdecl; external LIB_NAME name _PU + 'b2PolygonContact_b2PolygonContact_1'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2PolygonContactWrapper.Create(fixtureA: Pb2Fixture; fixtureB: Pb2Fixture): b2PolygonContactWrapper; cdecl;
begin
Result.FHandle := b2PolygonContact_Create(fixtureA, fixtureB);
end;
procedure b2PolygonContact_Destroy(_self: b2PolygonContactHandle); cdecl; external LIB_NAME name _PU + 'b2PolygonContact_dtor'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PolygonContactWrapper.Destroy; cdecl;
begin
b2PolygonContact_Destroy(FHandle);
end;
class operator b2PolygonContactWrapper.Implicit(handle: b2PolygonContactHandle): b2PolygonContactWrapper;
begin
Result.FHandle := handle;
end;
class operator b2PolygonContactWrapper.Implicit(wrapper: b2PolygonContactWrapper): b2PolygonContactHandle;
begin
Result := wrapper.FHandle;
end;
function b2PolygonContact_GetManifold(_self: b2PolygonContactHandle): Pb2Manifold; cdecl; external LIB_NAME name _PU + 'b2PolygonContact_GetManifold'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PolygonContactWrapper.GetManifold: Pb2Manifold; cdecl;
begin
Result := b2PolygonContact_GetManifold(FHandle)
end;
procedure b2PolygonContact_GetWorldManifold(_self: b2PolygonContactHandle; worldManifold: Pb2WorldManifold); cdecl; external LIB_NAME name _PU + 'b2PolygonContact_GetWorldManifold'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PolygonContactWrapper.GetWorldManifold(worldManifold: Pb2WorldManifold); cdecl;
begin
b2PolygonContact_GetWorldManifold(FHandle, worldManifold)
end;
function b2PolygonContact_IsTouching(_self: b2PolygonContactHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2PolygonContact_IsTouching'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PolygonContactWrapper.IsTouching: Boolean; cdecl;
begin
Result := b2PolygonContact_IsTouching(FHandle)
end;
procedure b2PolygonContact_SetEnabled(_self: b2PolygonContactHandle; flag: Boolean); cdecl; external LIB_NAME name _PU + 'b2PolygonContact_SetEnabled'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PolygonContactWrapper.SetEnabled(flag: Boolean); cdecl;
begin
b2PolygonContact_SetEnabled(FHandle, flag)
end;
function b2PolygonContact_IsEnabled(_self: b2PolygonContactHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2PolygonContact_IsEnabled'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PolygonContactWrapper.IsEnabled: Boolean; cdecl;
begin
Result := b2PolygonContact_IsEnabled(FHandle)
end;
function b2PolygonContact_GetNext(_self: b2PolygonContactHandle): b2ContactHandle; cdecl; external LIB_NAME name _PU + 'b2PolygonContact_GetNext'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PolygonContactWrapper.GetNext: b2ContactHandle; cdecl;
begin
Result := b2PolygonContact_GetNext(FHandle)
end;
function b2PolygonContact_GetFixtureA(_self: b2PolygonContactHandle): Pb2Fixture; cdecl; external LIB_NAME name _PU + 'b2PolygonContact_GetFixtureA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PolygonContactWrapper.GetFixtureA: Pb2Fixture; cdecl;
begin
Result := b2PolygonContact_GetFixtureA(FHandle)
end;
function b2PolygonContact_GetChildIndexA(_self: b2PolygonContactHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2PolygonContact_GetChildIndexA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PolygonContactWrapper.GetChildIndexA: Integer; cdecl;
begin
Result := b2PolygonContact_GetChildIndexA(FHandle)
end;
function b2PolygonContact_GetFixtureB(_self: b2PolygonContactHandle): Pb2Fixture; cdecl; external LIB_NAME name _PU + 'b2PolygonContact_GetFixtureB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PolygonContactWrapper.GetFixtureB: Pb2Fixture; cdecl;
begin
Result := b2PolygonContact_GetFixtureB(FHandle)
end;
function b2PolygonContact_GetChildIndexB(_self: b2PolygonContactHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2PolygonContact_GetChildIndexB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PolygonContactWrapper.GetChildIndexB: Integer; cdecl;
begin
Result := b2PolygonContact_GetChildIndexB(FHandle)
end;
procedure b2PolygonContact_SetFriction(_self: b2PolygonContactHandle; friction: Single); cdecl; external LIB_NAME name _PU + 'b2PolygonContact_SetFriction'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PolygonContactWrapper.SetFriction(friction: Single); cdecl;
begin
b2PolygonContact_SetFriction(FHandle, friction)
end;
function b2PolygonContact_GetFriction(_self: b2PolygonContactHandle): Single; cdecl; external LIB_NAME name _PU + 'b2PolygonContact_GetFriction'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PolygonContactWrapper.GetFriction: Single; cdecl;
begin
Result := b2PolygonContact_GetFriction(FHandle)
end;
procedure b2PolygonContact_ResetFriction(_self: b2PolygonContactHandle); cdecl; external LIB_NAME name _PU + 'b2PolygonContact_ResetFriction'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PolygonContactWrapper.ResetFriction; cdecl;
begin
b2PolygonContact_ResetFriction(FHandle)
end;
procedure b2PolygonContact_SetRestitution(_self: b2PolygonContactHandle; restitution: Single); cdecl; external LIB_NAME name _PU + 'b2PolygonContact_SetRestitution'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PolygonContactWrapper.SetRestitution(restitution: Single); cdecl;
begin
b2PolygonContact_SetRestitution(FHandle, restitution)
end;
function b2PolygonContact_GetRestitution(_self: b2PolygonContactHandle): Single; cdecl; external LIB_NAME name _PU + 'b2PolygonContact_GetRestitution'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PolygonContactWrapper.GetRestitution: Single; cdecl;
begin
Result := b2PolygonContact_GetRestitution(FHandle)
end;
procedure b2PolygonContact_ResetRestitution(_self: b2PolygonContactHandle); cdecl; external LIB_NAME name _PU + 'b2PolygonContact_ResetRestitution'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PolygonContactWrapper.ResetRestitution; cdecl;
begin
b2PolygonContact_ResetRestitution(FHandle)
end;
procedure b2PolygonContact_SetTangentSpeed(_self: b2PolygonContactHandle; speed: Single); cdecl; external LIB_NAME name _PU + 'b2PolygonContact_SetTangentSpeed'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PolygonContactWrapper.SetTangentSpeed(speed: Single); cdecl;
begin
b2PolygonContact_SetTangentSpeed(FHandle, speed)
end;
function b2PolygonContact_GetTangentSpeed(_self: b2PolygonContactHandle): Single; cdecl; external LIB_NAME name _PU + 'b2PolygonContact_GetTangentSpeed'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PolygonContactWrapper.GetTangentSpeed: Single; cdecl;
begin
Result := b2PolygonContact_GetTangentSpeed(FHandle)
end;
procedure b2PolygonContact_Evaluate(_self: b2PolygonContactHandle; manifold: Pb2Manifold; const [ref] xfA: b2Transform; const [ref] xfB: b2Transform); cdecl; external LIB_NAME name _PU + 'b2PolygonContact_Evaluate'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PolygonContactWrapper.Evaluate(manifold: Pb2Manifold; const [ref] xfA: b2Transform; const [ref] xfB: b2Transform); cdecl;
begin
b2PolygonContact_Evaluate(FHandle, manifold, xfA, xfB)
end;
function b2PolygonContact_Create_(_self: b2PolygonContactHandle; fixtureA: Pb2Fixture; indexA: Integer; fixtureB: Pb2Fixture; indexB: Integer; allocator: b2BlockAllocatorHandle): b2ContactHandle; cdecl; external LIB_NAME name _PU + 'b2PolygonContact_Create'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PolygonContactWrapper.Create_(fixtureA: Pb2Fixture; indexA: Integer; fixtureB: Pb2Fixture; indexB: Integer; allocator: b2BlockAllocatorHandle): b2ContactHandle; cdecl;
begin
Result := b2PolygonContact_Create_(FHandle, fixtureA, indexA, fixtureB, indexB, allocator)
end;
procedure b2PolygonContact_Destroy_(_self: b2PolygonContactHandle; contact: b2ContactHandle; allocator: b2BlockAllocatorHandle); cdecl; external LIB_NAME name _PU + 'b2PolygonContact_Destroy'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PolygonContactWrapper.Destroy_(contact: b2ContactHandle; allocator: b2BlockAllocatorHandle); cdecl;
begin
b2PolygonContact_Destroy_(FHandle, contact, allocator)
end;
function b2Jacobian_Create: b2Jacobian; cdecl; external LIB_NAME name _PU + 'b2Jacobian_b2Jacobian'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2Jacobian.Create: b2Jacobian; cdecl;
begin
Result := b2Jacobian_Create;
end;
function b2JointEdge_Create: b2JointEdge; cdecl; external LIB_NAME name _PU + 'b2JointEdge_b2JointEdge'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2JointEdge.Create: b2JointEdge; cdecl;
begin
Result := b2JointEdge_Create;
end;
function b2JointDef_Create: b2JointDef; cdecl; external LIB_NAME name _PU + 'b2JointDef_b2JointDef_1'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2JointDef.Create: b2JointDef; cdecl;
begin
Result := b2JointDef_Create;
end;
class operator b2JointWrapper.Implicit(handle: b2JointHandle): b2JointWrapper;
begin
Result.FHandle := handle;
end;
class operator b2JointWrapper.Implicit(wrapper: b2JointWrapper): b2JointHandle;
begin
Result := wrapper.FHandle;
end;
function b2Joint_GetType(_self: b2JointHandle): b2JointType; cdecl; external LIB_NAME name _PU + 'b2Joint_GetType'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2JointWrapper.GetType: b2JointType; cdecl;
begin
Result := b2Joint_GetType(FHandle)
end;
function b2Joint_GetBodyA(_self: b2JointHandle): b2BodyHandle; cdecl; external LIB_NAME name _PU + 'b2Joint_GetBodyA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2JointWrapper.GetBodyA: b2BodyHandle; cdecl;
begin
Result := b2Joint_GetBodyA(FHandle)
end;
function b2Joint_GetBodyB(_self: b2JointHandle): b2BodyHandle; cdecl; external LIB_NAME name _PU + 'b2Joint_GetBodyB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2JointWrapper.GetBodyB: b2BodyHandle; cdecl;
begin
Result := b2Joint_GetBodyB(FHandle)
end;
function b2Joint_GetAnchorA(_self: b2JointHandle): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2Joint_GetAnchorA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2JointWrapper.GetAnchorA: b2Vec2; cdecl;
begin
Result := b2Joint_GetAnchorA(FHandle)
end;
function b2Joint_GetAnchorB(_self: b2JointHandle): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2Joint_GetAnchorB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2JointWrapper.GetAnchorB: b2Vec2; cdecl;
begin
Result := b2Joint_GetAnchorB(FHandle)
end;
function b2Joint_GetReactionForce(_self: b2JointHandle; inv_dt: Single): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2Joint_GetReactionForce'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2JointWrapper.GetReactionForce(inv_dt: Single): b2Vec2; cdecl;
begin
Result := b2Joint_GetReactionForce(FHandle, inv_dt)
end;
function b2Joint_GetReactionTorque(_self: b2JointHandle; inv_dt: Single): Single; cdecl; external LIB_NAME name _PU + 'b2Joint_GetReactionTorque'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2JointWrapper.GetReactionTorque(inv_dt: Single): Single; cdecl;
begin
Result := b2Joint_GetReactionTorque(FHandle, inv_dt)
end;
function b2Joint_GetNext(_self: b2JointHandle): b2JointHandle; cdecl; external LIB_NAME name _PU + 'b2Joint_GetNext'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2JointWrapper.GetNext: b2JointHandle; cdecl;
begin
Result := b2Joint_GetNext(FHandle)
end;
function b2Joint_GetUserData(_self: b2JointHandle): Pointer; cdecl; external LIB_NAME name _PU + 'b2Joint_GetUserData'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2JointWrapper.GetUserData: Pointer; cdecl;
begin
Result := b2Joint_GetUserData(FHandle)
end;
procedure b2Joint_SetUserData(_self: b2JointHandle; data: Pointer); cdecl; external LIB_NAME name _PU + 'b2Joint_SetUserData'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2JointWrapper.SetUserData(data: Pointer); cdecl;
begin
b2Joint_SetUserData(FHandle, data)
end;
function b2Joint_IsActive(_self: b2JointHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2Joint_IsActive'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2JointWrapper.IsActive: Boolean; cdecl;
begin
Result := b2Joint_IsActive(FHandle)
end;
function b2Joint_GetCollideConnected(_self: b2JointHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2Joint_GetCollideConnected'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2JointWrapper.GetCollideConnected: Boolean; cdecl;
begin
Result := b2Joint_GetCollideConnected(FHandle)
end;
procedure b2Joint_Dump(_self: b2JointHandle); cdecl; external LIB_NAME name _PU + 'b2Joint_Dump'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2JointWrapper.Dump; cdecl;
begin
b2Joint_Dump(FHandle)
end;
procedure b2Joint_ShiftOrigin(_self: b2JointHandle; const [ref] newOrigin: b2Vec2); cdecl; external LIB_NAME name _PU + 'b2Joint_ShiftOrigin'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2JointWrapper.ShiftOrigin(const [ref] newOrigin: b2Vec2); cdecl;
begin
b2Joint_ShiftOrigin(FHandle, newOrigin)
end;
function b2DistanceJointDef_Create: b2DistanceJointDef; cdecl; external LIB_NAME name _PU + 'b2DistanceJointDef_b2DistanceJointDef_1'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2DistanceJointDef.Create: b2DistanceJointDef; cdecl;
begin
Result := b2DistanceJointDef_Create;
end;
procedure b2DistanceJointDef_Initialize(_self: Pb2DistanceJointDef; bodyA: b2BodyHandle; bodyB: b2BodyHandle; const [ref] anchorA: b2Vec2; const [ref] anchorB: b2Vec2); cdecl; external LIB_NAME name _PU + 'b2DistanceJointDef_Initialize'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2DistanceJointDef.Initialize(bodyA: b2BodyHandle; bodyB: b2BodyHandle; const [ref] anchorA: b2Vec2; const [ref] anchorB: b2Vec2); cdecl;
begin
b2DistanceJointDef_Initialize(@Self, bodyA, bodyB, anchorA, anchorB)
end;
procedure b2DistanceJoint_Destroy(_self: b2DistanceJointHandle); cdecl; external LIB_NAME name _PU + 'b2DistanceJoint_dtor'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2DistanceJointWrapper.Destroy; cdecl;
begin
b2DistanceJoint_Destroy(FHandle);
end;
class operator b2DistanceJointWrapper.Implicit(handle: b2DistanceJointHandle): b2DistanceJointWrapper;
begin
Result.FHandle := handle;
end;
class operator b2DistanceJointWrapper.Implicit(wrapper: b2DistanceJointWrapper): b2DistanceJointHandle;
begin
Result := wrapper.FHandle;
end;
function b2DistanceJoint_GetType(_self: b2DistanceJointHandle): b2JointType; cdecl; external LIB_NAME name _PU + 'b2DistanceJoint_GetType'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2DistanceJointWrapper.GetType: b2JointType; cdecl;
begin
Result := b2DistanceJoint_GetType(FHandle)
end;
function b2DistanceJoint_GetBodyA(_self: b2DistanceJointHandle): b2BodyHandle; cdecl; external LIB_NAME name _PU + 'b2DistanceJoint_GetBodyA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2DistanceJointWrapper.GetBodyA: b2BodyHandle; cdecl;
begin
Result := b2DistanceJoint_GetBodyA(FHandle)
end;
function b2DistanceJoint_GetBodyB(_self: b2DistanceJointHandle): b2BodyHandle; cdecl; external LIB_NAME name _PU + 'b2DistanceJoint_GetBodyB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2DistanceJointWrapper.GetBodyB: b2BodyHandle; cdecl;
begin
Result := b2DistanceJoint_GetBodyB(FHandle)
end;
function b2DistanceJoint_GetAnchorA(_self: b2DistanceJointHandle): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2DistanceJoint_GetAnchorA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2DistanceJointWrapper.GetAnchorA: b2Vec2; cdecl;
begin
Result := b2DistanceJoint_GetAnchorA(FHandle)
end;
function b2DistanceJoint_GetAnchorB(_self: b2DistanceJointHandle): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2DistanceJoint_GetAnchorB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2DistanceJointWrapper.GetAnchorB: b2Vec2; cdecl;
begin
Result := b2DistanceJoint_GetAnchorB(FHandle)
end;
function b2DistanceJoint_GetReactionForce(_self: b2DistanceJointHandle; inv_dt: Single): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2DistanceJoint_GetReactionForce'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2DistanceJointWrapper.GetReactionForce(inv_dt: Single): b2Vec2; cdecl;
begin
Result := b2DistanceJoint_GetReactionForce(FHandle, inv_dt)
end;
function b2DistanceJoint_GetReactionTorque(_self: b2DistanceJointHandle; inv_dt: Single): Single; cdecl; external LIB_NAME name _PU + 'b2DistanceJoint_GetReactionTorque'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2DistanceJointWrapper.GetReactionTorque(inv_dt: Single): Single; cdecl;
begin
Result := b2DistanceJoint_GetReactionTorque(FHandle, inv_dt)
end;
function b2DistanceJoint_GetNext(_self: b2DistanceJointHandle): b2JointHandle; cdecl; external LIB_NAME name _PU + 'b2DistanceJoint_GetNext'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2DistanceJointWrapper.GetNext: b2JointHandle; cdecl;
begin
Result := b2DistanceJoint_GetNext(FHandle)
end;
function b2DistanceJoint_GetUserData(_self: b2DistanceJointHandle): Pointer; cdecl; external LIB_NAME name _PU + 'b2DistanceJoint_GetUserData'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2DistanceJointWrapper.GetUserData: Pointer; cdecl;
begin
Result := b2DistanceJoint_GetUserData(FHandle)
end;
procedure b2DistanceJoint_SetUserData(_self: b2DistanceJointHandle; data: Pointer); cdecl; external LIB_NAME name _PU + 'b2DistanceJoint_SetUserData'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2DistanceJointWrapper.SetUserData(data: Pointer); cdecl;
begin
b2DistanceJoint_SetUserData(FHandle, data)
end;
function b2DistanceJoint_IsActive(_self: b2DistanceJointHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2DistanceJoint_IsActive'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2DistanceJointWrapper.IsActive: Boolean; cdecl;
begin
Result := b2DistanceJoint_IsActive(FHandle)
end;
function b2DistanceJoint_GetCollideConnected(_self: b2DistanceJointHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2DistanceJoint_GetCollideConnected'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2DistanceJointWrapper.GetCollideConnected: Boolean; cdecl;
begin
Result := b2DistanceJoint_GetCollideConnected(FHandle)
end;
procedure b2DistanceJoint_Dump(_self: b2DistanceJointHandle); cdecl; external LIB_NAME name _PU + 'b2DistanceJoint_Dump'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2DistanceJointWrapper.Dump; cdecl;
begin
b2DistanceJoint_Dump(FHandle)
end;
procedure b2DistanceJoint_ShiftOrigin(_self: b2DistanceJointHandle; const [ref] newOrigin: b2Vec2); cdecl; external LIB_NAME name _PU + 'b2DistanceJoint_ShiftOrigin'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2DistanceJointWrapper.ShiftOrigin(const [ref] newOrigin: b2Vec2); cdecl;
begin
b2DistanceJoint_ShiftOrigin(FHandle, newOrigin)
end;
function b2DistanceJoint_GetLocalAnchorA(_self: b2DistanceJointHandle): Pb2Vec2; cdecl; external LIB_NAME name _PU + 'b2DistanceJoint_GetLocalAnchorA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2DistanceJointWrapper.GetLocalAnchorA: Pb2Vec2; cdecl;
begin
Result := b2DistanceJoint_GetLocalAnchorA(FHandle)
end;
function b2DistanceJoint_GetLocalAnchorB(_self: b2DistanceJointHandle): Pb2Vec2; cdecl; external LIB_NAME name _PU + 'b2DistanceJoint_GetLocalAnchorB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2DistanceJointWrapper.GetLocalAnchorB: Pb2Vec2; cdecl;
begin
Result := b2DistanceJoint_GetLocalAnchorB(FHandle)
end;
procedure b2DistanceJoint_SetLength(_self: b2DistanceJointHandle; length: Single); cdecl; external LIB_NAME name _PU + 'b2DistanceJoint_SetLength'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2DistanceJointWrapper.SetLength(length: Single); cdecl;
begin
b2DistanceJoint_SetLength(FHandle, length)
end;
function b2DistanceJoint_GetLength(_self: b2DistanceJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2DistanceJoint_GetLength'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2DistanceJointWrapper.GetLength: Single; cdecl;
begin
Result := b2DistanceJoint_GetLength(FHandle)
end;
procedure b2DistanceJoint_SetFrequency(_self: b2DistanceJointHandle; hz: Single); cdecl; external LIB_NAME name _PU + 'b2DistanceJoint_SetFrequency'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2DistanceJointWrapper.SetFrequency(hz: Single); cdecl;
begin
b2DistanceJoint_SetFrequency(FHandle, hz)
end;
function b2DistanceJoint_GetFrequency(_self: b2DistanceJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2DistanceJoint_GetFrequency'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2DistanceJointWrapper.GetFrequency: Single; cdecl;
begin
Result := b2DistanceJoint_GetFrequency(FHandle)
end;
procedure b2DistanceJoint_SetDampingRatio(_self: b2DistanceJointHandle; ratio: Single); cdecl; external LIB_NAME name _PU + 'b2DistanceJoint_SetDampingRatio'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2DistanceJointWrapper.SetDampingRatio(ratio: Single); cdecl;
begin
b2DistanceJoint_SetDampingRatio(FHandle, ratio)
end;
function b2DistanceJoint_GetDampingRatio(_self: b2DistanceJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2DistanceJoint_GetDampingRatio'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2DistanceJointWrapper.GetDampingRatio: Single; cdecl;
begin
Result := b2DistanceJoint_GetDampingRatio(FHandle)
end;
function b2FrictionJointDef_Create: b2FrictionJointDef; cdecl; external LIB_NAME name _PU + 'b2FrictionJointDef_b2FrictionJointDef_1'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2FrictionJointDef.Create: b2FrictionJointDef; cdecl;
begin
Result := b2FrictionJointDef_Create;
end;
procedure b2FrictionJointDef_Initialize(_self: Pb2FrictionJointDef; bodyA: b2BodyHandle; bodyB: b2BodyHandle; const [ref] anchor: b2Vec2); cdecl; external LIB_NAME name _PU + 'b2FrictionJointDef_Initialize'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2FrictionJointDef.Initialize(bodyA: b2BodyHandle; bodyB: b2BodyHandle; const [ref] anchor: b2Vec2); cdecl;
begin
b2FrictionJointDef_Initialize(@Self, bodyA, bodyB, anchor)
end;
procedure b2FrictionJoint_Destroy(_self: b2FrictionJointHandle); cdecl; external LIB_NAME name _PU + 'b2FrictionJoint_dtor'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2FrictionJointWrapper.Destroy; cdecl;
begin
b2FrictionJoint_Destroy(FHandle);
end;
class operator b2FrictionJointWrapper.Implicit(handle: b2FrictionJointHandle): b2FrictionJointWrapper;
begin
Result.FHandle := handle;
end;
class operator b2FrictionJointWrapper.Implicit(wrapper: b2FrictionJointWrapper): b2FrictionJointHandle;
begin
Result := wrapper.FHandle;
end;
function b2FrictionJoint_GetType(_self: b2FrictionJointHandle): b2JointType; cdecl; external LIB_NAME name _PU + 'b2FrictionJoint_GetType'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2FrictionJointWrapper.GetType: b2JointType; cdecl;
begin
Result := b2FrictionJoint_GetType(FHandle)
end;
function b2FrictionJoint_GetBodyA(_self: b2FrictionJointHandle): b2BodyHandle; cdecl; external LIB_NAME name _PU + 'b2FrictionJoint_GetBodyA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2FrictionJointWrapper.GetBodyA: b2BodyHandle; cdecl;
begin
Result := b2FrictionJoint_GetBodyA(FHandle)
end;
function b2FrictionJoint_GetBodyB(_self: b2FrictionJointHandle): b2BodyHandle; cdecl; external LIB_NAME name _PU + 'b2FrictionJoint_GetBodyB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2FrictionJointWrapper.GetBodyB: b2BodyHandle; cdecl;
begin
Result := b2FrictionJoint_GetBodyB(FHandle)
end;
function b2FrictionJoint_GetAnchorA(_self: b2FrictionJointHandle): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2FrictionJoint_GetAnchorA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2FrictionJointWrapper.GetAnchorA: b2Vec2; cdecl;
begin
Result := b2FrictionJoint_GetAnchorA(FHandle)
end;
function b2FrictionJoint_GetAnchorB(_self: b2FrictionJointHandle): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2FrictionJoint_GetAnchorB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2FrictionJointWrapper.GetAnchorB: b2Vec2; cdecl;
begin
Result := b2FrictionJoint_GetAnchorB(FHandle)
end;
function b2FrictionJoint_GetReactionForce(_self: b2FrictionJointHandle; inv_dt: Single): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2FrictionJoint_GetReactionForce'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2FrictionJointWrapper.GetReactionForce(inv_dt: Single): b2Vec2; cdecl;
begin
Result := b2FrictionJoint_GetReactionForce(FHandle, inv_dt)
end;
function b2FrictionJoint_GetReactionTorque(_self: b2FrictionJointHandle; inv_dt: Single): Single; cdecl; external LIB_NAME name _PU + 'b2FrictionJoint_GetReactionTorque'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2FrictionJointWrapper.GetReactionTorque(inv_dt: Single): Single; cdecl;
begin
Result := b2FrictionJoint_GetReactionTorque(FHandle, inv_dt)
end;
function b2FrictionJoint_GetNext(_self: b2FrictionJointHandle): b2JointHandle; cdecl; external LIB_NAME name _PU + 'b2FrictionJoint_GetNext'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2FrictionJointWrapper.GetNext: b2JointHandle; cdecl;
begin
Result := b2FrictionJoint_GetNext(FHandle)
end;
function b2FrictionJoint_GetUserData(_self: b2FrictionJointHandle): Pointer; cdecl; external LIB_NAME name _PU + 'b2FrictionJoint_GetUserData'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2FrictionJointWrapper.GetUserData: Pointer; cdecl;
begin
Result := b2FrictionJoint_GetUserData(FHandle)
end;
procedure b2FrictionJoint_SetUserData(_self: b2FrictionJointHandle; data: Pointer); cdecl; external LIB_NAME name _PU + 'b2FrictionJoint_SetUserData'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2FrictionJointWrapper.SetUserData(data: Pointer); cdecl;
begin
b2FrictionJoint_SetUserData(FHandle, data)
end;
function b2FrictionJoint_IsActive(_self: b2FrictionJointHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2FrictionJoint_IsActive'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2FrictionJointWrapper.IsActive: Boolean; cdecl;
begin
Result := b2FrictionJoint_IsActive(FHandle)
end;
function b2FrictionJoint_GetCollideConnected(_self: b2FrictionJointHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2FrictionJoint_GetCollideConnected'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2FrictionJointWrapper.GetCollideConnected: Boolean; cdecl;
begin
Result := b2FrictionJoint_GetCollideConnected(FHandle)
end;
procedure b2FrictionJoint_Dump(_self: b2FrictionJointHandle); cdecl; external LIB_NAME name _PU + 'b2FrictionJoint_Dump'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2FrictionJointWrapper.Dump; cdecl;
begin
b2FrictionJoint_Dump(FHandle)
end;
procedure b2FrictionJoint_ShiftOrigin(_self: b2FrictionJointHandle; const [ref] newOrigin: b2Vec2); cdecl; external LIB_NAME name _PU + 'b2FrictionJoint_ShiftOrigin'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2FrictionJointWrapper.ShiftOrigin(const [ref] newOrigin: b2Vec2); cdecl;
begin
b2FrictionJoint_ShiftOrigin(FHandle, newOrigin)
end;
function b2FrictionJoint_GetLocalAnchorA(_self: b2FrictionJointHandle): Pb2Vec2; cdecl; external LIB_NAME name _PU + 'b2FrictionJoint_GetLocalAnchorA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2FrictionJointWrapper.GetLocalAnchorA: Pb2Vec2; cdecl;
begin
Result := b2FrictionJoint_GetLocalAnchorA(FHandle)
end;
function b2FrictionJoint_GetLocalAnchorB(_self: b2FrictionJointHandle): Pb2Vec2; cdecl; external LIB_NAME name _PU + 'b2FrictionJoint_GetLocalAnchorB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2FrictionJointWrapper.GetLocalAnchorB: Pb2Vec2; cdecl;
begin
Result := b2FrictionJoint_GetLocalAnchorB(FHandle)
end;
procedure b2FrictionJoint_SetMaxForce(_self: b2FrictionJointHandle; force: Single); cdecl; external LIB_NAME name _PU + 'b2FrictionJoint_SetMaxForce'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2FrictionJointWrapper.SetMaxForce(force: Single); cdecl;
begin
b2FrictionJoint_SetMaxForce(FHandle, force)
end;
function b2FrictionJoint_GetMaxForce(_self: b2FrictionJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2FrictionJoint_GetMaxForce'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2FrictionJointWrapper.GetMaxForce: Single; cdecl;
begin
Result := b2FrictionJoint_GetMaxForce(FHandle)
end;
procedure b2FrictionJoint_SetMaxTorque(_self: b2FrictionJointHandle; torque: Single); cdecl; external LIB_NAME name _PU + 'b2FrictionJoint_SetMaxTorque'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2FrictionJointWrapper.SetMaxTorque(torque: Single); cdecl;
begin
b2FrictionJoint_SetMaxTorque(FHandle, torque)
end;
function b2FrictionJoint_GetMaxTorque(_self: b2FrictionJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2FrictionJoint_GetMaxTorque'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2FrictionJointWrapper.GetMaxTorque: Single; cdecl;
begin
Result := b2FrictionJoint_GetMaxTorque(FHandle)
end;
function b2GearJointDef_Create: b2GearJointDef; cdecl; external LIB_NAME name _PU + 'b2GearJointDef_b2GearJointDef_1'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2GearJointDef.Create: b2GearJointDef; cdecl;
begin
Result := b2GearJointDef_Create;
end;
procedure b2GearJoint_Destroy(_self: b2GearJointHandle); cdecl; external LIB_NAME name _PU + 'b2GearJoint_dtor'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2GearJointWrapper.Destroy; cdecl;
begin
b2GearJoint_Destroy(FHandle);
end;
class operator b2GearJointWrapper.Implicit(handle: b2GearJointHandle): b2GearJointWrapper;
begin
Result.FHandle := handle;
end;
class operator b2GearJointWrapper.Implicit(wrapper: b2GearJointWrapper): b2GearJointHandle;
begin
Result := wrapper.FHandle;
end;
function b2GearJoint_GetType(_self: b2GearJointHandle): b2JointType; cdecl; external LIB_NAME name _PU + 'b2GearJoint_GetType'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2GearJointWrapper.GetType: b2JointType; cdecl;
begin
Result := b2GearJoint_GetType(FHandle)
end;
function b2GearJoint_GetBodyA(_self: b2GearJointHandle): b2BodyHandle; cdecl; external LIB_NAME name _PU + 'b2GearJoint_GetBodyA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2GearJointWrapper.GetBodyA: b2BodyHandle; cdecl;
begin
Result := b2GearJoint_GetBodyA(FHandle)
end;
function b2GearJoint_GetBodyB(_self: b2GearJointHandle): b2BodyHandle; cdecl; external LIB_NAME name _PU + 'b2GearJoint_GetBodyB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2GearJointWrapper.GetBodyB: b2BodyHandle; cdecl;
begin
Result := b2GearJoint_GetBodyB(FHandle)
end;
function b2GearJoint_GetAnchorA(_self: b2GearJointHandle): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2GearJoint_GetAnchorA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2GearJointWrapper.GetAnchorA: b2Vec2; cdecl;
begin
Result := b2GearJoint_GetAnchorA(FHandle)
end;
function b2GearJoint_GetAnchorB(_self: b2GearJointHandle): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2GearJoint_GetAnchorB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2GearJointWrapper.GetAnchorB: b2Vec2; cdecl;
begin
Result := b2GearJoint_GetAnchorB(FHandle)
end;
function b2GearJoint_GetReactionForce(_self: b2GearJointHandle; inv_dt: Single): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2GearJoint_GetReactionForce'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2GearJointWrapper.GetReactionForce(inv_dt: Single): b2Vec2; cdecl;
begin
Result := b2GearJoint_GetReactionForce(FHandle, inv_dt)
end;
function b2GearJoint_GetReactionTorque(_self: b2GearJointHandle; inv_dt: Single): Single; cdecl; external LIB_NAME name _PU + 'b2GearJoint_GetReactionTorque'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2GearJointWrapper.GetReactionTorque(inv_dt: Single): Single; cdecl;
begin
Result := b2GearJoint_GetReactionTorque(FHandle, inv_dt)
end;
function b2GearJoint_GetNext(_self: b2GearJointHandle): b2JointHandle; cdecl; external LIB_NAME name _PU + 'b2GearJoint_GetNext'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2GearJointWrapper.GetNext: b2JointHandle; cdecl;
begin
Result := b2GearJoint_GetNext(FHandle)
end;
function b2GearJoint_GetUserData(_self: b2GearJointHandle): Pointer; cdecl; external LIB_NAME name _PU + 'b2GearJoint_GetUserData'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2GearJointWrapper.GetUserData: Pointer; cdecl;
begin
Result := b2GearJoint_GetUserData(FHandle)
end;
procedure b2GearJoint_SetUserData(_self: b2GearJointHandle; data: Pointer); cdecl; external LIB_NAME name _PU + 'b2GearJoint_SetUserData'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2GearJointWrapper.SetUserData(data: Pointer); cdecl;
begin
b2GearJoint_SetUserData(FHandle, data)
end;
function b2GearJoint_IsActive(_self: b2GearJointHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2GearJoint_IsActive'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2GearJointWrapper.IsActive: Boolean; cdecl;
begin
Result := b2GearJoint_IsActive(FHandle)
end;
function b2GearJoint_GetCollideConnected(_self: b2GearJointHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2GearJoint_GetCollideConnected'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2GearJointWrapper.GetCollideConnected: Boolean; cdecl;
begin
Result := b2GearJoint_GetCollideConnected(FHandle)
end;
procedure b2GearJoint_Dump(_self: b2GearJointHandle); cdecl; external LIB_NAME name _PU + 'b2GearJoint_Dump'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2GearJointWrapper.Dump; cdecl;
begin
b2GearJoint_Dump(FHandle)
end;
procedure b2GearJoint_ShiftOrigin(_self: b2GearJointHandle; const [ref] newOrigin: b2Vec2); cdecl; external LIB_NAME name _PU + 'b2GearJoint_ShiftOrigin'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2GearJointWrapper.ShiftOrigin(const [ref] newOrigin: b2Vec2); cdecl;
begin
b2GearJoint_ShiftOrigin(FHandle, newOrigin)
end;
function b2GearJoint_GetJoint1(_self: b2GearJointHandle): b2JointHandle; cdecl; external LIB_NAME name _PU + 'b2GearJoint_GetJoint1'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2GearJointWrapper.GetJoint1: b2JointHandle; cdecl;
begin
Result := b2GearJoint_GetJoint1(FHandle)
end;
function b2GearJoint_GetJoint2(_self: b2GearJointHandle): b2JointHandle; cdecl; external LIB_NAME name _PU + 'b2GearJoint_GetJoint2'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2GearJointWrapper.GetJoint2: b2JointHandle; cdecl;
begin
Result := b2GearJoint_GetJoint2(FHandle)
end;
procedure b2GearJoint_SetRatio(_self: b2GearJointHandle; ratio: Single); cdecl; external LIB_NAME name _PU + 'b2GearJoint_SetRatio'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2GearJointWrapper.SetRatio(ratio: Single); cdecl;
begin
b2GearJoint_SetRatio(FHandle, ratio)
end;
function b2GearJoint_GetRatio(_self: b2GearJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2GearJoint_GetRatio'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2GearJointWrapper.GetRatio: Single; cdecl;
begin
Result := b2GearJoint_GetRatio(FHandle)
end;
function b2MotorJointDef_Create: b2MotorJointDef; cdecl; external LIB_NAME name _PU + 'b2MotorJointDef_b2MotorJointDef_1'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2MotorJointDef.Create: b2MotorJointDef; cdecl;
begin
Result := b2MotorJointDef_Create;
end;
procedure b2MotorJointDef_Initialize(_self: Pb2MotorJointDef; bodyA: b2BodyHandle; bodyB: b2BodyHandle); cdecl; external LIB_NAME name _PU + 'b2MotorJointDef_Initialize'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2MotorJointDef.Initialize(bodyA: b2BodyHandle; bodyB: b2BodyHandle); cdecl;
begin
b2MotorJointDef_Initialize(@Self, bodyA, bodyB)
end;
procedure b2MotorJoint_Destroy(_self: b2MotorJointHandle); cdecl; external LIB_NAME name _PU + 'b2MotorJoint_dtor'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2MotorJointWrapper.Destroy; cdecl;
begin
b2MotorJoint_Destroy(FHandle);
end;
class operator b2MotorJointWrapper.Implicit(handle: b2MotorJointHandle): b2MotorJointWrapper;
begin
Result.FHandle := handle;
end;
class operator b2MotorJointWrapper.Implicit(wrapper: b2MotorJointWrapper): b2MotorJointHandle;
begin
Result := wrapper.FHandle;
end;
function b2MotorJoint_GetType(_self: b2MotorJointHandle): b2JointType; cdecl; external LIB_NAME name _PU + 'b2MotorJoint_GetType'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2MotorJointWrapper.GetType: b2JointType; cdecl;
begin
Result := b2MotorJoint_GetType(FHandle)
end;
function b2MotorJoint_GetBodyA(_self: b2MotorJointHandle): b2BodyHandle; cdecl; external LIB_NAME name _PU + 'b2MotorJoint_GetBodyA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2MotorJointWrapper.GetBodyA: b2BodyHandle; cdecl;
begin
Result := b2MotorJoint_GetBodyA(FHandle)
end;
function b2MotorJoint_GetBodyB(_self: b2MotorJointHandle): b2BodyHandle; cdecl; external LIB_NAME name _PU + 'b2MotorJoint_GetBodyB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2MotorJointWrapper.GetBodyB: b2BodyHandle; cdecl;
begin
Result := b2MotorJoint_GetBodyB(FHandle)
end;
function b2MotorJoint_GetAnchorA(_self: b2MotorJointHandle): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2MotorJoint_GetAnchorA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2MotorJointWrapper.GetAnchorA: b2Vec2; cdecl;
begin
Result := b2MotorJoint_GetAnchorA(FHandle)
end;
function b2MotorJoint_GetAnchorB(_self: b2MotorJointHandle): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2MotorJoint_GetAnchorB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2MotorJointWrapper.GetAnchorB: b2Vec2; cdecl;
begin
Result := b2MotorJoint_GetAnchorB(FHandle)
end;
function b2MotorJoint_GetReactionForce(_self: b2MotorJointHandle; inv_dt: Single): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2MotorJoint_GetReactionForce'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2MotorJointWrapper.GetReactionForce(inv_dt: Single): b2Vec2; cdecl;
begin
Result := b2MotorJoint_GetReactionForce(FHandle, inv_dt)
end;
function b2MotorJoint_GetReactionTorque(_self: b2MotorJointHandle; inv_dt: Single): Single; cdecl; external LIB_NAME name _PU + 'b2MotorJoint_GetReactionTorque'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2MotorJointWrapper.GetReactionTorque(inv_dt: Single): Single; cdecl;
begin
Result := b2MotorJoint_GetReactionTorque(FHandle, inv_dt)
end;
function b2MotorJoint_GetNext(_self: b2MotorJointHandle): b2JointHandle; cdecl; external LIB_NAME name _PU + 'b2MotorJoint_GetNext'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2MotorJointWrapper.GetNext: b2JointHandle; cdecl;
begin
Result := b2MotorJoint_GetNext(FHandle)
end;
function b2MotorJoint_GetUserData(_self: b2MotorJointHandle): Pointer; cdecl; external LIB_NAME name _PU + 'b2MotorJoint_GetUserData'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2MotorJointWrapper.GetUserData: Pointer; cdecl;
begin
Result := b2MotorJoint_GetUserData(FHandle)
end;
procedure b2MotorJoint_SetUserData(_self: b2MotorJointHandle; data: Pointer); cdecl; external LIB_NAME name _PU + 'b2MotorJoint_SetUserData'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2MotorJointWrapper.SetUserData(data: Pointer); cdecl;
begin
b2MotorJoint_SetUserData(FHandle, data)
end;
function b2MotorJoint_IsActive(_self: b2MotorJointHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2MotorJoint_IsActive'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2MotorJointWrapper.IsActive: Boolean; cdecl;
begin
Result := b2MotorJoint_IsActive(FHandle)
end;
function b2MotorJoint_GetCollideConnected(_self: b2MotorJointHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2MotorJoint_GetCollideConnected'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2MotorJointWrapper.GetCollideConnected: Boolean; cdecl;
begin
Result := b2MotorJoint_GetCollideConnected(FHandle)
end;
procedure b2MotorJoint_Dump(_self: b2MotorJointHandle); cdecl; external LIB_NAME name _PU + 'b2MotorJoint_Dump'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2MotorJointWrapper.Dump; cdecl;
begin
b2MotorJoint_Dump(FHandle)
end;
procedure b2MotorJoint_ShiftOrigin(_self: b2MotorJointHandle; const [ref] newOrigin: b2Vec2); cdecl; external LIB_NAME name _PU + 'b2MotorJoint_ShiftOrigin'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2MotorJointWrapper.ShiftOrigin(const [ref] newOrigin: b2Vec2); cdecl;
begin
b2MotorJoint_ShiftOrigin(FHandle, newOrigin)
end;
procedure b2MotorJoint_SetLinearOffset(_self: b2MotorJointHandle; const [ref] linearOffset: b2Vec2); cdecl; external LIB_NAME name _PU + 'b2MotorJoint_SetLinearOffset'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2MotorJointWrapper.SetLinearOffset(const [ref] linearOffset: b2Vec2); cdecl;
begin
b2MotorJoint_SetLinearOffset(FHandle, linearOffset)
end;
function b2MotorJoint_GetLinearOffset(_self: b2MotorJointHandle): Pb2Vec2; cdecl; external LIB_NAME name _PU + 'b2MotorJoint_GetLinearOffset'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2MotorJointWrapper.GetLinearOffset: Pb2Vec2; cdecl;
begin
Result := b2MotorJoint_GetLinearOffset(FHandle)
end;
procedure b2MotorJoint_SetAngularOffset(_self: b2MotorJointHandle; angularOffset: Single); cdecl; external LIB_NAME name _PU + 'b2MotorJoint_SetAngularOffset'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2MotorJointWrapper.SetAngularOffset(angularOffset: Single); cdecl;
begin
b2MotorJoint_SetAngularOffset(FHandle, angularOffset)
end;
function b2MotorJoint_GetAngularOffset(_self: b2MotorJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2MotorJoint_GetAngularOffset'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2MotorJointWrapper.GetAngularOffset: Single; cdecl;
begin
Result := b2MotorJoint_GetAngularOffset(FHandle)
end;
procedure b2MotorJoint_SetMaxForce(_self: b2MotorJointHandle; force: Single); cdecl; external LIB_NAME name _PU + 'b2MotorJoint_SetMaxForce'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2MotorJointWrapper.SetMaxForce(force: Single); cdecl;
begin
b2MotorJoint_SetMaxForce(FHandle, force)
end;
function b2MotorJoint_GetMaxForce(_self: b2MotorJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2MotorJoint_GetMaxForce'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2MotorJointWrapper.GetMaxForce: Single; cdecl;
begin
Result := b2MotorJoint_GetMaxForce(FHandle)
end;
procedure b2MotorJoint_SetMaxTorque(_self: b2MotorJointHandle; torque: Single); cdecl; external LIB_NAME name _PU + 'b2MotorJoint_SetMaxTorque'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2MotorJointWrapper.SetMaxTorque(torque: Single); cdecl;
begin
b2MotorJoint_SetMaxTorque(FHandle, torque)
end;
function b2MotorJoint_GetMaxTorque(_self: b2MotorJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2MotorJoint_GetMaxTorque'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2MotorJointWrapper.GetMaxTorque: Single; cdecl;
begin
Result := b2MotorJoint_GetMaxTorque(FHandle)
end;
procedure b2MotorJoint_SetCorrectionFactor(_self: b2MotorJointHandle; factor: Single); cdecl; external LIB_NAME name _PU + 'b2MotorJoint_SetCorrectionFactor'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2MotorJointWrapper.SetCorrectionFactor(factor: Single); cdecl;
begin
b2MotorJoint_SetCorrectionFactor(FHandle, factor)
end;
function b2MotorJoint_GetCorrectionFactor(_self: b2MotorJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2MotorJoint_GetCorrectionFactor'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2MotorJointWrapper.GetCorrectionFactor: Single; cdecl;
begin
Result := b2MotorJoint_GetCorrectionFactor(FHandle)
end;
function b2MouseJointDef_Create: b2MouseJointDef; cdecl; external LIB_NAME name _PU + 'b2MouseJointDef_b2MouseJointDef_1'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2MouseJointDef.Create: b2MouseJointDef; cdecl;
begin
Result := b2MouseJointDef_Create;
end;
procedure b2MouseJoint_Destroy(_self: b2MouseJointHandle); cdecl; external LIB_NAME name _PU + 'b2MouseJoint_dtor'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2MouseJointWrapper.Destroy; cdecl;
begin
b2MouseJoint_Destroy(FHandle);
end;
class operator b2MouseJointWrapper.Implicit(handle: b2MouseJointHandle): b2MouseJointWrapper;
begin
Result.FHandle := handle;
end;
class operator b2MouseJointWrapper.Implicit(wrapper: b2MouseJointWrapper): b2MouseJointHandle;
begin
Result := wrapper.FHandle;
end;
function b2MouseJoint_GetType(_self: b2MouseJointHandle): b2JointType; cdecl; external LIB_NAME name _PU + 'b2MouseJoint_GetType'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2MouseJointWrapper.GetType: b2JointType; cdecl;
begin
Result := b2MouseJoint_GetType(FHandle)
end;
function b2MouseJoint_GetBodyA(_self: b2MouseJointHandle): b2BodyHandle; cdecl; external LIB_NAME name _PU + 'b2MouseJoint_GetBodyA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2MouseJointWrapper.GetBodyA: b2BodyHandle; cdecl;
begin
Result := b2MouseJoint_GetBodyA(FHandle)
end;
function b2MouseJoint_GetBodyB(_self: b2MouseJointHandle): b2BodyHandle; cdecl; external LIB_NAME name _PU + 'b2MouseJoint_GetBodyB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2MouseJointWrapper.GetBodyB: b2BodyHandle; cdecl;
begin
Result := b2MouseJoint_GetBodyB(FHandle)
end;
function b2MouseJoint_GetAnchorA(_self: b2MouseJointHandle): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2MouseJoint_GetAnchorA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2MouseJointWrapper.GetAnchorA: b2Vec2; cdecl;
begin
Result := b2MouseJoint_GetAnchorA(FHandle)
end;
function b2MouseJoint_GetAnchorB(_self: b2MouseJointHandle): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2MouseJoint_GetAnchorB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2MouseJointWrapper.GetAnchorB: b2Vec2; cdecl;
begin
Result := b2MouseJoint_GetAnchorB(FHandle)
end;
function b2MouseJoint_GetReactionForce(_self: b2MouseJointHandle; inv_dt: Single): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2MouseJoint_GetReactionForce'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2MouseJointWrapper.GetReactionForce(inv_dt: Single): b2Vec2; cdecl;
begin
Result := b2MouseJoint_GetReactionForce(FHandle, inv_dt)
end;
function b2MouseJoint_GetReactionTorque(_self: b2MouseJointHandle; inv_dt: Single): Single; cdecl; external LIB_NAME name _PU + 'b2MouseJoint_GetReactionTorque'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2MouseJointWrapper.GetReactionTorque(inv_dt: Single): Single; cdecl;
begin
Result := b2MouseJoint_GetReactionTorque(FHandle, inv_dt)
end;
function b2MouseJoint_GetNext(_self: b2MouseJointHandle): b2JointHandle; cdecl; external LIB_NAME name _PU + 'b2MouseJoint_GetNext'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2MouseJointWrapper.GetNext: b2JointHandle; cdecl;
begin
Result := b2MouseJoint_GetNext(FHandle)
end;
function b2MouseJoint_GetUserData(_self: b2MouseJointHandle): Pointer; cdecl; external LIB_NAME name _PU + 'b2MouseJoint_GetUserData'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2MouseJointWrapper.GetUserData: Pointer; cdecl;
begin
Result := b2MouseJoint_GetUserData(FHandle)
end;
procedure b2MouseJoint_SetUserData(_self: b2MouseJointHandle; data: Pointer); cdecl; external LIB_NAME name _PU + 'b2MouseJoint_SetUserData'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2MouseJointWrapper.SetUserData(data: Pointer); cdecl;
begin
b2MouseJoint_SetUserData(FHandle, data)
end;
function b2MouseJoint_IsActive(_self: b2MouseJointHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2MouseJoint_IsActive'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2MouseJointWrapper.IsActive: Boolean; cdecl;
begin
Result := b2MouseJoint_IsActive(FHandle)
end;
function b2MouseJoint_GetCollideConnected(_self: b2MouseJointHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2MouseJoint_GetCollideConnected'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2MouseJointWrapper.GetCollideConnected: Boolean; cdecl;
begin
Result := b2MouseJoint_GetCollideConnected(FHandle)
end;
procedure b2MouseJoint_Dump(_self: b2MouseJointHandle); cdecl; external LIB_NAME name _PU + 'b2MouseJoint_Dump'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2MouseJointWrapper.Dump; cdecl;
begin
b2MouseJoint_Dump(FHandle)
end;
procedure b2MouseJoint_ShiftOrigin(_self: b2MouseJointHandle; const [ref] newOrigin: b2Vec2); cdecl; external LIB_NAME name _PU + 'b2MouseJoint_ShiftOrigin'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2MouseJointWrapper.ShiftOrigin(const [ref] newOrigin: b2Vec2); cdecl;
begin
b2MouseJoint_ShiftOrigin(FHandle, newOrigin)
end;
procedure b2MouseJoint_SetTarget(_self: b2MouseJointHandle; const [ref] target: b2Vec2); cdecl; external LIB_NAME name _PU + 'b2MouseJoint_SetTarget'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2MouseJointWrapper.SetTarget(const [ref] target: b2Vec2); cdecl;
begin
b2MouseJoint_SetTarget(FHandle, target)
end;
function b2MouseJoint_GetTarget(_self: b2MouseJointHandle): Pb2Vec2; cdecl; external LIB_NAME name _PU + 'b2MouseJoint_GetTarget'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2MouseJointWrapper.GetTarget: Pb2Vec2; cdecl;
begin
Result := b2MouseJoint_GetTarget(FHandle)
end;
procedure b2MouseJoint_SetMaxForce(_self: b2MouseJointHandle; force: Single); cdecl; external LIB_NAME name _PU + 'b2MouseJoint_SetMaxForce'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2MouseJointWrapper.SetMaxForce(force: Single); cdecl;
begin
b2MouseJoint_SetMaxForce(FHandle, force)
end;
function b2MouseJoint_GetMaxForce(_self: b2MouseJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2MouseJoint_GetMaxForce'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2MouseJointWrapper.GetMaxForce: Single; cdecl;
begin
Result := b2MouseJoint_GetMaxForce(FHandle)
end;
procedure b2MouseJoint_SetFrequency(_self: b2MouseJointHandle; hz: Single); cdecl; external LIB_NAME name _PU + 'b2MouseJoint_SetFrequency'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2MouseJointWrapper.SetFrequency(hz: Single); cdecl;
begin
b2MouseJoint_SetFrequency(FHandle, hz)
end;
function b2MouseJoint_GetFrequency(_self: b2MouseJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2MouseJoint_GetFrequency'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2MouseJointWrapper.GetFrequency: Single; cdecl;
begin
Result := b2MouseJoint_GetFrequency(FHandle)
end;
procedure b2MouseJoint_SetDampingRatio(_self: b2MouseJointHandle; ratio: Single); cdecl; external LIB_NAME name _PU + 'b2MouseJoint_SetDampingRatio'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2MouseJointWrapper.SetDampingRatio(ratio: Single); cdecl;
begin
b2MouseJoint_SetDampingRatio(FHandle, ratio)
end;
function b2MouseJoint_GetDampingRatio(_self: b2MouseJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2MouseJoint_GetDampingRatio'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2MouseJointWrapper.GetDampingRatio: Single; cdecl;
begin
Result := b2MouseJoint_GetDampingRatio(FHandle)
end;
function b2PrismaticJointDef_Create: b2PrismaticJointDef; cdecl; external LIB_NAME name _PU + 'b2PrismaticJointDef_b2PrismaticJointDef_1'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2PrismaticJointDef.Create: b2PrismaticJointDef; cdecl;
begin
Result := b2PrismaticJointDef_Create;
end;
procedure b2PrismaticJointDef_Initialize(_self: Pb2PrismaticJointDef; bodyA: b2BodyHandle; bodyB: b2BodyHandle; const [ref] anchor: b2Vec2; const [ref] axis: b2Vec2); cdecl; external LIB_NAME name _PU + 'b2PrismaticJointDef_Initialize'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PrismaticJointDef.Initialize(bodyA: b2BodyHandle; bodyB: b2BodyHandle; const [ref] anchor: b2Vec2; const [ref] axis: b2Vec2); cdecl;
begin
b2PrismaticJointDef_Initialize(@Self, bodyA, bodyB, anchor, axis)
end;
procedure b2PrismaticJoint_Destroy(_self: b2PrismaticJointHandle); cdecl; external LIB_NAME name _PU + 'b2PrismaticJoint_dtor'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PrismaticJointWrapper.Destroy; cdecl;
begin
b2PrismaticJoint_Destroy(FHandle);
end;
class operator b2PrismaticJointWrapper.Implicit(handle: b2PrismaticJointHandle): b2PrismaticJointWrapper;
begin
Result.FHandle := handle;
end;
class operator b2PrismaticJointWrapper.Implicit(wrapper: b2PrismaticJointWrapper): b2PrismaticJointHandle;
begin
Result := wrapper.FHandle;
end;
function b2PrismaticJoint_GetType(_self: b2PrismaticJointHandle): b2JointType; cdecl; external LIB_NAME name _PU + 'b2PrismaticJoint_GetType'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PrismaticJointWrapper.GetType: b2JointType; cdecl;
begin
Result := b2PrismaticJoint_GetType(FHandle)
end;
function b2PrismaticJoint_GetBodyA(_self: b2PrismaticJointHandle): b2BodyHandle; cdecl; external LIB_NAME name _PU + 'b2PrismaticJoint_GetBodyA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PrismaticJointWrapper.GetBodyA: b2BodyHandle; cdecl;
begin
Result := b2PrismaticJoint_GetBodyA(FHandle)
end;
function b2PrismaticJoint_GetBodyB(_self: b2PrismaticJointHandle): b2BodyHandle; cdecl; external LIB_NAME name _PU + 'b2PrismaticJoint_GetBodyB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PrismaticJointWrapper.GetBodyB: b2BodyHandle; cdecl;
begin
Result := b2PrismaticJoint_GetBodyB(FHandle)
end;
function b2PrismaticJoint_GetAnchorA(_self: b2PrismaticJointHandle): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2PrismaticJoint_GetAnchorA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PrismaticJointWrapper.GetAnchorA: b2Vec2; cdecl;
begin
Result := b2PrismaticJoint_GetAnchorA(FHandle)
end;
function b2PrismaticJoint_GetAnchorB(_self: b2PrismaticJointHandle): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2PrismaticJoint_GetAnchorB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PrismaticJointWrapper.GetAnchorB: b2Vec2; cdecl;
begin
Result := b2PrismaticJoint_GetAnchorB(FHandle)
end;
function b2PrismaticJoint_GetReactionForce(_self: b2PrismaticJointHandle; inv_dt: Single): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2PrismaticJoint_GetReactionForce'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PrismaticJointWrapper.GetReactionForce(inv_dt: Single): b2Vec2; cdecl;
begin
Result := b2PrismaticJoint_GetReactionForce(FHandle, inv_dt)
end;
function b2PrismaticJoint_GetReactionTorque(_self: b2PrismaticJointHandle; inv_dt: Single): Single; cdecl; external LIB_NAME name _PU + 'b2PrismaticJoint_GetReactionTorque'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PrismaticJointWrapper.GetReactionTorque(inv_dt: Single): Single; cdecl;
begin
Result := b2PrismaticJoint_GetReactionTorque(FHandle, inv_dt)
end;
function b2PrismaticJoint_GetNext(_self: b2PrismaticJointHandle): b2JointHandle; cdecl; external LIB_NAME name _PU + 'b2PrismaticJoint_GetNext'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PrismaticJointWrapper.GetNext: b2JointHandle; cdecl;
begin
Result := b2PrismaticJoint_GetNext(FHandle)
end;
function b2PrismaticJoint_GetUserData(_self: b2PrismaticJointHandle): Pointer; cdecl; external LIB_NAME name _PU + 'b2PrismaticJoint_GetUserData'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PrismaticJointWrapper.GetUserData: Pointer; cdecl;
begin
Result := b2PrismaticJoint_GetUserData(FHandle)
end;
procedure b2PrismaticJoint_SetUserData(_self: b2PrismaticJointHandle; data: Pointer); cdecl; external LIB_NAME name _PU + 'b2PrismaticJoint_SetUserData'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PrismaticJointWrapper.SetUserData(data: Pointer); cdecl;
begin
b2PrismaticJoint_SetUserData(FHandle, data)
end;
function b2PrismaticJoint_IsActive(_self: b2PrismaticJointHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2PrismaticJoint_IsActive'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PrismaticJointWrapper.IsActive: Boolean; cdecl;
begin
Result := b2PrismaticJoint_IsActive(FHandle)
end;
function b2PrismaticJoint_GetCollideConnected(_self: b2PrismaticJointHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2PrismaticJoint_GetCollideConnected'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PrismaticJointWrapper.GetCollideConnected: Boolean; cdecl;
begin
Result := b2PrismaticJoint_GetCollideConnected(FHandle)
end;
procedure b2PrismaticJoint_Dump(_self: b2PrismaticJointHandle); cdecl; external LIB_NAME name _PU + 'b2PrismaticJoint_Dump'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PrismaticJointWrapper.Dump; cdecl;
begin
b2PrismaticJoint_Dump(FHandle)
end;
procedure b2PrismaticJoint_ShiftOrigin(_self: b2PrismaticJointHandle; const [ref] newOrigin: b2Vec2); cdecl; external LIB_NAME name _PU + 'b2PrismaticJoint_ShiftOrigin'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PrismaticJointWrapper.ShiftOrigin(const [ref] newOrigin: b2Vec2); cdecl;
begin
b2PrismaticJoint_ShiftOrigin(FHandle, newOrigin)
end;
function b2PrismaticJoint_GetLocalAnchorA(_self: b2PrismaticJointHandle): Pb2Vec2; cdecl; external LIB_NAME name _PU + 'b2PrismaticJoint_GetLocalAnchorA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PrismaticJointWrapper.GetLocalAnchorA: Pb2Vec2; cdecl;
begin
Result := b2PrismaticJoint_GetLocalAnchorA(FHandle)
end;
function b2PrismaticJoint_GetLocalAnchorB(_self: b2PrismaticJointHandle): Pb2Vec2; cdecl; external LIB_NAME name _PU + 'b2PrismaticJoint_GetLocalAnchorB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PrismaticJointWrapper.GetLocalAnchorB: Pb2Vec2; cdecl;
begin
Result := b2PrismaticJoint_GetLocalAnchorB(FHandle)
end;
function b2PrismaticJoint_GetLocalAxisA(_self: b2PrismaticJointHandle): Pb2Vec2; cdecl; external LIB_NAME name _PU + 'b2PrismaticJoint_GetLocalAxisA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PrismaticJointWrapper.GetLocalAxisA: Pb2Vec2; cdecl;
begin
Result := b2PrismaticJoint_GetLocalAxisA(FHandle)
end;
function b2PrismaticJoint_GetReferenceAngle(_self: b2PrismaticJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2PrismaticJoint_GetReferenceAngle'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PrismaticJointWrapper.GetReferenceAngle: Single; cdecl;
begin
Result := b2PrismaticJoint_GetReferenceAngle(FHandle)
end;
function b2PrismaticJoint_GetJointTranslation(_self: b2PrismaticJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2PrismaticJoint_GetJointTranslation'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PrismaticJointWrapper.GetJointTranslation: Single; cdecl;
begin
Result := b2PrismaticJoint_GetJointTranslation(FHandle)
end;
function b2PrismaticJoint_GetJointSpeed(_self: b2PrismaticJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2PrismaticJoint_GetJointSpeed'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PrismaticJointWrapper.GetJointSpeed: Single; cdecl;
begin
Result := b2PrismaticJoint_GetJointSpeed(FHandle)
end;
function b2PrismaticJoint_IsLimitEnabled(_self: b2PrismaticJointHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2PrismaticJoint_IsLimitEnabled'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PrismaticJointWrapper.IsLimitEnabled: Boolean; cdecl;
begin
Result := b2PrismaticJoint_IsLimitEnabled(FHandle)
end;
procedure b2PrismaticJoint_EnableLimit(_self: b2PrismaticJointHandle; flag: Boolean); cdecl; external LIB_NAME name _PU + 'b2PrismaticJoint_EnableLimit'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PrismaticJointWrapper.EnableLimit(flag: Boolean); cdecl;
begin
b2PrismaticJoint_EnableLimit(FHandle, flag)
end;
function b2PrismaticJoint_GetLowerLimit(_self: b2PrismaticJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2PrismaticJoint_GetLowerLimit'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PrismaticJointWrapper.GetLowerLimit: Single; cdecl;
begin
Result := b2PrismaticJoint_GetLowerLimit(FHandle)
end;
function b2PrismaticJoint_GetUpperLimit(_self: b2PrismaticJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2PrismaticJoint_GetUpperLimit'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PrismaticJointWrapper.GetUpperLimit: Single; cdecl;
begin
Result := b2PrismaticJoint_GetUpperLimit(FHandle)
end;
procedure b2PrismaticJoint_SetLimits(_self: b2PrismaticJointHandle; lower: Single; upper: Single); cdecl; external LIB_NAME name _PU + 'b2PrismaticJoint_SetLimits'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PrismaticJointWrapper.SetLimits(lower: Single; upper: Single); cdecl;
begin
b2PrismaticJoint_SetLimits(FHandle, lower, upper)
end;
function b2PrismaticJoint_IsMotorEnabled(_self: b2PrismaticJointHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2PrismaticJoint_IsMotorEnabled'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PrismaticJointWrapper.IsMotorEnabled: Boolean; cdecl;
begin
Result := b2PrismaticJoint_IsMotorEnabled(FHandle)
end;
procedure b2PrismaticJoint_EnableMotor(_self: b2PrismaticJointHandle; flag: Boolean); cdecl; external LIB_NAME name _PU + 'b2PrismaticJoint_EnableMotor'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PrismaticJointWrapper.EnableMotor(flag: Boolean); cdecl;
begin
b2PrismaticJoint_EnableMotor(FHandle, flag)
end;
procedure b2PrismaticJoint_SetMotorSpeed(_self: b2PrismaticJointHandle; speed: Single); cdecl; external LIB_NAME name _PU + 'b2PrismaticJoint_SetMotorSpeed'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PrismaticJointWrapper.SetMotorSpeed(speed: Single); cdecl;
begin
b2PrismaticJoint_SetMotorSpeed(FHandle, speed)
end;
function b2PrismaticJoint_GetMotorSpeed(_self: b2PrismaticJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2PrismaticJoint_GetMotorSpeed'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PrismaticJointWrapper.GetMotorSpeed: Single; cdecl;
begin
Result := b2PrismaticJoint_GetMotorSpeed(FHandle)
end;
procedure b2PrismaticJoint_SetMaxMotorForce(_self: b2PrismaticJointHandle; force: Single); cdecl; external LIB_NAME name _PU + 'b2PrismaticJoint_SetMaxMotorForce'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PrismaticJointWrapper.SetMaxMotorForce(force: Single); cdecl;
begin
b2PrismaticJoint_SetMaxMotorForce(FHandle, force)
end;
function b2PrismaticJoint_GetMaxMotorForce(_self: b2PrismaticJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2PrismaticJoint_GetMaxMotorForce'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PrismaticJointWrapper.GetMaxMotorForce: Single; cdecl;
begin
Result := b2PrismaticJoint_GetMaxMotorForce(FHandle)
end;
function b2PrismaticJoint_GetMotorForce(_self: b2PrismaticJointHandle; inv_dt: Single): Single; cdecl; external LIB_NAME name _PU + 'b2PrismaticJoint_GetMotorForce'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PrismaticJointWrapper.GetMotorForce(inv_dt: Single): Single; cdecl;
begin
Result := b2PrismaticJoint_GetMotorForce(FHandle, inv_dt)
end;
function b2PulleyJointDef_Create: b2PulleyJointDef; cdecl; external LIB_NAME name _PU + 'b2PulleyJointDef_b2PulleyJointDef_1'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2PulleyJointDef.Create: b2PulleyJointDef; cdecl;
begin
Result := b2PulleyJointDef_Create;
end;
procedure b2PulleyJointDef_Initialize(_self: Pb2PulleyJointDef; bodyA: b2BodyHandle; bodyB: b2BodyHandle; const [ref] groundAnchorA: b2Vec2; const [ref] groundAnchorB: b2Vec2; const [ref] anchorA: b2Vec2; const [ref] anchorB: b2Vec2; ratio: Single); cdecl; external LIB_NAME name _PU + 'b2PulleyJointDef_Initialize'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PulleyJointDef.Initialize(bodyA: b2BodyHandle; bodyB: b2BodyHandle; const [ref] groundAnchorA: b2Vec2; const [ref] groundAnchorB: b2Vec2; const [ref] anchorA: b2Vec2; const [ref] anchorB: b2Vec2; ratio: Single); cdecl;
begin
b2PulleyJointDef_Initialize(@Self, bodyA, bodyB, groundAnchorA, groundAnchorB, anchorA, anchorB, ratio)
end;
procedure b2PulleyJoint_Destroy(_self: b2PulleyJointHandle); cdecl; external LIB_NAME name _PU + 'b2PulleyJoint_dtor'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PulleyJointWrapper.Destroy; cdecl;
begin
b2PulleyJoint_Destroy(FHandle);
end;
class operator b2PulleyJointWrapper.Implicit(handle: b2PulleyJointHandle): b2PulleyJointWrapper;
begin
Result.FHandle := handle;
end;
class operator b2PulleyJointWrapper.Implicit(wrapper: b2PulleyJointWrapper): b2PulleyJointHandle;
begin
Result := wrapper.FHandle;
end;
function b2PulleyJoint_GetType(_self: b2PulleyJointHandle): b2JointType; cdecl; external LIB_NAME name _PU + 'b2PulleyJoint_GetType'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PulleyJointWrapper.GetType: b2JointType; cdecl;
begin
Result := b2PulleyJoint_GetType(FHandle)
end;
function b2PulleyJoint_GetBodyA(_self: b2PulleyJointHandle): b2BodyHandle; cdecl; external LIB_NAME name _PU + 'b2PulleyJoint_GetBodyA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PulleyJointWrapper.GetBodyA: b2BodyHandle; cdecl;
begin
Result := b2PulleyJoint_GetBodyA(FHandle)
end;
function b2PulleyJoint_GetBodyB(_self: b2PulleyJointHandle): b2BodyHandle; cdecl; external LIB_NAME name _PU + 'b2PulleyJoint_GetBodyB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PulleyJointWrapper.GetBodyB: b2BodyHandle; cdecl;
begin
Result := b2PulleyJoint_GetBodyB(FHandle)
end;
function b2PulleyJoint_GetAnchorA(_self: b2PulleyJointHandle): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2PulleyJoint_GetAnchorA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PulleyJointWrapper.GetAnchorA: b2Vec2; cdecl;
begin
Result := b2PulleyJoint_GetAnchorA(FHandle)
end;
function b2PulleyJoint_GetAnchorB(_self: b2PulleyJointHandle): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2PulleyJoint_GetAnchorB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PulleyJointWrapper.GetAnchorB: b2Vec2; cdecl;
begin
Result := b2PulleyJoint_GetAnchorB(FHandle)
end;
function b2PulleyJoint_GetReactionForce(_self: b2PulleyJointHandle; inv_dt: Single): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2PulleyJoint_GetReactionForce'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PulleyJointWrapper.GetReactionForce(inv_dt: Single): b2Vec2; cdecl;
begin
Result := b2PulleyJoint_GetReactionForce(FHandle, inv_dt)
end;
function b2PulleyJoint_GetReactionTorque(_self: b2PulleyJointHandle; inv_dt: Single): Single; cdecl; external LIB_NAME name _PU + 'b2PulleyJoint_GetReactionTorque'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PulleyJointWrapper.GetReactionTorque(inv_dt: Single): Single; cdecl;
begin
Result := b2PulleyJoint_GetReactionTorque(FHandle, inv_dt)
end;
function b2PulleyJoint_GetNext(_self: b2PulleyJointHandle): b2JointHandle; cdecl; external LIB_NAME name _PU + 'b2PulleyJoint_GetNext'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PulleyJointWrapper.GetNext: b2JointHandle; cdecl;
begin
Result := b2PulleyJoint_GetNext(FHandle)
end;
function b2PulleyJoint_GetUserData(_self: b2PulleyJointHandle): Pointer; cdecl; external LIB_NAME name _PU + 'b2PulleyJoint_GetUserData'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PulleyJointWrapper.GetUserData: Pointer; cdecl;
begin
Result := b2PulleyJoint_GetUserData(FHandle)
end;
procedure b2PulleyJoint_SetUserData(_self: b2PulleyJointHandle; data: Pointer); cdecl; external LIB_NAME name _PU + 'b2PulleyJoint_SetUserData'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PulleyJointWrapper.SetUserData(data: Pointer); cdecl;
begin
b2PulleyJoint_SetUserData(FHandle, data)
end;
function b2PulleyJoint_IsActive(_self: b2PulleyJointHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2PulleyJoint_IsActive'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PulleyJointWrapper.IsActive: Boolean; cdecl;
begin
Result := b2PulleyJoint_IsActive(FHandle)
end;
function b2PulleyJoint_GetCollideConnected(_self: b2PulleyJointHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2PulleyJoint_GetCollideConnected'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PulleyJointWrapper.GetCollideConnected: Boolean; cdecl;
begin
Result := b2PulleyJoint_GetCollideConnected(FHandle)
end;
procedure b2PulleyJoint_Dump(_self: b2PulleyJointHandle); cdecl; external LIB_NAME name _PU + 'b2PulleyJoint_Dump'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PulleyJointWrapper.Dump; cdecl;
begin
b2PulleyJoint_Dump(FHandle)
end;
procedure b2PulleyJoint_ShiftOrigin(_self: b2PulleyJointHandle; const [ref] newOrigin: b2Vec2); cdecl; external LIB_NAME name _PU + 'b2PulleyJoint_ShiftOrigin'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2PulleyJointWrapper.ShiftOrigin(const [ref] newOrigin: b2Vec2); cdecl;
begin
b2PulleyJoint_ShiftOrigin(FHandle, newOrigin)
end;
function b2PulleyJoint_GetGroundAnchorA(_self: b2PulleyJointHandle): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2PulleyJoint_GetGroundAnchorA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PulleyJointWrapper.GetGroundAnchorA: b2Vec2; cdecl;
begin
Result := b2PulleyJoint_GetGroundAnchorA(FHandle)
end;
function b2PulleyJoint_GetGroundAnchorB(_self: b2PulleyJointHandle): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2PulleyJoint_GetGroundAnchorB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PulleyJointWrapper.GetGroundAnchorB: b2Vec2; cdecl;
begin
Result := b2PulleyJoint_GetGroundAnchorB(FHandle)
end;
function b2PulleyJoint_GetLengthA(_self: b2PulleyJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2PulleyJoint_GetLengthA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PulleyJointWrapper.GetLengthA: Single; cdecl;
begin
Result := b2PulleyJoint_GetLengthA(FHandle)
end;
function b2PulleyJoint_GetLengthB(_self: b2PulleyJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2PulleyJoint_GetLengthB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PulleyJointWrapper.GetLengthB: Single; cdecl;
begin
Result := b2PulleyJoint_GetLengthB(FHandle)
end;
function b2PulleyJoint_GetRatio(_self: b2PulleyJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2PulleyJoint_GetRatio'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PulleyJointWrapper.GetRatio: Single; cdecl;
begin
Result := b2PulleyJoint_GetRatio(FHandle)
end;
function b2PulleyJoint_GetCurrentLengthA(_self: b2PulleyJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2PulleyJoint_GetCurrentLengthA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PulleyJointWrapper.GetCurrentLengthA: Single; cdecl;
begin
Result := b2PulleyJoint_GetCurrentLengthA(FHandle)
end;
function b2PulleyJoint_GetCurrentLengthB(_self: b2PulleyJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2PulleyJoint_GetCurrentLengthB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2PulleyJointWrapper.GetCurrentLengthB: Single; cdecl;
begin
Result := b2PulleyJoint_GetCurrentLengthB(FHandle)
end;
function b2RevoluteJointDef_Create: b2RevoluteJointDef; cdecl; external LIB_NAME name _PU + 'b2RevoluteJointDef_b2RevoluteJointDef_1'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2RevoluteJointDef.Create: b2RevoluteJointDef; cdecl;
begin
Result := b2RevoluteJointDef_Create;
end;
procedure b2RevoluteJointDef_Initialize(_self: Pb2RevoluteJointDef; bodyA: b2BodyHandle; bodyB: b2BodyHandle; const [ref] anchor: b2Vec2); cdecl; external LIB_NAME name _PU + 'b2RevoluteJointDef_Initialize'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2RevoluteJointDef.Initialize(bodyA: b2BodyHandle; bodyB: b2BodyHandle; const [ref] anchor: b2Vec2); cdecl;
begin
b2RevoluteJointDef_Initialize(@Self, bodyA, bodyB, anchor)
end;
procedure b2RevoluteJoint_Destroy(_self: b2RevoluteJointHandle); cdecl; external LIB_NAME name _PU + 'b2RevoluteJoint_dtor'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2RevoluteJointWrapper.Destroy; cdecl;
begin
b2RevoluteJoint_Destroy(FHandle);
end;
class operator b2RevoluteJointWrapper.Implicit(handle: b2RevoluteJointHandle): b2RevoluteJointWrapper;
begin
Result.FHandle := handle;
end;
class operator b2RevoluteJointWrapper.Implicit(wrapper: b2RevoluteJointWrapper): b2RevoluteJointHandle;
begin
Result := wrapper.FHandle;
end;
function b2RevoluteJoint_GetType(_self: b2RevoluteJointHandle): b2JointType; cdecl; external LIB_NAME name _PU + 'b2RevoluteJoint_GetType'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2RevoluteJointWrapper.GetType: b2JointType; cdecl;
begin
Result := b2RevoluteJoint_GetType(FHandle)
end;
function b2RevoluteJoint_GetBodyA(_self: b2RevoluteJointHandle): b2BodyHandle; cdecl; external LIB_NAME name _PU + 'b2RevoluteJoint_GetBodyA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2RevoluteJointWrapper.GetBodyA: b2BodyHandle; cdecl;
begin
Result := b2RevoluteJoint_GetBodyA(FHandle)
end;
function b2RevoluteJoint_GetBodyB(_self: b2RevoluteJointHandle): b2BodyHandle; cdecl; external LIB_NAME name _PU + 'b2RevoluteJoint_GetBodyB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2RevoluteJointWrapper.GetBodyB: b2BodyHandle; cdecl;
begin
Result := b2RevoluteJoint_GetBodyB(FHandle)
end;
function b2RevoluteJoint_GetAnchorA(_self: b2RevoluteJointHandle): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2RevoluteJoint_GetAnchorA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2RevoluteJointWrapper.GetAnchorA: b2Vec2; cdecl;
begin
Result := b2RevoluteJoint_GetAnchorA(FHandle)
end;
function b2RevoluteJoint_GetAnchorB(_self: b2RevoluteJointHandle): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2RevoluteJoint_GetAnchorB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2RevoluteJointWrapper.GetAnchorB: b2Vec2; cdecl;
begin
Result := b2RevoluteJoint_GetAnchorB(FHandle)
end;
function b2RevoluteJoint_GetReactionForce(_self: b2RevoluteJointHandle; inv_dt: Single): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2RevoluteJoint_GetReactionForce'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2RevoluteJointWrapper.GetReactionForce(inv_dt: Single): b2Vec2; cdecl;
begin
Result := b2RevoluteJoint_GetReactionForce(FHandle, inv_dt)
end;
function b2RevoluteJoint_GetReactionTorque(_self: b2RevoluteJointHandle; inv_dt: Single): Single; cdecl; external LIB_NAME name _PU + 'b2RevoluteJoint_GetReactionTorque'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2RevoluteJointWrapper.GetReactionTorque(inv_dt: Single): Single; cdecl;
begin
Result := b2RevoluteJoint_GetReactionTorque(FHandle, inv_dt)
end;
function b2RevoluteJoint_GetNext(_self: b2RevoluteJointHandle): b2JointHandle; cdecl; external LIB_NAME name _PU + 'b2RevoluteJoint_GetNext'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2RevoluteJointWrapper.GetNext: b2JointHandle; cdecl;
begin
Result := b2RevoluteJoint_GetNext(FHandle)
end;
function b2RevoluteJoint_GetUserData(_self: b2RevoluteJointHandle): Pointer; cdecl; external LIB_NAME name _PU + 'b2RevoluteJoint_GetUserData'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2RevoluteJointWrapper.GetUserData: Pointer; cdecl;
begin
Result := b2RevoluteJoint_GetUserData(FHandle)
end;
procedure b2RevoluteJoint_SetUserData(_self: b2RevoluteJointHandle; data: Pointer); cdecl; external LIB_NAME name _PU + 'b2RevoluteJoint_SetUserData'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2RevoluteJointWrapper.SetUserData(data: Pointer); cdecl;
begin
b2RevoluteJoint_SetUserData(FHandle, data)
end;
function b2RevoluteJoint_IsActive(_self: b2RevoluteJointHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2RevoluteJoint_IsActive'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2RevoluteJointWrapper.IsActive: Boolean; cdecl;
begin
Result := b2RevoluteJoint_IsActive(FHandle)
end;
function b2RevoluteJoint_GetCollideConnected(_self: b2RevoluteJointHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2RevoluteJoint_GetCollideConnected'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2RevoluteJointWrapper.GetCollideConnected: Boolean; cdecl;
begin
Result := b2RevoluteJoint_GetCollideConnected(FHandle)
end;
procedure b2RevoluteJoint_Dump(_self: b2RevoluteJointHandle); cdecl; external LIB_NAME name _PU + 'b2RevoluteJoint_Dump'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2RevoluteJointWrapper.Dump; cdecl;
begin
b2RevoluteJoint_Dump(FHandle)
end;
procedure b2RevoluteJoint_ShiftOrigin(_self: b2RevoluteJointHandle; const [ref] newOrigin: b2Vec2); cdecl; external LIB_NAME name _PU + 'b2RevoluteJoint_ShiftOrigin'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2RevoluteJointWrapper.ShiftOrigin(const [ref] newOrigin: b2Vec2); cdecl;
begin
b2RevoluteJoint_ShiftOrigin(FHandle, newOrigin)
end;
function b2RevoluteJoint_GetLocalAnchorA(_self: b2RevoluteJointHandle): Pb2Vec2; cdecl; external LIB_NAME name _PU + 'b2RevoluteJoint_GetLocalAnchorA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2RevoluteJointWrapper.GetLocalAnchorA: Pb2Vec2; cdecl;
begin
Result := b2RevoluteJoint_GetLocalAnchorA(FHandle)
end;
function b2RevoluteJoint_GetLocalAnchorB(_self: b2RevoluteJointHandle): Pb2Vec2; cdecl; external LIB_NAME name _PU + 'b2RevoluteJoint_GetLocalAnchorB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2RevoluteJointWrapper.GetLocalAnchorB: Pb2Vec2; cdecl;
begin
Result := b2RevoluteJoint_GetLocalAnchorB(FHandle)
end;
function b2RevoluteJoint_GetReferenceAngle(_self: b2RevoluteJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2RevoluteJoint_GetReferenceAngle'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2RevoluteJointWrapper.GetReferenceAngle: Single; cdecl;
begin
Result := b2RevoluteJoint_GetReferenceAngle(FHandle)
end;
function b2RevoluteJoint_GetJointAngle(_self: b2RevoluteJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2RevoluteJoint_GetJointAngle'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2RevoluteJointWrapper.GetJointAngle: Single; cdecl;
begin
Result := b2RevoluteJoint_GetJointAngle(FHandle)
end;
function b2RevoluteJoint_GetJointSpeed(_self: b2RevoluteJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2RevoluteJoint_GetJointSpeed'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2RevoluteJointWrapper.GetJointSpeed: Single; cdecl;
begin
Result := b2RevoluteJoint_GetJointSpeed(FHandle)
end;
function b2RevoluteJoint_IsLimitEnabled(_self: b2RevoluteJointHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2RevoluteJoint_IsLimitEnabled'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2RevoluteJointWrapper.IsLimitEnabled: Boolean; cdecl;
begin
Result := b2RevoluteJoint_IsLimitEnabled(FHandle)
end;
procedure b2RevoluteJoint_EnableLimit(_self: b2RevoluteJointHandle; flag: Boolean); cdecl; external LIB_NAME name _PU + 'b2RevoluteJoint_EnableLimit'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2RevoluteJointWrapper.EnableLimit(flag: Boolean); cdecl;
begin
b2RevoluteJoint_EnableLimit(FHandle, flag)
end;
function b2RevoluteJoint_GetLowerLimit(_self: b2RevoluteJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2RevoluteJoint_GetLowerLimit'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2RevoluteJointWrapper.GetLowerLimit: Single; cdecl;
begin
Result := b2RevoluteJoint_GetLowerLimit(FHandle)
end;
function b2RevoluteJoint_GetUpperLimit(_self: b2RevoluteJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2RevoluteJoint_GetUpperLimit'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2RevoluteJointWrapper.GetUpperLimit: Single; cdecl;
begin
Result := b2RevoluteJoint_GetUpperLimit(FHandle)
end;
procedure b2RevoluteJoint_SetLimits(_self: b2RevoluteJointHandle; lower: Single; upper: Single); cdecl; external LIB_NAME name _PU + 'b2RevoluteJoint_SetLimits'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2RevoluteJointWrapper.SetLimits(lower: Single; upper: Single); cdecl;
begin
b2RevoluteJoint_SetLimits(FHandle, lower, upper)
end;
function b2RevoluteJoint_IsMotorEnabled(_self: b2RevoluteJointHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2RevoluteJoint_IsMotorEnabled'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2RevoluteJointWrapper.IsMotorEnabled: Boolean; cdecl;
begin
Result := b2RevoluteJoint_IsMotorEnabled(FHandle)
end;
procedure b2RevoluteJoint_EnableMotor(_self: b2RevoluteJointHandle; flag: Boolean); cdecl; external LIB_NAME name _PU + 'b2RevoluteJoint_EnableMotor'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2RevoluteJointWrapper.EnableMotor(flag: Boolean); cdecl;
begin
b2RevoluteJoint_EnableMotor(FHandle, flag)
end;
procedure b2RevoluteJoint_SetMotorSpeed(_self: b2RevoluteJointHandle; speed: Single); cdecl; external LIB_NAME name _PU + 'b2RevoluteJoint_SetMotorSpeed'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2RevoluteJointWrapper.SetMotorSpeed(speed: Single); cdecl;
begin
b2RevoluteJoint_SetMotorSpeed(FHandle, speed)
end;
function b2RevoluteJoint_GetMotorSpeed(_self: b2RevoluteJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2RevoluteJoint_GetMotorSpeed'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2RevoluteJointWrapper.GetMotorSpeed: Single; cdecl;
begin
Result := b2RevoluteJoint_GetMotorSpeed(FHandle)
end;
procedure b2RevoluteJoint_SetMaxMotorTorque(_self: b2RevoluteJointHandle; torque: Single); cdecl; external LIB_NAME name _PU + 'b2RevoluteJoint_SetMaxMotorTorque'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2RevoluteJointWrapper.SetMaxMotorTorque(torque: Single); cdecl;
begin
b2RevoluteJoint_SetMaxMotorTorque(FHandle, torque)
end;
function b2RevoluteJoint_GetMaxMotorTorque(_self: b2RevoluteJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2RevoluteJoint_GetMaxMotorTorque'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2RevoluteJointWrapper.GetMaxMotorTorque: Single; cdecl;
begin
Result := b2RevoluteJoint_GetMaxMotorTorque(FHandle)
end;
function b2RevoluteJoint_GetMotorTorque(_self: b2RevoluteJointHandle; inv_dt: Single): Single; cdecl; external LIB_NAME name _PU + 'b2RevoluteJoint_GetMotorTorque'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2RevoluteJointWrapper.GetMotorTorque(inv_dt: Single): Single; cdecl;
begin
Result := b2RevoluteJoint_GetMotorTorque(FHandle, inv_dt)
end;
function b2RopeJointDef_Create: b2RopeJointDef; cdecl; external LIB_NAME name _PU + 'b2RopeJointDef_b2RopeJointDef_1'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2RopeJointDef.Create: b2RopeJointDef; cdecl;
begin
Result := b2RopeJointDef_Create;
end;
procedure b2RopeJoint_Destroy(_self: b2RopeJointHandle); cdecl; external LIB_NAME name _PU + 'b2RopeJoint_dtor'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2RopeJointWrapper.Destroy; cdecl;
begin
b2RopeJoint_Destroy(FHandle);
end;
class operator b2RopeJointWrapper.Implicit(handle: b2RopeJointHandle): b2RopeJointWrapper;
begin
Result.FHandle := handle;
end;
class operator b2RopeJointWrapper.Implicit(wrapper: b2RopeJointWrapper): b2RopeJointHandle;
begin
Result := wrapper.FHandle;
end;
function b2RopeJoint_GetType(_self: b2RopeJointHandle): b2JointType; cdecl; external LIB_NAME name _PU + 'b2RopeJoint_GetType'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2RopeJointWrapper.GetType: b2JointType; cdecl;
begin
Result := b2RopeJoint_GetType(FHandle)
end;
function b2RopeJoint_GetBodyA(_self: b2RopeJointHandle): b2BodyHandle; cdecl; external LIB_NAME name _PU + 'b2RopeJoint_GetBodyA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2RopeJointWrapper.GetBodyA: b2BodyHandle; cdecl;
begin
Result := b2RopeJoint_GetBodyA(FHandle)
end;
function b2RopeJoint_GetBodyB(_self: b2RopeJointHandle): b2BodyHandle; cdecl; external LIB_NAME name _PU + 'b2RopeJoint_GetBodyB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2RopeJointWrapper.GetBodyB: b2BodyHandle; cdecl;
begin
Result := b2RopeJoint_GetBodyB(FHandle)
end;
function b2RopeJoint_GetAnchorA(_self: b2RopeJointHandle): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2RopeJoint_GetAnchorA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2RopeJointWrapper.GetAnchorA: b2Vec2; cdecl;
begin
Result := b2RopeJoint_GetAnchorA(FHandle)
end;
function b2RopeJoint_GetAnchorB(_self: b2RopeJointHandle): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2RopeJoint_GetAnchorB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2RopeJointWrapper.GetAnchorB: b2Vec2; cdecl;
begin
Result := b2RopeJoint_GetAnchorB(FHandle)
end;
function b2RopeJoint_GetReactionForce(_self: b2RopeJointHandle; inv_dt: Single): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2RopeJoint_GetReactionForce'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2RopeJointWrapper.GetReactionForce(inv_dt: Single): b2Vec2; cdecl;
begin
Result := b2RopeJoint_GetReactionForce(FHandle, inv_dt)
end;
function b2RopeJoint_GetReactionTorque(_self: b2RopeJointHandle; inv_dt: Single): Single; cdecl; external LIB_NAME name _PU + 'b2RopeJoint_GetReactionTorque'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2RopeJointWrapper.GetReactionTorque(inv_dt: Single): Single; cdecl;
begin
Result := b2RopeJoint_GetReactionTorque(FHandle, inv_dt)
end;
function b2RopeJoint_GetNext(_self: b2RopeJointHandle): b2JointHandle; cdecl; external LIB_NAME name _PU + 'b2RopeJoint_GetNext'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2RopeJointWrapper.GetNext: b2JointHandle; cdecl;
begin
Result := b2RopeJoint_GetNext(FHandle)
end;
function b2RopeJoint_GetUserData(_self: b2RopeJointHandle): Pointer; cdecl; external LIB_NAME name _PU + 'b2RopeJoint_GetUserData'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2RopeJointWrapper.GetUserData: Pointer; cdecl;
begin
Result := b2RopeJoint_GetUserData(FHandle)
end;
procedure b2RopeJoint_SetUserData(_self: b2RopeJointHandle; data: Pointer); cdecl; external LIB_NAME name _PU + 'b2RopeJoint_SetUserData'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2RopeJointWrapper.SetUserData(data: Pointer); cdecl;
begin
b2RopeJoint_SetUserData(FHandle, data)
end;
function b2RopeJoint_IsActive(_self: b2RopeJointHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2RopeJoint_IsActive'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2RopeJointWrapper.IsActive: Boolean; cdecl;
begin
Result := b2RopeJoint_IsActive(FHandle)
end;
function b2RopeJoint_GetCollideConnected(_self: b2RopeJointHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2RopeJoint_GetCollideConnected'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2RopeJointWrapper.GetCollideConnected: Boolean; cdecl;
begin
Result := b2RopeJoint_GetCollideConnected(FHandle)
end;
procedure b2RopeJoint_Dump(_self: b2RopeJointHandle); cdecl; external LIB_NAME name _PU + 'b2RopeJoint_Dump'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2RopeJointWrapper.Dump; cdecl;
begin
b2RopeJoint_Dump(FHandle)
end;
procedure b2RopeJoint_ShiftOrigin(_self: b2RopeJointHandle; const [ref] newOrigin: b2Vec2); cdecl; external LIB_NAME name _PU + 'b2RopeJoint_ShiftOrigin'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2RopeJointWrapper.ShiftOrigin(const [ref] newOrigin: b2Vec2); cdecl;
begin
b2RopeJoint_ShiftOrigin(FHandle, newOrigin)
end;
function b2RopeJoint_GetLocalAnchorA(_self: b2RopeJointHandle): Pb2Vec2; cdecl; external LIB_NAME name _PU + 'b2RopeJoint_GetLocalAnchorA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2RopeJointWrapper.GetLocalAnchorA: Pb2Vec2; cdecl;
begin
Result := b2RopeJoint_GetLocalAnchorA(FHandle)
end;
function b2RopeJoint_GetLocalAnchorB(_self: b2RopeJointHandle): Pb2Vec2; cdecl; external LIB_NAME name _PU + 'b2RopeJoint_GetLocalAnchorB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2RopeJointWrapper.GetLocalAnchorB: Pb2Vec2; cdecl;
begin
Result := b2RopeJoint_GetLocalAnchorB(FHandle)
end;
procedure b2RopeJoint_SetMaxLength(_self: b2RopeJointHandle; length: Single); cdecl; external LIB_NAME name _PU + 'b2RopeJoint_SetMaxLength'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2RopeJointWrapper.SetMaxLength(length: Single); cdecl;
begin
b2RopeJoint_SetMaxLength(FHandle, length)
end;
function b2RopeJoint_GetMaxLength(_self: b2RopeJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2RopeJoint_GetMaxLength'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2RopeJointWrapper.GetMaxLength: Single; cdecl;
begin
Result := b2RopeJoint_GetMaxLength(FHandle)
end;
function b2RopeJoint_GetLimitState(_self: b2RopeJointHandle): b2LimitState; cdecl; external LIB_NAME name _PU + 'b2RopeJoint_GetLimitState'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2RopeJointWrapper.GetLimitState: b2LimitState; cdecl;
begin
Result := b2RopeJoint_GetLimitState(FHandle)
end;
function b2WeldJointDef_Create: b2WeldJointDef; cdecl; external LIB_NAME name _PU + 'b2WeldJointDef_b2WeldJointDef_1'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2WeldJointDef.Create: b2WeldJointDef; cdecl;
begin
Result := b2WeldJointDef_Create;
end;
procedure b2WeldJointDef_Initialize(_self: Pb2WeldJointDef; bodyA: b2BodyHandle; bodyB: b2BodyHandle; const [ref] anchor: b2Vec2); cdecl; external LIB_NAME name _PU + 'b2WeldJointDef_Initialize'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2WeldJointDef.Initialize(bodyA: b2BodyHandle; bodyB: b2BodyHandle; const [ref] anchor: b2Vec2); cdecl;
begin
b2WeldJointDef_Initialize(@Self, bodyA, bodyB, anchor)
end;
procedure b2WeldJoint_Destroy(_self: b2WeldJointHandle); cdecl; external LIB_NAME name _PU + 'b2WeldJoint_dtor'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2WeldJointWrapper.Destroy; cdecl;
begin
b2WeldJoint_Destroy(FHandle);
end;
class operator b2WeldJointWrapper.Implicit(handle: b2WeldJointHandle): b2WeldJointWrapper;
begin
Result.FHandle := handle;
end;
class operator b2WeldJointWrapper.Implicit(wrapper: b2WeldJointWrapper): b2WeldJointHandle;
begin
Result := wrapper.FHandle;
end;
function b2WeldJoint_GetType(_self: b2WeldJointHandle): b2JointType; cdecl; external LIB_NAME name _PU + 'b2WeldJoint_GetType'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WeldJointWrapper.GetType: b2JointType; cdecl;
begin
Result := b2WeldJoint_GetType(FHandle)
end;
function b2WeldJoint_GetBodyA(_self: b2WeldJointHandle): b2BodyHandle; cdecl; external LIB_NAME name _PU + 'b2WeldJoint_GetBodyA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WeldJointWrapper.GetBodyA: b2BodyHandle; cdecl;
begin
Result := b2WeldJoint_GetBodyA(FHandle)
end;
function b2WeldJoint_GetBodyB(_self: b2WeldJointHandle): b2BodyHandle; cdecl; external LIB_NAME name _PU + 'b2WeldJoint_GetBodyB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WeldJointWrapper.GetBodyB: b2BodyHandle; cdecl;
begin
Result := b2WeldJoint_GetBodyB(FHandle)
end;
function b2WeldJoint_GetAnchorA(_self: b2WeldJointHandle): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2WeldJoint_GetAnchorA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WeldJointWrapper.GetAnchorA: b2Vec2; cdecl;
begin
Result := b2WeldJoint_GetAnchorA(FHandle)
end;
function b2WeldJoint_GetAnchorB(_self: b2WeldJointHandle): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2WeldJoint_GetAnchorB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WeldJointWrapper.GetAnchorB: b2Vec2; cdecl;
begin
Result := b2WeldJoint_GetAnchorB(FHandle)
end;
function b2WeldJoint_GetReactionForce(_self: b2WeldJointHandle; inv_dt: Single): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2WeldJoint_GetReactionForce'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WeldJointWrapper.GetReactionForce(inv_dt: Single): b2Vec2; cdecl;
begin
Result := b2WeldJoint_GetReactionForce(FHandle, inv_dt)
end;
function b2WeldJoint_GetReactionTorque(_self: b2WeldJointHandle; inv_dt: Single): Single; cdecl; external LIB_NAME name _PU + 'b2WeldJoint_GetReactionTorque'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WeldJointWrapper.GetReactionTorque(inv_dt: Single): Single; cdecl;
begin
Result := b2WeldJoint_GetReactionTorque(FHandle, inv_dt)
end;
function b2WeldJoint_GetNext(_self: b2WeldJointHandle): b2JointHandle; cdecl; external LIB_NAME name _PU + 'b2WeldJoint_GetNext'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WeldJointWrapper.GetNext: b2JointHandle; cdecl;
begin
Result := b2WeldJoint_GetNext(FHandle)
end;
function b2WeldJoint_GetUserData(_self: b2WeldJointHandle): Pointer; cdecl; external LIB_NAME name _PU + 'b2WeldJoint_GetUserData'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WeldJointWrapper.GetUserData: Pointer; cdecl;
begin
Result := b2WeldJoint_GetUserData(FHandle)
end;
procedure b2WeldJoint_SetUserData(_self: b2WeldJointHandle; data: Pointer); cdecl; external LIB_NAME name _PU + 'b2WeldJoint_SetUserData'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2WeldJointWrapper.SetUserData(data: Pointer); cdecl;
begin
b2WeldJoint_SetUserData(FHandle, data)
end;
function b2WeldJoint_IsActive(_self: b2WeldJointHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2WeldJoint_IsActive'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WeldJointWrapper.IsActive: Boolean; cdecl;
begin
Result := b2WeldJoint_IsActive(FHandle)
end;
function b2WeldJoint_GetCollideConnected(_self: b2WeldJointHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2WeldJoint_GetCollideConnected'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WeldJointWrapper.GetCollideConnected: Boolean; cdecl;
begin
Result := b2WeldJoint_GetCollideConnected(FHandle)
end;
procedure b2WeldJoint_Dump(_self: b2WeldJointHandle); cdecl; external LIB_NAME name _PU + 'b2WeldJoint_Dump'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2WeldJointWrapper.Dump; cdecl;
begin
b2WeldJoint_Dump(FHandle)
end;
procedure b2WeldJoint_ShiftOrigin(_self: b2WeldJointHandle; const [ref] newOrigin: b2Vec2); cdecl; external LIB_NAME name _PU + 'b2WeldJoint_ShiftOrigin'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2WeldJointWrapper.ShiftOrigin(const [ref] newOrigin: b2Vec2); cdecl;
begin
b2WeldJoint_ShiftOrigin(FHandle, newOrigin)
end;
function b2WeldJoint_GetLocalAnchorA(_self: b2WeldJointHandle): Pb2Vec2; cdecl; external LIB_NAME name _PU + 'b2WeldJoint_GetLocalAnchorA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WeldJointWrapper.GetLocalAnchorA: Pb2Vec2; cdecl;
begin
Result := b2WeldJoint_GetLocalAnchorA(FHandle)
end;
function b2WeldJoint_GetLocalAnchorB(_self: b2WeldJointHandle): Pb2Vec2; cdecl; external LIB_NAME name _PU + 'b2WeldJoint_GetLocalAnchorB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WeldJointWrapper.GetLocalAnchorB: Pb2Vec2; cdecl;
begin
Result := b2WeldJoint_GetLocalAnchorB(FHandle)
end;
function b2WeldJoint_GetReferenceAngle(_self: b2WeldJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2WeldJoint_GetReferenceAngle'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WeldJointWrapper.GetReferenceAngle: Single; cdecl;
begin
Result := b2WeldJoint_GetReferenceAngle(FHandle)
end;
procedure b2WeldJoint_SetFrequency(_self: b2WeldJointHandle; hz: Single); cdecl; external LIB_NAME name _PU + 'b2WeldJoint_SetFrequency'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2WeldJointWrapper.SetFrequency(hz: Single); cdecl;
begin
b2WeldJoint_SetFrequency(FHandle, hz)
end;
function b2WeldJoint_GetFrequency(_self: b2WeldJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2WeldJoint_GetFrequency'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WeldJointWrapper.GetFrequency: Single; cdecl;
begin
Result := b2WeldJoint_GetFrequency(FHandle)
end;
procedure b2WeldJoint_SetDampingRatio(_self: b2WeldJointHandle; ratio: Single); cdecl; external LIB_NAME name _PU + 'b2WeldJoint_SetDampingRatio'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2WeldJointWrapper.SetDampingRatio(ratio: Single); cdecl;
begin
b2WeldJoint_SetDampingRatio(FHandle, ratio)
end;
function b2WeldJoint_GetDampingRatio(_self: b2WeldJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2WeldJoint_GetDampingRatio'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WeldJointWrapper.GetDampingRatio: Single; cdecl;
begin
Result := b2WeldJoint_GetDampingRatio(FHandle)
end;
function b2WheelJointDef_Create: b2WheelJointDef; cdecl; external LIB_NAME name _PU + 'b2WheelJointDef_b2WheelJointDef_1'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2WheelJointDef.Create: b2WheelJointDef; cdecl;
begin
Result := b2WheelJointDef_Create;
end;
procedure b2WheelJointDef_Initialize(_self: Pb2WheelJointDef; bodyA: b2BodyHandle; bodyB: b2BodyHandle; const [ref] anchor: b2Vec2; const [ref] axis: b2Vec2); cdecl; external LIB_NAME name _PU + 'b2WheelJointDef_Initialize'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2WheelJointDef.Initialize(bodyA: b2BodyHandle; bodyB: b2BodyHandle; const [ref] anchor: b2Vec2; const [ref] axis: b2Vec2); cdecl;
begin
b2WheelJointDef_Initialize(@Self, bodyA, bodyB, anchor, axis)
end;
procedure b2WheelJoint_Destroy(_self: b2WheelJointHandle); cdecl; external LIB_NAME name _PU + 'b2WheelJoint_dtor'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2WheelJointWrapper.Destroy; cdecl;
begin
b2WheelJoint_Destroy(FHandle);
end;
class operator b2WheelJointWrapper.Implicit(handle: b2WheelJointHandle): b2WheelJointWrapper;
begin
Result.FHandle := handle;
end;
class operator b2WheelJointWrapper.Implicit(wrapper: b2WheelJointWrapper): b2WheelJointHandle;
begin
Result := wrapper.FHandle;
end;
function b2WheelJoint_GetType(_self: b2WheelJointHandle): b2JointType; cdecl; external LIB_NAME name _PU + 'b2WheelJoint_GetType'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WheelJointWrapper.GetType: b2JointType; cdecl;
begin
Result := b2WheelJoint_GetType(FHandle)
end;
function b2WheelJoint_GetBodyA(_self: b2WheelJointHandle): b2BodyHandle; cdecl; external LIB_NAME name _PU + 'b2WheelJoint_GetBodyA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WheelJointWrapper.GetBodyA: b2BodyHandle; cdecl;
begin
Result := b2WheelJoint_GetBodyA(FHandle)
end;
function b2WheelJoint_GetBodyB(_self: b2WheelJointHandle): b2BodyHandle; cdecl; external LIB_NAME name _PU + 'b2WheelJoint_GetBodyB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WheelJointWrapper.GetBodyB: b2BodyHandle; cdecl;
begin
Result := b2WheelJoint_GetBodyB(FHandle)
end;
function b2WheelJoint_GetAnchorA(_self: b2WheelJointHandle): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2WheelJoint_GetAnchorA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WheelJointWrapper.GetAnchorA: b2Vec2; cdecl;
begin
Result := b2WheelJoint_GetAnchorA(FHandle)
end;
function b2WheelJoint_GetAnchorB(_self: b2WheelJointHandle): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2WheelJoint_GetAnchorB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WheelJointWrapper.GetAnchorB: b2Vec2; cdecl;
begin
Result := b2WheelJoint_GetAnchorB(FHandle)
end;
function b2WheelJoint_GetReactionForce(_self: b2WheelJointHandle; inv_dt: Single): b2Vec2; cdecl; external LIB_NAME name _PU + 'b2WheelJoint_GetReactionForce'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WheelJointWrapper.GetReactionForce(inv_dt: Single): b2Vec2; cdecl;
begin
Result := b2WheelJoint_GetReactionForce(FHandle, inv_dt)
end;
function b2WheelJoint_GetReactionTorque(_self: b2WheelJointHandle; inv_dt: Single): Single; cdecl; external LIB_NAME name _PU + 'b2WheelJoint_GetReactionTorque'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WheelJointWrapper.GetReactionTorque(inv_dt: Single): Single; cdecl;
begin
Result := b2WheelJoint_GetReactionTorque(FHandle, inv_dt)
end;
function b2WheelJoint_GetNext(_self: b2WheelJointHandle): b2JointHandle; cdecl; external LIB_NAME name _PU + 'b2WheelJoint_GetNext'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WheelJointWrapper.GetNext: b2JointHandle; cdecl;
begin
Result := b2WheelJoint_GetNext(FHandle)
end;
function b2WheelJoint_GetUserData(_self: b2WheelJointHandle): Pointer; cdecl; external LIB_NAME name _PU + 'b2WheelJoint_GetUserData'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WheelJointWrapper.GetUserData: Pointer; cdecl;
begin
Result := b2WheelJoint_GetUserData(FHandle)
end;
procedure b2WheelJoint_SetUserData(_self: b2WheelJointHandle; data: Pointer); cdecl; external LIB_NAME name _PU + 'b2WheelJoint_SetUserData'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2WheelJointWrapper.SetUserData(data: Pointer); cdecl;
begin
b2WheelJoint_SetUserData(FHandle, data)
end;
function b2WheelJoint_IsActive(_self: b2WheelJointHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2WheelJoint_IsActive'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WheelJointWrapper.IsActive: Boolean; cdecl;
begin
Result := b2WheelJoint_IsActive(FHandle)
end;
function b2WheelJoint_GetCollideConnected(_self: b2WheelJointHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2WheelJoint_GetCollideConnected'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WheelJointWrapper.GetCollideConnected: Boolean; cdecl;
begin
Result := b2WheelJoint_GetCollideConnected(FHandle)
end;
procedure b2WheelJoint_Dump(_self: b2WheelJointHandle); cdecl; external LIB_NAME name _PU + 'b2WheelJoint_Dump'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2WheelJointWrapper.Dump; cdecl;
begin
b2WheelJoint_Dump(FHandle)
end;
procedure b2WheelJoint_ShiftOrigin(_self: b2WheelJointHandle; const [ref] newOrigin: b2Vec2); cdecl; external LIB_NAME name _PU + 'b2WheelJoint_ShiftOrigin'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2WheelJointWrapper.ShiftOrigin(const [ref] newOrigin: b2Vec2); cdecl;
begin
b2WheelJoint_ShiftOrigin(FHandle, newOrigin)
end;
function b2WheelJoint_GetLocalAnchorA(_self: b2WheelJointHandle): Pb2Vec2; cdecl; external LIB_NAME name _PU + 'b2WheelJoint_GetLocalAnchorA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WheelJointWrapper.GetLocalAnchorA: Pb2Vec2; cdecl;
begin
Result := b2WheelJoint_GetLocalAnchorA(FHandle)
end;
function b2WheelJoint_GetLocalAnchorB(_self: b2WheelJointHandle): Pb2Vec2; cdecl; external LIB_NAME name _PU + 'b2WheelJoint_GetLocalAnchorB'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WheelJointWrapper.GetLocalAnchorB: Pb2Vec2; cdecl;
begin
Result := b2WheelJoint_GetLocalAnchorB(FHandle)
end;
function b2WheelJoint_GetLocalAxisA(_self: b2WheelJointHandle): Pb2Vec2; cdecl; external LIB_NAME name _PU + 'b2WheelJoint_GetLocalAxisA'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WheelJointWrapper.GetLocalAxisA: Pb2Vec2; cdecl;
begin
Result := b2WheelJoint_GetLocalAxisA(FHandle)
end;
function b2WheelJoint_GetJointTranslation(_self: b2WheelJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2WheelJoint_GetJointTranslation'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WheelJointWrapper.GetJointTranslation: Single; cdecl;
begin
Result := b2WheelJoint_GetJointTranslation(FHandle)
end;
function b2WheelJoint_GetJointSpeed(_self: b2WheelJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2WheelJoint_GetJointSpeed'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WheelJointWrapper.GetJointSpeed: Single; cdecl;
begin
Result := b2WheelJoint_GetJointSpeed(FHandle)
end;
function b2WheelJoint_IsMotorEnabled(_self: b2WheelJointHandle): Boolean; cdecl; external LIB_NAME name _PU + 'b2WheelJoint_IsMotorEnabled'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WheelJointWrapper.IsMotorEnabled: Boolean; cdecl;
begin
Result := b2WheelJoint_IsMotorEnabled(FHandle)
end;
procedure b2WheelJoint_EnableMotor(_self: b2WheelJointHandle; flag: Boolean); cdecl; external LIB_NAME name _PU + 'b2WheelJoint_EnableMotor'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2WheelJointWrapper.EnableMotor(flag: Boolean); cdecl;
begin
b2WheelJoint_EnableMotor(FHandle, flag)
end;
procedure b2WheelJoint_SetMotorSpeed(_self: b2WheelJointHandle; speed: Single); cdecl; external LIB_NAME name _PU + 'b2WheelJoint_SetMotorSpeed'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2WheelJointWrapper.SetMotorSpeed(speed: Single); cdecl;
begin
b2WheelJoint_SetMotorSpeed(FHandle, speed)
end;
function b2WheelJoint_GetMotorSpeed(_self: b2WheelJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2WheelJoint_GetMotorSpeed'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WheelJointWrapper.GetMotorSpeed: Single; cdecl;
begin
Result := b2WheelJoint_GetMotorSpeed(FHandle)
end;
procedure b2WheelJoint_SetMaxMotorTorque(_self: b2WheelJointHandle; torque: Single); cdecl; external LIB_NAME name _PU + 'b2WheelJoint_SetMaxMotorTorque'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2WheelJointWrapper.SetMaxMotorTorque(torque: Single); cdecl;
begin
b2WheelJoint_SetMaxMotorTorque(FHandle, torque)
end;
function b2WheelJoint_GetMaxMotorTorque(_self: b2WheelJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2WheelJoint_GetMaxMotorTorque'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WheelJointWrapper.GetMaxMotorTorque: Single; cdecl;
begin
Result := b2WheelJoint_GetMaxMotorTorque(FHandle)
end;
function b2WheelJoint_GetMotorTorque(_self: b2WheelJointHandle; inv_dt: Single): Single; cdecl; external LIB_NAME name _PU + 'b2WheelJoint_GetMotorTorque'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WheelJointWrapper.GetMotorTorque(inv_dt: Single): Single; cdecl;
begin
Result := b2WheelJoint_GetMotorTorque(FHandle, inv_dt)
end;
procedure b2WheelJoint_SetSpringFrequencyHz(_self: b2WheelJointHandle; hz: Single); cdecl; external LIB_NAME name _PU + 'b2WheelJoint_SetSpringFrequencyHz'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2WheelJointWrapper.SetSpringFrequencyHz(hz: Single); cdecl;
begin
b2WheelJoint_SetSpringFrequencyHz(FHandle, hz)
end;
function b2WheelJoint_GetSpringFrequencyHz(_self: b2WheelJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2WheelJoint_GetSpringFrequencyHz'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WheelJointWrapper.GetSpringFrequencyHz: Single; cdecl;
begin
Result := b2WheelJoint_GetSpringFrequencyHz(FHandle)
end;
procedure b2WheelJoint_SetSpringDampingRatio(_self: b2WheelJointHandle; ratio: Single); cdecl; external LIB_NAME name _PU + 'b2WheelJoint_SetSpringDampingRatio'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2WheelJointWrapper.SetSpringDampingRatio(ratio: Single); cdecl;
begin
b2WheelJoint_SetSpringDampingRatio(FHandle, ratio)
end;
function b2WheelJoint_GetSpringDampingRatio(_self: b2WheelJointHandle): Single; cdecl; external LIB_NAME name _PU + 'b2WheelJoint_GetSpringDampingRatio'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2WheelJointWrapper.GetSpringDampingRatio: Single; cdecl;
begin
Result := b2WheelJoint_GetSpringDampingRatio(FHandle)
end;
function b2MixFriction(friction1: Single; friction2: Single): Single; cdecl; external LIB_NAME name _PU + 'Dynamics_b2MixFriction'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2MixRestitution(restitution1: Single; restitution2: Single): Single; cdecl; external LIB_NAME name _PU + 'Dynamics_b2MixRestitution'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
initialization
{$IF (defined(CPUX64) or defined(CPUARM64))}
Assert(Sizeof(b2BodyDef) = 64, 'Size mismatch in b2BodyDef');
Assert(Sizeof(b2ContactEdge) = 32, 'Size mismatch in b2ContactEdge');
Assert(Sizeof(b2ContactRegister) = 24, 'Size mismatch in b2ContactRegister');
Assert(Sizeof(b2ContactSolverDef) = 64, 'Size mismatch in b2ContactSolverDef');
Assert(Sizeof(b2DistanceJointDef) = 72, 'Size mismatch in b2DistanceJointDef');
Assert(Sizeof(b2Fixture) = 72, 'Size mismatch in b2Fixture');
Assert(Sizeof(b2FixtureDef) = 40, 'Size mismatch in b2FixtureDef');
Assert(Sizeof(b2FixtureProxy) = 32, 'Size mismatch in b2FixtureProxy');
Assert(Sizeof(b2FrictionJointDef) = 64, 'Size mismatch in b2FrictionJointDef');
Assert(Sizeof(b2GearJointDef) = 64, 'Size mismatch in b2GearJointDef');
Assert(Sizeof(b2JointDef) = 40, 'Size mismatch in b2JointDef');
Assert(Sizeof(b2JointEdge) = 32, 'Size mismatch in b2JointEdge');
Assert(Sizeof(b2MotorJointDef) = 64, 'Size mismatch in b2MotorJointDef');
Assert(Sizeof(b2MouseJointDef) = 64, 'Size mismatch in b2MouseJointDef');
Assert(Sizeof(b2PrismaticJointDef) = 96, 'Size mismatch in b2PrismaticJointDef');
Assert(Sizeof(b2PulleyJointDef) = 88, 'Size mismatch in b2PulleyJointDef');
Assert(Sizeof(b2RevoluteJointDef) = 88, 'Size mismatch in b2RevoluteJointDef');
Assert(Sizeof(b2RopeJointDef) = 64, 'Size mismatch in b2RopeJointDef');
Assert(Sizeof(b2SolverData) = 40, 'Size mismatch in b2SolverData');
Assert(Sizeof(b2WeldJointDef) = 72, 'Size mismatch in b2WeldJointDef');
Assert(Sizeof(b2WheelJointDef) = 88, 'Size mismatch in b2WheelJointDef');
{$ELSE}
Assert(Sizeof(b2BodyDef) = 52, 'Size mismatch in b2BodyDef');
Assert(Sizeof(b2ContactEdge) = 16, 'Size mismatch in b2ContactEdge');
Assert(Sizeof(b2ContactRegister) = 12, 'Size mismatch in b2ContactRegister');
Assert(Sizeof(b2ContactSolverDef) = 44, 'Size mismatch in b2ContactSolverDef');
Assert(Sizeof(b2DistanceJointDef) = 48, 'Size mismatch in b2DistanceJointDef');
Assert(Sizeof(b2Fixture) = 44, 'Size mismatch in b2Fixture');
Assert(Sizeof(b2FixtureDef) = 28, 'Size mismatch in b2FixtureDef');
Assert(Sizeof(b2FixtureProxy) = 28, 'Size mismatch in b2FixtureProxy');
Assert(Sizeof(b2FrictionJointDef) = 44, 'Size mismatch in b2FrictionJointDef');
Assert(Sizeof(b2GearJointDef) = 32, 'Size mismatch in b2GearJointDef');
Assert(Sizeof(b2JointDef) = 20, 'Size mismatch in b2JointDef');
Assert(Sizeof(b2JointEdge) = 16, 'Size mismatch in b2JointEdge');
Assert(Sizeof(b2MotorJointDef) = 44, 'Size mismatch in b2MotorJointDef');
Assert(Sizeof(b2MouseJointDef) = 40, 'Size mismatch in b2MouseJointDef');
Assert(Sizeof(b2PrismaticJointDef) = 72, 'Size mismatch in b2PrismaticJointDef');
Assert(Sizeof(b2PulleyJointDef) = 64, 'Size mismatch in b2PulleyJointDef');
Assert(Sizeof(b2RevoluteJointDef) = 64, 'Size mismatch in b2RevoluteJointDef');
Assert(Sizeof(b2RopeJointDef) = 40, 'Size mismatch in b2RopeJointDef');
Assert(Sizeof(b2SolverData) = 32, 'Size mismatch in b2SolverData');
Assert(Sizeof(b2WeldJointDef) = 48, 'Size mismatch in b2WeldJointDef');
Assert(Sizeof(b2WheelJointDef) = 64, 'Size mismatch in b2WheelJointDef');
{$ENDIF}
Assert(Sizeof(b2ContactImpulse) = 20, 'Size mismatch in b2ContactImpulse');
Assert(Sizeof(b2ContactVelocityConstraint) = 156, 'Size mismatch in b2ContactVelocityConstraint');
Assert(Sizeof(b2Filter) = 6, 'Size mismatch in b2Filter');
Assert(Sizeof(b2Jacobian) = 16, 'Size mismatch in b2Jacobian');
Assert(Sizeof(b2Position) = 12, 'Size mismatch in b2Position');
Assert(Sizeof(b2Profile) = 32, 'Size mismatch in b2Profile');
Assert(Sizeof(b2TimeStep) = 24, 'Size mismatch in b2TimeStep');
Assert(Sizeof(b2Velocity) = 12, 'Size mismatch in b2Velocity');
Assert(Sizeof(b2VelocityConstraintPoint) = 36, 'Size mismatch in b2VelocityConstraintPoint');
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 2011-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit DSProjectLocationWizardPage;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, WizardAPI, ActnList, StdActns, StdCtrls, ExpertsUIWizard,
System.Actions;
type
TDSProjectLocationWizardFrame = class(TFrame, IExpertsWizardPageFrame)
Label1: TLabel;
LocationEdit: TEdit;
BrowseBtn: TButton;
ActionList1: TActionList;
BrowseForFolder1: TBrowseForFolder;
procedure BrowseForFolder1Accept(Sender: TObject);
procedure BrowseForFolder1BeforeExecute(Sender: TObject);
private
FPage: TCustomExpertsFrameWizardPage;
procedure LocationEditChange(Sender: TObject);
function LocationEditText: string;
function GetLeftMargin: Integer;
procedure SetLeftMargin(const Value: Integer);
function ValidateFields: Boolean;
function GetProjectLocation: string;
protected
{ IExpertsWizardPageFrame }
function ExpertsFrameValidatePage(ASender: TCustomExpertsWizardPage; var AHandled: Boolean): Boolean;
procedure ExpertsFrameUpdateInfo(ASender: TCustomExpertsWizardPage; var AHandled: Boolean);
procedure ExpertsFrameCreated(APage: TCustomExpertsFrameWizardPage);
procedure ExpertsFrameEnterPage(APage: TCustomExpertsFrameWizardPage);
{ Private declarations }
property LeftMargin: Integer read GetLeftMargin write SetLeftMargin;
public
{ Public declarations }
property ProjectLocation: string read GetProjectLocation;
end;
implementation
{$R *.dfm}
uses DSCreators, DSServerDsnResStrs, ToolsAPI, System.UITypes;
function SlashSep(const Path, S: string): string;
begin
if Path <> '' then
Result := IncludeTrailingPathDelimiter(Path) + S
else
Result := S;
end;
procedure TDSProjectLocationWizardFrame.BrowseForFolder1Accept(Sender: TObject);
begin
LocationEdit.Text := BrowseForFolder1.Folder;
LocationEditChange(nil);
end;
procedure TDSProjectLocationWizardFrame.LocationEditChange(Sender: TObject);
//var
// F: TSearchRec;
// Dir: string;
// SaveOnChange: TNotifyEvent;
begin
// if LocationEdit.Canvas.TextWidth(LocationEditText) > LocationEdit.ClientWidth then
// LocationEdit.Hint := LocationEditText
// else
// LocationEdit.Hint := '';
// SaveOnChange := LocationEdit.OnChange;
// LocationEdit.OnChange := nil;
// try
// if LocationEdit.Focused then
// begin
// if (Length(LocationEditText) > 0) and
// (AnsiCompareText(LocationEditText, FOldValue) = 0) then exit;
// Dir := IncludeTrailingPathDelimiter(LocationEditText);
// if DirectoryExists(Dir) and (FindFirst(Dir + '*.*', faDirectory, F) = 0) then // do not localize
// begin
// LocationEdit.ItemsEx.BeginUpdate;
// try
// LocationEdit.ItemsEx.Clear;
// with LocationEdit.ItemsEx.Add do
// Caption := LocationEditText;
// repeat
// if ((F.Attr and faDirectory) = faDirectory) and (F.Name <> '.') and
// (F.Name <> '..') then
// with LocationEdit.ItemsEx.Add do
// Caption := SlashSep(LocationEditText, F.Name);
// until FindNext(F) <> 0;
// FindClose(F);
// finally
// LocationEdit.ItemsEx.EndUpdate;
// end;
// end;
// FOldValue := LocationEditText;
// LocationEdit.Height := 150;
// end;
// finally
// LocationEdit.OnChange := SaveOnChange;
// end;
end;
procedure TDSProjectLocationWizardFrame.BrowseForFolder1BeforeExecute(
Sender: TObject);
var
LBaseDirectory: string;
begin
LBaseDirectory := ExtractFilePath(LocationEditText);
if DirectoryExists(LocationEditText) then
BrowseForFolder1.Folder := LocationEditText
else if DirectoryExists(LBaseDirectory) then
BrowseForFolder1.Folder := LBaseDirectory
// // This isn't likely to browse to the right location since the project
// // directory doesn't exist yet. We should however default this location
// // to the Borland projects directory or something reasonable...
// if FileExists(SlashSep(LocationEditText, '*.*')) then // do not localize
// BrowseForFolder1.Folder := LocationEditText
// else
// begin
// //BrowsForFolder1.Folder := IDEServices
// // Try defaulting it to the path minus the AppName path
// if (Pos(AppNameEdit.Text, LocationEditText) = Length(LocationEditText) - Length(AppNameEdit.Text) + 1) or
// (Pos(AppNameEdit.Text + '\', LocationEditText) = Length(LocationEditText) - Length(AppNameEdit.Text) + 1) then
// begin
// Dir := LocationEditText;
// Delete(Dir, Pos(AppNameEdit.Text, LocationEditText), MaxInt);
// BrowseForFolder1.Folder := Dir;
// end;
// end;
end;
const
sProjectDirTemplate = 'Project%d';
function DefaultProjectDirectory: string;
var
LTemplate: string;
I: Integer;
begin
LTemplate := IncludeTrailingPathDelimiter((BorlandIDEServices as IOTAServices).GetStartupDirectory) +
sProjectDirTemplate;
I := 1;
repeat
Result := Format(LTemplate, [I]);
Inc(I);
until not DirectoryExists(Result);
end;
procedure TDSProjectLocationWizardFrame.ExpertsFrameCreated(
APage: TCustomExpertsFrameWizardPage);
begin
LocationEdit.Text := DefaultProjectDirectory;
LeftMargin := ExpertsUIWizard.cExpertsLeftMargin;
FPage := APage;
FPage.Title := sLocationPageTitle;
FPage.Description := sLocationPageDescription;
end;
procedure TDSProjectLocationWizardFrame.ExpertsFrameEnterPage(
APage: TCustomExpertsFrameWizardPage);
begin
end;
procedure TDSProjectLocationWizardFrame.ExpertsFrameUpdateInfo(
ASender: TCustomExpertsWizardPage; var AHandled: Boolean);
begin
AHandled := True;
ASender.WizardInfo := sLocationPageInfo;
end;
function TDSProjectLocationWizardFrame.ExpertsFrameValidatePage(
ASender: TCustomExpertsWizardPage; var AHandled: Boolean): Boolean;
begin
AHandled := True;
Result := ValidateFields;
end;
function TDSProjectLocationWizardFrame.GetLeftMargin: Integer;
begin
Result := LocationEdit.Left;
end;
function TDSProjectLocationWizardFrame.GetProjectLocation: string;
begin
Result := LocationEdit.Text
end;
function TDSProjectLocationWizardFrame.LocationEditText: string;
begin
Result := LocationEdit.Text;
SetLength(Result, strlen(PChar(Result)));
end;
procedure TDSProjectLocationWizardFrame.SetLeftMargin(const Value: Integer);
begin
LocationEdit.Width := LocationEdit.Width - (Value - LocationEdit.Left);
LocationEdit.Left := Value;
Label1.Left := Value;
end;
function DirContainsRESTProject(Path: string): Boolean;
var
DirInfo: TSearchRec;
begin
Path := IncludeTrailingPathDelimiter(Path);
Result := DirectoryExists(Path) and
((FindFirst(Path + 'js\*.js', faAnyFile, DirInfo) = 0)or { do not localize }
(FindFirst(Path + 'cs\*.css', faAnyFile, DirInfo) = 0) or { do not localize }
(FindFirst(Path + 'template\*.html', FaAnyfile, DirInfo) = 0) ); { do not localize }
end;
function TDSProjectLocationWizardFrame.ValidateFields: Boolean;
var
LPath: string;
begin
Result := True;
try
LPath := Trim(Self.LocationEdit.Text);
if LPath = '' then
raise Exception.Create(sSpecifyDirectory);
if not IsValidIdent(ExtractFileName(LPath)) then
raise Exception.Create(sInvalidDirectorName);
if DirContainsRESTProject(LPath) then
raise Exception.CreateFmt(sDirectoryContainsAProject, [LPath]);
except
on E: Exception do
begin
Self.LocationEdit.SetFocus;
MessageDlg(E.Message, mtError, [mbOK], 0);
Result := False;
end;
end;
end;
end.
|
{**
* @Author: Du xinming
* @Contact: QQ<36511179>; Email<lndxm1979@163.com>
* @Version: 0.0
* @Date: 2018.11.25
* @Brief:
* @References:
* Introduction to Algorithms, Second Edition
* Jean-Philippe BEMPEL aka RDM, The Delphi Container Library
*}
unit org.algorithms.hashmap;
interface
uses
Winapi.Windows,
org.algorithms,
org.algorithms.tree;
type
THashFunction = function (Key: Integer): Integer of object;
THashNextFunction<TKey, TValue> = reference to function (var Node: TNode<TKey,TValue>): Boolean;
THashMap<TKey, TValue> = class
public type
TBuckets = array of TRBTree<TKey,TValue>;
private
FCS: TRTLCriticalSection;
FCapacity: Integer;
FCount: Integer;
FBuckets: TBuckets;
FHashFunction: THashFunction;
FKeyConvert: TValueConvert<TKey>;
FKeyCompare: TValueCompare<TKey>;
FValueCompare: TValueCompare<TValue>;
FKeyNotify: TValueNotify<TKey>;
FValueNotify: TValueNotify<TValue>;
function GetCount: Integer;
function HashMul(Key: Integer): Integer;
public
procedure Clear;
function ContainsKey(Key: TKey): Boolean;
function GetValue(Key: TKey): TValue;
function IsEmpty: Boolean;
procedure PutValue(Key: TKey; Value: TValue);
function Remove(Key: TKey): TValue;
function GetNexter: THashNextFunction<TKey, TValue>;
public
constructor Create(Capacity: Integer); overload;
destructor Destroy; override;
property HashFunction: THashFunction read FHashFunction write FHashFunction;
property OnKeyConvert: TValueConvert<TKey> read FKeyConvert write FKeyConvert;
property OnKeyCompare: TValueCompare<TKey> read FKeyCompare write FKeyCompare;
property OnValueCompare: TValueCompare<TValue> read FValueCompare write FValueCompare;
property OnKeyNotify: TValueNotify<TKey> read FKeyNotify write FKeyNotify;
property OnValueNotify: TValueNotify<TValue> read FValueNotify write FValueNotify;
property Count: Integer read GetCount;
{$IfDef TEST_ALGORITHMS}
property Capacity: Integer read FCapacity;
property Buckets: TBuckets read FBuckets;
{$Endif}
end;
implementation
{ THashMap<TKey, TValue> }
procedure THashMap<TKey, TValue>.Clear;
var
I: Integer;
begin
EnterCriticalSection(FCS);
try
for I := 0 to FCapacity - 1 do begin
if FBuckets[I] <> nil then begin
FBuckets[I].Free();
FBuckets[I] := nil;
end;
end;
FCount := 0;
finally
LeaveCriticalSection(FCS);
end;
end;
function THashMap<TKey, TValue>.ContainsKey(Key: TKey): Boolean;
var
Index: Integer;
Bucket: TRBTree<TKey, TValue>;
begin
Result := False;
EnterCriticalSection(FCS);
try
Index := FHashFunction(FKeyConvert(Key));
if FBuckets[Index] <> nil then
Result := FBuckets[Index].Search(Key) <> nil;
finally
LeaveCriticalSection(FCS);
end;
end;
constructor THashMap<TKey, TValue>.Create(Capacity: Integer);
begin
FCapacity := Capacity;
FCount := 0;
SetLength(FBuckets, FCapacity);
FHashFunction := HashMul;
InitializeCriticalSection(FCS);
end;
destructor THashMap<TKey, TValue>.Destroy;
begin
Clear();
DeleteCriticalSection(FCS);
inherited;
end;
function THashMap<TKey, TValue>.GetCount: Integer;
begin
EnterCriticalSection(FCS);
try
Result := FCount;
finally
LeaveCriticalSection(FCS);
end;
end;
function THashMap<TKey, TValue>.GetNexter: THashNextFunction<TKey, TValue>;
var
I: Integer;
NextNode: TNode<TKey, TValue>;
begin
I := 0;
NextNode := nil;
while (FBuckets[I] = nil) and (I < FCapacity) do Inc(I);
if I < FCapacity then
NextNode := FBuckets[I].Minimum(FBuckets[I].Root);
Result := function (var Node: TNode<TKey,TValue>): Boolean
begin
Node := NextNode;
Result := Node <> nil;
if Result then begin
NextNode := FBuckets[I].Successor(NextNode);
if (NextNode = nil) and (I + 1 < FCapacity) then begin
Inc(I);
while (FBuckets[I] = nil) and (I < FCapacity) do Inc(I);
if I < FCapacity then
NextNode := FBuckets[I].Minimum(FBuckets[I].Root);
end;
end;
end;
end;
function THashMap<TKey, TValue>.GetValue(Key: TKey): TValue;
var
Index: Integer;
Node: TNode<TKey, TValue>;
begin
Result := Default(TValue);
EnterCriticalSection(FCS);
try
Index := FHashFunction(FKeyConvert(Key));
if FBuckets[Index] <> nil then begin
Node := FBuckets[Index].Search(Key);
if Node <> nil then begin
Result := Node.Value;
end;
end;
finally
LeaveCriticalSection(FCS);
end;
end;
function THashMap<TKey, TValue>.HashMul(Key: Integer): Integer;
const
A = 0.6180339887; // (sqrt(5) - 1) / 2
begin
Result := Trunc(FCapacity * (Frac(Key * A)));
end;
function THashMap<TKey, TValue>.IsEmpty: Boolean;
begin
Result := FCount = 0;
end;
procedure THashMap<TKey, TValue>.PutValue(Key: TKey; Value: TValue);
var
Index: Integer;
begin
if FKeyCompare(Key, Default(TKey)) = 0 then Exit;
if FValueCompare(Value, Default(TValue)) = 0 then Exit;
EnterCriticalSection(FCS);
try
Index := FHashFunction(FKeyConvert(Key));
if FBuckets[Index] = nil then begin
FBuckets[Index] := TRBTree<TKey,TValue>.Create();
FBuckets[Index].OnKeyCompare := FKeyCompare;
FBuckets[Index].OnKeyNotify := FKeyNotify;
FBuckets[Index].OnValueNotify := FValueNotify;
end;
FBuckets[Index].Insert(Key, Value);
Inc(FCount);
finally
LeaveCriticalSection(FCS);
end;
end;
function THashMap<TKey, TValue>.Remove(Key: TKey): TValue;
var
Index: Integer;
Node: TNode<TKey, TValue>;
begin
Result := Default(TValue);
EnterCriticalSection(FCS);
try
Index := FHashFunction(FKeyConvert(Key));
if FBuckets[Index] <> nil then begin
Node := FBuckets[Index].Search(Key);
if Node <> nil then begin
Result := Node.Value;
FBuckets[Index].Delete(Node);
if Assigned(FKeyNotify) then
FKeyNotify(Node.Key, atDelete);
Node.Free();
Dec(FCount);
end;
end;
finally
LeaveCriticalSection(FCS);
end;
end;
end.
|
{
GMMarkerFMX unit
ES: contiene las clases necesarias para mostrar marcadores FMX en un mapa de
Google Maps mediante el componente TGMMap
EN: includes the base classes needed to show FMX markers on Google Map map using
the component TGMMap
=========================================================================
MODO DE USO/HOW TO USE
ES: poner el componente en el formulario, linkarlo a un TGMMap y poner los
marcadores a mostrar
EN: put the component into a form, link to a TGMMap and put the markers to show
=========================================================================
History:
ver 1.0.0
ES:
nuevo: se añade la propiedad TMarker.StyledMarker.
nuevo: se añade la propiedad TMarker.ColoredMarker.
EN:
new: TMarker.StyledMarker property is added.
new: TMarker.ColoredMarker property is added.
ver 0.1.9
ES:
nuevo: documentación
nuevo: se hace compatible con FireMonkey
EN:
new: documentation
new: now compatible with FireMonkey
=========================================================================
IMPORTANTE PROGRAMADORES: Por favor, si tienes comentarios, mejoras,
ampliaciones, errores y/o cualquier otro tipo de sugerencia, envíame un correo a:
gmlib@cadetill.com
IMPORTANT PROGRAMMERS: please, if you have comments, improvements, enlargements,
errors and/or any another type of suggestion, please send me a mail to:
gmlib@cadetill.com
=========================================================================
Copyright (©) 2012, by Xavier Martinez (cadetill)
@author Xavier Martinez (cadetill)
@web http://www.cadetill.com
}
{*------------------------------------------------------------------------------
The GMMarker unit includes the classes needed to show FMX markers on Google Map map using the component TGMMap.
@author Xavier Martinez (cadetill)
@version 1.5.0
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
La unit GMMarker contiene las clases bases necesarias para mostrar marcadores FMX en un mapa de Google Maps mediante el componente TGMMap
@author Xavier Martinez (cadetill)
@version 1.5.0
-------------------------------------------------------------------------------}
unit GMMarkerFMX;
interface
uses
System.Classes, System.UITypes,
GMMarker;
type
TMarker = class;
{*------------------------------------------------------------------------------
Features for ColoredMarker type marker.
Sorry, I lost the reference for more information.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Características para un marcador de tipo ColoredMarker.
Lo siento, he perdido la referencia para más información.
-------------------------------------------------------------------------------}
TColoredMarker = class(TCustomColoredMarker)
private
{*------------------------------------------------------------------------------
Stroke color.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Color del trazo.
-------------------------------------------------------------------------------}
FStrokeColor: TAlphaColor;
{*------------------------------------------------------------------------------
Corner color.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Color de la esquina.
-------------------------------------------------------------------------------}
FCornerColor: TAlphaColor;
{*------------------------------------------------------------------------------
Fill color.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Color de relleno.
-------------------------------------------------------------------------------}
FPrimaryColor: TAlphaColor;
procedure SetCornerColor(const Value: TAlphaColor);
procedure SetPrimaryColor(const Value: TAlphaColor);
procedure SetStrokeColor(const Value: TAlphaColor);
protected
function GetCornerColor: string; override;
function GetPrimaryColor: string; override;
function GetStrokeColor: string; override;
public
{*------------------------------------------------------------------------------
Constructor class
@param aOwner Owner
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Constructor de la clase
@param aOwner Propietario
-------------------------------------------------------------------------------}
constructor Create(aOwner: TMarker); reintroduce; virtual;
procedure Assign(Source: TPersistent); override;
published
property PrimaryColor: TAlphaColor read FPrimaryColor write SetPrimaryColor default TAlphaColorRec.Red;
property StrokeColor: TAlphaColor read FStrokeColor write SetStrokeColor default TAlphaColorRec.Black;
property CornerColor: TAlphaColor read FCornerColor write SetCornerColor default TAlphaColorRec.White;
end;
{*------------------------------------------------------------------------------
Features for ColoredMarker type marker.
More information at http://google-maps-utility-library-v3.googlecode.com/svn/trunk/styledmarker/docs/reference.html
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Características para un marcador de tipo ColoredMarker.
Más información en http://google-maps-utility-library-v3.googlecode.com/svn/trunk/styledmarker/docs/reference.html
-------------------------------------------------------------------------------}
TStyledMarker = class(TCustomStyledMarker)
private
{*------------------------------------------------------------------------------
Star color.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Color de la estrella.
-------------------------------------------------------------------------------}
FStarColor: TAlphaColor;
{*------------------------------------------------------------------------------
Text color.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Color del texto.
-------------------------------------------------------------------------------}
FTextColor: TAlphaColor;
{*------------------------------------------------------------------------------
Background color.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Color de fondo.
-------------------------------------------------------------------------------}
FBackgroundColor: TAlphaColor;
procedure SetBackgroundColor(const Value: TAlphaColor);
procedure SetStarColor(const Value: TAlphaColor);
procedure SetTextColor(const Value: TAlphaColor);
protected
function GetBackgroundColor: string; override;
function GetTextColor: string; override;
function GetStarColor: string; override;
public
{*------------------------------------------------------------------------------
Constructor class
@param aOwner Owner
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Constructor de la clase
@param aOwner Propietario
-------------------------------------------------------------------------------}
constructor Create(aOwner: TMarker); reintroduce; virtual;
procedure Assign(Source: TPersistent); override;
published
property BackgroundColor: TAlphaColor read FBackgroundColor write SetBackgroundColor default TAlphaColorRec.Red;
property TextColor: TAlphaColor read FTextColor write SetTextColor default TAlphaColorRec.Black;
property StarColor: TAlphaColor read FStarColor write SetStarColor default TAlphaColorRec.Lime;
end;
{*------------------------------------------------------------------------------
Features for Border property of TStyleLabel class.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Características para la propiedad Border de la clase TStyleLabel.
-------------------------------------------------------------------------------}
TGMBorder = class(TCustomGMBorder)
private
{*------------------------------------------------------------------------------
Border color.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Color del borde.
-------------------------------------------------------------------------------}
FColor: TAlphaColor;
procedure SetColor(const Value: TAlphaColor);
public
{*------------------------------------------------------------------------------
Constructor class
@param aOwner Owner
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Constructor de la clase
@param aOwner Propietario
-------------------------------------------------------------------------------}
constructor Create(aOwner: TMarker); reintroduce; virtual;
procedure Assign(Source: TPersistent); override;
published
property Color: TAlphaColor read FColor write SetColor;
end;
{*------------------------------------------------------------------------------
Features for Font property of TStyleLabel class.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Características para la propiedad Font de la clase TStyleLabel.
-------------------------------------------------------------------------------}
TGMFont = class(TCustomGMFont)
private
{*------------------------------------------------------------------------------
Font color.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Color de la fuente.
-------------------------------------------------------------------------------}
FColor: TAlphaColor;
procedure SetColor(const Value: TAlphaColor);
public
{*------------------------------------------------------------------------------
Constructor class
@param aOwner Owner
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Constructor de la clase
@param aOwner Propietario
-------------------------------------------------------------------------------}
constructor Create(aOwner: TMarker); reintroduce; virtual;
procedure Assign(Source: TPersistent); override;
published
property Color: TAlphaColor read FColor write SetColor;
end;
{*------------------------------------------------------------------------------
Features for mtStyledMarker type marker.
It is programmed but can not be selected because it does not work well with IE (TWebBrowser).
More information at http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerwithlabel/docs/reference.html
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Características para un marcador de tipo mtStyledMarker.
Está programado pero no se puede seleccionar debido a que no funciona bien con el IE (TWebBrowser).
Más información en http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerwithlabel/docs/reference.html
-------------------------------------------------------------------------------}
TStyleLabel = class(TCustomStyleLabel)
private
{*------------------------------------------------------------------------------
Background color.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Color de fondo.
-------------------------------------------------------------------------------}
FBackground: TAlphaColor;
procedure SetBackground(const Value: TAlphaColor);
public
{*------------------------------------------------------------------------------
Constructor class
@param aOwner Owner
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Constructor de la clase
@param aOwner Propietario
-------------------------------------------------------------------------------}
constructor Create(aOwner: TMarker); reintroduce; virtual;
procedure Assign(Source: TPersistent); override;
published
property Background: TAlphaColor read FBackground write SetBackground;
end;
{*------------------------------------------------------------------------------
Class for markers.
More information at https://developers.google.com/maps/documentation/javascript/reference?hl=en#Marker
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Clase para los marcadores.
Más información en https://developers.google.com/maps/documentation/javascript/reference?hl=en#Marker
-------------------------------------------------------------------------------}
TMarker = class(TCustomMarker)
private
{*------------------------------------------------------------------------------
Features applicable when marker type is mtStyledMarker.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Características aplicables cuando el marcador es de tipo mtStyledMarker.
-------------------------------------------------------------------------------}
FStyledMarker: TStyledMarker;
{*------------------------------------------------------------------------------
Features applicable when marker type is mtColored.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Características aplicables cuando el marcador es de tipo mtColored.
-------------------------------------------------------------------------------}
FColoredMarker: TColoredMarker;
protected
procedure CreatePropertiesWithColor; override;
function ColoredMarkerToStr: string; override;
function StyledMarkerToStr: string; override;
public
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
published
property ColoredMarker: TColoredMarker read FColoredMarker write FColoredMarker;
property StyledMarker: TStyledMarker read FStyledMarker write FStyledMarker;
end;
{*------------------------------------------------------------------------------
Class for markers collection.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Clase para la colección de marcadores.
-------------------------------------------------------------------------------}
TMarkers = class(TCustomMarkers)
private
procedure SetItems(I: Integer; const Value: TMarker);
function GetItems(I: Integer): TMarker;
protected
function GetOwner: TPersistent; override;
public
function Add: TMarker;
function Insert(Index: Integer): TMarker;
{*------------------------------------------------------------------------------
Lists the markers in the collection.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Lista de marcadores en la colección.
-------------------------------------------------------------------------------}
property Items[I: Integer]: TMarker read GetItems write SetItems; default;
end;
{*------------------------------------------------------------------------------
Class management of markers.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Clase para la gestión de marcadores.
-------------------------------------------------------------------------------}
TGMMarker = class(TCustomGMMarker)
private
function GetItems(I: Integer): TMarker;
public
function Add(Lat: Real = 0; Lng: Real = 0; Title: string = ''): TMarker;
{*------------------------------------------------------------------------------
Array with the collection items.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Array con la colección de elementos.
-------------------------------------------------------------------------------}
property Items[I: Integer]: TMarker read GetItems; default;
end;
implementation
uses
System.SysUtils,
GMFunctionsFMX, GMConstants;
{ TColoredMarker }
procedure TColoredMarker.Assign(Source: TPersistent);
begin
inherited;
if Source is TColoredMarker then
begin
CornerColor := TColoredMarker(Source).CornerColor;
StrokeColor := TColoredMarker(Source).StrokeColor;
PrimaryColor := TColoredMarker(Source).PrimaryColor;
end;
end;
constructor TColoredMarker.Create(aOwner: TMarker);
begin
inherited Create(aOwner);
FStrokeColor := TAlphaColorRec.Black;
FCornerColor := TAlphaColorRec.White;
FPrimaryColor := TAlphaColorRec.Red;
end;
function TColoredMarker.GetCornerColor: string;
begin
Result := TTransform.TColorToStr(FCornerColor);
end;
function TColoredMarker.GetPrimaryColor: string;
begin
Result := TTransform.TColorToStr(FPrimaryColor);
end;
function TColoredMarker.GetStrokeColor: string;
begin
Result := TTransform.TColorToStr(FStrokeColor);
end;
procedure TColoredMarker.SetCornerColor(const Value: TAlphaColor);
begin
if FCornerColor = Value then Exit;
FCornerColor := Value;
if not Assigned(FMarker) then Exit;
TMarker(FMarker).ChangeProperties;
if Assigned(TGMMarker(TMarkers(TMarker(FMarker).Collection).FGMLinkedComponent).OnColoredMarkerChange) then
TGMMarker(TMarkers(TMarker(FMarker).Collection).FGMLinkedComponent).OnColoredMarkerChange(
TGMMarker(TMarkers(TMarker(FMarker).Collection).FGMLinkedComponent),
FMarker.Index,
FMarker);
end;
procedure TColoredMarker.SetPrimaryColor(const Value: TAlphaColor);
begin
if FPrimaryColor = Value then Exit;
FPrimaryColor := Value;
if not Assigned(FMarker) then Exit;
TMarker(FMarker).ChangeProperties;
if Assigned(TGMMarker(TMarkers(TMarker(FMarker).Collection).FGMLinkedComponent).OnColoredMarkerChange) then
TGMMarker(TMarkers(TMarker(FMarker).Collection).FGMLinkedComponent).OnColoredMarkerChange(
TGMMarker(TMarkers(TMarker(FMarker).Collection).FGMLinkedComponent),
FMarker.Index,
FMarker);
end;
procedure TColoredMarker.SetStrokeColor(const Value: TAlphaColor);
begin
if FStrokeColor = Value then Exit;
FStrokeColor := Value;
if not Assigned(FMarker) then Exit;
TMarker(FMarker).ChangeProperties;
if Assigned(TGMMarker(TMarkers(TMarker(FMarker).Collection).FGMLinkedComponent).OnColoredMarkerChange) then
TGMMarker(TMarkers(TMarker(FMarker).Collection).FGMLinkedComponent).OnColoredMarkerChange(
TGMMarker(TMarkers(FMarker.Collection).FGMLinkedComponent),
FMarker.Index,
FMarker);
end;
{ TStyledMarker }
procedure TStyledMarker.Assign(Source: TPersistent);
begin
inherited;
if Source is TStyledMarker then
begin
BackgroundColor := TStyledMarker(Source).BackgroundColor;
TextColor := TStyledMarker(Source).TextColor;
StarColor := TStyledMarker(Source).StarColor;
end;
end;
constructor TStyledMarker.Create(aOwner: TMarker);
begin
inherited Create(aOwner);
FBackgroundColor := TAlphaColorRec.Red;
FTextColor := TAlphaColorRec.Black;
FStarColor := TAlphaColorRec.Lime;
end;
function TStyledMarker.GetBackgroundColor: string;
begin
Result := TTransform.TColorToStr(FBackgroundColor);
end;
function TStyledMarker.GetStarColor: string;
begin
Result := TTransform.TColorToStr(FStarColor);
end;
function TStyledMarker.GetTextColor: string;
begin
Result := TTransform.TColorToStr(FTextColor);
end;
procedure TStyledMarker.SetBackgroundColor(const Value: TAlphaColor);
begin
if FBackgroundColor = Value then Exit;
FBackgroundColor := Value;
if not Assigned(FMarker) then Exit;
TMarker(FMarker).ChangeProperties;
if Assigned(TGMMarker(TMarkers(TMarker(FMarker).Collection).FGMLinkedComponent).OnStyledMarkerChange) then
TGMMarker(TMarkers(TMarker(FMarker).Collection).FGMLinkedComponent).OnStyledMarkerChange(
TGMMarker(TMarkers(TMarker(FMarker).Collection).FGMLinkedComponent),
FMarker.Index,
FMarker);
end;
procedure TStyledMarker.SetStarColor(const Value: TAlphaColor);
begin
if FStarColor = Value then Exit;
FStarColor := Value;
if not Assigned(FMarker) then Exit;
TMarker(FMarker).ChangeProperties;
if Assigned(TGMMarker(TMarkers(TMarker(FMarker).Collection).FGMLinkedComponent).OnStyledMarkerChange) then
TGMMarker(TMarkers(TMarker(FMarker).Collection).FGMLinkedComponent).OnStyledMarkerChange(
TGMMarker(TMarkers(TMarker(FMarker).Collection).FGMLinkedComponent),
FMarker.Index,
FMarker);
end;
procedure TStyledMarker.SetTextColor(const Value: TAlphaColor);
begin
if FTextColor = Value then Exit;
FTextColor := Value;
if not Assigned(FMarker) then Exit;
TMarker(FMarker).ChangeProperties;
if Assigned(TGMMarker(TMarkers(TMarker(FMarker).Collection).FGMLinkedComponent).OnStyledMarkerChange) then
TGMMarker(TMarkers(TMarker(FMarker).Collection).FGMLinkedComponent).OnStyledMarkerChange(
TGMMarker(TMarkers(TMarker(FMarker).Collection).FGMLinkedComponent),
FMarker.Index,
FMarker);
end;
{ TGMBorder }
procedure TGMBorder.Assign(Source: TPersistent);
begin
inherited;
if Source is TGMBorder then
begin
Color := TGMBorder(Source).Color;
end
end;
constructor TGMBorder.Create(aOwner: TMarker);
begin
inherited Create(aOwner);
FColor := TAlphaColorRec.Black;
end;
procedure TGMBorder.SetColor(const Value: TAlphaColor);
begin
FColor := Value;
end;
{ TGMFont }
procedure TGMFont.Assign(Source: TPersistent);
begin
inherited;
if Source is TGMFont then
begin
Color := TGMFont(Source).Color;
end;
end;
constructor TGMFont.Create(aOwner: TMarker);
begin
inherited Create(aOwner);
FColor := TAlphaColorRec.Black;
end;
procedure TGMFont.SetColor(const Value: TAlphaColor);
begin
FColor := Value;
end;
{ TStyleLabel }
procedure TStyleLabel.Assign(Source: TPersistent);
begin
inherited;
if Source is TStyleLabel then
begin
Background := TStyleLabel(Source).Background;
end;
end;
constructor TStyleLabel.Create(aOwner: TMarker);
begin
inherited Create(aOwner);
FBackground := TAlphaColorRec.White;
Border := TGMBorder.Create(aOwner);
Font := TGMFont.Create(aOwner);
end;
procedure TStyleLabel.SetBackground(const Value: TAlphaColor);
begin
FBackground := Value;
end;
{ TMarker }
procedure TMarker.Assign(Source: TPersistent);
begin
inherited;
if Source is TMarker then
begin
ColoredMarker.Assign(TMarker(Source).ColoredMarker);
StyledMarker.Assign(TMarker(Source).StyledMarker);
end;
end;
function TMarker.ColoredMarkerToStr: string;
begin
Result := Format(StrColoredMarker, [
ColoredMarker.Width,
ColoredMarker.Height,
StringReplace(ColoredMarker.GetCornerColor, '#', '', [rfReplaceAll]),
StringReplace(ColoredMarker.GetPrimaryColor, '#', '', [rfReplaceAll]),
StringReplace(ColoredMarker.GetStrokeColor, '#', '', [rfReplaceAll])
]);
end;
procedure TMarker.CreatePropertiesWithColor;
begin
inherited;
ColoredMarker := TColoredMarker.Create(Self);
StyledMarker := TStyledMarker.Create(Self);
end;
destructor TMarker.Destroy;
begin
if Assigned(FColoredMarker) then FreeAndNil(FColoredMarker);
if Assigned(FStyledMarker) then FreeAndNil(FStyledMarker);
inherited;
end;
function TMarker.StyledMarkerToStr: string;
begin
Result := Format('%s,%s,%s,%s,%s', [
QuotedStr(TTransform.StyledIconToStr(StyledMarker.StyledIcon)),
QuotedStr(StyledMarker.GetBackgroundColor),
QuotedStr(StyledMarker.GetTextColor),
QuotedStr(StyledMarker.GetStarColor),
LowerCase(TTransform.GMBoolToStr(StyledMarker.ShowStar, True))
]);
end;
{ TMarkers }
function TMarkers.Add: TMarker;
begin
Result := TMarker(inherited Add);
end;
function TMarkers.GetItems(I: Integer): TMarker;
begin
Result := TMarker(inherited Items[I]);
end;
function TMarkers.GetOwner: TPersistent;
begin
Result := TGMMarker(inherited GetOwner);
end;
function TMarkers.Insert(Index: Integer): TMarker;
begin
Result := TMarker(inherited Insert(Index));
end;
procedure TMarkers.SetItems(I: Integer; const Value: TMarker);
begin
inherited SetItem(I, Value);
end;
{ TGMMarker }
function TGMMarker.Add(Lat, Lng: Real; Title: string): TMarker;
begin
Result := TMarker(inherited Add(Lat, Lng, Title));
end;
function TGMMarker.GetItems(I: Integer): TMarker;
begin
Result := TMarker(inherited Items[i]);
end;
end.
|
{*******************************************************************************
Класс для использования OPENSSL, что бы юзать RSA - Anton Rodin 2014
*******************************************************************************}
unit ExtendedSSL;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,
{%H-}
OpenSSL,
{%H+}
dynlibs, Dialogs;
const
PUB_EXP = 3;
const
RSA_STATE_NONE = -1;
RSA_STATE_PAIR = 0;
RSA_STATE_OPEN = 1;
RSA_STATE_PRIV = 2;
type
TPEM_write_bio_RSAPrivateKey = function(Pri: PBIO; KeyPair: PRSA;
var1, var2, var3, var4, var5: pointer): integer; cdecl;
TPEM_write_bio_RSAPublicKey = function(Pri: PBIO; KeyPair: PRSA): integer; cdecl;
TPEM_read_bio_RSA_PUBKEY = function(keybio: PBIO; rsa: PPRSA;
Pass: Pointer; CallBack: Pointer): PRSA; cdecl;
TPEM_read_bio_RSAPrivateKey = function(keybio: PBIO; rsa: PPRSA;
Pass: Pointer; CallBack: Pointer): PRSA; cdecl;
TPEM_read_bio_RSAPublicKey = function(keybio: PBIO; rsa: PPRSA;
Pass: Pointer; CallBack: Pointer): PRSA; cdecl;
type
{ TCustomRSA }
TCustomRSA = class(TObject)
PubKey: PRSA;
PriKey: PRSA;
private
ErrMsg: PChar;
public
constructor Create;
destructor Destroy; override;
public
PrivateKey: string;
PublicKey: string;
KeySize: integer;
procedure GenKeys;
function Encrypt(var OrigMsg: PByte; LenMsg: integer; var EncMsg: PByte;
var EncLen: integer): integer;
function Decrypt(var OrigMsg: PByte; LenMsg: integer; var EncMsg: PByte;
var EncLen: integer): integer;
procedure CloseKeys;
public
function PemToRsa(Pem: Pointer; Flag: integer = 0): PRSA;
procedure SaveKeyPair(PathToPubKey, PathToPriKey: string);
public
procedure LoadPubKeyFromFile(FileName: string);
procedure LoadPubKeyFromMem(PEM: string);
procedure LoadPriKeyFromFile(FileName: string);
procedure LoadPriKeyFromMem(PEM: string);
end;
type
TRsa = TCustomRSA;
var
PEM_write_bio_RSAPrivateKey: TPEM_write_bio_RSAPrivateKey;
PEM_write_bio_RSAPublicKey: TPEM_write_bio_RSAPublicKey;
PEM_read_bio_RSA_PUBKEY: TPEM_read_bio_RSA_PUBKEY;
PEM_read_bio_RSAPublicKey: TPEM_read_bio_RSAPublicKey;
PEM_read_bio_RSAPrivateKey: TPEM_read_bio_RSAPrivateKey;
hLibSSL: THandle;
function GenRsaKeys(KeySize: integer; var PriKey: string; var PubKey: string): PRSA;
function EncryptRsa(KeyPair: PRSA; var OrigMsg: PByte; LenMsg: integer;
var EncMsg: PByte; var EncLen: integer; var err: PChar): integer;
function DecryptRsa(KeyPair: PRSA; var OrigMsg: PByte; var LenMsg: integer;
var EncMsg: PByte; var EncLen: integer; var err: PChar): integer;
procedure CloseRSA(KeyPair: PRSA);
implementation
procedure DoUnloadOpenSSL;
begin
FreeLibrary(hLibSSL);
end;
procedure DoLoadOpenSSL;
begin
hLibSSL := LoadLibrary(DLLSSLName + '.so');
OpenSSL_add_all_algorithms();
PEM_write_bio_RSAPrivateKey :=
TPEM_write_bio_RSAPrivateKey(GetProcAddress(hLibSSL, 'PEM_write_bio_RSAPrivateKey'));
if PEM_write_bio_RSAPrivateKey = nil then
raise Exception.Create('Error Loading function #1');
PEM_write_bio_RSAPublicKey :=
TPEM_write_bio_RSAPublicKey(GetProcAddress(hLibSSL, 'PEM_write_bio_RSAPublicKey'));
if PEM_write_bio_RSAPublicKey = nil then
raise Exception.Create('Error Loading function #2');
PEM_read_bio_RSA_PUBKEY :=
TPEM_read_bio_RSA_PUBKEY(GetProcAddress(hLibSSL, 'PEM_read_bio_RSA_PUBKEY'));
if PEM_read_bio_RSA_PUBKEY = nil then
raise Exception.Create('Error Loading function #3');
PEM_read_bio_RSAPrivateKey :=
TPEM_read_bio_RSAPrivateKey(GetProcAddress(hLibSSL, 'PEM_read_bio_RSAPrivateKey'));
if PEM_read_bio_RSAPrivateKey = nil then
raise Exception.Create('Error Loading function #4');
PEM_read_bio_RSAPublicKey :=
TPEM_read_bio_RSAPublicKey(GetProcAddress(hLibSSL, 'PEM_read_bio_RSAPublicKey'));
if PEM_read_bio_RSAPublicKey = nil then
raise Exception.Create('Error Loading function #5');
end;
function GenRsaKeys(KeySize: integer; var PriKey: string; var PubKey: string): PRSA;
var
PriLen, PubLen: integer;
KeyPair: PRSA;
Pri: PBIO;
Pub: PBIO;
begin
KeyPair := RsaGenerateKey(KeySize, PUB_EXP, nil, nil);
Pri := BioNew(BioSMem);
Pub := BioNew(BioSMem);
PEM_write_bio_RSAPrivateKey(pri, keypair, nil, nil, nil, nil, nil);
PEM_write_bio_RSAPublicKey(pub, keypair);
Prilen := BioCtrlPending(pri);
Publen := BioCtrlPending(pub);
SetLength(PriKey, PriLen);
SetLength(PubKey, PubLen);
BioRead(pri, PriKey, PriLen);
BioRead(pub, PubKey, PubLen);
BioFreeAll(pub);
BioFreeAll(pri);
Result := keypair;
end;
function EncryptRsa(KeyPair: PRSA; var OrigMsg: PByte; LenMsg: integer;
var EncMsg: PByte; var EncLen: integer; var err: PChar): integer;
begin
EncLen := RSA_public_encrypt(LenMsg, OrigMsg, EncMsg, KeyPair, RSA_PKCS1_OAEP_PADDING);
if EncLen = -1 then
begin
ERR_load_crypto_strings();
Err_Error_String(ErrGetError(), err);
Result := 0;
end
else
Result := EncLen;
end;
function DecryptRsa(KeyPair: PRSA; var OrigMsg: PByte; var LenMsg: integer;
var EncMsg: PByte; var EncLen: integer; var err: PChar): integer;
begin
LenMsg := RSA_private_decrypt(EncLen, EncMsg, OrigMsg, KeyPair,
RSA_PKCS1_OAEP_PADDING);
if LenMsg = -1 then
begin
ERR_load_crypto_strings();
Err_Error_String(ErrGetError(), err);
Result := 0;
end
else
Result := LenMsg;
end;
procedure CloseRSA(KeyPair: PRSA);
begin
RSA_free(KeyPair);
end;
{ TCustomRSA }
constructor TCustomRSA.Create;
begin
GetMem(ErrMsg, MAX_PATH);
end;
destructor TCustomRSA.Destroy;
begin
FreeMem(ErrMsg);
end;
procedure TCustomRSA.GenKeys;
// Генерация RSA ключей
var
KeyPair: PRSA;
begin
KeyPair := GenRsaKeys(KeySize, PrivateKey, PublicKey);
CloseRSA(KeyPair);
LoadPriKeyFromMem(PrivateKey);
LoadPubKeyFromMem(PublicKey);
end;
function TCustomRSA.Encrypt(var OrigMsg: PByte; LenMsg: integer;
var EncMsg: PByte; var EncLen: integer): integer;
// RSA шифрование
begin
Result := EncryptRsa(PubKey, OrigMsg, LenMsg, EncMsg, EncLen, ErrMsg);
end;
function TCustomRSA.Decrypt(var OrigMsg: PByte; LenMsg: integer;
var EncMsg: PByte; var EncLen: integer): integer;
// RSA расшифровка
begin
Result := DecryptRsa(PriKey, OrigMsg, LenMsg, EncMsg, EncLen, ErrMsg);
end;
procedure TCustomRSA.CloseKeys;
// RSA закрытие и освобождение ключей и структур RSA
begin
CloseRSA(PubKey);
CloseRSA(PriKey);
end;
function TCustomRSA.PemToRsa(Pem: Pointer; Flag: integer): PRSA;
// Преобразование формата PEM в структуру PRSA
var
KeyBIO: PBIO;
TmpRsa: PRSA;
err: PChar;
begin
GetMem(err, MAX_PATH);
ERR_load_crypto_strings();
TmpRsa := nil;
KeyBIO := BIO_new_mem_buf(Pem, -1);
if KeyBIO = nil then
begin
Err_Error_String(ErrGetError(), err);
raise Exception.Create('Failed to create key PBIO ' + string(err));
Freemem(err);
abort;
end;
case flag of
0: Result := PEM_read_bio_RSAPublicKey(KeyBIO, @TmpRsa, nil, nil);
1: Result := PEM_read_bio_RSAPrivateKey(KeyBIO, @TmpRsa, nil, nil);
2: Result := PEM_read_bio_RSA_PUBKEY(KeyBIO, @TmpRsa, nil, nil);
end;
if Result = nil then
begin
Err_Error_String(ErrGetError(), err);
ShowMessage('Failed to create PRSA ' + string(err));
Freemem(err);
abort;
end;
end;
procedure TCustomRSA.SaveKeyPair(PathToPubKey, PathToPriKey: string);
// RSA сохранение ключей в PEM формате
var
hfile: TextFile;
begin
if PathToPubKey <> '' then
begin
AssignFile(hFile, PathToPubKey);
ReWrite(hFile);
Write(hFile, PublicKey);
Close(hFile);
end;
if PathToPriKey <> '' then
begin
AssignFile(hFile, PathToPriKey);
ReWrite(hFile);
Write(hFile, PrivateKey);
Close(hFile);
end;
end;
procedure TCustomRSA.LoadPubKeyFromFile(FileName: string);
// Загрузка открытого ключа
var
StringList: TStringList;
begin
CloseRSA(PubKey);
StringList := TStringList.Create;
StringList.LoadFromFile(FileName);
PublicKey := StringList.Text;
PubKey := PemToRsa(PChar(PublicKey), 0);
StringList.Free;
end;
procedure TCustomRSA.LoadPubKeyFromMem(PEM: string);
begin
CloseRSA(PubKey);
PublicKey := PEM;
PubKey := PemToRsa(PChar(PublicKey), 0);
end;
procedure TCustomRSA.LoadPriKeyFromFile(FileName: string);
// Загрузка приватного ключа
var
StringList: TStringList;
begin
CloseRSA(PriKey);
StringList := TStringList.Create;
StringList.LoadFromFile(FileName);
PrivateKey := StringList.Text;
PriKey := PemToRsa(PChar(PrivateKey), 1);
StringList.Free;
end;
procedure TCustomRSA.LoadPriKeyFromMem(PEM: string);
begin
CloseRSA(PriKey);
PrivateKey := PEM;
PriKey := PemToRsa(PChar(PrivateKey), 1);
end;
initialization
DoLoadOpenSSL;
finalization
DoUnloadOpenSSL;
end.
|
unit Bank_impl;
{This file was generated on 19 Jun 2000 15:50:28 GMT by version 03.03.03.C1.04}
{of the Inprise VisiBroker idl2pas CORBA IDL compiler. }
{Please do not edit the contents of this file. You should instead edit and }
{recompile the original IDL which was located in the file account.idl. }
{Delphi Pascal unit : Bank_impl }
{derived from IDL module : Bank }
interface
uses
SysUtils,
CORBA,
Bank_i,
Bank_c;
type
TRates = class;
TAccount = class;
TRates = class(TInterfacedObject, Bank_i.Rates)
protected
_interest_rate : single;
public
constructor Create;
function get_interest_rate : Single;
end;
TAccount = class(TInterfacedObject, Bank_i.Account)
protected
_balance : single;
public
constructor Create;
function balance : Single;
function get_rates(const myRates : Bank_i.Rates): Single;
end;
implementation
constructor TRates.Create;
begin
inherited;
_interest_rate := random * 10;
end;
function TRates.get_interest_rate : Single;
begin
result := _interest_rate;
end;
constructor TAccount.Create;
begin
inherited;
_balance := random * 10000;
end;
function TAccount.balance : Single;
begin
result := _balance;
end;
function TAccount.get_rates ( const myRates : Bank_i.Rates): Single;
begin
result := myRates.get_interest_rate;
end;
initialization
randomize;
end. |
unit frm_Archive;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ActnList, XPStyleActnCtrls, ActnMan, ToolWin, ActnCtrls, ComCtrls;
type
TfrmArchive = class(TForm)
ActionToolBar1: TActionToolBar;
ActionManager1: TActionManager;
acClose: TAction;
acBackup: TAction;
acRestore: TAction;
FileList: TListView;
procedure acCloseExecute(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure acBackupExecute(Sender: TObject);
procedure FileListColumnClick(Sender: TObject; Column: TListColumn);
procedure FileListCompare(Sender: TObject; Item1, Item2: TListItem;
Data: Integer; var Compare: Integer);
procedure acRestoreExecute(Sender: TObject);
procedure FileListSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
private
Dir:String;
Imported:Boolean;
procedure ListFiles;
{ Private declarations }
public
{ Public declarations }
end;
var
frmArchive: TfrmArchive;
implementation
uses dm_GUI,dm_AlarmDB,dm_Images;
{$R *.dfm}
procedure TfrmArchive.acBackupExecute(Sender: TObject);
begin
Screen.Cursor:=crHourglass;
try
dmGUI.Connection.Execute(Format('backup database [asos%d] TO DISK = N''%sasos%d set(%s) org(%s) usr(%s) %s.bak'' with init',[
dmGUI.DatabaseID,
Dir,
dmGUI.DatabaseID,
dmAlarmDB.GetSetting('DBSettings'),
dmAlarmDB.GetSetting('DBOrganisation'),
dmAlarmDB.GetSetting('DBUsers'),
FormatDateTime('yyyy-mm-dd hh-nn-ss',Now)
]));
finally
Screen.Cursor:=crDefault;
Application.ProcessMessages;
end;
ListFiles;
end;
procedure TfrmArchive.acCloseExecute(Sender: TObject);
begin
Close;
end;
procedure TfrmArchive.acRestoreExecute(Sender: TObject);
begin
if FileList.Selected=nil then Exit;
if not dmGUI.Confirm('Възстановяването ще презапише текущата база данни.'#13#10'Желаете ли да продължите?',mtWarning) then Exit;
dmGUI.Connection.Close;
Application.ProcessMessages;
dmAlarmDB.RestoreDB(Dir+FileList.Selected.Caption);
Imported:=True;
ShowMessage('Възстановяването завърши успешно');
end;
procedure TfrmArchive.FileListColumnClick(Sender: TObject; Column: TListColumn);
begin
if Column.ID+1=Abs(FileList.Tag) then
FileList.Tag:=-FileList.Tag
else
FileList.Tag:=Column.ID+1;
FileList.AlphaSort;
end;
procedure TfrmArchive.FileListCompare(Sender: TObject; Item1, Item2: TListItem;
Data: Integer; var Compare: Integer);
var S1,S2:String;
C:Integer;
begin
C:=Abs(FileList.Tag)-1;
if (C>=0) and (C<=3) then
begin
if C=0 then
begin
S1:=Item1.Caption;
S2:=Item2.Caption;
end else
begin
C:=C-1;
if C=1 then C:=C+1;
if C>=Item1.SubItems.Count then
S1:=''
else
S1:=Item1.SubItems[C];
if C>=Item2.SubItems.Count then
S2:=''
else
S2:=Item2.SubItems[C];
if C=0 then
begin
while Length(S1)<Length(S2) do S1:='0'+S1;
while Length(S2)<Length(S1) do S2:='0'+S2;
end;
end;
Compare:=lstrcmp(PChar(S1), PChar(S2));
if FileList.Tag<0 then Compare:=-Compare;
end
else
Compare:=0;
end;
procedure TfrmArchive.FileListSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
begin
acRestore.Enabled:=FileList.Selected<>nil;
end;
procedure TfrmArchive.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action:=caFree;
if Imported then ModalResult:=mrOk;
end;
procedure TfrmArchive.FormCreate(Sender: TObject);
begin
Dir:=ExtractFilePath(ParamStr(0))+'Archive\';
end;
procedure TfrmArchive.FormDestroy(Sender: TObject);
begin
frmArchive:=nil;
end;
procedure TfrmArchive.FormShow(Sender: TObject);
begin
ListFiles;
FileList.Tag:=-2;
FileList.AlphaSort;
end;
procedure TfrmArchive.ListFiles;
var F:TSearchRec;
Found:Boolean;
L:TListItem;
begin
FileList.Items.Clear;
Found:=FindFirst(Dir+'*.bak',faAnyFile and not faDirectory,F)=0;
try
while Found do
begin
L:=FileList.Items.Add;
L.Caption:=ExtractFileName(F.Name);
L.SubItems.Add(FormatDateTime('yyyy-mm-dd hh:nn:ss',FileDateToDateTime(F.Time)));
if F.Size<8192 then
L.SubItems.Add(IntToStr(F.Size)+' B')
else
if F.Size<8192*1024 then
L.SubItems.Add(IntToStr(Round(F.Size/1024))+' KB')
else
L.SubItems.Add(IntToStr(Round(F.Size/1024/1024))+' MB');
L.SubItems.Add(IntToStr(F.Size));
L.ImageIndex:=-1;
Found := SysUtils.FindNext(F) = 0;
end;
finally
SysUtils.FindClose(F);
end;
end;
end.
|
unit Voxel;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Schedule, BaseTypes;
const
MaxVoxelFidelity = 10;
DefaultBlockDepth = 3;
type
eVoxelPos = (BNW, BSW, TNW, TSW, BNE, BSE, TNE, TSE);
eVoxelDir = (dN = -%001, dS = %001, dB = -%010, dT = %010, dW = -%100, dE = %100);
{ tVoxel } //This voxel fucking sucks, what was I thinking?
tVoxel = class //37b
Order: byte; //1b //remove this
Parent: tVoxel; //4b/8b //prolly don't need parent either, use stack
Children: array [BNW..TSE] of tVoxel; //neighbour[0..5]? //32b / 64b
private
//NeedsUpdate: boolean;
//fContent: byte; //1b
function GetContent: byte;
public
property Content: byte read GetContent;
constructor Create(ParentVoxel: tVoxel);
destructor Destroy; override;
end;
tVoxelAA = specialize tAutoArray<tVoxel>;
tVoxelArray8 = array [BNW..TSE] of tVoxel;
tVoxelArray = array of tVoxel;
{ tVoxelContainer }
rVoxelDescriptor = packed record
Children, Content: byte;
end;
eLoadOption = (lWhole, lManhattan, lLinear);
rDescriptorArray = array of rVoxelDescriptor;
tVoxelContainer = class
//FileName: string;
FileStream: tFileStream;
BlockCount, FirstBlock: longword;
BlockSizes: array of longword; //in voxels
RootVoxel: tVoxel;
constructor Create;
function Load(FileName: string; Option: eLoadOption): integer;
procedure LoadWhole;
procedure LoadOptimized(c: rVec3);
function Save(FileName: string): integer;
function LoadBlock(Number: longword;
Depth: longword = MaxVoxelFidelity): tVoxel; //returns most high-level voxel
procedure LoadBlock(var ParentVoxel: tVoxel; Position: eVoxelPos;
Depth: longword = MaxVoxelFidelity);
procedure SaveBlock(Voxel: tVoxel);
destructor Destroy; override;
end;
rLocation = record
x, y: single;
Voxel: tVoxel;
end;
eMaterial = (emEarth, emGrass, emMud, emSand, emStone, emStillWater,
emRunningWater, emOreIron, emOreSilver, emOreCopper, emOreTin,
emBrick, emCobblestone);
const
MinValidPointer = pointer(65536);
//Leaf voxel states
NoVoxel = nil;
StoredVoxel = pointer(1);
NeedsStorage = pointer(2); //wtf is that????? how would you get to it???
LeafVoxel = pointer(3);
//Materials
MaterialOffset = %100000000;
MaxMaterialValue = integer(high(eMaterial));
mEarth = pointer(integer(emEarth) * MaterialOffset);
mGrass = pointer(integer(emGrass) * MaterialOffset);
mMud = pointer(integer(emMud) * MaterialOffset);
mSand = pointer(integer(emSand) * MaterialOffset);
mStone = pointer(integer(emStone) * MaterialOffset);
mStillWater = pointer(integer(emStillWater) * MaterialOffset);
mRunningWater = pointer(integer(emRunningWater) * MaterialOffset);
mOreIron = pointer(integer(emOreIron) * MaterialOffset);
mOreSilver = pointer(integer(emOreSilver) * MaterialOffset);
mOreCopper = pointer(integer(emOreCopper) * MaterialOffset);
mOreTin = pointer(integer(emOreTin) * MaterialOffset);
mBrick = pointer(integer(emBrick) * MaterialOffset);
mCobblestone = pointer(integer(emCobblestone) * MaterialOffset);
//\/invalid ptrs //content //state
//0..65535 2 bytes 0000 0000 0000 0000 <<lowest bit
var
VoxelFidelity: cardinal;
StructureOrder: longword;
MinVoxelDim: single = 0.25;//0.03125;
function GetVoxelCenter(ParentCenter: rVec3; ParentOrder: integer; Pos: eVoxelPos): rVec3;
function ValidPointerCount(a: tVoxelArray8): longword; inline;
function VoxelChildCount(v: rVoxelDescriptor): integer; inline;
function GetVoxelDescriptors(a: tVoxelArray): rDescriptorArray;
//pseudocode
//function GetAdjacentVoxel(c, d: rVec3): tVoxel;
//\pseudocode
implementation
uses
math, Utility;
function GetVoxelCenter(ParentCenter: rVec3; ParentOrder: integer; Pos: eVoxelPos): rVec3;
var
d: single;
v: rVec3;
begin
d:= MinVoxelDim * power(2, VoxelFidelity - ParentOrder) / 2;
case Pos of
BNW: begin
v.x:= -d;
v.y:= -d;
v.z:= -d;
end;
BSW: begin
v.x:= -d;
v.y:= -d;
v.z:= d;
end;
TNW: begin
v.x:= -d;
v.y:= d;
v.z:= -d;
end;
TSW: begin
v.x:= -d;
v.y:= d;
v.z:= d;
end;
BNE: begin
v.x:= d;
v.y:= -d;
v.z:= -d;
end;
BSE: begin
v.x:= d;
v.y:= -d;
v.z:= d;
end;
TNE: begin
v.x:= d;
v.y:= d;
v.z:= -d;
end;
TSE: begin
v.x:= d;
v.y:= d;
v.z:= d;
end;
end;
Result:= ParentCenter + v;
end;
function ValidPointerCount(a: tVoxelArray8): longword; inline;
var
i: eVoxelPos;
begin
Result:= 0;
for i:= low(eVoxelPos) to high(eVoxelPos) do
if pointer(a[i]) > LeafVoxel then //leaf voxels don't get their own descriptors... maybe 1b for material?
inc(Result);
end;
function VoxelChildCount(v: rVoxelDescriptor): integer; inline;
begin
Result:= popcnt(v.Children);
end;
function GetVoxelDescriptors(a: tVoxelArray): rDescriptorArray; //is result a new array or no?
var
i: integer;
j: eVoxelPos;
begin
setlength(Result, length(a));
for i:= 0 to high(a) do
with Result[i] do
begin
Children:= 0;
Content:= 0;
for j:= low(eVoxelPos) to high(eVoxelPos) do
if a[i].Children[j] <> nil then
begin
case j of
BNW: Children+= %00000001;
BSW: Children+= %00000010;
TNW: Children+= %00000100;
TSW: Children+= %00001000;
BNE: Children+= %00010000;
BSE: Children+= %00100000;
TNE: Children+= %01000000;
TSE: Children+= %10000000;
end;
if pointer(a[i].Children[j]) < MinValidPointer then
Content:= longword(pointer(a[i].Children[j])) shr 8; //tested
end;
end;
end;
{function GetAdjacentVoxel(c, d: rVec3): tVoxel;
var
cv: tVoxel;
pos: eVoxelPos;
dir: eVoxelDir;
begin
cv:= GetVoxel(c, VoxelCenter); //without extending the tree
while not cv.IsLeaf do
begin
cv:= cv.Parent;
case dir of
dN: ;
dS: ;
dB: ;
dT: ;
dW: ;
dE: ;
end;
end;
end; }
{ tVoxelContainer }
constructor tVoxelContainer.Create;
begin
//initialization
end;
procedure tVoxelContainer.LoadWhole;
var
i: eVoxelPos;
j: integer;
begin
FirstBlock:= sizeof(BlockCount) + BlockCount * sizeof(BlockSizes[0]);
FileStream.ReadBuffer(BlockSizes, BlockCount);
RootVoxel:= LoadBlock(0);
if assigned(RootVoxel) then
RootVoxel.Destroy;
for i:= BNW to TSE do
begin
end;
end;
procedure tVoxelContainer.LoadOptimized(c: rVec3);
var
i: eVoxelPos;
j: longword = 0;
vq: tVoxelAA;
{procedure LOD( }
begin
if assigned(RootVoxel) then
RootVoxel.Destroy;
vq:= tVoxelAA.Create;
RootVoxel:= LoadBlock(0);
for i:= BNW to TSE do
vq.Add(RootVoxel.Children[i]);
for i:= BNW to TSE do
begin
//check distance
// LoadBlock(vq.Values[j], i);//level from dist check);
//vq.Add();
inc(j);
end;
end;
function tVoxelContainer.Load(FileName: string; Option: eLoadOption): integer;
begin
Result:= 0;
try
Filestream:= TFileStream.Create(FileName, fmOpenReadWrite);
VoxelFidelity:= FileStream.ReadDWord;
setlength(BlockSizes, VoxelFidelity);
FileStream.ReadBuffer(BlockSizes, length(BlockSizes) * sizeof(longword));
except
on E: Exception do
begin
WriteLog(E.Message);
Result:= -1; //does this exit?
end;
end;
case Option of
lWhole: ;
lManhattan: ;
lLinear: ;
end;
end;
function tVoxelContainer.Save(FileName: string): integer;
var
vq1, vq2: tVoxelAA;
Descriptors: array of rVoxelDescriptor;
i, j: integer;
sum: longword;
begin
Result:= 0;
if FileStream.FileName <> FileName then
begin
WriteLog(msgFCr + ' ''' + FileName + '''');
FileStream.Destroy;
try
FileStream:= TFileStream.Create(FileName, fmOpenReadWrite);
except
on E: EFOpenError do
begin
WriteLog(E.Message);
Result:= -1;
end;
end;
end;
setlength(BlockSizes, VoxelFidelity);
BlockSizes[0]:= 1;
FileStream.Seek(VoxelFidelity + 1, soBeginning);
vq1:= tVoxelAA.Create(1);
vq1.Add(RootVoxel);
for i:= 1 to VoxelFidelity do
begin
vq2:= tVoxelAA.Create(vq1.Count * 4); //estimate?
sum:= 0;
for j:= 0 to vq1.Count - 1 do
begin
vq2.Add(vq1[j].Children);
Sum+= ValidPointerCount(vq1[j].Children);
Descriptors:= GetVoxelDescriptors(vq1.fValues);
FileStream.WriteBuffer(Descriptors, length(Descriptors) * sizeof(rVoxelDescriptor)); //still need a way to assign material to non-leaf voxels
end;
BlockSizes[i]:= Sum;
vq1.Destroy;
vq1:= vq2;
end;
FileStream.Seek(0, soBeginning);
FileStream.WriteDWord(VoxelFidelity);
FileStream.WriteBuffer(BlockSizes, length(BlockSizes) * sizeof(longword));
end;
function tVoxelContainer.LoadBlock(Number: longword;
Depth: longword = MaxVoxelFidelity): tVoxel;
var
Descriptors: array of rVoxelDescriptor;
i, j, pos: longword;
qc, qm: longint; //queue counter
//j: eVoxelPos;
//cv: tVoxel; //current voxel
vq: array of tVoxel; //voxel queue
begin
setlength(Descriptors, BlockSizes[Number]);
setlength(vq, BlockSizes[Number]);
pos:= FirstBlock;
for i:= 0 to Number - 1 do //??
pos+= BlockSizes[i]; //maybe keep this summed and find actual size by detracting?? //problematic to insert blocks
FileStream.Seek(pos, soBeginning); //this has 2 variants 32 & 64
FileStream.ReadBuffer(Descriptors, BlockSizes[Number] * sizeof(rVoxelDescriptor));
Result:= tVoxel.Create(nil);
i:= 0;
qc:= -1; //???
qm:= 0;
vq[qm]:= Result;
dec(Depth); //if depth = 3, 3rd level will have values 0..65535 as children
with vq[qc] do
begin
for i:= 0 to high(Descriptors) do //for each descriptor in block
begin
inc(qc);
//cv:= vq[qc]; //get next voxel from q
for j:= 0 to integer(TSE) do //decode children byte
begin
if GetBit(Descriptors[i].Children, j) then
begin
if Depth <> 0 then
begin
Children[eVoxelPos(j)]:= tVoxel.Create(vq[qc]); //allocate mem for voxels
inc(qm);
vq[qm]:= Children[eVoxelPos(j)]; //add to q for processing
end
else
begin
Children[eVoxelPos(j)]:= tVoxel(Descriptors[i].Content + StoredVoxel); //load state and content instead of valid pointer
end;
end;
if j = integer(TSE) then
dec(Depth);
end;
end;
end;
end;
procedure tVoxelContainer.LoadBlock(var ParentVoxel: tVoxel; Position: eVoxelPos;
Depth: longword = MaxVoxelFidelity);
var
Number: longword;
begin
Number:= 0;
ParentVoxel.Children[Position]:= LoadBlock(Number, Depth);
ParentVoxel.Children[Position].Parent:= ParentVoxel;
end;
procedure tVoxelContainer.SaveBlock(Voxel: tVoxel);
begin
//called by save world, saves block size at first provided pos, then block at 2nd provided pos
end;
destructor tVoxelContainer.Destroy;
begin
setlength(BlockSizes, 0);
freeandnil(FileStream);
freeandnil(RootVoxel);
end;
{ tVoxel }
constructor tVoxel.Create(ParentVoxel: tVoxel);
begin
Parent:= ParentVoxel;
if ParentVoxel <> nil then
begin
Order:= Parent.Order + 1;
//Parent.Content:= Parent.Content + 1;
end;
end;
destructor tVoxel.Destroy;
var
i: eVoxelPos;
begin
for i:= low(Children) to high(Children) do
if pointer(Children[i]) > LeafVoxel then
Children[i].Destroy;
end;
function tVoxel.GetContent: byte;
var
i: eVoxelPos;
begin
Result:= 0;
for i:= BNW to TSE do
if pointer(Children[i]) >= LeafVoxel then
inc(Result);
end;
end.
|
{
Const strings for localization
freeware SMComponent library
}
unit SMCnst;
interface
{English strings}
const
strMessage = 'Štampa...';
strSaveChanges = 'Da li želite da zapamtite promene u bazi podataka?';
strErrSaveChanges = 'Podaci se ne mogu zapamtiti. Proverite konekciju sa Serverom ili ispravnost podataka.';
strDeleteWarning = 'Obrisati tabelu %s?';
strEmptyWarning = 'Izbrisati tabelu %s?';
const
PopUpCaption: array [0..24] of string =
('Dodaj zapis',
'Umetni zapis',
'Promeni zapis',
'Obriši zapis',
'-',
'Štampaj ...',
'Export ...',
'Filter ...',
'Pretraga ...',
'-',
'Snimi promene',
'Otkaži promene',
'Osvežavanje',
'-',
'Označi/isključi zapise',
'Označi zapis',
'Označi sve zapise',
'-',
'Isključi zapise',
'Isključi sve zapise',
'-',
'Zapamti raspored kolona',
'Vrati raspored kolona',
'-',
'Podešavanja...');
const //for TSMSetDBGridDialog
SgbTitle = ' Naslov ';
SgbData = ' Podatak ';
STitleCaption = 'Oznaka:';
STitleAlignment = 'Poravnanje:';
STitleColor = 'Pozadina:';
STitleFont = 'Font:';
SWidth = 'Širina:';
SWidthFix = 'karakteri';
SAlignLeft = 'levo';
SAlignRight = 'desno';
SAlignCenter = 'centrirano';
const //for TSMDBFilterDialog
strEqual = 'jednako';
strNonEqual = 'nije jednako';
strNonMore = 'nije veće';
strNonLess = 'nije manje';
strLessThan = 'manje od';
strLargeThan = 'više od';
strExist = 'prazno';
strNonExist = 'nije prazno';
strIn = 'u listi';
strBetween = 'između';
strLike = 'kao';
strOR = 'ILI';
strAND = 'I';
strField = 'Polje';
strCondition = 'Uslov';
strValue = 'Vrednost';
strAddCondition = ' Definiši dodatne uslove:';
strSelection = ' Označi zapise koji zadovoljavaju usluve:';
strAddToList = 'Dodaj u listu';
strEditInList = 'Promeni u listi';
strDeleteFromList = 'Izbaci iz liste';
strTemplate = 'Šablon filtera';
strFLoadFrom = 'Učitaj ...';
strFSaveAs = 'Snimi kao..';
strFDescription = 'Opis';
strFFileName = 'Naziv fajla';
strFCreate = 'Kreiran: %s';
strFModify = 'Promenjen: %s';
strFProtect = 'Zaštiti od prepisivanja';
strFProtectErr = 'Fajl je zaštićen!';
const //for SMDBNavigator
SFirstRecord = 'Prvi zapis';
SPriorRecord = 'Prethodni zapis';
SNextRecord = 'Sledeći zapis';
SLastRecord = 'Poslednji zapis';
SInsertRecord = 'Dodaj zapis';
SCopyRecord = 'Kopiraj zapis';
SDeleteRecord = 'Obriši zapis';
SEditRecord = 'Promeni zapis';
SFilterRecord = 'Filter';
SFindRecord = 'Pronađi zapis';
SPrintRecord = 'Štampanje zapisa';
SExportRecord = 'Izvoz zapisa';
SImportRecord = 'Uvoz zapisa';
SPostEdit = 'Čuvanje promena';
SCancelEdit = 'Odustajanje od promena';
SRefreshRecord = 'Osvežavanje podataka';
SChoice = 'Izbor zapisa';
SClear = 'Poništiti izbor zapisa';
SDeleteRecordQuestion = 'Obrisati zapis?';
SDeleteMultipleRecordsQuestion = 'Obrisati sve označene zapise?';
SRecordNotFound = 'Zapis nije pronađen';
SFirstName = 'Prvi';
SPriorName = 'Prethodni';
SNextName = 'Sledeći';
SLastName = 'Poslednji';
SInsertName = 'Dodavanje';
SCopyName = 'Kopiranje';
SDeleteName = 'Brisanje';
SEditName = 'Promena';
SFilterName = 'Filter';
SFindName = 'Pretraga';
SPrintName = 'Štampa';
SExportName = 'Izvoz';
SImportName = 'Uvoz';
SPostName = 'Snimi';
SCancelName = 'Odustani';
SRefreshName = 'Osveži';
SChoiceName = 'Izaberi';
SClearName = 'Očisti';
SBtnOk = '&OK';
SBtnCancel = '&Odustani';
SBtnLoad = 'Učitaj';
SBtnSave = 'Snimi';
SBtnCopy = 'Copy';
SBtnPaste = 'Paste';
SBtnClear = 'Očisti';
SRecNo = 'zap.';
SRecOf = ' od ';
const //for EditTyped
etValidNumber = 'valid number';
etValidInteger = 'valid integer number';
etValidDateTime = 'valid date/time';
etValidDate = 'valid date';
etValidTime = 'valid time';
etValid = 'valid';
etIsNot = 'is not a';
etOutOfRange = 'Value %s out of range %s..%s';
SApplyAll = 'Apply to All';
SNoDataToDisplay = '<Nema podataka za prikaz>';
SPrevYear = 'prethodna godina';
SPrevMonth = 'prethodni mesec';
SNextMonth = 'sledeći mesec';
SNextYear = 'sledeća godina';
implementation
end.
|
unit Test.Devices.Logica.SPT943.ReqCreator;
interface
uses Windows, TestFrameWork, Devices.Logica.SPT943, GMGlobals, Test.Devices.Base.ReqCreator, GmSqlQuery;
type
TSPT943ReqCreatorFortest = class(TSPT943ReqCreator)
protected
function CanRequestPack(): bool; override;
function NeedReqArch(): int; override;
end;
TLogicaSPT943ReqCreatorTest = class(TDeviceReqCreatorTestBase)
protected
procedure SetUp; override;
procedure TearDown; override;
function GetDevType(): int; override;
protected
procedure DoCheckRequests(); override;
published
procedure CheckCRC();
end;
implementation
uses DateUtils, SysUtils, GMConst;
{ TLogicaReqCreatorTest }
procedure TLogicaSPT943ReqCreatorTest.CheckCRC;
var buf: ArrayOfByte;
begin
buf := TextNumbersStringToArray('10 ff 90 00 00 05 00 3f 00 00 00 00 d9 19');
Check(LogicaSPT943_CheckCRC(buf, Length(buf)));
buf := TextNumbersStringToArray('10 ff 90 4f 00 0b 00 72 4a 03 00 01 04 4a 03 00 00 04 27 0e');
Check(LogicaSPT943_CheckCRC(buf, Length(buf)));
end;
procedure TLogicaSPT943ReqCreatorTest.DoCheckRequests;
begin
Check(ReqList.Count >= 5, 'Count = ' + IntToStr(ReqList.Count));
CheckReqHexString(0, 'FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF'); // инициализация линии
CheckReqHexString(1, '10 22 90 0 0 5 0 3F 0 0 0 0 6A DB'); // запрос сеанса
CheckReqHexString(2, '10 22 90 1 0 10 00 72 4A 3 0 2 4 4A 3 0 3 4 4A 3 0 0 8 A5 1A'); // Chn 0
Check(ReqList[2].ReqID = 1, 'ReqList[2].ReqID');
Check(ReqList[2].rqtp = rqtSPT943_0, 'ReqList[2].rqtp');
Check(ReqList[2].ReqLinkCount = 3, 'ReqList[2].ReqLinkCount');
CheckReqHexString(3, '10 22 90 2 0 60 00 ' + // заголовок
'72 ' + // FNC
'4A 3 1 1 4 4A 3 1 2 4 4A 3 1 3 4 4A 3 1 4 4 4A 3 1 5 4 4A 3 1 6 4 4A 3 1 7 4 4A 3 1 8 4 4A 3 1 9 4 ' + // DATA
'4A 3 1 A 4 4A 3 1 B 4 4A 3 1 0 8 4A 3 1 1 8 4A 3 1 2 8 4A 3 1 3 8 4A 3 1 4 8 4A 3 1 5 8 4A 3 1 6 8 4A 3 1 7 8 ' + // DATA cont.
'1D 0F'); // CRC
Check(ReqList[3].ReqID = 2, 'ReqList[3].ReqID');
Check(ReqList[3].rqtp = rqtSPT943_1, 'ReqList[3].rqtp');
Check(ReqList[3].ReqLinkCount = 19, 'ReqList[3].ReqLinkCount');
CheckReqHexString(4, '10 22 90 3 0 60 00 ' + // заголовок
'72 ' + // FNC
'4A 3 2 1 4 4A 3 2 2 4 4A 3 2 3 4 4A 3 2 4 4 4A 3 2 5 4 4A 3 2 6 4 4A 3 2 7 4 4A 3 2 8 4 4A 3 2 9 4 ' + // DATA
'4A 3 2 A 4 4A 3 2 B 4 4A 3 2 0 8 4A 3 2 1 8 4A 3 2 2 8 4A 3 2 3 8 4A 3 2 4 8 4A 3 2 5 8 4A 3 2 6 8 4A 3 2 7 8 ' + // DATA cont.
'F8 65'); // CRC
Check(ReqList[4].ReqID = 3, 'ReqList[4].ReqID');
Check(ReqList[4].rqtp = rqtSPT943_2, 'ReqList[4].rqtp');
Check(ReqList[4].ReqLinkCount = 19, 'ReqList[4].ReqLinkCount');
CheckEquals('4', QueryResult('select LastReqNumber from ObjectStates where ID_Obj = (select ID_Obj from Devices where ID_Device = ' + IntToStr(GetID_Device()) + ')'), 'ObjectStates');
end;
function TLogicaSPT943ReqCreatorTest.GetDevType: int;
begin
Result := DEVTYPE_SPT_943;
end;
procedure TLogicaSPT943ReqCreatorTest.SetUp;
begin
inherited;
end;
procedure TLogicaSPT943ReqCreatorTest.TearDown;
begin
inherited;
end;
{ TSPT943ReqCreatorFortest }
function TSPT943ReqCreatorFortest.CanRequestPack: bool;
begin
Result := true;
end;
function TSPT943ReqCreatorFortest.NeedReqArch: int;
begin
Result := -1;
end;
initialization
RegisterTest('GMIOPSrv/Devices/Logica', TLogicaSPT943ReqCreatorTest.Suite);
end.
|
unit frm_Users;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DB, ActnList, XPStyleActnCtrls, ActnMan, ToolWin, ActnCtrls,
ExtCtrls, Grids, DBGrids, StdCtrls, DBCtrls, Mask;
type
TfrmUsers = class(TForm)
ActionToolBar1: TActionToolBar;
ActionManager1: TActionManager;
acClose: TAction;
acAdd: TAction;
acDelete: TAction;
srcUser: TDataSource;
DBGrid1: TDBGrid;
Splitter1: TSplitter;
Panel1: TPanel;
UserName: TDBEdit;
Password: TDBEdit;
WorkGroup: TDBLookupComboBox;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
acGroups: TAction;
srcWorkgroupList: TDataSource;
procedure acCloseExecute(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure acAddExecute(Sender: TObject);
procedure acDeleteExecute(Sender: TObject);
procedure acGroupsExecute(Sender: TObject);
procedure srcUserDataChange(Sender: TObject; Field: TField);
procedure srcUserStateChange(Sender: TObject);
private
procedure SetPassword(Sender: TField; const Text: string);
{ Private declarations }
public
{ Public declarations }
end;
var
frmUsers: TfrmUsers;
implementation
uses dm_GUI, frm_WorkGroup, dm_Images, Util;
{$R *.dfm}
procedure TfrmUsers.acAddExecute(Sender: TObject);
begin
if UserName.CanFocus and UserName.Showing then UserName.SetFocus;
srcUser.Dataset.Append;
end;
procedure TfrmUsers.acCloseExecute(Sender: TObject);
begin
Close;
end;
procedure TfrmUsers.acDeleteExecute(Sender: TObject);
begin
if dmGUI.ConfirmDelete then
srcUser.DataSet.Delete;
end;
procedure TfrmUsers.acGroupsExecute(Sender: TObject);
begin
dmGUI.ShowForm(TfrmWorkGroup,True,frmWorkGroup);
end;
procedure TfrmUsers.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action:=caFree;
srcUser.DataSet.CheckBrowseMode;
end;
procedure TfrmUsers.FormDestroy(Sender: TObject);
begin
frmUsers:=nil;
end;
procedure TfrmUsers.FormShow(Sender: TObject);
begin
dmGUI.WorkGroupList.Open;
dmGUI.UserEdit.Open;
end;
procedure TfrmUsers.srcUserDataChange(Sender: TObject; Field: TField);
begin
WorkGroup.Enabled:=srcUser.DataSet.FieldByName('ID').AsString<>'1';
end;
procedure TfrmUsers.srcUserStateChange(Sender: TObject);
begin
if Password.Field<>nil then
begin
Password.Field.OnSetText:=SetPassword;
Password.Field.Required:=True;
Password.Field.DisplayLabel:='парола';
end;
if UserName.Field<>nil then
begin
UserName.Field.Required:=True;
UserName.Field.DisplayLabel:='потребителско име';
end;
if WorkGroup.Field<>nil then
begin
WorkGroup.Field.Required:=True;
WorkGroup.Field.DisplayLabel:='потребителска група';
end;
end;
procedure TfrmUsers.SetPassword(Sender: TField; const Text: string);
begin
if Text='' then
Sender.Clear
else
begin
CheckValid(MatchPassword,Password,'Дължината на паролата трябва'#13#10'да е поне 6 символа');
Sender.AsString:=Text;
end;
end;
end.
|
{**********************************************}
{ TeeChart Export Dialog - Inherited }
{ Copyright (c) 1996-2004 by David Berneda }
{**********************************************}
unit TeExport;
{$I TeeDefs.inc}
interface
uses
{$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
SysUtils, Classes,
{$IFDEF CLX}
QGraphics, QControls, QForms, QDialogs, QStdCtrls, QExtCtrls, QComCtrls,
{$ELSE}
Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls,
{$ENDIF}
TeeExport, TeeProcs, TeCanvas;
type
TTeeExportForm = class(TTeeExportFormBase)
Splitter1: TSplitter;
private
{ Private declarations }
{$IFNDEF CLX}
procedure CMShowingChanged(var Message: TMessage); message CM_SHOWINGCHANGED;
{$ENDIF}
protected
Function CreateData:TTeeExportData; override;
Procedure DoSaveNativeToFile( Const FileName:String;
IncludeData:Boolean); override;
Function ExistData:Boolean; override;
Function CreateNativeStream:TStream; override;
Procedure PrepareOnShow; override;
public
{ Public declarations }
end;
{ Show the Export dialog }
{ example: TeeExport(Self,Chart1); }
Procedure TeeExport(AOwner:TComponent; APanel:TCustomTeePanel);
{ Show the Save dialog and save to AFormat export format }
{ example: TeeSavePanel(TGIFExportFormat,Chart1); }
Procedure TeeSavePanel(AFormat:TTeeExportFormatClass; APanel:TCustomTeePanel);
{ starts the MAPI (eg: Outlook) application with an empty new email
message with the attachment file "FileName" }
Procedure TeeEmailFile(Const FileName:String; Const Subject:String='TeeChart');
implementation
{$IFNDEF CLX}
{$R *.DFM}
{$ELSE}
{$R *.xfm}
{$ENDIF}
uses TeeConst, TeeStore, TeEngine, Chart;
Procedure TeeExport(AOwner:TComponent; APanel:TCustomTeePanel);
begin
With TTeeExportForm.Create(AOwner) do
try
ExportPanel:=APanel;
ShowModal;
finally
Free;
end;
end;
Procedure TeeSavePanel(AFormat:TTeeExportFormatClass; APanel:TCustomTeePanel);
begin
TeeExportSavePanel(AFormat,APanel);
end;
Procedure TeeEmailFile(Const FileName:String; Const Subject:String='TeeChart');
begin
InternalTeeEmailFile(FileName,Subject);
end;
{ TTeeExportForm }
function TTeeExportForm.CreateData: TTeeExportData;
Function SelectedSeries:TChartSeries;
begin
result:=TChartSeries(CBSeries.Items.Objects[CBSeries.ItemIndex]);
end;
function Chart: TCustomChart;
begin
result:=TCustomChart(ExportPanel);
end;
begin
Case RGText.ItemIndex of
0: begin
result:=TSeriesDataText.Create(Chart,SelectedSeries);
TSeriesDataText(result).TextDelimiter:=GetSeparator;
TSeriesDataText(result).TextQuotes:=EQuotes.Text; // 7.0
end;
1: result:=TSeriesDataXML.Create(Chart,SelectedSeries);
2: result:=TSeriesDataHTML.Create(Chart,SelectedSeries);
else
result:=TSeriesDataXLS.Create(Chart,SelectedSeries);
end;
// Configure options
With TSeriesData(result) do
begin
IncludeLabels:=CBLabels.Checked;
IncludeIndex :=CBIndex.Checked;
IncludeHeader:=CBHeader.Checked;
IncludeColors:=CBColors.Checked;
end;
end;
function TTeeExportForm.ExistData: Boolean;
begin
result:=(ExportPanel is TCustomAxisPanel) and
(TCustomAxisPanel(ExportPanel).SeriesCount>0);
end;
Procedure TTeeExportForm.DoSaveNativeToFile( Const FileName:String;
IncludeData:Boolean);
begin
SaveChartToFile(TCustomChart(ExportPanel),FileName,
IncludeData,NativeAsText);
end;
Procedure TTeeExportForm.PrepareOnShow;
begin
FillSeriesItems(CBSeries.Items,TCustomAxisPanel(ExportPanel).SeriesList);
CBSeries.Items.Insert(0,TeeMsg_All);
CBSeries.ItemIndex:=0;
end;
Function TTeeExportForm.CreateNativeStream:TStream;
begin
result:=TMemoryStream.Create;
SaveChartToStream(TCustomChart(ExportPanel),result,
CBNativeData.Checked,NativeAsText);
end;
{$IFNDEF CLX}
procedure TTeeExportForm.CMShowingChanged(var Message: TMessage);
begin
inherited;
if Assigned(Parent) then
Parent.UpdateControlState;
end;
{$ENDIF}
end.
|
(* Chapter 4 - Program 9 *)
program ABiggerCaseExample;
var Count : integer;
Index : 0..255;
begin (* main program *)
for Count := 1 to 10 do begin
Write(Count:5);
case Count of
{7..9} 7,8,9 : Write(' Big Number');
2,4,6 : begin Write(' Small');
Write(' even');
Write(' number.');
end;
3 : for Index := 1 to 3 do Write(' Boo');
1 : if TRUE then begin Write(' TRUE is True,');
Write(' and this is dumb.');
end;
{else Write(' This number is not in the allowable list');}
end; (* of case structure *)
Writeln;
end; (* of Count loop *)
end. (* of main program *)
{ Result of execution
1 TRUE is true, and this is dumb.
2 Small even number.
3 Boo Boo Boo
4 Small even number.
5 This number is not in the allowable list
6 Small even number.
7 Big number
8 Big number
9 Big number
10 This number is not in the allowable list
}
|
unit u_LODef;
//同频异频: (IO 1~8)
//使用IO6, IO7, IO8控制
//同频时:IO6 = H, IO7 = H, IO8 = L
//异频时:IO6 = L, IO7 = L, IO8 = H
interface
uses
CnCommon;
type
//---------------------LO 测试使用的结构-------------------------------------
TLOEnvironType = (loeNormalFirst, loeHighTemp, loeLowTemp, loeNormalFinal,
loeDelivery, loeSharinked, loeTempStriked);
TPortPhaseNoise = Record
Checked: Boolean;
Values: Array of Array[0..2] of Double; //1个端口测试N个频率下的1K, 10K, 100K下的相噪
End;
TPortSpurious = Record
Checked: Boolean;
Values: Array of Double; //1个端口测试N个频点
End;
TPortSignalPower = Record
Checked: Boolean;
Values: Array of Double; //3个端口测试N个频点
End;
TSignalPower = Array [0..2] of TPortSignalPower;
TSpurious = Array[0..0] of TPortSpurious;
TPhaseNoise = Array[0..0] of TPortPhaseNoise;
TLOUnit = Record
PhaseNoise : TPhaseNoise;
SignalPower : TSignalPower;
Spurious : TSpurious;
Offset : Double;
Procedure InitTestType(Environ: TLOEnvironType);
function CalcuTotalStep: Integer;
function NeedMeasurePhaseNoise(): Boolean;
function NeedMeasureSignalPower(): Boolean;
function NeedMeasureSpurious(): Boolean;
End;
TLOMesureLog = Record
AutoNext : Boolean;
EnvType : TLOEnvironType;
LOUnits : Array[0..1] of TLOUnit;
Procedure InitTestType(Environ: TLOEnvironType);
function CalcuTotalStep: Integer;
function NeedMeasurePhaseNoise(): Boolean;
function NeedMeasureSignalPower(): Boolean;
function NeedMeasureSpurious(): Boolean;
Procedure ToExcel(const SN: String; var Disqualification: Boolean);
End;
PLOMesureLog = ^TLOMesureLog;
const
CONST_THREASHOLD_LO_PN: Array[0..2] of Double = (-93, -99, -107);
CONST_SUBLO1_FREQ: Array[0..3] of Double = (1670, 2050, 2270, 2870);
CONST_SUBLO1_APPFREQ: Array[0..3] of Double = (270, 250, 270, 270);
CONST_SUBLO2_FREQ: Array[0..1] of Double = (790, 860);
CONST_SUBLO_PN_OFFSET: Array[0..2] of String = ('1KHz', '10KHz', '100KHz');
LO_ENV_DESC: Array[Low(TLOEnvironType)..HIgh(TLOEnvironType)] of string = (
'初测',
'高温',
'低温',
'终测',
'验收',
'震动后',
'温冲后'
);
LO_RES_NAME: Array[Low(TLOEnvironType)..HIgh(TLOEnvironType)] of string = (
'LO_TFIR',
'LO_HIG',
'LO_LOW',
'LO_TFIN',
'LO_DELI',
'LO_SSTR',
'LO_TSTR'
);
implementation
uses
Classes, Graphics,
XLSSheetData5, Xc12Utils5, SysUtils, u_ExamineGlobal, XLSReadWriteII5;
{ TMesureLog }
function TLOUnit.CalcuTotalStep: Integer;
var
i: Integer;
begin
Result:= 0;
for i := 0 to Length(self.PhaseNoise) - 1 do
begin
if self.PhaseNoise[i].Checked then
Inc(Result, Length(PhaseNoise[i].Values)); //相噪是一次测出的
end;
for i := 0 to Length(self.SignalPower) - 1 do
begin
if self.SignalPower[i].Checked then
Inc(Result, Length(SignalPower[i].Values));
end;
for i := 0 to Length(self.Spurious) - 1 do
begin
if self.Spurious[i].Checked then
Inc(Result, Length(Spurious[i].Values));
end;
end;
function TLOMesureLog.CalcuTotalStep: Integer;
var
i: integer;
begin
Result:= 0;
for i := 0 to Length(LOUnits) - 1 do
begin
Inc(Result, LOUnits[i].CalcuTotalStep);
end;
end;
procedure TLOMesureLog.InitTestType(Environ: TLOEnvironType);
var
iUnit: Integer;
iPort: Integer;
FreqCount: Integer;
begin
EnvType:= Environ;
for iUnit := 0 to Length(LOUnits) - 1 do
begin
LOUnits[iUnit].InitTestType(Environ);
if iUnit = 0 then
begin
FreqCount:= Length(CONST_SUBLO1_FREQ);
end
else
begin
FreqCount:= Length(CONST_SUBLO2_FREQ);
end;
SetLength(LOUnits[iUnit].PhaseNoise[0].Values, FreqCount);
SetLength(LOUnits[iUnit].Spurious[0].Values, FreqCount);
for iPort := 0 to Length(LOUnits[iUnit].SignalPower) - 1 do
begin
SetLength(LOUnits[iUnit].SignalPower[iPort].Values, FreqCount);
end;
end;
end;
function TLOMesureLog.NeedMeasurePhaseNoise: Boolean;
var
i: Integer;
begin
Result:= False;
for i := 0 to Length(self.LOUnits) - 1 do
begin
Result:= Result or LOUnits[i].NeedMeasurePhaseNoise;
end;
end;
function TLOMesureLog.NeedMeasureSignalPower: Boolean;
var
i: Integer;
begin
Result:= False;
for i := 0 to Length(self.LOUnits) - 1 do
begin
Result:= Result or LOUnits[i].NeedMeasureSignalPower;
end;
end;
function TLOMesureLog.NeedMeasureSpurious: Boolean;
var
i: Integer;
begin
Result:= False;
for i := 0 to Length(self.LOUnits) - 1 do
begin
Result:= Result or LOUnits[i].NeedMeasureSpurious;
end;
end;
// for i := Low(PhaseNoise) to High(PhaseNoise) do
// begin
// PhaseNoise[i].Checked:= True;
// end;
//
// for i := Low(SignalLevel) to High(SignalLevel) do
// begin
// SignalLevel[i].Checked:= True;
// end;
//
// for i := Low(Spurious) to High(Spurious) do
// begin
// SetLength(Spurious[i].Values, 5);
// Spurious[i].Checked:= True;
// end;
procedure TLOUnit.InitTestType(Environ: TLOEnvironType);
begin
//
end;
function TLOUnit.NeedMeasurePhaseNoise(): Boolean;
var
i: Integer;
begin
Result:= False;
for i := 0 to Length(PhaseNoise) - 1 do
begin
Result:= Result or PhaseNoise[i].Checked;
if Result then
Break;
end;
end;
function TLOUnit.NeedMeasureSignalPower: Boolean;
var
i: Integer;
begin
Result:= False;
for i := 0 to Length(SignalPower) - 1 do
begin
Result:= Result or SignalPower[i].Checked;
if Result then
Break;
end;
end;
function TLOUnit.NeedMeasureSpurious: Boolean;
var
i: Integer;
begin
Result:= False;
for i := 0 to Length(Spurious) - 1 do
begin
Result:= Result or Spurious[i].Checked;
if Result then
Break;
end;
end;
procedure TLOMesureLog.ToExcel(const SN: String; var Disqualification: Boolean);
Procedure DataToSheet(ASheet: TXLSWorksheet);
Procedure Spurious2Sheet();
var
iUnit, iFreq, ARowNum, AColNum, CurrRow, CurrCol: Integer;
AValue: Double;
begin
if NeedMeasureSpurious() then
begin
RefStrToColRow('I16', AColNum, ARowNum);
for iUnit := 0 to Length(LOUnits) - 1 do
begin
if LOUnits[iUnit].Spurious[0].Checked then
begin
for iFreq := 0 to Length(LOUnits[iUnit].Spurious[0].Values) - 1 do
begin
AValue:= LOUnits[iUnit].Spurious[0].Values[iFreq];
CurrRow:= ARowNum + iFreq + iUnit * 9;
CurrCol:= AColNum;
if AValue >= 65 then
begin
ASheet.Cell[CurrCol, CurrRow].FontColor:= clBlack
end
else
begin
ASheet.Cell[CurrCol, CurrRow].FontColor:= $FF0000;
Disqualification:= Disqualification or True;
end;
ASheet.AsString[CurrCol, CurrRow]:= Format('%.1f', [AValue]);
end;
end;
end;
end;
end;
Procedure PhaseNoise2Sheet();
var
iOffset: Integer;
iFreq: Integer;
iUnit: Integer;
ARowNum, AColNum, CurrRow, CurrCol: Integer;
AValue: Double;
begin
if NeedMeasurePhaseNoise() then
begin
RefStrToColRow('F16', AColNum, ARowNum);
for iUnit := 0 to Length(LOUnits) - 1 do
begin
if LOUnits[iUnit].PhaseNoise[0].Checked then
begin
for iFreq := 0 to Length(LOUnits[iUnit].PhaseNoise[0].Values) - 1 do
begin
for iOffset := 0 to Length(LOUnits[iUnit].PhaseNoise[0].Values[iFreq]) - 1 do
begin
AValue:= LOUnits[iUnit].PhaseNoise[0].Values[iFreq][iOffset];
//Row + iNoise
//COL + 4 * iFreq + iPort + 16 * iUnit
CurrRow:= ARowNum + iFreq + iUnit * 9;
CurrCol:= AColNum + iOffset;
if AValue <= CONST_THREASHOLD_LO_PN[iOffset] then
begin
ASheet.Cell[CurrCol, CurrRow].FontColor:= clBlack
end
else
begin
ASheet.Cell[CurrCol, CurrRow].FontColor:= $FF0000;
Disqualification:= Disqualification or True;
end;
ASheet.AsString[CurrCol, CurrRow]:= Format('%.1f', [AValue]);
end;
end;
end;
end;
end;
end;
Procedure Level2Sheet();
var
iUnit, iPort, iFreq: Integer;
ARowNum: Integer;
AColNum: Integer;
AValue: Double;
CurrRow, CurrCol: Integer;
begin
if NeedMeasureSignalPower() then
begin
RefStrToColRow('C16', AColNum, ARowNum);
for iUnit := 0 to Length(LOUnits) - 1 do
begin
for iPort := 0 to Length(LOUnits[iUnit].SignalPower) - 1 do
if LOUnits[iUnit].SignalPower[iPort].Checked then
begin
for iFreq := 0 to Length(LOUnits[iUnit].SignalPower[iPort].Values) - 1 do
begin
AValue:= LOUnits[iUnit].SignalPower[iPort].Values[iFreq];
CurrRow:= ARowNum + iFreq + iUnit * 9;
CurrCol:= AColNum + iPort;
if AValue >= 3 then
begin
ASheet.Cell[CurrCol, CurrRow].FontColor:= clBlack
end
else
begin
ASheet.Cell[CurrCol, CurrRow].FontColor:= $FF0000;
Disqualification:= Disqualification or True;
end;
ASheet.AsString[CurrCol, CurrRow]:= Format('%.1f', [AValue]);
if (iUnit = 0) and (iPort = 0) and (iFreq = 0) and (Not (EnvType in [loeSharinked, loeTempStriked])) then
begin
AValue:= LOUnits[iUnit].Offset;
if AValue >= 3 then
begin
ASheet.Cell[CurrCol + 7, CurrRow].FontColor:= clBlack
end
else
begin
ASheet.Cell[CurrCol + 7, CurrRow].FontColor:= $FF0000;
Disqualification:= Disqualification or True;
end;
ASheet.AsString[CurrCol + 7, CurrRow]:= '100Hz';
end;
end;
end;
end;
end;
end;
var
ARowNum: Integer;
AColNum: Integer;
begin
if EnvType = loeDelivery then
begin
RefStrToColRow('J4', AColNum, ARowNum);
ASheet.AsString[AColNum, ARowNum]:= SN;
end
else
begin
RefStrToColRow('C4', AColNum, ARowNum);
ASheet.AsString[AColNum, ARowNum]:= SN;
RefStrToColRow('I4', AColNum, ARowNum);
ASheet.AsString[AColNum, ARowNum]:= LO_ENV_DESC[EnvType];
end;
//相噪
PhaseNoise2Sheet();
//电平
Level2Sheet();
//杂散抑制
Spurious2Sheet();
end;
var
Book: TXLSReadWriteII5;
FullFileName: String;
rs: TResourceStream;
TemplateFullFileName: String;
begin
Disqualification:= False;
if Not DirectoryExists(Excel_Dir) then
begin
ForceDirectories(Excel_Dir);
end;
FullFileName:= Excel_Dir + ProductSN + '_本振_' + LO_ENV_DESC[EnvType] + '.xlsx';
//如果没有模板文件,则生成模板文件
TemplateFullFileName:= _CnExtractFilePath(ParamStr(0)) + 'template\LO\' + LO_ENV_DESC[EnvType] + '.xlsx';
ForceDirectories(_CnExtractFileDir(TemplateFullFileName));
if Not FileExists(TemplateFullFileName) then
begin
rs:= TResourceStream.Create(HInstance, LO_RES_NAME[EnvType], 'MYFILE');
try
rs.SaveToFile(TemplateFullFileName);
finally
rs.Free;
end;
end;
Book:= TXLSReadWriteII5.Create(Nil);
try
if FileExists(FullFileName) then
Book.LoadFromFile(FullFileName)
else
Book.LoadFromFile(TemplateFullFileName);
DataToSheet(Book.Sheets[0]);
Book.SaveToFile(FullFileName);
finally
Book.Free;
end;
end;
end.
|
unit Pprntprc;
interface
uses WinTypes, WinProcs, Classes, Graphics, Forms, Controls, Buttons, SysUtils,
StdCtrls, ExtCtrls, RPFiler, RPDefine, RPBase, RPCanvas, RPrinter, Types,
JPEG, UPrntPrc, Dialogs; {Print parcel information}
type
TParcelPrintDialog = class(TForm)
CancelButton: TBitBtn;
GroupBox1: TGroupBox;
ResidentialInventoryCheckBox: TCheckBox;
CommercialInventoryCheckBox: TCheckBox;
SalesCheckBox: TCheckBox;
ExemptionCheckBox: TCheckBox;
SpecialDistrictCheckBox: TCheckBox;
BaseInformationCheckBox: TCheckBox;
AssessmentsCheckBox: TCheckBox;
ReportPrinter: TReportPrinter;
ReportFiler: TReportFiler;
PrintButton: TBitBtn;
CheckAllButton: TBitBtn;
UncheckAllButton: TBitBtn;
PrinterSetupButton: TBitBtn;
PrinterSetupDialog: TPrinterSetupDialog;
PrintDialog: TPrintDialog;
PictureCheckBox: TCheckBox;
TaxableValuesGroupBox2: TGroupBox;
SchoolTaxableCheckBox: TCheckBox;
TownTaxableCheckBox: TCheckBox;
CountyTaxableCheckBox: TCheckBox;
NotesCheckBox: TCheckBox;
cb_Permits: TCheckBox;
cbSketches: TCheckBox;
procedure PrintButtonClick(Sender: TObject);
procedure ReportPrint(Sender: TObject);
procedure CancelButtonClick(Sender: TObject);
procedure CheckAllButtonClick(Sender: TObject);
procedure UncheckAllButtonClick(Sender: TObject);
procedure PrinterSetupButtonClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
SwisSBLKey : String;
ProcessingType : Integer;
Options : OptionsSet;
end;
var
ParcelPrintDialog: TParcelPrintDialog;
implementation
uses GlblVars, WinUtils, Utilitys, GlblCnst, PASUtils,
PasTypes, Preview;
{$R *.DFM}
{===============================================================}
Procedure TParcelPrintDialog.FormShow(Sender: TObject);
{CHG04242002-1: Make sure that the searcher does not have the option to print notes.}
begin
If GlblUserIsSearcher
then NotesCheckBox.Visible := False;
{CHG04302006-1(2.9.7.1): Allow the for permit printing.}
If _Compare(GlblBuildingSystemLinkType, bldMunicity, coEqual)
then cb_Permits.Visible := True
else cb_Permits.Checked := False;
{CHG04262012-1(2.28.4.19)[PAS-305]: Add sketches to the F5 print.}
If (GlblUsesSketches and
ApexIsInstalledOnComputer)
then cbSketches.Visible := True;
end; {FormShow}
{===============================================================}
Procedure TParcelPrintDialog.CheckAllButtonClick(Sender: TObject);
begin
ResidentialInventoryCheckBox.Checked := True;
CommercialInventoryCheckBox.Checked := True;
SalesCheckBox.Checked := True;
ExemptionCheckBox.Checked := True;
SpecialDistrictCheckBox.Checked := True;
BaseInformationCheckBox.Checked := True;
AssessmentsCheckBox.Checked := True;
CountyTaxableCheckBox.Checked := True;
TownTaxableCheckBox.Checked := True;
SchoolTaxableCheckBox.Checked := True;
If not GlblUserIsSearcher
then NotesCheckBox.Checked := True;
{CHG04302006-1(2.9.7.1): Allow the for permit printing.}
If GlblUsesPASPermits
then cb_Permits.Checked := True;
{CHG04262012-1(2.28.4.19)[PAS-305]: Add sketches to the F5 print.}
If (GlblUsesSketches and
ApexIsInstalledOnComputer)
then cbSketches.Checked := True;
end; {CheckAllButtonClick}
{=================================================================}
Procedure TParcelPrintDialog.UncheckAllButtonClick(Sender: TObject);
begin
ResidentialInventoryCheckBox.Checked := False;
CommercialInventoryCheckBox.Checked := False;
SalesCheckBox.Checked := False;
ExemptionCheckBox.Checked := False;
SpecialDistrictCheckBox.Checked := False;
BaseInformationCheckBox.Checked := False;
AssessmentsCheckBox.Checked := False;
CountyTaxableCheckBox.Checked := False;
TownTaxableCheckBox.Checked := False;
SchoolTaxableCheckBox.Checked := False;
If not GlblUserIsSearcher
then NotesCheckBox.Checked := False;
{CHG04302006-1(2.9.7.1): Allow the for permit printing.}
If GlblUsesPASPermits
then cb_Permits.Checked := False;
{CHG04262012-1(2.28.4.19)[PAS-305]: Add sketches to the F5 print.}
If (GlblUsesSketches and
ApexIsInstalledOnComputer)
then cbSketches.Visible := False;
end; {UncheckAllButtonClick}
{==========================================================}
Procedure TParcelPrintDialog.PrinterSetupButtonClick(Sender: TObject);
begin
PrintDialog.Execute;
end;
{==========================================================}
Procedure TParcelPrintDialog.PrintButtonClick(Sender: TObject);
var
NewFileName : String;
TempFile : File;
Quit : Boolean;
begin
{FXX09301998-1: Disable print button after clicking to avoid clicking twice.}
PrintButton.Enabled := False;
Application.ProcessMessages;
Options := [];
If BaseInformationCheckBox.Checked
then Options := Options + [ptBaseInformation];
If AssessmentsCheckBox.Checked
then Options := Options + [ptAssessments];
If SpecialDistrictCheckBox.Checked
then Options := Options + [ptSpecialDistricts];
If ExemptionCheckBox.Checked
then Options := Options + [ptExemptions];
If SalesCheckBox.Checked
then Options := Options + [ptSales];
If ResidentialInventoryCheckBox.Checked
then Options := Options + [ptResidentialInventory];
If CommercialInventoryCheckBox.Checked
then Options := Options + [ptCommercialInventory];
If PictureCheckBox.Checked
then Options := Options + [ptPictures];
{CHG09192001-2: Allow them to select which taxable values to show.}
If CountyTaxableCheckBox.Checked
then Options := Options + [ptCountyTaxable];
If TownTaxableCheckBox.Checked
then Options := Options + [ptTownTaxable];
If SchoolTaxableCheckBox.Checked
then Options := Options + [ptSchoolTaxable];
{CHG03282002-11: Allow them to print notes.}
If (NotesCheckBox.Checked and
(not GlblUserIsSearcher))
then Options := Options + [ptNotes];
{FXX12081999-1: Make sure that if they are not allowed to see NY,
we don't print it.}
If GlblUserIsSearcher
then
begin
If SearcherCanSeeNYValues
then Options := Options + [ptPrintNextYear];
end
else
If ((not GlblDoNotPrintNextYearOnF5) or
_Compare(GlblProcessingType, NextYear, coEqual))
then Options := Options + [ptPrintNextYear];
{CHG04302006-1(2.9.7.1): Allow the for permit printing.}
If (cb_Permits.Checked and
(not GlblUserIsSearcher))
then Options := Options + [ptPermits];
{CHG04262012-1(2.28.4.19)[PAS-305]: Add sketches to the F5 print.}
If GlblUsesSketches
then Options := Options + [ptSketches];
{FXX10231998-1: Do not keep showing the print dialog each time.}
{CHG10131998-1: Set the printer settings based on what printer they selected
only - they no longer need to worry about paper or landscape
mode.}
AssignPrinterSettings(PrintDialog, ReportPrinter, ReportFiler, [ptLaser], False, Quit);
If PrintDialog.PrintToFile
then
begin
NewFileName := GetPrintFileName(Self.Caption, True);
ReportFiler.FileName := NewFileName;
try
PreviewForm := TPreviewForm.Create(self);
PreviewForm.FilePrinter.FileName := NewFileName;
PreviewForm.FilePreview.FileName := NewFileName;
ReportFiler.Execute;
PreviewForm.ShowModal;
finally
PreviewForm.Free;
{Now delete the file.}
try
AssignFile(TempFile, NewFileName);
OldDeleteFile(NewFileName);
finally
{We don't care if it does not get deleted, so we won't put up an
error message.}
try
ChDir(GlblProgramDir);
except
end;
end;
end; {If PrintRangeDlg.PreviewPrint}
end {They did not select preview, so we will go
right to the printer.}
else ReportPrinter.Execute;
Close;
PrintButton.Enabled := True;
end; {PrintButtonClick}
{============================================================}
Procedure TParcelPrintDialog.ReportPrint(Sender: TObject);
begin
PrintAParcel(Sender, SwisSBLKey, ProcessingType, Options);
end;
{==============================================================}
Procedure TParcelPrintDialog.CancelButtonClick(Sender: TObject);
begin
Close;
end;
end.
|
unit Dialogs;
{
LLCL - FPC/Lazarus Light LCL
based upon
LVCL - Very LIGHT VCL
----------------------------
This file is a part of the Light LCL (LLCL).
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
This Source Code Form is "Incompatible With Secondary Licenses",
as defined by the Mozilla Public License, v. 2.0.
Copyright (c) 2015-2016 ChrisF
Based upon the Very LIGHT VCL (LVCL):
Copyright (c) 2008 Arnaud Bouchez - http://bouchez.info
Portions Copyright (c) 2001 Paul Toth - http://tothpaul.free.fr
Version 1.02:
Version 1.01:
* SelectDirectory added (for FPC/Lazarus)
* TSelectDirectoryDialog added for FPC/Lazarus (not enabled by default - see LLCL_OPT_USESELECTDIRECTORYDIALOG in LLCLOptions.inc)
Version 1.00:
* Application.BiDiMode used for ShowMessage (through Application.MessageBox)
* TOpenDialog and TSaveDialog implemented
}
// Original notes from LVCL
{
LVCL - Very LIGHT VCL
----------------------------
Tiny replacement for the standard VCL Dialogs.pas
Just put the LVCL directory in your Project/Options/Path/SearchPath
and your .EXE will shrink from 300KB to 30KB
Notes:
- dummy unit code to shrink exe size -> use Windows.MessageBox() instead
The contents of this file are subject to the Mozilla Public License
Version 1.1 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL
Software distributed under the License is distributed on an "AS IS"
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
License for the specific language governing rights and limitations
under the License.
The Initial Developer of the Original Code is Arnaud Bouchez.
This work is Copyright (C) 2008 Arnaud Bouchez - http://bouchez.info
Emulates the original Delphi/Kylix Cross-Platform Runtime Library
(c)2000,2001 Borland Software Corporation
Portions created by Paul Toth are Copyright (C) 2001 Paul Toth. http://tothpaul.free.fr
All Rights Reserved.
}
{$IFDEF FPC}
{$define LLCL_FPC_MODESECTION}
{$I LLCLFPCInc.inc} // For mode
{$undef LLCL_FPC_MODESECTION}
{$ENDIF}
{$I LLCLOptions.inc} // Options
//------------------------------------------------------------------------------
interface
uses
{$ifdef LLCL_OPT_USEDIALOG}
LLCLOSInt, Windows, {$IFDEF FPC}LMessages{$ELSE}Messages{$ENDIF},
Classes, Controls;
{$else}
LLCLOSInt, Windows;
{$endif}
{$ifdef LLCL_OPT_USEDIALOG}
type
TOpenOption = (ofReadOnly, ofOverwritePrompt, ofHideReadOnly, ofNoChangeDir,
ofShowHelp, ofNoValidate, ofAllowMultiSelect, ofExtensionDifferent, ofPathMustExist,
ofFileMustExist, ofCreatePrompt, ofShareAware, ofNoReadOnlyReturn, ofNoTestFileCreate,
ofNoNetworkButton, ofNoLongNames, ofOldStyleDialog, ofNoDereferenceLinks, ofEnableIncludeNotify,
ofEnableSizing, ofDontAddToRecent, ofForceShowHidden,
ofViewDetail, ofAutoPreview);
TOpenOptions = set of TOpenOption;
TOpenDialog = class(TNonVisualControl)
private
fDefaultExt: string;
fFileName: string;
fFilter: string;
fFilterIndex: integer;
fInitialDir: string;
fOptions: TOpenOptions;
fTitle: string;
fFiles: TStringList;
protected
procedure ReadProperty(const PropName: string; Reader: TReader); override;
procedure ControlInit(RuntimeCreate: boolean); override;
procedure ControlCall(var Msg: TMessage); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function Execute: boolean; virtual;
property DefaultExt: string read fDefaultExt write fDefaultExt;
property FileName: string read fFileName write fFileName;
property Filter: string read fFilter write fFilter;
property FilterIndex: integer read fFilterIndex write fFilterIndex;
property InitialDir: string read fInitialDir write fInitialDir;
property Options: TOpenOptions read fOptions write fOptions;
property Title: string read fTitle write fTitle;
property Files: TStringList read fFiles write fFiles;
end;
TSaveDialog = class(TOpenDialog)
public
constructor Create(AOwner: TComponent); override;
end;
{$ifdef LLCL_OPT_USESELECTDIRECTORYDIALOG}
TSelectDirectoryDialog = class(TOpenDialog)
public
constructor Create(AOwner: TComponent); override;
function Execute: boolean; override;
end;
{$endif LLCL_OPT_USESELECTDIRECTORYDIALOG}
{$endif LLCL_OPT_USEDIALOG}
procedure ShowMessage(const Msg: string);
{$IFDEF FPC} // SelectDirectory is in FileCtrl.pas for Delphi
function SelectDirectory(const Caption: string; const InitialDirectory: string; out Directory: string): Boolean; overload;
{$ENDIF FPC}
//------------------------------------------------------------------------------
implementation
uses
{$ifdef LLCL_OPT_USEDIALOG}
{$IFDEF FPC}FileCtrl,{$ELSE}CommDlg,{$ENDIF}
Forms, SysUtils;
{$else}
{$IFDEF FPC}FileCtrl,{$ENDIF}
Forms;
{$endif}
{$IFDEF FPC}
{$PUSH} {$HINTS OFF}
{$ENDIF}
function CharReplace(const Str: string; OldChar, NewChar: Char): string; forward;
const
MB_ICONMASK = $000000F0;
//------------------------------------------------------------------------------
{$IFDEF FPC}
// Dummy function to avoid compilation hint (LMessages or LLCLOSInt not used)
function LMessages_Dummy({$ifdef LLCL_OPT_USEDIALOG}const Msg: TLMCommand{$endif}): boolean;
begin
result := (LLCL_GetLastError()=0);
end;
{$ENDIF FPC}
// case sensitive - all occurences
function CharReplace(const Str: string; OldChar, NewChar: Char): string;
var i: integer;
begin
result := Str;
for i := 1 to length(Str) do
if result[i]=OldChar then
result[i] := NewChar;
end;
//------------------------------------------------------------------------------
procedure ShowMessage(const Msg: string);
begin
Application.MessageBox(@Msg[1], @Application.Title[1], MB_OK or MB_ICONMASK);
end;
{$IFDEF FPC}
function SelectDirectory(const Caption: string; const InitialDirectory: string; out Directory: string): Boolean;
begin
result := FC_SelectDirectory(Caption, InitialDirectory, [sdNewFolder, sdShowEdit, sdNewUI], Directory);
end;
{$ENDIF FPC}
{$ifdef LLCL_OPT_USEDIALOG}
//------------------------------------------------------------------------------
{ TOpenDialog }
constructor TOpenDialog.Create(AOwner: TComponent);
begin
ATType := ATTOpenDialog;
fFilterIndex := 1;
{$IFDEF FPC}
fOptions := [ofEnableSizing, ofViewDetail];
{$ELSE FPC}
fOptions := [ofHideReadOnly, ofEnableSizing];
{$ENDIF FPC}
fFiles := TStringList.Create;
inherited; // After (ControlInit called after create at runtime)
end;
destructor TOpenDialog.Destroy;
begin
fFiles.Free;
inherited;
end;
procedure TOpenDialog.ReadProperty(const PropName: string; Reader: TReader);
const Properties: array[0..6] of PChar = (
'DefaultExt', 'FileName', 'Filter', 'FilterIndex', 'InitialDir',
'Options', 'Title');
begin
case StringIndex(PropName, Properties) of
0 : fDefaultExt := Reader.StringProperty;
1 : fFileName := Reader.StringProperty;
2 : fFilter := Reader.StringProperty;
3 : fFilterIndex := Reader.IntegerProperty;
4 : fInitialDir := Reader.StringProperty;
5 : Reader.SetProperty(fOptions, TypeInfo(TOpenOption));
6 : fTitle := Reader.StringProperty;
else inherited;
end;
end;
procedure TOpenDialog.ControlInit(RuntimeCreate: boolean);
begin
end;
procedure TOpenDialog.ControlCall(var Msg: TMessage); // (Never called)
begin
end;
function TOpenDialog.Execute: boolean;
const // ofOldStyleDialog, ofViewDetail, ofAutoPreview have no direct equivalence
SYSTEM_OPTIONS: array[Low(TOpenOption)..High(TOpenOption)] of cardinal = (
OFN_READONLY, OFN_OVERWRITEPROMPT, OFN_HIDEREADONLY, OFN_NOCHANGEDIR,
OFN_SHOWHELP, OFN_NOVALIDATE, OFN_ALLOWMULTISELECT, OFN_EXTENSIONDIFFERENT, OFN_PATHMUSTEXIST,
OFN_FILEMUSTEXIST, OFN_CREATEPROMPT, OFN_SHAREAWARE, OFN_NOREADONLYRETURN, OFN_NOTESTFILECREATE,
OFN_NONETWORKBUTTON, OFN_NOLONGNAMES, 0, OFN_NODEREFERENCELINKS, OFN_ENABLEINCLUDENOTIFY,
OFN_ENABLESIZING, OFN_DONTADDTORECENT, OFN_FORCESHOWHIDDEN,
0, 0 );
var OpenFileName: TOpenFileName;
var OpenStrParam: TOpenStrParam;
var OneOpenOption: TOpenOption;
var MultiPath: string;
var i1, i2: integer;
var s1, s2: string;
begin
FillChar(OpenFileName, SizeOf(OpenFileName), 0);
with OpenFileName do
begin
lStructSize := SizeOf(OpenFileName);
if not CheckWin32Version(LLCL_WIN2000_MAJ, LLCL_WIN2000_MIN) then // Or WINVERS_98ME ?
lStructSize := lStructSize - 8 - SizeOf(Pointer);
hWndOwner := Parent.Handle;
hInstance := hInstance;
if fFilterIndex=0 then fFilterIndex := 1;
nFilterIndex := fFilterIndex;
for OneOpenOption := Low(TOpenOption) to High(TOpenOption) do
if OneOpenOption in fOptions then
Flags := Flags or SYSTEM_OPTIONS[OneOpenOption];
Flags := Flags or OFN_EXPLORER;
end;
with OpenStrParam do
begin
sFilter := CharReplace(fFilter, '|', Chr(0));
sFileName := fFileName;
if fInitialDir='' then
sInitialDir := string(GetCurrentDir())
else
sInitialDir := fInitialDir;
sTitle := fTitle;
sDefExt := fDefaultExt;
end;
result := LLCLS_GetOpenSaveFileName(OpenFileName, integer(ATType=ATTSaveDialog), OpenStrParam);
if result then
begin
fFiles.Clear;
MultiPath := '';
s1 := OpenStrParam.sFileName;
for i1 := 1 to OpenStrParam.NbrFileNames do
begin
i2 := Pos('|', s1);
s2 := Copy(s1, 1, i2-1);
if (OpenStrParam.NbrFileNames>1) and (i1=1) then
MultiPath := s2+PathDelim
else
begin
s2 := MultiPath+s2;
if i1<3 then fFileName := s2; // if i1=1 (1 file only), or i1=2 (multi select)
fFiles.Add(s2);
end;
s1 := Copy(s1, i2+1, length(s1)-i2);
end;
end;
end;
{ TSaveDialog }
constructor TSaveDialog.Create(AOwner: TComponent);
begin
inherited;
ATType := ATTSaveDialog;
end;
{$ifdef LLCL_OPT_USESELECTDIRECTORYDIALOG}
{ TSelectDirectoryDialog }
constructor TSelectDirectoryDialog.Create(AOwner: TComponent);
begin
inherited;
ATType := ATTSelectDirectoryDialog;
end;
function TSelectDirectoryDialog.Execute: boolean;
var sdOptions: TSelectDirExtOpts;
begin
if ofOldStyleDialog in Options then
sdOptions := []
else
sdOptions := [sdNewFolder, sdShowEdit, sdNewUI];
result := FC_SelectDirectory(fTitle, fInitialDir, sdOptions, fFileName);
end;
{$endif LLCL_OPT_USESELECTDIRECTORYDIALOG}
//------------------------------------------------------------------------------
{$endif}
{$ifdef LLCL_OPT_USEDIALOG}
initialization
RegisterClasses([TOpenDialog, TSaveDialog {$ifdef LLCL_OPT_USESELECTDIRECTORYDIALOG}, TSelectDirectoryDialog{$endif}]);
{$endif}
{$IFDEF FPC}
{$POP}
{$ENDIF}
end.
|
{ *************************************************************************************
Unit para criar uma telade aguarde modal, enquanto o processamento segue sem interrupção
Desenvolvido por
** Ivan Cesar - ivancesarf@gmail.com Skype: proadvanced **
Esta unit é disponibilizada como está, não existe nehuma responsabilidade de suporte
Use por sua conta e risco
Pode ser utilizada e alterada a vontade, desde que mantidos os créditos originais
Caso implemente alguma melhoria, peço por gentileza que me disponibilize as alterações
************************************************************************************** }
unit UFrameAguarde;
interface
uses
Classes,
Forms,
Dialogs,
StdCtrls,
Windows,
ExtCtrls,
Math,
StrUtils,
Controls,
SysUtils,
ComCtrls,
Graphics,
Messages,
UITypes,
AppEvnts,
Types;
type
TMsgDlgType = (mtWarning, mtError, mtInformation, mtConfirmation, mtCustom);
TMsgDlgBtn = (mbYes, mbNo, mbOK, mbCancel, mbAbort, mbRetry, mbIgnore, mbAll, mbNoToAll, mbYesToAll, mbHelp, mbClose);
TMsgDlgButtons = set of TMsgDlgBtn;
procedure MessageBoxError(const Msg: string);
function MessageBoxYesNo(const Msg: string): Integer;
function MessageBoxYesNoCancel(const Msg: string): Integer;
procedure MessageBoxInformation(const Msg: string);
function MessageBox(const Msg: string; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; DefaultButton: TMsgDlgBtn): Integer;
procedure WaitShowMessage(const Msg: string = 'Processando solicitação ...');
procedure WaitShowProgress(const Msg: string = 'Processando solicitação ...'; ExecProc: TProc = nil); overload;
procedure WaitShowProgress(const Msg: string = 'Processando solicitação ...'; ExecFunc: TFunc<Boolean> = nil); overload;
procedure WaitCloseMessage;
implementation
resourcestring
SMsgDlgWarning = 'Atenção';
SMsgDlgError = 'Erro';
SMsgDlgInformation = 'Informação';
SMsgDlgConfirm = 'Confirme';
SMsgDlgYes = '&Sim';
SMsgDlgNo = '&Não';
SMsgDlgOK = 'OK';
SMsgDlgCancel = 'Cancelar';
SMsgDlgAbort = '&Abortar';
SMsgDlgRetry = '&Repetir';
SMsgDlgIgnore = '&Ignorar';
SMsgDlgAll = '&Todos';
SMsgDlgNoToAll = 'Nã&o à todos';
SMsgDlgYesToAll = 'Si&m à todos';
SMsgDlgHelp = 'Aj&uda';
SMsgDlgClose = '&Fechar';
SMsgDlgCopyToClipBrd = 'Copiar mensagem';
SHintMsgDlgCopyToClipBrd = 'Copia a mensagem para a área de transferência';
var
Captions: array [TMsgDlgType] of Pointer = (
@SMsgDlgWarning,
@SMsgDlgError,
@SMsgDlgInformation,
@SMsgDlgConfirm,
nil
);
IconIDs: array [TMsgDlgType] of PChar = (
IDI_EXCLAMATION,
IDI_HAND,
IDI_ASTERISK,
IDI_QUESTION,
nil
);
ButtonCaptions: array [TMsgDlgBtn] of Pointer = (
@SMsgDlgYes,
@SMsgDlgNo,
@SMsgDlgOK,
@SMsgDlgCancel,
@SMsgDlgAbort,
@SMsgDlgRetry,
@SMsgDlgIgnore,
@SMsgDlgAll,
@SMsgDlgNoToAll,
@SMsgDlgYesToAll,
@SMsgDlgHelp,
@SMsgDlgClose
);
ButtonNames: array [TMsgDlgBtn] of string = (
'Yes',
'No',
'OK',
'Cancel',
'Abort',
'Retry',
'Ignore',
'All',
'NoToAll',
'YesToAll',
'Help',
'Close'
);
ModalResults: array [TMsgDlgBtn] of Integer = (
mrYes,
mrNo,
mrOk,
mrCancel,
mrAbort,
mrRetry,
mrIgnore,
mrAll,
mrNoToAll,
mrYesToAll,
0,
mrClose
);
ButtonWidths: array [TMsgDlgBtn] of Integer; // inicializa com zero
type
TMessageForm = class(TForm)
private
RichEditMessage: TRichEdit;
procedure HelpButtonClick(Sender: TObject);
protected
procedure CustomKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure CustomEnter(Sender: TObject);
procedure CutomLabelClick(Sender: TObject);
procedure CustomWriteTextToClipBoard;
public
constructor CreateNew(AOwner: TComponent; Dummy: Integer = 0); override;
end;
type
TWaitForm = class(TForm)
private
PanelContainer: TPanel;
LabelMessage : TLabel;
AppEvents : TApplicationEvents;
protected
procedure CustomCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure CustomAppEventsModalBegin(Sender: TObject);
end;
{ TMessageForm }
var
FExeVErsion: string;
constructor TMessageForm.CreateNew(AOwner: TComponent; Dummy: Integer);
begin
inherited CreateNew(AOwner, Dummy);
Font.Assign(Screen.MessageFont);
end;
procedure TMessageForm.CustomEnter(Sender: TObject);
begin
if Sender = RichEditMessage then
Perform($0028, 0, 0);
end;
procedure TMessageForm.CustomKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if (Shift = [ssCtrl]) and (Key = Word('C')) then
begin
MessageBeep(0);
CustomWriteTextToClipBoard;
end;
end;
procedure TMessageForm.CustomWriteTextToClipBoard;
var
FData : THandle;
FDataPtr: Pointer;
FText : string;
begin
if OpenClipBoard(0) then
begin
if FExeVErsion.Trim.IsEmpty then
FText := Caption + sLineBreak + Trim(RichEditMessage.Text)
else
FText := Caption + ' - ' + FExeVErsion + sLineBreak + Trim(RichEditMessage.Text);
try
FData := GlobalAlloc(GMEM_MOVEABLE + GMEM_DDESHARE, ByteLength(FText) + SizeOf(WideChar));
try
FDataPtr := GlobalLock(FData);
try
Move(PWChar(FText)^, FDataPtr^, ByteLength(FText) + SizeOf(WideChar));
EmptyClipBoard;
SetClipboardData(CF_UNICODETEXT, FData);
finally
GlobalUnlock(FData);
end;
except
GlobalFree(FData);
raise;
end;
finally
CloseClipBoard;
end;
end
else
raise Exception.Create('Não foi possível acessar a área de transferência.');
end;
procedure TMessageForm.CutomLabelClick(Sender: TObject);
begin
MessageBeep(0);
CustomWriteTextToClipBoard;
end;
procedure TMessageForm.HelpButtonClick(Sender: TObject);
begin
if HelpContext <> 0 then
Application.HelpContext(HelpContext);
end;
function GetAveCharSize(Canvas: TCanvas): TPoint;
var
I : Integer;
Buffer: array [0 .. 51] of Char;
begin
for I := 0 to 25 do
Buffer[I] := Chr(I + Ord('A'));
for I := 0 to 25 do
Buffer[I + 26] := Chr(I + Ord('a'));
GetTextExtentPoint(Canvas.Handle, Buffer, 52, TSize(Result));
Result.X := Result.X div 52;
end;
function TaskBarBounds: TRect;
begin
GetWindowRect(FindWindow('Shell_TrayWnd', nil), Result);
end;
function TaskBarPosition: TAlign;
var
TaskBar : TRect;
ScrW, ScrH: Integer;
begin
ScrW := Screen.Width;
ScrH := Screen.Height;
TaskBar := TaskBarBounds;
if (TaskBar.Top > ScrH div 2) and (TaskBar.Right >= ScrW) then
Result := alBottom
else
if (TaskBar.Top < ScrH div 2) and (TaskBar.Bottom <= ScrW div 2) then
Result := alTop
else
if (TaskBar.Left < ScrW div 2) and (TaskBar.Top <= 0) then
Result := alLeft
else
Result := alRight;
end;
function TaskBarWidth: Integer;
begin
with TaskBarBounds do
Result := Right - Left;
end;
function TaskBarHeight: Integer;
begin
with TaskBarBounds do
Result := Bottom - Top;
end;
function GetExeVersion: string;
type
pFFI = ^VS_FIXEDFILEINFO;
var
F : pFFI;
dwHandle, dwLen : DWORD;
szInfo : LongInt;
pchData, pchFile: PChar;
ptrBuff : Pointer;
strFile : string;
begin
strFile := Application.ExeName;
pchFile := StrAlloc(Length(strFile) + 1);
StrPcopy(pchFile, strFile);
szInfo := GetFileVersionInfoSize(pchFile, dwHandle);
Result := '';
if szInfo > 0 then
begin
pchData := StrAlloc(szInfo + 1);
if GetFileVersionInfo(pchFile, dwHandle, szInfo, pchData) then
begin
VerQueryValue(pchData, '\', ptrBuff, dwLen);
F := pFFI(ptrBuff);
Result := Format('v%d.%d.%d (%.3d) %s', [
HiWord(F^.dwFileVersionMs),
LoWord(F^.dwFileVersionMs),
HiWord(F^.dwFileVersionLs),
LoWord(F^.dwFileVersionLs),
{$IFDEF DEBUG}'Debug'{$ELSE}''{$ENDIF}]).Trim;
end;
StrDispose(pchData);
end;
StrDispose(pchFile);
end;
function CreateMessageDlg(const Msg: string; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; DefaultButton: TMsgDlgBtn): TForm;
const
mcHorzMargin = 8;
mcVertMargin = 8;
mcHorzSpacing = 10;
mcVertSpacing = 10;
mcButtonWidth = 50;
mcButtonHeight = 14;
mcButtonSpacing = 4;
DrawFormatLine = DT_CALCRECT or DT_LEFT or DT_SINGLELINE;
DrawFormatText = DT_EXPANDTABS or DT_CALCRECT or DT_WORDBREAK;
var
DialogUnits : TPoint;
HorzMargin : Integer;
VertMargin : Integer;
HorzSpacing : Integer;
VertSpacing : Integer;
ButtonTop : Integer;
ButtonWidth : Integer;
ButtonHeight : Integer;
ButtonSpacing : Integer;
ButtonCount : Integer;
ButtonGroupWidth: Integer;
MessageWidth : Integer;
MessageHeight : Integer;
LabelWidth : Integer;
ScreenWidth : Integer;
ScreenHeight : Integer;
X : Integer;
L : Integer;
B, CancelButton : TMsgDlgBtn;
IconID : PChar;
TextRect : TRect;
LButton : TButton;
LMsg : string;
begin
LMsg := Trim(Msg);
Result := TMessageForm.CreateNew(Application);
with Result do
begin
Font := Application.DefaultFont;
BiDiMode := Application.BiDiMode;
BorderStyle := bsDialog;
Canvas.Font := Font;
KeyPreview := True;
ShowHint := True;
PopupMode := pmAuto;
Position := poScreenCenter;
OnKeyDown := TMessageForm(Result).CustomKeyDown;
// definicao das variaveis
DialogUnits := GetAveCharSize(Canvas);
HorzMargin := MulDiv(mcHorzMargin, DialogUnits.X, 4);
VertMargin := MulDiv(mcVertMargin, DialogUnits.Y, 8);
HorzSpacing := MulDiv(mcHorzSpacing, DialogUnits.X, 4);
VertSpacing := MulDiv(mcVertSpacing, DialogUnits.Y, 8);
ButtonWidth := MulDiv(mcButtonWidth, DialogUnits.X, 4);
ButtonHeight := MulDiv(mcButtonHeight, DialogUnits.Y, 8);
ButtonSpacing := MulDiv(mcButtonSpacing, DialogUnits.X, 4);
// tamanho do grupo de botoes
for B := Low(TMsgDlgBtn) to High(TMsgDlgBtn) do
begin
if B in Buttons then
begin
if ButtonWidths[B] = 0 then
begin
TextRect := Rect(0, 0, 0, 0);
DrawText(Canvas.Handle, PChar(LoadResString(ButtonCaptions[B])), -1, TextRect,
DrawFormatLine or DrawTextBiDiModeFlagsReadingOnly);
with TextRect do
ButtonWidths[B] := Right - Left + 8;
end;
if ButtonWidths[B] > ButtonWidth then
ButtonWidth := ButtonWidths[B];
end;
end;
// tamanho do label
TextRect := Rect(0, 0, 0, 0);
DrawText(Canvas.Handle, SMsgDlgCopyToClipBrd, -1, TextRect, DrawFormatLine or DrawTextBiDiModeFlagsReadingOnly);
LabelWidth := TextRect.Right - TextRect.Left + 8;
SetRect(TextRect, 0, 0, Screen.WorkAreaWidth + 1 div 2, 0);
// tamanho da mensagem
DrawText(Canvas.Handle, LMsg, Length(LMsg) + 1, TextRect, DrawFormatText or DrawTextBiDiModeFlagsReadingOnly);
MessageWidth := TextRect.Right;
MessageHeight := TextRect.Bottom;
// ícone
IconID := IconIDs[DlgType];
if IconID <> nil then
begin
Inc(MessageWidth, 32 + HorzSpacing);
if MessageHeight < 32 then
MessageHeight := 32;
end;
ButtonCount := 0;
for B := Low(TMsgDlgBtn) to High(TMsgDlgBtn) do
if B in Buttons then
Inc(ButtonCount);
ButtonGroupWidth := 0;
if ButtonCount > 0 then
ButtonGroupWidth := (ButtonWidth * ButtonCount + ButtonSpacing * (ButtonCount - 1));
// tamanho da tela
ScreenWidth := Screen.WorkAreaWidth;
ScreenHeight := Screen.WorkAreaHeight;
case TaskBarPosition of
alTop, alBottom:
ScreenHeight := ScreenHeight - TaskBarHeight;
alLeft, alRight:
ScreenWidth := ScreenWidth - TaskBarWidth;
end;
// tamanho do formulario
ClientWidth := Max(MessageWidth + 20, ButtonGroupWidth + LabelWidth) + HorzMargin * 2;
if ClientWidth > ScreenWidth then
begin
ClientWidth := ScreenWidth;
if ClientWidth < (ButtonGroupWidth + LabelWidth) then
AutoScroll := True;
end;
ClientHeight := MessageHeight + ButtonHeight + VertSpacing + VertMargin * 2;
if ClientHeight > ScreenHeight then
ClientHeight := ScreenHeight;
// titulo
Caption := Application.Title;
{ if DlgType <> mtCustom then
Caption := Caption + ' - ' + LoadResString(Captions[DlgType]); }
FExeVErsion := GetExeVersion;
// criacao da imagem
if IconID <> nil then
with TImage.Create(Result) do
begin
Name := 'Image';
Parent := Result;
Transparent := True;
IncrementalDisplay := True;
Picture.Icon.Handle := LoadIcon(0, IconID);
SetBounds(HorzMargin, VertMargin, 32, 32);
end;
// criacao do richedit
TMessageForm(Result).RichEditMessage := TRichEdit.Create(Result);
with TMessageForm(Result).RichEditMessage do
begin
Name := 'RichMessage';
Parent := Result;
Cursor := crArrow;
WordWrap := True;
BevelInner := bvNone;
BevelOuter := bvNone;
BorderStyle := bsNone;
ParentColor := True;
PlainText := True;
ScrollBars := TScrollStyle.ssVertical;
Lines.Text := LMsg;
ReadOnly := True;
BoundsRect := TextRect;
BiDiMode := Result.BiDiMode;
TabStop := False;
OnEnter := TMessageForm(Result).CustomEnter;
L := MessageWidth - TextRect.Right + HorzMargin;
if UseRightToLeftAlignment then
L := Result.ClientWidth - L - Width;
SetBounds(L, VertMargin, Result.ClientWidth - 65, Result.ClientHeight - (ButtonHeight + VertMargin + VertSpacing));
end;
// definicao dos botoes
if mbCancel in Buttons then
CancelButton := mbCancel
else
if mbNo in Buttons then
CancelButton := mbNo
else
CancelButton := mbOK;
// posicao Top dos botoes
ButtonTop := Result.Height - (ButtonHeight + VertMargin + VertSpacing + 10);
// criacao do label
with TLabel.Create(Result) do
begin
Name := 'LabelClpBrd';
Parent := Result;
AutoSize := True;
Transparent := True;
Layout := tlCenter;
Font.Style := [fsUnderline, fsItalic];
Font.Size := 7;
Cursor := crHandPoint;
Caption := SMsgDlgCopyToClipBrd;
Hint := SHintMsgDlgCopyToClipBrd;
OnClick := TMessageForm(Result).CutomLabelClick;
SetBounds(mcHorzSpacing, ButtonTop + (ButtonHeight div 2) - mcVertMargin, LabelWidth, 15);
end;
// posicao incial do grupo de botoes
X := (ClientWidth - ButtonGroupWidth + LabelWidth) div 2;
// criacao dos botoes
for B := Low(TMsgDlgBtn) to High(TMsgDlgBtn) do
if B in Buttons then
begin
LButton := TButton.Create(Result);
with LButton do
begin
Name := ButtonNames[B];
Parent := Result;
Caption := LoadResString(ButtonCaptions[B]);
ModalResult := ModalResults[B];
if B = DefaultButton then
begin
Default := True;
ActiveControl := LButton;
end;
if B = CancelButton then
Cancel := True;
SetBounds(X, ButtonTop, ButtonWidth, ButtonHeight);
Inc(X, ButtonWidth + ButtonSpacing);
if B = mbHelp then
OnClick := TMessageForm(Result).HelpButtonClick;
end;
end;
end;
WaitCloseMessage;
end;
procedure ShowMsg(const Msg: string; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; DefaultButton: TMsgDlgBtn);
begin
with CreateMessageDlg(Msg, DlgType, Buttons, DefaultButton) do
begin
ShowModal;
Free;
end;
end;
function QueryMsg(const Msg: string; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; DefaultButton: TMsgDlgBtn): Integer;
begin
with CreateMessageDlg(Msg, DlgType, Buttons, DefaultButton) do
begin
try
ShowModal;
Result := ModalResult;
finally
Free;
end;
end;
end;
procedure MessageBoxError(const Msg: string);
begin
MessageBeep(16);
ShowMsg(Msg, mtError, [mbOK], mbOK);
end;
function MessageBoxYesNo(const Msg: string): Integer;
begin
MessageBeep(16);
Exit(QueryMsg(Msg, mtConfirmation, [mbYes, mbNo], mbNo));
end;
function MessageBoxYesNoCancel(const Msg: string): Integer;
begin
MessageBeep(16);
Exit(QueryMsg(Msg, mtConfirmation, [mbYes, mbNo, mbCancel], mbCancel));
end;
procedure MessageBoxInformation(const Msg: string);
begin
MessageBeep(64);
ShowMsg(Msg, mtInformation, [mbOK], mbOK);
end;
function MessageBox(const Msg: string; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; DefaultButton: TMsgDlgBtn): Integer;
begin
Exit(QueryMsg(Msg, DlgType, Buttons, DefaultButton));
end;
{ TWaitForm }
procedure TWaitForm.CustomAppEventsModalBegin(Sender: TObject);
begin
WaitCloseMessage;
end;
procedure TWaitForm.CustomCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
// método para implementação futura, onde poderá ser cancelada uma ação demorada
CanClose := True;
end;
procedure DisableProcessWindowsGhosting;
var
User32: HMODULE;
Proc : TProcedure;
begin
User32 := GetModuleHandle('USER32');
if User32 <> 0 then
begin
Proc := GetProcAddress(User32, 'DisableProcessWindowsGhosting');
if Assigned(Proc) then
Proc;
end;
end;
procedure EmptyKeyQueue;
var
Msg: TMsg;
begin
while PeekMessage(Msg, 0, WM_KEYFIRST, WM_KEYLAST, PM_REMOVE or PM_NOYIELD) do;
end;
procedure EmptyMouseQueue;
var
Msg: TMsg;
begin
while PeekMessage(Msg, 0, WM_MOUSEFIRST, WM_MOUSELAST, PM_REMOVE or PM_NOYIELD) do;
end;
var
WaitForm : TForm;
LastActiveForm: TForm;
WindowList : TTaskWindowList;
WindowLocked : Boolean;
const
MinHeight = 120;
MinWidth = 450;
function CreateWaitDlg(const Msg: string): TForm;
const
FWhiteColor = 16777215;
FFontTahoma = 'Tahoma';
var
FPanelLeft, FPanelTop: Integer;
begin
if not Assigned(LastActiveForm) then
if Assigned(Screen.ActiveForm) then
if not(Screen.ActiveForm.ClassNameIs(TWaitForm.ClassName)) then
begin
LastActiveForm := Screen.ActiveForm;
if LastActiveForm.FormStyle = fsMDIChild then
LastActiveForm := Application.MainForm;
if Assigned(LastActiveForm) then
WindowLocked := LockWindowUpdate(LastActiveForm.Handle);
end;
Result := TWaitForm.CreateNew(LastActiveForm);
with Result do
begin
Name := 'WaitForm';
BorderIcons := [];
BorderStyle := bsNone;
DoubleBuffered := False;
Color := clFuchsia;
Tag := -99;
PopupMode := pmAuto;
OnCloseQuery := TWaitForm(Result).CustomCloseQuery;
Position := poOwnerFormCenter;
Caption := Application.Title;
// dimensões padrao
ClientHeight := MinHeight;
ClientWidth := MinWidth;
// dimensiona de acordo ao formulario ativo
if Assigned(LastActiveForm) then
begin
ClientHeight := LastActiveForm.Height;
ClientWidth := LastActiveForm.Width;
end;
// posição do panel
FPanelLeft := 0;
FPanelTop := (ClientHeight div 2) - (MinHeight div 2);
// tratamento de transparência
TransparentColorValue := Color;
TransparentColor := True;
AlphaBlendValue := 240;
AlphaBlend := True;
end;
// panel
TWaitForm(Result).PanelContainer := TPanel.Create(Result);
with TWaitForm(Result).PanelContainer do
begin
Parent := Result;
Color := $00804000; // $0068001F;
ParentBackground := False;
if Assigned(LastActiveForm) then
BevelKind := bkNone
else
BevelKind := bkFlat;
SetBounds(FPanelLeft, FPanelTop, TWaitForm(Result).ClientWidth, MinHeight);
end;
// label version
with TLabel.Create(Result) do
begin
Parent := TWaitForm(Result).PanelContainer;
Transparent := True;
// Caption := GetExeVersion; RAFA - 16/11/2017
ParentFont := False;
Layout := tlCenter;
Font.Color := FWhiteColor;
Font.Name := FFontTahoma;
Font.Size := 7;
Left := 8;
Top := 5;
end;
// label aguarde
with TLabel.Create(Result) do
begin
Parent := TWaitForm(Result).PanelContainer;
AlignWithMargins := True;
Align := alTop;
Margins.Top := 15;
Alignment := taCenter;
Transparent := True;
Caption := 'Aguarde';
ParentFont := False;
Layout := tlCenter;
Font.Color := FWhiteColor;
Font.Name := FFontTahoma;
Font.Size := 18;
Font.Style := [fsBold];
end;
// label msg
TWaitForm(Result).LabelMessage := TLabel.Create(Result);
with TWaitForm(Result).LabelMessage do
begin
Parent := TWaitForm(Result).PanelContainer;
AlignWithMargins := True;
Align := alClient;
Alignment := taCenter;
Transparent := True;
Caption := 'Processando ...';
ParentFont := False;
Layout := tlCenter;
WordWrap := True;
Font.Color := FWhiteColor;
Font.Name := FFontTahoma;
Font.Size := 12;
Font.Style := [fsBold];
end;
// ApplicationEvents
TWaitForm(Result).AppEvents := TApplicationEvents.Create(Result);
with TWaitForm(Result).AppEvents do
OnModalBegin := TWaitForm(Result).CustomAppEventsModalBegin;
end;
procedure WaitShowMessage(const Msg: string);
begin
if not Assigned(WaitForm) then
begin
WaitForm := CreateWaitDlg(Msg);
with WaitForm do
begin
WindowList := DisableTaskWindows(0);
Screen.FocusedForm := WaitForm;
Show;
SendMessage(Handle, CM_ACTIVATE, 0, 0);
Screen.Cursor := crHourGlass;
end;
end;
with TWaitForm(WaitForm) do
begin
if Trim(Msg) = '' then
LabelMessage.Caption := 'Processando ...'
else
LabelMessage.Caption := Trim(Msg);
end;
Application.ProcessMessages;
end;
procedure WaitCloseMessage;
begin
try
if Assigned(WaitForm) then
begin
try
if WindowList <> nil then
EnableTaskWindows(WindowList);
WaitForm.Tag := -1;
WaitForm.Close;
FreeAndNil(WaitForm);
finally
EmptyKeyQueue;
EmptyMouseQueue;
LastActiveForm := nil;
WindowList := nil;
Screen.Cursor := crDefault;
end;
end;
finally
if WindowLocked then
begin
LockWindowUpdate(0);
WindowLocked := False;
end;
end;
end;
procedure WaitShowProgress(const Msg: string; ExecProc: TProc);
begin
WaitShowMessage(Msg);
try
if Assigned(ExecProc) then
ExecProc;
finally
WaitCloseMessage;
end;
end;
procedure WaitShowProgress(const Msg: string; ExecFunc: TFunc<Boolean>);
begin
WaitShowMessage(Msg);
try
if Assigned(ExecFunc) then
ExecFunc;
finally
WaitCloseMessage;
end;
end;
initialization
DisableProcessWindowsGhosting;
end.
|
unit FIToolkit.Runner.Consts;
interface
uses
FIToolkit.Localization;
const
{ Common consts }
CHR_TASK_OUTPUT_FILENAME_PARTS_DELIM = Char('_');
INT_SPIN_WAIT_ITERATIONS = 1000;
{ FixInsight output file waiting }
INT_FIOFILE_WAIT_CHECK_INTERVAL = 1000;
INT_FIOFILE_WAIT_TIMEOUT = 5 * INT_FIOFILE_WAIT_CHECK_INTERVAL;
resourcestring
{$IF LANGUAGE = LANG_EN_US}
{$INCLUDE 'Locales\en-US.inc'}
{$ELSEIF LANGUAGE = LANG_RU_RU}
{$INCLUDE 'Locales\ru-RU.inc'}
{$ELSE}
{$MESSAGE FATAL 'No language defined!'}
{$ENDIF}
implementation
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC MongoDB metadata }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.Phys.MongoDBMeta;
interface
uses
System.Classes,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Consts,
FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.Phys, FireDAC.Phys.Meta, FireDAC.Phys.SQLGenerator;
type
TFDPhysMongoMetadata = class (TFDPhysConnectionMetadata)
protected
function GetKind: TFDRDBMSKind; override;
function GetTxSupported: Boolean; override;
function GetEventSupported: Boolean; override;
function GetEventKinds: String; override;
function GetParamNameMaxLength: Integer; override;
function GetNameParts: TFDPhysNameParts; override;
function GetNameQuotedSupportedParts: TFDPhysNameParts; override;
function GetNameQuotedCaseSensParts: TFDPhysNameParts; override;
function GetNameDefLowCaseParts: TFDPhysNameParts; override;
function GetIdentitySupported: Boolean; override;
function GetIdentityInsertSupported: Boolean; override;
function GetIdentityInWhere: Boolean; override;
function GetNamedParamMark: TFDPhysParamMark; override;
function GetSelectOptions: TFDPhysSelectOptions; override;
function GetAsyncAbortSupported: Boolean; override;
function GetAsyncNativeTimeout: Boolean; override;
function GetArrayExecMode: TFDPhysArrayExecMode; override;
function GetLimitOptions: TFDPhysLimitOptions; override;
function IsNameValid(const AName: String): Boolean; override;
function GetTruncateSupported: Boolean; override;
function GetDefValuesSupported: TFDPhysDefaultValues; override;
function InternalEscapeBoolean(const AStr: String): String; override;
function InternalEscapeDate(const AStr: String): String; override;
function InternalEscapeTime(const AStr: String): String; override;
function InternalEscapeDateTime(const AStr: String): String; override;
function InternalEscapeFloat(const AStr: String): String; override;
function InternalEscapeString(const AStr: String): String; override;
// function InternalEscapeFunction(const ASeq: TFDPhysEscapeData): String; override;
// function InternalGetSQLCommandKind(const ATokens: TStrings): TFDPhysCommandKind; override;
end;
TFDPhysMongoCommandGenerator = class(TFDPhysCommandGenerator)
end;
implementation
uses
System.SysUtils, System.StrUtils,
FireDAC.Stan.Util, FireDAC.Stan.Param;
{-------------------------------------------------------------------------------}
{ TFDPhysMongoMetadata }
{-------------------------------------------------------------------------------}
function TFDPhysMongoMetadata.GetKind: TFDRDBMSKind;
begin
Result := TFDRDBMSKinds.MongoDB;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoMetadata.GetTxSupported: Boolean;
begin
Result := False;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoMetadata.GetEventSupported: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoMetadata.GetEventKinds: String;
begin
Result := S_FD_EventKind_Mongo_Tail;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoMetadata.GetParamNameMaxLength: Integer;
begin
Result := 1024;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoMetadata.GetNameParts: TFDPhysNameParts;
begin
Result := [npCatalog, npBaseObject, npObject];
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoMetadata.GetNameQuotedCaseSensParts: TFDPhysNameParts;
begin
Result := [];
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoMetadata.GetNameQuotedSupportedParts: TFDPhysNameParts;
begin
Result := [npBaseObject, npObject];
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoMetadata.GetNameDefLowCaseParts: TFDPhysNameParts;
begin
Result := GetNameParts;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoMetadata.GetIdentitySupported: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoMetadata.GetIdentityInsertSupported: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoMetadata.GetIdentityInWhere: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoMetadata.GetNamedParamMark: TFDPhysParamMark;
begin
Result := prName;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoMetadata.GetSelectOptions: TFDPhysSelectOptions;
begin
Result := [];
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoMetadata.GetAsyncAbortSupported: Boolean;
begin
Result := False;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoMetadata.GetAsyncNativeTimeout: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoMetadata.GetArrayExecMode: TFDPhysArrayExecMode;
begin
Result := aeCollectAllErrors;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoMetadata.GetLimitOptions: TFDPhysLimitOptions;
begin
Result := [loSkip, loRows];
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoMetadata.IsNameValid(const AName: String): Boolean;
var
i: Integer;
begin
Result := True;
for i := 1 to Length(AName) do
if not ((i = 1) and (AName[i] <> '$') or
(i > 1) and (AName[i] <> '.') and (AName[i] <> #0)) then begin
Result := False;
Break;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoMetadata.GetTruncateSupported: Boolean;
begin
Result := False;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoMetadata.GetDefValuesSupported: TFDPhysDefaultValues;
begin
Result := dvNone;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoMetadata.InternalEscapeBoolean(const AStr: String): String;
begin
Result := LowerCase(AStr);
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoMetadata.InternalEscapeDate(const AStr: String): String;
begin
Result := '{ "$date": "' + Trim(AStr) + '" }';
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoMetadata.InternalEscapeTime(const AStr: String): String;
begin
Result := '{ "$date": "0000-00-00T' + Trim(AStr) + '" }';
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoMetadata.InternalEscapeDateTime(const AStr: String): String;
begin
Result := '{ "$date": "' + ReplaceText(Trim(AStr), ' ', 'T') + '" }';
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoMetadata.InternalEscapeFloat(const AStr: String): String;
begin
Result := AStr;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoMetadata.InternalEscapeString(const AStr: String): String;
begin
Result := '"' + AStr + '"';
end;
{-------------------------------------------------------------------------------}
initialization
FDPhysManager().RegisterRDBMSKind(TFDRDBMSKinds.MongoDB, S_FD_Mongo_NoSQL);
end.
|
unit ucompuxui;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Graphics, Buttons, LResources;
type
{ TDefCompUXUI }
TDefCompUXUI = class
private
FDateFormat: String;
FBitBtn:TBitBtn;
FPic:TPicture;
FPng:TPortableNetworkGraphic;
protected
function getImageRes(AName:String):TBitmap;
public
constructor Create;
//procedure setDateEdit(var ADateEdit: TDateEdit);
procedure getBtnRefresh(var ABitBtn:TBitBtn);
procedure getBtnFirst(var ABitBtn:TBitBtn);
procedure getBtnLast(var ABitBtn:TBitBtn);
procedure getBtnNext(var ABitBtn:TBitBtn);
procedure getBtnPrevious(var ABitBtn:TBitBtn);
procedure getBtnDoorIn(var ABitBtn:TBitBtn);
procedure getBtnDoorOut(var ABitBtn:TBitBtn);
procedure getBtnGoogleCustomSearch(var ABitBtn:TBitBtn);
procedure getBtnExcels(var ABitBtn:TBitBtn);
end;
implementation
{ TDefCompUXUI }
function TDefCompUXUI.getImageRes(AName: String): TBitmap;
begin
try
FPng.LoadFromLazarusResource(AName);
FPic.PNG:=FPng;
finally
FPng.Clear;
end;
result:=FPic.Bitmap;
end;
constructor TDefCompUXUI.Create;
begin
inherited Create;
//FBitBtn:=TBitBtn.Create(nil);
FPic:=TPicture.Create;
FPng:=TPortableNetworkGraphic.Create;
end;
procedure TDefCompUXUI.getBtnRefresh(var ABitBtn: TBitBtn);
begin
FBitBtn:=ABitBtn;
FBitBtn.Height:=36;
FBitBtn.Caption:='';
FBitBtn.Glyph.Assign(getImageRes('Arrow-Refresh'));
FPic.Clear;
end;
procedure TDefCompUXUI.getBtnFirst(var ABitBtn: TBitBtn);
begin
FBitBtn:=ABitBtn;
FBitBtn.Height:=36;
FBitBtn.Caption:='';
FBitBtn.Glyph.Assign(getImageRes('Resultset-First'));
FPic.Clear;
end;
procedure TDefCompUXUI.getBtnLast(var ABitBtn: TBitBtn);
begin
FBitBtn:=ABitBtn;
FBitBtn.Height:=36;
FBitBtn.Caption:='';
FBitBtn.Glyph.Assign(getImageRes('Resultset-Last'));
FPic.Clear;
end;
procedure TDefCompUXUI.getBtnNext(var ABitBtn: TBitBtn);
begin
FBitBtn:=ABitBtn;
FBitBtn.Height:=36;
FBitBtn.Caption:='';
FBitBtn.Glyph.Assign(getImageRes('Resultset-Next'));
FPic.Clear;
end;
procedure TDefCompUXUI.getBtnPrevious(var ABitBtn: TBitBtn);
begin
FBitBtn:=ABitBtn;
FBitBtn.Height:=36;
FBitBtn.Caption:='';
FBitBtn.Glyph.Assign(getImageRes('Resultset-Previous'));
FPic.Clear;
end;
procedure TDefCompUXUI.getBtnDoorIn(var ABitBtn: TBitBtn);
begin
FBitBtn:=ABitBtn;
FBitBtn.Height:=36;
//FBitBtn.Height:=32;
FBitBtn.Caption:='';
FBitBtn.Glyph.Assign(getImageRes('Door-In'));
FPic.Clear;
end;
procedure TDefCompUXUI.getBtnDoorOut(var ABitBtn: TBitBtn);
begin
FBitBtn:=ABitBtn;
FBitBtn.Height:=36;
//FBitBtn.Height:=32;
FBitBtn.Caption:='';
FBitBtn.Glyph.Assign(getImageRes('Door-Out'));
FPic.Clear;
end;
procedure TDefCompUXUI.getBtnGoogleCustomSearch(var ABitBtn: TBitBtn);
begin
FBitBtn:=ABitBtn;
FBitBtn.Height:=36;
FBitBtn.Caption:='';
FBitBtn.Glyph.Assign(getImageRes('Google-Custom-Search'));
FPic.Clear;
end;
procedure TDefCompUXUI.getBtnExcels(var ABitBtn: TBitBtn);
begin
FBitBtn:=ABitBtn;
FBitBtn.Height:=36;
FBitBtn.Caption:='Export';
FBitBtn.Glyph.Assign(getImageRes('Page-White-Excel'));
FPic.Clear;
end;
initialization
{$I extico.lrs}
end.
|
unit PreProcessor;
interface
uses
Classes, Types, Windows, SysUtils,
Lexer, Token, Macro, Generics.Collections;
type
TPreProcessor = class
private
FMacros: TObjectList<TMacro>;
FWorkingDir: string;
FNameSpace: string;
FCounter: Cardinal;
function GetEmptyString(ACount: Integer): string;
function GetEmptyLines(ACount: Integer): string;
function GetTokenContent(AToken: TToken): string;
function GetRelativeTokenLineOffset(AToken: TToken): Integer;
function ProcessToken(ALexer: TLexer; AToken: TToken; var ALinePosition, ALastLine: Integer): string;
function IsMacro(AToken: TToken): Boolean;
function TryGetMacro(const AName: string; var AMacro: TMacro): Boolean;
function ProcessMacro(AMacro: TMacro; AParameters: TStringList): string;
procedure ParseParameters(ALexer: TLexer; AParameters: TStringList);
public
constructor Create();
destructor Destroy(); override;
procedure RegisterMacro(AMacro: TMacro);
procedure ProcessFile(const AName: string);
end;
implementation
uses
StrUtils;
{ TPreProcessor }
constructor TPreProcessor.Create;
begin
inherited;
FMacros := TObjectList<TMacro>.Create();
FCounter := 0;
end;
destructor TPreProcessor.Destroy;
begin
FMacros.Free;
inherited;
end;
function TPreProcessor.GetEmptyLines(ACount: Integer): string;
var
i: Integer;
begin
Result := '';
for i := 0 to ACount - 1 do
begin
Result := Result + sLineBreak;
end;
end;
function TPreProcessor.GetEmptyString(ACount: Integer): string;
begin
Result := StringOfChar(' ', ACount);
end;
function TPreProcessor.GetTokenContent(AToken: TToken): string;
begin
if AToken.IsType(ttCharLiteral) then
begin
Result := QuotedStr(AToken.Content);
end
else
begin
Result := AToken.Content;
end;
end;
function TPreProcessor.GetRelativeTokenLineOffset(AToken: TToken): Integer;
begin
if AToken.IsType(ttCharLiteral) then
begin
Result := AToken.RelativeLineOffset - 1;
end
else
begin
Result := AToken.RelativeLineOffset;
end;
end;
function TPreProcessor.IsMacro(AToken: TToken): Boolean;
var
LMacro: TMacro;
begin
Result := AToken.IsType(ttIdentifier) and TryGetMacro(AToken.Content, LMacro);
end;
procedure TPreProcessor.ParseParameters(ALexer: TLexer;
AParameters: TStringList);
var
LLevel: Integer;
LParameter: string;
begin
LLevel := 0;
if ALexer.PeekToken.IsContent('(') then
begin
ALexer.GetToken();
LParameter := '';
while not ALexer.EOF do
begin
if (LLevel = 0) and ALexer.PeekToken.IsContent(',') then
begin
AParameters.Add(LParameter);
LParameter := '';
ALexer.GetToken()
end;
if (LLevel = 0) and ALexer.PeekToken.IsContent(')') then
begin
if LParameter <> '' then
begin
AParameters.Add(LParameter);
end;
Break;
end;
LParameter := LParameter + ALexer.PeekToken.Content;
if ALexer.PeekToken.IsContent('(') then
begin
Inc(LLevel);
end
else
begin
if ALexer.PeekToken.IsContent(')') then
begin
Dec(LLevel);
end;
end;
ALexer.GetToken();
end;
end;
end;
procedure TPreProcessor.ProcessFile(const AName: string);
var
LLexer: TLexer;
LOutput: string;
LLinePosition: Integer;
LFile: TStringList;
LLastLine: Integer;
begin
FWorkingDir := ExtractFilePath(AName);
FNameSpace := ChangeFileExt(ExtractFileName(AName), '');
LLexer := TLexer.Create();
try
LOutput := '';
LLinePosition := 0;
LLastLine := 1;
LLexer.KeepComments := True;
LLexer.LoadFromFile(AName);
while not LLexer.EOF do
begin
LOutput := LOutput + ProcessToken(LLexer, LLexer.PeekToken, LLinePosition, LLastLine);
LLexer.GetToken();
end;
LFile := TStringList.Create();
try
LFile.Text := LOutput;
LFile.SaveToFile('Generated.pas');
finally
LFile.Free;
end;
finally
LLexer.Free;
end;
end;
function TPreProcessor.ProcessMacro(AMacro: TMacro;
AParameters: TStringList): string;
var
LLexer: TLexer;
LContent, LName: string;
LIndex, LLinePosition, LLastLine: Integer;
LToken: TToken;
LFile: TStringList;
begin
Result := '';
if AParameters.Count <> AMacro.Parameters.Count then
begin
raise Exception.Create('Parameter count does not match');
end;
LLexer := TLexer.Create();
try
LLinePosition := 0;
LLastLine := 1;
LLexer.LoadFromString(AMacro.Content);
while not LLexer.EOF do
begin
LContent := GetTokenContent(LLexer.PeekToken);
LIndex := AMacro.Parameters.IndexOf(LowerCase(LContent));
if LIndex > -1 then
begin
LToken := TToken.Create(AParameters[LIndex], ttIdentifier);
try
LToken.FollowedByNewLine := LLexer.PeekToken.FollowedByNewLine;
LToken.FoundInLine := LLexer.PeekToken.FoundInLine;
LToken.LineOffset := LLexer.PeekToken.LineOffset;
LToken.RelativeLineOffset := LLexer.PeekToken.RelativeLineOffset;
Result := Result + ProcessToken(LLexer, LToken, LLinePosition, LLastLine);
finally
LToken.Free;
end;
end
else
begin
Result := Result + ProcessToken(LLexer, LLexer.PeekToken, LLinePosition, LLastLine);
end;
LLexer.GetToken();
end;
finally
LLexer.Free;
end;
if AMacro.AddAsExternal then
begin
LFile := TStringList.Create();
try
LFile.Text := Result;
LName := FNameSpace + '_' + AMacro.Name + '_' + IntToHex(FCounter, 8) + '.inc';
Inc(FCounter);
LFile.SaveToFile(IncludeTrailingPathDelimiter(FWorkingDir) + LName);
Result := '{$i ''' + LName + ''' }';
finally
LFile.Free;
end;
end;
end;
function TPreProcessor.ProcessToken(ALexer: TLexer; AToken: TToken; var ALinePosition, ALastLine: Integer): string;
var
LContent, LOutput: string;
LMacro: TMacro;
LParameters: TStringList;
LRelativeOffset: Integer;
begin
LContent := GetTokenContent(AToken);
LRelativeOffset := GetRelativeTokenLineOffset(AToken);
// LPositionOffset := LOffset - ALinePosition;
LOutput := GetEmptyLines(AToken.FoundInLine - ALastLine - 1);
LOutput := LOutput + GetEmptyString(LRelativeOffset);
if (not ALexer.PreviousToken.IsContent('.')) and IsMacro(AToken) then
begin
LParameters := TStringList.Create();
try
TryGetMacro(AToken.Content, LMacro);
ALexer.GetToken();
ParseParameters(ALexer, LParameters);
LOutput := LOutput + ProcessMacro(LMacro, LParameters);
finally
LParameters.Free;
end;
end
else
begin
LOutput := LOutput + LContent;
end;
ALinePosition := ALinePosition + LRelativeOffset + Length(LContent);
ALastLine := AToken.FoundInLine;
if AToken.FollowedByNewLine then
begin
LOutput := LOutput + sLineBreak;
ALinePosition := 0;
end;
Result := LOutput;
end;
procedure TPreProcessor.RegisterMacro(AMacro: TMacro);
begin
FMacros.Add(AMacro);
end;
function TPreProcessor.TryGetMacro(const AName: string;
var AMacro: TMacro): Boolean;
var
LMacro: TMacro;
begin
Result := False;
for LMacro in FMacros do
begin
if SameText(LMacro.Name, AName) then
begin
Result := True;
AMacro := LMacro;
Break;
end;
end;
end;
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ }
{ Copyright (c) 1995,99 Inprise Corporation }
{ }
{*******************************************************}
unit DSProd;
interface
uses Classes, HTTPApp, DB;
type
TDataSetPageProducer = class(TPageProducer)
private
FDataSet: TDataSet;
protected
function GetDataSet: TDataSet; virtual;
procedure SetDataSet(ADataSet: TDataSet); virtual;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure DoTagEvent(Tag: TTag; const TagString: string; TagParams: TStrings;
var ReplaceText: string); override;
public
function Content: string; override;
published
property DataSet: TDataSet read GetDataSet write SetDataSet;
property OnHTMLTag;
end;
implementation
function TDataSetPageProducer.GetDataSet: TDataSet;
begin
Result := FDataSet;
end;
procedure TDataSetPageProducer.SetDataSet(ADataSet: TDataSet);
begin
if FDataSet <> ADataSet then
begin
if ADataSet <> nil then ADataSet.FreeNotification(Self);
FDataSet := ADataSet;
end;
end;
procedure TDataSetPageProducer.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation = opRemove) and (AComponent = FDataSet) then
FDataSet := nil;
end;
procedure TDataSetPageProducer.DoTagEvent(Tag: TTag; const TagString: string;
TagParams: TStrings; var ReplaceText: string);
var
Field: TField;
begin
if (TagParams.Count = 0) and Assigned(FDataSet) then
begin
Field := FDataSet.FindField(TagString);
if Assigned(Field) then
ReplaceText := Field.DisplayText;
end;
inherited DoTagEvent(Tag, TagString, TagParams, ReplaceText);
end;
function TDataSetPageProducer.Content: string;
begin
if (FDataSet <> nil) and not FDataSet.Active then
FDataSet.Open;
Result := inherited Content;
end;
end.
|
unit Kafka.FMX.Form.Producer;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
System.DateUtils,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, System.Actions, FMX.ActnList,
FMX.Memo.Types, FMX.Edit, FMX.StdCtrls, FMX.ScrollBox, FMX.Memo,
FMX.EditBox, FMX.SpinBox, FMX.Layouts, FMX.Controls.Presentation,
Kafka.Lib,
Kafka.Factory,
Kafka.Interfaces,
Kafka.Helper,
Kafka.Types;
type
TfrmProduce = class(TForm)
tmrUpdate: TTimer;
lblStatus: TLabel;
Layout1: TLayout;
Layout2: TLayout;
Label2: TLabel;
edtTopic: TEdit;
Layout4: TLayout;
Label3: TLabel;
edtMessage: TEdit;
Layout5: TLayout;
Label4: TLabel;
edtKey: TEdit;
Layout3: TLayout;
edtMessageCount: TSpinBox;
Button1: TButton;
Button4: TButton;
chkFlushAfterProduce: TCheckBox;
memConfig: TMemo;
ActionList1: TActionList;
Layout6: TLayout;
Label1: TLabel;
edtPartition: TSpinBox;
procedure ActionList1Execute(Action: TBasicAction; var Handled: Boolean);
procedure tmrUpdateTimer(Sender: TObject);
procedure memConfigChange(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Action1Execute(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
private
FKafkaProducer: IKafkaProducer;
FKafkaCluster: String;
FStringEncoding: TEncoding;
procedure UpdateStatus;
procedure Start;
public
constructor Create(AOwner: TComponent); override;
procedure Execute(const KafkaServers: String);
end;
var
frmProduce: TfrmProduce;
implementation
{$R *.fmx}
procedure TfrmProduce.Action1Execute(Sender: TObject);
var
Msgs: TArray<String>;
i: Integer;
begin
Start;
SetLength(Msgs, Trunc(edtMessageCount.Value));
for i := 0 to pred(Trunc(edtMessageCount.Value)) do
begin
Msgs[i] := edtMessage.Text + ' - ' + DateTimeToStr(now) + '.' + MilliSecondOf(now).ToString.PadLeft(3, '0');
end;
FKafkaProducer.Produce(
edtTopic.Text,
Msgs,
edtKey.Text,
FStringEncoding,
RD_KAFKA_PARTITION_UA,
RD_KAFKA_MSG_F_COPY,
@self);
if chkFlushAfterProduce.IsChecked then
begin
TKafkaHelper.Flush(FKafkaProducer.KafkaHandle);
end;
end;
procedure TfrmProduce.ActionList1Execute(Action: TBasicAction; var Handled: Boolean);
begin
//actFlush.Enabled := FKafkaProducer <> nil;
Handled := True;
end;
procedure TfrmProduce.Button1Click(Sender: TObject);
var
Msgs: TArray<String>;
i: Integer;
begin
Start;
SetLength(Msgs, Trunc(edtMessageCount.Value));
for i := 0 to pred(Trunc(edtMessageCount.Value)) do
begin
Msgs[i] := edtMessage.Text + ' - ' + DateTimeToStr(now) + '.' + MilliSecondOf(now).ToString.PadLeft(3, '0');
end;
FKafkaProducer.Produce(
edtTopic.Text,
Msgs,
edtKey.Text,
FStringEncoding,
Trunc(edtPartition.Value),
RD_KAFKA_MSG_F_COPY);
if chkFlushAfterProduce.IsChecked then
begin
TKafkaHelper.Flush(FKafkaProducer.KafkaHandle);
end;
end;
procedure TfrmProduce.Button4Click(Sender: TObject);
begin
Start;
TKafkaHelper.Flush(FKafkaProducer.KafkaHandle);
end;
constructor TfrmProduce.Create(AOwner: TComponent);
begin
inherited;
FStringEncoding := TEncoding.UTF8;
UpdateStatus;
end;
procedure TfrmProduce.Execute(const KafkaServers: String);
begin
FKafkaCluster := KafkaServers;
memConfig.Text := 'bootstrap.servers=' + KafkaServers;
Show;
Start;
end;
procedure TfrmProduce.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := TCloseAction.caFree;
end;
procedure TfrmProduce.memConfigChange(Sender: TObject);
begin
FKafkaProducer := nil;
end;
procedure TfrmProduce.Start;
var
Names, Values: TArray<String>;
begin
if FKafkaProducer = nil then
begin
TKafkaUtils.StringsToConfigArrays(memConfig.Lines, Names, Values);
FKafkaProducer := TKafkaFactory.NewProducer(
Names,
Values);
end;
end;
procedure TfrmProduce.tmrUpdateTimer(Sender: TObject);
begin
UpdateStatus;
end;
procedure TfrmProduce.UpdateStatus;
var
ProducedStr: String;
begin
if FKafkaProducer = nil then
begin
ProducedStr := 'Idle';
end
else
begin
ProducedStr := FKafkaProducer.ProducedCount.ToString;
end;
lblStatus.Text := 'Produced: ' + ProducedStr;
end;
end.
|
unit frm_Password;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TfrmPassword = class(TForm)
Password: TEdit;
Label1: TLabel;
btnOk: TButton;
btnClose: TButton;
procedure btnCloseClick(Sender: TObject);
procedure btnOkClick(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
private
LockPassword:String;
public
{ Public declarations }
end;
procedure GetPassword(Password:String);
implementation
uses Util, dm_GUI;
{$R *.dfm}
procedure GetPassword(Password:String);
var F: TfrmPassword;
begin
F:=nil;
Application.CreateForm(TfrmPassword,F);
F.LockPassword:=Password;
F.ShowModal;
end;
procedure TfrmPassword.btnCloseClick(Sender: TObject);
begin
if dmGUI.Confirm('Ако имате незаписани промени, те ще бъдат загубени.'#13#10'Наистина ли желаете да затворите приложението?',
mtWarning) then
Application.Terminate;
end;
procedure TfrmPassword.btnOkClick(Sender: TObject);
begin
if Password.Text=LockPassword then ModalResult:=mrOk
else raise TMessageException.Create('Грешна парола');
end;
procedure TfrmPassword.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
CanClose:=Application.Terminated or (ModalResult=mrOk);
end;
end.
|
{
Copyright (c) 2010, Loginov Dmitry Sergeevich
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
}
unit PropertyFrm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Grids, ExtCtrls, ComCtrls;
type
TPropertyForm = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
btnOk: TButton;
btnCancel: TButton;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
sgAttr: TStringGrid;
sgStyle: TStringGrid;
Label5: TLabel;
TrackBar1: TTrackBar;
procedure sgStyleDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect;
State: TGridDrawState);
procedure sgStyleEnter(Sender: TObject);
procedure sgStyleSelectCell(Sender: TObject; ACol, ARow: Integer;
var CanSelect: Boolean);
procedure TrackBar1Change(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
PropertyForm: TPropertyForm;
function ShowPropertyForm(AttrList, StyleList: TStringList; TagName: string): Boolean;
implementation
uses HTMLGlobal, AttribControls;
{$R *.dfm}
function ShowPropertyForm(AttrList, StyleList: TStringList; TagName: string): Boolean;
var
I: Integer;
S, S1: string;
AttrType: THTMLAttribType;
cntrl: TBaseAttribControl;
function GetNameByValue(AList: TStringList; AValue: string): string;
var
I: Integer;
S: string;
begin
Result := '';
for I := 0 to AList.Count - 1 do
begin
S := AList.ValueFromIndex[I];
if SameText(S, AValue) then
begin
Result := AList.Names[I];
Exit;
end;
end;
end;
begin
with TPropertyForm.Create(nil) do
try
Caption := Format('Свойства элемента "%s"', [TagName]);
sgAttr.RowCount := 2;
sgAttr.Cells[0,0] := 'Наименование атрибута';
sgAttr.Cells[1,0] := 'Значение атрибута';
PageControl1.ActivePageIndex := 0;
TabSheet2.TabVisible := Assigned(StyleList);
if Assigned(StyleList) then
begin
sgStyle.RowCount := 2;
sgStyle.Cells[0,0] := 'Наименование стиля';
sgStyle.Cells[1,0] := 'Значение стиля';
end;
for I := 0 to AttrList.Count - 1 do
begin
S := AttribTranslatesList.Values[AttrList.Names[I]];
if S = '' then
S := AttrList.Names[I];
sgAttr.Cells[0,sgAttr.RowCount-1] := S;
sgAttr.Cells[1,sgAttr.RowCount-1] := AttrList.ValueFromIndex[I];
CreateAttribControl(sgAttr, THTMLAttribType(AttrList.Objects[I]), sgAttr.RowCount-1, AttrList.ValueFromIndex[I]);
sgAttr.RowCount := sgAttr.RowCount + 1;
end;
if Assigned(StyleList) then
begin
for I := 0 to StyleList.Count - 1 do
begin
AttrType := GetStyleType(StyleList.Names[I]);
S := StyleTranslatesList.Values[StyleList.Names[I]];
if S = '' then
S := StyleList.Names[I];
sgStyle.Cells[0,sgStyle.RowCount-1] := S;
sgStyle.Cells[1,sgStyle.RowCount-1] := StyleList.ValueFromIndex[I];
CreateAttribControl(sgStyle, AttrType, sgStyle.RowCount-1, StyleList.ValueFromIndex[I]);
sgStyle.RowCount := sgStyle.RowCount + 1;
end;
end;
Result := ShowModal = mrOk;
if Result then
begin
AttrList.Clear;
for I := 1 to sgAttr.RowCount-1 do
begin
S := Trim(sgAttr.Cells[0,I]);
S := GetNameByValue(AttribTranslatesList, S);
cntrl := GetControlForCell(I, sgAttr);
if Assigned(cntrl) then
S1 := cntrl.AsText
else
S1 := sgAttr.Cells[1, I];
if S <> '' then
AttrList.Add(S + '=' + S1);
end;
if Assigned(StyleList) then
begin
StyleList.Clear;
for I := 1 to sgStyle.RowCount-1 do
begin
S := Trim(sgStyle.Cells[0,I]);
S := GetNameByValue(StyleTranslatesList, S);
cntrl := GetControlForCell(I, sgStyle);
if Assigned(cntrl) then
S1 := cntrl.AsText
else
S1 := sgStyle.Cells[1,I];
if S <> '' then
StyleList.Add(S + '=' + S1);
end;
end;
end;
inttostr(1);
finally
ClearControlList;
Free;
end;
end;
procedure TPropertyForm.FormShow(Sender: TObject);
begin
TrackBar1Change(TrackBar1);
end;
procedure TPropertyForm.sgStyleDrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
var
cntrl: TBaseAttribControl;
begin
if (ACol = 1) and (ARow > 0) then
begin
cntrl := GetControlForCell(ARow, TStringGrid(Sender));
if Assigned(cntrl) then
begin
//cntrl.ShowOnGrid(TStringGrid(Sender), ACol, ARow);
cntrl.DrawOnCell(Sender, ACol, ARow, Rect, State);
end;
//GetControlForCell
end;
end;
procedure TPropertyForm.sgStyleEnter(Sender: TObject);
begin
HideAllControls;
end;
procedure TPropertyForm.sgStyleSelectCell(Sender: TObject; ACol, ARow: Integer;
var CanSelect: Boolean);
var
cntrl: TBaseAttribControl;
begin
HideAllControls;
if (ACol = 1) and (ARow > 0) then
begin
cntrl := GetControlForCell(ARow, TStringGrid(Sender));
if Assigned(cntrl) then
begin
TStringGrid(Sender).EditorMode := False;
cntrl.ShowOnGrid(TStringGrid(Sender), ACol, ARow);
end;
//GetControlForCell
end;
//
end;
procedure TPropertyForm.TrackBar1Change(Sender: TObject);
begin
AlphaBlend := TrackBar1.Position <> 255;
AlphaBlendValue := TrackBar1.Position;
end;
end.
|
{
Copyright (C) 2013-2016 Tim Sinaeve tim.sinaeve@gmail.com
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License
for more details.
You should have received a copy of the GNU Library General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
unit SnippetSource.Modules.Data;
{$MODE Delphi}
interface
uses
Classes, SysUtils, ImgList, Controls,
sqlite3conn, sqldb, sqldblib, db, FileUtil,
ts.Core.Sharedlogger,
SnippetSource.Interfaces, sqlscript;
type
{ TdmSnippetSource }
TdmSnippetSource = class(TDataModule,
IConnection, ISnippet, IDataSet, ILookup, IGlyphs
)
{$region 'designer controls' /fold}
conMain : TSQLite3Connection;
imlGlyphs : TImageList;
imlMain : TImageList;
qryGlyphID : TLongintField;
qryGlyphImage : TBlobField;
qryGlyphImageIndex : TLongintField;
qryGlyphName : TMemoField;
qryNodeTypeID : TLongintField;
qryNodeTypeImageIndex : TLongintField;
qryNodeTypeName : TMemoField;
qrySnippet : TSQLQuery;
qrySnippetComment : TMemoField;
qrySnippetCommentRTF : TMemoField;
qrySnippetDateCreated : TDateTimeField;
qrySnippetDateModified : TDateTimeField;
qrySnippetFoldLevel : TLongintField;
qrySnippetFoldState : TStringField;
qrySnippetHighlighterID : TLongintField;
qrySnippetID : TLongintField;
qrySnippetImageIndex : TLongintField;
qrySnippetNodeName : TStringField;
qrySnippetNodePath : TWideStringField;
qrySnippetNodeTypeID : TLongintField;
qrySnippetParentID : TLongintField;
qrySnippetText : TMemoField;
qryGlyph : TSQLQuery;
qryNodeType : TSQLQuery;
scrCreateDatabase : TSQLScript;
trsSnippet : TSQLTransaction;
{$endregion}
{$region 'event handlers' /fold}
procedure conMainAfterConnect(Sender: TObject);
procedure conMainLog(Sender: TSQLConnection; EventType: TDBEventType;
const Msg: String);
procedure qrySnippetAfterEdit(DataSet: TDataSet);
procedure qrySnippetAfterInsert(DataSet: TDataSet);
procedure qrySnippetAfterPost(DataSet: TDataSet);
procedure qrySnippetAfterScroll(DataSet: TDataSet);
procedure qrySnippetBeforeScroll(DataSet: TDataSet);
procedure qrySnippetNewRecord(DataSet: TDataSet);
procedure qrySnippetTextGetText(Sender: TField; var aText: string;
DisplayText: Boolean);
procedure scrCreateDatabaseDirective(Sender: TObject; Directive,
Argument: AnsiString; var StopExecution: Boolean);
{$endregion}
private
FNeedsRefresh : Boolean;
FInserted : Boolean;
{$region 'property access methods' /fold}
function GetGlyphDataSet: TDataSet;
function GetGlyphList: TImageList;
function GetImageList: TImageList;
function GetImageIndex: Integer;
procedure SetDateCreated(AValue: TDateTime);
function GetDateCreated: TDateTime;
procedure SetDateModified(AValue: TDateTime);
function GetDateModified: TDateTime;
function GetComment: string;
function GetCommentRTF: string;
function GetFoldLevel: Integer;
function GetFoldState: string;
function GetHighlighter: string;
function GetID: Integer;
function GetNodeName: string;
function GetNodePath: string;
function GetNodeTypeID: Integer;
function GetParentID: Integer;
function GetText: string;
procedure SetComment(AValue: string);
procedure SetCommentRTF(AValue: string);
procedure SetFoldLevel(AValue: Integer);
procedure SetFoldState(AValue: string);
procedure SetHighlighter(AValue: string);
procedure SetImageIndex(AValue: Integer);
procedure SetNodeName(AValue: string);
procedure SetNodePath(AValue: string);
procedure SetNodeTypeID(AValue: Integer);
procedure SetParentID(AValue: Integer);
procedure SetText(AValue: string);
function GetFileName: string;
procedure SetFileName(AValue: string);
function GetActive: Boolean;
function GetDataSet: TDataSet;
function GetRecordCount: Integer;
procedure SetActive(AValue: Boolean);
function GetLookupDataSet: TDataSet;
{$endregion}
public
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
procedure LoadGlyphs;
function Execute(const ASQL: string): Boolean;
procedure CreateNewDatabase;
function Post: Boolean;
function Append: Boolean;
function Edit: Boolean;
procedure DisableControls;
procedure EnableControls;
procedure Lookup(
const ASearchString : string;
ASearchInText : Boolean;
ASearchInName : Boolean;
ASearchInComment : Boolean
);
property ImageList: TImageList
read GetImageList;
property GlyphList: TImageList
read GetGlyphList;
property GlyphDataSet: TDataSet
read GetGlyphDataSet;
property FileName: string
read GetFileName write SetFileName;
{ ISnippet }
property Comment: string
read GetComment write SetComment;
property CommentRTF: string
read GetCommentRTF write SetCommentRTF;
property DateCreated: TDateTime
read GetDateCreated write SetDateCreated;
property DateModified: TDateTime
read GetDateModified write SetDateModified;
property FoldLevel: Integer
read GetFoldLevel write SetFoldLevel;
property FoldState: string
read GetFoldState write SetFoldState;
property Highlighter: string
read GetHighlighter write SetHighlighter;
property ID: Integer
read GetID;
property NodeName: string
read GetNodeName write SetNodeName;
property NodePath: string
read GetNodePath write SetNodePath;
property NodeTypeID: Integer read
GetNodeTypeID write SetNodeTypeID;
property ParentID: Integer
read GetParentID write SetParentID;
property Text: string
read GetText write SetText;
property ImageIndex: Integer
read GetImageIndex write SetImageIndex;
property Active: Boolean
read GetActive write SetActive;
property RecordCount: Integer
read GetRecordCount;
property DataSet: TDataSet
read GetDataSet;
property LookupDataSet: TDataSet
read GetLookupDataSet;
end;
implementation
{$R *.lfm}
uses
Variants, Forms;
resourcestring
SQueryLookupErrorRunningQuery = 'Error running query [%s]';
SQueryLookupTooManyRecords = 'The query [%s] returned too many records';
SParameterNotAssigned = 'Parameter <%s> parameter not assigned';
function QueryLookup(AConnection: TSQLConnection; const AQuery: string;
const AParams: array of const) : Variant; overload;
var
DS : TSQLQuery;
I : Integer;
begin
if not Assigned(AConnection) then
raise Exception.CreateFmt(SParameterNotAssigned, ['AConnection']);
DS := TSQLQuery.Create(nil);
try
DS.SQLConnection := AConnection;
if Length(AParams) > 0 then
DS.SQL.Text := Format(AQuery, AParams)
else
DS.SQL.Text := AQuery;
try
DS.Active := True;
except
raise Exception.CreateFmt(SQueryLookupErrorRunningQuery, [DS.SQL.Text]);
end;
if DS.IsEmpty then
Result := Unassigned
else if DS.RecordCount = 1 then
// Cannot use this because fieldname can differ from the one given in the select
// Result := DS.FieldValues[AResultField]
begin
if DS.Fields.Count = 1 then
Result := DS.Fields[0].Value
else
begin
Result := VarArrayCreate([0, DS.Fields.Count], varVariant);
for I := 0 to DS.Fields.Count - 1 do
Result[I] := DS.Fields[I].Value
end;
end
else
raise Exception.CreateFmt(SQueryLookupTooManyRecords, [DS.SQL.Text])
finally
DS.Free;
end;
end;
function QueryLookup(AConnection: TSQLConnection; const AQuery: string)
: Variant; overload;
begin
Result := QueryLookup(AConnection, AQuery, []);
end;
{$region 'construction and destruction' /fold}
procedure TdmSnippetSource.AfterConstruction;
begin
inherited AfterConstruction;
conMain.Directory := ExtractFileDir(Application.ExeName);
conMain.DatabaseName := 'snippets.db';
conMain.Connected := True;
trsSnippet.Active := True;
DataSet.Active := True;
//Execute('PRAGMA synchronous = 1;'); // speeds up inserts
//
////ExecuteDirect('PRAGMA synchronous = 0;');
////ExecuteDirect('PRAGMA journal_mode = WAL;');
//Execute('PRAGMA journal_mode = OFF;');
//Execute('PRAGMA locking_mode = EXCLUSIVE;');
//Execute('PRAGMA temp_store = MEMORY;');
//Execute('PRAGMA count_changes = OFF;');
//Execute('PRAGMA PAGE_SIZE = 4096;');
//Execute('PRAGMA default_cache_size = 700000;');
//Execute('PRAGMA cache_size = 700000;');
//Execute('PRAGMA automatic_index = 1;');
qryNodeType.Active := True;
// LoadGlyphs;
// BuildImageList(GlyphDataSet, imlGlyphs);
end;
procedure TdmSnippetSource.BeforeDestruction;
begin
qrySnippet.ApplyUpdates;
trsSnippet.Commit;
inherited BeforeDestruction;
end;
{$endregion}
{$region 'property access mehods' /fold}
function TdmSnippetSource.GetActive: Boolean;
begin
Result := qrySnippet.Active;
end;
procedure TdmSnippetSource.SetActive(AValue: Boolean);
begin
qrySnippet.Active := AValue;
end;
function TdmSnippetSource.GetLookupDataSet: TDataSet;
begin
Result := qrySnippet;
end;
function TdmSnippetSource.GetImageIndex: Integer;
begin
Result := qrySnippetImageIndex.AsInteger;
end;
procedure TdmSnippetSource.SetDateCreated(AValue: TDateTime);
begin
qrySnippetDateCreated.AsDateTime := AValue;
end;
function TdmSnippetSource.GetDateCreated: TDateTime;
begin
Result := qrySnippetDateCreated.AsDateTime;
end;
procedure TdmSnippetSource.SetDateModified(AValue: TDateTime);
begin
qrySnippetDateModified.AsDateTime := AValue;
end;
function TdmSnippetSource.GetDateModified: TDateTime;
begin
Result := qrySnippetDateModified.AsDateTime;
end;
function TdmSnippetSource.GetComment: string;
begin
Result := qrySnippetComment.AsString;
end;
function TdmSnippetSource.GetCommentRTF: string;
begin
Result := qrySnippetCommentRTF.AsString;
end;
function TdmSnippetSource.GetFoldLevel: Integer;
begin
Result := qrySnippetFoldLevel.AsInteger;
end;
function TdmSnippetSource.GetFoldState: string;
begin
Result := qrySnippetFoldState.AsString;
end;
function TdmSnippetSource.GetHighlighter: string;
begin
Result := QueryLookup(
conMain,
'select Code from Highlighter where ID = %d',
[qrySnippetHighlighterID.AsInteger]
);
Logger.Send('Highlighter', Result);
end;
function TdmSnippetSource.GetID: Integer;
begin
Result := qrySnippetID.AsInteger;
end;
function TdmSnippetSource.GetNodeName: string;
begin
Result := qrySnippetNodeName.AsString;
end;
function TdmSnippetSource.GetNodePath: string;
begin
Result := qrySnippetNodePath.AsString;
end;
function TdmSnippetSource.GetNodeTypeID: Integer;
begin
Result := qrySnippetNodeTypeID.AsInteger;
end;
function TdmSnippetSource.GetParentID: Integer;
begin
Result := qrySnippetParentID.AsInteger;
end;
function TdmSnippetSource.GetText: string;
begin
Result := qrySnippetText.AsString;
end;
procedure TdmSnippetSource.SetComment(AValue: string);
begin
qrySnippetComment.AsString := AValue;
end;
procedure TdmSnippetSource.SetCommentRTF(AValue: string);
begin
qrySnippetCommentRTF.AsString := AValue;
end;
procedure TdmSnippetSource.SetFoldLevel(AValue: Integer);
begin
qrySnippetFoldLevel.AsInteger := AValue;
end;
procedure TdmSnippetSource.SetFoldState(AValue: string);
begin
qrySnippetFoldState.AsString := AValue;
end;
procedure TdmSnippetSource.SetHighlighter(AValue: string);
begin
Logger.Send('SetHighlighter', AValue);
qrySnippetHighlighterID.AsInteger :=
QueryLookup(
conMain,
'select ID from Highlighter where Code = ''%s''',
[AValue]
);
end;
procedure TdmSnippetSource.SetImageIndex(AValue: Integer);
begin
qrySnippetImageIndex.AsInteger := AValue;
end;
procedure TdmSnippetSource.SetNodeName(AValue: string);
begin
qrySnippetNodeName.AsString := AValue;
end;
procedure TdmSnippetSource.SetNodePath(AValue: string);
begin
qrySnippetNodePath.AsString := AValue;
end;
procedure TdmSnippetSource.SetNodeTypeID(AValue: Integer);
begin
qrySnippetNodeTypeID.AsInteger := AValue;
end;
procedure TdmSnippetSource.SetParentID(AValue: Integer);
begin
qrySnippetParentID.AsInteger := AValue;
end;
procedure TdmSnippetSource.SetText(AValue: string);
begin
qrySnippetText.AsString := AValue;
end;
function TdmSnippetSource.GetDataSet: TDataSet;
begin
Result := qrySnippet;
end;
function TdmSnippetSource.GetRecordCount: Integer;
begin
Result := qrySnippet.RecordCount;
end;
function TdmSnippetSource.GetGlyphDataSet: TDataSet;
begin
Result := qryGlyph;
end;
function TdmSnippetSource.GetGlyphList: TImageList;
begin
Result := imlGlyphs;
end;
function TdmSnippetSource.GetImageList: TImageList;
begin
Result := imlGlyphs;
end;
function TdmSnippetSource.GetFileName: string;
begin
Result := conMain.DatabaseName;
end;
procedure TdmSnippetSource.SetFileName(AValue: string);
begin
if AValue <> FileName then
begin
conMain.Connected := False;
conMain.DatabaseName := AValue;
conMain.Connected := True;
end;
end;
{$endregion}
{$region 'event handlers' /fold}
procedure TdmSnippetSource.conMainAfterConnect(Sender: TObject);
begin
qryGlyph.Active := True;
end;
procedure TdmSnippetSource.conMainLog(Sender: TSQLConnection;
EventType: TDBEventType; const Msg: String);
begin
Logger.Send(Msg);
end;
procedure TdmSnippetSource.qrySnippetAfterEdit(DataSet: TDataSet);
begin
//FNeedsRefresh := True;
end;
procedure TdmSnippetSource.qrySnippetAfterInsert(DataSet: TDataSet);
begin
FInserted := True;
end;
procedure TdmSnippetSource.qrySnippetAfterPost(DataSet: TDataSet);
var
N : Integer;
begin
qrySnippet.DisableControls;
try
N := qrySnippet.RecNo;
qrySnippet.ApplyUpdates;
trsSnippet.Commit; // will close the dataset and the transaction
qrySnippet.Active := True; // will start a new transaction
qrySnippet.Refresh;
if FNeedsRefresh then
begin
//qrySnippet.Refresh;
// qrySnippet.EnableControls;
//FNeedsRefresh := False;
end
else
begin
//if N < qrySnippet.RecordCount then
// qrySnippet.RecNo := N;
end;
//else
// qrySnippet.Resync([rmExact]);
//
//trsSnippet.Commit;
finally
qrySnippet.EnableControls;
if FInserted then
begin
qrySnippet.Last;
FInserted := False;
end
else
begin
if N < qrySnippet.RecordCount then
qrySnippet.RecNo := N;
end;
end;
end;
procedure TdmSnippetSource.qrySnippetAfterScroll(DataSet: TDataSet);
begin
if not qryNodeType.Active then
qryNodeType.Active := True;
qryNodeType.Locate(
'ID',
VarArrayOf(
[qrySnippetNodeTypeID.Value]
),
[]
);
//if not qryGlyph.Active then
// qryGlyph.Active := True;
//qryGlyph.Locate(
// 'ID',
// VarArrayOf(
// [qrySnippetGlyphID.Value]
// ),
// []
//);
end;
procedure TdmSnippetSource.qrySnippetBeforeScroll(DataSet: TDataSet);
begin
if DataSet.State in dsEditModes then
DataSet.Post;
end;
procedure TdmSnippetSource.qrySnippetNewRecord(DataSet: TDataSet);
begin
qrySnippetID.Value := 0;
FNeedsRefresh := True;
end;
procedure TdmSnippetSource.qrySnippetTextGetText(Sender: TField;
var aText: string; DisplayText: Boolean);
begin
aText := Sender.AsString;
end;
procedure TdmSnippetSource.scrCreateDatabaseDirective(Sender: TObject;
Directive, Argument: AnsiString; var StopExecution: Boolean);
begin
end;
{$endregion}
{$region 'private methods' /fold}
{$endregion}
{$region 'protected methods' /fold}
{$endregion}
{$region 'public methods' /fold}
procedure TdmSnippetSource.LoadGlyphs;
begin
// raise Exception.Create('Not implemented!');
end;
function TdmSnippetSource.Execute(const ASQL: string): Boolean;
begin
conMain.ExecuteDirect(ASQL);
end;
procedure TdmSnippetSource.CreateNewDatabase;
begin
scrCreateDatabase.ExecuteScript;
end;
function TdmSnippetSource.Post: Boolean;
begin
if DataSet.State in dsEditModes then
begin
DataSet.Post;
Result := True;
end
else
Result := False;
end;
function TdmSnippetSource.Append: Boolean;
begin
DataSet.Append;
end;
function TdmSnippetSource.Edit: Boolean;
begin
if not (DataSet.State in dsEditModes) then
begin
DataSet.Edit;
Result := True;
end
else
Result := False;
end;
procedure TdmSnippetSource.DisableControls;
begin
DataSet.DisableControls;
end;
procedure TdmSnippetSource.EnableControls;
begin
DataSet.EnableControls;
end;
procedure TdmSnippetSource.Lookup(const ASearchString: string;
ASearchInText: Boolean; ASearchInName: Boolean; ASearchInComment: Boolean);
begin
// raise Exception.Create('Not implemented!');
DataSet.Locate('Text', VarArrayOf([ASearchString]), []);
end;
{$endregion}
end.
|
unit ClassAdresy;
interface
uses DBTables, StdCtrls;
type TAdresy = class
private
Query : TQuery;
FAdresy : array of array of string;
function GetAdresy( I, J : integer ) : string;
function GetCount : integer;
function GetAdresyCount( I : integer ) : integer;
procedure NacitajAdresy;
procedure OpravDiakritiku;
public
constructor Create;
destructor Destroy; override;
property Adresy[I, J : integer] : string read GetAdresy; default;
property Count : integer read GetCount;
property AdresyCount[I : integer] : integer read GetAdresyCount;
end;
var Adresy : TAdresy;
implementation
uses Dialogs;
//==============================================================================
//==============================================================================
//
// Constructor
//
//==============================================================================
//==============================================================================
constructor TAdresy.Create;
begin
inherited;
Query := TQuery.Create(nil);
with Query do
begin
Active := False;
DatabaseName := 'PcPrompt';
SQL.Add( 'SELECT (adresy.odber1), (adresy.odber2), (adresy.odber3) , (adresy.odber4)' );
SQL.Add( 'FROM adresy' );
try
Active := True;
except
MessageDlg( 'Vyskytla sa chyba pri inicialzácii komunikácie s BDE' , mtError , [mbOk] , 0 );
exit;
end;
end;
NacitajAdresy;
OpravDiakritiku;
end;
//==============================================================================
//==============================================================================
//
// Destructor
//
//==============================================================================
//==============================================================================
destructor TAdresy.Destroy;
begin
Query.Free;
inherited;
end;
//==============================================================================
//==============================================================================
//
// Pomocné procedúry
//
//==============================================================================
//==============================================================================
function TAdresy.GetAdresy( I, J : integer ) : string;
begin
Result := FAdresy[I][J];
end;
function TAdresy.GetCount : integer;
begin
Result := Length( FAdresy );
end;
function TAdresy.GetAdresyCount( I : integer ) : integer;
begin
Result := Length( FAdresy[I] );
end;
procedure TAdresy.NacitajAdresy;
var I, J, Poc : integer;
begin
SetLength( FAdresy , Query.RecordCount );
I := 0;
Poc := 0;
Query.First;
while not Query.EoF do
begin
SetLength( FAdresy[I] , 4 );
for J := 0 to 3 do
if Query.Fields[J].AsString = '' then
begin
SetLength( FAdresy[I] , J );
if J = 0 then
begin
Dec( I );
Inc( Poc );
end;
break;
end
else
FAdresy[I][J] := Query.Fields[J].AsString;
Query.Next;
Inc( I );
end;
SetLength( FAdresy , Query.RecordCount-Poc );
end;
procedure TAdresy.OpravDiakritiku;
const MJK : array[$00..$0F,$08..$0A] of char =
(('Č','É','á'),
('ü','ž','í'),
('é','Ž','ó'),
('ď','ô','ú'),
('ä','ö','ň'),
('Ď','Ó','Ň'),
('Ť','ů','Ů'),
('č','Ú','Ô'),
('ě','ý','š'),
('Ě','Ö','ř'),
('Ĺ','Ü','ŕ'),
('Í','Š','Ŕ'),
('ľ','Ľ',' '),
('ĺ','Ý','§'),
('Ä','Ř',' '),
('Á','ť',' '));
var I, J : integer;
procedure Oprav( var s : string );
var I : integer;
begin
for I := 1 to Length(s) do
if (Ord(s[I]) div $10 in [$08..$0A]) then
s[I] := MJK[ Ord(s[I]) mod $10 , Ord(s[I]) div $10 ];
end;
begin
for I := 0 to Length( FAdresy )-1 do
for J := 0 to Length( FAdresy[I] )-1 do
Oprav( FAdresy[I][J] );
end;
//==============================================================================
//==============================================================================
//
// I N T E R F A C E
//
//==============================================================================
//==============================================================================
end.
|
unit LoadArrearsFromTaxSystems_SQL;
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, DBCtrls, DBTables, DB, Buttons, Grids,
Wwdbigrd, Wwdbgrid, ExtCtrls, Wwtable, Wwdatsrc, Menus, RPCanvas,
RPrinter, RPDefine, RPBase, RPFiler, ADODB;
type
TTaxSystemsSetType = set of (tsDelinquent, tsSchool, tsTown, tsCounty);
TLoadArrearsFlagsFromSQLTaxesForm = class(TForm)
ParcelTable: TwwTable;
Panel1: TPanel;
Panel2: TPanel;
ScrollBox1: TScrollBox;
CloseButton: TBitBtn;
TitleLabel: TLabel;
StartButton: TBitBtn;
Label1: TLabel;
ReportFiler: TReportFiler;
ReportPrinter: TReportPrinter;
PrintDialog: TPrintDialog;
Label2: TLabel;
GroupBox1: TGroupBox;
DelinquentTaxCheckBox: TCheckBox;
CurrentSchoolTaxCheckBox: TCheckBox;
CurrentTownTaxCheckBox: TCheckBox;
CurrentCountyTaxCheckBox: TCheckBox;
gb_Options: TGroupBox;
ClearOldArrearsFlagsCheckBox: TCheckBox;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure ReportHeaderPrint(Sender: TObject);
procedure ReportPrint(Sender: TObject);
procedure StartButtonClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
UnitName, AlternateDelinquentSystem : String;
ClearArrearsFlags, ReportCancelled : Boolean;
TaxSystemsToCheck : TTaxSystemsSetType;
Procedure InitializeForm; {Open the tables and setup.}
end;
implementation
uses GlblVars, WinUtils, Utilitys, GlblCnst, PASUtils, Prog, Preview,
Types, PASTypes, DataAccessUnit;
{$R *.DFM}
{========================================================}
Procedure TLoadArrearsFlagsFromSQLTaxesForm.FormActivate(Sender: TObject);
begin
SetFormStateMaximized(Self);
end;
{========================================================}
Procedure TLoadArrearsFlagsFromSQLTaxesForm.InitializeForm;
begin
UnitName := 'LoadArrearsFromTaxSystem'; {mmm}
OpenTablesForForm(Self, ThisYear);
end; {InitializeForm}
{===================================================================}
Procedure TLoadArrearsFlagsFromSQLTaxesForm.FormKeyPress( Sender: TObject;
var Key: Char);
begin
If (Key = #13)
then
begin
Key := #0;
Perform(WM_NEXTDLGCTL, 0, 0);
end;
end; {FormKeyPress}
{================================================================}
Procedure TLoadArrearsFlagsFromSQLTaxesForm.StartButtonClick(Sender: TObject);
var
Quit : Boolean;
NewFileName : String;
TempFile : File;
begin
Quit := False;
ReportCancelled := False;
{FXX09301998-1: Disable print button after clicking to avoid clicking twice.}
StartButton.Enabled := False;
Application.ProcessMessages;
Quit := False;
ClearArrearsFlags := ClearOldArrearsFlagsCheckBox.Checked;
TaxSystemsToCheck := [];
If CurrentSchoolTaxCheckBox.Checked
then TaxSystemsToCheck := TaxSystemsToCheck + [tsSchool];
If CurrentTownTaxCheckBox.Checked
then TaxSystemsToCheck := TaxSystemsToCheck + [tsTown];
If CurrentCountyTaxCheckBox.Checked
then TaxSystemsToCheck := TaxSystemsToCheck + [tsCounty];
If DelinquentTaxCheckBox.Checked
then TaxSystemsToCheck := TaxSystemsToCheck + [tsDelinquent];
{CHG10121998-1: Add user options for default destination and show vet max msg.}
SetPrintToScreenDefault(PrintDialog);
If PrintDialog.Execute
then
begin
{CHG10131998-1: Set the printer settings based on what printer they selected
only - they no longer need to worry about paper or landscape
mode.}
AssignPrinterSettings(PrintDialog, ReportPrinter, ReportFiler,
[ptLaser], False, Quit);
ProgressDialog.Start(GetRecordCount(ParcelTable), True, True);
{Now print the report.}
If not (Quit or ReportCancelled)
then
begin
If PrintDialog.PrintToFile
then
begin
NewFileName := GetPrintFileName(Self.Caption, True);
ReportFiler.FileName := NewFileName;
try
PreviewForm := TPreviewForm.Create(self);
PreviewForm.FilePrinter.FileName := NewFileName;
PreviewForm.FilePreview.FileName := NewFileName;
ReportFiler.Execute;
{FXX10111999-3: Make sure they know its done.}
ProgressDialog.StartPrinting(PrintDialog.PrintToFile);
PreviewForm.ShowModal;
finally
PreviewForm.Free;
{Now delete the file.}
try
AssignFile(TempFile, NewFileName);
OldDeleteFile(NewFileName);
finally
{We don't care if it does not get deleted, so we won't put up an
error message.}
ChDir(GlblProgramDir);
end;
end; {try PreviewForm := ...}
end {If PrintDialog.PrintToFile}
else ReportPrinter.Execute;
ResetPrinter(ReportPrinter);
end; {If not Quit}
ProgressDialog.Finish;
DisplayPrintingFinishedMessage(PrintDialog.PrintToFile);
end; {If PrintDialog.Execute}
StartButton.Enabled := True;
end; {StartButtonClick}
{=========================================================}
Function ParcelHasOpenDelinquentTaxes(qryLien : TADOQuery;
sSwisSBLKey : String) : Boolean;
begin
Result := False;
_ADOQuery(qryLien,
['select distinct p.SwisSBLKey as SwisSBL from parceltable p',
'inner join stddlqhdrtable sdh on',
'(sdh.SwisSBLKey = p.SwisSBLKey)',
'where (sdh.FullyPaidFlg = 0) and (p.SwisSBLKey = ' + FormatSQLString(sSwisSBLKey) + ')']);
try
If _Compare(qryLien.RecordCount, 0, coGreaterThan)
then Result := True;
except
end;
end; {ParcelHasOpenDelinquentTaxes}
{=========================================================}
Function GetMostCurrentCollectionID(qryTax : TADOQuery;
sCollectionType : String) : Integer;
begin
Result := -1;
_ADOQuery(qryTax,
['select top 1 Collection_ID from CollectionsAvailableTable',
'where (CollectionType = ' + FormatSQLString(sCollectionType) + ')',
'order by TaxYear desc']);
try
If _Compare(qryTax.RecordCount, 0, coGreaterThan)
then Result := qryTax.FieldByName('Collection_ID').AsInteger;
except
end;
end; {GetMostCurrentCollectionID}
{=========================================================}
Function ParcelHasOpenCurrentTaxes(qryTax : TADOQuery;
sSwisSBLKey : String;
sSchoolCode : String;
iCollectionID : Integer) : Boolean;
var
dNetDue : Double;
sSwisCode, sSBL : String;
begin
sSwisCode := Copy(sSwisSBLKey, 1, 6);
sSBL := Copy(sSwisSBLKey, 7, 20);
_ADOQuery(qryTax,
['select ROUND((SUM(d.Amount) - ISNULL(SUM(py.Amount), 0)), 2) as NetDue from ParcelYearMasterFile p',
'inner join DueFile d on',
'(d.SwisCode = p.SwisCode) and (d.SchoolCodeKey = p.SchoolKeyCode) and (d.SBL = p.SBL) and (d.Collection_ID = p.Collection_ID)',
'left outer join PayFile py on',
'(py.SwisCode = p.SwisCode) and (py.SchoolCodeKey = p.SchoolKeyCode) and (py.SBL = p.SBL) and (py.Collection_ID = p.Collection_ID)',
'where (p.Collection_ID = ' + IntToStr(iCollectionID) + ') and (p.SwisCode = ' + FormatSQLString(sSwisCode) + ') and ',
'(p.SchoolKeyCode = ' + FormatSQLString(sSchoolCode) + ') and (p.SBL = ' + FormatSQLString(sSBL) + ')']);
dNetDue := qryTax.FieldByName('NetDue').AsFloat;
Result := _Compare(dNetDue, 0, coGreaterThan);
end; {ParcelHasOpenCurrentTaxes}
{=========================================================}
Procedure LoadDelinquentTaxList(qryLien : TADOQuery;
slSBLs : TStringList);
begin
_ADOQueryExec(qryLien,
['drop Table [dbo].[#SBLs]']);
_ADOQueryExec(qryLien,
['Create Table #SBLs (',
'SwisSBLKey varchar(50),',
'NetDue [float] )']);
_ADOQueryExec(qryLien,
['insert into #SBLs (SwisSBLKey, NetDue)',
'select distinct p.SwisSBLKey as SwisSBL,',
'(ROUND(((select SUM(AmountDue) from stddlqduetable',
'where (stddlqduetable.SwisSBLKey = p.SwisSBLKey) and (VoidedItem = 0)) -',
'(select IsNull(SUM(AmountPaid), 0) from stddlqpaytable',
'where (stddlqpaytable.SwisSBLKey = p.SwisSBLKey))), 2))',
'from parceltable p']);
_ADOQuery(qryLien,
['select * from #SBLs',
'where (NetDue > 0)',
'order by SwisSBLKey']);
with qryLien do
begin
First;
while not EOF do
begin
slSBLs.Add(Trim(FieldByName('SwisSBLKey').AsString));
Next;
end;
end;
end; {LoadDelinquentTaxList}
{=========================================================}
Procedure LoadOpenTaxList(qryTax : TADOQuery;
iCollectionID : Integer;
slSBLs : TStringList);
begin
_ADOQueryExec(qryTax,
['drop Table [dbo].[#SBLs]']);
_ADOQueryExec(qryTax,
['Create Table #SBLs (',
'SwisSBLKey varchar(50),',
'[TotalDue] [float],',
'[DueAmount] [float],',
'[PayAmount] [float])']);
_ADOQueryExec(qryTax,
['insert into #SBLs (SwisSBLKey, DueAmount, PayAmount, TotalDue)',
'select p.SwisCode + p.SBL,',
'(select SUM(Amount) from duefile',
'where (dueFile.SwisCode = p.SwisCode) and (dueFile.SchoolCodeKey = p.SchoolKeyCode) and (dueFile.SBL = p.SBL) and (dueFile.Collection_ID = p.Collection_ID) and (Voided = 0)),',
'(select IsNull(SUM(Amount), 0) from Payfile',
'where (PayFile.SwisCode = p.SwisCode) and (PayFile.SchoolCodeKey = p.SchoolKeyCode) and (PayFile.SBL = p.SBL) and (PayFile.Collection_ID = p.Collection_ID)),',
'(ROUND(((select SUM(Amount) from duefile',
'where (dueFile.SwisCode = p.SwisCode) and (dueFile.SchoolCodeKey = p.SchoolKeyCode) and (dueFile.SBL = p.SBL) and (dueFile.Collection_ID = p.Collection_ID) and (Voided = 0)) -',
'(select IsNull(SUM(Amount), 0) from Payfile',
'where (PayFile.SwisCode = p.SwisCode) and (PayFile.SchoolCodeKey = p.SchoolKeyCode) and (PayFile.SBL = p.SBL) and (PayFile.Collection_ID = p.Collection_ID))), 2))',
'from parcelyearmasterfile p',
'where (p.Collection_ID =' + IntToStr(iCollectionID) + ')']);
_ADOQuery(qryTax,
['select * from #SBLs',
'where (TotalDue > 0)',
'order by SwisSBLKey']);
with qryTax do
begin
First;
while not EOF do
begin
slSBLs.Add(Trim(FieldByName('SwisSBLKey').AsString));
Next;
end;
end;
end; {LoadOpenTaxList}
{=========================================================}
Procedure TLoadArrearsFlagsFromSQLTaxesForm.ReportHeaderPrint(Sender: TObject);
begin
with Sender as TBaseReport do
begin
{Print the date and page number.}
SectionTop := 0.25;
SectionLeft := 0.5;
SectionRight := PageWidth - 0.5;
SetFont('Times New Roman',8);
PrintHeader('Page: ' + IntToStr(CurrentPage), pjRight);
PrintHeader('Date: ' + DateToStr(Date) + ' Time: ' + TimeToStr(Now), pjLeft);
SectionTop := 0.5;
SetFont('Arial',12);
Bold := True;
Home;
PrintCenter('Arrears Flags Cleared \ Set', (PageWidth / 2));
SetFont('Times New Roman', 9);
CRLF;
Println('');
ClearTabs;
SetTab(0.3, pjCenter, 1.8, 0, BOXLINEBottom, 0); {Parcel ID}
SetTab(2.2, pjCenter, 1.0, 0, BOXLINEBottom, 0); {Action}
Println(#9 + 'Parcel ID' +
#9 + 'Action');
ClearTabs;
SetTab(0.3, pjLeft, 1.8, 0, BOXLINENone, 0); {Parcel ID}
SetTab(2.2, pjLeft, 1.0, 0, BOXLINENone, 0); {Action}
end; {with Sender as TBaseReport do}
end; {ReportHeaderPrint}
{====================================================================}
Procedure TLoadArrearsFlagsFromSQLTaxesForm.ReportPrint(Sender: TObject);
var
Done, FirstTimeThrough, Quit,
ParcelHasLien, ParcelHasSchool,
ParcelHasTown, ParcelHasCounty : Boolean;
SwisSBLKey : String;
TaxSystems, SchoolCode : String;
NumCleared, NumAdded,
iSchoolCollectionID, iMunicipalCollectionID, iCountyCollectionID : Integer;
TempLen : Integer;
TotalLien, TotalSchool, TotalTown, TotalCounty : LongInt;
qryTax, qryLien : TADOQuery;
adoConnection, adoConnection_Lien : TADOConnection;
slSchoolSBLs, slMunicipalSBLs, slCountySBLs, slLienSBLs : TStringList;
begin
Quit := False;
NumCleared := 0;
NumAdded := 0;
Done := False;
FirstTimeThrough := True;
TotalLien := 0;
TotalSchool := 0;
TotalTown := 0;
TotalCounty := 0;
slSchoolSBLs := TStringList.Create;
slMunicipalSBLs := TStringList.Create;
slCountySBLs := TStringList.Create;
slLienSBLs := TStringList.Create;
try
adoConnection := TADOConnection.Create(nil);
adoConnection.ConnectionString := 'FILE NAME=' + GlblProgramDir + 'LocalTax.udl';
adoConnection.LoginPrompt := False;
adoConnection.Connected := True;
qryTax := TADOQuery.Create(nil);
qryTax.Connection := adoConnection;
except
MessageDlg('Error connecting to SQL tax database. UDL should be ' + GlblProgramDir + 'LocalTax.udl',
mtError, [mbOK], 0);
end;
If (tsDelinquent in TaxSystemsToCheck)
then
try
adoConnection_Lien := TADOConnection.Create(nil);
adoConnection_Lien.ConnectionString := 'FILE NAME=' + GlblProgramDir + 'Lien.udl';
adoConnection_Lien.LoginPrompt := False;
adoConnection_Lien.Connected := True;
qryLien := TADOQuery.Create(nil);
qryLien.Connection := adoConnection_Lien;
except
MessageDlg('Error connecting to SQL lien database. UDL should be ' + GlblProgramDir + 'Lien.udl.',
mtError, [mbOK], 0);
end;
iSchoolCollectionID := GetMostCurrentCollectionID(qryTax, 'SC');
iMunicipalCollectionID := GetMostCurrentCollectionID(qryTax, 'TO');
If _Compare(iMunicipalCollectionID, -1, coEqual)
then iMunicipalCollectionID := GetMostCurrentCollectionID(qryTax, 'VI');
iCountyCollectionID := GetMostCurrentCollectionID(qryTax, 'CO');
If (tsSchool in TaxSystemsToCheck)
then LoadOpenTaxList(qryTax, iSchoolCollectionID, slSchoolSBLs);
If (tsTown in TaxSystemsToCheck)
then LoadOpenTaxList(qryTax, iMunicipalCollectionID, slMunicipalSBLs);
If (tsCounty in TaxSystemsToCheck)
then LoadOpenTaxList(qryTax, iCountyCollectionID, slCountySBLs);
If (tsDelinquent in TaxSystemsToCheck)
then LoadDelinquentTaxList(qryLien, slLienSBLs);
ParcelTable.First;
with ParcelTable, Sender as TBaseReport do
begin
repeat
If FirstTimeThrough
then FirstTimeThrough := False
else Next;
If EOF
then Done := True;
SwisSBLKey := ExtractSSKey(ParcelTable);
ProgressDialog.Update(Self, ConvertSwisSBLToDashDot(SwisSBLKey));
ProgressDialog.UserLabelCaption := 'Number Arrears Flags Added = ' + IntToStr(NumAdded);
Application.ProcessMessages;
If ((not Done) and
ClearArrearsFlags and
FieldByName('Arrears').AsBoolean)
then
with ParcelTable do
try
Edit;
FieldByName('Arrears').AsBoolean := False;
Post;
Println(#9 + ConvertSwisSBLToDashDot(SwisSBLKey) +
#9 + 'Cleared');
NumCleared := NumCleared + 1;
except
SystemSupport(001, ParcelTable, 'Error clearing arrears flag for ' + ConvertSwisSBLToDashDot(SwisSBLKey) + '.',
UnitName, GlblErrorDlgBox);
end;
{Now check for delinquent status.}
SchoolCode := FieldByName('SchoolCode').Text;
ParcelHasLien := False;
ParcelHasSchool := False;
ParcelHasTown := False;
ParcelHasCounty := False;
(* If ((tsDelinquent in TaxSystemsToCheck) and
ParcelHasOpenDelinquentTaxes(qryLien, SwisSBLKey))
then
begin
ParcelHasLien := True;
TotalLien := TotalLien + 1;
end;
If ((tsSchool in TaxSystemsToCheck) and
ParcelHasOpenCurrentTaxes(qryTax, SwisSBLKey, SchoolCode, iSchoolCollectionID))
then
begin
ParcelHasSchool := True;
TotalSchool := TotalSchool + 1;
end;
If ((tsTown in TaxSystemsToCheck) and
ParcelHasOpenCurrentTaxes(qryTax, SwisSBLKey, '999999', iMunicipalCollectionID))
then
begin
ParcelHasTown := True;
TotalTown := TotalTown + 1;
end;
If ((tsCounty in TaxSystemsToCheck) and
ParcelHasOpenCurrentTaxes(qryTax, SwisSBLKey, '999999', iCountyCollectionID))
then
begin
ParcelHasCounty := True;
TotalCounty := TotalCounty + 1;
end; *)
If ((tsDelinquent in TaxSystemsToCheck) and
_Compare(slLienSBLs.IndexOf(SwisSBLKey), -1, coGreaterThan))
then
begin
ParcelHasLien := True;
TotalLien := TotalLien + 1;
end;
If ((tsSchool in TaxSystemsToCheck) and
_Compare(slSchoolSBLs.IndexOf(SwisSBLKey), -1, coGreaterThan))
then
begin
ParcelHasSchool := True;
TotalSchool := TotalSchool + 1;
end;
If ((tsTown in TaxSystemsToCheck) and
_Compare(slMunicipalSBLs.IndexOf(SwisSBLKey), -1, coGreaterThan))
then
begin
ParcelHasTown := True;
TotalTown := TotalTown + 1;
end;
If ((tsCounty in TaxSystemsToCheck) and
_Compare(slCountySBLs.IndexOf(SwisSBLKey), -1, coGreaterThan))
then
begin
ParcelHasCounty := True;
TotalCounty := TotalCounty + 1;
end;
If ((not Done) and
(ParcelHasLien or
ParcelHasSchool or
ParcelHasTown or
ParcelHasCounty))
then
with ParcelTable do
try
Edit;
FieldByName('Arrears').AsBoolean := True;
Post;
Println(#9 + ConvertSwisSBLToDashDot(SwisSBLKey) +
#9 + 'Added');
NumAdded := NumAdded + 1;
except
SystemSupport(002, ParcelTable, 'Error adding arrears flag for ' + ConvertSwisSBLToDashDot(SwisSBLKey) + '.',
UnitName, GlblErrorDlgBox);
end;
ReportCancelled := ProgressDialog.Cancelled;
If (LinesLeft < 5)
then NewPage;
until (Done or ReportCancelled);
If (LinesLeft < 7)
then NewPage;
Println('');
Println('');
Println(#9 + 'Number cleared = ' + IntToStr(NumCleared));
Println(#9 + 'Number added = ' + IntToStr(NumAdded) +
' (distinct parcels that were marked with arrears flag)');
If (tsDelinquent in TaxSystemsToCheck)
then Println(#9 + ' Parcels with delinquent liens = ' + IntToStr(TotalLien));
If (tsSchool in TaxSystemsToCheck)
then Println(#9 + ' Parcels with delinquent school taxes = ' +
IntToStr(TotalSchool));
If (tsTown in TaxSystemsToCheck)
then Println(#9 + ' Parcels with delinquent town taxes = ' +
IntToStr(TotalTown));
If (tsCounty in TaxSystemsToCheck)
then Println(#9 + ' Parcels with delinquent county taxes = ' +
IntToStr(TotalCounty));
end; {with Sender as TBaseReport do}
slSchoolSBLs.Free;
slMunicipalSBLs.Free;
slCountySBLs.Free;
slLienSBLs.Free;
end; {ReportPrint}
{===================================================================}
Procedure TLoadArrearsFlagsFromSQLTaxesForm.FormClose( Sender: TObject;
var Action: TCloseAction);
begin
CloseTablesForForm(Self);
{Free up the child window and set the ClosingAForm Boolean to
true so that we know to delete the tab.}
Action := caFree;
GlblClosingAForm := True;
GlblClosingFormCaption := Caption;
end; {FormClose}
end. |
//
// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
{$POINTERMATH ON}
unit RN_NavMeshTileTool;
interface
uses
Classes, Controls, Math, OpenGL, StrUtils, SysUtils, Unit_FrameTileTool,
RN_InputGeom, RN_Sample, RN_SampleTileMesh, RN_DetourNavMesh, RN_Recast, RN_ChunkyTriMesh;
type
TNavMeshTileTool = class(TSampleTool)
private
fFrame: TFrameTileTool;
fUpdateUI: Boolean;
public
m_sample: TSample_TileMesh;
m_hitPos: array [0..2] of Single;
m_hitPosSet: Boolean;
public
constructor Create(aOwner: TWinControl);
destructor Destroy; override;
procedure init(sample: TSample); override;
procedure reset(); override;
procedure handleMenu(Sender: TObject); override;
procedure handleClick(s,p: PSingle; shift: Boolean); override;
procedure handleToggle(); override;
procedure handleStep(); override;
procedure handleUpdate(dt: Single); override;
procedure handleRender(); override;
procedure handleRenderOverlay(proj, model: PDouble; view: PInteger); override;
end;
implementation
uses
RN_RecastDebugDraw, RN_RecastHelper, RN_DetourNavMeshBuilder, RN_DetourDebugDraw, RN_NavMeshTesterTool, RN_NavMeshPruneTool,
{RN_OffMeshConnectionTool, RN_ConvexVolumeTool,} RN_CrowdTool;
constructor TNavMeshTileTool.Create(aOwner: TWinControl);
begin
inherited Create;
&type := TOOL_TILE_EDIT;
fFrame := TFrameTileTool.Create(aOwner);
fFrame.Align := alClient;
fFrame.Parent := aOwner;
fFrame.Visible := True;
fFrame.btnCreateAll.OnClick := handleMenu;
fFrame.btnRemoveAll.OnClick := handleMenu;
end;
destructor TNavMeshTileTool.Destroy;
begin
fFrame.Free;
inherited;
end;
procedure TNavMeshTileTool.init(sample: TSample);
begin
m_sample := TSample_TileMesh(sample);
end;
procedure TNavMeshTileTool.reset();
begin
end;
procedure TNavMeshTileTool.handleMenu(Sender: TObject);
begin
if fUpdateUI then Exit;
if Sender = fFrame.btnCreateAll then
begin
if (m_sample <> nil) then
m_sample.buildAllTiles();
end;
if Sender = fFrame.btnRemoveAll then
begin
if (m_sample <> nil) then
m_sample.removeAllTiles();
end;
end;
procedure TNavMeshTileTool.handleClick(s,p: PSingle; shift: Boolean);
begin
m_hitPosSet := true;
rcVcopy(@m_hitPos[0], p);
if (m_sample <> nil) then
begin
if (shift) then
m_sample.removeTile(@m_hitPos[0])
else
m_sample.buildTile(@m_hitPos[0]);
end;
end;
procedure TNavMeshTileTool.handleToggle();
begin
end;
procedure TNavMeshTileTool.handleStep();
begin
end;
procedure TNavMeshTileTool.handleUpdate(dt: Single);
begin
end;
procedure TNavMeshTileTool.handleRender();
var s: Single;
begin
if (m_hitPosSet) then
begin
s := m_sample.getAgentRadius;
glColor4ub(0,0,0,128);
glLineWidth(2.0);
glBegin(GL_LINES);
glVertex3f(m_hitPos[0]-s,m_hitPos[1]+0.1,m_hitPos[2]);
glVertex3f(m_hitPos[0]+s,m_hitPos[1]+0.1,m_hitPos[2]);
glVertex3f(m_hitPos[0],m_hitPos[1]-s+0.1,m_hitPos[2]);
glVertex3f(m_hitPos[0],m_hitPos[1]+s+0.1,m_hitPos[2]);
glVertex3f(m_hitPos[0],m_hitPos[1]+0.1,m_hitPos[2]-s);
glVertex3f(m_hitPos[0],m_hitPos[1]+0.1,m_hitPos[2]+s);
glEnd();
glLineWidth(1.0);
end;
end;
procedure TNavMeshTileTool.handleRenderOverlay(proj, model: PDouble; view: PInteger);
//var x, y, z: GLdouble;
begin
{if (m_hitPosSet and gluProject((GLdouble)m_hitPos[0], (GLdouble)m_hitPos[1], (GLdouble)m_hitPos[2],
model, proj, view, &x, &y, &z))
begin
int tx=0, ty=0;
m_sample->getTilePos(m_hitPos, tx, ty);
char text[32];
snprintf(text,32,"(%d,%d)", tx,ty);
imguiDrawText((int)x, (int)y-25, IMGUI_ALIGN_CENTER, text, imguiRGBA(0,0,0,220));
end;
// Tool help
const int h = view[3]: array [0..2] of Integer;
imguiDrawText(280, h-40, IMGUI_ALIGN_LEFT, "LMB: Rebuild hit tile. Shift+LMB: Clear hit tile.", imguiRGBA(255,255,255,192));
end;}
end;
end.
|
{----------------------------------------------------------------------------}
{ Written by Nguyen Le Quang Duy }
{ Nguyen Quang Dieu High School, An Giang }
{----------------------------------------------------------------------------}
Program MYSTERY;
Const
base =20122007;
Var
a :LongInt;
res :Int64;
function Power(i :Int64) :Int64;
var
tmp :Int64;
begin
if (i=1) then Exit(3);
tmp:=Power(i div 2);
tmp:=tmp*tmp mod base;
if (i mod 2=1) then tmp:=3*tmp mod base;
Exit(tmp);
end;
procedure Solve;
var
i :LongInt;
begin
res:=1;
for i:=1 to Trunc(Sqrt(a)) do
if (a mod i=0) then
begin
res:=res*(Power(i)-1) mod base;
if (i*i<>a) then
res:=res*(Power(a div i)-1) mod base;
end;
end;
Begin
Assign(Input,''); Reset(Input);
Assign(Output,''); Rewrite(Output);
Read(a);
Solve;
Write(res);
Close(Input); Close(Output);
End. |
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, IdBaseComponent, IdCoder, IdCoder3to4, IdCoderMIME,
ExtCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
IdDecoderMIME1: TIdDecoderMIME;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
const
Codes64 = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/';
function Encode64(S: string): string;
var
i: Integer;
a: Integer;
x: Integer;
b: Integer;
begin
Result := '';
a := 0;
b := 0;
for i := 1 to Length(s) do
begin
x := Ord(s[i]);
b := b * 256 + x;
a := a + 8;
while a >= 6 do
begin
a := a - 6;
x := b div (1 shl a);
b := b mod (1 shl a);
Result := Result + Codes64[x + 1];
end;
end;
if a > 0 then
begin
x := b shl (6 - a);
Result := Result + Codes64[x + 1];
end;
end;
function Decode64(S: string): string;
var
i: Integer;
a: Integer;
x: Integer;
b: Integer;
begin
Result := '';
a := 0;
b := 0;
for i := 1 to Length(s) do
begin
x := Pos(s[i], codes64) - 1;
if x >= 0 then
begin
b := b * 64 + x;
a := a + 6;
if a >= 8 then
begin
a := a - 8;
x := b shr a;
b := b mod (1 shl a);
x := x mod 256;
Result := Result + chr(x);
end;
end
else
Exit;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var arquivo:TStringList; decodificado:string;
StrStream: TStringStream;
begin
arquivo:=TStringList.Create;
arquivo.LoadFromFile('arquivo.txt');
StrStream := TStringStream.Create(IdDecoderMIME1.DecodeString(arquivo.Text));
try
StrStream.SaveToFile('imagem.png');
finally
StrStream.Free;
end;
arquivo.Free;
end;
end.
|
unit MediaProcessing.Convertor.HHH264.H264;
interface
uses SysUtils,Windows,Classes, MediaProcessing.Definitions,MediaProcessing.Global;
type
TChangeFPSMode = (cfmNone,cfmAbsolute, cfmVIFrameOnly);
TMediaProcessor_Convertor_Hh_H264_H624=class (TMediaProcessor,IMediaProcessor_Convertor_HhH264_H264)
protected
FChangeFPSMode : TChangeFPSMode;
FFPSValue: integer;
FVIFramesOnly: boolean;
protected
procedure SaveCustomProperties(const aWriter: IPropertiesWriter); override;
procedure LoadCustomProperties(const aReader: IPropertiesReader); override;
class function MetaInfo:TMediaProcessorInfo; override;
public
constructor Create; override;
destructor Destroy; override;
function HasCustomProperties: boolean; override;
procedure ShowCustomProperiesDialog;override;
end;
implementation
uses Controls,uBaseClasses,MediaProcessing.Convertor.HhH264.H264.SettingsDialog;
{ TMediaProcessor_Convertor_Hh_H264_H624 }
constructor TMediaProcessor_Convertor_Hh_H264_H624.Create;
begin
inherited;
end;
destructor TMediaProcessor_Convertor_Hh_H264_H624.Destroy;
begin
inherited;
end;
function TMediaProcessor_Convertor_Hh_H264_H624.HasCustomProperties: boolean;
begin
result:=true;
end;
class function TMediaProcessor_Convertor_Hh_H264_H624.MetaInfo: TMediaProcessorInfo;
begin
result.Clear;
result.TypeID:=IMediaProcessor_Convertor_HhH264_H264;
result.Name:='Конвертор HH/H.264->H.264';
result.Description:='Преобразует видеокадры формата HH/H.264 (камеры Beward) в формат H.264';
result.SetInputStreamType(stHHVI);
result.InputStreamSubType:='H.264';
result.OutputStreamType:=stH264;
result.ConsumingLevel:=0;
end;
procedure TMediaProcessor_Convertor_Hh_H264_H624.LoadCustomProperties(const aReader: IPropertiesReader);
begin
inherited;
FChangeFPSMode:=TChangeFPSMode(aReader.ReadInteger('ChangeFPSMode',0));
FFPSValue:=aReader.ReadInteger('FPSValue',25);
FVIFramesOnly:=aReader.ReadBool('VIFramesOnly',false)
end;
procedure TMediaProcessor_Convertor_Hh_H264_H624.SaveCustomProperties(const aWriter: IPropertiesWriter);
begin
inherited;
aWriter.WriteInteger('ChangeFPSMode',integer(FChangeFPSMode));
aWriter.WriteInteger('FPSValue',FFPSValue);
aWriter.WriteBool('VIFramesOnly',FVIFramesOnly);
end;
procedure TMediaProcessor_Convertor_Hh_H264_H624.ShowCustomProperiesDialog;
var
aDialog: TfmMediaProcessingSettingsHhH264_H264;
begin
aDialog:=TfmMediaProcessingSettingsHhH264_H264.Create(nil);
try
aDialog.ckChangeFPS.Checked:=FChangeFPSMode<>cfmNone;
aDialog.ckChangeFPSAbsolute.Checked:=FChangeFPSMode in [cfmAbsolute,cfmNone];
aDialog.ckFPSVIFramesOnly.Checked:=FChangeFPSMode=cfmVIFrameOnly;
aDialog.edFPSValue.Value:=FFPSValue;
if aDialog.ShowModal=mrOK then
begin
FChangeFPSMode:=cfmNone;
if aDialog.ckChangeFPS.Checked then
begin
if aDialog.ckChangeFPSAbsolute.Checked then
begin
FChangeFPSMode:=cfmAbsolute;
FFPSValue:=aDialog.edFPSValue.Value
end
else begin
FChangeFPSMode:=cfmVIFrameOnly;
end;
end;
end;
finally
aDialog.Free;
end;
end;
initialization
MediaProceccorFactory.RegisterMediaProcessor(TMediaProcessor_Convertor_Hh_H264_H624);
end.
|
program CreationLectureEcrireFichierType;
uses crt;
type
c=file of integer; // fichier d'entier uniquement, sera crypte si la personne essaie de l'ouvrir manuellement, aussi possible avec les enregistrements ou des chaines par exemple
procedure CreerFichier(var d:c); // la procedure servira a creer le fichier en supposant qu'il n'existe pas encore
var
q:integer;
begin
q:=123;
Assign(d,'entier.txt'); // va indiquer que f correspond au fichier entier, dans la destination en question (ici dans le meme fichier que le programme)
rewrite(d); // permet de creer le fichier si il n'existe pas encore, et si il existe, efface son contenu
writeln('Le fichier type sera cree avec dedans marque 123');
write(d,q); // va ecrire le 123 dans le fichier
close(d); // ferme le fichier
end;
procedure LectureFichier(var d:c; s:integer); // va permettre a l'utilisateur de lire le fichier
begin
Reset(d); // Va ouvrir le fichier uniquement en lecture, et donc non modifiable
writeln('Va afficher le chiffre dans le fichier');
read(d,s);
writeln(s);
close(d); //ferme le fichier
end;
var
d:c; // pour dire que d correspond au fichier d'entier
s:integer;
begin
clrscr;
CreerFichier(d);
LectureFichier(d,s);
readln;
END.
|
{
*****************************************************************************
* *
* See the file COPYING.modifiedLGPL, included in this distribution, *
* for details about the copyright. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* *
*****************************************************************************
Author: Mattias Gaertner
Abstract:
Find in files dialog form.
}
unit FindInFilesDlg;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LCLProc, LCLIntf, Controls, StdCtrls, Forms, Buttons,
ExtCtrls, LResources, FileUtil, LazarusIDEStrConsts, Dialogs, SynEditTypes,
IDEDialogs, IDEWindowIntf, InputHistory;
type
{ TLazFindInFilesDialog }
TLazFindInFilesDialog = class(TForm)
ReplaceCheckBox: TCheckBox;
ReplaceTextComboBox: TComboBox;
IncludeSubDirsCheckBox: TCheckBox;
FileMaskComboBox: TComboBox;
DirectoryBrowse: TBitBtn;
DirectoryComboBox: TComboBox;
DirectoryLabel: TLabel;
FileMaskLabel: TLabel;
OKButton: TButton;
CancelButton: TButton;
DirectoryOptionsGroupBox: TGroupBox;
OptionsCheckGroupBox: TCheckGroup;
SelectDirectoryDialog: TSelectDirectoryDialog;
TextToFindComboBox: TComboBox;
TextToFindLabel: TLabel;
WhereRadioGroup: TRadioGroup;
procedure DirectoryBrowseClick(Sender: TObject);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure ReplaceCheckBoxChange(Sender: TObject);
procedure WhereRadioGroupClick(Sender: TObject);
private
function GetFindText: string;
function GetOptions: TLazFindInFileSearchOptions;
function GetReplaceText: string;
function GetSynOptions: TSynSearchOptions;
procedure SetFindText(const NewFindText: string);
procedure SetOptions(NewOptions: TLazFindInFileSearchOptions);
procedure SetReplaceText(const AValue: string);
procedure SetSynOptions(NewOptions: TSynSearchOptions);
procedure UpdateReplaceCheck;
public
property Options: TLazFindInFileSearchOptions read GetOptions
write SetOptions;
property FindText: string read GetFindText write SetFindText;
property ReplaceText: string read GetReplaceText write SetReplaceText;
property SynSearchOptions: TSynSearchOptions read GetSynOptions
write SetSynOptions;
end;
var FindInFilesDialog: TLazFindInFilesDialog;
implementation
{ TLazFindInFilesDialog }
procedure TLazFindInFilesDialog.SetFindText(const NewFindText: string);
begin
TextToFindComboBox.Text := NewFindText;
TextToFindComboBox.SelectAll;
ActiveControl := TextToFindComboBox;
end;
function TLazFindInFilesDialog.GetFindText: string;
begin
Result := TextToFindComboBox.Text;
end;
function TLazFindInFilesDialog.GetReplaceText: string;
begin
Result:=ReplaceTextComboBox.Text;
end;
procedure TLazFindInFilesDialog.WhereRadioGroupClick(Sender: TObject);
begin
DirectoryOptionsGroupBox.Enabled := (WhereRadioGroup.ItemIndex = 2)
end;
procedure TLazFindInFilesDialog.DirectoryBrowseClick(Sender: TObject);
begin
InitIDEFileDialog(SelectDirectoryDialog);
if DirectoryExists(DirectoryComboBox.Text) then
SelectDirectoryDialog.InitialDir := DirectoryComboBox.Text else
SelectDirectoryDialog.InitialDir := GetCurrentDir;
if SelectDirectoryDialog.Execute then
DirectoryComboBox.Text := SelectDirectoryDialog.FileName;
StoreIDEFileDialog(SelectDirectoryDialog);
end;
procedure TLazFindInFilesDialog.FormClose(Sender: TObject;
var CloseAction: TCloseAction);
begin
IDEDialogLayoutList.SaveLayout(Self);
end;
procedure TLazFindInFilesDialog.FormCreate(Sender: TObject);
begin
Caption := srkmecFindInFiles;
TextToFindLabel.Caption := lisFindFileTextToFind;
ReplaceCheckBox.Caption := lisMenuReplace;
OptionsCheckGroupBox.Caption := dlgFROpts;
OptionsCheckGroupBox.Items[0] := lisFindFileCaseSensitive;
OptionsCheckGroupBox.Items[1] := lisFindFileWholeWordsOnly;
OptionsCheckGroupBox.Items[2] := lisFindFileRegularExpressions;
OptionsCheckGroupBox.Items[3] := lisFindFileMultiLine;
WhereRadioGroup.Caption:=lisFindFileWhere;
WhereRadioGroup.Items[0] := lisFindFilesearchAllFilesInProject;
WhereRadioGroup.Items[1] := lisFindFilesearchAllOpenFiles;
WhereRadioGroup.Items[2] := lisFindFilesearchInDirectories;
DirectoryOptionsGroupBox.Caption := lisFindFileDirectoryOptions;
DirectoryLabel.Caption := lisCodeToolsDefsInsertBehindDirectory;
FileMaskLabel.Caption := lisFindFileFileMaskBak;
IncludeSubDirsCheckBox.Caption := lisFindFileIncludeSubDirectories;
OkButton.Caption := lisLazBuildOk;
CancelButton.Caption := dlgCancel;
ReplaceCheckBox.Enabled:=true;
UpdateReplaceCheck;
DirectoryOptionsGroupBox.Enabled:=WhereRadioGroup.ItemIndex=2;
IDEDialogLayoutList.ApplyLayout(Self);
end;
procedure TLazFindInFilesDialog.ReplaceCheckBoxChange(Sender: TObject);
begin
UpdateReplaceCheck;
end;
procedure TLazFindInFilesDialog.SetOptions(NewOptions: TLazFindInFileSearchOptions);
begin
OptionsCheckGroupBox.Checked[0] := fifMatchCase in NewOptions;
OptionsCheckGroupBox.Checked[1] := fifWholeWord in NewOptions;
OptionsCheckGroupBox.Checked[2] := fifRegExpr in NewOptions;
OptionsCheckGroupBox.Checked[3] := fifMultiLine in NewOptions;
DirectoryOptionsGroupBox.Enabled := fifSearchDirectories in NewOptions;
IncludeSubDirsCheckBox.Checked := fifIncludeSubDirs in NewOptions;
ReplaceCheckBox.Checked := [fifReplace,fifReplaceAll]*NewOptions<>[];
if fifSearchProject in NewOptions then WhereRadioGroup.ItemIndex := 0;
if fifSearchOpen in NewOptions then WhereRadioGroup.ItemIndex := 1;
if fifSearchDirectories in NewOptions then WhereRadioGroup.ItemIndex := 2;
UpdateReplaceCheck;
end;
function TLazFindInFilesDialog.GetOptions: TLazFindInFileSearchOptions;
begin
Result := [];
if OptionsCheckGroupBox.Checked[0] then Include(Result, fifMatchCase);
if OptionsCheckGroupBox.Checked[1] then Include(Result, fifWholeWord);
if OptionsCheckGroupBox.Checked[2] then Include(Result, fifRegExpr);
if OptionsCheckGroupBox.Checked[3] then Include(Result, fifMultiLine);
if IncludeSubDirsCheckBox.Checked then Include(Result, fifIncludeSubDirs);
if ReplaceCheckBox.Checked then Include(Result, fifReplace);
case WhereRadioGroup.ItemIndex of
0: Include(Result, fifSearchProject);
1: Include(Result, fifSearchOpen);
2: Include(Result, fifSearchDirectories);
end;//case
end;
function TLazFindInFilesDialog.GetSynOptions: TSynSearchOptions;
begin
Result := [];
if OptionsCheckGroupBox.Checked[0] then Include(Result, ssoMatchCase);
if OptionsCheckGroupBox.Checked[1] then Include(Result, ssoWholeWord);
if OptionsCheckGroupBox.Checked[2] then Include(Result, ssoRegExpr);
if OptionsCheckGroupBox.Checked[3] then Include(Result, ssoRegExprMultiLine);
if ReplaceCheckBox.Checked then Include(Result, ssoReplace);
end;//GetSynOptions
procedure TLazFindInFilesDialog.SetReplaceText(const AValue: string);
begin
ReplaceTextComboBox.Text := AValue;
end;
procedure TLazFindInFilesDialog.SetSynOptions(NewOptions: TSynSearchOptions);
begin
OptionsCheckGroupBox.Checked[0] := ssoMatchCase in NewOptions;
OptionsCheckGroupBox.Checked[1] := ssoWholeWord in NewOptions;
OptionsCheckGroupBox.Checked[2] := ssoRegExpr in NewOptions;
OptionsCheckGroupBox.Checked[3] := ssoRegExprMultiLine in NewOptions;
ReplaceCheckBox.Checked := ([ssoReplace,ssoReplaceAll]*NewOptions <> []);
UpdateReplaceCheck;
end;//SetSynOptions
procedure TLazFindInFilesDialog.UpdateReplaceCheck;
begin
ReplaceTextComboBox.Enabled:=ReplaceCheckBox.Checked;
if ReplaceCheckBox.Checked then
OKButton.Caption:=lisMenuReplace
else
OKButton.Caption:=lisMenuFind;
end;
initialization
{$I findinfilesdlg.lrs}
FindInFilesDialog := nil;
end.
|
{ 25/05/2007 11:15:22 (GMT+1:00) > [Akadamia] checked in }
{ 25/05/2007 11:14:58 (GMT+1:00) > [Akadamia] checked out /}
{ 25/05/2007 11:14:27 (GMT+1:00) > [Akadamia] checked in }
{-----------------------------------------------------------------------------
Unit Name: FDU
Author: ken.adam
Date: 15-Jan-2007
Purpose: Translation of Facilities Data example to Delphi
History:
-----------------------------------------------------------------------------}
unit FDU;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ImgList, ToolWin, ActnMan, ActnCtrls, XPStyleActnCtrls,
ActnList, ComCtrls, SimConnect, StdActns;
const
// Define a user message for message driven version of the example
WM_USER_SIMCONNECT = WM_USER + 2;
type
// Use enumerated types to create unique IDs as required
TGroupId = (Group0);
TInputId = (Input0);
TEventID = (Event0, Event1, EventMenu1, EventMenu2);
TDataRequestId = (Request0, Request1);
// The form
TFacilitiesDataForm = class(TForm)
StatusBar: TStatusBar;
ActionManager: TActionManager;
ActionToolBar: TActionToolBar;
Images: TImageList;
Memo: TMemo;
StartPoll: TAction;
FileExit: TFileExit;
StartEvent: TAction;
procedure StartPollExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure SimConnectMessage(var Message: TMessage); message
WM_USER_SIMCONNECT;
procedure StartEventExecute(Sender: TObject);
private
{ Private declarations }
RxCount: integer; // Count of Rx messages
Quit: boolean; // True when signalled to quit
hSimConnect: THandle; // Handle for the SimConection
public
{ Public declarations }
procedure DispatchHandler(pData: PSimConnectRecv; cbData: DWORD; pContext:
Pointer);
procedure RespondTo(Rcv: PSimConnectRecvFaciltiesList; ListType:
SIMCONNECT_FACILITY_LIST_TYPE);
end;
var
FacilitiesDataForm: TFacilitiesDataForm;
implementation
uses SimConnectSupport;
resourcestring
StrRx6d = 'Rx: %6d';
const
szTitle = 'Facilities Data' + #0;
szHelp = 'Press Ctrl-F1 for Get Facilities, Ctrl-F2 for Subscribe to Facilities'
+ #0;
GetFacilitiesMenu = 'SimConnect Facilities Test' + #0 +
'Choose which item:' + #0 +
'Get airport facilities' + #0 +
'Get waypoints' + #0 +
'Get NDB' + #0 +
'Get VOR' + #0 +
'Close menu' + #0;
SubscribeFacilitiesMenu = 'SimConnect Facilities Test' + #0 +
'Choose which item:' + #0 +
'Subscribe to airports' + #0 +
'Subscribe to waypoints' + #0 +
'Subscribe to NDB' + #0 +
'Subscribe to VOR' + #0 +
'Unsubscribe to airports' + #0 +
'Unsubscribe to waypoints' + #0 +
'Unsubscribe to NDB' + #0 +
'Unsubscribe to VOR' + #0 +
'Close menu' + #0;
{$R *.dfm}
{-----------------------------------------------------------------------------
Procedure: MyDispatchProc
Wraps the call to the form method in a simple StdCall procedure
Author: ken.adam
Date: 11-Jan-2007
Arguments:
pData: PSimConnectRecv
cbData: DWORD
pContext: Pointer
-----------------------------------------------------------------------------}
procedure MyDispatchProc(pData: PSimConnectRecv; cbData: DWORD; pContext:
Pointer); stdcall;
begin
FacilitiesDataForm.DispatchHandler(pData, cbData, pContext);
end;
function MenuText(InResult: SIMCONNECT_TEXT_RESULT): string;
begin
case InResult of
SIMCONNECT_TEXT_RESULT_DISPLAYED:
Result := 'Displayed';
SIMCONNECT_TEXT_RESULT_QUEUED:
Result := 'Queued';
SIMCONNECT_TEXT_RESULT_REMOVED:
Result := 'Removed from Queue';
SIMCONNECT_TEXT_RESULT_REPLACED:
Result := 'Replaced in Queue';
SIMCONNECT_TEXT_RESULT_TIMEOUT:
Result := 'Timeout';
else
begin
if (SIMCONNECT_TEXT_RESULT_MENU_SELECT_1 <= InResult)
and (InResult <= SIMCONNECT_TEXT_RESULT_MENU_SELECT_10) then
Result := Format('%2d Selected', [Ord(InResult) -
Ord(SIMCONNECT_TEXT_RESULT_MENU_SELECT_1) + 1])
else
Result := '<unknown>';
end;
end;
end;
{-----------------------------------------------------------------------------
Procedure: DispatchHandler
Handle the Dispatched callbacks in a method of the form. Note that this is
used by both methods of handling the interface.
Author: ken.adam
Date: 11-Jan-2007
Arguments:
pData: PSimConnectRecv
cbData: DWORD
pContext: Pointer
-----------------------------------------------------------------------------}
procedure TFacilitiesDataForm.DispatchHandler(pData: PSimConnectRecv; cbData:
DWORD;
pContext: Pointer);
var
hr : HRESULT;
Evt : PSimconnectRecvEvent;
OpenData : PSimConnectRecvOpen;
Item : cardinal;
begin
// Maintain a display of the message count
Inc(RxCount);
StatusBar.Panels[1].Text := Format(StrRx6d, [RxCount]);
// Only keep the last 2000 lines in the Memo
while Memo.Lines.Count > 2000 do
Memo.Lines.Delete(0);
// Handle the various types of message
case TSimConnectRecvId(pData^.dwID) of
SIMCONNECT_RECV_ID_EXCEPTION:
with PSimConnectRecvException(pData)^ do
Memo.Lines.Add(Format('%s (%8.8x,%8.8x,%8.8x,%8.8x,%8.8x,%8.8x)', [
SimConnectExceptionNames[TSimConnectException(dwException)],
dwSize, dwVersion, dwID, dwException, dwSendID, dwIndex]));
SIMCONNECT_RECV_ID_OPEN:
begin
StatusBar.Panels[0].Text := 'Opened';
OpenData := PSimConnectRecvOpen(pData);
with OpenData^ do
begin
Memo.Lines.Add('');
Memo.Lines.Add(Format('%s %1d.%1d.%1d.%1d', [szApplicationName,
dwApplicationVersionMajor, dwApplicationVersionMinor,
dwApplicationBuildMajor, dwApplicationBuildMinor]));
Memo.Lines.Add(Format('%s %1d.%1d.%1d.%1d', ['SimConnect',
dwSimConnectVersionMajor, dwSimConnectVersionMinor,
dwSimConnectBuildMajor, dwSimConnectBuildMinor]));
Memo.Lines.Add('');
end;
end;
SIMCONNECT_RECV_ID_EVENT:
begin
evt := PSimconnectRecvEvent(pData);
case TEventId(evt^.uEventID) of
Event0: // Display menu
SimConnect_Text(hSimConnect, SIMCONNECT_TEXT_TYPE_MENU, 0,
Ord(EventMenu1), length(GetFacilitiesMenu),
@GetFacilitiesMenu[1]);
Event1: // Stop displaying menu
SimConnect_Text(hSimConnect, SIMCONNECT_TEXT_TYPE_MENU, 0,
Ord(EventMenu2), length(SubscribeFacilitiesMenu),
@SubscribeFacilitiesMenu[1]);
EventMenu1: // Respond to the users menu selection
begin
Memo.Lines.Add(Format('MENU #1 Event: dwData=%d (%s)',
[evt^.dwData, MenuText(SIMCONNECT_TEXT_RESULT(evt^.dwData))]));
Item := evt^.dwData - Ord(SIMCONNECT_TEXT_RESULT_MENU_SELECT_1);
if Item < Ord(SIMCONNECT_FACILITY_LIST_TYPE_COUNT) then
// Get the current cached list of airports, waypoints, etc, as the item indicates
hr := SimConnect_RequestFacilitiesList(hSimConnect,
SIMCONNECT_FACILITY_LIST_TYPE(Item), Ord(Request0));
end;
EventMenu2:
begin
Memo.Lines.Add(Format('MENU #2 Event: dwData=%d (%s)',
[evt^.dwData, MenuText(SIMCONNECT_TEXT_RESULT(evt^.dwData))]));
Item := evt^.dwData - Ord(SIMCONNECT_TEXT_RESULT_MENU_SELECT_1);
if Item < Ord(SIMCONNECT_FACILITY_LIST_TYPE_COUNT) then
hr := SimConnect_SubscribeToFacilities(hSimConnect,
SIMCONNECT_FACILITY_LIST_TYPE(item), Ord(Request1))
else if (Ord(SIMCONNECT_FACILITY_LIST_TYPE_COUNT) <= Item)
and (Item < 2 * Ord(SIMCONNECT_FACILITY_LIST_TYPE_COUNT)) then
hr := SimConnect_UnsubscribeToFacilities(hSimConnect,
SIMCONNECT_FACILITY_LIST_TYPE(item -
Ord(SIMCONNECT_FACILITY_LIST_TYPE_COUNT)));
end
else
Memo.Lines.Add(Format('SIMCONNECT_RECV_EVENT: 0x%08X 0x%08X 0x%X',
[evt^.uEventID, evt^.dwData, cbData]));
end;
end;
SIMCONNECT_RECV_ID_AIRPORT_LIST:
RespondTo(PSimConnectRecvFaciltiesList(pData),
SIMCONNECT_FACILITY_LIST_TYPE_AIRPORT);
SIMCONNECT_RECV_ID_WAYPOINT_LIST:
RespondTo(PSimConnectRecvFaciltiesList(pData),
SIMCONNECT_FACILITY_LIST_TYPE_WAYPOINT);
SIMCONNECT_RECV_ID_NDB_LIST:
RespondTo(PSimConnectRecvFaciltiesList(pData),
SIMCONNECT_FACILITY_LIST_TYPE_NDB);
SIMCONNECT_RECV_ID_VOR_LIST:
RespondTo(PSimConnectRecvFaciltiesList(pData),
SIMCONNECT_FACILITY_LIST_TYPE_VOR);
SIMCONNECT_RECV_ID_QUIT:
begin
Quit := True;
StatusBar.Panels[0].Text := 'FS X Quit';
end
else
Memo.Lines.Add(Format('Unknown dwID: %d', [pData.dwID]));
end;
end;
{-----------------------------------------------------------------------------
Procedure: FormCloseQuery
Ensure that we can signal "Quit" to the busy wait loop
Author: ken.adam
Date: 11-Jan-2007
Arguments: Sender: TObject var CanClose: Boolean
Result: None
-----------------------------------------------------------------------------}
procedure TFacilitiesDataForm.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
Quit := True;
CanClose := True;
end;
{-----------------------------------------------------------------------------
Procedure: FormCreate
We are using run-time dynamic loading of SimConnect.dll, so that the program
will execute and fail gracefully if the DLL does not exist.
Author: ken.adam
Date: 11-Jan-2007
Arguments:
Sender: TObject
Result: None
-----------------------------------------------------------------------------}
procedure TFacilitiesDataForm.FormCreate(Sender: TObject);
begin
if InitSimConnect then
StatusBar.Panels[2].Text := 'SimConnect.dll Loaded'
else
begin
StatusBar.Panels[2].Text := 'SimConnect.dll NOT FOUND';
StartPoll.Enabled := False;
StartEvent.Enabled := False;
end;
Quit := False;
hSimConnect := 0;
StatusBar.Panels[0].Text := 'Not Connected';
RxCount := 0;
StatusBar.Panels[1].Text := Format(StrRx6d, [RxCount]);
end;
procedure TFacilitiesDataForm.RespondTo(Rcv: PSimConnectRecvFaciltiesList;
ListType: SIMCONNECT_FACILITY_LIST_TYPE);
var
I : integer;
procedure Dump(pFac: PSIMCONNECT_DATA_FACILITY_AIRPORT); overload;
begin
Memo.Lines.Add(Format(' Icao: %s Latitude: %f Longitude: %f Altitude: %f',
[pFac^.Icao, pFac^.Latitude, pFac^.Longitude, pFac^.Altitude]));
end;
procedure Dump(pFac: PSIMCONNECT_DATA_FACILITY_WAYPOINT); overload;
begin
Dump(PSIMCONNECT_DATA_FACILITY_AIRPORT(pFac));
Memo.Lines.Add(Format(' fMagVar: %f', [pFac^.fMagVar]));
end;
procedure Dump(pFac: PSIMCONNECT_DATA_FACILITY_NDB); overload;
begin
Dump(PSIMCONNECT_DATA_FACILITY_WAYPOINT(pFac));
Memo.Lines.Add(Format(' fFrequency: %d', [pFac^.fFrequency]));
end;
procedure Dump(pFac: PSIMCONNECT_DATA_FACILITY_VOR); overload;
begin
Dump(PSIMCONNECT_DATA_FACILITY_NDB(pFac));
Memo.Lines.Add(Format(
' Flags: %x fLocalizer: %f GlideLat: %f GlideLon: %f GlideAlt: %f fGlideSlopeAngle: %f',
[pFac^.Flags, pFac^.fLocalizer, pFac^.GlideLat, pFac^.GlideLon,
pFac^.GlideAlt, pFac^.fGlideSlopeAngle]));
end;
begin
Memo.Lines.Add(Format('RequestID: %d dwArraySize: %d dwEntryNumber: %d dwOutOf: %d',
[Rcv^.dwRequestID, Rcv^.dwArraySize, Rcv^.dwEntryNumber, Rcv^.dwOutOf]));
for I := 0 to Rcv^.dwArraySize - 1 do
case ListType of
SIMCONNECT_FACILITY_LIST_TYPE_AIRPORT:
with PSIMCONNECT_RECV_AIRPORT_LIST(Rcv)^ do
Dump(PSIMCONNECT_DATA_FACILITY_AIRPORT(@rgData[I]));
SIMCONNECT_FACILITY_LIST_TYPE_WAYPOINT:
with PSIMCONNECT_RECV_WAYPOINT_LIST(Rcv)^ do
Dump(PSIMCONNECT_DATA_FACILITY_WAYPOINT(@rgData[I]));
SIMCONNECT_FACILITY_LIST_TYPE_NDB:
with PSIMCONNECT_RECV_NDB_LIST(Rcv)^ do
Dump(PSIMCONNECT_DATA_FACILITY_NDB(@rgData[I]));
SIMCONNECT_FACILITY_LIST_TYPE_VOR:
with PSIMCONNECT_RECV_VOR_LIST(Rcv)^ do
Dump(PSIMCONNECT_DATA_FACILITY_VOR(@rgData[I]));
end;
end;
{-----------------------------------------------------------------------------
Procedure: SimConnectMessage
This uses CallDispatch, but could probably avoid the callback and use
SimConnect_GetNextDispatch instead.
Author: ken.adam
Date: 11-Jan-2007
Arguments:
var Message: TMessage
-----------------------------------------------------------------------------}
procedure TFacilitiesDataForm.SimConnectMessage(var Message: TMessage);
begin
SimConnect_CallDispatch(hSimConnect, MyDispatchProc, nil);
end;
{-----------------------------------------------------------------------------
Procedure: StartEventExecute
Opens the connection for Event driven handling. If successful sets up the data
requests and hooks the system event "SimStart".
Author: ken.adam
Date: 11-Jan-2007
Arguments:
Sender: TObject
-----------------------------------------------------------------------------}
procedure TFacilitiesDataForm.StartEventExecute(Sender: TObject);
var
hr : HRESULT;
begin
if (SUCCEEDED(SimConnect_Open(hSimConnect, 'Facilities Data', Handle,
WM_USER_SIMCONNECT, 0, 0))) then
begin
StatusBar.Panels[0].Text := 'Connected';
hr := SimConnect_MapClientEventToSimEvent(hSimConnect, Ord(Event0));
hr := SimConnect_MapClientEventToSimEvent(hSimConnect, Ord(Event1));
hr := SimConnect_AddClientEventToNotificationGroup(hSimConnect, Ord(Group0),
Ord(Event0), TRUE);
hr := SimConnect_AddClientEventToNotificationGroup(hSimConnect, Ord(Group0),
Ord(Event1), TRUE);
hr := SimConnect_SetNotificationGroupPriority(hSimConnect, Ord(Group0),
Ord(SIMCONNECT_GROUP_PRIORITY_HIGHEST));
hr := SimConnect_MapInputEventToClientEvent(hSimConnect, Ord(Input0),
'Ctrl+F1', Ord(Event0));
hr := SimConnect_MapInputEventToClientEvent(hSimConnect, Ord(Input0),
'Ctrl+F2', Ord(Event1));
hr := SimConnect_SetInputGroupState(hSimConnect, Ord(Input0),
Ord(SIMCONNECT_STATE_ON));
SimConnect_Text(hSimConnect, SIMCONNECT_TEXT_TYPE_PRINT_RED, 15, 0,
Length(szTitle), @szTitle[1]);
SimConnect_Text(hSimConnect, SIMCONNECT_TEXT_TYPE_PRINT_RED, 15, 0,
Length(szHelp), @szHelp[1]);
StartEvent.Enabled := False;
StartPoll.Enabled := False;
end;
end;
{-----------------------------------------------------------------------------
Procedure: StartPollExecute
Opens the connection for Polled access. If successful sets up the data
requests and hooks the system event "SimStart", and then loops indefinitely
on CallDispatch.
Author: ken.adam
Date: 11-Jan-2007
Arguments:
Sender: TObject
-----------------------------------------------------------------------------}
procedure TFacilitiesDataForm.StartPollExecute(Sender: TObject);
var
hr : HRESULT;
begin
if (SUCCEEDED(SimConnect_Open(hSimConnect, 'Facilities Data', 0, 0, 0, 0))) then
begin
StatusBar.Panels[0].Text := 'Connected';
hr := SimConnect_MapClientEventToSimEvent(hSimConnect, Ord(Event0));
hr := SimConnect_MapClientEventToSimEvent(hSimConnect, Ord(Event1));
hr := SimConnect_AddClientEventToNotificationGroup(hSimConnect, Ord(Group0),
Ord(Event0), TRUE);
hr := SimConnect_AddClientEventToNotificationGroup(hSimConnect, Ord(Group0),
Ord(Event1), TRUE);
hr := SimConnect_SetNotificationGroupPriority(hSimConnect, Ord(Group0),
Ord(SIMCONNECT_GROUP_PRIORITY_HIGHEST));
hr := SimConnect_MapInputEventToClientEvent(hSimConnect, Ord(Input0),
'Ctrl+F1', Ord(Event0));
hr := SimConnect_MapInputEventToClientEvent(hSimConnect, Ord(Input0),
'Ctrl+F2', Ord(Event1));
hr := SimConnect_SetInputGroupState(hSimConnect, Ord(Input0),
Ord(SIMCONNECT_STATE_ON));
SimConnect_Text(hSimConnect, SIMCONNECT_TEXT_TYPE_PRINT_RED, 15, 0,
Length(szTitle), @szTitle[1]);
SimConnect_Text(hSimConnect, SIMCONNECT_TEXT_TYPE_PRINT_RED, 15, 0,
Length(szHelp), @szHelp[1]);
StartEvent.Enabled := False;
StartPoll.Enabled := False;
while not Quit do
begin
SimConnect_CallDispatch(hSimConnect, MyDispatchProc, nil);
Application.ProcessMessages;
Sleep(1);
end;
hr := SimConnect_Close(hSimConnect);
end;
end;
end.
|
unit uEndereco;
interface
uses System.Classes, System.SysUtils, IdHTTP, xmlDoc, Xml.xmldom, Xml.Win.msxmldom,
Vcl.Forms;
type TEndereco = class
private
FLogradouro: string;
FBairro: String;
FMunicipio: string;
FCidade: String;
FTipo: String;
FCodigoMunicipio: String;
FEstado: String;
FCep: String;
FEncontrou: boolean;
procedure limpaEndereco;
public
property cep : String read FCep;
property logradouro : string read FLogradouro;
property tipo : String read FTipo;
property bairro : String read FBairro;
property cidade : String read FCidade;
property estado : String read FEstado;
property codigoMunicipio : String read FCodigoMunicipio;
property municipio : string read FMunicipio;
property encontrou : boolean read FEncontrou default False;
procedure buscaEndereco(ACep: String);
end;
implementation
{ TEndereco }
procedure TEndereco.buscaEndereco(ACep: String);
var
resposta : TStringStream;
consulta : TStringList;
idHttp : TIdHTTP;
xml : TXMLDocument;
begin
limpaEndereco;
consulta := TStringList.Create;
resposta := TStringStream.Create('');
xml := TXMLDocument.Create(Application);
idHttp := TIdHTTP.Create(Application);
try
idHttp.Request.UserAgent:='Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV2';
consulta.Values['&cep'] := ACep;
consulta.Values['&formato'] := 'xml';
idHttp.Post('http://cep.republicavirtual.com.br/web_cep.php?', consulta, Resposta);
xml.Active := True;
xml.Encoding := 'iso-8859-1';
xml.LoadFromStream(Resposta);
FCidade := xml.DocumentElement.ChildNodes['cidade'].NodeValue;
FEstado := xml.DocumentElement.ChildNodes['uf'].NodeValue;
FMunicipio := FCidade;
FLogradouro := xml.DocumentElement.ChildNodes['logradouro'].NodeValue;
FTipo := xml.DocumentElement.ChildNodes['tipo_logradouro'].NodeValue;
FBairro := xml.DocumentElement.ChildNodes['bairro'].NodeValue;
FEncontrou := True;
finally
consulta.Free;
resposta.Free;
xml.Active := False;
xml.Free;
end;
end;
procedure TEndereco.limpaEndereco;
begin
FCep := '';
FLogradouro := '';
FTipo := '';
FBairro := '';
FCidade := '';
FEstado := '';
FCodigoMunicipio := '';
FMunicipio := '';
FEncontrou := False;
end;
end.
|
{*********************************************}
{ TeeChart Delphi Component Library }
{ Bubble Series Type Demo }
{ Copyright (c) 1995-1996 by David Berneda }
{ All rights reserved }
{*********************************************}
unit Bubble;
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, Chart, Series, ExtCtrls, StdCtrls, BubbleCh,
Teengine, Buttons, TeeProcs;
type
TBubbleForm = class(TForm)
Chart1: TChart;
Panel1: TPanel;
CheckBox1: TCheckBox;
Timer1: TTimer;
CheckBox2: TCheckBox;
ComboBox1: TComboBox;
Label1: TLabel;
BitBtn3: TBitBtn;
CheckBox3: TCheckBox;
BubbleSeries1: TBubbleSeries;
ZoomInButton: TSpeedButton;
ZoomOutButton: TSpeedButton;
Memo1: TMemo;
procedure FormCreate(Sender: TObject);
procedure CheckBox1Click(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure CheckBox2Click(Sender: TObject);
procedure ComboBox1Change(Sender: TObject);
procedure CheckBox3Click(Sender: TObject);
function BubbleSeries1GetPointerStyle(Sender: TChartSeries;
ValueIndex: Longint): TSeriesPointerStyle;
procedure ZoomInButtonClick(Sender: TObject);
procedure ZoomOutButtonClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
implementation
{$R *.DFM}
procedure TBubbleForm.FormCreate(Sender: TObject);
var t:Longint;
begin
ComboBox1.ItemIndex:=Ord(psCircle); { <-- Circled Bubbles by default }
BubbleSeries1.Clear;
for t:=1 to 100 do
BubbleSeries1.AddBubble( Date+t,
Random(ChartSamplesMax), { <-- y value }
ChartSamplesMax/(20+Random(25)), { <-- radius value }
'', { <-- label string }
GetDefaultColor(t)); { <-- color }
end;
procedure TBubbleForm.CheckBox1Click(Sender: TObject);
begin
Timer1.Enabled:=CheckBox1.Checked; { <-- on / off animation }
end;
procedure TBubbleForm.Timer1Timer(Sender: TObject);
Var tmpColor:TColor;
Begin
Timer1.Enabled:=False; { <-- stop the timer (this is optional) }
With BubbleSeries1 do
Begin
tmpColor:=ValueColor[0];
Delete(0); { <-- remove the first point }
{ Add a new random bubble }
AddBubble( XValues.Last+1, { <-- x value }
Random(ChartSamplesMax), { <-- y value }
ChartSamplesMax/(20+Random(25)), { <-- radius value }
'', { <-- label string }
tmpColor); { <-- color }
end;
if Random(100)<8 then
begin
if ComboBox1.ItemIndex<ComboBox1.Items.Count-1 then
ComboBox1.ItemIndex:=ComboBox1.ItemIndex+1
else
ComboBox1.ItemIndex:=0;
ComboBox1Change(Self);
end;
if (GetTickCount mod 1000)<=55 then
begin
with BubbleSeries1.GetHorizAxis.Title do
if Angle>=90 then Angle:=Angle-90 else Angle:=270;
with BubbleSeries1.GetVertAxis.Title do
if Angle>=90 then Angle:=Angle-90 else Angle:=270;
with BubbleSeries1.GetVertAxis do
if LabelsAngle>=90 then LabelsAngle:=LabelsAngle-90 else LabelsAngle:=270;
with BubbleSeries1.GetHorizAxis do
if LabelsAngle>=90 then LabelsAngle:=LabelsAngle-90 else LabelsAngle:=270;
end;
Timer1.Enabled:=True; { <-- restart the timer }
end;
procedure TBubbleForm.CheckBox2Click(Sender: TObject);
begin
BubbleSeries1.Marks.Visible:=CheckBox2.Checked; { switch on/off Marks }
end;
procedure TBubbleForm.ComboBox1Change(Sender: TObject);
begin { the demo combobox1 allows changing Bubble style }
BubbleSeries1.Pointer.Style:=TSeriesPointerStyle(ComboBox1.ItemIndex);
end;
procedure TBubbleForm.CheckBox3Click(Sender: TObject);
begin
Chart1.Repaint;
end;
function TBubbleForm.BubbleSeries1GetPointerStyle(Sender: TChartSeries;
ValueIndex: Longint): TSeriesPointerStyle;
begin
if CheckBox3.Checked then
result:=TSeriesPointerStyle(Random(Ord(High(TSeriesPointerStyle))))
else
result:=BubbleSeries1.Pointer.Style;
end;
procedure TBubbleForm.ZoomInButtonClick(Sender: TObject);
begin
Chart1.ZoomPercent(110);
end;
procedure TBubbleForm.ZoomOutButtonClick(Sender: TObject);
begin
Chart1.ZoomPercent(90);
end;
end.
|
unit JdcView;
interface
uses
ObserverList, ValueList,
Classes, SysUtils;
type
TView = class(TObserverList)
protected
constructor Create(AOwner: TComponent); reintroduce;
public
class function Obj: TView;
procedure sp_SyncPacket(const APacket: String);
procedure sp_ASyncPacket(const APacket: String);
procedure sp_ErrorMessage(const AName: String; AMsg: String = '');
procedure sp_LogMessage(const AName: String; AMsg: String = '');
procedure sp_DebugMessage(const AName: String; AMsg: String = '');
procedure sp_SyncMessage(const ACode: String; AMsg: String = '');
procedure sp_AsyncMessage(const ACode: String; AMsg: String = '');
destructor Destroy; override;
procedure sp_Terminate(const Msg: string = '');
end;
implementation
var
MyObj: TView = nil;
{ TView }
constructor TView.Create(AOwner: TComponent);
begin
inherited;
end;
destructor TView.Destroy;
begin
inherited;
end;
procedure TView.sp_AsyncMessage(const ACode: String; AMsg: String = '');
var
ValueList: TValueList;
begin
ValueList := TValueList.Create;
try
ValueList.Values['Code'] := ACode;
ValueList.Values['Msg'] := AMsg;
AsyncBroadcast(ValueList);
finally
ValueList.Free;
end;
end;
procedure TView.sp_ASyncPacket(const APacket: String);
var
ValueList: TValueList;
begin
ValueList := TValueList.Create;
try
ValueList.Text := APacket;
AsyncBroadcast(ValueList);
finally
ValueList.Free;
end;
end;
procedure TView.sp_DebugMessage(const AName: String; AMsg: String);
var
ValueList: TValueList;
begin
ValueList := TValueList.Create;
try
ValueList.Values['Code'] := 'DebugMessage';
ValueList.Values['Name'] := AName;
ValueList.Values['Msg'] := AMsg;
AsyncBroadcast(ValueList);
finally
ValueList.Free;
end;
end;
procedure TView.sp_ErrorMessage(const AName: String; AMsg: String);
var
ValueList: TValueList;
begin
ValueList := TValueList.Create;
try
ValueList.Values['Code'] := 'ErrorMessage';
ValueList.Values['Name'] := AName;
ValueList.Values['Msg'] := AMsg;
AsyncBroadcast(ValueList);
finally
ValueList.Free;
end;
end;
procedure TView.sp_LogMessage(const AName: String; AMsg: String = '');
var
ValueList: TValueList;
begin
ValueList := TValueList.Create;
try
ValueList.Values['Code'] := 'LogMessage';
ValueList.Values['Name'] := AName;
ValueList.Values['Msg'] := AMsg;
AsyncBroadcast(ValueList);
finally
ValueList.Free;
end;
end;
procedure TView.sp_SyncPacket(const APacket: String);
var
ValueList: TValueList;
begin
ValueList := TValueList.Create;
try
ValueList.Text := APacket;
BroadCast(ValueList);
finally
ValueList.Free;
end;
end;
procedure TView.sp_SyncMessage(const ACode: String; AMsg: String = '');
var
ValueList: TValueList;
begin
ValueList := TValueList.Create;
try
ValueList.Values['Code'] := ACode;
ValueList.Values['Msg'] := AMsg;
BroadCast(ValueList);
finally
ValueList.Free;
end;
end;
procedure TView.sp_Terminate(const Msg: string);
begin
sp_SyncMessage('Terminate', Msg);
end;
class function TView.Obj: TView;
begin
if MyObj = nil then
MyObj := TView.Create(nil);
Result := MyObj;
end;
initialization
MyObj := TView.Create(nil);
end.
|
{
Maze painter class of the Lazarus Mazes program
Copyright (C) 2012 G.A. Nijland (eny @ lazarus forum http://www.lazarus.freepascal.org/)
This source is free software; you can redistribute it and/or modify it under the terms of the GNU General Public
License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later
version.
This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
details.
A copy of the GNU General Public License is available on the World Wide Web at
<http://www.gnu.org/copyleft/gpl.html>. You can also obtain it by writing to the Free Software Foundation, Inc., 59
Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
unit MazePainter;
{$mode objfpc}{$H+}
interface
uses
Maze,
Graphics, Classes, SysUtils;
type
{ TMazePainter }
TMazePainter = class
private
FCellDrawWidth: integer;
FCellDrawHeight: integer;
FisDirty: boolean;
Maze: TMaze;
FCanvas: TCanvas;
bmp: TBitMap;
FWallColor: TColor;
FWallShadowColor: TColor;
FCellColors: array[TCellState] of TColor;
function GetCellColor(const pState: TCellState): TColor;
procedure SetCellColor(const pState: TCellState; pColor: TColor);
procedure Grow(var pRect: TRect; const pdx, pdy: integer);
public
constructor Create(const pMaze: TMaze; pCanvas: TCanvas);
destructor Destroy; override;
procedure Paint(const pOffsetX: integer = 0; const pOffsetY: integer = 0);
function Width : integer;
function Height: integer;
property CellDrawWidth: integer read FCellDrawWidth write FCellDrawWidth;
property CellDrawHeight: integer read FCellDrawHeight write FCellDrawHeight;
property CellColor[const pState: TCellState]: TColor read GetCellColor write SetCellColor;
property WallColor: TColor read FWallColor write FWallColor;
property WallShadowColor: TColor read FWallShadowColor write FWallShadowColor;
property IsDirty: boolean read FisDirty write FisDirty;
end;
implementation
{ TMazePainter }
constructor TMazePainter.Create(const pMaze: TMaze; pCanvas: TCanvas);
begin
// Init the default drawing width and height
FCellDrawWidth := 15;
FCellDrawHeight := 15;
// Set default colors
WallColor := clBlue;
CellColor[csEmpty] := clSkyBlue;
CellColor[csStart] := clYellow;
CellColor[csVisited] := clMaroon;
CellColor[csExit] := clGreen;
// Store maze and canvas for future reference
Maze := pMaze;
FCanvas := pCanvas;
// Refresh on the next draw
isDirty := true;
end;
destructor TMazePainter.Destroy;
begin
bmp.Free;
inherited Destroy;
end;
function TMazePainter.GetCellColor(const pState: TCellState): TColor;
begin
result := FCellColors[pState];
end;
procedure TMazePainter.SetCellColor(const pState: TCellState; pColor: TColor);
begin
FCellColors[pState] := pColor
end;
procedure TMazePainter.Grow(var pRect: TRect; const pdx, pdy: integer);
begin
dec(pRect.Left, pdx);
dec(pRect.Top, pdy);
inc(pRect.Right, pdx);
inc(pRect.Bottom, pdy);
end;
procedure TMazePainter.Paint(const pOffsetX: integer; const pOffsetY: integer);
const C_LINE_THICK = 1;
var row,col: integer;
square : TRect;
Canvas : TCanvas;
dx,dy : integer;
begin
if isDirty then
begin
FreeAndNil(bmp);
bmp := TBitMap.Create;
bmp.Width := Width+1;
bmp.Height := Height+1;
Canvas := bmp.Canvas;
for row := 0 to Maze.Height-1 do
for col := 0 to Maze.Width-1 do
begin
// Draw the empty cell frame
Canvas.Brush.Color := CellColor[csEmpty];
Canvas.Pen.Color := Canvas.Brush.Color;
square.Top := row * CellDrawHeight;
square.Left := col * CellDrawWidth;
square.Right := square.Left + CellDrawWidth;
square.Bottom := square.Top + CellDrawHeight;
Canvas.Rectangle(square);
// draw walls
Canvas.Pen.color := FWallColor;
Canvas.Pen.Width := C_LINE_THICK;
Canvas.Pen.JoinStyle := pjsBevel;
with Maze[row,col] do
begin
if not CanGo[dirNorth] then
begin
Canvas.Line(square.Left, Square.Top, square.right, square.Top);
Canvas.Pen.color := clMoneyGreen;
Canvas.Line(square.Left+1, Square.Top+1, square.right-1, square.Top+1);
Canvas.Pen.color := clBlue;
end;
if not CanGo[dirSouth] then Canvas.Line(square.Left, Square.Bottom, square.right, square.Bottom);
if not CanGo[dirWest] then
begin
Canvas.Line(square.Left, Square.Top, square.Left, square.Bottom);
Canvas.Pen.color := clMoneyGreen;
Canvas.Line(square.Left+1, Square.Top+1, square.Left+1, square.Bottom-1);
Canvas.Pen.color := clBlue;
end;
if not CanGo[dirEast] then Canvas.Line(square.Right, Square.Top, square.Right, square.Bottom);
end;
// Draw inside when the cell is not empty
if Maze[row,col].State <> csEmpty then
begin
// Determine a visibly pleasing margin with the walls
if FCellDrawWidth < 13 then dx := -1 else dx := -3;
if FCellDrawHeight < 13 then dy := -1 else dy := -3;
// Shring by this margin and draw the cell's inside
Grow(square, dx, dy);
Canvas.Brush.Color := CellColor[Maze[row,col].State];
Canvas.Pen.Color := CellColor[Maze[row,col].State];
Canvas.Rectangle(square);
end;
end;
// Fully refreshed
isDirty := false;
end;
// Draw bitmap
FCanvas.CopyRect(Rect(pOffsetX,pOffsetY,pOffsetX+Width+1,pOffsetY+Height+1), bmp.Canvas, Rect(0,0,Width+1,Height+1));
end;
function TMazePainter.Width: integer;
begin
result := Maze.Width * CellDrawWidth;
end;
function TMazePainter.Height: integer;
begin
result := Maze.Height * CellDrawHeight;
end;
end.
|
{*******************************************************************************
* *
* TksListViewFilter - Search Filter for TksVirtualListView *
* *
* https://bitbucket.org/gmurt/kscomponents *
* *
* Copyright 2017 Graham Murt *
* *
* email: graham@kernow-software.co.uk *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* *
*******************************************************************************}
unit ksListViewFilter;
interface
{$I ksComponents.inc}
uses Classes, FMX.StdCtrls, FMX.Graphics, ksTypes, FMX.Objects,
System.UITypes, System.UIConsts, FMX.Edit, FMX.Types;
type
[ComponentPlatformsAttribute(
pidWin32 or
pidWin64 or
{$IFDEF XE8_OR_NEWER} pidiOSDevice32 or pidiOSDevice64 {$ELSE} pidiOSDevice {$ENDIF} or
{$IFDEF XE10_3_OR_NEWER} pidiOSSimulator32 or pidiOSSimulator64 {$ELSE} pidiOSSimulator {$ENDIF} or
{$IFDEF XE10_3_OR_NEWER} pidAndroid32Arm or pidAndroid64Arm {$ELSE} pidAndroid {$ENDIF}
)]
TksListViewFilter = class(TCustomEdit)
private
FTimer: TTimer;
FClearButton: TSpeedButton;
FButtonText: string;
procedure DoTimer(Sender: TObject);
procedure DoClickClear(Sender: TObject);
procedure ClearButtonMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single);
procedure SetButtonText(const Value: string);
protected
procedure SetText(const Value: string); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Unfocus;
published
property ButtonText: string read FButtonText write SetButtonText;
end;
procedure Register;
implementation
uses Math, System.TypInfo, System.Types, ksCommon, SysUtils, Fmx.Forms, FMX.Controls;
procedure Register;
begin
RegisterComponents('Kernow Software FMX', [TksListViewFilter]);
end;
{ TksSpeedButton }
procedure TksListViewFilter.ClearButtonMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Single);
begin
Text := '';
FClearButton.Visible := False;
end;
constructor TksListViewFilter.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
if (csDesigning in ComponentState) then exit;
FTimer := TTimer.Create(nil);
FTimer.Interval := 1000;
FTimer.OnTimer := DoTimer;
FClearButton := TSpeedButton.Create(Self);
FClearButton.Name := Name + 'FilterButton';
FClearButton.Align := TAlignLayout.Right;
FClearButton.TextSettings.Font.Size := 13;
FClearButton.StyledSettings := [TStyledSetting.Family,TStyledSetting.Style,TStyledSetting.FontColor];
FButtonText := 'CLEAR';
FClearButton.Text := FButtonText;
FClearButton.HitTest := True;
FClearButton.CanFocus := False;
StyleLookup := 'searcheditbox';
FClearButton.OnClick := DoClickClear;
FClearButton.OnMouseDown := ClearButtonMouseDown;
FClearButton.Visible := False;
AddObject(FClearButton);
Height := 60;
end;
destructor TksListViewFilter.Destroy;
begin
FClearButton.DisposeOf;
FreeAndNil(FTimer);
inherited;
end;
procedure TksListViewFilter.DoClickClear(Sender: TObject);
begin
Text := '';
FClearButton.Visible := False;
end;
procedure TksListViewFilter.DoTimer(Sender: TObject);
begin
FClearButton.Visible := Text <> '';
end;
procedure TksListViewFilter.SetButtonText(const Value: string);
begin
FButtonText := Value;
FClearButton.Text := FButtonText;
end;
procedure TksListViewFilter.SetText(const Value: string);
begin
inherited;
end;
procedure TksListViewFilter.Unfocus;
begin
Root.SetFocused(nil);
end;
end.
|
unit SearchFamOrCompoQuery;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseQuery, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt,
Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.StdCtrls;
type
TQuerySearchFamilyOrComp = class(TQueryBase)
private
{ Private declarations }
public
procedure PrepareSearchByValue(AValues: TArray<String>;
ALike, AFamily: Boolean);
function SearchFamily(const AFamily: String): Integer;
function SearchComponent(const AComponent: String): Integer;
function SearchEx(const AValue: String; ALike, AFamily: Boolean): Integer;
{ Public declarations }
end;
implementation
uses
StrHelper, System.StrUtils;
{$R *.dfm}
procedure TQuerySearchFamilyOrComp.PrepareSearchByValue(AValues: TArray<String>;
ALike, AFamily: Boolean);
var
ANewStipulation: string;
AStipulation: string;
AUpperS: string;
S: string;
begin
Assert(Length(AValues) > 0);
AStipulation := '';
// Формируем несколько условий
for S in AValues do
begin
AUpperS := S.ToUpper;
ANewStipulation := 'upper(Value) ' +
IfThen(ALike, 'like ' + QuotedStr(AUpperS + '%'),
'= ' + QuotedStr(AUpperS));
AStipulation := IfThen(AStipulation.IsEmpty, '', ' or ');
AStipulation := AStipulation + ANewStipulation;
end;
// Делаем замену в первоначальном SQL запросе
FDQuery.SQL.Text := ReplaceInSQL(SQL, AStipulation, 0);
AStipulation := Format('ParentProductId is %s null',
[IfThen(AFamily, '', 'not')]);
FDQuery.SQL.Text := ReplaceInSQL(FDQuery.SQL.Text, AStipulation, 1);
end;
function TQuerySearchFamilyOrComp.SearchFamily(const AFamily: String): Integer;
begin
Result := SearchEx(AFamily, False, True);
end;
function TQuerySearchFamilyOrComp.SearchComponent(const AComponent: String):
Integer;
begin
Result := SearchEx(AComponent, False, False);
end;
function TQuerySearchFamilyOrComp.SearchEx(const AValue: String; ALike,
AFamily: Boolean): Integer;
begin
Assert(not AValue.IsEmpty);
PrepareSearchByValue([AValue], ALike, AFamily);
FDQuery.Close;
FDQuery.Open;
Result := FDQuery.RecordCount;
end;
end.
|
unit Vigilante.Configuracao;
interface
type
{$M+}
IConfiguracao = interface(IInterface)
['{DA70BB30-F87D-4E5E-BFEA-24BD01F871E5}']
function GetSimularBuild: boolean;
function GetAtualizacoesAutomaticas: boolean;
function GetAtualizacoesIntervalo: integer;
procedure SetSimularBuild(const Value: boolean);
procedure SetAtualizacoesAutomaticas(const Value: boolean);
procedure SetAtualizacoesIntervalo(const Value: integer);
procedure CarregarConfiguracoes;
procedure PersistirConfiguracoes;
property SimularBuild: boolean read GetSimularBuild write SetSimularBuild;
property AtualizacoesAutomaticas: boolean read GetAtualizacoesAutomaticas write SetAtualizacoesAutomaticas;
property AtualizacoesIntervalo: integer read GetAtualizacoesIntervalo write SetAtualizacoesIntervalo;
end;
function PegarConfiguracoes: IConfiguracao;
procedure DefinirConfiguracoes(const AConfiguracao: IConfiguracao);
implementation
var
_Configuracoes: IConfiguracao;
function PegarConfiguracoes: IConfiguracao;
begin
Result := _Configuracoes;
end;
procedure DefinirConfiguracoes(const AConfiguracao: IConfiguracao);
begin
_Configuracoes := AConfiguracao;
end;
end.
|
unit Billiards.Member;
interface
uses
Classes,
Graphics,
JPEG;
type
TBilliardMember = class
private
fBirthDate: string;
fDocumentType: string;
fStreet: string;
fValidFrom: string;
fLastName: string;
fCardNumber: string;
fZipCode: string;
fMunicipality: string;
fNickName: string;
fId: integer;
fNationality: string;
fNationalNumber: string;
fChipNumber: string;
fGender: string;
fCountry: string;
fFirstName: string;
fBirthPlace: string;
fValidUntil: string;
fPicture: TJpegImage;
function GetFullName: string;
function GetListName: string;
function GetPicture: TJpegImage;
procedure SetPicture(const Value: TJpegImage);
public
procedure Clear;
function Exist: boolean;
procedure Retrieve(aID: integer);
procedure Update;
procedure Store;
procedure StorePicture;
function ToString: string; override;
procedure LoadPictureFromStream(aStream: TStream);
property ID: integer read fId write fId;
property LastName: string read fLastName write fLastName;
property FirstName: string read fFirstName write fFirstName;
property FullName: string read GetFullName;
property NickName: string read fNickName write fNickName;
property ListName: string read GetListName;
property BirthDate: string read fBirthDate write fBirthDate;
property BirthPlace: string read fBirthPlace write fBirthPlace;
property NationalNumber: string read fNationalNumber write fNationalNumber;
property Gender: string read fGender write fGender;
property Nationality: string read fNationality write fNationality;
property Municipality: string read fMunicipality write fMunicipality;
property CardNumber: string read fCardNumber write fCardNumber;
property ValidFrom: string read fValidFrom write fValidFrom;
property ValidUntil: string read fValidUntil write fValidUntil;
property DocumentType: string read fDocumentType write fDocumentType;
property ChipNumber: string read fChipNumber write fChipNumber;
property Street: string read fStreet write fStreet;
property ZipCode: string read fZipCode write fZipCode;
property Country: string read fCountry write fCountry;
property Picture: TJpegImage read GetPicture write SetPicture;
end;
implementation
uses
SysUtils,
Dialogs,
DB,
IBDatabase,
IBQuery,
IBCustomDataSet,
Billiards.DataModule;
{ TBilliardMember }
procedure TBilliardMember.Clear;
begin
ID := 0;
LastName := '';
FirstName := '';
NickName := '';
BirthDate := '';
BirthPlace := '';
NationalNumber := '';
Gender := '';
Nationality := '';
Municipality := '';
CardNumber := '';
ValidFrom := '';
ValidUntil := '';
DocumentType := '';
ChipNumber := '';
Street := '';
ZipCode := '';
Country := '';
if Assigned(fPicture) then
FreeAndNil(fPicture);
end;
procedure TBilliardMember.Retrieve(aID: integer);
begin
if fId <> aID then
fId := aID;
Update;
end;
function TBilliardMember.Exist: boolean;
var
SL: TStringList;
begin
SL := TStringList.Create;
try
SL.Add('select ID');
SL.Add(' from MEMBERS');
SL.Add(' where LASTNAME = :lastname ');
SL.Add(' and FIRSTNAME = :firstname');
BilliardDataModule.sqlQuery.SQL.Assign(SL);
finally
SL.Free;
end;
BilliardDataModule.sqlQuery.ParamByName('lastname').AsString := fLastName;
BilliardDataModule.sqlQuery.ParamByName('firstname').AsString := fFirstName;
BilliardDataModule.sqlQuery.Open;
Result := (BilliardDataModule.sqlQuery.RecordCount > 0);
if Result then
begin
BilliardDataModule.sqlQuery.First;
fId := BilliardDataModule.sqlQuery.FieldByName('ID').AsInteger;
end;
BilliardDataModule.sqlQuery.Close;
end;
function TBilliardMember.GetFullName: string;
begin
Result := fLastName;
if fFirstName <> '' then
Result := Result + ', ' + fFirstName;
end;
function TBilliardMember.GetListName: string;
begin
Result := FullName;
if fNickName <> '' then
Result := Result + '(' + fNickName + ')';
end;
function TBilliardMember.GetPicture: TJpegImage;
begin
Result := fPicture;
end;
procedure TBilliardMember.LoadPictureFromStream(aStream: TStream);
begin
if not Assigned(fPicture) then
fPicture := TJpegImage.Create;
aStream.Position := 0;
fPicture.LoadFromStream(aStream);
end;
procedure TBilliardMember.SetPicture(const Value: TJpegImage);
begin
if not Assigned(fPicture) then
fPicture := TJpegImage.Create;
fPicture.Assign(Value);
end;
procedure TBilliardMember.Store;
var
SL: TStringList;
bExist: boolean;
begin
SL := TStringList.Create;
try
bExist := Exist;
if bExist then
begin
SL.Add('UPDATE MEMBERS SET');
SL.Add('LASTNAME = :LASTNAME,');
SL.Add('FIRSTNAME = :FIRSTNAME,');
SL.Add('GENDER = :GENDER,');
SL.Add('BIRTHDATE = :BIRTHDATE,');
SL.Add('BIRTHPLACE = :BIRTHPLACE,');
SL.Add('NATIONALITY = :NATIONALITY,');
SL.Add('NATIONALNUMBER = :NATIONALNUMBER,');
SL.Add('STREET = :STREET,');
SL.Add('ZIPCODE = :ZIPCODE,');
SL.Add('MUNICIPALITY = :MUNICIPALITY,');
SL.Add('COUNTRY = :COUNTRY,');
SL.Add('CHIPNUMBER = :CHIPNUMBER,');
SL.Add('CARDNUMBER = :CARDNUMBER,');
SL.Add('DOCUMENTTYPE = :DOCUMENTTYPE,');
SL.Add('VALIDFROM = :VALIDFROM,');
SL.Add('VALIDUNTIL = :VALIDUNTIL,');
SL.Add('WHERE ID = :ID');
end
else
begin
SL.Add('INSERT INTO MEMBERS ');
SL.Add('(LASTNAME,');
SL.Add(' FIRSTNAME,');
SL.Add(' GENDER,');
SL.Add(' BIRTHDATE,');
SL.Add(' BIRTHPLACE,');
SL.Add(' NATIONALITY,');
SL.Add(' NATIONALNUMBER,');
SL.Add(' STREET,');
SL.Add(' ZIPCODE,');
SL.Add(' MUNICIPALITY,');
SL.Add(' COUNTRY,');
SL.Add(' CHIPNUMBER,');
SL.Add(' CARDNUMBER,');
SL.Add(' DOCUMENTTYPE,');
SL.Add(' VALIDFROM,');
SL.Add(' VALIDUNTIL)');
SL.Add('values (:LASTNAME,');
SL.Add(' :FIRSTNAME,');
SL.Add(' :GENDER,');
SL.Add(' :BIRTHDATE,');
SL.Add(' :BIRTHPLACE,');
SL.Add(' :NATIONALITY,');
SL.Add(' :NATIONALNUMBER,');
SL.Add(' :STREET,');
SL.Add(' :ZIPCODE,');
SL.Add(' :MUNICIPALITY,');
SL.Add(' :COUNTRY,');
SL.Add(' :CHIPNUMBER,');
SL.Add(' :CARDNUMBER,');
SL.Add(' :DOCUMENTTYPE,');
SL.Add(' :VALIDFROM,');
SL.Add(' :VALIDUNTIL)');
end;
BilliardDataModule.sqlCommand.SQL.Assign(SL);
finally
SL.Free;
end;
BilliardDataModule.sqlCommand.ParamByName('LASTNAME').AsString := fLastName;
BilliardDataModule.sqlCommand.ParamByName('FIRSTNAME').AsString := fFirstName;
BilliardDataModule.sqlCommand.ParamByName('GENDER').AsString := fGender;
BilliardDataModule.sqlCommand.ParamByName('BIRTHDATE').AsString := fBirthDate;
BilliardDataModule.sqlCommand.ParamByName('BIRTHPLACE').AsString := fBirthPlace;
BilliardDataModule.sqlCommand.ParamByName('NATIONALITY').AsString := fNationality;
BilliardDataModule.sqlCommand.ParamByName('NATIONALNUMBER').AsString := fNationalNumber;
BilliardDataModule.sqlCommand.ParamByName('STREET').AsString := fStreet;
BilliardDataModule.sqlCommand.ParamByName('ZIPCODE').AsString := fZipCode;
BilliardDataModule.sqlCommand.ParamByName('MUNICIPALITY').AsString := fMunicipality;
BilliardDataModule.sqlCommand.ParamByName('COUNTRY').AsString := fCountry;
BilliardDataModule.sqlCommand.ParamByName('CHIPNUMBER').AsString := fChipNumber;
BilliardDataModule.sqlCommand.ParamByName('CARDNUMBER').AsString := fCardNumber;
BilliardDataModule.sqlCommand.ParamByName('DOCUMENTTYPE').AsString := fDocumentType;
BilliardDataModule.sqlCommand.ParamByName('VALIDFROM').AsString := fValidFrom;
BilliardDataModule.sqlCommand.ParamByName('VALIDUNTIL').AsString := fValidUntil;
if bExist then
BilliardDataModule.sqlCommand.ParamByName('ID').AsInteger := fId;
BilliardDataModule.sqlCommand.ExecQuery;
ShowMessage(IntToStr(BilliardDataModule.sqlCommand.RowsAffected) + ' row s affected.');
BilliardDataModule.BilliardDBTransaction.Commit;
bExist := Exist;
if Assigned(fPicture) then
StorePicture;
end;
procedure TBilliardMember.StorePicture;
var
stream: TStream;
SL: TStringList;
begin
stream := TMemoryStream.Create;
try
stream.Position := 0;
fPicture.SaveToStream(stream);
stream.Position := 0;
SL := TStringList.Create;
try
SL.Add('UPDATE MEMBERS SET');
SL.Add('PICTURE = :PICTURE');
SL.Add('WHERE ID = :ID');
BilliardDataModule.sqlCommand.SQL.Assign(SL);
finally
SL.Free;
end;
BilliardDataModule.sqlCommand.ParamByName('PICTURE').LoadFromStream(stream);
BilliardDataModule.sqlCommand.ParamByName('ID').AsInteger := fId;
BilliardDataModule.sqlCommand.ExecQuery;
ShowMessage(IntToStr(BilliardDataModule.sqlCommand.RowsAffected) + ' row s affected.');
BilliardDataModule.BilliardDBTransaction.Commit;
finally
FreeAndNil(stream);
end;
end;
function TBilliardMember.ToString: string;
begin
Result := '"Member": { ';
Result := Result + Format('"ID": "%d", ', [fId]);
Result := Result + Format(#13#10'"LastName": "%s", ', [fLastName]);
Result := Result + Format(#13#10'"FirstName": "%s", ', [fFirstName]);
Result := Result + Format(#13#10'"NickName": "%s", ', [fNickName]);
Result := Result + Format(#13#10'"BirthDate": "%s", ', [fBirthDate]);
Result := Result + Format(#13#10'"BirthPlace": "%s", ', [fBirthPlace]);
Result := Result + Format(#13#10'"NationalNumber": "%s", ', [fNationalNumber]);
Result := Result + Format(#13#10'"Gender": "%s", ', [fGender]);
Result := Result + Format(#13#10'"Nationality": "%s", ', [fNationality]);
Result := Result + Format(#13#10'"Municipality": "%s", ', [fMunicipality]);
Result := Result + Format(#13#10'"CardNumber": "%s", ', [fCardNumber]);
Result := Result + Format(#13#10'"ValidFrom": "%s", ', [fValidFrom]);
Result := Result + Format(#13#10'"ValidUntil": "%s", ', [fValidUntil]);
Result := Result + Format(#13#10'"DocumentType": "%s", ', [fDocumentType]);
Result := Result + Format(#13#10'"ChipNumber": "%s", ', [fChipNumber]);
Result := Result + Format(#13#10'"Street": "%s", ', [fStreet]);
Result := Result + Format(#13#10'"Zip": "%s", ', [fZipCode]);
Result := Result + Format(#13#10'"Country": "%s" ', [fCountry]);
Result := Result + #13#10'}';
end;
procedure TBilliardMember.Update;
var
SL: TStringList;
stream: TMemoryStream;
begin
SL := TStringList.Create;
try
SL.Add('SELECT *');
SL.Add(' FROM MEMBERS');
SL.Add(' WHERE ID = :id');
BilliardDataModule.sqlQuery.SQL.Assign(SL);
finally
SL.Free;
end;
BilliardDataModule.sqlQuery.ParamByName('id').AsInteger := fId;
BilliardDataModule.sqlQuery.Open;
try
if BilliardDataModule.sqlQuery.RecordCount = 1 then
begin
ID := BilliardDataModule.sqlQuery.FieldByName('ID').AsInteger;
LastName := BilliardDataModule.sqlQuery.FieldByName('LASTNAME').AsString;
FirstName := BilliardDataModule.sqlQuery.FieldByName('FIRSTNAME').AsString;
NickName := BilliardDataModule.sqlQuery.FieldByName('NICKNAME').AsString;
BirthDate := BilliardDataModule.sqlQuery.FieldByName('BIRTHDATE').AsString;
BirthPlace := BilliardDataModule.sqlQuery.FieldByName('BIRTHPLACE').AsString;
NationalNumber := BilliardDataModule.sqlQuery.FieldByName('NATIONALNUMBER').AsString;
Gender := BilliardDataModule.sqlQuery.FieldByName('GENDER').AsString;
Nationality := BilliardDataModule.sqlQuery.FieldByName('NATIONALITY').AsString;
Municipality := BilliardDataModule.sqlQuery.FieldByName('MUNICIPALITY').AsString;
CardNumber := BilliardDataModule.sqlQuery.FieldByName('CARDNUMBER').AsString;
ValidFrom := BilliardDataModule.sqlQuery.FieldByName('VALIDFROM').AsString;
ValidUntil := BilliardDataModule.sqlQuery.FieldByName('VALIDUNTIL').AsString;
DocumentType := BilliardDataModule.sqlQuery.FieldByName('DOCUMENTTYPE').AsString;
ChipNumber := BilliardDataModule.sqlQuery.FieldByName('CHIPNUMBER').AsString;
Street := BilliardDataModule.sqlQuery.FieldByName('STREET').AsString;
ZipCode := BilliardDataModule.sqlQuery.FieldByName('ZIPCODE').AsString;
Country := BilliardDataModule.sqlQuery.FieldByName('COUNTRY').AsString;
stream := TMemoryStream.Create;
try
stream.Position := 0;
TBlobField(BilliardDataModule.sqlQuery.FieldByName('PICTURE')).SaveToStream(stream);
if stream.Position > 0 then
begin
if not Assigned(fPicture) then
fPicture := TJpegImage.Create;
stream.Position := 0;
fPicture.LoadFromStream(stream);
end;
finally
stream.Free;
end;
end;
finally
BilliardDataModule.sqlQuery.Close;
end;
end;
end.
|
(******************************************************************************)
(* TdfsEnhListView component demo. *)
(* This demo illustrates the following features of the TdfsEnhListView *)
(* component: *)
(* + Automatic column sorting of string, date and numeric values toggling *)
(* between ascending and descending order. *)
(* + Sort column and direction indicator in column header with NO code. *)
(* + Owner draw event that doesn't actually have to do any drawing in order *)
(* to change the appearance. You have control of the canvas, so you can *)
(* simply make changes to it to affect the font in the default drawing. *)
(* + Owner drawn header that modifies the appearance without actually doing *)
(* all of the drawing. Illustrates how to have images in the column *)
(* headers without using the COMCTL32.DLL update! *)
(* + Automatic saving and restoring of the column widths between sessions. *)
(******************************************************************************)
{$I DFS.INC}
unit EnhMain;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
{$IFDEF DFS_COMPILER_4_UP}
ImgList,
{$ENDIF}
ComCtrls, EnhListView, StdCtrls, ExtCtrls;
type
TForm1 = class(TForm)
AnEnhListView: TdfsEnhListView;
ColumnImageList: TImageList;
procedure FormCreate(Sender: TObject);
procedure AnEnhListViewDrawItem(Control: TWinControl;
var Canvas: TCanvas; Index: Integer; Rect: TRect;
State: TOwnerDrawState; var DefaultDrawing, FullRowSelect: Boolean);
procedure AnEnhListViewDrawSubItem(Control: TWinControl;
var Canvas: TCanvas; Index, SubItem: Integer; Rect: TRect;
State: TOwnerDrawState; var DefaultDrawing: Boolean);
procedure AnEnhListViewDrawHeader(Control: TWinControl;
var Canvas: TCanvas; Index: Integer; var Rect: TRect; Selected: Boolean;
var DefaultDrawing: Boolean);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.FormCreate(Sender: TObject);
procedure AddDemoLine(ACaption: string; ANum: integer; ADate: TDateTime);
begin
with AnEnhListView.Items.Add do
begin
Caption := ACaption;
ImageIndex := GetTickCount mod 3; { Pick a semi-random image }
SubItems.Add(IntToStr(ANum));
SubItems.Add(DateToStr(ADate));
end;
end;
begin
// Note that I am NOT using ELV.Items.BeginUpdate. ELV.BeginUpdate does the
// same thing, but it also prevents resorting as well. Otherwise, the list
// would get resorted each time an item was added. Very inefficient.
AnEnhListView.BeginUpdate;
try
AddDemoLine('Some text', 391, Now);
AddDemoLine('More text', 1931, Now-2);
AddDemoLine('Other stuff', 175, Now+10);
AddDemoLine('Enhancing', 1, Now-5);
AddDemoLine('isn''t', 2865, Now+4);
AddDemoLine('it?', -9, Now);
finally
AnEnhListView.EndUpdate;
end;
end;
procedure TForm1.AnEnhListViewDrawItem(Control: TWinControl;
var Canvas: TCanvas; Index: Integer; Rect: TRect; State: TOwnerDrawState;
var DefaultDrawing, FullRowSelect: Boolean);
begin
DefaultDrawing := TRUE; // let the componet draw it for us.
FullRowSelect := TRUE; // I like full row selection
// Make the selected item bold italics just to show how easy it is
if (AnEnhListView.Selected <> NIL) and
(AnEnhListView.Selected.Index = Index) then
Canvas.Font.Style := Canvas.Font.Style + [fsBold, fsItalic];
end;
procedure TForm1.AnEnhListViewDrawSubItem(Control: TWinControl;
var Canvas: TCanvas; Index, SubItem: Integer; Rect: TRect;
State: TOwnerDrawState; var DefaultDrawing: Boolean);
begin
DefaultDrawing := TRUE;
{ Draw the numbers in red if not selected }
if (SubItem = 0) and not (odSelected in State) then
Canvas.Font.Color := clRed;
end;
procedure TForm1.AnEnhListViewDrawHeader(Control: TWinControl;
var Canvas: TCanvas; Index: Integer; var Rect: TRect; Selected: Boolean;
var DefaultDrawing: Boolean);
var
Offset: integer;
begin
// Draw an image in the header
Offset := (Rect.Bottom - Rect.Top - ColumnImageList.Height) div 2;
ColumnImageList.Draw(Canvas, Rect.Left + 4, Rect.Top + Offset, Index);
inc(Rect.Left, ColumnImageList.Width + 4);
DefaultDrawing := TRUE;
Canvas.Font.Style := Canvas.Font.Style + [fsItalic];
if Selected then
Canvas.Font.Color := clRed;
end;
end.
|
unit Scanner;
{
Author: Wanderlan Santos dos Anjos, wanderlan.anjos@gmail.com
Date: jan-2010
License: <extlink http://www.opensource.org/licenses/bsd-license.php>BSD</extlink>
}
interface
uses
Classes, Token;
const
MaxIncludeLevel = 32;
Version = '2012.5 Alpha I semantics';
TargetCPU = 'x86_64'; // 'arm'; 'cellspu'; 'hexagon'; 'mips'; 'mipsel'; 'mips64'; 'mips64el'; 'msp430'; 'powerpc64'; 'powerpc';
// 'r600'; 'sparc'; 'sparcv9'; 'tce'; 'thumb'; 'i386'; 'xcore'; 'mblaze'; 'ptx32'; 'ptx64'; 'le32'; 'amdil';
TargetOS = 'win32'; // 'auroraux'; 'cygwin'; 'darwin'; 'dragonfly'; 'freebsd'; 'ios'; 'kfreebsd'; 'linux'; 'lv2'; 'macosx';
// 'mingw32'; 'netbsd'; 'openbsd'; 'solaris'; 'haiku'; 'minix'; 'rtems'; 'nacl'; 'cnk';
type
{$IFDEF UNICODE}
Char = AnsiChar;
{$ENDIF}
TSetChar = set of char;
TScanner = class
private
Arq : array[0..MaxIncludeLevel] of text;
FToken : TToken;
Include,
LenLine : integer;
FInitTime : TDateTime;
Macros : TStringList;
Line : AnsiString;
Buffer : array[1..8 * 1024] of byte;
FSourceName : array[0..MaxIncludeLevel] of ShortString;
FStartComment : string[10];
FEndComment : string[100];
Procedure GetCompilerInfo; // Compiler Info and Environment Variable
procedure SetDelphiMode;
function TokenIn(const S : AnsiString) : boolean; inline;
function GetFLineNumber : integer;
function GetFSourceName : AnsiString;
function TestIncludePaths : boolean;
procedure NextChar(C : TSetChar);
procedure FindEndComment(const StartComment, EndComment : AnsiString);
procedure SetFSourceName(const Value : AnsiString);
procedure DoDirective(DollarInc : integer);
procedure SkipBlank; inline;
procedure NextString;
procedure DoIf(Condition : boolean);
procedure CreateMacro;
procedure OpenInclude;
procedure SetFLineNumber(const Value : integer);
procedure EmitMessage;
procedure GotoEndComment;
protected
FEndSource, FPCMode, DoNextToken : boolean;
FLineNumber : array[0..MaxIncludeLevel] of integer;
FTotalLines, First, FErrors, FMaxErrors, Top, LastGoodTop, FAnt, LineComment, FSilentMode : integer;
LastLexeme, ErrorCode, NestedIf : ShortString;
IncludePath, FNotShow, ReservedWords : TStringList;
function CharToTokenKind(N : char) : TTokenKind;
function TokenKindToChar(T : TTokenKind) : char;
function StringToTokenKind(S : string; Default : TTokenKind = tkUndefined) : TTokenKind;
function GetNonTerminalName(N : char) : AnsiString;
procedure ScanChars(const Chars: array of TSetChar; const Tam : array of integer; Optional : boolean = false);
procedure NextToken(Skip : boolean = false);
procedure RecoverFromError(const Expected, Found : AnsiString); virtual;
procedure ChangeLanguageMode(FPC : boolean);
public
constructor Create(MaxErrors : integer = 10 ; Includes : AnsiString = ''; SilentMode : integer = 2 ;
LanguageMode : AnsiString = ''; NotShow : AnsiString = '');
destructor Destroy; override;
procedure MatchTerminal(KindExpected : TTokenKind); //inline;
procedure ShowMessage(Kind, Msg : ShortString);
procedure Error(const Msg : AnsiString); virtual;
procedure MatchToken(const TokenExpected : AnsiString); //inline;
property SourceName : AnsiString read GetFSourceName write SetFSourceName;
property LineNumber : integer read GetFLineNumber write SetFLineNumber;
property TotalLines : integer read FTotalLines;
property ColNumber : integer read First;
property Token : TToken read FToken write FToken;
property EndSource : boolean read FEndSource;
property Errors : integer read FErrors;
property InitTime : TDateTime read FInitTime;
property SilentMode : integer read FSilentMode;
end;
implementation
uses
SysUtils, StrUtils, IniFiles, Math, Grammar {$IFDEF UNICODE}, AnsiStrings{$ENDIF};
const
DelphiReservedWords = 'and.array.as.asm.automated.begin.case.class.const.constructor.destructor.dispinterface.div.do.downto.' +
'else.end.except.exports.file.finalization.finally.for.function.goto.if.implementation.in.inherited.initialization.inline.' +
'interface.is.label.library.mod.nil.not.object.of.or.out.packed.private.procedure.program.property.protected.public.' +
'published.raise.record.repeat.resourcestring.set.shl.shr.strict.then.threadvar.to.try.type.unit.until.uses.var.while.with.xor';
FPCReservedWords = '.operator';
ConditionalSymbols : AnsiString = '.llvm.ver2010.mswindows.win32.cpu386.conditionalexpressions.purepascal.';
constructor TScanner.Create(MaxErrors : integer = 10; Includes : AnsiString = ''; SilentMode : integer = 2;
LanguageMode : AnsiString = ''; NotShow : AnsiString = ''); begin
FInitTime := Now;
FMaxErrors := MaxErrors;
DecimalSeparator := '.';
ThousandSeparator := ',';
FSilentMode := SilentMode;
IncludePath := TStringList.Create;
IncludePath.Delimiter := ';';
IncludePath.StrictDelimiter := true;
IncludePath.DelimitedText := ';' + Includes;
FNotShow := TStringList.Create;
FNotShow.DelimitedText := NotShow;
ReservedWords := THashedStringList.Create;
ReservedWords.Delimiter := '.';
ReservedWords.CaseSensitive := false;
SetDelphiMode;
ChangeLanguageMode(pos('FPC', UpperCase(LanguageMode)) <> 0);
end;
destructor TScanner.Destroy;
var
Elapsed : TDateTime;
begin
Elapsed := Now - InitTime;
if Elapsed = 0 then Elapsed := 3E-9;
if FileExists(SourceName) then close(Arq[Include]);
writeln;
if Errors <> 0 then writeln(Errors, ' error(s).');
writeln(TotalLines, ' lines, ', IfThen(FormatDateTime('n', Elapsed) = '0', '', FormatDateTime('n ', Elapsed) + 'minute(s) and '),
FormatDateTime('s.z ', Elapsed), 'seconds, ', TotalLines/1000.0/(Elapsed*24*60*60):0:1, ' klps.');
inherited;
FToken.Free;
IncludePath.Free;
FNotShow.Free;
ReservedWords.Free;
FreeAndNil(Macros);
end;
procedure TScanner.ScanChars(const Chars : array of TSetChar; const Tam : array of integer; Optional : boolean = false);
var
I, T, Last : integer;
begin
FToken.Lexeme := '';
FToken.Kind := tkUndefined;
for I := 0 to high(Chars) do begin
Last := First;
T := 1;
while (Last <= LenLine) and (T <= Tam[I]) and (Line[Last] in Chars[I]) do begin
inc(Last);
inc(T);
end;
if Last > First then begin
FToken.Lexeme := FToken.Lexeme + copy(Line, First, Last - First);
First := Last;
end
else
if Optional then exit;
end;
end;
procedure TScanner.SetFLineNumber(const Value : integer); begin
FLineNumber[Include] := Value
end;
procedure TScanner.SetFSourceName(const Value : AnsiString); begin
if FErrors >= FMaxErrors then Abort;
if FileExists(SourceName) then close(Arq[Include]);
Include := 0;
LineNumber := 0;
LenLine := 0;
NestedIf := '';
FEndSource := false;
FSourceName[Include] := Value;
if FileExists(SourceName) then begin
if FSilentMode >= 2 then writeln(ExtractFileName(SourceName));
assign(Arq[Include], SourceName);
SetTextBuf(Arq[Include], Buffer);
reset(Arq[Include]);
First := 1;
FToken := TToken.Create;
FreeAndNil(Macros);
NextToken;
end
else begin
FEndSource := true;
Error('Source file "' + SourceName + '" not found');
Abort;
end;
end;
procedure TScanner.NextChar(C : TSetChar); begin
if (First < LenLine) and (Line[First + 1] in C) then begin
FToken.Lexeme := copy(Line, First, 2);
inc(First, 2);
end
else begin
FToken.Lexeme := Line[First];
inc(First);
end;
FToken.Kind := tkSpecialSymbol;
end;
procedure TScanner.DoIf(Condition : boolean); begin
if Condition then begin
NestedIf := NestedIf + 'T';
FStartComment := '$';
end
else begin
NestedIf := NestedIf + 'F';
FEndComment := 'ENDIF' + FEndComment;
end;
end;
procedure TScanner.GetCompilerInfo; begin
ScanChars([['A'..'Z', 'a'..'z', '_', '0'..'9']], [254]);
case AnsiIndexText(FToken.Lexeme, ['FILE', 'LINE', 'DATE', 'TIME', 'VERSION', 'FPCVERSION', 'TARGETOS', 'FPCTARGETOS',
'TARGETCPU', 'FPCTARGETCPU']) of
-1 : FToken.Lexeme := GetEnvironmentVariable(FToken.Lexeme);
0 : FToken.Lexeme := ExtractFileName(SourceName);
1 : FToken.Lexeme := IntToStr(LineNumber);
2 : FToken.Lexeme := FormatDateTime('ddddd', Date);
3 : FToken.Lexeme := FormatDateTime('tt', Now);
4,
5 : FToken.Lexeme := Version;
6,
7 : FToken.Lexeme := TargetOS;
8,
9 : FToken.Lexeme := TargetCPU;
end;
FToken.Kind := tkStringConstant;
end;
function TScanner.TestIncludePaths : boolean;
var
F : string;
I : integer;
begin
Result := false;
for I := 0 to IncludePath.Count-1 do begin
F := AnsiReplaceStr(IfThen(I = 0, ExtractFilePath(FSourceName[0]), IncludePath[I]) + trim(FToken.Lexeme), '*', ExtractFileName(SourceName));
Result := FileExists(F);
if Result then begin
FToken.Lexeme := F;
exit;
end;
end;
end;
procedure TScanner.OpenInclude; begin
if Line[First] in ['+', '-'] then exit;
First := FAnt;
SkipBlank;
if Line[First] = '%' then begin
inc(First);
GetCompilerInfo;
GotoEndComment;
Abort;
end
else begin
ScanChars([['!'..#255] - ['}']], [255]);
FToken.Lexeme := AnsiDequotedStr(trim(FToken.Lexeme), '''');
if FToken.Lexeme = '' then exit;
if TestIncludePaths then begin
if length(trim(copy(Line, First, 100))) > 1 then
ShowMessage('Warning', 'Text after $Include directive, in the same line, is lost, break the line please.');
GotoEndComment;
inc(Include);
assign(Arq[Include], FToken.Lexeme);
reset(Arq[Include]);
LineNumber := 0;
FSourceName[Include] := FToken.Lexeme;
if FSilentMode >= 2 then writeln('' : Include * 2, ExtractFileName(SourceName));
end
else
if FSilentMode >= 2 then Error('Include file "' + FToken.Lexeme + '" not found');
end;
end;
procedure TScanner.ShowMessage(Kind, Msg : ShortString);
function CanShowMessage : boolean;
var
I : integer;
begin
for I := 0 to FNotShow.Count - 1 do
if pos(FNotShow[I], Kind[1] + ErrorCode) = 1 then begin
Result := false;
exit;
end;
Result := true;
end;
begin
if length(ErrorCode) = 1 then ErrorCode := IntToStr(ord(ErrorCode[1]));
Kind := UpCase(Kind[1]) + LowerCase(copy(Kind, 2, 10));
if CanShowMessage and ((FSilentMode >= 2) or (Kind = 'Error') or (Kind = 'Fatal')) then begin
writeln('[' + Kind + '] ' + ExtractFileName(SourceName) + '('+ IntToStr(LineNumber) + ', ' + IntToStr(ColNumber - Length(Token.Lexeme)) + '): ' +
Kind[1] + ErrorCode + ' ' + Msg);
if (FSilentMode >= 1) and (Line <> '') then writeln(Line, ^J, '^' : ColNumber - Length(Token.Lexeme));
end;
if Kind = 'Fatal' then FEndSource := true;
end;
procedure TScanner.EmitMessage;
var
L : AnsiString;
begin
L := FToken.Lexeme;
SkipBlank;
ScanChars([[#1..#255]-['}']], [100]);
case AnsiIndexText(L, ['HINT', 'WARN', 'ERROR', 'FATAL']) of
0, 1 : ShowMessage(L, FToken.Lexeme);
2 : Error(FToken.Lexeme);
3 : ShowMessage('Fatal', FToken.Lexeme);
else
First := FAnt;
SkipBlank;
ScanChars([[#1..#255]-['}']], [100]);
ShowMessage('Hint', FToken.Lexeme);
end;
end;
procedure TScanner.DoDirective(DollarInc : integer);
var
I : integer;
L : AnsiString;
begin
First := DollarInc + 1;
if Line[First] in ['A'..'Z', '_', 'a'..'z'] then begin
ScanChars([['A'..'Z', 'a'..'z', '_', '0'..'9']], [255]);
L := FToken.Lexeme;
FAnt := First;
SkipBlank;
ScanChars([['A'..'Z', 'a'..'z', '_', '0'..'9']], [255]);
case AnsiIndexText(L, ['DEFINE', 'UNDEF', 'IFDEF', 'IFNDEF', 'IF', 'IFOPT', 'ENDIF', 'IFEND', 'ELSE', 'ELSEIF', 'MODE',
'I', 'INCLUDE', 'MESSAGE', 'MODESWITCH']) of
0 : begin
if not TokenIn(ConditionalSymbols) then ConditionalSymbols := ConditionalSymbols + LowerCase(FToken.Lexeme) + '.';
CreateMacro;
end;
1 : begin
I := pos('.' + LowerCase(FToken.Lexeme) + '.', ConditionalSymbols);
if I <> 0 then delete(ConditionalSymbols, I, length(FToken.Lexeme) + 1);
end;
2 : DoIf(TokenIn(ConditionalSymbols));
3 : DoIf(not TokenIn(ConditionalSymbols));
4, 9 : if AnsiIndexText(FToken.Lexeme, ['DEFINED', 'DECLARED']) <> -1 then begin
ScanChars([['(']], [1]);
ScanChars([['A'..'Z', 'a'..'z', '_', '0'..'9']], [255]);
DoIf(TokenIn(ConditionalSymbols));
end;
5 : DoIf(false);
6, 7 : if NestedIf <> '' then SetLength(NestedIf, length(NestedIf)-1);
8 : DoIf(not((NestedIf = '') or (NestedIf[length(NestedIf)] = 'T')));
10 : ChangeLanguageMode(pos('FPC', UpperCase(FToken.Lexeme)) <> 0);
11, 12 : OpenInclude;
13 : EmitMessage;
14 : ShowMessage('Fatal', 'Invalid directive "' + L + ' ' + FToken.Lexeme + '"');
else
GotoEndComment;
exit;
end;
FindEndComment(FStartComment, FEndComment);
end
else begin
Error('Invalid compiler directive "' + Line[First] + '"');
inc(First);
end;
end;
procedure TScanner.GotoEndComment;
var
P : integer;
begin
P := PosEx(FEndComment, UpperCase(Line), First);
if P <> 0 then begin // End comment in same line
First := P + length(FEndComment);
if length(FEndComment) <= 2 then FEndComment := '';
end
else
First := LenLine + 1;
end;
procedure TScanner.FindEndComment(const StartComment, EndComment : AnsiString);
procedure DoEndIf; begin
FEndComment := copy(FEndComment, 6, 100);
if NestedIf <> '' then SetLength(NestedIf, length(NestedIf)-1);
dec(First, 5);
end;
var
P : integer;
begin
if FEndComment = '' then LineComment := LineNumber;
FStartComment := StartComment;
FEndComment := EndComment;
P := PosEx(FStartComment + '$', Line, First);
if ((P - First) > 2) and (EndComment = '}') then P := 0;
if (P <> 0) and ((NestedIf = '') or (NestedIf[length(NestedIf)] = 'T')) then
DoDirective(P + length(FStartComment))
else begin
while (P <> 0) and ((NestedIf <> '') and (NestedIf[length(NestedIf)] = 'F')) do begin
First := P + length(FStartComment) + 1;
if Line[First] in ['A'..'Z', '_', 'a'..'z'] then begin
ScanChars([['A'..'Z', 'a'..'z', '_', '0'..'9']], [255]);
case AnsiIndexText(FToken.Lexeme, ['IFDEF', 'IFNDEF', 'IFOPT', 'IF', 'ENDIF', 'IFEND', 'ELSE', 'ELSEIF']) of
0..3 : begin DoIf(false); exit; end;
4..5 : DoEndIf;
6, 7 : if (NestedIf = 'F') or (NestedIf[length(NestedIf)-1] = 'T') then DoEndIf;
end;
end;
P := PosEx(FStartComment + '$', Line, First);
end;
GotoEndComment;
end;
end;
procedure TScanner.SkipBlank; begin
while (First <= LenLine) and (Line[First] in [' ', #9]) do inc(First);
end;
function TScanner.TokenIn(const S : AnsiString) : boolean; begin
Result := pos('.' + LowerCase(FToken.Lexeme) + '.', S) <> 0;
end;
procedure TScanner.NextString;
var
Str : AnsiString;
begin
Str := '';
repeat
if Line[First] <> '#' then begin
inc(First);
repeat
ScanChars([[#0..#255] - ['''']], [5000]);
Str := Str + FToken.Lexeme;
if (First < LenLine) and (Line[First + 1] = '''') then begin
Str := Str + '''';
inc(First, 2);
end;
until (First >= LenLine) or (Line[First] = '''');
inc(First);
end;
repeat
ScanChars([['^'], ['@'..'Z']], [1, 1], true);
case length(FToken.Lexeme) of
1 : begin
FToken.Kind := tkSpecialSymbol;
exit;
end;
2 : Str := Str + char(byte(FToken.Lexeme[2]) - ord('@'))
end;
until FToken.Lexeme = '';
repeat
ScanChars([['#'], ['0'..'9']], [1, 3], true);
case length(FToken.Lexeme) of
1 :
if Line[First] = '$' then begin
ScanChars([['$'], ['0'..'9', 'A'..'F', 'a'..'f']], [1, 4]);
Str := Str + char(StrToIntDef(FToken.Lexeme, 0));
end
else begin
FToken.Kind := tkSpecialSymbol;
exit;
end;
2..3 : Str := Str + char(StrToIntDef(copy(FToken.Lexeme, 2, 3), 0));
4..5 : Str := Str + widechar(StrToIntDef(copy(FToken.Lexeme, 2, 5), 0));
end;
until FToken.Lexeme = '';
until (First >= length(Line)) or (Line[First] <> '''');
FToken.Lexeme := Str;
if length(FToken.Lexeme) = 1 then
FToken.Kind := tkCharConstant
else
FToken.Kind := tkStringConstant;
end;
procedure TScanner.NextToken(Skip : boolean = false);
var
Str : AnsiString;
I : integer;
begin
DoNextToken := false;
LastLexeme := FToken.Lexeme;
while not FEndSource do begin
while First > LenLine do begin
readln(Arq[Include], Line);
LenLine := length(Line);
if EOF(Arq[Include]) and ((LenLine = 0) or (Line = ^Z)) then begin
if FEndComment <> '' then
Error('Unterminated ' + IfThen(pos('ENDIF', FEndComment) <> 0, 'compiler directive', 'comment') + ' started on line ' + IntToStr(LineComment));
FEndComment := '';
if Include > 0 then begin
close(Arq[Include]);
dec(Include);
First := LenLine + 1;
continue;
end
else begin
FEndSource := true;
FToken.Lexeme := 'End of Source';
exit;
end;
end;
LineNumber := LineNumber + 1;
inc(FTotalLines);
First := 1;
if (FEndComment = '') and (Macros <> nil) and (LenLine <> 0) and ((NestedIf = '') or (NestedIf[length(NestedIf)] = 'T')) then
for I := 0 to Macros.Count - 1 do // Replace macros
Line := AnsiReplaceStr(Line, Macros.Names[I], Macros.ValueFromIndex[I]);
end;
// End comment across many lines
if FEndComment <> '' then begin
FindEndComment(FStartComment, FEndComment);
continue;
end;
case Line[First] of
' ', #9 : SkipBlank;
'A'..'Z', 'a'..'z', '_', '&' : begin // Identifiers
ScanChars([['A'..'Z', 'a'..'z', '_', '&', '0'..'9'], ['A'..'Z', 'a'..'z', '_', '0'..'9']], [1, 254]);
if length(FToken.Lexeme) = 1 then
FToken.Kind := tkIdentifier
else
if ReservedWords.IndexOf({$IFDEF FPC}LowerCase{$ENDIF}(FToken.Lexeme)) <> -1 then
FToken.Kind := tkReservedWord
else
if (FToken.Lexeme[1] = '&') and (FToken.Lexeme[2] in ['0'..'7']) then begin // Octal
FToken.Kind := tkIntegerConstant;
FToken.IntegerValue := 0;
for I := length(FToken.Lexeme) downto 2 do
inc(FToken.IntegerValue, trunc((ord(FToken.Lexeme[I]) - 48) * Power(8, length(FToken.Lexeme) - I)));
end
else begin
FToken.Kind := tkIdentifier;
if FPCMode and TokenIn('.generic.specialize.') then NextToken;
end;
exit;
end;
';', ',', '=', ')', '[', ']', '@' : begin
FToken.Lexeme := Line[First];
FToken.Kind := tkSpecialSymbol;
inc(First);
exit;
end;
'+', '-' : begin NextChar(['=']); exit; end;
'^' : begin
Str := '';
FAnt := First;
repeat
ScanChars([['^'], ['@'..'Z', 'a'..'z']], [1, 2], true);
if length(FToken.Lexeme) = 2 then
Str := Str + char(byte(FToken.Lexeme[2]) - ord('@'));
until length(FToken.Lexeme) <> 2;
FToken.Lexeme := Str;
if ErrorCode >= Generics[2] then FToken.Lexeme := '';
case length(FToken.Lexeme) of
0 : begin
First := FAnt + 1;
FToken.Lexeme := Line[First-1];
FToken.Kind := tkSpecialSymbol;
end;
1 : FToken.Kind := tkCharConstant
else
FToken.Kind := tkStringConstant;
end;
exit;
end;
'''', '#': begin NextString; exit; end; // strings
'0'..'9' : begin // Numbers
ScanChars([['0'..'9'], ['.', 'E', 'e']], [28, 1], true);
Str := FToken.Lexeme;
case Str[length(Str)] of
'.' : begin
ScanChars([['0'..'9'], ['E', 'e'], ['+', '-'], ['0'..'9']], [27, 1, 1, 4], true);
Str := Str + UpperCase(FToken.Lexeme);
FToken.Lexeme := '';
if upcase(Str[length(Str)]) = 'E' then ScanChars([['0'..'9']], [4]);
end;
'E', 'e' : begin
ScanChars([['+', '-'], ['0'..'9']], [1, 4]);
Str := Str + FToken.Lexeme;
FToken.Lexeme := '';
end;
else
FToken.Lexeme := '';
end;
FToken.Lexeme := Str + UpperCase(FToken.Lexeme);
if FToken.Lexeme[length(FToken.Lexeme)] in ['.', 'E', '+', '-'] then begin
dec(First);
SetLength(FToken.Lexeme, length(FToken.Lexeme)-1);
end;
if (pos('.', FToken.Lexeme) <> 0) or (pos('E', UpperCase(FToken.Lexeme)) <> 0) then
FToken.Kind := tkRealConstant
else
if length(FToken.Lexeme) > 18 then
FToken.Kind := tkRealConstant
else
FToken.Kind := tkIntegerConstant;
if FToken.Kind = tkRealConstant then
FToken.RealValue := StrToFloat(FToken.Lexeme)
else
FToken.IntegerValue := StrToInt64(FToken.Lexeme);
exit;
end;
'(' :
if (LenLine > First) and (Line[First + 1] = '*') then // Comment Style (*
FindEndComment('(*', '*)')
else begin
FToken.Lexeme := '(';
FToken.Kind := tkSpecialSymbol;
inc(First);
exit
end;
'/' :
if (LenLine > First) and (Line[First + 1] = '/') then // Comment Style //
First := MAXINT
else begin
NextChar(['=']);
exit
end;
'{' :
try
FindEndComment('{', '}');
except
on EAbort do exit;
end;
'.' : begin NextChar(['.']); exit; end;
'*' : begin NextChar(['*', '=']); exit; end;
'>',
':' : begin NextChar(['=']); exit; end;
'<' : begin NextChar(['=', '>']); exit; end;
'$' : begin // Hexadecimal
ScanChars([['$'], ['0'..'9', 'A'..'F', 'a'..'f']], [1, 16]);
FToken.Kind := tkIntegerConstant;
FToken.IntegerValue := StrToInt64(FToken.Lexeme);
exit;
end;
'%' : begin // Binary and Compiler Info
ScanChars([['%'], ['0', '1']], [1, 32]);
if length(FToken.Lexeme) > 1 then begin
FToken.Kind := tkIntegerConstant;
FToken.IntegerValue := 0;
for I := length(FToken.Lexeme) downto 2 do
if FToken.Lexeme[I] = '1' then
inc(FToken.IntegerValue, trunc(Power(2, length(FToken.Lexeme) - I)));
end
else
GetCompilerInfo;
exit;
end;
else
inc(First);
if not EOF(Arq[Include]) and not Skip then begin
Token.Lexeme := Line[First-1];
Error('Invalid character "' + Line[First-1] + '" ($' + IntToHex(ord(Line[First-1]), 4) + ')');
end;
end;
end;
end;
procedure TScanner.Error(const Msg : AnsiString);
const
LastColNumber : integer = 0;
LastLineNumber : integer = 0;
LastSourceName : AnsiString = '';
LastError : char = #0;
begin
if ((LastColNumber = ColNumber) or (LastError = ErrorCode[1])) and
(LastLineNumber = LineNumber) and (LastSourceName = SourceName) then
NextToken // Prevents locks in the same error
else begin
ShowMessage('Error', Msg);
inc(FErrors);
if FErrors >= FMaxErrors then FEndSource := true;
LastColNumber := ColNumber;
LastLineNumber := LineNumber;
LastSourceName := SourceName;
LastError := ErrorCode[1];
end;
end;
function ReplaceSpecialChars(const S : AnsiString) : AnsiString;
var
I : integer;
begin
Result := '';
for I := 1 to length(S) do
if S[I] >= ' ' then
Result := Result + S[I]
else
Result := Result + '#' + IntToStr(byte(S[I]));
end;
procedure TScanner.RecoverFromError(const Expected, Found : AnsiString); begin
if Expected <> '' then Error(Expected + ' not found, but "' + ReplaceSpecialChars(Found) + '" found');
end;
procedure TScanner.MatchTerminal(KindExpected : TTokenKind); begin
if DoNextToken then NextToken;
if KindExpected = FToken.Kind then begin
LastGoodTop := Top;
DoNextToken := true;
end
else begin
ErrorCode := IntToStr(ord(ErrorCode[1])) + '.' + IntToStr(byte(KindExpected));
RecoverFromError(Kinds[KindExpected], FToken.Lexeme);
end;
end;
procedure TScanner.MatchToken(const TokenExpected : AnsiString); begin
if DoNextToken then NextToken;
if TokenExpected = UpperCase(FToken.Lexeme) then begin
LastGoodTop := Top;
DoNextToken := true;
end
else begin
ErrorCode := IntToStr(ord(ErrorCode[1])) + '.' + IntToStr(byte(TokenExpected[1]));
RecoverFromError('"' + TokenExpected + '"', FToken.Lexeme)
end;
end;
procedure TScanner.SetDelphiMode;
var
I : Integer;
begin
ReservedWords.DelimitedText := DelphiReservedWords;
I := pos('{[}', Productions[Directives[2]]);
if I <> 0 then begin
Productions[ExternalDir[2]] := OrigExternalDir;
Productions[Directives[2]] := OrigDirectives;
end;
end;
procedure TScanner.ChangeLanguageMode(FPC : boolean); begin
if FPCMode = FPC then exit;
FPCMode := FPC;
if FPC then begin
ReservedWords.DelimitedText := DelphiReservedWords + FPCReservedWords;
if pos('{[}', Productions[Directives[2]]) = 0 then begin
Productions[ExternalDir[2]] := Productions[ExternalDir[2]] + '{CVAR};' + ExternalDir;
Productions[Directives[2]] := Productions[Directives[2]] + '{[}' + Skip + ']' + Mark + ';';
end;
end
else
SetDelphiMode;
end;
function TScanner.CharToTokenKind(N : char) : TTokenKind; begin
Result := TTokenKind(byte(N) - byte(pred(Ident)))
end;
function TScanner.TokenKindToChar(T : TTokenKind) : char; begin
Result := char(byte(T) + byte(pred(Ident)))
end;
function TScanner.StringToTokenKind(S : string; Default : TTokenKind = tkUndefined) : TTokenKind; begin
Result := TTokenKind(AnsiIndexText(S, Kinds));
if Result = TTokenKind(-1) then Result := Default;
end;
function TScanner.GetFLineNumber: integer; begin
Result := FLineNumber[Include]
end;
function TScanner.GetFSourceName: AnsiString; begin
Result := FSourceName[Include]
end;
function TScanner.GetNonTerminalName(N : char): AnsiString; begin
Result := Kinds[CharToTokenKind(N)]
end;
procedure TScanner.CreateMacro;
var
Macro : AnsiString;
begin
Macro := FToken.Lexeme;
SkipBlank;
ScanChars([[':'], ['=']], [1, 1]);
if FToken.Lexeme <> '' then begin
SkipBlank;
ScanChars([[#1..#255] - ['}']], [50000]);
if Macros = nil then Macros := TStringList.Create;
Macros.Add(Macro + '=' + FToken.Lexeme);
end;
end;
end.
|
// RFC-1321 https://www.ietf.org/rfc/rfc1321.txt
{$MODE FPC}
{$MODESWITCH OUT}
{$MODESWITCH RESULT}
unit dmd5;
interface
//
// MD5Digest
//
// Computes MD5 digest of the data.
//
// Parameters:
//
// Data: start of input data, may be nil
// Size: size of input data
// DataEnd: end of data, that is DataEnd-Data=Size
//
// Returns:
//
// Digest: MD5 digest of the data
//
type
TMD5Digest = array[0 .. 16 - 1] of Byte;
procedure MD5Digest(Data: PByte; Size: SizeUInt; var Digest: TMD5Digest);
procedure MD5Digest(Data, DataEnd: PByte; var Digest: TMD5Digest);
//
// MD5Init
//
// Initializes Context variable.
//
// MD5Update
//
// Consumes next part of data.
//
// MD5Final
//
// Finalizes Context variable and returns MD5 digest of data consumed by
// MD5Update.
//
// Usage:
//
// Computes MD5 digest of stream-like data. Semantics of these functions
// are equivalent to those defined in RFC-1321.
//
// Typical use:
//
// var
// Context: TMD5Context;
// Digest: TMD5Digest;
// begin
// MD5Init(Context);
// while {there is data} do begin
// // ... read next data block to memory
// // Pass next part of data
// MD5Update(Context, Data, Size);
// end;
// MD5Final(Context, Digest);
// // now Digest contains MD5 digest of the data
// // ...
// end;
//
type
TMD5Context = record
State: array[0 .. 4 - 1] of Cardinal; // state (ABCD)
Count: QWord; // number of bits, modulo 2^64, lsb 1st
Buffer: array[0 .. 64 - 1] of Byte; // input buffer
end;
procedure MD5Init(out Context: TMD5Context);
procedure MD5Update(var Context: TMD5Context; Data: PByte; Size: SizeUInt);
procedure MD5Update(var Context: TMD5Context; Data, DataEnd: PByte);
procedure MD5Final(var Context: TMD5Context; out Digest: TMD5Digest);
implementation
type
TMD5State = array[0 .. 3] of Cardinal;
PMD5State = ^TMD5State;
function AuxF(X, Y, Z: Cardinal): Cardinal; inline;
begin
Result := (X and Y) or ((not X) and Z);
end;
function AuxG(X, Y, Z: Cardinal): Cardinal; inline;
begin
Result := (X and Z) or (Y and not Z);
end;
function AuxH(X, Y, Z: Cardinal): Cardinal; inline;
begin
Result := X xor Y xor Z;
end;
function AuxI(X, Y, Z: Cardinal): Cardinal; inline;
begin
Result := Y xor (X or not Z);
end;
//
// RotateLeft
//
// Circularly shifting X left by S bit positions
//
function RotateLeft(X: Cardinal; S: Byte): Cardinal; inline;
begin
Result := (X shl S) or (X shr (32 - S));
end;
const
T: array[0..63] of Cardinal = (
$D76AA478, $E8C7B756, $242070DB, $C1BDCEEE,
$F57C0FAF, $4787C62A, $A8304613, $FD469501,
$698098D8, $8B44F7AF, $FFFF5BB1, $895CD7BE,
$6B901122, $FD987193, $A679438E, $49B40821,
$F61E2562, $C040B340, $265E5A51, $E9B6C7AA,
$D62F105D, $02441453, $D8A1E681, $E7D3FBC8,
$21E1CDE6, $C33707D6, $F4D50D87, $455A14ED,
$A9E3E905, $FCEFA3F8, $676F02D9, $8D2A4C8A,
$FFFA3942, $8771F681, $6D9D6122, $FDE5380C,
$A4BEEA44, $4BDECFA9, $F6BB4B60, $BEBFBC70,
$289B7EC6, $EAA127FA, $D4EF3085, $04881D05,
$D9D4D039, $E6DB99E5, $1FA27CF8, $C4AC5665,
$F4292244, $432AFF97, $AB9423A7, $FC93A039,
$655B59C3, $8F0CCC92, $FFEFF47D, $85845DD1,
$6FA87E4F, $FE2CE6E0, $A3014314, $4E0811A1,
$F7537E82, $BD3AF235, $2AD7D2BB, $EB86D391
);
procedure MD5Transform(Block: PByte; var State: TMD5State);
var
I: Cardinal;
Saved: TMD5State;
begin
// Save State
Saved := State;
// Round 1
for I := 0 to 3 do begin
State[0] := State[1] + RotateLeft(State[0] + AuxF(State[1], State[2], State[3]) + {$IFDEF ENDIAN_BIG}SwapEndian{$ENDIF}(PCardinal(Block)[I * 4 + 0] + T[I * 4 + 0]), 7);
State[3] := State[0] + RotateLeft(State[3] + AuxF(State[0], State[1], State[2]) + {$IFDEF ENDIAN_BIG}SwapEndian{$ENDIF}(PCardinal(Block)[I * 4 + 1] + T[I * 4 + 1]), 12);
State[2] := State[3] + RotateLeft(State[2] + AuxF(State[3], State[0], State[1]) + {$IFDEF ENDIAN_BIG}SwapEndian{$ENDIF}(PCardinal(Block)[I * 4 + 2] + T[I * 4 + 2]), 17);
State[1] := State[2] + RotateLeft(State[1] + AuxF(State[2], State[3], State[0]) + {$IFDEF ENDIAN_BIG}SwapEndian{$ENDIF}(PCardinal(Block)[I * 4 + 3] + T[I * 4 + 3]), 22);
end;
// Round 2
for I := 0 to 3 do begin
State[0] := State[1] + RotateLeft(State[0] + AuxG(State[1], State[2], State[3]) + {$IFDEF ENDIAN_BIG}SwapEndian{$ENDIF}(PCardinal(Block)[(I * 20 + 1) and 15] + T[16 + I * 4 + 0]), 5);
State[3] := State[0] + RotateLeft(State[3] + AuxG(State[0], State[1], State[2]) + {$IFDEF ENDIAN_BIG}SwapEndian{$ENDIF}(PCardinal(Block)[(I * 20 + 6) and 15] + T[16 + I * 4 + 1]), 9);
State[2] := State[3] + RotateLeft(State[2] + AuxG(State[3], State[0], State[1]) + {$IFDEF ENDIAN_BIG}SwapEndian{$ENDIF}(PCardinal(Block)[(I * 20 + 11) and 15] + T[16 + I * 4 + 2]), 14);
State[1] := State[2] + RotateLeft(State[1] + AuxG(State[2], State[3], State[0]) + {$IFDEF ENDIAN_BIG}SwapEndian{$ENDIF}(PCardinal(Block)[(I * 20 + 16) and 15] + T[16 + I * 4 + 3]), 20);
end;
// Round 3
for I := 0 to 3 do begin
State[0] := State[1] + RotateLeft(State[0] + AuxH(State[1], State[2], State[3]) + {$IFDEF ENDIAN_BIG}SwapEndian{$ENDIF}(PCardinal(Block)[(I * 12 + 5) and 15] + T[32 + I * 4 + 0]), 4);
State[3] := State[0] + RotateLeft(State[3] + AuxH(State[0], State[1], State[2]) + {$IFDEF ENDIAN_BIG}SwapEndian{$ENDIF}(PCardinal(Block)[(I * 12 + 8) and 15] + T[32 + I * 4 + 1]), 11);
State[2] := State[3] + RotateLeft(State[2] + AuxH(State[3], State[0], State[1]) + {$IFDEF ENDIAN_BIG}SwapEndian{$ENDIF}(PCardinal(Block)[(I * 12 + 11) and 15] + T[32 + I * 4 + 2]), 16);
State[1] := State[2] + RotateLeft(State[1] + AuxH(State[2], State[3], State[0]) + {$IFDEF ENDIAN_BIG}SwapEndian{$ENDIF}(PCardinal(Block)[(I * 12 + 14) and 15] + T[32 + I * 4 + 3]), 23);
end;
// Round 4
for I := 0 to 3 do begin
State[0] := State[1] + RotateLeft(State[0] + AuxI(State[1], State[2], State[3]) + {$IFDEF ENDIAN_BIG}SwapEndian{$ENDIF}(PCardinal(Block)[(I * 28 + 0) and 15] + T[48 + I * 4 + 0]), 6);
State[3] := State[0] + RotateLeft(State[3] + AuxI(State[0], State[1], State[2]) + {$IFDEF ENDIAN_BIG}SwapEndian{$ENDIF}(PCardinal(Block)[(I * 28 + 7) and 15] + T[48 + I * 4 + 1]), 10);
State[2] := State[3] + RotateLeft(State[2] + AuxI(State[3], State[0], State[1]) + {$IFDEF ENDIAN_BIG}SwapEndian{$ENDIF}(PCardinal(Block)[(I * 28 + 14) and 15] + T[48 + I * 4 + 2]), 15);
State[1] := State[2] + RotateLeft(State[1] + AuxI(State[2], State[3], State[0]) + {$IFDEF ENDIAN_BIG}SwapEndian{$ENDIF}(PCardinal(Block)[(I * 28 + 21) and 15] + T[48 + I * 4 + 3]), 21);
end;
// Increment each registers by the value it had before this block was started
Inc(State[0], Saved[0]);
Inc(State[1], Saved[1]);
Inc(State[2], Saved[2]);
Inc(State[3], Saved[3]);
end;
procedure MD5Init_(out State: TMD5State);
begin
// Load magic initialization constants.
State[0] := $67452301;
State[1] := $efcdab89;
State[2] := $98badcfe;
State[3] := $10325476;
end;
procedure MD5Final_(Block: PByte;
Rest: SizeUInt;
var Digest: TMD5Digest;
Bits: QWord);
begin
Block[Rest] := $80;
if Rest < 56 then begin
FillChar(Block[Rest + 1], 55 - Rest, 0);
end else begin
FillChar(Block[Rest + 1], 63 - Rest, 0);
MD5Transform(@Block[0], TMD5State(Digest));
FillChar(Block[0], 56, 0);
end;
// number of bits
PCardinal(@Block[0])[14] := {$IFDEF ENDIAN_BIG}SwapEndian{$ENDIF}(Bits and $FFFFFFFF);
PCardinal(@Block[0])[15] := {$IFDEF ENDIAN_BIG}SwapEndian{$ENDIF}((Bits shr 32) and $FFFFFFFF);
MD5Transform(@Block[0], TMD5State(Digest));
{$IFDEF ENDIAN_BIG}
TMD5State(Digest)[0] := SwapEndian(TMD5State(Digest)[0]);
TMD5State(Digest)[1] := SwapEndian(TMD5State(Digest)[1]);
TMD5State(Digest)[2] := SwapEndian(TMD5State(Digest)[2]);
TMD5State(Digest)[3] := SwapEndian(TMD5State(Digest)[3]);
{$ENDIF}
end;
procedure MD5Digest(Data, DataEnd: PByte; var Digest: TMD5Digest);
var
Len: SizeUInt;
Temp: array[0 .. 64 - 1] of Byte;
begin
if Data = nil then
DataEnd := nil;
Len := DataEnd - Data;
MD5Init_(TMD5State(Digest));
while Data + 64 < DataEnd do begin
MD5Transform(Data, TMD5State(Digest));
Inc(Data, 64);
end;
if Data <> nil then
Move(Data^, Temp[0], DataEnd - Data);
MD5Final_(@Temp[0], DataEnd - Data, Digest, Len shl 3);
// Zeroize sensitive information.
Len := 0;
FillChar(Temp[0], SizeOf(Temp), 0);
end;
procedure MD5Digest(Data: PByte; Size: SizeUInt; var Digest: TMD5Digest);
begin
MD5Digest(Data, Data + Size, Digest);
end;
procedure MD5Init(out Context: TMD5Context);
begin
MD5Init_(TMD5State(Context.State));
Context.Count := 0;
end;
procedure MD5Update(var Context: TMD5Context; Data, DataEnd: PByte);
begin
MD5Update(Context, Data, DataEnd - Data);
end;
procedure MD5Update(var Context: TMD5Context; Data: PByte; Size: SizeUInt);
var
I, Index, PartLen: Cardinal;
begin
Index := (Context.Count shr 3) and $3F;
Inc(Context.Count, Size shl 3);
PartLen := 64 - Index;
if Size >= PartLen then begin
Move(Data^, Context.Buffer[Index], PartLen);
MD5Transform(@Context.Buffer[0], TMD5State(Context.State));
I := PartLen;
while I + 63 < Size do begin
MD5Transform(@Data[I], TMD5State(Context.State));
Inc(I, 64);
end;
Index := 0;
end else
I := 0;
Move(Data[I], Context.Buffer[Index], Size - I);
end;
procedure MD5Final(var Context: TMD5Context; out Digest: TMD5Digest);
begin
Digest := TMD5Digest(Context.State);
MD5Final_(@Context.Buffer[0], (Context.Count shr 3) and $3F, Digest, Context.Count);
// Zeroize sensitive information.
FillChar(Context, SizeOf(Context), 0);
end;
end.
|
// ==========================================================================
//
// Copyright(c) 2012-2014 Embarcadero Technologies, Inc.
//
// ==========================================================================
//
// Delphi-C++ Library Bridge
// Interface for library FlatBox2D
//
unit Box2D.Rope;
interface
uses
Box2D.Common,
Box2DTypes;
type
b2RopeHandle = THandle;
Pb2RopeHandle = ^b2RopeHandle;
Pb2RopeDef = ^b2RopeDef;
PPb2RopeDef = ^Pb2RopeDef;
{ ===== Records ===== }
b2RopeDef = record
vertices: Pb2Vec2;
count: Integer;
masses: PSingle;
gravity: b2Vec2;
damping: Single;
k2: Single; { Stretching stiffness}
k3: Single; { Bending stiffness. Values above 0.5 can make the simulation blow up.}
class function Create: b2RopeDef; static; cdecl;
end;
b2RopeWrapper = record
FHandle: b2RopeHandle;
class function Create: b2RopeWrapper; static; cdecl;
procedure Destroy; cdecl;
class operator Implicit(handle: b2RopeHandle): b2RopeWrapper; overload;
class operator Implicit(wrapper: b2RopeWrapper): b2RopeHandle; overload;
procedure Initialize(def: Pb2RopeDef); cdecl;
procedure Step(timeStep: Single; iterations: Integer); cdecl;
function GetVertexCount: Integer; cdecl;
function GetVertices: Pb2Vec2; cdecl;
procedure Draw(draw: b2DrawHandle); cdecl;
procedure SetAngle(angle: Single); cdecl;
end;
implementation
const
{$IFDEF MSWINDOWS}
LIB_NAME = 'FlatBox2DDyn.dll';
{$IFDEF WIN64}
_PU = '';
{$ELSE}
_PU = '_';
{$ENDIF}
{$ENDIF}
{$IFDEF ANDROID}
LIB_NAME = 'libFlatBox2D.a';
_PU = '';
{$ENDIF}
{$IFDEF MACOS}
{$IFDEF IOS}
LIB_NAME = 'libFlatBox2D.a';
{$ELSE}
LIB_NAME = 'libFlatBox2DDyn.dylib';
{$ENDIF}
{$IFDEF UNDERSCOREIMPORTNAME}
_PU = '_';
{$ELSE}
_PU = '';
{$ENDIF}
{$ENDIF}
{ ===== Record methods: import and definition ===== }
function b2RopeDef_Create: b2RopeDef; cdecl; external LIB_NAME name _PU + 'b2RopeDef_b2RopeDef_1'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2RopeDef.Create: b2RopeDef; cdecl;
begin
Result := b2RopeDef_Create;
end;
function b2Rope_Create: b2RopeHandle; cdecl; external LIB_NAME name _PU + 'b2Rope_b2Rope_1'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
class function b2RopeWrapper.Create: b2RopeWrapper; cdecl;
begin
Result.FHandle := b2Rope_Create;
end;
procedure b2Rope_Destroy(_self: b2RopeHandle); cdecl; external LIB_NAME name _PU + 'b2Rope_dtor'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2RopeWrapper.Destroy; cdecl;
begin
b2Rope_Destroy(FHandle);
end;
class operator b2RopeWrapper.Implicit(handle: b2RopeHandle): b2RopeWrapper;
begin
Result.FHandle := handle;
end;
class operator b2RopeWrapper.Implicit(wrapper: b2RopeWrapper): b2RopeHandle;
begin
Result := wrapper.FHandle;
end;
procedure b2Rope_Initialize(_self: b2RopeHandle; def: Pb2RopeDef); cdecl; external LIB_NAME name _PU + 'b2Rope_Initialize'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2RopeWrapper.Initialize(def: Pb2RopeDef); cdecl;
begin
b2Rope_Initialize(FHandle, def)
end;
procedure b2Rope_Step(_self: b2RopeHandle; timeStep: Single; iterations: Integer); cdecl; external LIB_NAME name _PU + 'b2Rope_Step'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2RopeWrapper.Step(timeStep: Single; iterations: Integer); cdecl;
begin
b2Rope_Step(FHandle, timeStep, iterations)
end;
function b2Rope_GetVertexCount(_self: b2RopeHandle): Integer; cdecl; external LIB_NAME name _PU + 'b2Rope_GetVertexCount'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2RopeWrapper.GetVertexCount: Integer; cdecl;
begin
Result := b2Rope_GetVertexCount(FHandle)
end;
function b2Rope_GetVertices(_self: b2RopeHandle): Pb2Vec2; cdecl; external LIB_NAME name _PU + 'b2Rope_GetVertices'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
function b2RopeWrapper.GetVertices: Pb2Vec2; cdecl;
begin
Result := b2Rope_GetVertices(FHandle)
end;
procedure b2Rope_Draw(_self: b2RopeHandle; draw: b2DrawHandle); cdecl; external LIB_NAME name _PU + 'b2Rope_Draw'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2RopeWrapper.Draw(draw: b2DrawHandle); cdecl;
begin
b2Rope_Draw(FHandle, draw)
end;
procedure b2Rope_SetAngle(_self: b2RopeHandle; angle: Single); cdecl; external LIB_NAME name _PU + 'b2Rope_SetAngle'
{$IF DEFINED(ANDROID)} dependency 'gnustl_static' {$ELSEIF DEFINED(IOS)} {$ENDIF};
procedure b2RopeWrapper.SetAngle(angle: Single); cdecl;
begin
b2Rope_SetAngle(FHandle, angle)
end;
initialization
{$IF (defined(CPUX64) or defined(CPUARM64))}
Assert(Sizeof(b2RopeDef) = 48, 'Size mismatch in b2RopeDef');
{$ELSE}
Assert(Sizeof(b2RopeDef) = 32, 'Size mismatch in b2RopeDef');
{$ENDIF}
end.
|
//Настройки
unit fOptions;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, RtColorPicker, ComCtrls, ExtCtrls, RXSpin;
type
TfrmOptions = class(TForm)
pnlTop: TPanel;
pnlBottom: TPanel;
btnOK: TButton;
btnCancel: TButton;
PageOption: TPageControl;
TabSheetInfo: TTabSheet;
TabSheetInterface: TTabSheet;
cbUnCorrectStreet: TCheckBox;
Bevel1: TBevel;
lblValue1: TLabel;
lblTimeOut1: TLabel;
edUnCorrectStreetTimeOut: TRxSpinEdit;
edUnCorrectStreetValue: TRxSpinEdit;
lblValue2: TLabel;
lblTimeOut2: TLabel;
cbReeArc: TCheckBox;
Bevel2: TBevel;
lblValue3: TLabel;
lblTimeOut3: TLabel;
edReeArcValue: TRxSpinEdit;
edReeArcTimeOut: TRxSpinEdit;
lblValue4: TLabel;
lblTimeOut4: TLabel;
cbUseColorMode: TCheckBox;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure cbUnCorrectStreetClick(Sender: TObject);
procedure btnOKClick(Sender: TObject);
procedure cbReeArcClick(Sender: TObject);
private
procedure LoadFromIni;
procedure SaveToIni;
public
{ Public declarations }
end;
implementation
uses
uCommon;
{$R *.dfm}
procedure TfrmOptions.FormCreate(Sender: TObject);
begin
PageOption.ActivePageIndex := 0;
LoadFromIni;
//TODO: почему-то не срабатывает при вызове метода "cbUnCorrectStreetClick"
edUnCorrectStreetValue.Enabled := cbUnCorrectStreet.Checked;
edUnCorrectStreetTimeOut.Enabled := cbUnCorrectStreet.Checked;
edReeArcValue.Enabled := cbReeArc.Checked;
edReeArcTimeOut.Enabled := cbReeArc.Checked;
end;
procedure TfrmOptions.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
//------------------------------------------------------------------------------
//
// INI
//
//------------------------------------------------------------------------------
//загрузка параметров из ini-файла
procedure TfrmOptions.LoadFromIni;
var
sect: String;
begin
sect := 'Options';
cbUnCorrectStreet.Checked := OptionsIni.ReadBool(sect, 'UnCorrectStreet', false);
edUnCorrectStreetValue.Value := OptionsIni.ReadFloat(sect, 'UnCorrectStreetValue', 1000);
edUnCorrectStreetTimeOut.Value := OptionsIni.ReadFloat(sect, 'UnCorrectStreetTimeOut', 600);
cbReeArc.Checked := OptionsIni.ReadBool(sect, 'ReeArc', false);
edReeArcValue.Value := OptionsIni.ReadFloat(sect, 'ReeArcValue', 0);
edReeArcTimeOut.Value := OptionsIni.ReadFloat(sect, 'ReeArcTimeOut', 600);
cbUseColorMode.Checked := OptionsIni.ReadBool(sect, 'UseColorMode', true);
end;
//сохранение параметров в ini-файл
procedure TfrmOptions.SaveToIni;
var
sect: String;
begin
sect := 'Options';
OptionsIni.WriteBool(sect, 'UnCorrectStreet', cbUnCorrectStreet.Checked);
OptionsIni.WriteFloat(sect, 'UnCorrectStreetValue', edUnCorrectStreetValue.Value);
OptionsIni.WriteFloat(sect, 'UnCorrectStreetTimeOut', edUnCorrectStreetTimeOut.Value);
OptionsIni.WriteBool(sect, 'ReeArc', cbReeArc.Checked);
OptionsIni.WriteFloat(sect, 'ReeArcValue', edReeArcValue.Value);
OptionsIni.WriteFloat(sect, 'ReeArcTimeOut', edReeArcTimeOut.Value);
OptionsIni.WriteBool(sect, 'UseColorMode', cbUseColorMode.Checked);
end;
procedure TfrmOptions.cbUnCorrectStreetClick(Sender: TObject);
begin
edUnCorrectStreetValue.Enabled := cbUnCorrectStreet.Checked;
edUnCorrectStreetTimeOut.Enabled := cbUnCorrectStreet.Checked;
end;
procedure TfrmOptions.cbReeArcClick(Sender: TObject);
begin
edReeArcValue.Enabled := cbReeArc.Checked;
edReeArcTimeOut.Enabled := cbReeArc.Checked;
end;
procedure TfrmOptions.btnOKClick(Sender: TObject);
begin
SaveToIni;
end;
end.
|
// Unit that hooks LoadLibrary, GetProcAddress, FreeLibrary for MemoryModule
// to allow transparent DLL loading.
unit MemoryModuleHook;
interface
uses
Windows,
MemoryModule, FuncHook;
type
// Callback function that is called from LoadLibraryHook to determine
// an address of library data.
// lpLibFileName: name of library to load
// Returns:
// Pointer to library data; nil to bypass MemoryModule and use WinAPI
TGetLibPtrProc = function (lpLibFileName: PWideChar): Pointer;
function InstallHook(AGetLibPtrCallback: TGetLibPtrProc): Boolean;
function UninstallHook: Boolean;
implementation
var
HookInstalled: Boolean = False;
GetLibPtrCallback: TGetLibPtrProc;
LoadedModules: array of HMODULE;
CS: RTL_CRITICAL_SECTION;
LoadLibrary_Old: function (lpLibFileName: PWideChar): HMODULE; stdcall;
GetProcAddress_Old: function (hModule: HMODULE; lpProcName: LPCSTR): FARPROC; stdcall;
FreeLibrary_Old: function (hLibModule: HMODULE): BOOL; stdcall;
HI_LL, HI_GPA, HI_FL: THookInfo;
function IndexOfLoadedModule(hModule: HMODULE): Integer;
var i: Integer;
begin
EnterCriticalSection(CS);
try
for i := Low(LoadedModules) to High(LoadedModules) do
if LoadedModules[i] = hModule then
Exit(i);
Result := -1;
finally
LeaveCriticalSection(CS);
end;
end;
// Try to get library address and load it, run WinAPI routine otherwise.
function LoadLibraryHook(lpLibFileName: PWideChar): HMODULE; stdcall;
var
LibPtr: Pointer;
begin
Result := 0;
LibPtr := GetLibPtrCallback(lpLibFileName);
if LibPtr = nil then
begin
LoadLibrary_Old(lpLibFileName);
Exit;
end;
Result := HMODULE(MemoryLoadLibary(LibPtr));
if Result <> 0 then
try
EnterCriticalSection(CS);
SetLength(LoadedModules, Length(LoadedModules) + 1);
LoadedModules[Length(LoadedModules) - 1] := Result;
finally
LeaveCriticalSection(CS);
end;
end;
// If hModule was loaded via MM, run MM's routine. Otherwise, run WinAPI one.
function GetProcAddressHook(hModule: HMODULE; lpProcName: LPCSTR): FARPROC; stdcall;
begin
if IndexOfLoadedModule(hModule) <> -1 then
Result := FARPROC(MemoryGetProcAddress(TMemoryModule(hModule), lpProcName))
else
Result := GetProcAddress_Old(hModule, lpProcName);
end;
// If hLibModule was loaded via MM, run MM's routine. Otherwise, run WinAPI one.
function FreeLibraryHook(hLibModule: HMODULE): BOOL; stdcall;
var idx: Integer;
begin
idx := IndexOfLoadedModule(hLibModule);
if idx <> -1 then
begin
MemoryFreeLibrary(TMemoryModule(hLibModule));
Result := BOOL(True);
// Remove from the list
try
EnterCriticalSection(CS);
LoadedModules[idx] := 0;
if idx < Length(LoadedModules) - 1 then
Move(LoadedModules[idx + 1], LoadedModules[idx], (Length(LoadedModules) - idx + 1)*SizeOf(HMODULE));
SetLength(LoadedModules, Length(LoadedModules) - 1);
finally
LeaveCriticalSection(CS);
end;
end
else
Result := FreeLibrary_Old(hLibModule);
end;
function InstallHook(AGetLibPtrCallback: TGetLibPtrProc): Boolean;
begin
Result := False;
if not Assigned(AGetLibPtrCallback) then Exit;
EnterCriticalSection(CS);
try
if HookInstalled then Exit;
if not HookProcedure(False, HI_LL) or
not HookProcedure(False, HI_GPA) or
not HookProcedure(False, HI_FL) then Exit;
LoadLibrary_Old := HI_LL.OrigProc;
GetProcAddress_Old := HI_GPA.OrigProc;
FreeLibrary_Old := HI_FL.OrigProc;
HookInstalled := True;
GetLibPtrCallback := AGetLibPtrCallback;
Result := True;
finally
if not Result then
UninstallHook;
LeaveCriticalSection(CS);
end;
end;
function UninstallHook: Boolean;
begin
Result := False;
EnterCriticalSection(CS);
try
if not HookInstalled then Exit;
while Length(LoadedModules) > 0 do
FreeLibrary(LoadedModules[0]);
Result :=
UnhookProcedure(HI_LL) and
UnhookProcedure(HI_GPA) and
UnhookProcedure(HI_FL);
GetLibPtrCallback := nil;
HookInstalled := False;
finally
LeaveCriticalSection(CS);
end;
end;
initialization
InitializeCriticalSection(CS);
HI_LL.Init(@LoadLibrary, @LoadLibraryHook);
HI_GPA.Init(@GetProcAddress, @GetProcAddressHook);
HI_FL.Init(@FreeLibrary, @FreeLibraryHook);
finalization
UninstallHook;
DeleteCriticalSection(CS);
end.
|
unit Unit1;
interface
uses
System.SysUtils, System.Classes, System.Math,
Vcl.Forms, Vcl.Controls, Vcl.ExtCtrls, Vcl.StdCtrls,
//GLS
GLScene, GLObjects, GLTexture, GLVectorGeometry,
GLCadencer, GLWin32Viewer, GLCrossPlatform, GLMaterial,
GLCoordinates, GLBaseClasses, GLSimpleNavigation, GLProcTextures,
GLUtils;
type
TForm1 = class(TForm)
GLScene1: TGLScene;
GLSceneViewer1: TGLSceneViewer;
DummyCube1: TGLDummyCube;
GLCamera1: TGLCamera;
Sprite1: TGLSprite;
Sprite2: TGLSprite;
GLMaterialLibrary1: TGLMaterialLibrary;
GLCadencer1: TGLCadencer;
GLSimpleNavigation1: TGLSimpleNavigation;
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
private
{ Private declarations }
public
{ Public declatrations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.FormCreate(Sender: TObject);
var
Spr : TGLSprite;
I : Integer;
MediaPath : String;
begin
SetGLSceneMediaDir;
// Load texture for sprite2, this is the hand-coded way using a PersistentImage
// Sprite1 uses a PicFileImage, and so the image is automagically loaded by
// GLScene when necessary (no code is required).
// (Had I used two PicFileImage, I would have avoided this code)
GLMaterialLibrary1.TexturePaths := GetCurrentDir;
MediaPath := GLMaterialLibrary1.TexturePaths + '\';
Sprite1.Material.Texture.Image.LoadFromFile(MediaPath + 'Flare1.bmp');
GLMaterialLibrary1.Materials[0].Material.Texture.Image.LoadFromFile('Flare1.bmp');
// New sprites are created by duplicating the template "sprite2"
for i:=1 to 9 do begin
spr:=TGLSprite(DummyCube1.AddNewChild(TGLSprite));
spr.Assign(Sprite2);
end;
end;
procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
var
i : Integer;
a, aBase : Double;
begin
// angular reference : 90° per second <=> 4 second per revolution
aBase:=90*newTime;
// "pulse" the star
a:=DegToRad(aBase);
Sprite1.SetSquareSize(4+0.2*cos(3.5*a));
// rotate the sprites around the yellow "star"
for i:=0 to DummyCube1.Count-1 do begin
a:=DegToRad(aBase+i*8);
with (DummyCube1.Children[i] as TGLSprite) do begin
// rotation movement
Position.X:=4*cos(a);
Position.Z:=4*sin(a);
// ondulation
Position.Y:=2*cos(2.1*a);
// sprite size change
SetSquareSize(2+cos(3*a));
end;
end;
end;
procedure TForm1.FormResize(Sender: TObject);
begin
// This lines take cares of auto-zooming.
// magic numbers explanation :
// 333 is a form width where things looks good when focal length is 50,
// ie. when form width is 333, uses 50 as focal length,
// when form is 666, uses 100, etc...
GLCamera1.FocalLength:=Width*50/333;
end;
end.
|
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
OpenGL;
type
TfrmGL = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormPaint(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormResize(Sender: TObject);
private
DC : HDC;
hrc: HGLRC;
Palette : HPalette;
procedure SetDCPixelFormat (DC : HDC);
protected
procedure WMQueryNewPalette(var Msg: TWMQueryNewPalette); message WM_QUERYNEWPALETTE;
procedure WMPaletteChanged(var Msg: TWMPaletteChanged); message WM_PALETTECHANGED;
end;
var
frmGL: TfrmGL;
implementation
uses DGLUT;
{$R *.DFM}
{=======================================================================
Перерисовка окна}
procedure TfrmGL.FormPaint(Sender: TObject);
begin
glClear (GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
glutSolidTeapot (1.0);
SwapBuffers(DC);
glRotatef (1, 1.0, 1.0, 1.0);
InvalidateRect(Handle, nil, False);
end;
{=======================================================================
Создание формы}
procedure TfrmGL.FormCreate(Sender: TObject);
begin
DC := GetDC (Handle);
SetDCPixelFormat(DC);
hrc := wglCreateContext(DC);
wglMakeCurrent(DC, hrc);
glClearColor (0.5, 0.5, 0.75, 1.0);
glColor3f (1.0, 0.0, 0.5);
glEnable (GL_DEPTH_TEST);
glEnable (GL_COLOR_MATERIAL);
glEnable (GL_LIGHTING);
glEnable (GL_LIGHT0);
end;
{=======================================================================
Конец работы приложения}
procedure TfrmGL.FormDestroy(Sender: TObject);
begin
wglMakeCurrent(0, 0);
wglDeleteContext(hrc);
ReleaseDC (Handle, DC);
DeleteDC (DC);
end;
procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
If Key = VK_ESCAPE then Close;
end;
procedure TfrmGL.FormResize(Sender: TObject);
begin
glViewport(0, 0, ClientWidth, ClientHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity;
glFrustum (-1, 1, -1, 1, 5, 10);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity;
glTranslatef(0.0, 0.0, -8.0); // перенос объекта - ось Z
glRotatef(30.0, 1.0, 0.0, 0.0); // поворот объекта - ось X
glRotatef(70.0, 0.0, 1.0, 0.0); // поворот объекта - ось Y
InvalidateRect(Handle, nil, False);
end;
{=======================================================================
Задаем формат пикселей}
procedure TfrmGL.SetDCPixelFormat (DC : HDC);
var
hHeap: THandle;
nColors, i: Integer;
lpPalette: PLogPalette;
byRedMask, byGreenMask, byBlueMask: Byte;
nPixelFormat: Integer;
pfd: TPixelFormatDescriptor;
begin
FillChar(pfd, SizeOf(pfd), 0);
pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or
PFD_DOUBLEBUFFER;
nPixelFormat := ChoosePixelFormat(DC, @pfd);
SetPixelFormat(DC, nPixelFormat, @pfd);
DescribePixelFormat(DC, nPixelFormat, sizeof(TPixelFormatDescriptor), pfd);
if ((pfd.dwFlags and PFD_NEED_PALETTE) <> 0) then begin
nColors := 1 shl pfd.cColorBits;
hHeap := GetProcessHeap;
lpPalette := HeapAlloc(hHeap, 0, sizeof(TLogPalette) + (nColors * sizeof(TPaletteEntry)));
// Стандартные установки номера версии и числа элементов палитры
lpPalette^.palVersion := $300;
lpPalette^.palNumEntries := nColors;
byRedMask := (1 shl pfd.cRedBits) - 1;
byGreenMask := (1 shl pfd.cGreenBits) - 1;
byBlueMask := (1 shl pfd.cBlueBits) - 1;
// Заполняем палитру цветами
for i := 0 to nColors - 1 do begin
lpPalette^.palPalEntry[i].peRed := (((i shr pfd.cRedShift) and byRedMask) * 255) DIV byRedMask;
lpPalette^.palPalEntry[i].peGreen := (((i shr pfd.cGreenShift) and byGreenMask) * 255) DIV byGreenMask;
lpPalette^.palPalEntry[i].peBlue := (((i shr pfd.cBlueShift) and byBlueMask) * 255) DIV byBlueMask;
lpPalette^.palPalEntry[i].peFlags := 0;
end;
// Создаем палитру
Palette := CreatePalette(lpPalette^);
HeapFree(hHeap, 0, lpPalette);
// Устанавливаем палитру в контексте устройства
if (Palette <> 0) then begin
SelectPalette(DC, Palette, False);
RealizePalette(DC);
end;
end;
end;
{=======================================================================
Сообщение WM_QUERYNEWPALETTE}
procedure TfrmGL.WMQueryNewPalette(var Msg : TWMQueryNewPalette);
begin
// Это сообщение посылается окну, которое становится активным
// В ответ мы должны реализовать свою логическую палитру, т.к.
// пока главное окно не было активным, другое прложение
// могло изменить системную палитру
if (Palette <> 0) then begin
Msg.Result := RealizePalette(DC);
// Если удалось отобразить хоть один цвет в системную палитру,
// перерисовываем окно
if (Msg.Result <> GDI_ERROR) then
InvalidateRect(Handle, nil, False);
end;
end;
{=======================================================================
Сообщение WM_PALETTECHANGED}
procedure TfrmGL.WMPaletteChanged(var Msg : TWMPaletteChanged);
begin
// Этот обработчик активизируется всегда, когда какое-либо приложение
// изменяет системную палитру
if ((Palette <> 0) and (THandle(TMessage(Msg).wParam) <> Handle))
then begin
if (RealizePalette(DC) <> GDI_ERROR) then
UpdateColors(DC);
Msg.Result := 0;
end;
end;
end.
|
unit uCodeExplorer;
interface
uses
Windows,
Messages,
SysUtils,
Variants,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
JvComponent,
JvDockControlForm,
JvDockVCStyle,
ComCtrls,
ImgList,
uPlugInDefinitions,
uPluginManager;
type
TCodeExplorerForm = class(TForm)
JvDockClient: TJvDockClient;
JvDockVCStyle: TJvDockVCStyle;
trvCodeExplorer: TTreeView;
imglCodeExplorer: TImageList;
private
{ Private declarations }
fIndexArr: array of TTreeNode;
fCodeExplorerGetItemInfo: TCodeExplorerGetItemInfo;
fCodeExplorerInit: TCodeExplorerInit;
procedure WMCodeExpAddItem(var Message: TMessage); message WM_CODEEXP_ADDITEM;
procedure WMCodeExpBegin(var Message: TMessage); message WM_CODEEXP_BEGIN;
procedure WMCodeExpEnd(var Message: TMessage); message WM_CODEXP_END;
procedure WMCodeExpError(var Message: TMessage); message WM_CODEXP_ERROR;
public
{ Public declarations }
procedure ScanDocment;
end;
var
CodeExplorerForm: TCodeExplorerForm;
implementation
uses uDocuments, uMain, uUtils;
{$R *.dfm}
{ TCodeExplorerForm }
procedure TCodeExplorerForm.WMCodeExpAddItem(var Message: TMessage);
var
Item: TCodeExplorerItem;
Node, ParentNode: TTreeNode;
Count: Integer;
begin
ParentNode := nil;
Count := High(fIndexArr);
if fCodeExplorerGetItemInfo(Message.WParam, Item) then
begin
if Item.ParentIndex <> -1 then
ParentNode := fIndexArr[Item.ParentIndex];
Node := trvCodeExplorer.Items.AddChild(ParentNode, Item.Caption);
Node.ImageIndex := Item.ImageIndex;
if Count > Item.Index then
SetLength(fIndexArr, Succ(Count) + 100);
fIndexArr[Item.Index] := Node;
end;
end;
procedure TCodeExplorerForm.WMCodeExpBegin(var Message: TMessage);
begin
trvCodeExplorer.Items.BeginUpdate;
trvCodeExplorer.Items.Clear;
fCodeExplorerGetItemInfo := Document.CodeExplorerPlugin.GetProcAddress('CodeExplorerGetItemInfo');
end;
procedure TCodeExplorerForm.WMCodeExpEnd(var Message: TMessage);
begin
trvCodeExplorer.Items.Clear;
trvCodeExplorer.Items.EndUpdate;
Finalize(fIndexArr);
end;
procedure TCodeExplorerForm.WMCodeExpError(var Message: TMessage);
begin
MainForm.StatusMsg('Error while parsing the document.', ErrorMsgColor, clWhite,
6000, True);
end;
procedure TCodeExplorerForm.ScanDocment;
var
GrammarFile: String;
begin
SetLength(fIndexArr, 100);
GrammarFile := Settings.ReadString('DocumentTypes', 'DocumentTypeGrammarFile'
+ IntToStr( GetDocumentTypeIndex(Document.DocumentType) ), '');
GrammarFile := AppPath + 'Grammars\' + GrammarFile;
if FileExists(GrammarFile) then
begin
fCodeExplorerInit := Document.CodeExplorerPlugin.GetProcAddress('CodeExplorerInit');
fCodeExplorerInit( PChar(Document.Code), PChar(GrammarFile), Handle );
end;
end;
end.
|
Unit handlers;
uses System.IO;
uses System.Net;
uses controllers;
uses session;
procedure writeHtml(var ctx: System.Net.HttpListenerContext; content: string);
begin
ctx.Response.ContentType := 'text/html';
ctx.Response.ContentLength64 := Length(content);
var sw := new StreamWriter(ctx.Response.OutputStream);
sw.WriteLine(content);
sw.Close();
end;
procedure redirect(var ctx: System.Net.HttpListenerContext; path: string);
begin
ctx.Response.Redirect(path);
ctx.Response.Close();
end;
procedure notFound(var ctx: System.Net.HttpListenerContext);
begin
ctx.Response.StatusCode := 404;
writeHtml(ctx, '<h3>404 not found</h3>')
end;
function getContentType(ext: string): string;
begin
case ext of
'jpg': Result := 'image/jpeg';
'html': Result := 'text/html';
'css': Result := 'text/css';
'ico': Result := 'image/x-icon';
else
Result := 'text/plain';
end;
end;
procedure serveStatic(var ctx: System.Net.HttpListenerContext; ext: string);
begin
var filePath := '.' + ctx.Request.Url.LocalPath;
if not FileExists(filePath) then begin notFound(ctx); exit; end;
ctx.Response.ContentType := getContentType(ext);
var fileInfo := new System.IO.FileInfo(filepath);
ctx.Response.ContentLength64 := fileInfo.Length;
var sr := new FileStream(filepath, FileMode.Open);
var buffer := new byte[4096];
var len := sr.Read(buffer, 0, Length(buffer));
while (len > 0) do begin
ctx.Response.OutputStream.Write(buffer,0, len);
len := sr.Read(buffer, 0, Length(buffer));
end;
sr.Close();
ctx.Response.OutputStream.Close();
end;
procedure HandleIcecreams(var ctx: System.Net.HttpListenerContext);
begin
var user := GetUserSession(ctx);
if (user = nil) then begin redirect(ctx, '/login.html'); exit; end;
writeHtml(ctx, 'Your icecreams: <br>' + GetIcecreams(user));
end;
procedure HandleAddIcecream(var ctx: System.Net.HttpListenerContext);
begin
var user := GetUserSession(ctx);
if (user = nil) then begin redirect(ctx, '/login.html'); exit; end;
var getParams := ctx.Request.QueryString;
var icecream := getParams['icecream'];
if ((icecream = nil) or (icecream = '')) then begin writeHtml(ctx, 'Fill the form please'); exit; end;
AddIcecream(user, icecream);
writeHtml(ctx, 'Icecream added successfully');
end;
procedure HandleRegister(var ctx: System.Net.HttpListenerContext);
begin
var getParams := ctx.Request.QueryString;
var login := getParams['login'];
var password := getParams['password'];
if ((login = nil) or (login = '') or (password = nil) or (password = '')) then begin writeHtml(ctx, 'Fill the form please'); exit; end;
if (GetUser(login) <> nil) then begin writeHtml(ctx, 'User with this username already exists'); exit; end;
AddUser(login, password);
LoginSession(login, ctx);
redirect(ctx, '/index.html');
end;
procedure HandleLogin(var ctx: System.Net.HttpListenerContext);
begin
var getParams := ctx.Request.QueryString;
var login := getParams['login'];
var password := getParams['password'];
if ((login = nil) or (login = '') or (password = nil) or (password = '')) then begin writeHtml(ctx, 'Fill the form please'); exit; end;
if (GetUser(login) <> password) then begin writeHtml(ctx, 'Incorrect login or password'); exit; end;
LoginSession(login, ctx);
redirect(ctx, '/index.html');
end;
procedure HandleLastUsers(var ctx: System.Net.HttpListenerContext);
begin
writeHtml(ctx, 'Last 40 users: <br>' + GetLastUsers(40));
end;
procedure HandleRoot(var ctx: System.Net.HttpListenerContext);
begin
if (ctx.Request.Url.LocalPath = '/') then begin
redirect(ctx, '/index.html');
exit;
end;
var parts := ctx.Request.Url.ToString().Split('.');
var ext := parts[Length(parts) - 1];
case ext of
'jpg','html','css','ico': serveStatic(ctx, ext);
else
notFound(ctx);
end;
end;
end. |
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2013-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit System.Android.Sensors;
interface
uses
System.Sensors, Androidapi.Sensor, Androidapi.JNI.Location;
type
INDKSensor = interface
['{523B5B0F-AD54-4C1E-B9A1-978B5CD37D8B}']
/// <summary>
/// Type of this instance of sensor. Using this value you can understand what kind of sensor you use.
/// For example, if SensorType = 10 it means that you use ASENSOR_TYPE_LINEAR_ACCELERATION.
/// This const declared in Androidapi.Sensor.pas
/// </summary>
function SensorType: Integer;
/// <summary>
/// Instance of a specific sensor manager
/// </summary>
function SensorManager: PASensorManager;
/// <summary>
/// Instance of a specific sensor
/// </summary>
function Sensor: PASensor;
/// <summary>
/// Event queue for the sensor
/// </summary>
function NativeEventQueue: PASensorEventQueue;
/// <summary>
/// This record represents a Sensor event and holds information such as the time-stamp, accuracy and the sensor data.
/// </summary>
function LastValue: ASensorEvent;
end;
ILocationListeners = interface
['{F379C0D0-63A5-4B98-845B-09C611BE5D40}']
/// <summary>
/// For GPS location provider. Used for receiving notifications from the LocationManager when the location has changed.
/// </summary>
function GetGPSListener: JLocationListener;
/// <summary>
/// For network location provider. Used for receiving notifications from the LocationManager when the location has changed.
/// </summary>
function GetNetworkListener: JLocationListener;
/// <summary>
/// For passive location provider. Used for receiving notifications from the LocationManager when the location has changed.
/// </summary>
function GetPassiveListener: JLocationListener;
end;
TPlatformSensorManager = class(TSensorManager)
protected
class function GetSensorManager: TSensorManager; override;
end;
TPlatformGeocoder = class(TGeocoder)
protected
class function GetGeocoderImplementer: TGeocoderClass; override;
end;
TPlatformGpsStatus = class(TGpsStatus)
protected
class function GetGpsStatusImplementer: TGpsStatusClass; override;
end;
implementation
uses
System.SysUtils, System.Generics.Collections, System.DateUtils, System.Permissions, Androidapi.AppGlue,
Androidapi.Looper, System.Math, Androidapi.Jni, Androidapi.JNIBridge, Androidapi.JNI.JavaTypes, Androidapi.JNI.Os,
Androidapi.JNI.App, Androidapi.JNI.GraphicsContentViewText, Androidapi.Helpers;
type
TAndroidGeocoder = class(TGeocoder)
private
type
TGeocoderRunnable = class(TJavaLocal, JRunnable)
private
FCoord: TLocationCoord2D;
FLGeocoder: JGeocoder;
public
constructor Create(ACoord: TLocationCoord2D; AGeocoder: JGeocoder);
procedure run; cdecl;
end;
private class var
FGeocoder: JGeocoder;
private
class constructor Create;
class destructor Destroy;
protected
class function GetGeocoderImplementer: TGeocoderClass; override;
class procedure GeocodeRequest(const AAddress: TCivicAddress); override;
class procedure GeocodeReverseRequest(const Coords: TLocationCoord2D); override;
public
class function Supported: Boolean; override;
class function Authorized: TAuthorizationType; override;
class procedure Cancel; override;
end;
type
TUIAndroidLocationSensor = class(TCustomLocationSensor)
private
FPermitted: Boolean;
FLastValue: JLocation;
FLocationManager: JLocationManager;
FAccuracy: TLocationAccuracy;
FDistance: TLocationDistance;
type
TLocationListener = class(TJavaLocal, JLocationListener)
private
FLocationSensor: TUIAndroidLocationSensor;
public
constructor Create(ALocationSensor: TUIAndroidLocationSensor);
procedure onLocationChanged(P1: JLocation); cdecl;
procedure onStatusChanged(P1: JString; P2: Integer; P3: JBundle); cdecl;
procedure onProviderEnabled(P1: JString); cdecl;
procedure onProviderDisabled(P1: JString); cdecl;
end;
TLocationRunnable = class(TJavaLocal, JRunnable)
private
FLocationManager: JLocationManager;
FListener: TLocationListener;
FProvider: JString;
public
constructor Create(ALocationManager: JLocationManager; AListener: TLocationListener; AProvider: JString);
procedure run; cdecl;
end;
TInterfaceHolder = class(TInterfacedObject, ILocationListeners)
private
FLocationSensor: TUIAndroidLocationSensor;
function GetGPSListener: JLocationListener;
function GetNetworkListener: JLocationListener;
function GetPassiveListener: JLocationListener;
public
constructor Create(const ALocationSensor: TUIAndroidLocationSensor);
end;
private
FLocationListeners: ILocationListeners;
FGPSListener: TLocationListener;
FGPSRunner: TLocationRunnable;
FNetworkListener: TLocationListener;
FNetworkRunner: TLocationRunnable;
FPassiveListener: TLocationListener;
FPassiveRunner: TLocationRunnable;
protected
function DoStart: Boolean; override;
procedure DoStop; override;
function GetLocationSensorType: TLocationSensorType; override;
function GetAvailableProperties: TCustomLocationSensor.TProperties; override;
function GetDoubleProperty(Prop: TCustomLocationSensor.TProperty): Double; override;
function GetStringProperty(Prop: TCustomLocationSensor.TProperty): string; override;
function GetSensorCategory: TSensorCategory; override;
function GetState: TSensorState; override;
function GetTimeStamp: TDateTime; override;
procedure DoOptimize; override;
function GetAuthorized: TAuthorizationType; override;
function GetAccuracy: TLocationAccuracy; override;
function GetDistance: TLocationDistance; override;
function GetPowerConsumption: TPowerConsumption; override;
procedure SetAccuracy(const Value: TLocationAccuracy); override;
procedure SetDistance(const Value: TLocationDistance); override;
procedure DoLocationChangeType; override;
function DoGetInterface(const IID: TGUID; out Obj): HResult; override;
public
constructor Create(AManager: TSensorManager); override;
function Supported: Boolean;
end;
TNativeSensor = class(TInterfacedObject, INDKSensor)
strict private
FSensorType: Integer;
FSensorManager: PASensorManager;
FNativeSensor: PASensor;
FNativeEventQueue: PASensorEventQueue;
FLastSensorEvent: ASensorEvent;
FUpdateInterval: Double;
function GetInterval: Double;
procedure SetInterval(const Value: Double);
function SensorType: Integer;
function SensorManager: PASensorManager;
function Sensor: PASensor;
function NativeEventQueue: PASensorEventQueue;
public
function GetInterface(const IID: TGUID; out Obj): HResult;
constructor Create(SensorType: Integer);
destructor Destroy; override;
function Supported: Boolean;
function LastValue: ASensorEvent;
property UpdateInterval: Double read GetInterval write SetInterval;
function DoStart: Boolean;
procedure DoStop;
function TimeStamp: Double;
end;
{
TAndroidNativeSensor = class(TCustomSensor)
strict private
FNativeSensor: TNativeSensor;
protected
function GetSensorCategory: TSensorCategory; override;
function GetState: TSensorState; override;
function GetTimeStamp: TDateTime; override;
function GetDoubleProperty(Prop: TProperty): Double; override;
public
constructor Create(AManager: TSensorManager); override;
function Supported: Boolean;
end;
}
TAndroidNativeGravitySensor = class(TCustomMotionSensor)
strict private
FNativeSensor: TNativeSensor;
protected
function GetMotionSensorType: TMotionSensorType; override;
function GetAvailableProperties: TCustomMotionSensor.TProperties; override;
function DoStart: Boolean; override;
procedure DoStop; override;
function GetSensorCategory: TSensorCategory; override;
function GetState: TSensorState; override;
function GetTimeStamp: TDateTime; override;
function GetDoubleProperty(Prop: TCustomMotionSensor.TProperty): Double; override;
function GetUpdateInterval: Double; override;
procedure SetUpdateInterval(AInterval: Double); override;
function DoGetInterface(const IID: TGUID; out Obj): HResult; override;
public
constructor Create(AManager: TSensorManager); override;
function Supported: Boolean;
end;
TAndroidNativeLinearAccelerometrSensor = class(TCustomMotionSensor)
strict private
FNativeSensor: TNativeSensor;
protected
function GetMotionSensorType: TMotionSensorType; override;
function GetAvailableProperties: TCustomMotionSensor.TProperties; override;
function DoStart: Boolean; override;
procedure DoStop; override;
function GetSensorCategory: TSensorCategory; override;
function GetState: TSensorState; override;
function GetTimeStamp: TDateTime; override;
function GetDoubleProperty(Prop: TCustomMotionSensor.TProperty): Double; override;
function GetUpdateInterval: Double; override;
procedure SetUpdateInterval(AInterval: Double); override;
function DoGetInterface(const IID: TGUID; out Obj): HResult; override;
public
constructor Create(AManager: TSensorManager); override;
function Supported: Boolean;
end;
TAndroidNativeHumiditySensor = class(TCustomEnvironmentalSensor)
strict private
FNativeSensor: TNativeSensor;
protected
function GetSensorCategory: TSensorCategory; override;
function GetState: TSensorState; override;
function GetTimeStamp: TDateTime; override;
function GetDoubleProperty(Prop: TCustomEnvironmentalSensor.TProperty): Double; override;
function GetEnvironmentalSensorType: TEnvironmentalSensorType; override;
function GetAvailableProperties: TCustomEnvironmentalSensor.TProperties; override;
function DoStart: Boolean; override;
procedure DoStop; override;
function DoGetInterface(const IID: TGUID; out Obj): HResult; override;
public
constructor Create(AManager: TSensorManager); override;
function Supported: Boolean;
end;
TAndroidNativeTemperatureSensor = class(TCustomEnvironmentalSensor)
strict private
FNativeSensor: TNativeSensor;
protected
function GetSensorCategory: TSensorCategory; override;
function GetState: TSensorState; override;
function GetTimeStamp: TDateTime; override;
function GetDoubleProperty(Prop: TCustomEnvironmentalSensor.TProperty): Double; override;
function GetEnvironmentalSensorType: TEnvironmentalSensorType; override;
function GetAvailableProperties: TCustomEnvironmentalSensor.TProperties; override;
function DoStart: Boolean; override;
procedure DoStop; override;
function DoGetInterface(const IID: TGUID; out Obj): HResult; override;
public
constructor Create(AManager: TSensorManager); override;
function Supported: Boolean;
end;
TAndroidNativeProximitySensor = class(TCustomBiometricSensor)
strict private
FNativeSensor: TNativeSensor;
protected
function GetBiometricSensorType: TBiometricSensorType; override;
function GetSensorCategory: TSensorCategory; override;
function GetState: TSensorState; override;
function GetTimeStamp: TDateTime; override;
function GetAvailableProperties: TCustomBiometricSensor.TProperties; override;
function GetDoubleProperty(Prop: TCustomBiometricSensor.TProperty): Double; override;
function DoStart: Boolean; override;
procedure DoStop; override;
function DoGetInterface(const IID: TGUID; out Obj): HResult; override;
public
constructor Create(AManager: TSensorManager); override;
function Supported: Boolean;
end;
TAndroidNativeMagneticSensor = class(TCustomOrientationSensor)
strict private
FNativeSensor: TNativeSensor;
protected
function GetUpdateInterval: Double; override;
procedure SetUpdateInterval(AInterval: Double); override;
function GetOrientationSensorType: TOrientationSensorType; override;
function GetSensorCategory: TSensorCategory; override;
function GetState: TSensorState; override;
function GetTimeStamp: TDateTime; override;
function GetAvailableProperties: TCustomOrientationSensor.TProperties; override;
function GetDoubleProperty(Prop: TCustomOrientationSensor.TProperty): Double; override;
function DoStart: Boolean; override;
procedure DoStop; override;
function DoGetInterface(const IID: TGUID; out Obj): HResult; override;
public
constructor Create(AManager: TSensorManager); override;
function Supported: Boolean;
end;
TAndroidNativePressureSensor = class(TCustomEnvironmentalSensor)
strict private
FNativeSensor: TNativeSensor;
protected
function GetSensorCategory: TSensorCategory; override;
function GetState: TSensorState; override;
function GetTimeStamp: TDateTime; override;
function GetEnvironmentalSensorType: TEnvironmentalSensorType; override;
function GetAvailableProperties: TCustomEnvironmentalSensor.TProperties; override;
function GetDoubleProperty(Prop: TCustomEnvironmentalSensor.TProperty): Double; override;
function DoStart: Boolean; override;
procedure DoStop; override;
function DoGetInterface(const IID: TGUID; out Obj): HResult; override;
public
constructor Create(AManager: TSensorManager); override;
function Supported: Boolean;
end;
TAndroidNativeLightSensor = class(TCustomLightSensor)
strict private
FNativeSensor: TNativeSensor;
protected
function GetLightSensorType: TLightSensorType; override;
function GetAvailableProperties: TCustomLightSensor.TProperties; override;
function GetDoubleProperty(Prop: TCustomLightSensor.TProperty): Double; override;
function GetSensorCategory: TSensorCategory; override;
function GetState: TSensorState; override;
function GetTimeStamp: TDateTime; override;
function DoStart: Boolean; override;
procedure DoStop; override;
function DoGetInterface(const IID: TGUID; out Obj): HResult; override;
public
constructor Create(AManager: TSensorManager); override;
function Supported: Boolean;
end;
TAndroidNativeAccelerometrSensor = class(TCustomMotionSensor)
strict private
FNativeSensor: TNativeSensor;
protected
function GetMotionSensorType: TMotionSensorType; override;
function GetAvailableProperties: TCustomMotionSensor.TProperties; override;
function DoStart: Boolean; override;
procedure DoStop; override;
function GetSensorCategory: TSensorCategory; override;
function GetState: TSensorState; override;
function GetTimeStamp: TDateTime; override;
function GetDoubleProperty(Prop: TCustomMotionSensor.TProperty): Double; override;
function GetUpdateInterval: Double; override;
procedure SetUpdateInterval(AInterval: Double); override;
function DoGetInterface(const IID: TGUID; out Obj): HResult; override;
public
constructor Create(AManager: TSensorManager); override;
function Supported: Boolean;
end;
TAndroidNativeRotationSensor = class(TCustomOrientationSensor)
private
FNativeSensor: TNativeSensor;
protected
function GetOrientationSensorType: TOrientationSensorType; override;
function GetAvailableProperties: TCustomOrientationSensor.TProperties; override;
function GetDoubleProperty(Prop: TCustomOrientationSensor.TProperty): Double; override;
function GetSensorCategory: TSensorCategory; override;
function GetUpdateInterval: Double; override;
procedure SetUpdateInterval(AInterval: Double); override;
function DoStart: Boolean; override;
procedure DoStop; override;
function GetState: TSensorState; override;
function GetTimeStamp: TDateTime; override;
function DoGetInterface(const IID: TGUID; out Obj): HResult; override;
public
constructor Create(AManager: TSensorManager); override;
function Supported: Boolean;
end;
TAndroidNativeGyroscopeSensor = class(TCustomMotionSensor)
private
FNativeSensor: TNativeSensor;
protected
function GetMotionSensorType: TMotionSensorType; override;
function GetAvailableProperties: TCustomMotionSensor.TProperties; override;
function GetDoubleProperty(Prop: TCustomMotionSensor.TProperty): Double; override;
function GetSensorCategory: TSensorCategory; override;
function GetUpdateInterval: Double; override;
procedure SetUpdateInterval(AInterval: Double); override;
function DoStart: Boolean; override;
procedure DoStop; override;
function GetState: TSensorState; override;
function GetTimeStamp: TDateTime; override;
function DoGetInterface(const IID: TGUID; out Obj): HResult; override;
public
constructor Create(AManager: TSensorManager); override;
function Supported: Boolean;
end;
type
TAndroidSensorManager = class(TPlatformSensorManager)
private
FActive: Boolean;
FSensorManager: PASensorManager;
protected
function GetCanActivate: Boolean; override;
function GetActive: Boolean; override;
public
constructor Create;
destructor Destroy; override;
procedure Activate; override;
procedure Deactivate; override;
end;
{ TAndroidSensorManager }
procedure TAndroidSensorManager.Activate;
var
Accelerator: TAndroidNativeAccelerometrSensor;
Orientation: TAndroidNativeGyroscopeSensor;
Light: TAndroidNativeLightSensor;
Pressure: TAndroidNativePressureSensor;
MagneticField: TAndroidNativeMagneticSensor;
Proximity: TAndroidNativeProximitySensor;
Rotation: TAndroidNativeRotationSensor;
Temperature: TAndroidNativeTemperatureSensor;
Humidity: TAndroidNativeHumiditySensor;
Gravity: TAndroidNativeGravitySensor;
LinearAcceleration: TAndroidNativeLinearAccelerometrSensor;
Location: TUIAndroidLocationSensor;
begin
if not Active then
begin
FActive := True;
Accelerator := TAndroidNativeAccelerometrSensor.Create(Self);
if not Accelerator.Supported then
RemoveSensor(Accelerator);
Orientation := TAndroidNativeGyroscopeSensor.Create(Self);
if not Orientation.Supported then
RemoveSensor(Orientation);
Light := TAndroidNativeLightSensor.Create(Self);
if not Light.Supported then
RemoveSensor(Light);
Pressure := TAndroidNativePressureSensor.Create(Self);
if not Pressure.Supported then
RemoveSensor(Pressure);
MagneticField := TAndroidNativeMagneticSensor.Create(Self);
if not MagneticField.Supported then
RemoveSensor(MagneticField);
Proximity := TAndroidNativeProximitySensor.Create(Self);
if not Proximity.Supported then
RemoveSensor(Proximity);
Rotation := TAndroidNativeRotationSensor.Create(Self);
if not Rotation.Supported then
RemoveSensor(Rotation);
Temperature := TAndroidNativeTemperatureSensor.Create(Self);
if not Temperature.Supported then
RemoveSensor(Temperature);
Humidity := TAndroidNativeHumiditySensor.Create(Self);
if not Humidity.Supported then
RemoveSensor(Humidity);
Gravity := TAndroidNativeGravitySensor.Create(Self);
if not Gravity.Supported then
RemoveSensor(Gravity);
LinearAcceleration := TAndroidNativeLinearAccelerometrSensor.Create(Self);
if not LinearAcceleration.Supported then
RemoveSensor(LinearAcceleration);
Location := TUIAndroidLocationSensor.Create(Self);
if not Location.Supported then
RemoveSensor(Location);
end;
end;
constructor TAndroidSensorManager.Create;
begin
inherited;
FSensorManager := ASensorManager_getInstance;
FActive := False;
end;
procedure TAndroidSensorManager.Deactivate;
var
I: Integer;
begin
FActive := False;
for I := Count - 1 downto 0 do
RemoveSensor(Sensors[I]);
end;
destructor TAndroidSensorManager.Destroy;
begin
inherited;
end;
function TAndroidSensorManager.GetActive: Boolean;
begin
Result := FActive;
end;
function TAndroidSensorManager.GetCanActivate: Boolean;
begin
Result := Assigned(FSensorManager);
end;
{ TAndroidCustomSensor }
constructor TAndroidNativeAccelerometrSensor.Create(AManager: TSensorManager);
begin
inherited;
FNativeSensor := TNativeSensor.Create(ASENSOR_TYPE_ACCELEROMETER);
end;
function TAndroidNativeAccelerometrSensor.DoGetInterface(const IID: TGUID; out Obj): HResult;
begin
Result := FNativeSensor.GetInterface(IID, Obj);
end;
function TAndroidNativeAccelerometrSensor.DoStart: Boolean;
begin
Result := FNativeSensor.DoStart;
end;
procedure TAndroidNativeAccelerometrSensor.DoStop;
begin
inherited;
FNativeSensor.DoStop;
end;
function TAndroidNativeAccelerometrSensor.GetAvailableProperties: TCustomMotionSensor.TProperties;
begin
Result := [TCustomMotionSensor.TProperty.AccelerationX, TCustomMotionSensor.TProperty.AccelerationY,
TCustomMotionSensor.TProperty.AccelerationZ]
end;
function TAndroidNativeAccelerometrSensor.GetDoubleProperty(
Prop: TCustomMotionSensor.TProperty): Double;
begin
case Prop of
TCustomMotionSensor.TProperty.AccelerationX: Result := -1 * FNativeSensor.LastValue.acceleration.x / ASENSOR_STANDARD_GRAVITY;
TCustomMotionSensor.TProperty.AccelerationY: Result := -1 * FNativeSensor.LastValue.acceleration.y / ASENSOR_STANDARD_GRAVITY;
TCustomMotionSensor.TProperty.AccelerationZ: Result := -1 * FNativeSensor.LastValue.acceleration.z / ASENSOR_STANDARD_GRAVITY;
else
Result := NaN;
end;
end;
function TAndroidNativeAccelerometrSensor.GetMotionSensorType: TMotionSensorType;
begin
Result := TMotionSensorType.Accelerometer3D;
end;
function TAndroidNativeAccelerometrSensor.GetSensorCategory: TSensorCategory;
begin
Result := TSensorCategory.Motion;
end;
function TAndroidNativeAccelerometrSensor.GetState: TSensorState;
begin
if Supported then
Result := TSensorState.Ready
else
Result := TSensorState.NoData;
end;
function TAndroidNativeAccelerometrSensor.GetTimeStamp: TDateTime;
begin
Result := FNativeSensor.TimeStamp;
end;
function TAndroidNativeAccelerometrSensor.GetUpdateInterval: Double;
begin
Result := FNativeSensor.UpdateInterval;
end;
procedure TAndroidNativeAccelerometrSensor.SetUpdateInterval(AInterval: Double);
begin
if Supported then
FNativeSensor.UpdateInterval := AInterval;
end;
function TAndroidNativeAccelerometrSensor.Supported: Boolean;
begin
Result := FNativeSensor.Supported;
end;
{ TPlatformSensorManager }
class function TPlatformSensorManager.GetSensorManager: TSensorManager;
begin
Result := TAndroidSensorManager.Create;
end;
{ TPlatformGeocoder }
class function TPlatformGeocoder.GetGeocoderImplementer: TGeocoderClass;
begin
Result := TAndroidGeocoder;
end;
{ TPlatformGpsStatus }
class function TPlatformGpsStatus.GetGpsStatusImplementer: TGpsStatusClass;
begin
Result := nil;
end;
constructor TAndroidNativeGyroscopeSensor.Create(AManager: TSensorManager);
begin
inherited;
FNativeSensor := TNativeSensor.Create(ASENSOR_TYPE_GYROSCOPE);
end;
function TAndroidNativeGyroscopeSensor.DoGetInterface(const IID: TGUID; out Obj): HResult;
begin
Result := FNativeSensor.GetInterface(IID, Obj);
end;
function TAndroidNativeGyroscopeSensor.DoStart: Boolean;
begin
Result := FNativeSensor.DoStart;
end;
procedure TAndroidNativeGyroscopeSensor.DoStop;
begin
inherited;
FNativeSensor.DoStop;
end;
function TAndroidNativeGyroscopeSensor.GetAvailableProperties: TCustomMotionSensor.TProperties;
begin
Result := [TCustomMotionSensor.TProperty.AngleAccelX, TCustomMotionSensor.TProperty.AngleAccelY, TCustomMotionSensor.TProperty.AngleAccelZ];
end;
function TAndroidNativeGyroscopeSensor.GetDoubleProperty(
Prop: TCustomMotionSensor.TProperty): Double;
begin
case Prop of
TCustomMotionSensor.TProperty.AngleAccelX: Result := FNativeSensor.LastValue.vector.x;
TCustomMotionSensor.TProperty.AngleAccelY: Result := FNativeSensor.LastValue.vector.y;
TCustomMotionSensor.TProperty.AngleAccelZ: Result := FNativeSensor.LastValue.vector.z;
else
Result := NaN;
end;
end;
function TAndroidNativeGyroscopeSensor.GetMotionSensorType: TMotionSensorType;
begin
Result := TMotionSensorType.Gyrometer3D;
end;
function TAndroidNativeGyroscopeSensor.GetSensorCategory: TSensorCategory;
begin
Result := TSensorCategory.Motion;
end;
function TAndroidNativeGyroscopeSensor.GetState: TSensorState;
begin
if FNativeSensor.Supported then
Result := TSensorState.Ready
else
Result := TSensorState.NoData;
end;
function TAndroidNativeGyroscopeSensor.GetTimeStamp: TDateTime;
begin
Result := FNativeSensor.TimeStamp;
end;
function TAndroidNativeGyroscopeSensor.GetUpdateInterval: Double;
begin
Result := FNativeSensor.UpdateInterval;
end;
procedure TAndroidNativeGyroscopeSensor.SetUpdateInterval(AInterval: Double);
begin
inherited;
FNativeSensor.UpdateInterval := AInterval;
end;
function TAndroidNativeGyroscopeSensor.Supported: Boolean;
begin
Result := FNativeSensor.Supported;
end;
{ TNativeSensor }
constructor TNativeSensor.Create(SensorType: Integer);
begin
FSensorType := SensorType;
FSensorManager := ASensorManager_getInstance;
FNativeSensor := ASensorManager_getDefaultSensor(FSensorManager, SensorType);
FNativeEventQueue := ASensorManager_createEventQueue(FSensorManager, ALooper_forThread, LOOPER_ID_USER,
nil, nil);
SetInterval(1000);
end;
destructor TNativeSensor.Destroy;
begin
ASensorManager_destroyEventQueue(FSensorManager, FNativeEventQueue);
inherited;
end;
function TNativeSensor.DoStart: Boolean;
begin
Result := True;
if Supported then
ASensorEventQueue_enableSensor(FNativeEventQueue, FNativeSensor);
end;
procedure TNativeSensor.DoStop;
begin
ASensorEventQueue_disableSensor(FNativeEventQueue,FNativeSensor);
end;
function TNativeSensor.GetInterface(const IID: TGUID; out Obj): HResult;
begin
Result := E_NOTIMPL;
if IID = INDKSensor then
begin
Pointer(Obj) := Pointer(Self);
Result := S_OK;
end;
end;
function TNativeSensor.GetInterval: Double;
begin
Result := FUpdateInterval;
end;
function TNativeSensor.LastValue: ASensorEvent;
var
SensorEvent: ASensorEvent;
begin
while ASensorEventQueue_getEvents(FNativeEventQueue, @SensorEvent,1) > 0 do
FLastSensorEvent := SensorEvent;
Result := FLastSensorEvent;
end;
function TNativeSensor.NativeEventQueue: PASensorEventQueue;
begin
Result := FNativeEventQueue;
end;
function TNativeSensor.Sensor: PASensor;
begin
Result := FNativeSensor;
end;
function TNativeSensor.SensorManager: PASensorManager;
begin
Result := FSensorManager;
end;
function TNativeSensor.SensorType: Integer;
begin
Result := FSensorType;
end;
procedure TNativeSensor.SetInterval(const Value: Double);
begin
if Supported then
begin
FUpdateInterval := Value;
ASensorEventQueue_setEventRate(FNativeEventQueue,FNativeSensor,Round(FUpdateInterval));
end;
end;
function TNativeSensor.Supported: Boolean;
begin
Result := Assigned(FNativeSensor) and Assigned(FNativeEventQueue);
end;
function TNativeSensor.TimeStamp: Double;
const
TimeScale = 1000000;
begin
Result := NaN;
if Supported then
Result := IncMilliSecond(UnixDateDelta, LastValue.timestamp div TimeScale);
end;
{ TAndroidNativeLightSensor }
constructor TAndroidNativeLightSensor.Create(AManager: TSensorManager);
begin
inherited;
FNativeSensor := TNativeSensor.Create(ASENSOR_TYPE_LIGHT);
end;
function TAndroidNativeLightSensor.DoGetInterface(const IID: TGUID; out Obj): HResult;
begin
Result := FNativeSensor.GetInterface(IID, Obj);
end;
function TAndroidNativeLightSensor.DoStart: Boolean;
begin
Result := FNativeSensor.DoStart;
end;
procedure TAndroidNativeLightSensor.DoStop;
begin
inherited;
FNativeSensor.DoStop;
end;
function TAndroidNativeLightSensor.GetAvailableProperties: TCustomLightSensor.TProperties;
begin
Result := [TCustomLightSensor.TProperty.Lux];
end;
function TAndroidNativeLightSensor.GetDoubleProperty(Prop: TCustomLightSensor.TProperty): Double;
begin
case Prop of
TCustomLightSensor.TProperty.Lux: Result := FNativeSensor.LastValue.light;
else
Result := NaN;
end;
end;
function TAndroidNativeLightSensor.GetLightSensorType: TLightSensorType;
begin
Result := TLightSensorType.AmbientLight;
end;
function TAndroidNativeLightSensor.GetSensorCategory: TSensorCategory;
begin
Result := TSensorCategory.Light;
end;
function TAndroidNativeLightSensor.GetState: TSensorState;
begin
if FNativeSensor.Supported then
Result := TSensorState.Ready
else
Result := TSensorState.NoData;
end;
function TAndroidNativeLightSensor.GetTimeStamp: TDateTime;
begin
Result := FNativeSensor.TimeStamp;
end;
function TAndroidNativeLightSensor.Supported: Boolean;
begin
Result := FNativeSensor.Supported;
end;
{ TAndroidNativePressureSensor }
constructor TAndroidNativePressureSensor.Create(AManager: TSensorManager);
begin
inherited;
FNativeSensor := TNativeSensor.Create(ASENSOR_TYPE_PRESSURE);
end;
function TAndroidNativePressureSensor.DoGetInterface(const IID: TGUID; out Obj): HResult;
begin
Result := FNativeSensor.GetInterface(IID, Obj);
end;
function TAndroidNativePressureSensor.DoStart: Boolean;
begin
Result := FNativeSensor.DoStart;
end;
procedure TAndroidNativePressureSensor.DoStop;
begin
inherited;
FNativeSensor.DoStop;
end;
function TAndroidNativePressureSensor.GetAvailableProperties: TCustomEnvironmentalSensor.TProperties;
begin
Result := [TCustomEnvironmentalSensor.TProperty.Pressure];
end;
function TAndroidNativePressureSensor.GetDoubleProperty(
Prop: TCustomEnvironmentalSensor.TProperty): Double;
begin
case Prop of
// Atmospheric pressure in hPa (millibar)
TCustomEnvironmentalSensor.TProperty.Pressure: Result := FNativeSensor.LastValue.pressure;
else
Result := NaN;
end;
end;
function TAndroidNativePressureSensor.GetEnvironmentalSensorType: TEnvironmentalSensorType;
begin
Result := TEnvironmentalSensorType.AtmosphericPressure;
end;
function TAndroidNativePressureSensor.GetSensorCategory: TSensorCategory;
begin
Result := TSensorCategory.Environmental;
end;
function TAndroidNativePressureSensor.GetState: TSensorState;
begin
if Supported then
Result := TSensorState.Ready
else
Result := TSensorState.NoData;
end;
function TAndroidNativePressureSensor.GetTimeStamp: TDateTime;
begin
Result := FNativeSensor.TimeStamp;
end;
function TAndroidNativePressureSensor.Supported: Boolean;
begin
Result := FNativeSensor.Supported;
end;
{ TAndroidNativeMagneticSensor }
constructor TAndroidNativeMagneticSensor.Create(AManager: TSensorManager);
begin
inherited;
FNativeSensor := TNativeSensor.Create(ASENSOR_TYPE_MAGNETIC_FIELD);
end;
function TAndroidNativeMagneticSensor.DoGetInterface(const IID: TGUID; out Obj): HResult;
begin
Result := FNativeSensor.GetInterface(IID, Obj);
end;
function TAndroidNativeMagneticSensor.DoStart: Boolean;
begin
Result := FNativeSensor.DoStart;
end;
procedure TAndroidNativeMagneticSensor.DoStop;
begin
inherited;
FNativeSensor.DoStop;
end;
function TAndroidNativeMagneticSensor.GetAvailableProperties: TCustomOrientationSensor.TProperties;
begin
Result := [TCustomOrientationSensor.TProperty.HeadingX, TCustomOrientationSensor.TProperty.HeadingY,
TCustomOrientationSensor.TProperty.HeadingZ];
end;
function TAndroidNativeMagneticSensor.GetDoubleProperty(
Prop: TCustomOrientationSensor.TProperty): Double;
begin
case Prop of
// All values are in micro-Tesla (uT) and measure the ambient magnetic field in the X, Y and Z axis.
TCustomOrientationSensor.TProperty.HeadingX: Result := FNativeSensor.LastValue.magnetic.x;
TCustomOrientationSensor.TProperty.HeadingY: Result := FNativeSensor.LastValue.magnetic.y;
TCustomOrientationSensor.TProperty.HeadingZ: Result := FNativeSensor.LastValue.magnetic.z;
else
Result := NaN;
end;
end;
function TAndroidNativeMagneticSensor.GetOrientationSensorType: TOrientationSensorType;
begin
Result := TOrientationSensorType.Compass3D;
end;
function TAndroidNativeMagneticSensor.GetSensorCategory: TSensorCategory;
begin
Result := TSensorCategory.Orientation;
end;
function TAndroidNativeMagneticSensor.GetState: TSensorState;
begin
if Supported then
Result := TSensorState.Ready
else
Result := TSensorState.NoData;
end;
function TAndroidNativeMagneticSensor.GetTimeStamp: TDateTime;
begin
Result := FNativeSensor.TimeStamp;
end;
function TAndroidNativeMagneticSensor.GetUpdateInterval: Double;
begin
Result := FNativeSensor.UpdateInterval;
end;
procedure TAndroidNativeMagneticSensor.SetUpdateInterval(AInterval: Double);
begin
inherited;
FNativeSensor.UpdateInterval := AInterval;
end;
function TAndroidNativeMagneticSensor.Supported: Boolean;
begin
Result := FNativeSensor.Supported;
end;
{ TAndroidNativeProximitySensor }
constructor TAndroidNativeProximitySensor.Create(AManager: TSensorManager);
begin
inherited;
FNativeSensor := TNativeSensor.Create(ASENSOR_TYPE_PROXIMITY);
end;
function TAndroidNativeProximitySensor.DoGetInterface(const IID: TGUID; out Obj): HResult;
begin
Result := FNativeSensor.GetInterface(IID, Obj);
end;
function TAndroidNativeProximitySensor.DoStart: Boolean;
begin
Result := FNativeSensor.DoStart;
end;
procedure TAndroidNativeProximitySensor.DoStop;
begin
inherited;
FNativeSensor.DoStop;
end;
function TAndroidNativeProximitySensor.GetAvailableProperties: TCustomBiometricSensor.TProperties;
begin
Result := [TCustomBiometricSensor.TProperty.HumanProximity];
end;
function TAndroidNativeProximitySensor.GetBiometricSensorType: TBiometricSensorType;
begin
Result := TBiometricSensorType.HumanProximity;
end;
function TAndroidNativeProximitySensor.GetDoubleProperty(
Prop: TCustomBiometricSensor.TProperty): Double;
begin
case Prop of
// Proximity sensor distance measured in centimeters
TCustomBiometricSensor.TProperty.HumanProximity:
begin
Result := FNativeSensor.LastValue.proximity;
end;
else
Result := NaN;
end;
end;
function TAndroidNativeProximitySensor.GetSensorCategory: TSensorCategory;
begin
Result := TSensorCategory.Biometric;
end;
function TAndroidNativeProximitySensor.GetState: TSensorState;
begin
if Supported then
Result := TSensorState.Ready
else
Result := TSensorState.NoData;
end;
function TAndroidNativeProximitySensor.GetTimeStamp: TDateTime;
begin
Result := FNativeSensor.TimeStamp;
end;
function TAndroidNativeProximitySensor.Supported: Boolean;
begin
Result := FNativeSensor.Supported;
end;
{ TAndroidNativeRotationSensor }
constructor TAndroidNativeRotationSensor.Create(AManager: TSensorManager);
begin
inherited;
FNativeSensor := TNativeSensor.Create(ASENSOR_TYPE_ROTATION_VECTOR);
end;
function TAndroidNativeRotationSensor.DoGetInterface(const IID: TGUID; out Obj): HResult;
begin
Result := FNativeSensor.GetInterface(IID, Obj);
end;
function TAndroidNativeRotationSensor.DoStart: Boolean;
begin
Result := FNativeSensor.DoStart;
end;
procedure TAndroidNativeRotationSensor.DoStop;
begin
inherited;
FNativeSensor.DoStop;
end;
function TAndroidNativeRotationSensor.GetAvailableProperties: TCustomOrientationSensor.TProperties;
begin
Result := [TCustomOrientationSensor.TProperty.TiltX, TCustomOrientationSensor.TProperty.TiltY, TCustomOrientationSensor.TProperty.TiltZ];
end;
function TAndroidNativeRotationSensor.GetDoubleProperty(Prop: TCustomOrientationSensor.TProperty): Double;
var
Tilts: ASensorVector;
function VectorToAngles(const RotationVector: ASensorVector): ASensorVector;
var
RM: array[0..8] of Double;
Len: Double;
sqX, sqY, sqZ, qXY, qZL, qXZ, qYL, qYZ, qXL: Double;
begin
sqX := RotationVector.x * RotationVector.x;
sqY := RotationVector.y * RotationVector.y;
sqZ := RotationVector.z * RotationVector.z;
Len := 1 - sqX - sqY - sqZ;
if Len > 0 then
Len := Sqrt(Len)
else
Len := 0;
sqX := 2 * sqX;
sqY := 2 * sqY;
sqZ := 2 * sqZ;
qXY := 2 * RotationVector.x * RotationVector.y;
qZL := 2 * RotationVector.z * Len;
qXZ := 2 * RotationVector.x * RotationVector.z;
qYL := 2 * RotationVector.y * Len;
qYZ := 2 * RotationVector.y * RotationVector.z;
qXL := 2 * RotationVector.x * Len;
RM[0] := 1 - sqY - sqZ;
RM[1] := qXY - qZL;
RM[2] := qXZ + qYL;
RM[3] := qXY + qZL;
RM[4] := 1 - sqX - sqZ;
RM[5] := qYZ - qXL;
RM[6] := qXZ - qYL;
RM[7] := qYZ + qXL;
RM[8] := 1 - sqX - sqY;
Result.azimuth := RadToDeg(ArcTan2( RM[1], RM[4]));
Result.pitch := RadToDeg(ArcCos( - RM[7]) - Pi / 2);
Result.roll := RadToDeg(ArcTan2( - RM[6], RM[8]));
end;
begin
Tilts := VectorToAngles(FNativeSensor.LastValue.vector);
case Prop of
TCustomOrientationSensor.TProperty.TiltX: Result := Tilts.roll;
TCustomOrientationSensor.TProperty.TiltY: Result := Tilts.pitch;
TCustomOrientationSensor.TProperty.TiltZ: Result := Tilts.azimuth;
else
Result := NaN;
end;
end;
function TAndroidNativeRotationSensor.GetOrientationSensorType: TOrientationSensorType;
begin
Result := TOrientationSensorType.Inclinometer3D;
end;
function TAndroidNativeRotationSensor.GetSensorCategory: TSensorCategory;
begin
Result := TSensorCategory.Orientation;
end;
function TAndroidNativeRotationSensor.GetState: TSensorState;
begin
if FNativeSensor.Supported then
Result := TSensorState.Ready
else
Result := TSensorState.NoData;
end;
function TAndroidNativeRotationSensor.GetTimeStamp: TDateTime;
begin
Result := FNativeSensor.TimeStamp;
end;
function TAndroidNativeRotationSensor.GetUpdateInterval: Double;
begin
Result := FNativeSensor.UpdateInterval;
end;
procedure TAndroidNativeRotationSensor.SetUpdateInterval(AInterval: Double);
begin
inherited;
FNativeSensor.UpdateInterval := AInterval;
end;
function TAndroidNativeRotationSensor.Supported: Boolean;
begin
Result := FNativeSensor.Supported;
end;
{ TAndroidNativeTemperatureSensor }
constructor TAndroidNativeTemperatureSensor.Create(AManager: TSensorManager);
begin
inherited;
FNativeSensor := TNativeSensor.Create(ASENSOR_TYPE_AMBIENT_TEMPERATURE);
end;
function TAndroidNativeTemperatureSensor.DoGetInterface(const IID: TGUID; out Obj): HResult;
begin
Result := FNativeSensor.GetInterface(IID, Obj);
end;
function TAndroidNativeTemperatureSensor.DoStart: Boolean;
begin
Result := FNativeSensor.DoStart;
end;
procedure TAndroidNativeTemperatureSensor.DoStop;
begin
inherited;
FNativeSensor.DoStop;
end;
function TAndroidNativeTemperatureSensor.GetAvailableProperties: TCustomEnvironmentalSensor.TProperties;
begin
Result := [TCustomEnvironmentalSensor.TProperty.Temperature];
end;
function TAndroidNativeTemperatureSensor.GetDoubleProperty(
Prop: TCustomEnvironmentalSensor.TProperty): Double;
begin
case Prop of
// ambient (room) temperature in degree Celsius
TCustomEnvironmentalSensor.TProperty.Temperature: Result := FNativeSensor.LastValue.temperature;
else
Result := NaN;
end;
end;
function TAndroidNativeTemperatureSensor.GetEnvironmentalSensorType: TEnvironmentalSensorType;
begin
Result := TEnvironmentalSensorType.Temperature;
end;
function TAndroidNativeTemperatureSensor.GetSensorCategory: TSensorCategory;
begin
Result := TSensorCategory.Environmental;
end;
function TAndroidNativeTemperatureSensor.GetState: TSensorState;
begin
if Supported then
Result := TSensorState.Ready
else
Result := TSensorState.NoData;
end;
function TAndroidNativeTemperatureSensor.GetTimeStamp: TDateTime;
begin
Result := FNativeSensor.TimeStamp;
end;
function TAndroidNativeTemperatureSensor.Supported: Boolean;
begin
Result := FNativeSensor.Supported;
end;
{ TAndroidNativeSensor }
constructor TAndroidNativeHumiditySensor.Create(AManager: TSensorManager);
begin
inherited;
FNativeSensor := TNativeSensor.Create(ASENSOR_TYPE_RELATIVE_HUMIDITY);
end;
function TAndroidNativeHumiditySensor.DoGetInterface(const IID: TGUID; out Obj): HResult;
begin
Result := FNativeSensor.GetInterface(IID, Obj);
end;
function TAndroidNativeHumiditySensor.DoStart: Boolean;
begin
Result := FNativeSensor.DoStart;
end;
procedure TAndroidNativeHumiditySensor.DoStop;
begin
inherited;
FNativeSensor.DoStop;
end;
function TAndroidNativeHumiditySensor.GetAvailableProperties: TCustomEnvironmentalSensor.TProperties;
begin
Result := [TCustomEnvironmentalSensor.TProperty.Humidity];
end;
function TAndroidNativeHumiditySensor.GetDoubleProperty(
Prop: TCustomEnvironmentalSensor.TProperty): Double;
begin
case Prop of
// Relative ambient air humidity in percent
TCustomEnvironmentalSensor.TProperty.Humidity: Result := FNativeSensor.LastValue.vector.v[0];
else
Result := NaN;
end;
end;
function TAndroidNativeHumiditySensor.GetEnvironmentalSensorType: TEnvironmentalSensorType;
begin
Result := TEnvironmentalSensorType.Humidity;
end;
function TAndroidNativeHumiditySensor.GetSensorCategory: TSensorCategory;
begin
Result := TSensorCategory.Environmental;
end;
function TAndroidNativeHumiditySensor.GetState: TSensorState;
begin
if Supported then
Result := TSensorState.Ready
else
Result := TSensorState.NoData;
end;
function TAndroidNativeHumiditySensor.GetTimeStamp: TDateTime;
begin
Result := FNativeSensor.TimeStamp;
end;
function TAndroidNativeHumiditySensor.Supported: Boolean;
begin
Result := FNativeSensor.Supported;
end;
{ TAndroidNativeGravitySensor }
constructor TAndroidNativeGravitySensor.Create(AManager: TSensorManager);
begin
inherited;
FNativeSensor := TNativeSensor.Create(ASENSOR_TYPE_GRAVITY);
end;
function TAndroidNativeGravitySensor.DoGetInterface(const IID: TGUID; out Obj): HResult;
begin
Result := FNativeSensor.GetInterface(IID, Obj);
end;
function TAndroidNativeGravitySensor.DoStart: Boolean;
begin
Result := FNativeSensor.DoStart;
end;
procedure TAndroidNativeGravitySensor.DoStop;
begin
inherited;
FNativeSensor.DoStop;
end;
function TAndroidNativeGravitySensor.GetAvailableProperties: TCustomMotionSensor.TProperties;
begin
Result := [TCustomMotionSensor.TProperty.AccelerationX, TCustomMotionSensor.TProperty.AccelerationY,
TCustomMotionSensor.TProperty.AccelerationZ]
end;
function TAndroidNativeGravitySensor.GetDoubleProperty(Prop: TCustomMotionSensor.TProperty): Double;
begin
case Prop of
TCustomMotionSensor.TProperty.AccelerationX: Result := -1 * FNativeSensor.LastValue.acceleration.x / ASENSOR_STANDARD_GRAVITY;
TCustomMotionSensor.TProperty.AccelerationY: Result := -1 * FNativeSensor.LastValue.acceleration.y / ASENSOR_STANDARD_GRAVITY;
TCustomMotionSensor.TProperty.AccelerationZ: Result := -1 * FNativeSensor.LastValue.acceleration.z / ASENSOR_STANDARD_GRAVITY;
else
Result := NaN;
end;
end;
function TAndroidNativeGravitySensor.GetMotionSensorType: TMotionSensorType;
begin
Result := TMotionSensorType.GravityAccelerometer3D;
end;
function TAndroidNativeGravitySensor.GetSensorCategory: TSensorCategory;
begin
Result := TSensorCategory.Motion;
end;
function TAndroidNativeGravitySensor.GetState: TSensorState;
begin
if Supported then
Result := TSensorState.Ready
else
Result := TSensorState.NoData;
end;
function TAndroidNativeGravitySensor.GetTimeStamp: TDateTime;
begin
Result := FNativeSensor.TimeStamp;
end;
function TAndroidNativeGravitySensor.GetUpdateInterval: Double;
begin
Result := FNativeSensor.UpdateInterval;
end;
procedure TAndroidNativeGravitySensor.SetUpdateInterval(AInterval: Double);
begin
inherited;
FNativeSensor.UpdateInterval := AInterval;
end;
function TAndroidNativeGravitySensor.Supported: Boolean;
begin
Result := FNativeSensor.Supported;
end;
{ TAndroidNativeLinearAccelerometrSensor }
constructor TAndroidNativeLinearAccelerometrSensor.Create(
AManager: TSensorManager);
begin
inherited;
FNativeSensor := TNativeSensor.Create(ASENSOR_TYPE_LINEAR_ACCELERATION);
end;
function TAndroidNativeLinearAccelerometrSensor.DoGetInterface(const IID: TGUID; out Obj): HResult;
begin
Result := FNativeSensor.GetInterface(IID, Obj);
end;
function TAndroidNativeLinearAccelerometrSensor.DoStart: Boolean;
begin
Result := FNativeSensor.DoStart;
end;
procedure TAndroidNativeLinearAccelerometrSensor.DoStop;
begin
inherited;
FNativeSensor.DoStop;
end;
function TAndroidNativeLinearAccelerometrSensor.GetAvailableProperties: TCustomMotionSensor.TProperties;
begin
Result := [TCustomMotionSensor.TProperty.AccelerationX, TCustomMotionSensor.TProperty.AccelerationY,
TCustomMotionSensor.TProperty.AccelerationZ]
end;
function TAndroidNativeLinearAccelerometrSensor.GetDoubleProperty(
Prop: TCustomMotionSensor.TProperty): Double;
begin
case Prop of
TCustomMotionSensor.TProperty.AccelerationX: Result := -1 * FNativeSensor.LastValue.acceleration.x / ASENSOR_STANDARD_GRAVITY;
TCustomMotionSensor.TProperty.AccelerationY: Result := -1 * FNativeSensor.LastValue.acceleration.y / ASENSOR_STANDARD_GRAVITY;
TCustomMotionSensor.TProperty.AccelerationZ: Result := -1 * FNativeSensor.LastValue.acceleration.z / ASENSOR_STANDARD_GRAVITY;
else
Result := NaN;
end;
end;
function TAndroidNativeLinearAccelerometrSensor.GetMotionSensorType: TMotionSensorType;
begin
Result := TMotionSensorType.LinearAccelerometer3D;
end;
function TAndroidNativeLinearAccelerometrSensor.GetSensorCategory: TSensorCategory;
begin
Result := TSensorCategory.Motion;
end;
function TAndroidNativeLinearAccelerometrSensor.GetState: TSensorState;
begin
if Supported then
Result := TSensorState.Ready
else
Result := TSensorState.NoData;
end;
function TAndroidNativeLinearAccelerometrSensor.GetTimeStamp: TDateTime;
begin
Result := FNativeSensor.TimeStamp;
end;
function TAndroidNativeLinearAccelerometrSensor.GetUpdateInterval: Double;
begin
Result := FNativeSensor.UpdateInterval;
end;
procedure TAndroidNativeLinearAccelerometrSensor.SetUpdateInterval(
AInterval: Double);
begin
inherited;
FNativeSensor.UpdateInterval := AInterval;
end;
function TAndroidNativeLinearAccelerometrSensor.Supported: Boolean;
begin
Result := FNativeSensor.Supported;
end;
{ TUIAndroidLocationSensor.TLocationListener }
constructor TUIAndroidLocationSensor.TLocationListener.Create(ALocationSensor: TUIAndroidLocationSensor);
begin
inherited Create;
FLocationSensor := ALocationSensor;
end;
procedure TUIAndroidLocationSensor.TLocationListener.onLocationChanged(P1: JLocation);
var
OldLocation, CurrentLocation: TLocationCoord2D;
Heading: THeading;
begin
if Assigned(FLocationSensor.FLastValue) then
OldLocation.Create(FLocationSensor.FLastValue.getLatitude,
FLocationSensor.FLastValue.getLongitude)
else
OldLocation.Create(NaN,NaN);
CurrentLocation.Create(P1.getLatitude, P1.getLongitude);
FLocationSensor.FLastValue := P1;
FLocationSensor.DoLocationChanged(OldLocation, CurrentLocation);
if p1.hasBearing then
begin
Heading.Azimuth := P1.getBearing;
FLocationSensor.DoHeadingChanged(Heading);
end;
end;
procedure TUIAndroidLocationSensor.TLocationListener.onProviderDisabled(
P1: JString);
begin
;
end;
procedure TUIAndroidLocationSensor.TLocationListener.onProviderEnabled(
P1: JString);
begin
;
end;
procedure TUIAndroidLocationSensor.TLocationListener.onStatusChanged(
P1: JString; P2: Integer; P3: JBundle);
begin
;
end;
{ TUIAndroidLocationSensor.TLocationRunnable }
constructor TUIAndroidLocationSensor.TLocationRunnable.Create(ALocationManager: JLocationManager; AListener:
TLocationListener; AProvider: JString);
begin
Inherited Create;
FLocationManager := ALocationManager;
FListener := AListener;
FProvider := AProvider;
end;
procedure TUIAndroidLocationSensor.TLocationRunnable.run;
const
cMinTime = 100;
cMinDistance = 10;
begin
FLocationManager.requestLocationUpdates( FProvider, cMinTime, cMinDistance, FListener);
end;
{ TUIAndroidLocationSensor }
constructor TUIAndroidLocationSensor.Create(AManager: TSensorManager);
begin
inherited;
FLocationManager := TJLocationManager.Wrap(TAndroidHelper.Context.getSystemService(TJContext.JavaClass.LOCATION_SERVICE));
FLocationListeners := TInterfaceHolder.Create(Self);
end;
function TUIAndroidLocationSensor.DoGetInterface(const IID: TGUID; out Obj): HResult;
begin
Result := E_NOTIMPL;
if FLastValue <> nil then
Result := FLastValue.QueryInterface(IID, Obj);
if (Result <> S_OK) and (FLocationManager <> nil) then
Result := FLocationManager.QueryInterface(IID, Obj);
if (Result <> S_OK) then
Result := FLocationListeners.QueryInterface(IID, Obj);
end;
procedure TUIAndroidLocationSensor.DoLocationChangeType;
begin
inherited;
end;
procedure TUIAndroidLocationSensor.DoOptimize;
begin
end;
function TUIAndroidLocationSensor.DoStart: Boolean;
function RunIfPossible(var ARunnable: TLocationRunnable; var AListener: TLocationListener; AProviderName: JString):
Boolean;
var
Provider: JLocationProvider;
Handler: JHandler;
begin
Result := False;
if FLocationManager.isProviderEnabled(AProviderName) then
begin
if AListener = nil then
AListener := TLocationListener.Create(Self);
Provider := FLocationManager.getProvider(AProviderName);
if Provider <> nil then
begin
ARunnable := TLocationRunnable.Create(FLocationManager, AListener, AProviderName);
if System.DelphiActivity <> nil then
TAndroidHelper.Activity.runOnUiThread(ARunnable)
else
begin
Handler := TJHandler.JavaClass.init;
Handler.post(ARunnable);
end;
Result := True;
end;
end;
end;
function RunTheBestProvider(var ARunnable: TLocationRunnable; var AListener: TLocationListener):Boolean;
var
Criteria: JCriteria;
ProviderName: JString;
begin
Result := False;
Criteria := TJCriteria.JavaClass.init;
case Round(FAccuracy) of
0..100:
Criteria.setHorizontalAccuracy(TJCriteria.JavaClass.ACCURACY_HIGH);
101..500:
Criteria.setHorizontalAccuracy(TJCriteria.JavaClass.ACCURACY_MEDIUM);
else
Criteria.setHorizontalAccuracy(TJCriteria.JavaClass.ACCURACY_LOW);
end;
ProviderName := FLocationManager.getBestProvider(Criteria, True);
if ProviderName <> nil then
Result := RunIfPossible(ARunnable, AListener, ProviderName);
end;
var
GPSStarted, NetworkStarted, PassiveStarted: Boolean;
begin
Result := False;
FPermitted := TPermissionsService.DefaultService.IsPermissionGranted(JStringToString(TJManifest_permission.JavaClass.ACCESS_FINE_LOCATION));
if FPermitted then
begin
if FAccuracy > 0 then
Result := RunTheBestProvider(FPassiveRunner, FPassiveListener)
else
begin
GPSStarted := RunIfPossible(FGPSRunner, FGPSListener, TJLocationManager.JavaClass.GPS_PROVIDER);
NetworkStarted := RunIfPossible(FNetworkRunner, FNetworkListener, TJLocationManager.JavaClass.NETWORK_PROVIDER);
PassiveStarted := RunIfPossible(FPassiveRunner, FPassiveListener, TJLocationManager.JavaClass.PASSIVE_PROVIDER);
Result := GPSStarted or NetworkStarted or PassiveStarted;
end;
end;
end;
procedure TUIAndroidLocationSensor.DoStop;
begin
inherited;
if FPassiveListener <> nil then
FLocationManager.removeUpdates(FPassiveListener);
if FNetworkListener <> nil then
FLocationManager.removeUpdates(FNetworkListener);
if FGPSListener <> nil then
FLocationManager.removeUpdates(FGPSListener);
end;
function TUIAndroidLocationSensor.GetAccuracy: TLocationAccuracy;
begin
Result := FAccuracy;
end;
function TUIAndroidLocationSensor.GetAuthorized: TAuthorizationType;
begin
Result := TAuthorizationType.atNotSpecified;
end;
function TUIAndroidLocationSensor.GetAvailableProperties: TCustomLocationSensor.TProperties;
begin
Result := [TCustomLocationSensor.TProperty.Latitude,
TCustomLocationSensor.TProperty.Longitude, TCustomLocationSensor.TProperty.Altitude,
TCustomLocationSensor.TProperty.Speed, TCustomLocationSensor.TProperty.TrueHeading];
end;
function TUIAndroidLocationSensor.GetDistance: TLocationDistance;
begin
Result := FDistance;
end;
function TUIAndroidLocationSensor.GetDoubleProperty(Prop: TCustomLocationSensor.TProperty): Double;
begin
Result := NaN;
if Assigned(FLastValue) then
case Prop of
TCustomLocationSensor.TProperty.Latitude: Result := FLastValue.getLatitude;
TCustomLocationSensor.TProperty.Longitude: Result := FLastValue.getLongitude ;
TCustomLocationSensor.TProperty.Altitude:
if FLastValue.hasAltitude then
Result := FLastValue.getAltitude;
TCustomLocationSensor.TProperty.Speed:
if FLastValue.hasSpeed then
Result := FLastValue.getSpeed;
TCustomLocationSensor.TProperty.TrueHeading:
if FLastValue.hasBearing then
Result := FLastValue.getBearing;
else
Result := NaN;
end;
end;
function TUIAndroidLocationSensor.GetLocationSensorType: TLocationSensorType;
begin
Result := TLocationSensorType.GPS;
end;
function TUIAndroidLocationSensor.GetPowerConsumption: TPowerConsumption;
begin
Result := TPowerConsumption.pcNotSpecified;
end;
function TUIAndroidLocationSensor.GetSensorCategory: TSensorCategory;
begin
Result := TSensorCategory.Location;
end;
function TUIAndroidLocationSensor.GetState: TSensorState;
begin
if Supported then
begin
if FPermitted then
Result := TSensorState.Ready
else
Result := TSensorState.AccessDenied
end
else
Result := TSensorState.NoData;
end;
function TUIAndroidLocationSensor.GetStringProperty(Prop: TCustomLocationSensor.TProperty): string;
begin
Result := '';
end;
function TUIAndroidLocationSensor.GetTimeStamp: TDateTime;
begin
if Assigned(FLastValue) then
Result := FLastValue.getTime
else
Result := 0;
end;
procedure TUIAndroidLocationSensor.SetAccuracy(const Value: TLocationAccuracy);
begin
inherited;
FAccuracy := Max(0, Value);
end;
procedure TUIAndroidLocationSensor.SetDistance(const Value: TLocationDistance);
begin
inherited;
FDistance := Value;
end;
function TUIAndroidLocationSensor.Supported: Boolean;
begin
Result := Assigned(FLocationManager);
end;
{ TAndroidGeocoder }
class function TAndroidGeocoder.Authorized: TAuthorizationType;
begin
Result := TAuthorizationType.atNotSpecified;
end;
class procedure TAndroidGeocoder.Cancel;
begin
;
end;
class constructor TAndroidGeocoder.Create;
begin
FGeocoder := TJGeocoder.JavaClass.init(TAndroidHelper.Context);
end;
class destructor TAndroidGeocoder.Destroy;
begin
end;
class procedure TAndroidGeocoder.GeocodeRequest(const AAddress: TCivicAddress);
var
I: Integer;
List: JList;
LAddress: JAddress;
JO: JObject;
begin
List := FGeocoder.getFromLocationName(StringToJString(AAddress.ToString),10);
SetLength(FGeoFwdCoords, List.size);
for I := 0 to List.size - 1 do
begin
JO := List.get(I);
LAddress := TJAddress.Wrap((JO as ILocalObject).GetObjectID);
FGeoFwdCoords[I] := TLocationCoord2D.Create(LAddress.getLatitude,LAddress.getLongitude);
end;
DoGeocode(FGeoFwdCoords);
end;
class procedure TAndroidGeocoder.GeocodeReverseRequest(const Coords: TLocationCoord2D);
var
List: JList;
LAddress: JAddress;
Addr: TCivicAddress;
JO: JObject;
I: Integer;
begin
List := FGeocoder.getFromLocation(Coords.Latitude,Coords.Longitude,1);
if List.size = 0 then
Addr := nil
else
begin
for I := 0 to List.size - 1 do
begin
JO := List.get(I);
LAddress := TJAddress.Wrap((JO as ILocalObject).GetObjectID);
Addr := FGeoRevAddress;
Addr.AdminArea := JStringToString(LAddress.getAdminArea);
Addr.CountryName := JStringToString(LAddress.getCountryName);
Addr.CountryCode := JStringToString(LAddress.getCountryCode);
Addr.Locality := JStringToString(LAddress.getLocality);
Addr.FeatureName := JStringToString(LAddress.getFeatureName);
Addr.PostalCode := JStringToString(LAddress.getPostalCode);
Addr.SubAdminArea := JStringToString(LAddress.getAdminArea);
Addr.SubLocality := JStringToString(LAddress.getSubLocality);
Addr.SubThoroughfare := JStringToString(LAddress.getSubThoroughfare);
Addr.Thoroughfare := JStringToString(LAddress.getThoroughfare);
end;
end;
DoGeocodeReverse(Addr);
end;
class function TAndroidGeocoder.GetGeocoderImplementer: TGeocoderClass;
begin
Result := Self;
end;
class function TAndroidGeocoder.Supported: Boolean;
begin
Result := False;
if Assigned(FGeocoder) then
Result := TjGeocoder.JavaClass.isPresent;
end;
{ TAndroidGeocoder.TGeocoderRunnable }
constructor TAndroidGeocoder.TGeocoderRunnable.Create(ACoord: TLocationCoord2D; AGeocoder: JGeocoder);
begin
inherited Create;
FCoord := ACoord;
FLGeocoder := AGeocoder;
end;
procedure TAndroidGeocoder.TGeocoderRunnable.run;
var
List: JList;
Address: JAddress;
Addr: TCivicAddress;
JO: JObject;
I: Integer;
begin
FLGeocoder := TJGeocoder.JavaClass.init(TAndroidHelper.Context);
List := FLGeocoder.getFromLocation(FCoord.Latitude,FCoord.Longitude,10);
if List.size = 0 then
Addr := nil
else
begin
for I := 0 to List.size - 1 do
begin
JO := List.get(I);
Address := TJAddress.Wrap((JO as ILocalObject).GetObjectID);
Addr := FGeoRevAddress;
Addr.AdminArea := JStringToString(Address.getAdminArea);
Addr.CountryName := JStringToString(Address.getCountryName);
Addr.CountryCode := JStringToString(Address.getCountryCode);
Addr.Locality := JStringToString(Address.getLocality);
Addr.FeatureName := JStringToString(Address.getFeatureName);
Addr.PostalCode := JStringToString(Address.getPostalCode);
Addr.SubAdminArea := JStringToString(Address.getAdminArea);
Addr.SubLocality := JStringToString(Address.getSubLocality);
Addr.SubThoroughfare := JStringToString(Address.getSubThoroughfare);
Addr.Thoroughfare := JStringToString(Address.getThoroughfare);
end;
end;
DoGeocodeReverse(Addr);
end;
{ TUIAndroidLocationSensor.TInterfaceHolder }
constructor TUIAndroidLocationSensor.TInterfaceHolder.Create(
const ALocationSensor: TUIAndroidLocationSensor);
begin
FLocationSensor := ALocationSensor;
end;
function TUIAndroidLocationSensor.TInterfaceHolder.GetGPSListener: JLocationListener;
begin
Result := FLocationSensor.FGPSListener;
end;
function TUIAndroidLocationSensor.TInterfaceHolder.GetNetworkListener: JLocationListener;
begin
Result := FLocationSensor.FNetworkListener;
end;
function TUIAndroidLocationSensor.TInterfaceHolder.GetPassiveListener: JLocationListener;
begin
Result := FLocationSensor.FPassiveListener;
end;
initialization
end.
|
{ Routines that manipulate CAN devices lists.
}
module can_devlist;
define can_devlist_create;
define can_devlist_add;
define can_devlist_del;
define can_devlist_get;
%include 'can2.ins.pas';
{
********************************************************************************
*
* Subroutine CAN_DEVLIST_CREATE (MEM, DEVS)
*
* Create and initialize a new blank CAN devices list. MEM is the parent
* memory context. A new memory context subordinate to it will be created, and
* all dynamic memory of the list will be allocated under the new subordinate
* memory context. The list is returned initialized and ready for use, but
* empty.
}
procedure can_devlist_create ( {create new CAN devices list}
in out mem: util_mem_context_t; {parent context for dynamic memory}
out devs: can_devs_t); {returned initialized and empty list}
val_param;
begin
util_mem_context_get (mem, devs.mem_p); {make private memory context for the list}
devs.n := 0; {init to no list entries}
devs.list_p := nil;
devs.last_p := nil;
end;
{
********************************************************************************
*
* Subroutine CAN_DEVLIST_ADD (DEVS, DEV_P)
*
* Create a new entry to the CAN devices list DEVS. The new entry will be
* initialized to default or benign values and added to the end of the list.
* DEV_P will be returned pointing to the contents of the new entry.
}
procedure can_devlist_add ( {add entry to CAN devices list}
in out devs: can_devs_t; {list to add entry to}
out dev_p: can_dev_p_t); {returned pointing to new entry}
val_param;
var
ent_p: can_dev_ent_p_t; {pointer to new list entry}
ii: sys_int_machine_t; {scratch integer and loop counter}
begin
util_mem_grab ( {allocate memory for the new entry}
sizeof(ent_p^), devs.mem_p^, false, ent_p);
{
* Initialize the entry data.
}
ent_p^.next_p := nil; {new entry will be at end of list}
ent_p^.dev.name.max := size_char(ent_p^.dev.name.str);
ent_p^.dev.name.len := 0;
for ii := 1 to ent_p^.dev.name.max do begin
ent_p^.dev.name.str[ii] := chr(0);
end;
ent_p^.dev.path.max := size_char(ent_p^.dev.path.str);
ent_p^.dev.path.len := 0;
for ii := 1 to ent_p^.dev.path.max do begin
ent_p^.dev.path.str[ii] := chr(0);
end;
ent_p^.dev.nspec := 0;
for ii := 0 to can_spec_last_k do begin {init all device spec bytes to zero}
ent_p^.dev.spec[ii] := 0;
end;
ent_p^.dev.devtype := can_dev_none_k;
{
* Link the new entry to the end of the list.
}
if devs.last_p = nil
then begin {the list is empty}
devs.list_p := ent_p;
end
else begin {there is at least one previous entry}
devs.last_p^.next_p := ent_p;
end
;
devs.last_p := ent_p;
devs.n := devs.n + 1; {count one more entry in the list}
dev_p := addr(ent_p^.dev); {return pointer to new list entry contents}
end;
{
********************************************************************************
*
* Subroutine CAN_DEVLIST_DEL (DEVS)
*
* Delete the CAN devices list DEVS. All system resources allocated to the
* list are released. DEVS can not be used after this call except to pass to
* CAN_DEVLIST_CREATE to create a new list.
}
procedure can_devlist_del ( {delete CAN devices list}
in out devs: can_devs_t); {list to delete, returned unusable}
val_param;
begin
util_mem_context_del (devs.mem_p); {deallocate all dynamic memory used by the list}
devs.n := 0;
devs.list_p := nil;
devs.last_p := nil;
end;
{
********************************************************************************
*
* Subroutine CAN_DEVLIST_GET (MEM, DEVS)
*
* Get the list of all CAN devices known to be availble to this system thru
* this library. MEM is the parent memory context. A subordinate memory
* context will be created, which will be used for all dynamically allocated
* list memory. This subordinate memory context will be deleted when the list
* is deleted.
}
procedure can_devlist_get ( {get list of known CAN devices available to this system}
in out mem: util_mem_context_t; {parent context for list memory}
out devs: can_devs_t); {returned list of devices}
val_param;
begin
can_devlist_create (mem, devs); {create a new empty CAN devices list}
{
* Call the ADDLIST entry point for each driver. If a new driver is added that
* supports enumeratable devices, a call to its ADDLIST entry point must be
* added here.
}
can_addlist_usbcan (devs);
end;
|
unit IdUDPClient;
interface
uses
IdUDPBase;
type
TIdUDPClient = class(TIdUDPBase)
protected
public
procedure Send(AData: string); overload;
procedure SendBuffer(var ABuffer; const AByteCount: integer); overload;
published
property Host: string read FHost write FHost;
property Port: Integer read FPort write FPort;
property ReceiveTimeout;
end;
implementation
procedure TIdUDPClient.Send(AData: string);
begin
Send(Host, Port, AData);
end;
procedure TIdUDPClient.SendBuffer(var ABuffer; const AByteCount: integer);
begin
SendBuffer(Host, Port, ABuffer, AByteCount);
end;
end.
|
unit record_properties_3;
interface
implementation
type
TRec = record
private
FData: Int32;
public
property Data: Int32 read FData;
function Get: Int32;
end;
var R: TRec;
G: Int32;
function TRec.Get: Int32;
begin
Result := Data;
end;
procedure Test;
begin
R.FData := 12;
G := R.Get();
end;
initialization
Test();
finalization
Assert(G = 12);
end. |
unit ncEndereco;
interface
uses sysutils, classes, DB;
type
TncEndereco = class
enID : TGUID;
enEndereco : String;
enEndereco2 : String;
enCidade : String;
enUF : String;
enBairro : String;
enCEP : String;
enNumero : String;
enCodMun : String;
enDest : String;
enPais : String;
enObs : String;
enPos : Byte;
enCliente : Cardinal;
enDefCad : Boolean;
enDefCobr : Boolean;
enDefEntrega : Boolean;
constructor Create;
function Resumo: String;
function Vazio: Boolean;
function ResumoEntrega(L: TncEndereco): String;
function ResumoLinhaUnica: String;
function is_br: Boolean;
function is_foreign: Boolean;
function NFeOk: Boolean;
function Alterou(B: TncEndereco): Boolean;
procedure Assign(B: TncEndereco);
procedure Clear;
procedure SaveToDataset(D: TDataset);
procedure LoadFromDataset(D: TDataset);
end;
implementation
{ TncEndereco }
uses ncGuidUtils, ncClassesBase;
function TncEndereco.Alterou(B: TncEndereco): Boolean;
begin
Result :=
(enEndereco<>B.enEndereco) or
(enEndereco2<>B.enEndereco) or
(enCidade<>B.enCidade) or
(enUF<>B.enUF) or
(enBairro<>B.enBairro) or
(enCEP<>B.enCEP) or
(enNumero<>B.enNumero) or
(enCodMun<>B.enCodMun) or
(enDest<>B.enDest) or
(enPais<>B.enPais) or
(enPos<>B.enPos) or
(enCliente<>B.enCliente) or
(enObs<>B.enObs) or
(enDefCad<>B.enDefCad) or
(enDefCobr<>B.enDefCobr) or
(enDefEntrega<>B.enDefEntrega);
end;
procedure TncEndereco.Assign(B: TncEndereco);
begin
enID := B.enID;
enEndereco := B.enEndereco;
enEndereco2 := B.enEndereco2;
enCidade := B.enCidade;
enUF := B.enUF;
enBairro := B.enBairro;
enCEP := B.enCEP;
enNumero := B.enNumero;
enCodMun := B.enCodMun;
enDest := B.enDest;
enPais := B.enPais;
enPos := B.enPos;
enCliente := B.enCliente;
enObs := B.enObs;
enDefCad := B.enDefCad;
enDefCobr := B.enDefCobr;
enDefEntrega := B.enDefEntrega;
end;
procedure TncEndereco.Clear;
begin
enID := TGuidEx.New;
enEndereco := '';
enEndereco2 := '';
enCidade := '';
enUF := '';
enBairro := '';
enCEP := '';
enNumero := '';
enCodMun := '';
enDest := '';
enPais := gConfig.PaisNorm;
enObs := '';
enCliente := 0;
enPos := 0;
enDefCad := False;
enDefCobr := False;
enDefEntrega := False;
end;
constructor TncEndereco.Create;
begin
inherited;
Clear;
end;
function TncEndereco.is_br: Boolean;
begin
Result := SameText('BR', enPais);
end;
function TncEndereco.is_foreign: Boolean;
begin
Result := not SameText(gConfig.PaisNorm, enPais);
end;
procedure TncEndereco.LoadFromDataset(D: TDataset);
var F: TField;
begin
if not D.FieldByName('endereco_id').IsNull then
enID := TGuidEx.FromString(D.FieldByName('endereco_id').AsString);
if TGuidEx.IsEmpty(enID) then enID := TGuidEx.New;
F := D.FindField('cliente_id');
if F<>nil then
enCliente := F.AsLongWord else
enCliente := D.FieldByName('id').AsLongWord;
enEndereco := D.FieldByName('endereco').AsString;
enEndereco2 := D.FieldByName('endereco2').AsString;
enCidade := D.FieldByName('cidade').AsString;
enUF := D.FieldByName('uf').AsString;
enBairro := D.FieldByName('bairro').AsString;
enCEP := D.FieldByName('CEP').AsString;
enNumero := D.FieldByName('end_numero').AsString;
enCodMun := D.FieldByName('end_CodMun').AsString;
enDest := D.FieldByName('end_dest').AsString;
enPais := D.FieldByName('pais').AsString;
if enPais='' then enPais := gConfig.PaisNorm;
enObs := D.FieldByName('end_obs').AsString;
F := D.FindField('pos');
if Assigned(F) then
enPos := F.AsInteger else
enPos := 0;
F := D.FindField('def_cad');
if Assigned(F) then
enDefCad := F.AsBoolean else
enDefCad := True;
F := D.FindField('def_cob');
if Assigned(F) then
enDefCobr := F.AsBoolean else
enDefCobr := True;
F := D.FindField('def_end');
if Assigned(F) then
enDefEntrega := F.AsBoolean else
enDefEntrega := True;
end;
function TncEndereco.NFeOk: Boolean;
begin
if is_br then begin
Result := (Trim(enEndereco)>'') and
(Trim(enNumero)>'') and
(SoDig(enCodMun)>'') and
(Trim(enCidade)>'') and
(Length(SoDig(enCEP))=8) and
(Trim(enUF)>'');
end else begin
Result := (Trim(enEndereco)>'') and
(Trim(enCidade)>'');
end;
end;
function TncEndereco.Resumo: String;
procedure Add(S: String; aSep: String = sLinebreak);
begin
if Trim(S)='' then Exit;
if Result>'' then Result := Result + aSep;
Result := Result + Trim(S);
end;
begin
Result := '';
Add(enDest);
if is_br then
Add(enEndereco+' '+Trim(enNumero)+' '+Trim(enEndereco2))
else begin
Add(enEndereco);
Add(enEndereco2);
end;
Add(enBairro);
Add(enCidade);
Add(enUF, ', ');
Add(enCEP, ', ');
if is_br and (enCodMun>'') then
Add('IBGE: '+enCodMun, ', ');
Add(enObs);
end;
function TncEndereco.ResumoEntrega(L: TncEndereco): String;
procedure Add(S: String; aSep: String = sLinebreak);
begin
if Trim(S)='' then Exit;
if Result>'' then Result := Result + aSep;
Result := Result + Trim(S);
end;
begin
Result := '';
Add(enDest);
if is_br then
Add(enEndereco+' '+Trim(enNumero)+' '+Trim(enEndereco2))
else begin
Add(enEndereco);
Add(enEndereco2);
end;
Add(enBairro);
if (L=nil) or (not SameText(enCidade, L.enCidade)) then begin
Add(enCidade);
Add(enUF, '-');
end;
Add(enObs);
end;
function TncEndereco.ResumoLinhaUnica: String;
procedure Add(S: String; aSep: String = ', ');
begin
if Trim(S)='' then Exit;
if Result>'' then Result := Result + aSep;
Result := Result + Trim(S);
end;
begin
Result := '';
if is_br then
Add(enEndereco+' '+Trim(enNumero)+' '+Trim(enEndereco2))
else begin
Add(enEndereco);
Add(enEndereco2, ' ');
end;
Add(enBairro);
Add(enCidade);
Add(enUF, '-');
end;
procedure TncEndereco.SaveToDataset(D: TDataset);
var F: TField;
begin
D.FieldByName('endereco_id').AsString := TGuidEx.ToString(enID);
F := D.FindField('cliente_id');
if F<>nil then
F.AsLongWord := enCliente else
D.FieldByName('id').AsLongWord := enCliente;
D.FieldByName('endereco').AsString := enEndereco;
D.FieldByName('endereco2').AsString := enEndereco2;
D.FieldByName('cidade').AsString := enCidade;
D.FieldByName('uf').AsString := enUF;
D.FieldByName('bairro').AsString := enBairro;
D.FieldByName('CEP').AsString := enCEP;
D.FieldByName('end_numero').AsString := enNumero;
D.FieldByName('end_CodMun').AsString := enCodMun;
D.FieldByName('end_dest').AsString := enDest;
D.FieldByName('pais').AsString := enPais;
D.FieldByName('end_obs').AsString := enObs;
F := D.FindField('pos');
if Assigned(F) then
F.AsInteger := enPos;
F := D.FindField('def_cad');
if Assigned(F) then
F.AsBoolean := enDefCad;
F := D.FindField('def_cob');
if Assigned(F) then
F.AsBoolean := enDefCobr;
F := D.FindField('def_end');
if Assigned(F) then
F.AsBoolean := enDefEntrega;
end;
function TncEndereco.Vazio: Boolean;
begin
Result := (enEndereco='') and (enEndereco2='') and (enCidade='') and (enUF='') and (enBairro='') and (enCEP='') and (enNumero='') and (enDest='');
end;
end.
|
unit FMXBI.GridForm;
interface
{
A generic reusable / embeddable form with a BIGrid and a Navigator toolbar
}
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types,
FMX.Controls, FMX.Forms,
{$IF CompilerVersion>25}
FMX.Graphics,
{$ENDIF}
{$IF CompilerVersion<=27}
{$DEFINE HASFMX20}
{$ENDIF}
{$IFNDEF HASFMX20}
FMX.Controls.Presentation,
{$ENDIF}
FMX.Dialogs, Data.Bind.Controls, Data.DB, FMX.Layouts,
Fmx.Bind.Navigator, FMX.Grid, FMXBI.Grid, BI.DataItem, Data.Bind.Components,
Data.Bind.DBScope, FMX.StdCtrls;
type
TBIGridForm = class(TForm)
Layout1: TLayout;
BindNavigator1: TBindNavigator;
Layout2: TLayout;
LRow: TLabel;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
FOnDataChange : TNotifyEvent;
procedure DataChange(Sender: TObject; Field: TField);
procedure SetDataItem(const AData:TDataItem);
public
{ Public declarations }
Grid : TBIGrid;
class function Embedd(const AOwner:TComponent; const AParent:TControl;
const AData:TDataItem):TBIGridForm; static;
procedure MakeEditable;
class function Present(const AOwner:TComponent; const AData:TDataItem):TModalResult; overload;
property OnDataChange:TNotifyEvent read FOnDataChange write FOnDataChange;
end;
implementation
|
unit Test.Threads.RegularControl;
interface
uses SysUtils, Classes, GMGlobals, Windows, TestFrameWork, Threads.RegularControl, Threads.Pool,
Threads.ReqSpecDevTemplate, RequestThreadsContainer, Threads.TCP, GMConst, GM485, GMSqlQuery, Threads.GMCOM;
type
TMultiObjectRequestThreadForTest = class(TMultiObjectRequestThread)
protected
procedure SafeExecute(); override;
procedure UpdateThreadList; override;
constructor Create();
end;
TRequestTCPDevicesForTest = class(TRequestTCPDevices)
protected
procedure SafeExecute; override;
end;
TRequestCOMDevicesForTest = class(TRequestCOMDevices)
protected
procedure SafeExecute; override;
end;
TRequestThreadsContainerForTest = class(TRequestThreadsContainer)
protected
procedure CreateThreads; override;
end;
TRegularControlThreadForTest = class(TRegularControl)
public
procedure Execute(); override;
end;
TRegularControlThreadTest = class(TTestCase)
private
thr: TRegularControlThreadForTest;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure CheckTestData();
end;
implementation
{ TRegularControlThreadForTest }
procedure TRegularControlThreadForTest.Execute;
begin
// Ничего не делаем, просто выходим
end;
{ TRegularControlThreadTest }
type TRequestTCPDevicesHack = class(TRequestTCPDevices);
procedure TRegularControlThreadTest.CheckTestData;
var thrReq: TRequestSpecDevices;
req: TSpecDevReqListItem;
origin: ArrayOfByte;
i: int;
begin
thr.Process();
Check(ThreadsContainer[0] is TMultiObjectRequestThreadForTest);
thrReq := TRequestSpecDevices(TMultiObjectRequestThreadForTest(ThreadsContainer[0]).ThreadPool[0]);
Check(thrReq is TRequestTCPDevices);
TRequestTCPDevicesHack(thrReq).LoadCommands();
Check(TRequestTCPDevicesForTest(thrReq).RequestList.Count = 2);
// само значение
req := TRequestTCPDevicesForTest(thrReq).RequestList[0];
origin := TextNumbersStringToArray('00 00 00 00 00 06 01 06 01 02 27 10');
for i := 0 to High(origin) do
CheckEquals(origin[i], req.ReqDetails.buf[i], 'Cmd: ' + IntToStr(i));
// возраст значения. если падает тест - прогнать testdb.sql
req := TRequestTCPDevicesForTest(thrReq).RequestList[1];
origin := TextNumbersStringToArray('00 00 00 00 00 06 01 06 02 BB 00 00');
for i := 0 to High(origin) do
CheckEquals(origin[i], req.ReqDetails.buf[i], 'Age: ' + IntToStr(i));
end;
procedure TRegularControlThreadTest.SetUp;
begin
inherited;
thr := TRegularControlThreadForTest.Create();
ThreadsContainer := TRequestThreadsContainerForTest.Create();
ThreadsContainer.Terminate();
ExecSQL('update CurrVals set UTime = ' + IntToStr(NowGM()) + ' where ID_Prm = 1');
end;
procedure TRegularControlThreadTest.TearDown;
begin
inherited;
thr.Free();
FreeAndNil(ThreadsContainer);
end;
{ TRequestThreadsContainerForTest }
procedure TRequestThreadsContainerForTest.CreateThreads;
begin
Add(TMultiObjectRequestThreadForTest.Create());
end;
{ TRequestTCPDevicesForTest }
procedure TRequestTCPDevicesForTest.SafeExecute;
begin
end;
{ TMultiObjectRequestThreadForTest }
constructor TMultiObjectRequestThreadForTest.Create;
begin
inherited;
UpdateThreadList();
end;
procedure TMultiObjectRequestThreadForTest.SafeExecute;
begin
end;
procedure TMultiObjectRequestThreadForTest.UpdateThreadList;
begin
ThreadPool.Add(TRequestTCPDevicesForTest.Create(4)); // ID_Obj = 4 для теста управления по TCP
ThreadPool.Add(TRequestCOMDevicesForTest.Create(6)); // ID_Obj = 6 для теста управления по COM
end;
{ TRequestCOMDevicesForTest }
procedure TRequestCOMDevicesForTest.SafeExecute;
begin
end;
initialization
RegisterTest('GMIOPSrv/Threads', TRegularControlThreadTest.Suite);
end.
|
unit AppConstants;
interface
type TForms = (fmNone, fmClientMain, fmClientList, fmGroupList, fmEmployerList,
fmBanksList, fmDesignationList, fmLoanClassList, fmLoanMain,
fmLoanList, fmCompetitorList, fmPurposeList,fmLoanTypeList,
fmAcctTypeList, fmLoanCancelReasonList, fmLoanRejectReasonList,
fmSettings, fmPaymentMain, fmPaymentList, fmWithdrawalList,
fmChargeTypeList,fmInfoSourceList,fmLoanCloseReasonList,
fmMaintenanceDrawer, fmSecurityDrawer, fmLineItemList,
fmAccountClassList,fmAccountTitlesList,fmSubsidiaryTypeList,
fmSubsidiaryList,fmExpenseMain);
{
Entity types
CL = CLIENT
LL = LANDLORD
IH = IMMEDIATE HEAD
RF = REFEREE
CK = COMAKER
RP = RECIPIENT
}
type TEntityTypes = (CL,LL,IH,RF,CK,RP);
{
Payment types
PRN = PRINCIPAL
INT = INTEREST
PEN = PENALTY
}
type TPaymentTypes = (PRN,INT,PEN);
{
Event objects
LON = LOAN
PAY = PAYMENT
}
type TEventObjects = (LON,PAY,ITR,REB);
{
Ledger record status
OPN = OPEN
CLS = CLOSE
CNL = CANCEL
PND = PENDING
}
type TLedgerRecordStatus = (OPN,CLS,CNL,PND);
{
Case types
ITS = INTEREST
PRC = PRINCIPAL
PNT = PENALTY
RBT = REBATE
}
type TCaseTypes = (ITS,PRC,PNT,RBT);
{
Interest status (INTEREST TABLE)
P = PENDING
T = POSTED
D = DISREGARD
}
type TInterestStatus = (P,T,D);
{
Interest source (INTEREST TABLE)
SYS = SYSTEM
PYT = PAYMENT
}
type TInterestSource = (SYS,PYT);
implementation
end.
|
PROCEDURE ReadDigit(VAR InF: TEXT; VAR Digit: INTEGER);
VAR
Ch: CHAR;
BEGIN{ReadDigit}
Digit := -1;
IF NOT EOLN(InF)
THEN
BEGIN
READ(InF ,Ch);
IF Ch = '0' THEN Digit := 0;
IF Ch = '1' THEN Digit := 1;
IF Ch = '2' THEN Digit := 2;
IF Ch = '3' THEN Digit := 3;
IF Ch = '4' THEN Digit := 4;
IF Ch = '5' THEN Digit := 5;
IF Ch = '6' THEN Digit := 6;
IF Ch = '7' THEN Digit := 7;
IF Ch = '8' THEN Digit := 8;
IF Ch = '9' THEN Digit := 9
END
END;{ReadDigit}
PROCEDURE ReadNumber(VAR InF: TEXT; VAR Number: INTEGER);
VAR
Digit: INTEGER;
BEGIN{ReadNumber}
Number := 0;
ReadDigit(InF, Digit);
WHILE (Digit <> -1 ) AND (Number <> -1)
DO
BEGIN
IF (MAXINT DIV 10 < Number) OR (MAXINT DIV 10 = Number) AND (MAXINT MOD 10 < Digit)
THEN
Number := -1
ELSE
BEGIN
Number := Number * 10;
Number := Number + Digit;
END;
ReadDigit(InF, Digit)
END;
END;{ReadNumber}
VAR
Number: INTEGER;
BEGIN
ReadNumber(INPUT, Number);
WRITELN(Number)
END.
|
unit Code02.Jacek.DaylightTimeZone;
interface
{
@theme: Delphi Challenge
@subject: #02 Daylight Time Zone
@author: Bogdan Polak
@date: 2020-05-16 21:00
}
{
Zadaniem jest wydobycie z treści strony https://www.timeanddate.com/
informacji o tym czy w podanej strefie czasowej wykonuje się przesuniecie
czasu podstawowego (zimowego) na czas letni. Daylight Saving Time
Funkcja:
* IsDaylightSaving - powinna sprawdzić to dla podanego roku (year) i dla podanego obszaru (area).
Jeśli przesuniecie czasu jest aktywne to funkcje:
* GetDaylightStart
* GetDaylightEnd
powinny zwrócić informacje w jakim dniu i o jakiej godzinie następuje przesuniecie czasu.
Dla przykładu przy danych:
- area: poland/warsaw
- year: 2015
Powinna zostać wywołana strona:
https://www.timeanddate.com/time/change/poland/warsaw?year=2015
i na podstawie analizy treści strony WWW należy zwrócić podane wyżej wyniki
Aby nie powtarzać wielokrotnego pobierania danych dla tych samych stron
należy przechować poprzednie wyniki, aby nie pobierać wielokrotnie tych
samych danych.
Uwaga!
Wymagane jest użycie `TMyHttpGet.GetWebsiteContent` do pobrania zawartości strony
Przykład wywołania:
aHtmlPageContent := TMyHttpGet.GetWebsiteContent(‘http://delphi.pl/’);
}
function IsDaylightSaving(const area: string; year: Word): boolean;
function GetDaylightStart(const area: string; year: Word): TDateTime;
function GetDaylightEnd(const area: string; year: Word): TDateTime;
implementation
uses
System.RegularExpressions,
System.StrUtils,
System.SysUtils,
System.Generics.Collections,
Code02.HttpGet;
type
TTimeAreaPoint = type string;
TTimeAreaPointHelper = record helper for TTimeAreaPoint
protected
function GetYear(): Word;
procedure SetYear(const aValue: Word);
function GetArea(): string;
procedure SetArea(const aValue: string);
public
property Area: string read GetArea write SetArea;
property Year: Word read GetYear write SetYear;
end;
TDayligtSavingPeriod = record
StartPeriod : TDateTime;
EndPeriod : TDateTime;
end;
TDaylightSavingMatrix = record
private
const cMonthNames : array of string = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'];
const cReg = 'mgt0.*?reach<br>.*?([0-9]+[^0-9]*?[0-9]+).*?<strong>(.*?)</strong>';
const cNotDST = 'Daylight Saving Time (DST) Not Observed in Year ';
const cURL = 'https://www.timeanddate.com/time/change/%s?year=%d';
class var cfDLSMatrix : TDictionary<TTimeAreaPoint, TDayligtSavingPeriod>;
class function ConvertDateTime(const aDate, aTime : string): TDateTime; static;
class function ImportPeriod(const aArea: string; aYear: Word): TDayligtSavingPeriod; static;
public
class function GetPeriod(const aArea: string; aYear: Word): TDayligtSavingPeriod; static;
class constructor Create();
class destructor Destroy();
end;
function IsDaylightSaving(const area: string; year: Word): boolean;
var
lPeriod: TDayligtSavingPeriod;
begin
lPeriod := TDaylightSavingMatrix.GetPeriod(area, year);
Result := (lPeriod.StartPeriod > 0) and (lPeriod.EndPeriod > 0);
end;
function GetDaylightStart(const area: string; year: Word): TDateTime;
begin
Result := TDaylightSavingMatrix.GetPeriod(area, year).StartPeriod;
end;
function GetDaylightEnd(const area: string; year: Word): TDateTime;
begin
Result := TDaylightSavingMatrix.GetPeriod(area, year).EndPeriod;
end;
function TTimeAreaPointHelper.GetArea(): string;
begin
if Length(Self) < 1 then
begin
Result := '';
end else
begin
Result := Copy(Self, 2);
end;
end;
function TTimeAreaPointHelper.GetYear(): Word;
begin
if Length(self) = 0 then
begin
Result := 0;
end else
begin
Result := Word(Self[1]);
end;
end;
procedure TTimeAreaPointHelper.SetArea(const aValue: string);
begin
if Length(Self) = 0 then
begin
Self := #0 + aValue;
end else
begin
Self := Self[1] + aValue;
end;
end;
procedure TTimeAreaPointHelper.SetYear(const aValue: Word);
begin
if Length(Self) = 0 then
begin
SetLength(Self, 1);
end;
Self[1] := Char(aValue);
end;
class constructor TDaylightSavingMatrix.Create();
begin
cfDLSMatrix := TDictionary<TTimeAreaPoint, TDayligtSavingPeriod>.Create();
end;
class destructor TDaylightSavingMatrix.Destroy();
begin
cfDLSMatrix.Free;
end;
class function TDaylightSavingMatrix.ConvertDateTime(const aDate, aTime : string): TDateTime;
var
i: Integer;
lDateItems: TArray<string>;
lDayNumber: Integer;
lMonthName: string;
lMonthNumber: Integer;
lName: string;
lYearNumber: Integer;
begin
// 7 November 2021
// 03:00:00
lDateItems := SplitString(aDate.ToLower, ' ');
lDayNumber := StrToInt(lDateItems[0]);
lYearNumber := StrToInt(lDateItems[2]);
lMonthName := lDateItems[1];
lMonthNumber := 0;
for i := 0 to 11 do
begin
lName := cMonthNames[i];
if SameText(lName, lMonthName) then
begin
lMonthNumber := i + 1;
Break;
end;
end;
if lMonthNumber = 0 then
begin
raise Exception.CreateFmt('Bad input data: %s - %s', [aDate, aTime]);
end;
Result := EncodeDate(lYearNumber, lMonthNumber, lDayNumber) + StrToTime(aTime);
end;
class function TDaylightSavingMatrix.GetPeriod(const aArea: string; aYear: Word): TDayligtSavingPeriod;
var
lArea: string;
lPoint : TTimeAreaPoint;
begin
lArea := aArea.ToLower;
lPoint.Area := lArea;
lPoint.Year := aYear;
if cfDLSMatrix.TryGetValue(lPoint, Result) then
begin
Exit;
end;
Result := ImportPeriod(lArea, aYear);
cfDLSMatrix.Add(lPoint, Result);
end;
class function TDaylightSavingMatrix.ImportPeriod(const aArea: string; aYear: Word): TDayligtSavingPeriod;
var
lBody: string;
lDate: string;
lEndDateTime: TDateTime;
lMatches: TMatchCollection;
lStartDateTime: TDateTime;
lTime: string;
lURL : string;
begin
lURL := Format(cURL, [aArea, aYear]);
lBody := TMyHttpGet.GetWebsiteContent(lURL);
if Pos(cNotDST, lBody) > 0 then
begin
Result.StartPeriod := 0;
Result.EndPeriod := 0;
end else
begin
lMatches := TRegEx.Matches(lBody, cReg, [roIgnoreCase, roMultiLine]);
if lMatches.Count = 2 then
begin
if lMatches.Item[0].Groups.Count = 3 then
begin
lDate := lMatches.Item[0].Groups[1].Value;
lTime := lMatches.Item[0].Groups[2].Value;
lStartDateTime := ConvertDateTime(lDate, lTime);
end else
begin
raise Exception.Create('Unknown website content');
end;
if lMatches.Item[1].Groups.Count = 3 then
begin
lDate := lMatches.Item[1].Groups[1].Value;
lTime := lMatches.Item[1].Groups[2].Value;
lEndDateTime := ConvertDateTime(lDate, lTime);
end else
begin
raise Exception.Create('Unknown website content');
end;
end else
begin
raise Exception.CreateFmt('Bad input data: %s: %d', [aArea, aYear]);
end;
Result.StartPeriod := lStartDateTime;
Result.EndPeriod := lEndDateTime;
end;
end;
end.
|
unit eSocial.Views.Default;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.ExtCtrls,
Vcl.StdCtrls,
Router4D,
Router4D.Props,
Router4D.Interfaces,
Bind4D,
Bind4D.Interfaces,
Bind4D.Attributes,
Bind4D.Types,
eSocial.Classes.Events;
type
TViewDefault = class(TForm, iRouter4DComponent)
PanelView: TPanel;
PanelHeader: TPanel;
PanelContent: TPanel;
PanelTitle: TPanel;
lblTitle: TLabel;
lblSubtitle: TLabel;
PanelBody: TPanel;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
FTitle : String;
procedure ApplyStyleDefault;
public
{ Public declarations }
procedure UnRender; virtual;
procedure BackToHome;
procedure CloseMenu;
function Render : TForm;
end;
var
ViewDefault: TViewDefault;
implementation
uses
eSocial.Views.Styles,
eSocial.Views.Styles.Colors;
{$R *.dfm}
{ TViewDefault }
procedure TViewDefault.ApplyStyleDefault;
begin
Self.Color := BACKGROUD_COLOR_WHITE;
PanelHeader.Color := BACKGROUD_COLOR_SECONDARY;
PanelContent.Color := BACKGROUD_COLOR_WHITE;
PanelBody.Color := BACKGROUD_COLOR_WHITE;
// Fonte geral do Form
with Self do
begin
Font.Name := FONT_NAME;
Font.Size := FONT_SIZE_NORMAL;
Font.Color := BACKGROUD_COLOR_DARK;
end;
// Fonte do título/subtítulo
with lblTitle do
begin
Font.Name := FONT_NAME;
Font.Size := FONT_SIZE_H1;
Font.Color := FONT_COLOR_WHITE;
end;
with lblSubtitle do
begin
Font.Name := FONT_NAME;
Font.Size := FONT_SIZE_H5;
Font.Color := FONT_COLOR_WHITE;
end;
end;
procedure TViewDefault.BackToHome;
begin
; //TRouter4D.Link.&To('ViewHome');
end;
procedure TViewDefault.CloseMenu;
var
aEvent : TEventsSplitViewChangeEvent;
begin
aEvent := TEventsSplitViewChangeEvent.Create;
aEvent.Opened := False;
GlobalEventBus.Post(aEvent);
end;
procedure TViewDefault.FormCreate(Sender: TObject);
begin
TBind4D
.New
.Form(Self)
.BindFormDefault(FTitle)
.SetStyleComponents;
Self.Caption := FTitle;
lblTitle.Caption := FTitle;
ApplyStyleDefault;
end;
function TViewDefault.Render: TForm;
begin
Result := Self;
Self.CloseMenu;
end;
procedure TViewDefault.UnRender;
begin
;
end;
end.
|
{*******************************************************}
{ }
{ Delphi REST Client Framework }
{ }
{ Copyright(c) 2013-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit uOAuth1_frm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Rtti, System.Classes,
System.Variants,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs,
FMX.StdCtrls, FMX.ListBox, FMX.Edit, FMX.ComboEdit,
uRESTObjects, REST.Client, FMX.Controls.Presentation;
type
Tfrm_OAuth1 = class(TForm)
btn_Cancel: TButton;
btn_Apply: TButton;
gb_Endpoints: TGroupBox;
edt_OAuth1AuthEndpoint: TEdit;
Label20: TLabel;
edt_OAuth1AccessTokenEndpoint: TEdit;
Label21: TLabel;
edt_OAuth1RequestTokentEndpoint: TEdit;
Label22: TLabel;
gb_ClientData: TGroupBox;
edt_OAuth1ClientID: TEdit;
Label18: TLabel;
edt_OAuth1ClientSecret: TEdit;
Label19: TLabel;
gb_MiscSettings: TGroupBox;
gb_CodeTokens: TGroupBox;
edt_OAuth1AuthCode: TEdit;
Label17: TLabel;
edt_OAuth1AccessToken: TEdit;
Label23: TLabel;
edt_OAuth1RequestToken: TEdit;
Label24: TLabel;
edt_OAuth1RedirectEndpoint: TEdit;
Label1: TLabel;
cmb_SigningClass: TComboEdit;
Label2: TLabel;
edt_OAuth1AccessTokenSecret: TEdit;
edt_OAuth1RequestTokenSecret: TEdit;
Label3: TLabel;
Label4: TLabel;
btn_Step1: TButton;
Button1: TButton;
procedure btn_ApplyClick(Sender: TObject);
procedure btn_CancelClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btn_Step1Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
procedure InitializeSigningClassCombo;
procedure ConfigureProxyServer( AClient : TCustomRESTClient );
procedure DoGetRequestToken;
procedure DoGetAcessToken;
public
{ Public declarations }
procedure FetchParamsFromControls(const AParams: TRESTRequestParams);
procedure PushParamsToControls(const AParams: TRESTRequestParams);
end;
var
frm_OAuth1: Tfrm_OAuth1;
implementation
uses
uMain_frm,
uOSUtils,
REST.Types,
REST.Utils,
System.StrUtils,
REST.Authenticator.OAuth,
uRESTDebuggerResStrs;
{$R *.fmx}
procedure Tfrm_OAuth1.btn_ApplyClick(Sender: TObject);
begin
ModalResult := mrOK;
end;
procedure Tfrm_OAuth1.btn_CancelClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure Tfrm_OAuth1.btn_Step1Click(Sender: TObject);
begin
DoGetRequestToken;
end;
procedure Tfrm_OAuth1.Button1Click(Sender: TObject);
begin
DoGetAcessToken;
end;
procedure Tfrm_OAuth1.DoGetAcessToken;
var
LOAuth1: TCustomAuthenticator;
LClient: TRESTClient;
LRequest: TRESTRequest;
LToken: string;
begin
LOAuth1 := TOAuth1Authenticator.Create(NIL);
with (LOAuth1 AS TOAuth1Authenticator) do
begin
SigningClass := TOAuth1SignatureMethod_HMAC_SHA1.Create;
ConsumerKey := edt_OAuth1ClientID.Text;
ConsumerSecret := edt_OAuth1ClientSecret.Text;
// yes- in this step we do use the request-token as access-token
AccessToken := edt_OAuth1RequestToken.Text;
AccessTokenSecret := edt_OAuth1RequestTokenSecret.Text;
end;
LClient := TRESTClient.Create(edt_OAuth1AccessTokenEndpoint.Text);
LClient.Authenticator := LOAuth1;
ConfigureProxyServer( LClient );
LRequest := TRESTRequest.Create(nil);
try
LRequest.Method := TRESTRequestMethod.rmPOST;
LRequest.AddAuthParameter('oauth_verifier', edt_OAuth1AuthCode.Text, TRESTRequestParameterKind.pkGETorPOST,
[TRESTRequestParameterOption.poDoNotEncode]);
LRequest.Client := LClient;
LRequest.Execute;
//memo_Response.Lines.Text := LRequest.Response.Content;
if LRequest.Response.GetSimpleValue('oauth_token', LToken) then
edt_OAuth1AccessToken.Text := LToken;
if LRequest.Response.GetSimpleValue('oauth_token_secret', LToken) then
edt_OAuth1AccessTokenSecret.Text := LToken;
finally
FreeAndNil(LRequest);
end;
end;
procedure Tfrm_OAuth1.DoGetRequestToken;
var
LClient: TRESTClient;
LRequest: TRESTRequest;
LOAuth1: TOAuth1Authenticator;
LURL: string;
LToken: string;
begin
/// step #1, get request-token
LOAuth1 := TOAuth1Authenticator.Create(NIL);
with (LOAuth1 AS TOAuth1Authenticator) do
begin
SigningClass := TOAuth1SignatureMethod_HMAC_SHA1.Create;
ConsumerKey := edt_OAuth1ClientID.Text;
ConsumerSecret := edt_OAuth1ClientSecret.Text;
CallbackEndpoint := edt_OAuth1RedirectEndpoint.Text;
end;
try
LClient := TRESTClient.Create(edt_OAuth1RequestTokentEndpoint.Text);
LClient.Authenticator := LOAuth1;
ConfigureProxyServer( LClient );
LRequest := TRESTRequest.Create(nil);
LRequest.Method := TRESTRequestMethod.rmPOST;
LRequest.Resource := '';
LRequest.Client := LClient;
LRequest.Execute;
//memo_Response.Lines.Text := LRequest.Response.Content;
if LRequest.Response.GetSimpleValue('oauth_token', LToken) then
edt_OAuth1RequestToken.Text := LToken;
if LRequest.Response.GetSimpleValue('oauth_token_secret', LToken) then
edt_OAuth1RequestTokenSecret.Text := LToken;
finally
FreeAndNil(LRequest);
FreeAndNil(LClient);
end;
if (edt_OAuth1RequestToken.Text = '') then
begin
ShowMessage(RSCannotProceedWithoutRequest);
EXIT;
end;
/// step #2: get the auth-verifier (PIN must be entered by the user!)
LURL := edt_OAuth1AuthEndpoint.Text;
if ContainsText( LURL, '?' ) then
LURL := LURL + '&oauth_token=' + edt_OAuth1RequestToken.Text
else
LURL := LURL + '?oauth_token=' + edt_OAuth1RequestToken.Text;
OSExecute( LURL );
end;
procedure Tfrm_OAuth1.FetchParamsFromControls(const AParams: TRESTRequestParams);
begin
AParams.EndpointAuth:= edt_OAuth1AuthEndpoint.Text;
AParams.EndpointAccessToken:= edt_OAuth1AccessTokenEndpoint.Text;
AParams.EndpointRequestToken:= edt_OAuth1RequestTokentEndpoint.Text;
AParams.EndpointRedirect:= edt_OAuth1RedirectEndpoint.Text;
AParams.AuthCode:= edt_OAuth1AuthCode.Text;
AParams.AccessToken:= edt_OAuth1AccessToken.Text;
AParams.AccessTokenSecret:= edt_OAuth1AccessTokenSecret.Text;
AParams.RequestToken:= edt_OAuth1RequestToken.Text;
AParams.RequestTokenSecret:= edt_OAuth1RequestTokenSecret.Text;
AParams.ClientID:= edt_OAuth1ClientID.Text;
AParams.ClientSecret:= edt_OAuth1ClientSecret.Text;
AParams.OAuth1SignatureMethod:= cmb_SigningClass.Text;
end;
procedure Tfrm_OAuth1.FormCreate(Sender: TObject);
begin
InitializeSigningClassCombo;
end;
procedure Tfrm_OAuth1.PushParamsToControls(const AParams: TRESTRequestParams);
begin
edt_OAuth1AuthEndpoint.Text:= AParams.EndpointAuth;
edt_OAuth1AccessTokenEndpoint.Text:= AParams.EndpointAccessToken;
edt_OAuth1RequestTokentEndpoint.Text:= AParams.EndpointRequestToken;
edt_OAuth1RedirectEndpoint.Text:= AParams.EndpointRedirect;
edt_OAuth1AuthCode.Text:= AParams.AuthCode;
edt_OAuth1AccessToken.Text:= AParams.AccessToken;
edt_OAuth1AccessTokenSecret.Text:= AParams.AccessTokenSecret;
edt_OAuth1RequestToken.Text:= AParams.RequestToken;
edt_OAuth1RequestTokenSecret.Text:= AParams.RequestTokenSecret;
edt_OAuth1ClientID.Text:= AParams.ClientID;
edt_OAuth1ClientSecret.Text:= AParams.ClientSecret;
if (AParams.OAuth1SignatureMethod <> '') then
begin
if (cmb_SigningClass.Items.IndexOf(AParams.OAuth1SignatureMethod) > -1) then
cmb_SigningClass.ItemIndex:= cmb_SigningClass.Items.IndexOf(AParams.OAuth1SignatureMethod)
else
begin
cmb_SigningClass.ItemIndex:= -1;
cmb_SigningClass.Text:= AParams.OAuth1SignatureMethod;
end;
end
else
begin
if (cmb_SigningClass.Items.IndexOf(DefaultOAuth1SignatureClass.GetName) > -1) then
cmb_SigningClass.ItemIndex:= cmb_SigningClass.Items.IndexOf(DefaultOAuth1SignatureClass.GetName)
else
begin
cmb_SigningClass.ItemIndex:= -1;
cmb_SigningClass.Text:= '';
end;
end;
end;
procedure Tfrm_OAuth1.InitializeSigningClassCombo;
begin
cmb_SigningClass.Items.BeginUpdate;
TRY
cmb_SigningClass.Items.Clear;
cmb_SigningClass.Items.Add(TOAuth1SignatureMethod_HMAC_SHA1.GetName);
cmb_SigningClass.Items.Add(TOAuth1SignatureMethod_PLAINTEXT.GetName);
FINALLY
cmb_SigningClass.Items.EndUpdate;
END;
/// well, it *really* should be > 0 here, but cheking cannot be wrong...
if (cmb_SigningClass.Items.Count > 0) then
cmb_SigningClass.ItemIndex := 0;
end;
procedure Tfrm_OAuth1.ConfigureProxyServer( AClient : TCustomRESTClient );
begin
if frm_Main.cbProxy.IsChecked then
begin
AClient.ProxyServer := frm_Main.edt_ProxyServer.Text;
AClient.ProxyPort := Trunc(frm_Main.edt_ProxyPort.Value);
AClient.ProxyUsername := frm_Main.edt_ProxyUser.Text;
AClient.ProxyPassword := frm_Main.edt_ProxyPass.Text;
end
else
begin
AClient.ProxyServer := '';
AClient.ProxyPort := 0;
AClient.ProxyUsername := '';
AClient.ProxyPassword := '';
end;
end;
end.
|
unit PascalCoin.RPC.Operation;
interface
uses PascalCoin.Utils.Interfaces, PascalCoin.RPC.Interfaces, System.JSON;
type
TPascalCoinOperation = class(TInterfacedObject, IPascalCoinOperation)
private
FValid: Boolean;
FErrors: string;
FBlock: UInt64;
FTime: Integer;
FOpBlock: UInt64;
FMaturation: Integer;
FOpType: Integer;
FOpTxt: string;
FAccount: Cardinal;
FAmount: Currency;
FFee: Currency;
FBalance: Currency;
FSender_Account: Cardinal;
FDest_Account: Cardinal;
FEnc_Pubkey: HexStr;
FOpHash: HexStr;
FOld_Ophash: HexStr;
FSubType: string;
FSigner_account: Cardinal;
FN_Operation: Integer;
FPayload: HexStr;
FSenders: IPascalCoinList<IPascalCoinSender>;
FReceivers: IPascalCoinList<IPascalCoinReceiver>;
FChangers: IPascalCoinList<IPascalCoinChanger>;
protected
function GetValid: Boolean;
procedure SetValid(const Value: Boolean);
function GetErrors: string;
procedure SetErrors(const Value: string);
function GetBlock: UInt64;
procedure SetBlock(const Value: UInt64);
function GetTime: Integer;
procedure SetTime(const Value: Integer);
function GetOpblock: Integer;
procedure SetOpblock(const Value: Integer);
function GetMaturation: Integer;
procedure SetMaturation(const Value: Integer);
function GetOptype: Integer;
procedure SetOptype(const Value: Integer);
function GetOperationType: TOperationType;
procedure SetOperationType(const Value: TOperationType);
function GetOptxt: string;
procedure SetOptxt(const Value: string);
function GetAccount: Cardinal;
procedure SetAccount(const Value: Cardinal);
function GetAmount: Currency;
procedure SetAmount(const Value: Currency);
function GetFee: Currency;
procedure SetFee(const Value: Currency);
function GetBalance: Currency;
procedure SetBalance(const Value: Currency);
function GetSender_account: Cardinal;
procedure SetSender_Account(const Value: Cardinal);
function GetDest_account: Cardinal;
procedure SetDest_Account(const Value: Cardinal);
function GetEnc_pubkey: HexStr;
procedure SetEnc_pubkey(const Value: HexStr);
function GetOphash: HexStr;
procedure SetOphash(const Value: HexStr);
function GetOld_ophash: HexStr;
procedure SetOld_ophash(const Value: HexStr);
function GetSubtype: string;
procedure SetSubtype(const Value: string);
function GetSigner_account: Cardinal;
procedure SetSigner_account(const Value: Cardinal);
function GetN_operation: Integer;
procedure SetN_operation(const Value: Integer);
function GetPayload: HexStr;
procedure SetPayload(const Value: HexStr);
function GetSenders: IPascalCoinList<IPascalCoinSender>;
procedure SetSenders(Value: IPascalCoinList<IPascalCoinSender>);
function GetReceivers: IPascalCoinList<IPascalCoinReceiver>;
procedure SetReceivers(Value: IPascalCoinList<IPascalCoinReceiver>);
function GetChangers: IPascalCoinList<IPascalCoinChanger>;
procedure SetChangers(Value: IPascalCoinList<IPascalCoinChanger>);
public
constructor Create;
class function CreateFromJSON(Value: TJSONValue): TPascalCoinOperation;
end;
TPascalCoinSender = class(TInterfacedObject, IPascalCoinSender)
private
FAccount: Cardinal;
FN_Operation: Integer;
FAmount: Currency;
FPayload: HexStr;
protected
function GetAccount: Cardinal;
procedure SetAccount(const Value: Cardinal);
function GetN_operation: Integer;
procedure SetN_operation(const Value: Integer);
function GetAmount: Currency;
procedure SetAmount(const Value: Currency);
function GetPayload: HexStr;
procedure SetPayload(const Value: HexStr);
public
end;
TPascalCoinReceiver = class(TInterfacedObject, IPascalCoinReceiver)
private
FAccount: Cardinal;
FAmount: Currency;
FPayload: HexStr;
protected
function GetAccount: Cardinal;
procedure SetAccount(const Value: Cardinal);
function GetAmount: Currency;
procedure SetAmount(const Value: Currency);
function GetPayload: HexStr;
procedure SetPayload(const Value: HexStr);
public
end;
TPascalCoinChanger = Class(TInterfacedObject, IPascalCoinChanger)
private
FAccount: Cardinal;
FN_Operation: Integer;
FNew_enc_pubkey: String;
FNew_Type: string;
FAmount: Currency;
FSeller_account: Cardinal;
FAccount_price: Currency;
FLocked_until_block: UInt64;
FFee: Currency;
protected
function GetAccount: Cardinal;
procedure SetAccount(const Value: Cardinal);
function GetN_operation: Integer;
procedure SetN_operation(const Value: Integer);
function GetNew_enc_pubkey: string;
procedure SetNew_enc_pubkey(const Value: string);
function GetNew_Type: string;
procedure SetNew_Type(const Value: string);
function GetSeller_account: Cardinal;
procedure SetSeller_account(const Value: Cardinal);
function GetAccount_price: Currency;
procedure SetAccount_price(const Value: Currency);
function GetLocked_until_block: UInt64;
procedure SetLocked_until_block(const Value: UInt64);
function GetFee: Currency;
procedure SetFee(const Value: Currency);
public
end;
implementation
{ TPascalCoinOperation }
uses PascalCoin.Utils.Classes, REST.JSON;
constructor TPascalCoinOperation.Create;
begin
inherited Create;
FSenders := TPascalCoinList<IPascalCoinSender>.Create;
FReceivers := TPascalCoinList<IPascalCoinReceiver>.Create;
FChangers := TPascalCoinList<IPascalCoinChanger>.Create;
end;
class function TPascalCoinOperation.CreateFromJSON(Value: TJSONValue)
: TPascalCoinOperation;
var
lObj: TJSONObject;
lArr: TJSONArray;
lVal: TJSONValue;
lSender: IPascalCoinSender;
lReceiver: IPascalCoinReceiver;
lChanger: IPascalCoinChanger;
S: string;
begin
lObj := Value as TJSONObject;
result := TPascalCoinOperation.Create;
if lObj.TryGetValue<string>('valid', S) then
result.FValid := (S <> 'false')
else
result.FValid := True;
result.FBlock := lObj.Values['block'].AsType<UInt64>; // 279915
result.FTime := lObj.Values['time'].AsType<Integer>; // 0,
result.FOpBlock := lObj.Values['opblock'].AsType<UInt64>; // 1,
lObj.Values['maturation'].TryGetValue<Integer>(result.FMaturation); // null,
result.FOpType := lObj.Values['optype'].AsType<Integer>; // 1,
{ TODO : should be Int? }
result.FSubType := lObj.Values['subtype'].AsType<string>; // 12,
result.FAccount := lObj.Values['account'].AsType<Cardinal>; // 865822,
result.FSigner_account := lObj.Values['signer_account'].AsType<Cardinal>;
// 865851,
result.FN_Operation := lObj.Values['n_operation'].AsType<Integer>;
result.FOpTxt := lObj.Values['optxt'].AsType<String>;
// "Tx-In 16.0000 PASC from 865851-95 to 865822-14",
result.FFee := lObj.Values['fee'].AsType<Currency>; // 0.0000,
result.FAmount := lObj.Values['amount'].AsType<Currency>; // 16.0000,
result.FPayload := lObj.Values['payload'].AsType<HexStr>;
// "7A6962626564656520646F6F646168",
result.FBalance := lObj.Values['balance'].AsType<Currency>; // 19.1528,
result.FSender_Account := lObj.Values['sender_account'].AsType<Cardinal>;
// 865851,
result.FDest_Account := lObj.Values['dest_account'].AsType<Cardinal>;
// 865822,
result.FOpHash := lObj.Values['ophash'].AsType<HexStr>;
lArr := lObj.Values['senders'] as TJSONArray;
for lVal in lArr do
begin
result.FSenders.Add(TJSON.JsonToObject<TPascalCoinSender>
(lVal as TJSONObject));
end;
lArr := lObj.Values['receivers'] as TJSONArray;
for lVal in lArr do
begin
result.FReceivers.Add(TJSON.JsonToObject<TPascalCoinReceiver>
(lVal as TJSONObject));
end;
lArr := lObj.Values['changers'] as TJSONArray;
for lVal in lArr do
begin
result.FChangers.Add(TJSON.JsonToObject<TPascalCoinChanger>
(lVal as TJSONObject));
end;
end;
function TPascalCoinOperation.GetAccount: Cardinal;
begin
result := FAccount;
end;
function TPascalCoinOperation.GetAmount: Currency;
begin
result := FAmount;
end;
function TPascalCoinOperation.GetBalance: Currency;
begin
result := FBalance;
end;
function TPascalCoinOperation.GetBlock: UInt64;
begin
result := FBlock;
end;
function TPascalCoinOperation.GetChangers: IPascalCoinList<IPascalCoinChanger>;
begin
result := FChangers;
end;
function TPascalCoinOperation.GetDest_account: Cardinal;
begin
result := FDest_Account;
end;
function TPascalCoinOperation.GetEnc_pubkey: HexStr;
begin
result := FEnc_Pubkey;
end;
function TPascalCoinOperation.GetErrors: string;
begin
result := FErrors;
end;
function TPascalCoinOperation.GetFee: Currency;
begin
result := FFee;
end;
function TPascalCoinOperation.GetMaturation: Integer;
begin
result := FMaturation;
end;
function TPascalCoinOperation.GetN_operation: Integer;
begin
result := FN_Operation;
end;
function TPascalCoinOperation.GetOld_ophash: HexStr;
begin
result := FOld_Ophash;
end;
function TPascalCoinOperation.GetOpblock: Integer;
begin
result := FOpBlock;
end;
function TPascalCoinOperation.GetOperationType: TOperationType;
begin
result := TOperationType(FOpType);
end;
function TPascalCoinOperation.GetOphash: HexStr;
begin
result := FOpHash;
end;
function TPascalCoinOperation.GetOptxt: string;
begin
result := FOpTxt;
end;
function TPascalCoinOperation.GetOptype: Integer;
begin
result := FOpType;
end;
function TPascalCoinOperation.GetPayload: HexStr;
begin
result := FPayload;
end;
function TPascalCoinOperation.GetReceivers
: IPascalCoinList<IPascalCoinReceiver>;
begin
result := FReceivers;
end;
function TPascalCoinOperation.GetSenders: IPascalCoinList<IPascalCoinSender>;
begin
result := FSenders;
end;
function TPascalCoinOperation.GetSender_account: Cardinal;
begin
result := FSender_Account;
end;
function TPascalCoinOperation.GetSigner_account: Cardinal;
begin
result := FSigner_account;
end;
function TPascalCoinOperation.GetSubtype: string;
begin
result := FSubType;
end;
function TPascalCoinOperation.GetTime: Integer;
begin
result := FTime;
end;
function TPascalCoinOperation.GetValid: Boolean;
begin
result := FValid;
end;
procedure TPascalCoinOperation.SetAccount(const Value: Cardinal);
begin
FAccount := Value;
end;
procedure TPascalCoinOperation.SetAmount(const Value: Currency);
begin
FAmount := Value;
end;
procedure TPascalCoinOperation.SetBalance(const Value: Currency);
begin
FBalance := Value;
end;
procedure TPascalCoinOperation.SetBlock(const Value: UInt64);
begin
FBlock := Value;
end;
procedure TPascalCoinOperation.SetChangers
(Value: IPascalCoinList<IPascalCoinChanger>);
begin
FChangers := Value;
end;
procedure TPascalCoinOperation.SetDest_Account(const Value: Cardinal);
begin
FDest_Account := Value;
end;
procedure TPascalCoinOperation.SetEnc_pubkey(const Value: HexStr);
begin
FEnc_Pubkey := Value;
end;
procedure TPascalCoinOperation.SetErrors(const Value: string);
begin
FErrors := Value;
end;
procedure TPascalCoinOperation.SetFee(const Value: Currency);
begin
FFee := Value;
end;
procedure TPascalCoinOperation.SetMaturation(const Value: Integer);
begin
FMaturation := Value;
end;
procedure TPascalCoinOperation.SetN_operation(const Value: Integer);
begin
FN_Operation := Value;
end;
procedure TPascalCoinOperation.SetOld_ophash(const Value: HexStr);
begin
FOld_Ophash := Value;
end;
procedure TPascalCoinOperation.SetOpblock(const Value: Integer);
begin
FOpBlock := Value;
end;
procedure TPascalCoinOperation.SetOperationType(const Value: TOperationType);
begin
FOpType := Integer(Value);
end;
procedure TPascalCoinOperation.SetOphash(const Value: HexStr);
begin
FOpHash := Value;
end;
procedure TPascalCoinOperation.SetOptxt(const Value: string);
begin
FOpTxt := Value;
end;
procedure TPascalCoinOperation.SetOptype(const Value: Integer);
begin
FOpType := Value;
end;
procedure TPascalCoinOperation.SetPayload(const Value: HexStr);
begin
FPayload := Value;
end;
procedure TPascalCoinOperation.SetReceivers
(Value: IPascalCoinList<IPascalCoinReceiver>);
begin
FReceivers := Value;
end;
procedure TPascalCoinOperation.SetSenders
(Value: IPascalCoinList<IPascalCoinSender>);
begin
FSenders := Value;
end;
procedure TPascalCoinOperation.SetSender_Account(const Value: Cardinal);
begin
FSender_Account := Value;
end;
procedure TPascalCoinOperation.SetSigner_account(const Value: Cardinal);
begin
FSigner_account := Value;
end;
procedure TPascalCoinOperation.SetSubtype(const Value: string);
begin
FSubType := Value;
end;
procedure TPascalCoinOperation.SetTime(const Value: Integer);
begin
FTime := Value;
end;
procedure TPascalCoinOperation.SetValid(const Value: Boolean);
begin
FValid := Value;
end;
{ TPascalCoinSender }
function TPascalCoinSender.GetAccount: Cardinal;
begin
end;
function TPascalCoinSender.GetAmount: Currency;
begin
end;
function TPascalCoinSender.GetN_operation: Integer;
begin
end;
function TPascalCoinSender.GetPayload: HexStr;
begin
end;
procedure TPascalCoinSender.SetAccount(const Value: Cardinal);
begin
end;
procedure TPascalCoinSender.SetAmount(const Value: Currency);
begin
end;
procedure TPascalCoinSender.SetN_operation(const Value: Integer);
begin
end;
procedure TPascalCoinSender.SetPayload(const Value: HexStr);
begin
end;
{ TPascalCoinReceiver }
function TPascalCoinReceiver.GetAccount: Cardinal;
begin
end;
function TPascalCoinReceiver.GetAmount: Currency;
begin
end;
function TPascalCoinReceiver.GetPayload: HexStr;
begin
end;
procedure TPascalCoinReceiver.SetAccount(const Value: Cardinal);
begin
end;
procedure TPascalCoinReceiver.SetAmount(const Value: Currency);
begin
end;
procedure TPascalCoinReceiver.SetPayload(const Value: HexStr);
begin
end;
{ TPascalCoinChanger }
function TPascalCoinChanger.GetAccount: Cardinal;
begin
end;
function TPascalCoinChanger.GetAccount_price: Currency;
begin
end;
function TPascalCoinChanger.GetFee: Currency;
begin
end;
function TPascalCoinChanger.GetLocked_until_block: UInt64;
begin
end;
function TPascalCoinChanger.GetNew_enc_pubkey: string;
begin
end;
function TPascalCoinChanger.GetNew_Type: string;
begin
end;
function TPascalCoinChanger.GetN_operation: Integer;
begin
end;
function TPascalCoinChanger.GetSeller_account: Cardinal;
begin
end;
procedure TPascalCoinChanger.SetAccount(const Value: Cardinal);
begin
end;
procedure TPascalCoinChanger.SetAccount_price(const Value: Currency);
begin
end;
procedure TPascalCoinChanger.SetFee(const Value: Currency);
begin
end;
procedure TPascalCoinChanger.SetLocked_until_block(const Value: UInt64);
begin
end;
procedure TPascalCoinChanger.SetNew_enc_pubkey(const Value: string);
begin
end;
procedure TPascalCoinChanger.SetNew_Type(const Value: string);
begin
end;
procedure TPascalCoinChanger.SetN_operation(const Value: Integer);
begin
end;
procedure TPascalCoinChanger.SetSeller_account(const Value: Cardinal);
begin
end;
end.
|
{-------------------------------------------------------------------------------
// EasyComponents For Delphi 7
// 一轩软研第三方开发包
// @Copyright 2010 hehf
// ------------------------------------
//
// 本开发包是公司内部使用,作为开发工具使用任何,何海锋个人负责开发,任何
// 人不得外泄,否则后果自负.
//
// 使用权限以及相关解释请联系何海锋
//
//
// 网站地址:http://www.YiXuan-SoftWare.com
// 电子邮件:hehaifeng1984@126.com
// YiXuan-SoftWare@hotmail.com
// QQ :383530895
// MSN :YiXuan-SoftWare@hotmail.com
//------------------------------------------------------------------------------
//单元说明:
// 定义系统经常使用的一此类,常驻内存
//主要实现:
//-----------------------------------------------------------------------------}
unit untEasyUtilClasses;
interface
uses
Windows, Classes, DB, DBClient;
type
TEasyUpdateMode = (eumWhereKeyOnly, eumWhereUpdated, eumWhereAll);
//插件类
PPLugin = ^TPlugin;
TPlugin = record
FileName: string; //插件文件
EName: string; //英文名
CName: string; //中文名
image1: string; //图片
image2: string; //点击时图片
iOrder: Integer; //序号
Flag : string; //标志符
end;
TEasyObject = class
private
FGUID : string;
FClientDataSet: TClientDataSet;
FRecordList : TStrings;
FKeyField : string;
FUpdateMode : TEasyUpdateMode;
FTag : Integer;
FFlag : string;
FData : Pointer;
function GetClientDataSet: TClientDataSet;
function GetEasyUpdateMode: TEasyUpdateMode;
function GetFlag: string;
function GetGUID: string;
function GetKeyField: string;
function GetRecordList: TStrings;
function GetTag: Integer;
procedure SetClientDataSet(const Value: TClientDataSet);
procedure SetEasyUpdateMode(const Value: TEasyUpdateMode);
procedure SetFlag(const Value: string);
procedure SetGUID(const Value: string);
procedure SetKeyField(const Value: string);
procedure SetRecordList(const Value: TStrings);
procedure SetTag(const Value: Integer);
function GetData: Pointer;
procedure SetData(const Value: Pointer);
public
constructor Create; virtual;
destructor Destroy; override;
procedure GenerateListByRecord(var AClientDataSet: TClientDataSet); virtual;
property GUID: string read GetGUID write SetGUID;
property ClientDataSet: TClientDataSet read GetClientDataSet write SetClientDataSet;
property RecordList: TStrings read GetRecordList write SetRecordList;
property KeyField: string read GetKeyField write SetKeyField;
property UpdateMode: TEasyUpdateMode read GetEasyUpdateMode write SetEasyUpdateMode;
property Tag: Integer read GetTag write SetTag;
property Flag: string read GetFlag write SetFlag;
property Data: Pointer read GetData write SetData;
end;
implementation
{ TEasyObject }
constructor TEasyObject.Create;
begin
inherited;
FRecordList := TStringList.Create;
end;
destructor TEasyObject.Destroy;
begin
FRecordList.Free;
if FData <> nil then
TObject(FData).Free;
inherited;
end;
procedure TEasyObject.GenerateListByRecord(var AClientDataSet: TClientDataSet);
var
J: Integer;
begin
for J := 0 to AClientDataSet.FieldCount - 1 do
FRecordList.Add(AClientDataSet.Fields[J].FieldName + '=' + AClientDataSet.Fields[J].Value);
end;
function TEasyObject.GetClientDataSet: TClientDataSet;
begin
Result := FClientDataSet;
end;
function TEasyObject.GetData: Pointer;
begin
Result := FData;
end;
function TEasyObject.GetEasyUpdateMode: TEasyUpdateMode;
begin
Result := FUpdateMode;
end;
function TEasyObject.GetFlag: string;
begin
Result := FFlag;
end;
function TEasyObject.GetGUID: string;
begin
Result := FGUID;
end;
function TEasyObject.GetKeyField: string;
begin
Result := FKeyField;
end;
function TEasyObject.GetRecordList: TStrings;
begin
Result := FRecordList;
end;
function TEasyObject.GetTag: Integer;
begin
Result := FTag;
end;
procedure TEasyObject.SetClientDataSet(const Value: TClientDataSet);
begin
FClientDataSet := Value;
end;
procedure TEasyObject.SetData(const Value: Pointer);
begin
FData := Value;
end;
procedure TEasyObject.SetEasyUpdateMode(const Value: TEasyUpdateMode);
begin
FUpdateMode := Value;
end;
procedure TEasyObject.SetFlag(const Value: string);
begin
FFlag := Value;
end;
procedure TEasyObject.SetGUID(const Value: string);
begin
FGUID := Value;
end;
procedure TEasyObject.SetKeyField(const Value: string);
begin
FKeyField := Value;
end;
procedure TEasyObject.SetRecordList(const Value: TStrings);
begin
FRecordList := Value;
end;
procedure TEasyObject.SetTag(const Value: Integer);
begin
FTag := Value;
end;
end.
|
unit UnWidgets;
interface
uses Classes, Controls, StdCtrls, ExtCtrls,
{ Fluente }
UnProduto;
const
COMANDA_ALTURA = 123;
COMANDA_NOME_FONTE = 'Segoe UI';
COMANDA_LARGURA = 270;
COMANDA_MARGENS = 10;
COMANDA_TAMANHO_FONTE = 34;
ITEM_ALTURA = 45;
ITEM_NOME_FONTE = 'Segoe UI';
ITEM_TAMANHO_FONTE = 16;
type
TComanda = class(TPanel)
private
FDescricao: string;
FFichaAbertaDesde: TDate;
FFichaTotal: Real;
FIdentificacao: string;
FLabelIdentificacao: TLabel;
FLabelTotal: TLabel;
FTotal: Real;
protected
procedure SetDescricao(const Descricao: string);
procedure SetTotal(const Total: Real);
public
property Identificacao: string read FIdentificacao write FIdentificacao;
property Descricao: string read FDescricao write SetDescricao;
property FichaAbertaDesde: TDate read FFichaAbertaDesde
write FFichaAbertaDesde;
property FichaTotal: Real read FFichaTotal write FFichaTotal;
property Total: Real read FTotal write SetTotal;
constructor Create(const ParentControl: TWinControl;
const Descricao: string; const Total: Real; const aEvent: TNotifyEvent); reintroduce;
end;
TItemEdit = class(TPanel)
private
FLabelProduto: TLabel;
FLabelQuantidade: TLabel;
FLabelValorUnitario: TLabel;
FLabelTotal: TLabel;
FProduto: TProduto;
FBtnEditItem: TButton;
protected
function criaTexto(const aTexto: string): TLabel;
public
constructor Create(const aParentControl: TWinControl;
const aProduto: TProduto); reintroduce;
property Produto: TProduto read FProduto;
end;
implementation
uses SysUtils, Graphics;
{ TComanda }
constructor TComanda.Create(const ParentControl: TWinControl;
const Descricao: string; const Total: Real; const aEvent: TNotifyEvent);
var
_divisor: TSplitter;
begin
inherited create(ParentControl);
Self.FDescricao := Descricao;
Self.FTotal := Total;
Self.Height := COMANDA_ALTURA;
Self.Width := COMANDA_LARGURA;
Self.Parent := ParentControl;
Self.ParentColor := False;
Self.Color := $006F3700;
Self.FLabelIdentificacao := TLabel.Create(Self);
Self.FLabelIdentificacao.Alignment := taCenter;
Self.FLabelIdentificacao.Caption := Descricao;
Self.FLabelIdentificacao.Font.Name := COMANDA_NOME_FONTE;
Self.FLabelIdentificacao.Font.Size := COMANDA_TAMANHO_FONTE;
Self.FLabelIdentificacao.Font.Color := clWhite;
Self.FLabelIdentificacao.Font.Style := [fsBold];
Self.FLabelIdentificacao.Align := alTop;
Self.FLabelIdentificacao.Parent := Self;
Self.FLabelIdentificacao.Transparent := False;
Self.FLabelIdentificacao.ParentColor := False;
Self.FLabelIdentificacao.Color := $006F3700;
Self.FLabelIdentificacao.OnClick := aEvent;
_divisor := TSplitter.Create(Self);
_divisor.Align := alTop;
_divisor.Parent := Self;
Self.FLabelTotal := TLabel.Create(Self);
Self.FLabelTotal.Alignment := taCenter;
Self.FLabelTotal.Caption := FormatFloat('R$ ###,##0.00', Total);
Self.FLabelTotal.Font.Name := COMANDA_NOME_FONTE;
Self.FLabelTotal.Font.Style := [fsBold];
Self.FLabelTotal.Font.Size := COMANDA_TAMANHO_FONTE;
Self.FLabelTotal.Font.Color := clWhite;
Self.FLabelTotal.Align := alClient;
Self.FLabelTotal.Parent := Self;
Self.FLabelTotal.Transparent := False;
Self.FLabelTotal.ParentColor := False;
Self.FLabelTotal.OnClick := aEvent;
end;
procedure TComanda.SetDescricao(const Descricao: string);
begin
Self.FDescricao := Descricao;
Self.FLabelIdentificacao.Caption := Self.FDescricao;
end;
procedure TComanda.SetTotal(const Total: Real);
begin
Self.FTotal := Total;
Self.FLabelTotal.Caption := FormatFloat('R$ ###,##0.00', Self.FTotal);
end;
{ TItemEdit }
constructor TItemEdit.Create(const aParentControl: TWinControl; const aProduto: TProduto);
begin
inherited Create(aParentControl);
Self.FProduto := aProduto;
Self.Height := ITEM_ALTURA;
{ Produto }
Self.FLabelProduto := Self.criaTexto(aProduto.GetDescricao());
Self.FLabelProduto.Parent := Self;
Self.FLabelProduto.Width := 330;
Self.FLabelProduto.Left := 10;
Self.FLabelProduto.Top := 5;
{ Valor Unitário }
Self.FLabelValorUnitario := Self.criaTexto(FormatFloat('##0.00', aProduto.GetValor));
Self.FLabelValorUnitario.Parent := Self;
Self.FLabelValorUnitario.Alignment := taRightJustify;
Self.FLabelValorUnitario.Width := 110;
Self.FLabelValorUnitario.Left := Self.FLabelProduto.Width + 10;
Self.FLabelValorUnitario.Top := 5;
{ Quantidade }
Self.FLabelQuantidade := Self.criaTexto(FormatFloat('##0.00', aProduto.GetQuantidade));
Self.FLabelQuantidade.Parent := Self;
Self.FLabelQuantidade.Alignment := taRightJustify;
Self.FLabelQuantidade.Width := 110;
Self.FLabelQuantidade.Left := Self.FLabelProduto.Width + 10 +
Self.FLabelValorUnitario.Width + 10;
Self.FLabelQuantidade.Top := 5;
{ Total }
Self.FLabelTotal := Self.criaTexto(FormatFloat('##0.00',
aProduto.GetQuantidade() * aProduto.GetValor));
Self.FLabelTotal.Parent := Self;
Self.FLabelTotal.Alignment := taRightJustify;
Self.FLabelTotal.Width := 110;
Self.FLabelTotal.Left := Self.FLabelProduto.Width + 10 +
Self.FLabelValorUnitario.Width + 10 +
Self.FLabelQuantidade.Width + 10 + 35;
Self.FLabelTotal.Top := 5;
{ Botao de Edicao }
Self.FBtnEditItem := TButton.Create(Self);
Self.FBtnEditItem.Parent := Self;
Self.FBtnEditItem.Left := Self.FLabelProduto.Width + 10 +
Self.FLabelValorUnitario.Width + 10 +
Self.FLabelQuantidade.Width + 10 + 35 +
Self.FLabelTotal.Width + 10;
Self.FBtnEditItem.Width := 50;
Self.FBtnEditItem.Height := 40;
{ Configura Painel}
Self.Align := alTop;
Self.Parent := aParentControl;
end;
function TItemEdit.criaTexto(const aTexto: string): TLabel;
begin
Result := TLabel.Create(Self);
Result.Font.Name := ITEM_NOME_FONTE;
Result.Font.Size := ITEM_TAMANHO_FONTE;
Result.Font.Style := [fsBold];
Result.Caption := aTexto;
end;
end.
|
unit NewHiScore;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf,
FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys,
FireDAC.Phys.SQLite, FireDAC.Phys.SQLiteDef, FireDAC.Stan.ExprFuncs,
FireDAC.VCLUI.Wait, Data.DB, FireDAC.Comp.Client;
type
TNewHiScoreForm = class(TForm)
InfoText: TLabel;
EditInitials: TEdit;
SaveHiScoreButton: TButton;
Conn: TFDConnection;
procedure SaveHiScoreButtonClick(Sender: TObject);
private
_position: Integer;
_numMoves: Integer;
public
constructor Create(owner: TComponent; position: Integer; num_moves: Integer); reintroduce;
end;
var
NewHiScoreForm: TNewHiScoreForm;
EditInitials: TEdit;
implementation
{$R *.dfm}
constructor TNewHiScoreForm.Create(owner: TComponent; position: Integer; num_moves: Integer);
begin
inherited Create(owner);
_position := position;
_numMoves := num_moves;
InfoText.Caption :=
Format(
'You score is good enough to put you in the hi score list at postion %d.' +
sLineBreak + 'Please enter your initials below.',
[position]
);
end;
procedure TNewHiScoreForm.SaveHiScoreButtonClick(Sender: TObject);
var
query: TFDQuery;
begin
Conn.Open();
query := TFDQuery.Create(nil);
query.Connection := Conn;
query.SQL.Text := 'SELECT initials, num_moves FROM hiscores ORDER BY num_moves ASC, initials ASC LIMIT 10;';
query.OpenOrExecute;
// If the hiscore list is "full", we need to remove the last entry
if query.RecordCount = 10 then
begin
query.Last();
query.Delete();
end;
// Add the new hiscore
query.AppendRecord([EditInitials.Text, _numMoves]);
query.Free();
Conn.Close();
Screen.ActiveForm.Close();
end;
end.
|
unit uNxCompression;
interface
uses SysUtils, Windows, classes, nxllZipCompressor, nxllTypes, ncDebug;
function CompressFile(fnUncomp, fnCompr: string):boolean;
function UnCompressFile(fnCompr, fnUncomp : string):boolean;
implementation
function CompressFile(fnUncomp, fnCompr: string):boolean;
var
UnCompressedStream, CompressedStream :TMemoryStream;
UnCompressedStreamSize, CompressedStreamSize : TnxWord32;
Compressor : TnxZipCompressor;
f1 : TFileStream;
f2 : TFileStream;
begin
result := false;
UnCompressedStream := TMemoryStream.Create;
CompressedStream := TMemoryStream.Create;
Compressor := TnxZipCompressor.Create;
f1 := TFileStream.Create(fnUncomp, fmOpenRead );
try
UnCompressedStream.CopyFrom(f1,0);
CompressedStream.Position := 0;
UnCompressedStream.Position := 0;
UnCompressedStreamSize := UnCompressedStream.Size;
CompressedStream.Write(UnCompressedStreamSize,4);
CompressedStream.SetSize(UnCompressedStreamSize+4) ;
CompressedStream.Position := 4;
CompressedStreamSize :=
Compressor.Compress( UnCompressedStream.Memory,
Pointer(Cardinal(CompressedStream.Memory) + 4),
UnCompressedStreamSize);
if CompressedStreamSize < UnCompressedStreamSize then begin
CompressedStream.Position := 0;
CompressedStream.Write(UnCompressedStreamSize,4);
CompressedStream.SetSize(CompressedStreamSize+4);
end else begin
CompressedStream.Position := 0;
CompressedStreamSize := 0;
CompressedStream.Write(CompressedStreamSize,4);
UnCompressedStream.Position := 0;
CompressedStream.Write( UnCompressedStream.Memory,
UnCompressedStreamSize);
end;
try
deletefile(pchar(fnCompr));
f2 := TFileStream.Create(fnCompr, fmCreate );
CompressedStream.seek(0,0);
f2.copyfrom (CompressedStream, 0);
f2.Free;
result := true;
except
end;
finally
UnCompressedStream.Free;
CompressedStream.Free;
Compressor.Free;
f1.free;
end;
end;
function UnCompressFile(fnCompr, fnUncomp : string):boolean;
var
CompressedStream, DecompressedStream :TMemoryStream;
CompressedStreamSize, DeCompressedStreamSize : TnxWord32;
Compressor : TnxZipCompressor;
f1 : TFileStream;
f2 : TFileStream;
begin
result := false;
CompressedStream := TMemoryStream.Create;
DecompressedStream := TMemoryStream.Create;
Compressor := TnxZipCompressor.Create;
f1 := TFileStream.Create(fnCompr, fmOpenRead);
try
CompressedStream.CopyFrom(f1,0);
CompressedStreamSize := f1.size - 4;
CompressedStream.Position := 0;
CompressedStream.Read(DeCompressedStreamSize,4);
DecompressedStream.SetSize (DeCompressedStreamSize);
try
Compressor.Uncompress( Pointer(Cardinal(CompressedStream.Memory) + 4),
DecompressedStream.Memory,
CompressedStreamSize, DeCompressedStreamSize);
deletefile(pchar(fnUncomp));
f2 := TFileStream.Create(fnUncomp, fmCreate );
DecompressedStream.seek(0,0);
f2.copyfrom (DecompressedStream, 0);
f2.Free;
result := true;
except
end;
finally
f1.free;
CompressedStream.Free;
DecompressedStream.Free;
Compressor.Free;
end;
end;
end.
|
{$i deltics.interfacedobjects.inc}
unit Deltics.InterfacedObjects.InterfacedObjectList;
interface
uses
Contnrs,
Deltics.InterfacedObjects.Interfaces.IInterfacedObjectList,
Deltics.InterfacedObjects.ComInterfacedObject;
type
TInterfacedObjectList = class(TComInterfacedObject, IInterfacedObjectList)
// IInterfacedObjectList
protected
function get_Capacity: Integer;
function get_Count: Integer;
function get_Item(const aIndex: Integer): IUnknown;
function get_Object(const aIndex: Integer): TObject;
procedure set_Capacity(const aValue: Integer);
function Add(const aItem: IInterface): Integer; overload;
function Add(const aItem: TObject): Integer; overload;
procedure Clear;
function Contains(const aItem: IInterface): Boolean; overload;
function Contains(const aItem: IInterface; var aIndex: Integer): Boolean; overload;
function Contains(const aItem: TObject): Boolean; overload;
function Contains(const aItem: TObject; var aIndex: Integer): Boolean; overload;
procedure Delete(const aIndex: Integer);
function IndexOf(const aItem: IInterface): Integer; overload;
function IndexOf(const aItem: TObject): Integer; overload;
function Insert(const aIndex: Integer; const aItem: IInterface): Integer; overload;
function Insert(const aIndex: Integer; const aItem: TObject): Integer; overload;
function Remove(const aItem: IInterface): Boolean; overload;
function Remove(const aItem: TObject): Boolean; overload;
property Capacity: Integer read get_Capacity write set_Capacity;
property Count: Integer read get_Count;
property Items[const aIndex: Integer]: IUnknown read get_Item; default;
property Objects[const aIndex: Integer]: TObject read get_Object;
private
fItems: TObjectList;
function InternalAdd(const aIndex: Integer; const aItem: TObject): Integer;
procedure OnItemDestroyed(aSender: TObject);
public
constructor Create;
destructor Destroy; override;
end;
implementation
uses
Classes,
SysUtils,
Deltics.Multicast,
Deltics.InterfacedObjects;
{ TInterfacedObjectList -------------------------------------------------------------------------- }
type
TListItem = class
ItemObject: TObject;
ItemInterface: IUnknown;
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
constructor TInterfacedObjectList.Create;
begin
inherited Create;
fItems := TObjectList.Create(TRUE);
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
destructor TInterfacedObjectList.Destroy;
begin
FreeAndNIL(fItems);
inherited;
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure TInterfacedObjectList.OnItemDestroyed(aSender: TObject);
var
idx: Integer;
begin
idx := IndexOf(aSender);
if idx = -1 then
EXIT;
Delete(idx);
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure TInterfacedObjectList.set_Capacity(const aValue: Integer);
begin
fItems.Capacity := aValue;
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
function TInterfacedObjectList.get_Capacity: Integer;
begin
result := fItems.Capacity;
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
function TInterfacedObjectList.get_Count: Integer;
begin
result := fItems.Count;
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
function TInterfacedObjectList.get_Item(const aIndex: Integer): IUnknown;
begin
result := TListItem(fItems[aIndex]).ItemInterface;
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
function TInterfacedObjectList.get_Object(const aIndex: Integer): TObject;
begin
result := TListItem(fItems[aIndex]).ItemObject;
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
function TInterfacedObjectList.Add(const aItem: IInterface): Integer;
var
i: IInterfacedObject;
begin
if NOT Supports(aItem, IInterfacedObject, i) then
raise EInvalidOperation.CreateFmt('Items added to a %s must implement IInterfacedObject', [ClassName]);
result := Add(i.AsObject);
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
function TInterfacedObjectList.Add(const aItem: TObject): Integer;
begin
result := InternalAdd(-1, aItem);
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure TInterfacedObjectList.Clear;
begin
fItems.Clear;
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
function TInterfacedObjectList.Contains(const aItem: IInterface): Boolean;
begin
result := IndexOf(aItem) <> -1;
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
function TInterfacedObjectList.Contains(const aItem: IInterface;
var aIndex: Integer): Boolean;
begin
aIndex := IndexOf(aItem);
result := aIndex <> -1;
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
function TInterfacedObjectList.Contains(const aItem: TObject): Boolean;
begin
result := IndexOf(aItem) <> -1;
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
function TInterfacedObjectList.Contains(const aItem: TObject;
var aIndex: Integer): Boolean;
begin
aIndex := IndexOf(aItem);
result := aIndex <> -1;
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure TInterfacedObjectList.Delete(const aIndex: Integer);
begin
fItems.Delete(aIndex);
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
function TInterfacedObjectList.IndexOf(const aItem: IInterface): Integer;
var
unk: IUnknown;
begin
unk := aItem as IUnknown;
for result := 0 to Pred(fItems.Count) do
if TListItem(fItems[result]).ItemInterface = unk then
EXIT;
result := -1;
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
function TInterfacedObjectList.IndexOf(const aItem: TObject): Integer;
begin
for result := 0 to Pred(fItems.Count) do
if TListItem(fItems[result]).ItemObject = aItem then
EXIT;
result := -1;
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
function TInterfacedObjectList.Insert(const aIndex: Integer;
const aItem: IInterface): Integer;
var
i: IInterfacedObject;
begin
if NOT Supports(aItem, IInterfacedObject, i) then
raise EInvalidOperation.CreateFmt('Items added to a %s must implement IInterfacedObject', [ClassName]);
result := InternalAdd(aIndex, i.AsObject);
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
function TInterfacedObjectList.Insert(const aIndex: Integer;
const aItem: TObject): Integer;
begin
result := InternalAdd(aIndex, aItem);
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
function TInterfacedObjectList.InternalAdd(const aIndex: Integer;
const aItem: TObject): Integer;
var
item: TListItem;
intf: IInterfacedObject;
onDestroy: IOn_Destroy;
begin
if (ReferenceCount = 0) then
raise EInvalidOperation.Create('You appear to be using a reference counted object list via an object reference. Reference counted object lists MUST be used via an interface reference to avoid errors arising from the internal On_Destroy mechanism');
item := TListItem.Create;
item.ItemObject := aItem;
if Assigned(aItem) then
begin
aItem.GetInterface(IUnknown, item.ItemInterface);
// If the object being added is reference counted then its presence in this
// list ensures it will not be freed unless and until it is removed.
//
// But if the object is NOT reference counted then it could be destroyed
// while in this list; we need to subscribe to its On_Destroy event so
// that we can remove the item from the list if it is destroyed.
//
// NOTE: Subscribing to the On_Destroy of a reference counted object
// establishes a mutual dependency between the list and the object
// which causes a death-embrace when the list is destroyed.
//
// i.e. Do NOT subscribe to reference counted object On_Destroy events!
if Supports(aItem, IInterfacedObject, intf)
and (NOT intf.IsReferenceCounted)
and Supports(aItem, IOn_Destroy, onDestroy) then
onDestroy.Add(OnItemDestroyed);
end;
result := IndexOf(aItem);
if result <> -1 then
EXIT;
result := aIndex;
if (result = -1) or (result >= fItems.Count) then
result := fItems.Add(item)
else
fItems.Insert(result, item);
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
function TInterfacedObjectList.Remove(const aItem: IInterface): Boolean;
var
idx: Integer;
begin
idx := IndexOf(aItem);
result := idx <> -1;
if result then
Delete(idx);
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
function TInterfacedObjectList.Remove(const aItem: TObject): Boolean;
var
idx: Integer;
begin
idx := IndexOf(aItem);
result := idx <> -1;
if result then
Delete(idx);
end;
end.
|
{ Routines that manipulate individual menu entries.
}
module gui_menu;
define gui_menu_ent_add;
define gui_menu_ent_add_str;
define gui_menu_ent_draw;
define gui_menu_ent_refresh;
define gui_menu_ent_pixel;
define gui_menu_ent_select;
define gui_menu_ent_next;
define gui_menu_ent_prev;
%include 'gui2.ins.pas';
{
********************************************************************************
*
* Subroutine GUI_MENU_ENT_ADD (MENU, NAME, SHCUT, ID)
*
* Add a new entry to the end of the menu. NAME is the name to display to the
* user for this entry. SHCUT is the 1-N character position in NAME of the
* shortcut key for this entry. This character will be displayed underlined.
* SHCUT of 0 indicates no shortcut key exists for this entry. ID is an
* arbitrary integer value that will be returned to the application when this
* entry is selected.
}
procedure gui_menu_ent_add ( {add new entry to end of menu}
in out menu: gui_menu_t; {menu object}
in name: univ string_var_arg_t; {name to display to user for this choice}
in shcut: string_index_t; {NAME index for shortcut key, 0 = none}
in id: sys_int_machine_t); {ID returned when this entry picked}
val_param;
var
ent_p: gui_menent_p_t; {pointer to new menu entry}
kid: rend_key_id_t; {RENDlib ID for shortcut key}
keys_p: rend_key_ar_p_t; {pointer to list of RENDlib keys}
nk: sys_int_machine_t; {number of RENDlib keys}
label
done_shcut;
begin
util_mem_grab ( {allocate memory for the new menu entry}
sizeof(ent_p^), menu.mem_p^, false, ent_p);
{
* Link the new menu entry to the end of the menu entries chain.
}
if menu.first_p = nil
then begin {this is first entry in menu}
menu.first_p := ent_p;
ent_p^.prev_p := nil;
end
else begin {there is an existing entries chain}
menu.last_p^.next_p := ent_p;
ent_p^.prev_p := menu.last_p;
end
;
ent_p^.next_p := nil; {this entry is at end of chain}
menu.last_p := ent_p;
{
* Fill in this menu entry descriptor.
}
string_alloc ( {allocate memory for entry name string}
name.len, menu.mem_p^, false, ent_p^.name_p);
string_copy (name, ent_p^.name_p^); {save entry name string}
ent_p^.id := id; {application ID for this entry}
ent_p^.shcut := 0; {init to no shortcut key for this entry}
ent_p^.xl := 0.0; {display coordinates not set yet}
ent_p^.xr := 0.0;
ent_p^.yb := 0.0;
ent_p^.yt := 0.0;
ent_p^.xtext := 0.0;
ent_p^.key_p := nil; {init to no modifier key}
ent_p^.mod_req := []; {init to no modifier keys required}
ent_p^.mod_not := []; {init to no modifier keys disallowed}
ent_p^.flags := [ {init flags for this entry}
gui_entflag_vis_k, {entry will be visible}
gui_entflag_selectable_k]; {entry is candidate for user selection}
if {name ends in "..."}
(name.len >= 3) and
(name.str[name.len] = '.') and
(name.str[name.len - 1] = '.') and
(name.str[name.len - 2] = '.')
then begin
ent_p^.flags := {flag entry as bringing up anothe menu level}
ent_p^.flags + [gui_entflag_nlevel_k];
end;
{
* Deal with special shortcut key issues. The entry has been initialized
* as if there is no shortcut key.
}
if (shcut <= 0) or (shcut > ent_p^.name_p^.len) {SHCUT argument out of range ?}
then goto done_shcut;
ent_p^.shcut := shcut; {set shortcut character index}
kid := {get RENDlib ID for shortcut key, if any}
gui_key_alpha_id (ent_p^.name_p^.str[ent_p^.shcut]);
if kid = rend_key_none_k then goto done_shcut; {no such key is available ?}
rend_get.keys^ (keys_p, nk); {get list of all available keys}
ent_p^.key_p := addr(keys_p^[kid]); {get pointer to descriptor for shortcut key}
ent_p^.mod_req := []; {no modifier keys required with shortcut key}
ent_p^.mod_not := [ {modifiers not allowed with shortcut key}
rend_key_mod_ctrl_k, {control}
rend_key_mod_alt_k]; {ALT}
if gui_menflag_alt_k in menu.flags then begin {ALT required with shcut key ?}
ent_p^.mod_req := ent_p^.mod_req + [rend_key_mod_alt_k]; {ALT is required}
ent_p^.mod_not := ent_p^.mod_not - [rend_key_mod_alt_k]; {ALT allowed}
end;
done_shcut: {all done dealing with shortcut key setup}
end;
{
********************************************************************************
*
* Subroutine GUI_MENU_ENT_ADD_STR (MENU, NAME, SHCUT, ID)
*
* Just like GUI_MENU_ENT_ADD, above, except that NAME is a regular string
* instead of a var string.
}
procedure gui_menu_ent_add_str ( {add entry to menu, takes regular string}
in out menu: gui_menu_t; {menu object}
in name: string; {name to display to user for this choice}
in shcut: string_index_t; {NAME index for shortcut key, 0 = none}
in id: sys_int_machine_t); {ID returned when this entry picked}
val_param;
var
vname: string_var80_t; {var string version of NAME}
begin
vname.max := size_char(vname.str); {init local var string}
string_vstring (vname, name, size_char(name));
gui_menu_ent_add ( {call routine to do the real work}
menu, vname, shcut, id);
end;
{
********************************************************************************
*
* Subroutine GUI_MENU_ENT_DRAW (MENU, ENT)
*
* Low level routine to perform the actual drawing of a menu entry.
* Applications should call GUI_MENU_ENT_REFRESH, which causes the specfic part
* of the menu window to be refreshed. This routine does the actual drawing,
* and is for use within the menu window drawing routine.
}
procedure gui_menu_ent_draw ( {draw one entry of a menu}
in out menu: gui_menu_t; {menu containing entry}
in ent: gui_menent_t); {descriptor of entry to draw}
val_param;
const
usfore_k = 0.4; {unselectable entry foreground color fraction}
usback_k = 1.0 - usfore_k; {unselectable entry background color fraction}
var
col_fore, col_back: rend_rgb_t; {foreground and background colors}
bv, up, ll: vect_2d_t; {character string size/position values}
x, y: real; {scratch coordinate}
label
done_shcut;
begin
if not gui_win_clip (menu.win, ent.xl, ent.xr, ent.yb, ent.yt)
then return; {whole entry clipped off ?}
rend_set.enter_rend^; {push one level into graphics mode}
if gui_entflag_selected_k in ent.flags
then begin {this entry is selected}
col_fore := menu.col_fore_sel;
col_back := menu.col_back_sel;
end
else begin {this entry is not selected}
col_fore := menu.col_fore;
col_back := menu.col_back;
end
;
if not (gui_entflag_selectable_k in ent.flags) then begin {user can't select ent ?}
col_fore.red := col_fore.red * usfore_k + col_back.red * usback_k; {"grayed" col}
col_fore.grn := col_fore.grn * usfore_k + col_back.grn * usback_k;
col_fore.blu := col_fore.blu * usfore_k + col_back.blu * usback_k;
end;
rend_set.rgb^ (col_back.red, col_back.grn, col_back.blu); {clear to background}
rend_prim.clear_cwind^;
rend_set.rgb^ (col_fore.red, col_fore.grn, col_fore.blu); {set to foreground color}
rend_set.cpnt_2d^ ( {go to left center of text string}
ent.xtext, (ent.yb + ent.yt) * 0.5);
rend_prim.text^ (ent.name_p^.str, ent.name_p^.len); {draw the entry name}
{
* Underline the shortcut letter, if any.
}
if ent.shcut = 0 then goto done_shcut; {no shortcut letter ?}
if ent.shcut > 1
then begin {shortcut letter is not first letter}
rend_get.txbox_txdraw^ ( {get size of string up to shortcut letter}
ent.name_p^.str, ent.shcut - 1, {string to measure}
bv, up, ll); {returned string metrics}
x := ent.xtext + bv.x; {make left X of shortcut letter}
end
else begin {shortcut letter is first letter}
x := ent.xtext; {set left X of shortcut letter}
end
;
rend_get.txbox_txdraw^ ( {get size of shortcut letter}
ent.name_p^.str[ent.shcut], 1, {string to measure}
bv, up, ll); {returned string metrics}
y := {make Y coordinate of underline}
(ent.yb + ent.yt) * 0.5 - {start in middle of character cell}
menu.tparm.size * (menu.tparm.height * 0.5 + {down to bottom of character cell}
menu.tparm.lspace * 0.40); {to near bottom of vertical padding}
rend_set.cpnt_2d^ (x, y); {go to left end of underline}
rend_prim.vect_2d^ (x + bv.x, y); {draw to right end of underline}
done_shcut: {all done underlining the shortcut letter}
rend_set.exit_rend^; {pop back one level from graphics mode}
end;
{
********************************************************************************
*
* Subroutine GUI_MENU_ENT_REFRESH (MENU, ENT)
*
* Unconditionally redraw the entry ENT of the menu MENU.
}
procedure gui_menu_ent_refresh ( {refresh the graphics of a menu entry}
in out menu: gui_menu_t; {menu containing entry}
in ent: gui_menent_t); {descriptor of entry to draw}
val_param;
begin
gui_win_draw ( {draw the part of menu window with this entry}
menu.win, {window to redraw}
ent.xl, ent.xr, {left and right draw limits}
ent.yb, ent.yt); {bottom and top draw limits}
end;
{
********************************************************************************
*
* Subroutine GUI_MENU_ENT_PIXEL (MENU, X, Y, ENT_P)
*
* Determine which menu entry, if any, the pixel X,Y is in. ENT_P is returned
* pointing to the menu entry. If X,Y is not within a menu entry then ENT_P is
* returned NIL. X and Y are in RENDlib 2DIMI coordinates.
}
procedure gui_menu_ent_pixel ( {find menu entry containing a pixel}
in out menu: gui_menu_t; {menu object}
in x, y: sys_int_machine_t; {pixel coordinate to test for}
out ent_p: gui_menent_p_t); {returned pointer to selected entry or NIL}
val_param;
var
rp: vect_2d_t; {RENDlib 2DIM point coordinates}
mp: vect_2d_t; {menu 2D coordinates}
begin
rp.x := x + 0.5; {make 2DIM coordinate at pixel center}
rp.y := y + 0.5;
rend_get.bxfpnt_2d^ (rp, mp); {make menu 2D coordinate in MP}
ent_p := menu.first_p; {init to first entry in menu}
while ent_p <> nil do begin {once for each entry in the menu}
if {this is the selected entry ?}
(gui_entflag_vis_k in ent_p^.flags) and {entry is drawable ?}
(mp.x >= ent_p^.xl) and (mp.x <= ent_p^.xr) and {within horizontally ?}
(mp.y >= ent_p^.yb) and (mp.y <= ent_p^.yt) {within vertically ?}
then return;
ent_p := ent_p^.next_p; {advance to next entry in the menu}
end; {back to process this new entry}
end;
{
********************************************************************************
*
* Subroutine GUI_MENU_ENT_SELECT (MENU, SEL_P, NEW_P)
*
* Change the selected menu entry from that pointed to by SEL_P to the one
* pointed to by NEW_P. SEL_P is updated to point to the new selected menu
* entry. Either pointer may be NIL to indicate no entry is selected.
*
* The entries are re-drawn as appropriate.
}
procedure gui_menu_ent_select ( {select new menu entry}
in out menu: gui_menu_t; {menu object}
in out sel_p: gui_menent_p_t; {pointer to old selected entry, updated}
in new_p: gui_menent_p_t); {pointer to new entry to select}
val_param;
begin
if new_p = sel_p then return; {nothing is being changed ?}
if sel_p <> nil then begin {an existing entry is being deselected ?}
sel_p^.flags := sel_p^.flags - [gui_entflag_selected_k]; {de-select entry}
gui_menu_ent_refresh (menu, sel_p^); {update display of deselected entry}
end;
sel_p := new_p; {update pointer to currently selected entry}
if sel_p <> nil then begin {new entry is being selected ?}
sel_p^.flags := sel_p^.flags + [gui_entflag_selected_k]; {select entry}
gui_menu_ent_refresh (menu, sel_p^); {update display of selected entry}
end;
end;
{
********************************************************************************
*
* Subroutine GUI_MENU_ENT_NEXT (MENU, SEL_P)
*
* Select the next selectable entry after the one pointed to by SEL_P. SEL_P
* will be updated to point to the new selected entry.
}
procedure gui_menu_ent_next ( {select next sequential selectable menu entry}
in out menu: gui_menu_t; {menu object}
in out sel_p: gui_menent_p_t); {pointer to selected menu entry}
val_param;
var
start_p: gui_menent_p_t; {starting menu entry pointer}
ent_p: gui_menent_p_t; {pointer to current menu entry}
begin
if sel_p = nil
then begin {no entry is currently selected}
start_p := menu.first_p; {start at first entry}
end
else begin {there is a currently selected entry}
start_p := sel_p^.next_p; {start at next entry after current}
if start_p = nil then start_p := menu.first_p; {wrap back to first entry ?}
end
;
if start_p = nil then return; {no entries in menu, nothing to do ?}
ent_p := start_p; {init current entry to starting entry}
while {loop until next selectable entry}
not (gui_entflag_selectable_k in ent_p^.flags)
do begin
ent_p := ent_p^.next_p; {advance to next entry}
if ent_p = nil then ent_p := menu.first_p; {wrap back to first entry ?}
if ent_p = start_p then return; {go back to starting entry ?}
end;
{
* ENT_P is pointing to the entry to make the new selected entry.
}
gui_menu_ent_select (menu, sel_p, ent_p); {updated selected menu entry}
end;
{
********************************************************************************
*
* Local subroutine GUI_MENU_ENT_PREV (MENU, SEL_P)
*
* Select the previous selectable entry after the one pointed to by SEL_P.
* SEL_P will be updated to point to the new selected entry.
}
procedure gui_menu_ent_prev ( {select previous sequential selectable entry}
in out menu: gui_menu_t; {menu object}
in out sel_p: gui_menent_p_t); {pointer to selected menu entry}
val_param;
var
start_p: gui_menent_p_t; {starting menu entry pointer}
ent_p: gui_menent_p_t; {pointer to current menu entry}
begin
if sel_p = nil
then begin {no entry is currently selected}
start_p := menu.last_p; {start at last entry}
end
else begin {there is a currently selected entry}
start_p := sel_p^.prev_p; {start at previous entry before current}
if start_p = nil then start_p := menu.last_p; {wrap back to last entry ?}
end
;
if start_p = nil then return; {no entries in menu, nothing to do ?}
ent_p := start_p; {init current entry to starting entry}
while {loop until next selectable entry}
not (gui_entflag_selectable_k in ent_p^.flags)
do begin
ent_p := ent_p^.prev_p; {advance to previous entry}
if ent_p = nil then ent_p := menu.last_p; {wrap back to last entry ?}
if ent_p = start_p then return; {go back to starting entry ?}
end;
{
* ENT_P is pointing to the entry to make the new selected entry.
}
gui_menu_ent_select (menu, sel_p, ent_p); {updated selected menu entry}
end;
|
unit DriveStat;
interface
uses Classes,
sysUtils;
type
tDriveStat = class
private
fTotalS : uInt64;
fFreeS : UInt64;
public
property TotalS: uInt64 read FTotalS write FTotalS;
property FreeS: uInt64 read FFreeS write FFreeS;
end;
implementation
end. |
UNIT StrUtil;
{ some string utilites }
interface
TYPE
SearchPattern = RECORD
str : string;
strlen : BYTE;
code : SHORTINT;
END;
procedure StartStringSearch(InputStr : string; VAR sr : SearchPattern);
{ initialize search variables }
function StringSearch(ch : CHAR; VAR sr : SearchPattern) : BOOLEAN;
function Capitalize(s : String) : String;
function StripTrail(s : String;StripChar : CHAR) : String;
function Compress(s : String;StripChar : CHAR) : String;
implementation
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
procedure StartStringSearch(InputStr : string; VAR sr : SearchPattern);
{ initialize search variables }
BEGIN
sr.code := 1;
sr.str := InputStr;
sr.strlen := length(sr.str);
END;
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
function StringSearch(ch : CHAR; VAR sr: SearchPattern) : BOOLEAN;
{ code = 0 success
code > 0 search in process }
BEGIN
IF sr.code > 0 THEN BEGIN
IF ch = sr.str[sr.code] THEN
sr.code := sr.code + 1
ELSE
sr.code := 1;
END;
IF sr.code > sr.strlen THEN BEGIN
sr.code := 1;
StringSearch := TRUE; END
ELSE
StringSearch := FALSE;
END;
function Capitalize(s : String) : String;
var
i : Integer;
begin
for i := 1 to Length(s) do
s[i] := UpCase(s[i]);
Capitalize := s;
end;
function StripTrail(s : String;StripChar : CHAR) : String;
VAR
i : BYTE;
BEGIN
i := ORD(s[0]);
WHILE s[i] = StripChar DO
BEGIN
dec(i);
s[0] := CHR(i);
END;
StripTrail := s;
END;
function Compress(s : String;StripChar : CHAR) : String;
VAR
tempstr : STRING;
i,j : BYTE;
BEGIN
j := 0;
tempstr := '';
FOR i := 1 to ORD(s[0]) DO
BEGIN
IF NOT (s[i] = StripChar) THEN
BEGIN
INC(j);
tempstr[j] := s[i]
END;
END;
tempstr[0] := chr(j);
Compress := tempstr;
END;
END.
|
unit ejb_sidl_java_util_c;
{This file was generated on 28 Feb 2001 10:06:55 GMT by version 03.03.03.C1.06}
{of the Inprise VisiBroker idl2pas CORBA IDL compiler. }
{Please do not edit the contents of this file. You should instead edit and }
{recompile the original IDL which was located in the file sidl.idl. }
{Delphi Pascal unit : ejb_sidl_java_util_c }
{derived from IDL module : util }
interface
uses
CORBA,
ejb_sidl_java_util_i;
type
TCollectionHelper = class;
TEnumerationHelper = class;
TListHelper = class;
TVectorHelper = class;
TDateHelper = class;
TDate = class;
TCollectionHelper = class
class procedure Insert (var _A: CORBA.Any; const _Value : ejb_sidl_java_util_i.Collection);
class function Extract(const _A: CORBA.Any): ejb_sidl_java_util_i.Collection;
class function TypeCode : CORBA.TypeCode;
class function RepositoryId: string;
class function Read (const _Input : CORBA.InputStream) : ejb_sidl_java_util_i.Collection;
class procedure Write(const _Output : CORBA.OutputStream; const _Value : ejb_sidl_java_util_i.Collection);
end;
TEnumerationHelper = class
class procedure Insert (var _A: CORBA.Any; const _Value : ejb_sidl_java_util_i.Enumeration);
class function Extract(const _A: CORBA.Any): ejb_sidl_java_util_i.Enumeration;
class function TypeCode : CORBA.TypeCode;
class function RepositoryId: string;
class function Read (const _Input : CORBA.InputStream) : ejb_sidl_java_util_i.Enumeration;
class procedure Write(const _Output : CORBA.OutputStream; const _Value : ejb_sidl_java_util_i.Enumeration);
end;
TListHelper = class
class procedure Insert (var _A: CORBA.Any; const _Value : ejb_sidl_java_util_i.List);
class function Extract(const _A: CORBA.Any): ejb_sidl_java_util_i.List;
class function TypeCode : CORBA.TypeCode;
class function RepositoryId: string;
class function Read (const _Input : CORBA.InputStream) : ejb_sidl_java_util_i.List;
class procedure Write(const _Output : CORBA.OutputStream; const _Value : ejb_sidl_java_util_i.List);
end;
TVectorHelper = class
class procedure Insert (var _A: CORBA.Any; const _Value : ejb_sidl_java_util_i.Vector);
class function Extract(const _A: CORBA.Any): ejb_sidl_java_util_i.Vector;
class function TypeCode : CORBA.TypeCode;
class function RepositoryId: string;
class function Read (const _Input : CORBA.InputStream) : ejb_sidl_java_util_i.Vector;
class procedure Write(const _Output : CORBA.OutputStream; const _Value : ejb_sidl_java_util_i.Vector);
end;
TDateHelper = class
class procedure Insert (var _A: CORBA.Any; const _Value : ejb_sidl_java_util_i.Date);
class function Extract(const _A: CORBA.Any): ejb_sidl_java_util_i.Date;
class function TypeCode : CORBA.TypeCode;
class function RepositoryId: string;
class function Read (const _Input : CORBA.InputStream) : ejb_sidl_java_util_i.Date;
class procedure Write(const _Output : CORBA.OutputStream; const _Value : ejb_sidl_java_util_i.Date);
end;
TDate = class (TInterfacedObject, ejb_sidl_java_util_i.Date)
private
time : Int64;
constructor Create; overload;
public
function _get_time : Int64; virtual;
procedure _set_time ( const _value : Int64 ); virtual;
constructor Create (const time : Int64
); overload;
end;
implementation
class procedure TCollectionHelper.Insert(var _A : CORBA.Any; const _Value : ejb_sidl_java_util_i.Collection);
var
_Output : CORBA.OutputStream;
begin
_Output := ORB.CreateOutputStream;
TCollectionHelper.Write(_Output, _Value);
ORB.PutAny(_A, TCollectionHelper.TypeCode, _Output);
end;
class function TCollectionHelper.Extract(const _A : CORBA.Any): ejb_sidl_java_util_i.Collection;
var
_Input : InputStream;
begin
Orb.GetAny(_A, _Input);
Result := TCollectionHelper.Read(_Input);
end;
class function TCollectionHelper.TypeCode: CORBA.TypeCode;
begin
Result := ORB.CreateSequenceTC(0, ORB.CreateTC(Integer(tk_any)));
end;
class function TCollectionHelper.RepositoryId: string;
begin
Result := 'IDL:borland.com/sidl/java/util/Collection:1.0';
end;
class function TCollectionHelper.Read(const _Input : CORBA.InputStream) : ejb_sidl_java_util_i.Collection;
var
L0 : Cardinal;
I0 : Cardinal;
begin
_Input.ReadULong(L0);
SetLength(Result, L0);
if (L0 > 0) then
begin
for I0 := 0 to High(Result) do
begin
_Input.ReadAny(Result[I0]);
end;
end;
end;
class procedure TCollectionHelper.Write(const _Output: CORBA.OutputStream; const _Value: ejb_sidl_java_util_i.Collection);
var
L0 : Cardinal;
I0 : Cardinal;
begin
L0 := Length(_Value);
_Output.WriteULong(L0);
if (L0 > 0) then
begin
for I0 := 0 to High(_Value) do
begin
_Output.WriteAny(_Value[I0]);
end;
end;
end;
class procedure TEnumerationHelper.Insert(var _A : CORBA.Any; const _Value : ejb_sidl_java_util_i.Enumeration);
var
_Output : CORBA.OutputStream;
begin
_Output := ORB.CreateOutputStream;
TEnumerationHelper.Write(_Output, _Value);
ORB.PutAny(_A, TEnumerationHelper.TypeCode, _Output);
end;
class function TEnumerationHelper.Extract(const _A : CORBA.Any): ejb_sidl_java_util_i.Enumeration;
var
_Input : InputStream;
begin
Orb.GetAny(_A, _Input);
Result := TEnumerationHelper.Read(_Input);
end;
class function TEnumerationHelper.TypeCode: CORBA.TypeCode;
begin
Result := ORB.CreateSequenceTC(0, ORB.CreateTC(Integer(tk_any)));
end;
class function TEnumerationHelper.RepositoryId: string;
begin
Result := 'IDL:borland.com/sidl/java/util/Enumeration:1.0';
end;
class function TEnumerationHelper.Read(const _Input : CORBA.InputStream) : ejb_sidl_java_util_i.Enumeration;
var
L0 : Cardinal;
I0 : Cardinal;
begin
_Input.ReadULong(L0);
SetLength(Result, L0);
if (L0 > 0) then
begin
for I0 := 0 to High(Result) do
begin
_Input.ReadAny(Result[I0]);
end;
end;
end;
class procedure TEnumerationHelper.Write(const _Output: CORBA.OutputStream; const _Value: ejb_sidl_java_util_i.Enumeration);
var
L0 : Cardinal;
I0 : Cardinal;
begin
L0 := Length(_Value);
_Output.WriteULong(L0);
if (L0 > 0) then
begin
for I0 := 0 to High(_Value) do
begin
_Output.WriteAny(_Value[I0]);
end;
end;
end;
class procedure TListHelper.Insert(var _A : CORBA.Any; const _Value : ejb_sidl_java_util_i.List);
var
_Output : CORBA.OutputStream;
begin
_Output := ORB.CreateOutputStream;
TListHelper.Write(_Output, _Value);
ORB.PutAny(_A, TListHelper.TypeCode, _Output);
end;
class function TListHelper.Extract(const _A : CORBA.Any): ejb_sidl_java_util_i.List;
var
_Input : InputStream;
begin
Orb.GetAny(_A, _Input);
Result := TListHelper.Read(_Input);
end;
class function TListHelper.TypeCode: CORBA.TypeCode;
begin
Result := ORB.CreateSequenceTC(0, ORB.CreateTC(Integer(tk_any)));
end;
class function TListHelper.RepositoryId: string;
begin
Result := 'IDL:borland.com/sidl/java/util/List:1.0';
end;
class function TListHelper.Read(const _Input : CORBA.InputStream) : ejb_sidl_java_util_i.List;
var
L0 : Cardinal;
I0 : Cardinal;
begin
_Input.ReadULong(L0);
SetLength(Result, L0);
if (L0 > 0) then
begin
for I0 := 0 to High(Result) do
begin
_Input.ReadAny(Result[I0]);
end;
end;
end;
class procedure TListHelper.Write(const _Output: CORBA.OutputStream; const _Value: ejb_sidl_java_util_i.List);
var
L0 : Cardinal;
I0 : Cardinal;
begin
L0 := Length(_Value);
_Output.WriteULong(L0);
if (L0 > 0) then
begin
for I0 := 0 to High(_Value) do
begin
_Output.WriteAny(_Value[I0]);
end;
end;
end;
class procedure TVectorHelper.Insert(var _A : CORBA.Any; const _Value : ejb_sidl_java_util_i.Vector);
var
_Output : CORBA.OutputStream;
begin
_Output := ORB.CreateOutputStream;
TVectorHelper.Write(_Output, _Value);
ORB.PutAny(_A, TVectorHelper.TypeCode, _Output);
end;
class function TVectorHelper.Extract(const _A : CORBA.Any): ejb_sidl_java_util_i.Vector;
var
_Input : InputStream;
begin
Orb.GetAny(_A, _Input);
Result := TVectorHelper.Read(_Input);
end;
class function TVectorHelper.TypeCode: CORBA.TypeCode;
begin
Result := ORB.CreateSequenceTC(0, ORB.CreateTC(Integer(tk_any)));
end;
class function TVectorHelper.RepositoryId: string;
begin
Result := 'IDL:borland.com/sidl/java/util/Vector:1.0';
end;
class function TVectorHelper.Read(const _Input : CORBA.InputStream) : ejb_sidl_java_util_i.Vector;
var
L0 : Cardinal;
I0 : Cardinal;
begin
_Input.ReadULong(L0);
SetLength(Result, L0);
if (L0 > 0) then
begin
for I0 := 0 to High(Result) do
begin
_Input.ReadAny(Result[I0]);
end;
end;
end;
class procedure TVectorHelper.Write(const _Output: CORBA.OutputStream; const _Value: ejb_sidl_java_util_i.Vector);
var
L0 : Cardinal;
I0 : Cardinal;
begin
L0 := Length(_Value);
_Output.WriteULong(L0);
if (L0 > 0) then
begin
for I0 := 0 to High(_Value) do
begin
_Output.WriteAny(_Value[I0]);
end;
end;
end;
class procedure TDateHelper.Insert(var _A : CORBA.Any; const _Value : ejb_sidl_java_util_i.Date);
var
_Output : CORBA.OutputStream;
begin
_Output := ORB.CreateOutputStream;
TDateHelper.Write(_Output, _Value);
ORB.PutAny(_A, TDateHelper.TypeCode, _Output);
end;
class function TDateHelper.Extract(const _A : CORBA.Any) : ejb_sidl_java_util_i.Date;
var
_Input : CORBA.InputStream;
begin
Orb.GetAny(_A, _Input);
Result := TDateHelper.Read(_Input);
end;
class function TDateHelper.TypeCode : CORBA.TypeCode;
var
_Seq: StructMemberSeq;
begin
SetLength(_Seq, 1);
_Seq[0].Name := 'time';
_Seq[0].TC := ORB.CreateTC(Integer(tk_longlong));
Result := ORB.MakeStructureTypecode(RepositoryID, 'Date', _Seq);
end;
class function TDateHelper.RepositoryId : string;
begin
Result := 'IDL:borland.com/sidl/java/util/Date:1.0';
end;
class function TDateHelper.Read(const _Input : CORBA.InputStream) : ejb_sidl_java_util_i.Date;
var
_Value : ejb_sidl_java_util_c.TDate;
begin
_Value := ejb_sidl_java_util_c.TDate.Create;
_Input.ReadLongLong(_Value.time);
Result := _Value;
end;
class procedure TDateHelper.Write(const _Output : CORBA.OutputStream; const _Value : ejb_sidl_java_util_i.Date);
begin
_Output.WriteLongLong(_Value.time);
end;
constructor TDate.Create;
begin
inherited Create;
end;
constructor TDate.Create(const time: Int64);
begin
Self.time := time;
end;
function TDate._get_time: Int64;
begin
Result := time;
end;
procedure TDate._set_time(const _Value : Int64);
begin
time := _Value;
end;
initialization
end. |
function Int(X: Double): Integer;
begin
Result := Trunc(X);
end;
function Ceil(X: Double): Integer;
begin
Result := Integer(Trunc(X));
if Frac(X) > 0 then
Inc(Result);
end;
function Floor(X: Double): Integer;
begin
Result := Integer(Trunc(X));
if Frac(X) < 0 then
Dec(Result);
end;
function IfThenInt(AValue: Boolean; ATrue: Integer; AFalse: Integer): Integer;
begin
if AValue then
Result := ATrue
else
Result := AFalse;
end;
function IfThenDbl(AValue: Boolean; ATrue: Double; AFalse: Double): Double;
begin
if AValue then
Result := ATrue
else
Result := AFalse;
end;
function MinInt(A, B: Integer): Integer;
begin
Result := IfThenInt(A < B, A, B);
end;
function MinDbl(A, B: Double): Double;
begin
Result := IfThenDbl(A < B, A, B);
end;
function MaxInt(A, B: Integer): Integer;
begin
Result := IfThenInt(A > B, A, B);
end;
function MaxDbl(A, B: Double): Double;
begin
Result := IfThenDbl(A > B, A, B);
end;
function SignInt(AValue: Integer): Integer;
begin
Result := 0;
if AValue < 0 then
Result := -1
else if AValue > 0 then
Result := 1;
end;
function SignDbl(AValue: Double): Integer;
begin
Result := 0;
if AValue < 0 then
Result := -1
else if AValue > 0 then
Result := 1;
end;
procedure SwapInt(var A, B: Integer);
var
T: Integer;
begin
T := A;
A := B;
B := T;
end;
procedure SwapDbl(var A, B: Double);
var
T: Double;
begin
T := A;
A := B;
B := T;
end;
function InRangeInt(AValue, AMin, AMax: Integer): Boolean;
begin
Result := (AValue >= AMin) and (AValue <= AMax);
end;
function InRangeDbl(AValue, AMin, AMax: Double): Boolean;
begin
Result := (AValue >= AMin) and (AValue <= AMax);
end;
function EnsureRangeInt(AValue, AMin, AMax: Integer): Integer;
begin
if AValue < AMin then
Result := AMin
else if AValue > AMax then
Result := AMax
else
Result := AValue;
end;
function EnsureRangeDbl(AValue, AMin, AMax: Double): Double;
begin
if AValue < AMin then
Result := AMin
else if AValue > AMax then
Result := AMax
else
Result := AValue;
end;
function MinElemInt(Data: array of Integer): Integer;
var
I: Integer;
begin
Result := Data[Low(Data)];
for I := Low(Data) + 1 to High(Data) do
if Result > Data[I] then
Result := Data[I];
end;
function MinElemDbl(Data: array of Double): Double;
var
I: Integer;
begin
Result := Data[Low(Data)];
for I := Low(Data) + 1 to High(Data) do
if Result > Data[I] then
Result := Data[I];
end;
function MaxElemInt(Data: array of Integer): Integer;
var
I: Integer;
begin
Result := Data[Low(Data)];
for I := Low(Data) + 1 to High(Data) do
if Result < Data[I] then
Result := Data[I];
end;
function MaxElemDbl(Data: array of Double): Double;
var
I: Integer;
begin
Result := Data[Low(Data)];
for I := Low(Data) + 1 to High(Data) do
if Result < Data[I] then
Result := Data[I];
end;
// A = B -> True
// A <> B -> False
function SameValue(const A, B: Double): Boolean;
var
Epsilon: Double;
FUZZ_FACTOR: Integer;
DOUBLE_RESOLUTION: Double;
begin
FUZZ_FACTOR := 1000;
DOUBLE_RESOLUTION := 1E-15 * FUZZ_FACTOR;
Epsilon := MaxDbl(MinDbl(Abs(A), Abs(B)) * DOUBLE_RESOLUTION, DOUBLE_RESOLUTION);
if A > B then
Result := (A - B) <= Epsilon
else
Result := (B - A) <= Epsilon;
end;
// A < B -> -1
// A = B -> 0
// A > B -> 1
function CompareValue(const A, B: Double): Integer;
begin
if SameValue(A, B) then
Result := 0
else if A < B then
Result := -1
else
Result := 1;
end; |
unit classe.aluno_disciplina;
interface
Uses TEntity, AttributeEntity, SysUtils;
type
[TableName('Aluno_Disciplina')]
TAluno_Disciplina = class(TGenericEntity)
private
FIdAluno:integer;
FIdDisciplina:integer;
FNotaTrabSegPer: Extended;
FNotaTrabPriPer: Extended;
FNotaQuaPer: Extended;
FNotaTrabQuaPer: Extended;
FNotaTrabTerPer: Extended;
FNotaPriPer: Extended;
FNotaSegPer: Extended;
FNotaTerPer: Extended;
procedure setIdAluno(const Value: integer);
procedure setIdDisciplina(const Value: integer);
procedure setNotaPriPer(const Value: Extended);
procedure setNotaQuaPer(const Value: Extended);
procedure setNotaTerPer(const Value: Extended);
procedure setNotaTrabPriPer(const Value: Extended);
procedure setNotaTrabQuaPer(const Value: Extended);
procedure setNotaTrabSegPer(const Value: Extended);
procedure setNotaTrabTerPer(const Value: Extended);
procedure setNotaSegPer(const Value: Extended);
public
[KeyField('IDALUNO')]
[FieldName('IDALUNO')]
property CodigoAluno: integer read FIdAluno write setIdAluno;
[FieldName('IDDISCIPLINA')]
property CodigoDisciplina: integer read FIdDisciplina write setIdDisciplina;
[FieldName('NOTAPRIPER')]
property NotaPriPer: Extended read FNotaPriPer write setNotaPriPer;
[FieldName('NOTATRABPRIPER')]
property NotaTrabPriPer: Extended read FNotaTrabPriPer write setNotaTrabPriPer;
[FieldName('NOTASEGPER')]
property NotaSegPer: Extended read FNotaSegPer write setNotaSegPer;
[FieldName('NOTATRABSEGPER')]
property NotaTrabSegPer: Extended read FNotaTrabSegPer write setNotaTrabSegPer;
[FieldName('NOTATERPER')]
property NotaTerPer: Extended read FNotaTerPer write setNotaTerPer;
[FieldName('NOTATRABTERPER')]
property NotaTrabTerPer: Extended read FNotaTrabTerPer write setNotaTrabTerPer;
[FieldName('NOTAQUAPER')]
property NotaQuaPer: Extended read FNotaQuaPer write setNotaQuaPer;
[FieldName('NOTATRABQUAPER')]
property NotaTrabQuaPer: Extended read FNotaTrabQuaPer write setNotaTrabQuaPer;
function ToString:string; override;
end;
implementation
procedure TAluno_Disciplina.setIdDisciplina(const Value: integer);
begin
FIdDisciplina := Value;
end;
procedure TAluno_Disciplina.setNotaPriPer(const Value: Extended);
begin
FNotaPriPer := Value;
end;
procedure TAluno_Disciplina.setNotaQuaPer(const Value: Extended);
begin
FNotaQuaPer := Value;
end;
procedure TAluno_Disciplina.setNotaSegPer(const Value: Extended);
begin
FNotaSegPer := Value;
end;
procedure TAluno_Disciplina.setNotaTerPer(const Value: Extended);
begin
FNotaTerPer := Value;
end;
procedure TAluno_Disciplina.setNotaTrabPriPer(const Value: Extended);
begin
FNotaTrabPriPer := Value;
end;
procedure TAluno_Disciplina.setNotaTrabQuaPer(const Value: Extended);
begin
FNotaTrabQuaPer := Value;
end;
procedure TAluno_Disciplina.setNotaTrabSegPer(const Value: Extended);
begin
FNotaTrabSegPer := Value;
end;
procedure TAluno_Disciplina.setNotaTrabTerPer(const Value: Extended);
begin
FNotaTrabTerPer := Value;
end;
procedure TAluno_Disciplina.setIdAluno(const Value: integer);
begin
FIdAluno := Value;
end;
function TAluno_Disciplina.toString;
begin
result := ' Código Prof. : '+ IntToStr(CodigoAluno) +' Código Deisc. : '+IntToStr(CodigoDisciplina);
end;
end.
|
{
GMMarker unit
ES: contiene las clases bases necesarias para mostrar marcadores en un mapa de
Google Maps mediante el componente TGMMap
EN: includes the base classes needed to show markers on Google Map map using
the component TGMMap
=========================================================================
MODO DE USO/HOW TO USE
ES: poner el componente en el formulario, linkarlo a un TGMMap y poner los
marcadores a mostrar
EN: put the component into a form, link to a TGMMap and put the markers to show
=========================================================================
History:
ver 1.5.0
ES:
cambio: TCustomMarker -> añadida propiedad Direction (GC: issue 38)
EN:
change: TCustomMarker -> addod Direction property (GC: issue 38)
ver 1.2.X
ES:
cambio: TCustomMarker -> en el método LoadFromDataSet se añade el parámetro
opcional HTMLContentField (GC: issue 24).
cambio: TCustomMarker -> en el método LoadFromDataSet se añade control de la
existencia de los campos.
EN:
change: TCustomMarker -> added optional parameter HTMLContentField into
LoadFromDataSet method (GC: issue 24).
change: TCustomMarker -> the LoadFromDataSet method checks the existence of
the needed fields.
ver 1.1.0
ES:
cambio: TCustomMarker -> el método CenterMapToMarker se marca como deprecated,
en su lugar usar CenterMapTo.
nuevo: TCustomMarker -> añadida propiedad CrossOnDrag.
nuevo: TCustomGMMarker -> añadido evento OnCrossOnDragChange.
EN:
change: TCustomMarker -> CenterMapToMarker methos is marked as deprecated,
instead use CenterMapTo.
new: TCustomMarker -> added CrossOnDrag property.
new: TCustomGMMarker -> added OnCrossOnDragChange event.
ver 1.0.1
ES:
error: TCustomGMMarker -> corregido error en el método LoadFromDataSet (first
del DataSet).
EN:
bug: TCustomGMMarker -> bug fixed on LoadFromDataSet method (first from DataSet).
ver 1.0.0
ES:
cambio: se elimina la propiedad TCustomMarker.ColoredMarker para que sea
definida en los hijos como TColoredMarker.
cambio: se elimina la propiedad TCustomMarker.StyledMarker para que sea
definida en los hijos como TStyledMarker.
cambio: se ha añadido un parámetro al método TCustomGMMarker.LoadFromCSV,
IconColumn, para poder especificar el icono a mostrar por defecto.
nuevo: nuevo método TCustomGMMarker.LoadFromDataSet.
nuevo: TCustomGMMarker -> ZoomToPoints, establece el zoom óptimo para visualizar
todos los marcadores.
cambio: TCustomGMMarker -> ZoomMapToAllMarkers se marca como obsoleta.
EN:
change: TCustomMarker.ColoredMarker property is removed to be defined
in descendents as TColoredMarker.
change: TCustomMarker.StyledMarker property is removed to be defined
in descendents as TStyledMarker.
change: a new parameter is added in TCustomGMMarker.LoadFromCSV method,
IconColumn, to specify a default icon to show.
new: added new method TCustomGMMarker.LoadFromDataSet.
new: TCustomGMMarker -> ZoomToPoints, sets the optimal zoom to display all markers.
change: TCustomGMMarker -> ZoomMapToAllMarkers is now deprecated.
ver 0.1.9
ES:
nuevo: documentación
nuevo: se hace compatible con FireMonkey
nuevo: TCustomGMMarker -> añadido método ZoomMapToAllMarkers (gracias Hugo Pedersen)
EN:
new: documentation
new: now compatible with FireMonkey
nuevo: TCustomGMMarker -> added method ZoomMapToAllMarkers (thanks Hugo Pedersen)
ver 0.1.7
ES:
cambio: modificados métodos Set y ShowElement para que usen el nuevo método
ChangeProperties heredado de TLinkedComponent
cambio: suprimida clase TMarkerLatLng. Ahora se usa directamente la clase TLatLng
cambio: TMarker-> la pripiedad Position ahora es de tipo TLatLng.
cambio: TMarker-> añadida propiedad MarkerType para especificar el tipo de
marcador a mostrar (mtStandard, mtColored, mtStyledMarker).
cambio: TMarker-> añadida propiedad ColoredMarker para especificar la forma
del marcador si MarkerType = mtColored.
cambio: TMarker-> añadida propiedad StyledMarker para especificar la forma
del marcador si MarkerType = mtStyledMarker.
cambio: TGMMarker-> añadido método público LoadFromCSV para una carga masiva
de marcadores que estén en un archivo CSV (unos 500 cada 10 seg.).
cambio: TGMMarker-> 4 nuevos eventos: OnLoadFile y AfterLoadFile para el procesado
del fichero CSV, y OnColoredMarkerChange y OnStyledMarkerChange para el cambio
de las propiedades
EN:
change: modified all Set and ShowElements methods to use the new method
ChangeProperties inherited from TLinkedComponent
change: TMarkerLatLng class are deleted. Now it use the TLatLng class directly
change: TMarker-> the Position property now is a TLatLng.
change: TMarker-> added MarkerType property to specify the marker type to
show (mtStandard, mtColored, mtStyledMarker).
change: TMarker-> added ColoredMarker property to specify properties of marker
when MarkerType = mtColored.
change: TMarker-> added StyledMarker property to specify properties of marker
when MarkerType = mtStyledMarker.
change: TGMMarker-> added LoadFromCSV public method for a massive load of
markers that are in a CSV file (about 500 each 10 sec).
change: TGMMarker-> 4 news events: OnLoadFile and AfterLoadFile for processing
the CSV file, and OnColoredMarkerChange and OnStyledMarkerChange for changing
the properties
ver 0.1.5
ES:
error: se controlan la comilla simple en la propiedad Title
EN:
bug: the single quote is controled into Title property
ver 0.1.4
ES:
cambio: cambio en el JavaScript de algunos métodos Set
EN:
change: JavaScript changed from some Set methods
ver 0.1.3
ES:
nuevo: añadido propiedad Icon para especificar la imagen del marcador. Puede
ser una imagen en la web (url) o una imagen en el ordenador. En blanco será
la imagen por defecto.
nuevo: añadido evento OnIconChange
cambio: métodos Set cambiados para evitar duplicidad de código
EN:
new: added Icon property to specify a marker image. You can specify a web
image (url) or a file in the PC. Nothing for default image
new: added OnIconChange event
change: changed Set methods to avoid duplicate code
ver 0.1.2
ES:
error: algunas propiedades daban un error de JavaScript al modificarse
EN:
bug: some properties giving a JavaScript error when modifying
ver 0.1.1
ES:
nuevo: Añadido evento Assign a la clase TMarkerLatLng
cambio: Cuando se cambia la lat/lng de un marcador, éste cambia automáticamente en el mapa
EN:
new: Added Assign Assign to the TMarkerLatLng class
change: When a lat/lng is changed into a marker, this is automatically changed into the map
ver 0.1:
ES- primera versión
EN- first version
=========================================================================
IMPORTANTE PROGRAMADORES: Por favor, si tienes comentarios, mejoras,
ampliaciones, errores y/o cualquier otro tipo de sugerencia, envíame un correo a:
gmlib@cadetill.com
IMPORTANT PROGRAMMERS: please, if you have comments, improvements, enlargements,
errors and/or any another type of suggestion, please send me a mail to:
gmlib@cadetill.com
=========================================================================
Copyright (©) 2012, by Xavier Martinez (cadetill)
@author Xavier Martinez (cadetill)
@web http://www.cadetill.com
}
{*------------------------------------------------------------------------------
The GMMarker unit includes the base classes needed to show markers on Google Map map using the component TGMMap.
@author Xavier Martinez (cadetill)
@version 1.5.3
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
La unit GMMarker contiene las clases bases necesarias para mostrar marcadores en un mapa de Google Maps mediante el componente TGMMap
@author Xavier Martinez (cadetill)
@version 1.5.3
-------------------------------------------------------------------------------}
unit GMMarker;
{$I ..\gmlib.inc}
interface
uses
{$IFDEF DELPHIXE2}
System.Classes, System.Types, Data.DB,
{$ELSE}
Classes, Types, DB,
{$ENDIF}
GMLinkedComponents, GMConstants, GMClasses;
type
TCustomGMMarker = class;
TCustomMarker = class;
{*------------------------------------------------------------------------------
Internal class to determine animation of a marker.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Clase interna para determinar el tipo de animación de un marcador.
-------------------------------------------------------------------------------}
TAnimation = class(TPersistent)
private
FMarker: TCustomMarker;
{*------------------------------------------------------------------------------
If true, marker falls from the top of the map ending with a small bounce.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Si se establece a true, el marcador cae desde la parte superior del mapa terminando con un pequeño rebote.
-------------------------------------------------------------------------------}
FOnDrop: Boolean;
{*------------------------------------------------------------------------------
If true, marker bounces until animation is stopped.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Si se establece a true, el marcador rebota hasta parar la animación.
-------------------------------------------------------------------------------}
FBounce: Boolean;
{*------------------------------------------------------------------------------
Index position in the list FLinkedComponents of TCustomGMMap class.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Índice de la posición en la lista FLinkedComponents de la clase TCustomGMMap.
-------------------------------------------------------------------------------}
FIdxList: Cardinal;
procedure SetOnDrop(const Value: Boolean);
protected
{*------------------------------------------------------------------------------
Set Bounce property.
@param Value New value for Bounce property
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Establece la propiedad Bounce.
@param Value Nuevo valor para la propiedad Bounce
-------------------------------------------------------------------------------}
procedure SetBounce(const Value: Boolean); virtual;
property IdxList: Cardinal read FIdxList write FIdxList;
public
{*------------------------------------------------------------------------------
Constructor class
@param aOwner Owner.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Constructor de la clase
@param aOwner Propietario.
-------------------------------------------------------------------------------}
constructor Create(aOwner: TCustomMarker); virtual;
{*------------------------------------------------------------------------------
Assign method copies the contents of another similar object.
@param Source object to copy content
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
El método Assign copia el contenido de un objeto similar.
@param Source objeto a copiar el contenido
-------------------------------------------------------------------------------}
procedure Assign(Source: TPersistent); override;
published
property OnDrop: Boolean read FOnDrop write SetOnDrop default False;
property Bounce: Boolean read FBounce write SetBounce default False;
end;
{*------------------------------------------------------------------------------
Features for ColoredMarker type marker.
Sorry, I lost the reference for more information.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Características para un marcador de tipo ColoredMarker.
Lo siento, he perdido la referencia para más información.
-------------------------------------------------------------------------------}
TCustomColoredMarker = class(TPersistent)
private
{*------------------------------------------------------------------------------
Marker width.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Ancho del marcador.
-------------------------------------------------------------------------------}
FWidth: Integer;
{*------------------------------------------------------------------------------
Marker height.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Altura del marcador.
-------------------------------------------------------------------------------}
FHeight: Integer;
procedure SetHeight(const Value: Integer);
procedure SetWidth(const Value: Integer);
protected
{*------------------------------------------------------------------------------
Class owner.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Propietario de la clase.
-------------------------------------------------------------------------------}
FMarker: TCustomMarker;
{*------------------------------------------------------------------------------
This method returns the assigned color to the CornerColor property defined into its descendents.
@return String with the color in RGB format
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Método que devuelve el color asignado a la propiedad CornerColor definida en los descendientes.
@return Cadena con el color en formato RGB
-------------------------------------------------------------------------------}
function GetCornerColor: string; virtual; abstract;
{*------------------------------------------------------------------------------
This method returns the assigned color to the PrimaryColor property defined into its descendents.
@return String with the color in RGB format
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Método que devuelve el color asignado a la propiedad PrimaryColor definida en los descendientes.
@return Cadena con el color en formato RGB
-------------------------------------------------------------------------------}
function GetPrimaryColor: string; virtual; abstract;
{*------------------------------------------------------------------------------
This method returns the assigned color to the StrokeColor property defined into its descendents.
@return String with the color in RGB format
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Método que devuelve el color asignado a la propiedad StrokeColor definida en los descendientes.
@return Cadena con el color en formato RGB
-------------------------------------------------------------------------------}
function GetStrokeColor: string; virtual; abstract;
public
{*------------------------------------------------------------------------------
Constructor class
@param aOwner Owner
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Constructor de la clase
@param aOwner Propietario
-------------------------------------------------------------------------------}
constructor Create(aOwner: TCustomMarker); virtual;
{*------------------------------------------------------------------------------
Assign method copies the contents of another similar object.
@param Source object to copy content
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
El método Assign copia el contenido de un objeto similar.
@param Source objeto a copiar el contenido
-------------------------------------------------------------------------------}
procedure Assign(Source: TPersistent); override;
published
property Width: Integer read FWidth write SetWidth default 32;
property Height: Integer read FHeight write SetHeight default 32;
end;
{*------------------------------------------------------------------------------
Features for ColoredMarker type marker.
More information at http://google-maps-utility-library-v3.googlecode.com/svn/trunk/styledmarker/docs/reference.html
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Características para un marcador de tipo ColoredMarker.
Más información en http://google-maps-utility-library-v3.googlecode.com/svn/trunk/styledmarker/docs/reference.html
-------------------------------------------------------------------------------}
TCustomStyledMarker = class(TPersistent)
private
{*------------------------------------------------------------------------------
Show or hide a star in the upper right of the marker.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Mostrar o ocultar una estrella en la parte superior derecha del marcador.
-------------------------------------------------------------------------------}
FShowStar: Boolean;
{*------------------------------------------------------------------------------
Marker type.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Tipo del marcador.
-------------------------------------------------------------------------------}
FStyledIcon: TStyledIcon;
procedure SetShowStar(const Value: Boolean);
procedure SetStyledIcon(const Value: TStyledIcon);
protected
{*------------------------------------------------------------------------------
Class owner.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Propietario de la clase.
-------------------------------------------------------------------------------}
FMarker: TCustomMarker;
{*------------------------------------------------------------------------------
This method returns the assigned color to the BackgroundColor property defined into its descendents.
@return String with the color in RGB format
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Método que devuelve el color asignado a la propiedad BackgroundColor definida en los descendientes.
@return Cadena con el color en formato RGB
-------------------------------------------------------------------------------}
function GetBackgroundColor: string; virtual; abstract;
{*------------------------------------------------------------------------------
This method returns the assigned color to the TextColor property defined into its descendents.
@return String with the color in RGB format
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Método que devuelve el color asignado a la propiedad TextColor definida en los descendientes.
@return Cadena con el color en formato RGB
-------------------------------------------------------------------------------}
function GetTextColor: string; virtual; abstract;
{*------------------------------------------------------------------------------
This method returns the assigned color to the StarColor property defined into its descendents.
@return String with the color in RGB format
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Método que devuelve el color asignado a la propiedad StarColor definida en los descendientes.
@return Cadena con el color en formato RGB
-------------------------------------------------------------------------------}
function GetStarColor: string; virtual; abstract;
public
{*------------------------------------------------------------------------------
Constructor class
@param aOwner Owner
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Constructor de la clase
@param aOwner Propietario
-------------------------------------------------------------------------------}
constructor Create(aOwner: TCustomMarker); virtual;
{*------------------------------------------------------------------------------
Assign method copies the contents of another similar object.
@param Source object to copy content
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
El método Assign copia el contenido de un objeto similar.
@param Source objeto a copiar el contenido
-------------------------------------------------------------------------------}
procedure Assign(Source: TPersistent); override;
published
property StyledIcon: TStyledIcon read FStyledIcon write SetStyledIcon default siMarker;
property ShowStar: Boolean read FShowStar write SetShowStar default False;
end;
{*------------------------------------------------------------------------------
Font styles.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Estilos para las fuentes.
-------------------------------------------------------------------------------}
TGMFontStyle = (fstBold, fstItalic, fstOverline, fstUnderline, fstStrikeOut);
{*------------------------------------------------------------------------------
Set of Font styles.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Conjunto de estilos de fuentes.
-------------------------------------------------------------------------------}
TGMFontStyles = set of TGMFontStyle;
{*------------------------------------------------------------------------------
Features for Border property of TCustomStyleLabel class.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Características para la propiedad Border de la clase TCustomStyleLabel.
-------------------------------------------------------------------------------}
TCustomGMBorder = class(TPersistent)
private
{*------------------------------------------------------------------------------
Border size.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Tamaño del borde.
-------------------------------------------------------------------------------}
FSize: Integer;
{*------------------------------------------------------------------------------
Border style.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Estilo del borde.
-------------------------------------------------------------------------------}
FStyle: TBorderStyle;
procedure SetSize(const Value: Integer);
procedure SetStyle(const Value: TBorderStyle);
protected
{*------------------------------------------------------------------------------
Class owner.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Propietario de la clase.
-------------------------------------------------------------------------------}
FMarker: TCustomMarker;
public
{*------------------------------------------------------------------------------
Constructor class
@param aOwner Owner
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Constructor de la clase
@param aOwner Propietario
-------------------------------------------------------------------------------}
constructor Create(aOwner: TCustomMarker); virtual;
{*------------------------------------------------------------------------------
Assign method copies the contents of another similar object.
@param Source object to copy content
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
El método Assign copia el contenido de un objeto similar.
@param Source objeto a copiar el contenido
-------------------------------------------------------------------------------}
procedure Assign(Source: TPersistent); override;
published
property Size: Integer read FSize write SetSize;
property Style: TBorderStyle read FStyle write SetStyle;
end;
{*------------------------------------------------------------------------------
Features for Font property of TCustomStyleLabel class.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Características para la propiedad Font de la clase TCustomStyleLabel.
-------------------------------------------------------------------------------}
TCustomGMFont = class(TPersistent)
private
{*------------------------------------------------------------------------------
Font size.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Tamaño de la fuente.
-------------------------------------------------------------------------------}
FSize: Integer;
{*------------------------------------------------------------------------------
Font style.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Estilo de la fuente.
-------------------------------------------------------------------------------}
FStyle: TGMFontStyles;
procedure SetSize(const Value: Integer);
procedure SetStyle(const Value: TGMFontStyles);
protected
{*------------------------------------------------------------------------------
Class owner.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Propietario de la clase.
-------------------------------------------------------------------------------}
FMarker: TCustomMarker;
public
{*------------------------------------------------------------------------------
Constructor class
@param aOwner Owner
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Constructor de la clase
@param aOwner Propietario
-------------------------------------------------------------------------------}
constructor Create(aOwner: TCustomMarker); virtual;
{*------------------------------------------------------------------------------
Assign method copies the contents of another similar object.
@param Source object to copy content
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
El método Assign copia el contenido de un objeto similar.
@param Source objeto a copiar el contenido
-------------------------------------------------------------------------------}
procedure Assign(Source: TPersistent); override;
published
property Style: TGMFontStyles read FStyle write SetStyle;
property Size: Integer read FSize write SetSize;
end;
{*------------------------------------------------------------------------------
Features for mtStyledMarker type marker.
It is programmed but can not be selected because it does not work well with IE (TWebBrowser).
More information at http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerwithlabel/docs/reference.html
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Características para un marcador de tipo mtStyledMarker.
Está programado pero no se puede seleccionar debido a que no funciona bien con el IE (TWebBrowser).
Más información en http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerwithlabel/docs/reference.html
-------------------------------------------------------------------------------}
TCustomStyleLabel = class(TPersistent)
private
{*------------------------------------------------------------------------------
Features for Font property.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Características para la propiedad Font.
-------------------------------------------------------------------------------}
FFont: TCustomGMFont;
{*------------------------------------------------------------------------------
Features for Border property.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Características para la propiedad Border.
-------------------------------------------------------------------------------}
FBorder: TCustomGMBorder;
{*------------------------------------------------------------------------------
Opacity with values between 0 and 1.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Opacidad con valores entre 0 y 1.
-------------------------------------------------------------------------------}
FOpacity: Real;
{*------------------------------------------------------------------------------
Label in Background.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Etiqueta de fondo.
-------------------------------------------------------------------------------}
FNoBackground: Boolean;
procedure SetOpacity(const Value: Real);
procedure SetNoBackground(const Value: Boolean);
protected
{*------------------------------------------------------------------------------
Class owner.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Propietario de la clase.
-------------------------------------------------------------------------------}
FMarker: TCustomMarker;
public
{*------------------------------------------------------------------------------
Constructor class
@param aOwner Owner
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Constructor de la clase
@param aOwner Propietario
-------------------------------------------------------------------------------}
constructor Create(aOwner: TCustomMarker); virtual;
{*------------------------------------------------------------------------------
Destructor class
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Destructor de la clase
-------------------------------------------------------------------------------}
destructor Destroy; override;
{*------------------------------------------------------------------------------
Assign method copies the contents of another similar object.
@param Source object to copy content
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
El método Assign copia el contenido de un objeto similar.
@param Source objeto a copiar el contenido
-------------------------------------------------------------------------------}
procedure Assign(Source: TPersistent); override;
published
property Font: TCustomGMFont read FFont write FFont;
property Border: TCustomGMBorder read FBorder write FBorder;
property Opacity: Real read FOpacity write SetOpacity;
property NoBackground: Boolean read FNoBackground write SetNoBackground;
end;
{*------------------------------------------------------------------------------
Base class for markers.
More information at https://developers.google.com/maps/documentation/javascript/reference?hl=en#Marker
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Clase base para los marcadores.
Más información en https://developers.google.com/maps/documentation/javascript/reference?hl=en#Marker
-------------------------------------------------------------------------------}
TCustomMarker = class(TLinkedComponent)
private
{*------------------------------------------------------------------------------
Animation style for marker.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Tipo de animación para los marcadores.
-------------------------------------------------------------------------------}
FAnimation: TAnimation;
{*------------------------------------------------------------------------------
If true, the marker receives mouse events.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Si se establece en true, el marcador recibe eventos del ratón.
-------------------------------------------------------------------------------}
FClickable: Boolean;
{*------------------------------------------------------------------------------
If true, the marker can be dragged.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Si se establece en true, el marcador puede desplazarse.
-------------------------------------------------------------------------------}
FDraggable: Boolean;
{*------------------------------------------------------------------------------
If true, the marker shadow will not be displayed.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Si se establece en true, no se mostrará la sombra del marcador.
-------------------------------------------------------------------------------}
FFlat: Boolean;
{*------------------------------------------------------------------------------
Optimization renders many markers as a single static element.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
La optimización hace que muchos marcadores sean como un único elemento estático.
-------------------------------------------------------------------------------}
FOptimized: Boolean;
{*------------------------------------------------------------------------------
Marker position.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Posición del marcador.
-------------------------------------------------------------------------------}
FPosition: TLatLng;
{*------------------------------------------------------------------------------
If false, disables raising and lowering the marker on drag.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Si se establece a false, deshabilita el subir y bajar del marcador al arrastrarlo.
-------------------------------------------------------------------------------}
FRaiseOnDrag: Boolean;
{*------------------------------------------------------------------------------
This property is used, if applicable, to establish the name that appears in the collection editor and is the hint text that appears when mouse is over the marker.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Esta propiedad se usa, si procede, para establecer el nombre que aparece en el editor de la colección y es el texto ayuda que aparece al posicionar el ratón encima del marcador.
-------------------------------------------------------------------------------}
FTitle: string;
{*------------------------------------------------------------------------------
If true, the marker is visible.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Si se establece a true, el marcador será visible.
-------------------------------------------------------------------------------}
FVisible: Boolean;
{*------------------------------------------------------------------------------
Icon to display. Can be a url or a file on the PC. If not specified, will display the default icon.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Icono a mostrar. Puede ser una url o un archivo en el PC. Si no se especifica, se mostrará el icono por defecto.
-------------------------------------------------------------------------------}
FIcon: string;
{*------------------------------------------------------------------------------
Marker type.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Tipo de marcador.
-------------------------------------------------------------------------------}
FMarkerType: TMarkerType;
{*------------------------------------------------------------------------------
If false, disables cross that appears beneath the marker when dragging.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Si es falso, desactiva la cruz que aparece debajo del marcador cuando éste es desplazado.
-------------------------------------------------------------------------------}
FCrossOnDrag: Boolean;
FIsUpdating: Boolean;
FDirection: Integer;
procedure SetClickable(const Value: Boolean);
procedure SetDraggable(const Value: Boolean);
procedure SetFlat(const Value: Boolean);
procedure SetRaiseOnDrag(const Value: Boolean);
procedure SetVisible(const Value: Boolean);
function GetZIndex: Integer;
procedure SetOptimized(const Value: Boolean);
procedure SetTitle(const Value: string);
procedure SetIcon(const Value: string);
procedure OnLatLngChange(Sender: TObject);
procedure SetMarkerType(const Value: TMarkerType);
procedure SetCrossOnDrag(const Value: Boolean);
procedure SetDirection(const Value: Integer);
protected
procedure SetIdxList(const Value: Cardinal); override;
function GetDisplayName: string; override;
function ChangeProperties: Boolean; override;
{*------------------------------------------------------------------------------
Create the properties that contains some color value.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Crea las propiedades que contienen algún valor de color.
-------------------------------------------------------------------------------}
procedure CreatePropertiesWithColor; virtual; abstract;
{*------------------------------------------------------------------------------
Return a formatted string that contains the ColoredMarker property values.
@return Formatted string.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Devuelve una cadena formateada con los valores de la propiedad ColoredMarker.
@return Cadena formateada.
-------------------------------------------------------------------------------}
function ColoredMarkerToStr: string; virtual; abstract;
{*------------------------------------------------------------------------------
Return a formatted string that contains the StyledMarker property values.
@return Formatted string.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Devuelve una cadena formateada con los valores de la propiedad StyledMarker.
@return Cadena formateada.
-------------------------------------------------------------------------------}
function StyledMarkerToStr: string; virtual; abstract;
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
{*------------------------------------------------------------------------------
Center the map on the marker. Deprecated, instead use CenterMapTo.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Centra el mapa en el marcador. Obsoleto, en su lugar usar CenterMapTo.
-------------------------------------------------------------------------------}
procedure CenterMapToMarker; deprecated;
procedure CenterMapTo; override;
published
property Direction: Integer read FDirection write SetDirection default 0;
property MarkerType: TMarkerType read FMarkerType write SetMarkerType default mtStandard;
property Animation: TAnimation read FAnimation write FAnimation;
property Clickable: Boolean read FClickable write SetClickable default True;
property Draggable: Boolean read FDraggable write SetDraggable default False;
property Flat: Boolean read FFlat write SetFlat default False;
property Position: TLatLng read FPosition write FPosition;
property Title: string read FTitle write SetTitle;
property Visible: Boolean read FVisible write SetVisible default True;
property Optimized: Boolean read FOptimized write SetOptimized default True;
property RaiseOnDrag: Boolean read FRaiseOnDrag write SetRaiseOnDrag default True;
property Icon: string read FIcon write SetIcon;
property CrossOnDrag: Boolean read FCrossOnDrag write SetCrossOnDrag default True;
{*------------------------------------------------------------------------------
Index within the collection.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Índice dentro de la colección.
-------------------------------------------------------------------------------}
property ZIndex: Integer read GetZIndex;
{*------------------------------------------------------------------------------
InfoWindows associated object.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
InfoWindows asociado al objeto.
-------------------------------------------------------------------------------}
property InfoWindow;
{*------------------------------------------------------------------------------
If true, InfoWindows is showed when mouse enter into the object and it is closed when leave.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Si true, el InfoWindos se muestra cuando el ratón entra en el objeto y se cierra cuando sale.
-------------------------------------------------------------------------------}
property ShowInfoWinMouseOver;
end;
{*------------------------------------------------------------------------------
Base class for markers collection.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Clase base para la colección de marcadores.
-------------------------------------------------------------------------------}
TCustomMarkers = class(TLinkedComponents)
private
procedure SetItems(I: Integer; const Value: TCustomMarker);
function GetItems(I: Integer): TCustomMarker;
protected
function GetOwner: TPersistent; override;
public
function Add: TCustomMarker;
function Insert(Index: Integer): TCustomMarker;
{*------------------------------------------------------------------------------
Lists the markers in the collection.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Lista de marcadores en la colección.
-------------------------------------------------------------------------------}
property Items[I: Integer]: TCustomMarker read GetItems write SetItems; default;
end;
{*------------------------------------------------------------------------------
TOnLoadFile event is fired on load each row of the CSV file.
@param Sender Owner object of the collection item.
@param Marker New marker.
@param Current Current Row.
@param Count Number of rows.
@param Stop True to stop the process.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
El evento TOnLoadFile se dispara al cargar cada una de las filas del archivo CSV.
@param Sender Objecto propietario del elemento de la colección.
@param Marker Nuevo marcador.
@param Current Fila actual.
@param Count Cantidad de filas.
@param Stop True para detener el proceso.
-------------------------------------------------------------------------------}
TOnLoadFile = procedure (Sender: TCustomGMMarker; Marker: TCustomMarker; Current, Count: Integer; var Stop: Boolean) of object;
{*------------------------------------------------------------------------------
This event is fired when TAfterLoadFile finish loading the CSV file.
@param Sender Owner object of the collection item.
@param Loaded Number of rows loaded.
@param Count Number of rows.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
El evento TAfterLoadFile se dispara al terminar de cargar el archivo CSV.
@param Sender Objecto propietario del elemento de la colección.
@param Loaded Número de filas cargadas.
@param Count Cantidad de filas.
-------------------------------------------------------------------------------}
TAfterLoadFile = procedure (Sender: TCustomGMMarker; Loaded, Count: Integer) of object;
{*------------------------------------------------------------------------------
Base class management of markers.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Clase base para la gestión de marcadores.
-------------------------------------------------------------------------------}
TCustomGMMarker = class(TGMLinkedComponent)
private
{*------------------------------------------------------------------------------
This event occurs when the user click a marker.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento ocurre cuando el usuario pulsa un marcador.
-------------------------------------------------------------------------------}
FOnClick: TLatLngIdxEvent;
{*------------------------------------------------------------------------------
This event occurs when the user double-clicks a marker.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento ocurre cuando el usuario hace doble click un marcador.
-------------------------------------------------------------------------------}
FOnDblClick: TLatLngIdxEvent;
{*------------------------------------------------------------------------------
This event is repeatedly fired while the user drags the marker.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento se dispara repetidamente mientras el usuario desplaza el marcador.
-------------------------------------------------------------------------------}
FOnDrag: TLatLngIdxEvent;
{*------------------------------------------------------------------------------
This event is fired when the user stops dragging the marker.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento se dispara cuando el usuario para de desplazar el marcador.
-------------------------------------------------------------------------------}
FOnDragEnd: TLatLngIdxEvent;
{*------------------------------------------------------------------------------
This event is fired for a rightclick on the marker.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento se dispara al hacer click con el botón derecho del ratón en el marcador.
-------------------------------------------------------------------------------}
FOnRightClick: TLatLngIdxEvent;
{*------------------------------------------------------------------------------
This event is fired for a mousedown on the marker.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento se dispara al pulsar en el marcador.
-------------------------------------------------------------------------------}
FOnMouseDown: TLatLngIdxEvent;
{*------------------------------------------------------------------------------
This event is fired for a mouseup on the marker.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento se dispara al soltar el marcador.
-------------------------------------------------------------------------------}
FOnMouseUp: TLatLngIdxEvent;
{*------------------------------------------------------------------------------
This event is fired when the mouse leaves the area of the marker icon.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento se dispara cuando el ratón deja el área del icono del marcador.
-------------------------------------------------------------------------------}
FOnMouseOut: TLatLngIdxEvent;
{*------------------------------------------------------------------------------
This event is fired when the user starts dragging the marker.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento se dispara cuando el usuario empieza a desplazar el marcador.
-------------------------------------------------------------------------------}
FOnDragStart: TLatLngIdxEvent;
{*------------------------------------------------------------------------------
This event is fired when the mouse enters the area of the marker icon.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento se dispara cuando el ratón entra en el área del icono del marcador.
-------------------------------------------------------------------------------}
FOnMouseOver: TLatLngIdxEvent;
{*------------------------------------------------------------------------------
This event is fired when the marker's Clickable property changes.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento se dispara cuando cambia la propiedad Clickable del marcador.
-------------------------------------------------------------------------------}
FOnClickableChange: TLinkedComponentChange;
{*------------------------------------------------------------------------------
This event is fired when the marker's Draggable property changes.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento se dispara cuando cambia la propiedad Draggable del marcador.
-------------------------------------------------------------------------------}
FOnDraggableChange: TLinkedComponentChange;
{*------------------------------------------------------------------------------
This event is fired when the marker's Flat property changes.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento se dispara cuando cambia la propiedad Flat del marcador.
-------------------------------------------------------------------------------}
FOnFlatChange: TLinkedComponentChange;
{*------------------------------------------------------------------------------
This event is fired when the marker's Position property changes.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento se dispara cuando cambia la propiedad Position del marcador.
-------------------------------------------------------------------------------}
FOnPositionChange: TLatLngIdxEvent;
{*------------------------------------------------------------------------------
This event is fired when the marker's Title property changes.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento se dispara cuando cambia la propiedad Title del marcador.
-------------------------------------------------------------------------------}
FOnTitleChange: TLinkedComponentChange;
{*------------------------------------------------------------------------------
This event is fired when the marker's Visible property changes.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento se dispara cuando cambia la propiedad Visible del marcador.
-------------------------------------------------------------------------------}
FOnVisibleChange: TLinkedComponentChange;
{*------------------------------------------------------------------------------
This event is fired when the marker's Icon property changes.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento se dispara cuando cambia la propiedad Icon del marcador.
-------------------------------------------------------------------------------}
FOnIconChange: TLinkedComponentChange;
{*------------------------------------------------------------------------------
This event is fired every time you load a row of the CSV file.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento se dispara cada vez que se carga una fila del archivo CSV.
-------------------------------------------------------------------------------}
FOnLoadFile: TOnLoadFile;
{*------------------------------------------------------------------------------
This event is fired to finish loading the CSV file.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento se dispara al terminar de cargar el archivo CSV.
-------------------------------------------------------------------------------}
FAfterLoadFile: TAfterLoadFile;
{*------------------------------------------------------------------------------
This event is fired when a property of the marker's ColoredMarker property changes.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento se dispara cuando cambia una propiedad de la propiedad ColoredMarker del marcador.
-------------------------------------------------------------------------------}
FOnColoredMarkerChange: TLinkedComponentChange;
{*------------------------------------------------------------------------------
This event is fired when a property of the marker's StyledMarker property changes.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento se dispara cuando cambia una propiedad de la propiedad StyledMarker del marcador.
-------------------------------------------------------------------------------}
FOnStyledMarkerChange: TLinkedComponentChange;
{*------------------------------------------------------------------------------
This event is fired when the marker's CrossOnDrag property changes.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento se dispara cuando cambia la propiedad CrossOnDrag del marcador.
-------------------------------------------------------------------------------}
FOnCrossOnDragChange: TLinkedComponentChange;
protected
function GetAPIUrl: string; override;
function GetItems(I: Integer): TCustomMarker;
procedure EventFired(EventType: TEventType; Params: array of const); override;
function GetCollectionItemClass: TLinkedComponentClass; override;
function GetCollectionClass: TLinkedComponentsClass; override;
public
{*------------------------------------------------------------------------------
Creates TMarker instances and adds them to the Items array from a CSV file.
@param LatColumn Column with latitude information.
@param LngColumn Column with longitude information.
@param FileName File name.
@param TitleColumn Column with title information.
@param Delimiter Field delimiter.
@param DeleteBeforeLoad To true, delete markers before load file.
@param WithRownTitle If the file have a first row with title columns.
@param IconColumn Column for icon information.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Crea instancias de TMarker y las añade en el array de Items desde un archivo CSV.
@param LatColumn Columna con la información de la latitud.
@param LngColumn Columna con información de la longitud.
@param FileName Nombre del fichero.
@param TitleColumn Columna con información del título.
@param Delimiter Delimitador de campos.
@param DeleteBeforeLoad A true, borra los marcadores antes de cargar el fichero.
@param WithRownTitle Si el fichero tiene una primera fila con el título de las columnas.
@param IconColumn Columna con información del icono a mostrar.
-------------------------------------------------------------------------------}
procedure LoadFromCSV(LatColumn, LngColumn: Integer; FileName: string;
TitleColumn: Integer = -1; Delimiter: Char = ','; DeleteBeforeLoad: Boolean = True;
WithRownTitle: Boolean = True; IconColumn: Integer = -1);
{*------------------------------------------------------------------------------
Creates TMarker instances and adds them to the Items array from a DataSet.
@param DataSet DataSet where get the data.
@param LatField Field with latitude.
@param LngField Field with longitude.
@param TitleField Field with title information.
@param IconField Field for icon information.
@param DeleteBeforeLoad To true, delete markers before load file.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Crea instancias de TMarker y las añade en el array de Items desde un DataSet.
@param DataSet DataSet de donde obtener los datos.
@param LatField Campo con la latitud.
@param LngField Campo con la longitud.
@param TitleField Campo con información del título.
@param IconField Campo con información del icono a mostrar.
@param DeleteBeforeLoad A true, borra los marcadores antes de cargar el fichero.
-------------------------------------------------------------------------------}
procedure LoadFromDataSet(DataSet: TDataSet; LatField, LngField: string;
TitleField: string = ''; IconField: string = ''; DeleteBeforeLoad: Boolean = True;
HTMLContentField: string = '');
{*------------------------------------------------------------------------------
Creates a new TMarker instance and adds it to the Items array.
@param Lat Marker latitude.
@param Lng Marker longitude.
@param Title Marker title.
@return New marker.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Crea una nueva instancia de TMarker y la añade en el array de Items.
@param Lat Latitud del marcador.
@param Lng Longitud del marcador.
@param Title Título del marcador.
@return Nuevo marcador.
-------------------------------------------------------------------------------}
function Add(Lat: Real = 0; Lng: Real = 0; Title: string = ''): TCustomMarker;
{*------------------------------------------------------------------------------
Applies zoom to the map to include all markers.
Deprecated. Instead use ZoomToPoints method.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Se aplica zoom al mapa para incluir todos los marcadores.
Obsoleto. En su lugar usar el método ZoomToPoints.
-------------------------------------------------------------------------------}
procedure ZoomMapToAllMarkers; deprecated;
{*------------------------------------------------------------------------------
Sets the optimal zoom to display all markers.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Establece el zoom óptimo para visualizar todos los marcadores.
-------------------------------------------------------------------------------}
procedure ZoomToPoints;
{*------------------------------------------------------------------------------
Array with the collection items.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Array con la colección de elementos.
-------------------------------------------------------------------------------}
property Items[I: Integer]: TCustomMarker read GetItems; default;
published
{*------------------------------------------------------------------------------
Collection items.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Colección de elementos.
-------------------------------------------------------------------------------}
property VisualObjects;
// eventos
// events
property OnLoadFile: TOnLoadFile read FOnLoadFile write FOnLoadFile;
property AfterLoadFile: TAfterLoadFile read FAfterLoadFile write FAfterLoadFile;
// from map
property OnClick: TLatLngIdxEvent read FOnClick write FOnClick;
property OnDblClick: TLatLngIdxEvent read FOnDblClick write FOnDblClick;
property OnDrag: TLatLngIdxEvent read FOnDrag write FOnDrag;
property OnDragEnd: TLatLngIdxEvent read FOnDragEnd write FOnDragEnd;
property OnDragStart: TLatLngIdxEvent read FOnDragStart write FOnDragStart;
property OnMouseDown: TLatLngIdxEvent read FOnMouseDown write FOnMouseDown;
property OnMouseOut: TLatLngIdxEvent read FOnMouseOut write FOnMouseOut;
property OnMouseOver: TLatLngIdxEvent read FOnMouseOver write FOnMouseOver;
property OnMouseUp: TLatLngIdxEvent read FOnMouseUp write FOnMouseUp;
property OnRightClick: TLatLngIdxEvent read FOnRightClick write FOnRightClick;
// from properties
property OnClickableChange: TLinkedComponentChange read FOnClickableChange write FOnClickableChange;
property OnDraggableChange: TLinkedComponentChange read FOnDraggableChange write FOnDraggableChange;
property OnFlatChange: TLinkedComponentChange read FOnFlatChange write FOnFlatChange;
property OnPositionChange: TLatLngIdxEvent read FOnPositionChange write FOnPositionChange;
property OnTitleChange: TLinkedComponentChange read FOnTitleChange write FOnTitleChange;
property OnVisibleChange: TLinkedComponentChange read FOnVisibleChange write FOnVisibleChange;
property OnIconChange: TLinkedComponentChange read FOnIconChange write FOnIconChange;
property OnColoredMarkerChange: TLinkedComponentChange read FOnColoredMarkerChange write FOnColoredMarkerChange;
property OnStyledMarkerChange: TLinkedComponentChange read FOnStyledMarkerChange write FOnStyledMarkerChange;
property OnCrossOnDragChange: TLinkedComponentChange read FOnCrossOnDragChange write FOnCrossOnDragChange;
end;
implementation
uses
{$IFDEF DELPHIXE2}
System.SysUtils,
{$ELSE}
SysUtils,
{$ENDIF}
Lang, GMFunctions;
{ TCustomGMMarker }
function TCustomGMMarker.Add(Lat, Lng: Real; Title: string): TCustomMarker;
begin
Result := TCustomMarker(inherited Add);
Result.Position.Lat := Lat;
Result.Position.Lng := Lng;
if Title <> '' then Result.Title := Title
else Result.Title := Result.GetDisplayName;
end;
function TCustomGMMarker.GetAPIUrl: string;
begin
Result := 'https://developers.google.com/maps/documentation/javascript/reference?hl=en#Marker';
end;
function TCustomGMMarker.GetCollectionClass: TLinkedComponentsClass;
begin
Result := TCustomMarkers;
end;
function TCustomGMMarker.GetCollectionItemClass: TLinkedComponentClass;
begin
Result := TCustomMarker;
end;
function TCustomGMMarker.GetItems(I: Integer): TCustomMarker;
begin
Result := TCustomMarker(inherited Items[i]);
end;
procedure TCustomGMMarker.LoadFromCSV(LatColumn, LngColumn: Integer;
FileName: string; TitleColumn: Integer; Delimiter: Char; DeleteBeforeLoad,
WithRownTitle: Boolean; IconColumn: Integer);
var
L1, L2: TStringList;
i: Integer;
Auto: Boolean;
Marker: TCustomMarker;
Stop: Boolean;
begin
if not FileExists(FileName) then
raise Exception.Create(GetTranslateText('El fichero no existe', Language));
Auto := AutoUpdate;
AutoUpdate := False;
if DeleteBeforeLoad then Clear;
L1 := TStringList.Create;
L2 := TStringList.Create;
try
L1.LoadFromFile(FileName);
if WithRownTitle then L1.Delete(0);
L2.Delimiter := Delimiter;
{$IFDEF DELPHI2005}
L2.StrictDelimiter := True;
{$ENDIF}
for i := 0 to L1.Count - 1 do
begin
L2.DelimitedText := L1[i];
if (LatColumn > L2.Count) or (LngColumn > L2.Count) or
((TitleColumn <>1) and (TitleColumn > L2.Count)) then
raise Exception.Create(GetTranslateText('El número de columna es incorrecto', Language));
if TitleColumn = -1 then Marker := Add
else Marker := Add(0, 0, L2[TitleColumn]);
Marker.Position.Lat := Marker.Position.StringToReal(L2[LatColumn]);
Marker.Position.Lng := Marker.Position.StringToReal(L2[LngColumn]);
if IconColumn <> -1 then Marker.Icon := L2[IconColumn];
Stop := False;
if Assigned(FOnLoadFile) then FOnLoadFile(Self, Marker, i, L1.Count, Stop);
if Stop then Break;
end;
if Auto then AutoUpdate := True;
ShowElements;
if Assigned(FAfterLoadFile) then FAfterLoadFile(Self, i, L1.Count);
finally
AutoUpdate := Auto;
if Assigned(L1) then FreeAndNil(L1);
if Assigned(L2) then FreeAndNil(L2);
end;
end;
procedure TCustomGMMarker.LoadFromDataSet(DataSet: TDataSet; LatField, LngField,
TitleField, IconField: string; DeleteBeforeLoad: Boolean;
HTMLContentField: string);
procedure CheckFields;
begin
if not Assigned(DataSet.FindField(LatField)) then
raise Exception.Create(Format(GetTranslateText('Campo "%s" no encontrado en la tabla.', Map.Language), [LatField]));
if not Assigned(DataSet.FindField(LngField)) then
raise Exception.Create(Format(GetTranslateText('Campo "%s" no encontrado en la tabla.', Map.Language), [LngField]));
if (TitleField <> '') and not Assigned(DataSet.FindField(TitleField)) then
raise Exception.Create(Format(GetTranslateText('Campo "%s" no encontrado en la tabla.', Map.Language), [TitleField]));
if (IconField <> '') and not Assigned(DataSet.FindField(IconField)) then
raise Exception.Create(Format(GetTranslateText('Campo "%s" no encontrado en la tabla.', Map.Language), [IconField]));
if (HTMLContentField <> '') and not Assigned(DataSet.FindField(HTMLContentField)) then
raise Exception.Create(Format(GetTranslateText('Campo "%s" no encontrado en la tabla.', Map.Language), [HTMLContentField]));
end;
var
Auto: Boolean;
Marker: TCustomMarker;
i: Integer;
Bkm: TBookmark;
begin
if not DataSet.Active then DataSet.Open;
CheckFields;
Auto := AutoUpdate;
AutoUpdate := False;
if DeleteBeforeLoad then Clear;
Bkm := DataSet.GetBookmark;
DataSet.DisableControls;
try
i := 0;
DataSet.First;
while not DataSet.Eof do
begin
if TitleField = '' then Marker := Add
else Marker := Add(0, 0, DataSet.FieldByName(TitleField).AsString);
Marker.Position.Lat := DataSet.FieldByName(LatField).AsFloat;
Marker.Position.Lng := DataSet.FieldByName(LngField).AsFloat;
if IconField <> '' then Marker.Icon := DataSet.FieldByName(IconField).AsString;
if HTMLContentField <> '' then
Marker.InfoWindow.HTMLContent := DataSet.FieldByName(HTMLContentField).AsString;
Inc(i);
DataSet.Next;
end;
DataSet.GotoBookmark(Bkm);
if Auto then AutoUpdate := True;
ShowElements;
if Assigned(FAfterLoadFile) then FAfterLoadFile(Self, i, DataSet.RecordCount);
finally
DataSet.FreeBookmark(Bkm);
DataSet.EnableControls;
AutoUpdate := Auto;
end;
end;
procedure TCustomGMMarker.ZoomMapToAllMarkers;
var
i: integer;
LatLow, LatHigh: real;
LngLow, LngHigh: real;
LatCenter: real;
LngCenter: real;
begin
LatLow := 500;
LatHigh := -500;
LngLow := 500;
LngHigh := -500;
for i := 0 to Count - 1 do
begin
if Items[i].Position.Lat < LatLow then
LatLow := Items[i].Position.Lat;
if Items[i].Position.Lat > LatHigh then
LatHigh := Items[i].Position.Lat;
if Items[i].Position.Lng < LngLow then
LngLow := Items[i].Position.Lng;
if Items[i].Position.Lng > LngHigh then
LngHigh := Items[i].Position.Lng;
end;
LatCenter := LatLow + ((LatHigh - LatLow) / 2);
LngCenter := LngLow + ((LngHigh - LngLow) / 2);
Map.SetCenter(LatCenter, LngCenter);
Map.LatLngBoundsSetBounds(LatLow, LngLow, LatHigh, LngHigh);
end;
procedure TCustomGMMarker.ZoomToPoints;
var
Points: array of TLatLng;
i: Integer;
begin
if not Assigned(Map) then Exit;
SetLength(Points, Count);
for i := 0 to Count - 1 do
Points[i] := Items[i].Position;
Map.ZoomToPoints(Points);
end;
procedure TCustomGMMarker.EventFired(EventType: TEventType; Params: array of const);
var
LL: TLatLng;
begin
inherited;
if EventType = etInfoWinCloseClick then Exit;
if High(Params) <> 2 then
raise Exception.Create(GetTranslateText('Número de parámetros incorrecto', Map.Language));
if (Params[0].VType <> vtExtended) or (Params[1].VType <> vtExtended) then
raise Exception.Create(GetTranslateText('Tipo de parámetro incorrecto', Map.Language));
if Params[2].VType <> vtInteger then
raise Exception.Create(GetTranslateText('Tipo de parámetro incorrecto', Map.Language));
if Params[2].VInteger > VisualObjects.Count - 1 then
raise Exception.Create(GetTranslateText('Valor de parámetro incorrecto', Map.Language));
LL := TLatLng.Create(ControlPrecision(Params[0].VExtended^, GetMapPrecision),
ControlPrecision(Params[1].VExtended^, GetMapPrecision));
try
case EventType of
etMarkerClick: if Assigned(FOnClick) then FOnClick(Self, LL, Params[2].VInteger, Items[Params[2].VInteger]);
etMarkerDblClick: if Assigned(FOnDblClick) then FOnDblClick(Self, LL, Params[2].VInteger, Items[Params[2].VInteger]);
etMarkerDrag: if Assigned(FOnDrag) then FOnDrag(Self, LL, Params[2].VInteger, Items[Params[2].VInteger]);
etMarkerDragEnd:
begin
Items[Params[2].VInteger].FIsUpdating := True;
Items[Params[2].VInteger].Position.Assign(LL);
if Assigned(FOnDragEnd) then FOnDragEnd(Self, LL, Params[2].VInteger, Items[Params[2].VInteger]);
Items[Params[2].VInteger].FIsUpdating := False;
end;
etMarkerDragStart: if Assigned(FOnDragStart) then FOnDragStart(Self, LL, Params[2].VInteger, Items[Params[2].VInteger]);
etMarkerMouseDown: if Assigned(FOnMouseDown) then FOnMouseDown(Self, LL, Params[2].VInteger, Items[Params[2].VInteger]);
etMarkerMouseOut: if Assigned(FOnMouseOut) then FOnMouseOut(Self, LL, Params[2].VInteger, Items[Params[2].VInteger]);
etMarkerMouseOver: if Assigned(FOnMouseOver) then FOnMouseOver(Self, LL, Params[2].VInteger, Items[Params[2].VInteger]);
etMarkerMouseUp: if Assigned(FOnMouseUp) then FOnMouseUp(Self, LL, Params[2].VInteger, Items[Params[2].VInteger]);
etMarkerRightClick: if Assigned(FOnRightClick) then FOnRightClick(Self, LL, Params[2].VInteger, Items[Params[2].VInteger]);
end;
finally
FreeAndNil(LL);
end;
end;
{ TCustomMarkers }
function TCustomMarkers.Add: TCustomMarker;
begin
Result := TCustomMarker(inherited Add);
end;
function TCustomMarkers.GetItems(I: Integer): TCustomMarker;
begin
Result := TCustomMarker(inherited Items[I]);
end;
function TCustomMarkers.GetOwner: TPersistent;
begin
Result := TCustomGMMarker(inherited GetOwner);
end;
function TCustomMarkers.Insert(Index: Integer): TCustomMarker;
begin
Result := TCustomMarker(inherited Insert(Index));
end;
procedure TCustomMarkers.SetItems(I: Integer; const Value: TCustomMarker);
begin
inherited SetItem(I, Value);
end;
{ TAnimation }
procedure TAnimation.Assign(Source: TPersistent);
begin
if Source is TAnimation then
begin
OnDrop := TAnimation(Source).OnDrop;
Bounce := TAnimation(Source).Bounce;
end
else
inherited Assign(Source);
end;
constructor TAnimation.Create(aOwner: TCustomMarker);
begin
FMarker := aOwner;
FOnDrop := False;
FBounce := False;
if Assigned(FMarker) then FIdxList := FMarker.IdxList;
end;
procedure TAnimation.SetBounce(const Value: Boolean);
const
StrParams = '%s,%s,%s';
var
Params: String;
begin
if FBounce = Value then Exit;
FBounce := Value;
if Assigned(FMarker) and (FMarker is TCustomMarker) and
Assigned(FMarker.Collection) and (FMarker.Collection is TCustomMarkers) and
Assigned(TCustomMarkers(FMarker.Collection).FGMLinkedComponent) and
TCustomGMMarker(TCustomMarkers(FMarker.Collection).FGMLinkedComponent).AutoUpdate then
begin
Params := Format(StrParams, [
IntToStr(FIdxList),
LowerCase(TCustomTransform.GMBoolToStr(FBounce, True)),
IntToStr(FMarker.Index)]);
TCustomGMMarker(TCustomMarkers(FMarker.Collection).FGMLinkedComponent).ExecuteScript('MarkerSetBounce', Params);
// control de errores // error control
TCustomGMMarker(TCustomMarkers(FMarker.Collection).FGMLinkedComponent).ErrorControl;
end;
end;
procedure TAnimation.SetOnDrop(const Value: Boolean);
begin
if FOnDrop = Value then Exit;
FOnDrop := Value;
if Assigned(FMarker) and (FMarker is TCustomMarker) and
Assigned(FMarker.Collection) and (FMarker.Collection is TCustomMarkers) and
Assigned(TCustomMarkers(FMarker.Collection).FGMLinkedComponent) and
TCustomGMMarker(TCustomMarkers(FMarker.Collection).FGMLinkedComponent).AutoUpdate then
TCustomGMMarker(TCustomMarkers(FMarker.Collection).FGMLinkedComponent).ShowElements;
end;
{ TCustomMarker }
procedure TCustomMarker.Assign(Source: TPersistent);
begin
inherited;
if Source is TCustomMarker then
begin
Animation.Assign(TCustomMarker(Source).Animation);
Clickable := TCustomMarker(Source).Clickable;
Draggable := TCustomMarker(Source).Draggable;
Flat := TCustomMarker(Source).Flat;
Optimized := TCustomMarker(Source).Optimized;
Position.Assign(TCustomMarker(Source).Position);
RaiseOnDrag := TCustomMarker(Source).RaiseOnDrag;
Title := TCustomMarker(Source).Title;
Visible := TCustomMarker(Source).Visible;
MarkerType := TCustomMarker(Source).MarkerType;
end;
end;
procedure TCustomMarker.CenterMapTo;
begin
inherited;
if Assigned(Collection) and (Collection is TCustomMarkers) and
Assigned(TCustomMarkers(Collection).FGMLinkedComponent) and
Assigned(TCustomMarkers(Collection).FGMLinkedComponent.Map) then
TCustomMarkers(Collection).FGMLinkedComponent.Map.SetCenter(Position.Lat, Position.Lng);
end;
procedure TCustomMarker.CenterMapToMarker;
begin
if Assigned(Collection) and (Collection is TCustomMarkers) and
Assigned(TCustomMarkers(Collection).FGMLinkedComponent) and
Assigned(TCustomMarkers(Collection).FGMLinkedComponent.Map) then
TCustomMarkers(Collection).FGMLinkedComponent.Map.SetCenter(Position.Lat, Position.Lng);
end;
function TCustomMarker.ChangeProperties: Boolean;
const
StrParams = '%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s';
var
Params: string;
Icon: string;
begin
inherited;
Result := False;
if not Assigned(Collection) or not(Collection is TCustomMarkers) or
not Assigned(TCustomMarkers(Collection).FGMLinkedComponent) or
//not TCustomGMMarker(TCustomMarkers(Collection).FGMLinkedComponent).AutoUpdate or
not Assigned(TCustomGMMarker(TCustomMarkers(Collection).FGMLinkedComponent).Map) or
(csDesigning in TCustomGMMarker(TCustomMarkers(Collection).FGMLinkedComponent).ComponentState) then
Exit;
if MarkerType = mtColored then Icon := ColoredMarkerToStr
else
begin
Icon := FIcon;
if FileExists(Icon) then
begin
Icon := 'file:///' + Icon;
Icon := StringReplace(Icon, '\', '/', [rfReplaceAll]);
end;
end;
Params := Format(StrParams, [
IntToStr(IdxList),
LowerCase(TCustomTransform.GMBoolToStr(Animation.OnDrop, True)),
LowerCase(TCustomTransform.GMBoolToStr(Animation.Bounce, True)),
LowerCase(TCustomTransform.GMBoolToStr(Clickable, True)),
LowerCase(TCustomTransform.GMBoolToStr(Draggable, True)),
LowerCase(TCustomTransform.GMBoolToStr(Flat, True)),
LowerCase(TCustomTransform.GMBoolToStr(Optimized, True)),
Position.LatToStr(TCustomGMMarker(TCustomMarkers(Collection).FGMLinkedComponent).GetMapPrecision),
Position.LngToStr(TCustomGMMarker(TCustomMarkers(Collection).FGMLinkedComponent).GetMapPrecision),
LowerCase(TCustomTransform.GMBoolToStr(RaiseOnDrag, True)),
QuotedStr(TCustomGMMarker(TCustomMarkers(Collection).FGMLinkedComponent).GetConvertedString(Title)),
LowerCase(TCustomTransform.GMBoolToStr(Visible, True)),
QuotedStr(Icon),
IntToStr(Index),
QuotedStr(InfoWindow.GetConvertedString),
LowerCase(TCustomTransform.GMBoolToStr(InfoWindow.DisableAutoPan, True)),
IntToStr(InfoWindow.MaxWidth),
IntToStr(InfoWindow.PixelOffset.Height),
IntToStr(InfoWindow.PixelOffset.Width),
LowerCase(TCustomTransform.GMBoolToStr(InfoWindow.CloseOtherBeforeOpen, True)),
QuotedStr(TCustomTransform.MarkerTypeToStr(MarkerType)),
StyledMarkerToStr,
LowerCase(TCustomTransform.GMBoolToStr(ShowInfoWinMouseOver, True)),
LowerCase(TCustomTransform.GMBoolToStr(FCrossOnDrag, True))
]);
Result := TCustomGMMarker(TCustomMarkers(Collection).FGMLinkedComponent).ExecuteScript('MakeMarker', Params);
TCustomGMMarker(TCustomMarkers(Collection).FGMLinkedComponent).ErrorControl;
end;
constructor TCustomMarker.Create(Collection: TCollection);
begin
inherited;
FAnimation := TAnimation.Create(Self);
FClickable := True;
FDraggable := False;
FFlat := False;
FOptimized := True;
FPosition := TLatLng.Create;
FPosition.OnChange := OnLatLngChange;
FRaiseOnDrag := True;
FTitle := '';
FVisible := True;
FIsUpdating := False;
FMarkerType := mtStandard;
FCrossOnDrag := True;
CreatePropertiesWithColor;
end;
destructor TCustomMarker.Destroy;
begin
if Assigned(FPosition) then FreeAndNil(FPosition);
if Assigned(FAnimation) then FreeAndNil(FAnimation);
inherited;
end;
function TCustomMarker.GetDisplayName: string;
begin
if Length(Title) > 0 then
begin
if Length(Title) > 15 then
Result := Copy(Title, 0, 12) + '...'
else
Result := Title;
end
else
begin
Result := inherited GetDisplayName;
Title := Result;
end;
end;
function TCustomMarker.GetZIndex: Integer;
begin
Result := Index;
end;
procedure TCustomMarker.OnLatLngChange(Sender: TObject);
begin
if FIsUpdating then Exit;
ChangeProperties;
if Assigned(TCustomGMMarker(TCustomMarkers(Collection).FGMLinkedComponent).FOnPositionChange) then
TCustomGMMarker(TCustomMarkers(Collection).FGMLinkedComponent).FOnPositionChange(
TCustomGMMarker(TCustomMarkers(Collection).FGMLinkedComponent),
Position,
Index,
Self);
end;
procedure TCustomMarker.SetClickable(const Value: Boolean);
begin
if FClickable = Value then Exit;
FClickable := Value;
ChangeProperties;
if Assigned(TCustomGMMarker(TCustomMarkers(Collection).FGMLinkedComponent).FOnClickableChange) then
TCustomGMMarker(TCustomMarkers(Collection).FGMLinkedComponent).FOnClickableChange(
TCustomGMMarker(TCustomMarkers(Collection).FGMLinkedComponent),
Index,
Self);
end;
procedure TCustomMarker.SetCrossOnDrag(const Value: Boolean);
begin
if FCrossOnDrag = Value then Exit;
FCrossOnDrag := Value;
ChangeProperties;
if Assigned(TCustomGMMarker(TCustomMarkers(Collection).FGMLinkedComponent).FOnCrossOnDragChange) then
TCustomGMMarker(TCustomMarkers(Collection).FGMLinkedComponent).FOnCrossOnDragChange(
TCustomGMMarker(TCustomMarkers(Collection).FGMLinkedComponent),
Index,
Self);
end;
procedure TCustomMarker.SetDirection(const Value: Integer);
begin
if FDirection = Value then Exit;
FDirection := Value;
if FDirection > 360 then FDirection := 360;
if FDirection < 0 then FDirection := 0;
end;
procedure TCustomMarker.SetDraggable(const Value: Boolean);
begin
if FDraggable = Value then Exit;
FDraggable := Value;
ChangeProperties;
if Assigned(TCustomGMMarker(TCustomMarkers(Collection).FGMLinkedComponent).FOnDraggableChange) then
TCustomGMMarker(TCustomMarkers(Collection).FGMLinkedComponent).FOnDraggableChange(
TCustomGMMarker(TCustomMarkers(Collection).FGMLinkedComponent),
Index,
Self);
end;
procedure TCustomMarker.SetFlat(const Value: Boolean);
begin
if FFlat = Value then Exit;
FFlat := Value;
ChangeProperties;
if Assigned(TCustomGMMarker(TCustomMarkers(Collection).FGMLinkedComponent).FOnFlatChange) then
TCustomGMMarker(TCustomMarkers(Collection).FGMLinkedComponent).FOnFlatChange(
TCustomGMMarker(TCustomMarkers(Collection).FGMLinkedComponent),
Index,
Self);
end;
procedure TCustomMarker.SetIcon(const Value: string);
begin
if FIcon = Value then Exit;
FIcon := Value;
ChangeProperties;
if Assigned(TCustomGMMarker(TCustomMarkers(Collection).FGMLinkedComponent).FOnIconChange) then
TCustomGMMarker(TCustomMarkers(Collection).FGMLinkedComponent).FOnIconChange(
TCustomGMMarker(TCustomMarkers(Collection).FGMLinkedComponent),
Index,
Self);
end;
procedure TCustomMarker.SetIdxList(const Value: Cardinal);
begin
inherited;
FAnimation.IdxList := Value;
end;
procedure TCustomMarker.SetMarkerType(const Value: TMarkerType);
begin
if FMarkerType = Value then Exit;
FMarkerType := Value;
ChangeProperties;
end;
procedure TCustomMarker.SetOptimized(const Value: Boolean);
begin
if FOptimized = Value then Exit;
FOptimized := Value;
ChangeProperties;
end;
procedure TCustomMarker.SetRaiseOnDrag(const Value: Boolean);
begin
if FRaiseOnDrag = Value then Exit;
FRaiseOnDrag := Value;
ChangeProperties;
end;
procedure TCustomMarker.SetTitle(const Value: string);
begin
if FTitle = Value then Exit;
FTitle := Value;
ChangeProperties;
if Assigned(TCustomGMMarker(TCustomMarkers(Collection).FGMLinkedComponent).FOnTitleChange) then
TCustomGMMarker(TCustomMarkers(Collection).FGMLinkedComponent).FOnTitleChange(
TCustomGMMarker(TCustomMarkers(Collection).FGMLinkedComponent),
Index,
Self);
end;
procedure TCustomMarker.SetVisible(const Value: Boolean);
begin
if FVisible = Value then Exit;
FVisible := Value;
ChangeProperties;
if Assigned(TCustomGMMarker(TCustomMarkers(Collection).FGMLinkedComponent).FOnVisibleChange) then
TCustomGMMarker(TCustomMarkers(Collection).FGMLinkedComponent).FOnVisibleChange(
TCustomGMMarker(TCustomMarkers(Collection).FGMLinkedComponent),
Index,
Self);
end;
{ TCustomColoredMarker }
procedure TCustomColoredMarker.Assign(Source: TPersistent);
begin
if Source is TCustomColoredMarker then
begin
FMarker := TCustomColoredMarker(Source).FMarker;
Height := TCustomColoredMarker(Source).Height;
Width := TCustomColoredMarker(Source).Width;
end
else inherited;
end;
constructor TCustomColoredMarker.Create(aOwner: TCustomMarker);
begin
FMarker := aOwner;
FHeight := 32;
FWidth := 32;
end;
procedure TCustomColoredMarker.SetHeight(const Value: Integer);
begin
if FHeight = Value then Exit;
FHeight := Value;
if not Assigned(FMarker) then Exit;
FMarker.ChangeProperties;
if Assigned(TCustomGMMarker(TCustomMarkers(FMarker.Collection).FGMLinkedComponent).FOnColoredMarkerChange) then
TCustomGMMarker(TCustomMarkers(FMarker.Collection).FGMLinkedComponent).FOnColoredMarkerChange(
TCustomGMMarker(TCustomMarkers(FMarker.Collection).FGMLinkedComponent),
FMarker.Index,
FMarker);
end;
procedure TCustomColoredMarker.SetWidth(const Value: Integer);
begin
if FWidth = Value then Exit;
FWidth := Value;
if not Assigned(FMarker) then Exit;
FMarker.ChangeProperties;
if Assigned(TCustomGMMarker(TCustomMarkers(FMarker.Collection).FGMLinkedComponent).FOnColoredMarkerChange) then
TCustomGMMarker(TCustomMarkers(FMarker.Collection).FGMLinkedComponent).FOnColoredMarkerChange(
TCustomGMMarker(TCustomMarkers(FMarker.Collection).FGMLinkedComponent),
FMarker.Index,
FMarker);
end;
{ TCustomStyledMarker }
procedure TCustomStyledMarker.Assign(Source: TPersistent);
begin
if Source is TCustomStyledMarker then
begin
FMarker := TCustomStyledMarker(Source).FMarker;
StyledIcon := TCustomStyledMarker(Source).StyledIcon;
ShowStar := TCustomStyledMarker(Source).ShowStar;
end
else inherited;
end;
constructor TCustomStyledMarker.Create(aOwner: TCustomMarker);
begin
FMarker := aOwner;
FStyledIcon := siMarker;
FShowStar := False;
end;
procedure TCustomStyledMarker.SetShowStar(const Value: Boolean);
begin
if FShowStar = Value then Exit;
FShowStar := Value;
if not Assigned(FMarker) then Exit;
FMarker.ChangeProperties;
if Assigned(TCustomGMMarker(TCustomMarkers(FMarker.Collection).FGMLinkedComponent).FOnStyledMarkerChange) then
TCustomGMMarker(TCustomMarkers(FMarker.Collection).FGMLinkedComponent).FOnStyledMarkerChange(
TCustomGMMarker(TCustomMarkers(FMarker.Collection).FGMLinkedComponent),
FMarker.Index,
FMarker);
end;
procedure TCustomStyledMarker.SetStyledIcon(const Value: TStyledIcon);
begin
if FStyledIcon = Value then Exit;
FStyledIcon := Value;
if not Assigned(FMarker) then Exit;
FMarker.ChangeProperties;
if Assigned(TCustomGMMarker(TCustomMarkers(FMarker.Collection).FGMLinkedComponent).FOnStyledMarkerChange) then
TCustomGMMarker(TCustomMarkers(FMarker.Collection).FGMLinkedComponent).FOnStyledMarkerChange(
TCustomGMMarker(TCustomMarkers(FMarker.Collection).FGMLinkedComponent),
FMarker.Index,
FMarker);
end;
{ TCustomStyleLabel }
procedure TCustomStyleLabel.Assign(Source: TPersistent);
begin
if Source is TCustomStyleLabel then
begin
FMarker := TCustomStyleLabel(Source).FMarker;
Font.Assign(TCustomStyleLabel(Source).Font);
Border.Assign(TCustomStyleLabel(Source).Border);
Opacity := TCustomStyleLabel(Source).Opacity;
NoBackground := TCustomStyleLabel(Source).NoBackground;
end
else inherited;
end;
constructor TCustomStyleLabel.Create(aOwner: TCustomMarker);
begin
FMarker := aOwner;
FOpacity := 1;
FNoBackground := False;
end;
destructor TCustomStyleLabel.Destroy;
begin
if Assigned(FFont) then FreeAndNil(FFont);
if Assigned(FBorder) then FreeAndNil(FBorder);
inherited;
end;
procedure TCustomStyleLabel.SetNoBackground(const Value: Boolean);
begin
FNoBackground := Value;
end;
procedure TCustomStyleLabel.SetOpacity(const Value: Real);
begin
FOpacity := Value;
if FOpacity < 0 then FOpacity := 0;
if FOpacity > 1 then FOpacity := 1;
FOpacity := Trunc(FOpacity * 100) / 100;
end;
{ TCustomGMFont }
procedure TCustomGMFont.Assign(Source: TPersistent);
begin
if Source is TCustomGMFont then
begin
FMarker := TCustomGMFont(Source).FMarker;
Style := TCustomGMFont(Source).Style;
Size := TCustomGMFont(Source).Size;
end
else inherited;
end;
constructor TCustomGMFont.Create(aOwner: TCustomMarker);
begin
FMarker := aOwner;
FStyle := [fstBold];
FSize := 20;
end;
procedure TCustomGMFont.SetSize(const Value: Integer);
begin
FSize := Value;
end;
procedure TCustomGMFont.SetStyle(const Value: TGMFontStyles);
begin
FStyle := Value;
end;
{ TCustomGMBorder }
procedure TCustomGMBorder.Assign(Source: TPersistent);
begin
if Source is TCustomGMBorder then
begin
FMarker := TCustomGMBorder(Source).FMarker;
Size := TCustomGMBorder(Source).Size;
Style := TCustomGMBorder(Source).Style;
end
else inherited;
end;
constructor TCustomGMBorder.Create(aOwner: TCustomMarker);
begin
FMarker := aOwner;
FSize := 2;
FStyle := bsSolid;
end;
procedure TCustomGMBorder.SetSize(const Value: Integer);
begin
FSize := Value;
end;
procedure TCustomGMBorder.SetStyle(const Value: TBorderStyle);
begin
FStyle := Value;
end;
end.
|
unit Tests;
{$mode objfpc}
{$H+}
interface
uses
TestFramework;
type
TTestCaseLargestPalindromeProduct = class(TTestCase)
published
procedure TestResult;
end;
type
TTestCaseLargestPrimeFactor = class(TTestCase)
published
procedure TestResult;
end;
type
TTestCaseEvenFibonacciNumbers = class(TTestCase)
published
procedure TestResult;
end;
type
TTestCaseMultiplesOf3And5 = class(TTestCase)
published
procedure TestResult;
end;
procedure RegisterTests;
implementation
uses
SysUtils, Solutions;
procedure RegisterTests;
begin
TestFramework.RegisterTest(TTestCaseEvenFibonacciNumbers.Suite);
TestFramework.RegisterTest(TTestCaseLargestPalindromeProduct.Suite);
TestFramework.RegisterTest(TTestCaseLargestPrimeFactor.Suite);
TestFramework.RegisterTest(TTestCaseMultiplesOf3And5.Suite);
end;
procedure TTestCaseEvenFibonacciNumbers.TestResult;
begin
Check(Solutions.EvenFibonacciNumbers = 4613732, 'Incorrect!');
end;
procedure TTestCaseLargestPalindromeProduct.TestResult;
begin
Check(Solutions.LargestPalindromeProduct = 906609, 'Incorrect!');
end;
procedure TTestCaseLargestPrimeFactor.TestResult;
begin
Check(Solutions.LargestPrimeFactor(600851475143) = 6857, 'Incorrect!');
end;
procedure TTestCaseMultiplesOf3And5.TestResult;
begin
Check(Solutions.MultiplesOf3And5 = 233168, 'Incorrect!');
end;
end.
|
{ Mapviewer drawing engine
(C) 2019 Werner Pamler (user wp at Lazarus forum https://forum.lazarus.freepascal.org)
License: modified LGPL with linking exception (like RTL, FCL and LCL)
See the file COPYING.modifiedLGPL.txt, included in the Lazarus distribution,
for details about the license.
See also: https://wiki.lazarus.freepascal.org/FPC_modified_LGPL
}
unit mvDrawingEngine;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Graphics, Types, IntfGraphics;
type
TMvCustomDrawingEngine = class(TComponent)
protected
function GetBrushColor: TColor; virtual; abstract;
function GetBrushStyle: TBrushStyle; virtual; abstract;
function GetFontColor: TColor; virtual; abstract;
function GetFontName: String; virtual; abstract;
function GetFontSize: Integer; virtual; abstract;
function GetFontStyle: TFontStyles; virtual; abstract;
function GetPenColor: TColor; virtual; abstract;
function GetPenWidth: Integer; virtual; abstract;
procedure SetBrushColor(AValue: TColor); virtual; abstract;
procedure SetBrushStyle(AValue: TBrushStyle); virtual; abstract;
procedure SetFontColor(AValue: TColor); virtual; abstract;
procedure SetFontName(AValue: String); virtual; abstract;
procedure SetFontSize(AValue: Integer); virtual; abstract;
procedure SetFontStyle(AValue: TFontStyles); virtual; abstract;
procedure SetPenColor(AValue: TColor); virtual; abstract;
procedure SetPenWidth(AValue: Integer); virtual; abstract;
public
procedure CreateBuffer(AWidth, AHeight: Integer); virtual; abstract;
procedure DrawBitmap(X, Y: Integer; ABitmap: TCustomBitmap;
UseAlphaChannel: Boolean); virtual; abstract;
procedure DrawLazIntfImage(X, Y: Integer; AImg: TLazIntfImage); virtual; abstract;
procedure Ellipse(X1, Y1, X2, Y2: Integer); virtual; abstract;
procedure FillRect(X1, Y1, X2, Y2: Integer); virtual; abstract;
procedure Line(X1, Y1, X2, Y2: Integer); virtual; virtual; abstract;
procedure PaintToCanvas(ACanvas: TCanvas); virtual; abstract;
procedure Rectangle(X1, Y1, X2, Y2: Integer); virtual; abstract;
function SaveToImage(AClass: TRasterImageClass): TRasterImage; virtual; abstract;
function TextExtent(const AText: String): TSize; virtual; abstract;
function TextHeight(const AText: String): Integer;
procedure TextOut(X, Y: Integer; const AText: String); virtual; abstract;
function TextWidth(const AText: String): Integer;
property BrushColor: TColor read GetBrushColor write SetBrushColor;
property BrushStyle: TBrushStyle read GetBrushStyle write SetBrushStyle;
property FontColor: TColor read GetFontColor write SetFontColor;
property FontName: String read GetFontName write SetFontName;
property FontSize: Integer read GetFontSize write SetFontSize;
property FontStyle: TFontStyles read GetFontStyle write SetFontStyle;
property PenColor: TColor read GetPenColor write SetPenColor;
property PenWidth: Integer read GetPenWidth write SetPenWidth;
end;
implementation
function TMvCustomDrawingEngine.TextHeight(const AText: String): Integer;
begin
Result := TextExtent(AText).CX;
end;
function TMvCustomDrawingEngine.TextWidth(const AText: String): Integer;
begin
Result := TextExtent(AText).CY;
end;
end.
|
unit BodyOptionsQuery;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseQuery, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt,
Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.StdCtrls, DSWrap;
type
TBodyOptionsW = class(TDSWrap)
private
FOption: TFieldWrap;
FID: TFieldWrap;
public
constructor Create(AOwner: TComponent); override;
function LocateOrAppend(const AOption: string): Boolean;
property Option: TFieldWrap read FOption;
property ID: TFieldWrap read FID;
end;
TQueryBodyOptions = class(TQueryBase)
private
FW: TBodyOptionsW;
{ Private declarations }
public
constructor Create(AOwner: TComponent); override;
property W: TBodyOptionsW read FW;
{ Public declarations }
end;
implementation
{$R *.dfm}
constructor TQueryBodyOptions.Create(AOwner: TComponent);
begin
inherited;
FW := TBodyOptionsW.Create(FDQuery);
end;
constructor TBodyOptionsW.Create(AOwner: TComponent);
begin
inherited;
FID := TFieldWrap.Create(Self, 'ID', '', True);
FOption := TFieldWrap.Create(Self, 'Option');
end;
function TBodyOptionsW.LocateOrAppend(const AOption: string): Boolean;
begin
Assert(not AOption.IsEmpty);
Result := Option.Locate(AOption, [lxoCaseInsensitive]);
if Result then Exit;
TryAppend;
Option.F.AsString := AOption;
TryPost;
end;
end.
|
unit KbdMacro;
interface
uses Windows, IniFiles, Messages, XMLIntf, MSScriptControl_TLB,
Classes;
type
TMacroAction = (KeyboardSequence, SimConnectEvent, maSysCommand, maScript,
maSendToBuffer, maXPLCommand);
TMouseEvent = (None, Wheel, Left, Middle, Right);
TMacroDirection = (mdDown, mdUp);
type THIDKeyboard = class
private
fName: string;
fSystemID: string;
fHandle: HWND;
fLinkedMacrosCount: Integer;
function GetIsAlive: boolean; virtual;
public
property Name : string read fName write fName;
property Handle : HWND read fHandle;
property SystemID : string read fSystemID;
property IsAlive: boolean read GetIsAlive;
property LinkedMacrosCount: Integer read fLinkedMacrosCount;
procedure SaveToIni(f : TIniFile; Section: String); virtual;
procedure SaveToXML(devices : IXMLNode; MyName: String); virtual;
procedure ResetMacrosCount;
procedure IncMacrosCount;
constructor Create(pSystemID: string; pHandle: HWND);
end;
type THIDMouse = class (THIDKeyboard)
// nothing, just inherit all
end;
type TKeyboardMacro = class
private
fId : Integer;
fName: string;
fAction: TMacroAction;
fSequence: string;
fSCEvent: string;
fXPLCommand: string;
fKbdName: string;
fKeyboard: THIDKeyboard;
fKeyCode: Integer;
fButtonIndex: Integer; // for game devices
fSCEventIndex: Integer;
fSCHandle: HWND;
fWindowName: String;
fSCText: Boolean;
fSCParams: String;
fSCParamsArray: array of Cardinal;
fSCParamsIndex: Integer;
fEnteredParams: String;
fMouseEvent: TMouseEvent;
fDirection: TMacroDirection;
fSysCommand: String;
fScriptSource: String;
fScriptCompiled: boolean;
fScriptControl: TScriptControl;
procedure SetSCParams(const Value: String);
function GetSCParamsCount: Integer;
procedure FireSysCommand;
procedure FireScript();
public
property KbdName : string read fKbdName write fKbdName;
property Keyboard : THIDKeyboard read fKeyboard write fKeyboard;
property KeyCode: Integer read fKeyCode write fKeyCode;
property ButtonIndex: Integer read fButtonIndex write fButtonIndex;
property MouseEvent: TMouseEvent read fMouseEvent write fMouseEvent;
property Direction: TMacroDirection read fDirection write fDirection;
property Name : string read fName write fName;
property Action : TMacroAction read fAction write fAction;
property Sequence : string read fSequence write fSequence;
property SCEvent : string read fSCEvent write fSCEvent;
property XPLCommand : string read fXPLCommand write fXPLCommand;
property SCEventIndex : Integer read fSCEventIndex write fSCEventIndex;
property SCHandle: HWND read fSCHandle write fSCHandle;
property SCText: Boolean read fSCText write fSCText;
property WindowName: String read fWindowName write fWindowName;
property SCParams: String read fEnteredParams write SetSCParams;
property SCParamsCount: Integer read GetSCParamsCount;
property Id: Integer read fId;
property SysCommand: String read fSysCommand write fSysCommand;
property ScriptSource : string read fScriptSource write fScriptSource;
property ScriptCompiled: Boolean read fScriptCompiled write fScriptCompiled;
property ScriptControl: TScriptControl read fScriptControl write fScriptControl;
procedure SaveToIni(f : TIniFile; Section: String);
procedure SaveToXML(devices : IXMLNode; MyName: String);
function LoadFromIni(f : TIniFile; Section: String): Boolean;
function LoadFromXml(parent : IXMLNode): Boolean;
function HaveSameTrigger(m: TKeyboardMacro): Boolean;
procedure Fire;
constructor Create;
end;
TMacroThread = class (TThread)
private
fMacro: TKeyboardMacro;
protected
procedure Execute; override;
public
// Creates thread waiting on request:
constructor Create(pMacro: TKeyboardMacro);
destructor Destroy; override;
end;
TMacrosList = class
private
fItems: TList;
function GetCount: Integer;
function GetItems(Index: Integer): TKeyboardMacro;
public
constructor Create;
destructor Destroy; Override;
procedure Add(pMacro: TKeyboardMacro);
function Delete(pMacro: TKeyboardMacro): Boolean;
procedure MoveFromTo(pFrom, pTo: THIDKeyboard; var pMoved, pNotMoved: Integer);
property Items[Index: Integer]: TKeyboardMacro read GetItems;
property Count: Integer read GetCount;
end;
implementation
uses uSendKeys, SysUtils, SimConnect, Forms, ShellAPI,
ActiveX, FSXcontrol, uGlobals; //, Dialogs;
var TMacroId : Integer = 0;
function GetCharFromVKey(vkey: Word): string;
var
keystate: TKeyboardState;
retcode: Integer;
begin
Win32Check(GetKeyboardState(keystate)) ;
SetLength(Result, 2) ;
retcode := ToAscii(vkey,
MapVirtualKey(vkey, 0),
keystate, @Result[1],
0) ;
case retcode of
0: Result := '';
1: SetLength(Result, 1) ;
2: ;
else
Result := '';
end;
end;
{ TKseyboardMacro }
constructor TKeyboardMacro.Create;
begin
fAction := KeyboardSequence;
fScriptCompiled := False;
fKeyboard := nil;
fSCEventIndex := -1;
fSCHandle := 0;
fSCParams := '';
fSCParamsIndex := 0;
fEnteredParams := '';
fKeyCode := -1;
fButtonIndex := -1;
fMouseEvent := None;
fDirection := mdDown;
fSysCommand := '';
fId := TMacroId;
Inc(TMacroId);
inherited;
end;
procedure TKeyboardMacro.Fire;
var arg: PChar;
Text2Send: String;
scValC: Cardinal;
lSndKey: TKeySequence;
lFormHasFocus: Boolean;
begin
//OutputDebugString('[HDM]Fired macro');
lFormHasFocus := Application.Active;
// Following condition is present because of bug (probalby)
// When application starts minimized to tray
// with Application.ShowMainForm := False
// then Application.Active return always true for some reason
// but Screen.ActiveForm is nil luckily
if lFormHasFocus and (Screen.ActiveForm = nil) then
lFormHasFocus := False;
if (fAction = KeyboardSequence) then
begin
arg := StrAlloc(Length(fSequence)+1);
try
StrPCopy(arg, fSequence);
begin
// don't send keystrokes to myself
if (fWindowName <> '') or (not lFormHasFocus) then
begin
//SendKeys(arg, False, fWindowName);
//SendKeys(arg, False);
lSndKey := TKeySequence.Create;
lSndKey.Sequence := fSequence;
lSndKey.Resume;
end;
end;
finally
StrDispose(arg);
end;
end;
if (fAction = SimConnectEvent) then
begin
if (Length(fSCParamsArray) = 0) then
begin
scValC := 0;
Text2Send := fName;
end
else
begin
scValC := fSCParamsArray[fSCParamsIndex];
Text2Send := fName + ' ' + IntToStr(scValC);
Inc(fSCParamsIndex);
if (fSCParamsIndex >= Length(fSCParamsArray)) then
fSCParamsIndex := 0;
end;
Glb.FSX.SendEvent(fSCEvent, scValC);
// text notification
if fSCText then
Glb.FSX.SendText(Text2Send);
end;
if (fAction = maSysCommand) and (Trim(fSysCommand) <> '') then
begin
FireSysCommand();
end;
if (fAction = maScript) and (Trim(fScriptSource) <> '') then
begin
FireScript();
end;
if (fAction = maSendToBuffer) and (fKeyCode >= 0) then // only for keyboard macros
begin
Glb.Buffer.Add(GetCharFromVKey(fKeyCode));
end;
if (fAction = maXPLCommand) and (Trim(fXPLCommand) <> '') then
begin
Glb.Xpl.ExecuteCommand(fXPLCommand);
end;
end;
procedure TKeyboardMacro.FireScript;
var
Bounds : array [0..0] of TSafeArrayBound;
Params : PSafeArray;
begin
if fScriptCompiled then
begin
// no params
Bounds[0].cElements:=0;
Bounds[0].lLbound:=0;
Params:=SafeArrayCreate(varVariant, 1, Bounds);
fScriptControl.Run('Macro'+intToStr(fId), Params);
//ShowMessage('Fired');
end;
end;
procedure TKeyboardMacro.FireSysCommand;
var
arg, comd, pars: String;
I: Integer;
begin
arg := Trim(fSysCommand);
if Length(arg) = 0 then
exit;
if arg[1] = '"' then
begin
// serach for second "
I := Pos('"', Copy(arg, 2, 1000));
if I = 0 then
exit;
comd := Copy(arg,2,I-1);
I := I + 2;
end
else
begin
comd := arg;
I := Pos(' ', arg);
if I = 0 then
I := Length(comd)
else
comd := Copy(arg, 1, I);
end;
// check for params
if I < Length(arg) then
begin
pars := Trim(Copy(arg, I, 1000));
end
else
pars := '';
ShellExecute(Application.MainForm.Handle, nil, PChar(comd), PChar(pars), nil, SW_SHOWNORMAL);
//ShellExecute(Application.MainForm.Handle, nil, PChar('C:\Program Files\PuTTY\putty.exe'), PChar('@Linux'), nil, SW_SHOWNORMAL);
//Showmessage(comd + ' pars: >' + pars + '<');
end;
function TKeyboardMacro.GetSCParamsCount: Integer;
begin
Result := Length(fSCParamsArray);
end;
function TKeyboardMacro.HaveSameTrigger(m: TKeyboardMacro): Boolean;
begin
Result := False;
if (m.Keyboard = nil) or (fKeyboard = nil) then
exit;
if m.Keyboard.SystemID <> fKeyboard.SystemID then
exit;
if fMouseEvent <> m.MouseEvent then
exit;
if fDirection <> m.Direction then
exit;
// keyboard test
if (fKeyCode > 0) and (m.KeyCode <> fKeyCode) then
exit;
// game test
if (fButtonIndex >= 0) and (m.ButtonIndex <> fButtonIndex) then
exit;
// mouse event and direction already checked, so it's ok
Result := True;
end;
function TKeyboardMacro.LoadFromIni(f: TIniFile; Section: String): Boolean;
var tmp: String;
A: Integer;
B: TMouseEvent;
begin
Result := True;
fKbdName := f.ReadString(Section, 'Keyboard', '');
fName := f.ReadString(Section, 'Name', '');
fKeyCode := f.ReadInteger(Section, 'KeyCode', -1);
fButtonIndex := f.ReadInteger(Section, 'ButtonIndex', 0) - 1;
A := f.ReadInteger(Section, 'MouseEvent', 0);
for B := Low(TMouseEvent) to High(TMouseEvent) do
if (Ord(B) = A) then
begin
fMouseEvent := B;
end;
tmp := f.ReadString(Section, 'Direction', 'down');
if UpperCase(tmp) = 'DOWN' then
fDirection := mdDown
else if UpperCase(tmp) = 'UP' then
fDirection := mdUp
else
Result := False;
tmp := f.ReadString(Section, 'Action', '');
if (tmp = 'SIMC') then
fAction := SimConnectEvent
else if (tmp = 'SEQ') then
fAction := KeyboardSequence
else if (tmp = 'CMD') then
fAction := maSysCommand
else
Result := False;
fSequence := f.ReadString(Section, 'Sequence', '');
fSCEvent := f.ReadString(Section, 'SCEvent', '');
SCParams := f.ReadString(Section, 'SCParams', '');
fSCText := f.ReadBool(Section, 'SCText', False);
fSysCommand := f.ReadString(Section, 'Command', '');
if FileExists(fSysCommand) and
(Pos(' ', Trim(fSysCommand)) > 0) and
(Pos('"', Trim(fSysCommand)) <> 1) then
fSysCommand := '"'+fSysCommand+'"';
//if (fKbdName = '') or
// (fKeyCode < 0) then
// Result := False;
end;
function TKeyboardMacro.LoadFromXml(parent : IXMLNode): Boolean;
var tmp: String;
A: Integer;
B: TMouseEvent;
aNode: IXMLNode;
begin
Result := True;
aNode := parent.ChildNodes.First;
while aNode <> nil do
begin
if UpperCase(aNode.NodeName) = 'DEVICE' then
fKbdName := aNode.Text
else if UpperCase(aNode.NodeName) = 'NAME' then
fName := aNode.Text
else if UpperCase(aNode.NodeName) = 'KEYCODE' then
fKeyCode := StrToIntDef(aNode.Text, -1)
else if UpperCase(aNode.NodeName) = 'BUTTONINDEX' then
fButtonIndex := StrToIntDef(aNode.Text, 0) - 1
else if UpperCase(aNode.NodeName) = 'SEQUENCE' then
fSequence := aNode.Text
else if UpperCase(aNode.NodeName) = 'SCEVENT' then
fSCEvent := aNode.Text
else if UpperCase(aNode.NodeName) = 'XPLCOMMAND' then
fXPLCommand := aNode.Text
else if UpperCase(aNode.NodeName) = 'SCPARAMS' then
SCParams := aNode.Text
else if UpperCase(aNode.NodeName) = 'SCTEXT' then
fSCText := aNode.Text = '1'
else if UpperCase(aNode.NodeName) = 'COMMAND' then
fSysCommand := aNode.Text
else if UpperCase(aNode.NodeName) = 'SCRIPTSOURCE' then
fScriptSource := aNode.Text
else if UpperCase(aNode.NodeName) = 'MOUSEEVENT' then
begin
A := StrToIntDef(aNode.Text, 0);
for B := Low(TMouseEvent) to High(TMouseEvent) do
if (Ord(B) = A) then
fMouseEvent := B;
end
else if UpperCase(aNode.NodeName) = 'DIRECTION' then
begin
tmp := aNode.Text;
if UpperCase(tmp) = 'DOWN' then
fDirection := mdDown
else if UpperCase(tmp) = 'UP' then
fDirection := mdUp
else
Result := False;
end
else if UpperCase(aNode.NodeName) = 'ACTION' then
begin
tmp := aNode.Text;
if (tmp = 'SIMC') then
fAction := SimConnectEvent
else if (tmp = 'SEQ') then
fAction := KeyboardSequence
else if (tmp = 'CMD') then
fAction := maSysCommand
else if (tmp = 'BUF') then
fAction := maSendToBuffer
else if (tmp = 'XPLC') then
fAction := maXPLCommand
else if (tmp = 'SCR') then
fAction := maScript
else
Result := False;
end;
aNode := aNode.NextSibling;
end;
if FileExists(fSysCommand) and
(Pos(' ', Trim(fSysCommand)) > 0) and
(Pos('"', Trim(fSysCommand)) <> 1) then
fSysCommand := '"'+fSysCommand+'"';
end;
procedure TKeyboardMacro.SaveToIni(f: TIniFile; Section: String);
begin
f.WriteString(Section, 'Keyboard', fKbdName);
f.WriteString(Section, 'Name', fName);
if (fMouseEvent = None) then
begin
if (fKeyCode >= 0) then
f.WriteInteger(Section, 'KeyCode', fKeyCode);
if (fButtonIndex >= 0) then
f.WriteInteger(Section, 'ButtonIndex', fButtonIndex + 1);
end else
f.WriteInteger(Section, 'MouseEvent', Ord(fMouseEvent));
if (fDirection=mdDown) then
f.WriteString(Section, 'Direction', 'down');
if (fDirection=mdUp) then
f.WriteString(Section, 'Direction', 'up');
if (fAction=SimConnectEvent) then
f.WriteString(Section, 'Action', 'SIMC');
if (fAction=KeyboardSequence) then
f.WriteString(Section, 'Action', 'SEQ');
if (fAction=maSysCommand) then
f.WriteString(Section, 'Action', 'CMD');
f.WriteString(Section, 'Sequence', fSequence);
f.WriteString(Section, 'SCEvent', fSCEvent);
f.WriteBool(Section, 'SCText', fSCText);
f.WriteString(Section, 'SCParams', fEnteredParams);
f.WriteString(Section, 'Command', fSysCommand);
end;
procedure TKeyboardMacro.SaveToXml(devices : IXMLNode; MyName: String);
var parent, x: IXMLNode;
begin
parent := devices.AddChild(MyName);
x := parent.AddChild('Device');
x.Text := fKbdName;
x := parent.AddChild('Name');
x.Text := fName;
if (fMouseEvent = None) then
begin
if (fKeyCode >= 0) then
begin
x := parent.AddChild('KeyCode');
x.Text := IntToStr(fKeyCode);
end;
if (fButtonIndex >= 0) then
begin
x := parent.AddChild('ButtonIndex');
x.Text := IntToStr(fButtonIndex + 1);
end;
end
else
begin
x := parent.AddChild('MouseEvent');
x.Text := IntToStr(Ord(fMouseEvent));
end;
if (fDirection=mdDown) then
begin
x := parent.AddChild('Direction');
x.Text := 'down';
end;
if (fDirection=mdUp) then
begin
x := parent.AddChild('Direction');
x.Text := 'up';
end;
if (fAction=SimConnectEvent) then
begin
x := parent.AddChild('Action');
x.Text := 'SIMC';
end;
if (fAction=KeyboardSequence) then
begin
x := parent.AddChild('Action');
x.Text := 'SEQ';
end;
if (fAction=maSysCommand) then
begin
x := parent.AddChild('Action');
x.Text := 'CMD';
end;
if (fAction=maScript) then
begin
x := parent.AddChild('Action');
x.Text := 'SCR';
end;
if (fAction=maSendToBuffer) then
begin
x := parent.AddChild('Action');
x.Text := 'BUF';
end;
if (fAction=maXPLCommand) then
begin
x := parent.AddChild('Action');
x.Text := 'XPLC';
end;
x := parent.AddChild('Sequence'); x.Text := fSequence;
x := parent.AddChild('SCEvent'); x.Text := fSCEvent;
x := parent.AddChild('XPLCommand'); x.Text := fXPLCommand;
x := parent.AddChild('ScriptSource'); x.Text := fScriptSource;
x := parent.AddChild('SCText');
if fSCText then
x.Text := '1'
else
x.Text := '0';
x := parent.AddChild('SCParams'); x.Text := fEnteredParams;
x := parent.AddChild('Command'); x.Text := fSysCommand;
end;
procedure TKeyboardMacro.SetSCParams(const Value: String);
var
Pos2 : Integer;
TmpC : Cardinal;
ToDo : String;
begin
fSCParams := '';
fSCParamsIndex := 0;
fEnteredParams := Value;
Todo := Value;
SetLength(fSCParamsArray, 0);
if (Trim(Value) = '') then
Exit;
repeat
Pos2 := Pos(';', Todo);
if (Pos2 = 0) then
Pos2 := Length(ToDo)+1;
try
TmpC := StrToInt64(Copy(ToDo, 1, Pos2-1));
SetLength(fSCParamsArray, Length(fSCParamsArray) + 1);
fSCParamsArray[Length(fSCParamsArray)-1] := TmpC;
if (Length(fSCParams) = 0) then
fSCParams := IntToStr(TmpC)
else
fSCParams := fSCParams + ';' + IntToStr(TmpC);
except
on E: EConvertError do
;
end;
ToDo := Copy(ToDo, Pos2+1, Length(Value));
until Length(ToDo) = 0;
end;
{ THIDKeyboard }
constructor THIDKeyboard.Create(pSystemID: string; pHandle: HWND);
begin
fSystemID := pSystemID;
fHandle := pHandle;
inherited Create;
end;
function THIDKeyboard.GetIsAlive: boolean;
begin
Result := (fHandle > 0);
end;
procedure THIDKeyboard.IncMacrosCount;
begin
Inc(fLinkedMacrosCount);
end;
procedure THIDKeyboard.ResetMacrosCount;
begin
fLinkedMacrosCount := 0;
end;
procedure THIDKeyboard.SaveToIni(f: TIniFile; Section: String);
begin
f.WriteString(Section, 'Name', fName);
f.WriteString(Section, 'SystemID', fSystemID);
end;
procedure THIDKeyboard.SaveToXML(devices : IXMLNode; MyName: String);
var parent, x: IXMLNode;
begin
parent := devices.AddChild(MyName);
x := parent.AddChild('Name');
x.Text := fName;
x := parent.AddChild('SystemID');
x.Text := fSystemID;
end;
{ TMacroThread }
constructor TMacroThread.Create(pMacro: TKeyboardMacro);
begin
inherited Create(True);
fMacro := pMacro;
Self.FreeOnTerminate:=True;
end;
destructor TMacroThread.Destroy;
begin
inherited;
end;
procedure TMacroThread.Execute;
var
tmp: array[0..255] of char;
begin
try
fMacro.Fire;
except
on E:Exception do
begin
StrPCopy(tmp, 'HIDMACROS: Thread exception ' + E.Message);
OutputDebugString(tmp);
end;
end;
end;
{ THIDControl }
{ TMacrosList }
procedure TMacrosList.Add(pMacro: TKeyboardMacro);
begin
fItems.Add(pMacro);
end;
constructor TMacrosList.Create;
begin
fItems := TList.Create;
end;
function TMacrosList.Delete(pMacro: TKeyboardMacro): Boolean;
var
lCount: Integer;
begin
lCount := fItems.Count;
Result := fItems.Remove(pMacro) < lCount;
end;
destructor TMacrosList.Destroy;
begin
fItems.Free;
inherited;
end;
function TMacrosList.GetCount: Integer;
begin
Result := fItems.Count;
end;
function TMacrosList.GetItems(Index: Integer): TKeyboardMacro;
begin
Result := TKeyboardMacro(fItems[Index]);
end;
procedure TMacrosList.MoveFromTo(pFrom, pTo: THIDKeyboard; var pMoved, pNotMoved: Integer);
var
I, J: Integer;
begin
pMoved := 0;
pNotMoved := 0;
for I := 0 to fItems.Count - 1 do
if Items[i].fKeyboard = pFrom then
begin
// try to set, then compare if there's any other with the same trigger
Items[i].fKeyboard := pTo;
Inc(pMoved);
Items[i].fKbdName := pTo.Name;
for J := 0 to fItems.Count - 1 do
if (i <> j) and (Items[j].HaveSameTrigger(Items[i])) then
begin
// can not be moved, revert assignment
Items[i].fKeyboard := pFrom;
Items[i].fKbdName := pFrom.Name;
Dec(pMoved);
Inc(pNotMoved);
end;
end;
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLKeyboard<p>
Provides on demand state of any key on the keyboard as well as a set of
utility functions for working with virtual keycodes.<p>
Note that windows maps the mouse buttons to virtual key codes too, and you
can use the functions/classes in this unit to check mouse buttons too.<br>
See "Virtual-Key Codes" in the Win32 programmers réferences for a list of
key code constants (VK_* constants are declared in the "Windows" unit).<p>
<b>Historique : </b><font size=-1><ul>
<li>07/11/09 - DaStr - Improved FPC compatibility and moved to the /Source/Platform/
directory (BugtrackerID = 2893580) (thanks Predator)
<li>28/03/07 - DaStr - Renamed from Keyboard.pas (BugTracker ID = 1678646)
<li>17/03/07 - DaStr - Dropped Kylix support in favor of FPC (BugTrackerID=1681585)
<li>19/12/06 - DaS - Added additional string constants and made all
existing 'Mixed Case', not 'UPPERCASE'
KeyNameToVirtualKeyCode optimized,
Fixed comments to KeyNameToVirtualKeyCode() function
<li>17/11/03 - Egg - Fixed IsKeyDown (VK) (A. P. Mohrenweiser)
<li>09/10/00 - Egg - Fixed VirtualKeyCodeToKeyName
<li>03/08/00 - Egg - Creation, partly based Silicon Commander code
</ul></font>
}
unit GLKeyboard;
interface
{$I GLScene.inc}
uses
Windows;
type
TVirtualKeyCode = Integer;
const
// pseudo wheel keys (we squat F23/F24), see KeyboardNotifyWheelMoved
VK_MOUSEWHEELUP = VK_F23;
VK_MOUSEWHEELDOWN = VK_F24;
{: Check if the key corresponding to the given Char is down.<p>
The character is mapped to the <i>main keyboard</i> only, and not to the
numeric keypad.<br>
The Shift/Ctrl/Alt state combinations that may be required to type the
character are ignored (ie. 'a' is equivalent to 'A', and on my french
keyboard, '5' = '(' = '[' since they all share the same physical key). }
function IsKeyDown(c : Char) : Boolean; overload;
{: Check if the given virtual key is down.<p>
This function is just a wrapper for GetAsyncKeyState. }
function IsKeyDown(vk : TVirtualKeyCode) : Boolean; overload;
{: Returns the first pressed key whose virtual key code is >= to minVkCode.<p>
If no key is pressed, the return value is -1, this function does NOT
wait for user input.<br>
If you don't care about multiple key presses, just don't use the parameter. }
function KeyPressed(minVkCode : TVirtualKeyCode = 0) : TVirtualKeyCode;
{: Converts a virtual key code to its name.<p>
The name is expressed using the locale windows options. }
function VirtualKeyCodeToKeyName(vk : TVirtualKeyCode) : String;
{: Converts a key name to its virtual key code.<p>
The comparison is **NOT** case-sensitive, if no match is found, returns -1.<p>
The name is expressed using the locale windows options, except for mouse
buttons which are translated to 'LBUTTON', 'MBUTTON' and 'RBUTTON'. }
function KeyNameToVirtualKeyCode(const keyName : String) : TVirtualKeyCode;
{: Returns the virtual keycode corresponding to the given char.<p>
The returned code is untranslated, f.i. 'a' and 'A' will give the same
result. A return value of -1 means that the characted cannot be entered
using the keyboard. }
function CharToVirtualKeyCode(c : Char) : TVirtualKeyCode;
{: Use this procedure to notify a wheel movement and have it resurfaced as key stroke.<p>
Honoured by IsKeyDown and KeyPressed }
procedure KeyboardNotifyWheelMoved(wheelDelta : Integer);
var
vLastWheelDelta : Integer;
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
implementation
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
uses SysUtils;
const
cLBUTTON = 'Left Mouse Button';
cMBUTTON = 'Middle Mouse Button';
cRBUTTON = 'Right Mouse Button';
cUP = 'Up';
cDOWN = 'Down';
cRIGHT = 'Right';
cLEFT = 'Left';
cPAGEUP = 'Page up';
cPAGEDOWN = 'Page down';
cHOME = 'Home';
cEND = 'End';
cMOUSEWHEELUP = 'Mouse Wheel Up';
cMOUSEWHEELDOWN = 'Mouse Wheel Down';
cPAUSE = 'Pause';
cSNAPSHOT = 'Print Screen';
cNUMLOCK = 'Num Lock';
cINSERT = 'Insert';
cDELETE = 'Delete';
cDIVIDE = 'Num /';
cLWIN = 'Left Win';
cRWIN = 'Right Win';
cAPPS = 'Application Key';
c0 = '~';
c1 = '[';
c2 = ']';
c3 = ';';
c4 = '''';
c5 = '<';
c6 = '>';
c7 = '/';
c8 = '\';
// IsKeyDown
//
function IsKeyDown(c : Char) : Boolean;
{$IFDEF MSWINDOWS}
var
vk : Integer;
begin
// '$FF' filters out translators like Shift, Ctrl, Alt
vk:=VkKeyScan(c) and $FF;
if vk<>$FF then
Result:=(GetAsyncKeyState(vk)<0)
else Result:=False;
end;
{$ELSE}
begin
raise Exception.Create('GLKeyboard.IsKeyDown(c : Char) not yet implemented for your platform!');
end;
{$ENDIF}
// IsKeyDown
//
function IsKeyDown(vk : TVirtualKeyCode) : Boolean;
begin
case vk of
VK_MOUSEWHEELUP:
begin
Result := vLastWheelDelta > 0;
if Result then
vLastWheelDelta := 0;
end;
VK_MOUSEWHEELDOWN:
begin
Result := vLastWheelDelta < 0;
if Result then
vLastWheelDelta := 0;
end;
else
{$IFDEF MSWINDOWS}
Result := (GetAsyncKeyState(vk) < 0);
{$ELSE}
raise Exception.Create('GLKeyboard.IsKeyDown(vk : TVirtualKeyCode) not fully yet implemented for your platform!');
{$ENDIF}
end;
end;
// KeyPressed
//
function KeyPressed(minVkCode : TVirtualKeyCode = 0) : TVirtualKeyCode;
{$IFDEF MSWINDOWS}
var
i : Integer;
buf : TKeyboardState;
begin
Assert(minVkCode>=0);
Result:=-1;
if GetKeyboardState(buf) then begin
for i:=minVkCode to High(buf) do begin
if (buf[i] and $80)<>0 then begin
Result:=i;
Exit;
end;
end;
end;
if vLastWheelDelta<>0 then begin
if vLastWheelDelta>0 then
Result:=VK_MOUSEWHEELUP
else Result:=VK_MOUSEWHEELDOWN;
vLastWheelDelta:=0;
end;
end;
{$ELSE}
begin
raise Exception.Create('GLKeyboard.KeyPressed not yet implemented for your platform!');
end;
{$ENDIF}
// VirtualKeyCodeToKeyName
//
function VirtualKeyCodeToKeyName(vk : TVirtualKeyCode) : String;
{$IFDEF MSWINDOWS}
var
nSize : Integer;
{$ENDIF}
begin
// Win32 API can't translate mouse button virtual keys to string
case vk of
VK_LBUTTON : Result:=cLBUTTON;
VK_MBUTTON : Result:=cMBUTTON;
VK_RBUTTON : Result:=cRBUTTON;
VK_UP : Result:=cUP;
VK_DOWN : Result:=cDOWN;
VK_LEFT : Result:=cLEFT;
VK_RIGHT : Result:=cRIGHT;
VK_PRIOR : Result:=cPAGEUP;
VK_NEXT : Result:=cPAGEDOWN;
VK_HOME : Result:=cHOME;
VK_END : Result:=cEND;
VK_MOUSEWHEELUP : Result:=cMOUSEWHEELUP;
VK_MOUSEWHEELDOWN : Result:=cMOUSEWHEELDOWN;
VK_PAUSE : Result := cPAUSE;
VK_SNAPSHOT : Result := cSNAPSHOT;
VK_NUMLOCK : Result := cNUMLOCK;
VK_INSERT : Result := cINSERT;
VK_DELETE : Result := cDELETE;
VK_DIVIDE : Result := cDIVIDE;
VK_LWIN : Result := cLWIN;
VK_RWIN : Result := cRWIN;
VK_APPS : Result := cAPPS;
192 : Result := c0;
219 : Result := c1;
221 : Result := c2;
186 : Result := c3;
222 : Result := c4;
188 : Result := c5;
190 : Result := c6;
191 : Result := c7;
220 : Result := c8;
else
{$IFDEF MSWINDOWS}
nSize:=32; // should be enough
SetLength(Result, nSize);
vk:=MapVirtualKey(vk, 0);
nSize:=GetKeyNameText((vk and $FF) shl 16, PChar(Result), nSize);
SetLength(Result, nSize);
{$ELSE}
raise Exception.Create('GLKeyboard.VirtualKeyCodeToKeyName not yet fully implemented for your platform!');
{$ENDIF}
end;
end;
// KeyNameToVirtualKeyCode
//
function KeyNameToVirtualKeyCode(const keyName : String) : TVirtualKeyCode;
{$IFDEF MSWINDOWS}
var
i : Integer;
begin
// ok, I admit this is plain ugly. 8)
Result:=-1;
for i:=0 to 255 do
begin
if SameText(VirtualKeyCodeToKeyName(i), keyName) then
begin
Result:=i;
Break;
end;
end;
end;
{$ELSE}
var
i : Integer;
lExceptionWasRaised: Boolean;
begin
// ok, I admit this is plain ugly. 8)
Result := -1;
lExceptionWasRaised := False;
for i:=0 to 255 do
try
if SameText(VirtualKeyCodeToKeyName(i), keyName) then
begin
Result:=i;
Exit;
end;
finally
lExceptionWasRaised := True;
// DaStr: Since VirtualKeyCodeToKeyName is not fully implemented in non-Unix
// systems, this function can thow exceptions, which we need to catch here.
end;
if (Result = -1) and lExceptionWasRaised then
raise Exception.Create('GLKeyboard.KeyNameToVirtualKeyCode not yet fully implemented for your platform or keyName wasn''t found!');
end;
{$ENDIF}
// CharToVirtualKeyCode
//
function CharToVirtualKeyCode(c : Char) : TVirtualKeyCode;
begin
{$IFDEF MSWINDOWS}
Result:=VkKeyScan(c) and $FF;
if Result=$FF then Result:=-1;
{$ELSE}
raise Exception.Create('GLKeyboard.CharToVirtualKeyCode not yet implemented for your platform!');
{$ENDIF}
end;
// KeyboardNotifyWheelMoved
//
procedure KeyboardNotifyWheelMoved(wheelDelta : Integer);
begin
vLastWheelDelta:=wheelDelta;
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit System.Win.ComConst;
interface
resourcestring
SCreateRegKeyError = 'Error creating system registry entry';
SOleError = 'OLE error %.8x';
SObjectFactoryMissing = 'Object factory for class %s missing';
STypeInfoMissing = 'Type information missing for class %s';
SBadTypeInfo = 'Incorrect type information for class %s';
SDispIntfMissing = 'Dispatch interface missing from class %s';
SNoMethod = 'Method ''%s'' not supported by automation object';
SVarNotObject = 'Variant does not reference an automation object';
STooManyParams = 'Dispatch methods do not support more than 64 parameters';
SDCOMNotInstalled = 'DCOM not installed';
SDAXError = 'DAX Error';
SAutomationWarning = 'COM Server Warning';
SNoCloseActiveServer1 = 'There are still active COM objects in this ' +
'application. One or more clients may have references to these objects, ' +
'so manually closing ';
SNoCloseActiveServer2 = 'this application may cause those client ' +
'application(s) to fail.'#13#10#13#10'Are you sure you want to close this ' +
'application?';
implementation
end.
|
{$mode objfpc}{$H+}{$J-}
program is_as;
uses
SysUtils;
type
TMyClass = class
procedure MyMethod;
end;
TMyClassDescendant = class(TMyClass)
procedure MyMethodInDescendant;
end;
procedure TMyClass.MyMethod;
begin
WriteLn('Это MyMethod')
end;
procedure TMyClassDescendant.MyMethodInDescendant;
begin
WriteLn('Это MyMethodInDescendant')
end;
var
Descendant: TMyClassDescendant;
C: TMyClass;
begin
Descendant := TMyClassDescendant.Create;
try
Descendant.MyMethod;
Descendant.MyMethodInDescendant;
{ производные классы сохраняют все функции родительского класса
TMyClass, по этому можно таким образом создавать ссылку }
C := Descendant;
C.MyMethod;
{ так не сработает, поскольку в TMyClass не определён этот метод }
//C.MyMethodInDescendant;
{ правильно записать следующим образом: }
if C is TMyClassDescendant then
(C as TMyClassDescendant).MyMethodInDescendant;
finally
FreeAndNil(Descendant);
end;
end.
|
//====================================================================//
// uKembali //
//--------------------------------------------------------------------//
// Unit yang menangani hal-hal yang berhubungan dengan pengembalian //
//====================================================================//
unit uKembali;
interface
uses uFileLoader, udate, Crt;
function isThnKabisat(j:integer): boolean;
{ Menghasilkan true jika tahun adalah tahun kabisat dan false jika tidak }
function convertBulantoHari(m, y: integer): integer;
{ Mengkonversikan bulan menjadi hari }
function convertTahuntoHari(y: integer): Integer;
{ Mngkonversikan tahun menjadi hari }
procedure denda(var tk, bk, hk, tbk, bbk, hbk: integer);
{ Menampilkan jumlah hari keterlambatan dan besar dendanya }
{I.S. : input tahun, bulan, dan hari pengembalian serta batas pengembalian belum berupa hari }
{F.S. : input tahun, bulan, dan hari pengembalian serta batas pengembalian telah dikonversikan menjadi hari dan
menampilkan selisihnya (jumlah hari keterlambatan) dan dikali 2000 sebagai besar dendanya }
procedure KembalikanBuku (var arrHistoryPengembalian : KembaliArr ; var arrHistoryPeminjaman : PinjamArr; var arrBuku : BArr ; UserIn : User);
{Mengisi data yang diinputkan oleh pengguna ke dalam arrHistoryPengembalian}
{I.S. : arrHistoryPengembalian sudah berisi data dari file riwayat peminjaman dan/atau modifikasi di main program}
{F.S. : arrHistoryPengembalian tercetak ke layar sesuai format data riwayat pengembalian}
procedure PrintHistoryPengembalian (var arrHistoryPengembalian : KembaliArr);
{Menulis elemen-elemen dari arrHistoryPengembalian ke layar dengan format sesuai data riwayat pengembalian}
{I.S. : arrHistoryPengembalian sudah berisi data dari file riwayat pengembalian dan/atau modifikasi di main program}
{F.S. : arrHistoryPengembalian tercetak ke layar sesuai format data riwayat pengembalian}
implementation
function isThnKabisat(j:integer): boolean;
{ Menghasilkan true jika tahun adalah tahun kabisat dan false jika tidak }
{ ALGORITMA }
begin
isThnKabisat := (j mod 4 = 0) and (j mod 100 <> 0) or (j mod 400 = 0);
end;
function convertBulantoHari(m, y: integer): integer;
{ Mengkonversikan bulan menjadi hari }
{ KAMUS LOKAL }
var
jml_hari, i: Integer;
{ ALGORITMA }
begin
if(m = 1) then
begin
convertBulantoHari := 0; { fungsi mengembalikan 0 jika input bulan = 1 }
end
else
begin
jml_hari := 0; { inisialisasi }
for i:=1 to (m-1) do { EOP: i = m-1 }
begin
if((i = 2) and (isThnKabisat(y))) then { proses kasus jika bulan = Februari dan tahun adalah kabisat }
begin
jml_hari := jml_hari + 29;
end
else if((i=2) and (not isThnKabisat(y))) then { proses kasus jika bulan = Februari dan tahun bukan kabisat }
begin
jml_hari := jml_hari + 28;
end
else if((i<=7) and (i mod 2 = 1)) then { proses kasus jika bulan <= Juli dan merupakan bulan ganjil }
begin
jml_hari := jml_hari + 31;
end
else if((i>7) and (i mod 2 = 0)) then { proses kasus jika bulan > Juli dan merupakan bulan genap }
begin
jml_hari := jml_hari + 31;
end
else { bulan genap <= Juli atau bulan ganjil > Juli }
begin
jml_hari := jml_hari + 30;
end;
end;
convertBulantoHari := jml_hari; { fungsi mengembalikan jumlah hari }
end;
end;
function convertTahuntoHari(y: integer): Integer;
{ Mngkonversikan tahun menjadi hari }
{ KAMUS LOKAL }
var
jml_hari, i: Integer;
{ ALGORITMA }
begin
jml_hari:=0; { inisialisasi }
for i:=0 to y do { EOP : i = y }
begin
if(isThnKabisat(y)) then { proses kasus tahun adalah kabisat }
begin
jml_hari := jml_hari + 366;
end
else { proses kasus tahun bukan kabisat }
begin
jml_hari := jml_hari + 365;
end;
end;
convertTahuntoHari := jml_hari; { fungsi mengembalikan jumlah hari }
end;
procedure denda(var tk, bk, hk, tbk, bbk, hbk: integer);
{ Menampilkan jumlah hari keterlambatan dan besar dendanya }
{I.S. : input tahun, bulan, dan hari pengembalian serta batas pengembalian belum berupa hari }
{F.S. : input tahun, bulan, dan hari pengembalian serta batas pengembalian telah dikonversikan menjadi hari dan
menampilkan selisihnya (jumlah hari keterlambatan) dan dikali 2000 sebagai besar dendanya }
{ KAMUS LOKAL }
var
fine, days : integer;
{ ALGORITMA }
begin
days:= (convertTahuntoHari(tk) + hk + convertBulantoHari(bk, tk) - convertTahuntoHari(tbk) -
hbk - convertBulantoHari(bbk, tbk));
begin
fine:=days*2000;
writeln('Anda terlambat mengembalikan buku ', days, ' hari.');
writeln('Anda terkena denda ', fine, ' rupiah.');
end;
end;
procedure KembalikanBuku (var arrHistoryPengembalian : KembaliArr ; var arrHistoryPeminjaman : PinjamArr; var arrBuku : BArr ; UserIn : User);
{Mengisi data yang diinputkan oleh pengguna ke dalam arrHistoryPengembalian}
{I.S. : arrHistoryPengembalian sudah berisi data dari file riwayat peminjaman dan/atau modifikasi di main program}
{F.S. : arrHistoryPengembalian tercetak ke layar sesuai format data riwayat pengembalian}
{ KAMUS LOKAL }
var
idkembali, judulbuku : string;
i, TahunKembali, BulanKembali, HariKembali, TahunBatasKembali, BulanBatasKembali, HariBatasKembali : integer;
tanggalkembalistring : string;
{ ALGORITMA }
begin
// Pengguna menginput id buku yang bertype string yang kemudian disimpan
// di array History Peminjaman
write('Masukkan id buku yang ingin dikembalikan: ');
readln(idkembali);
arrHistoryPengembalian[lenhistorypengembalian + 1].ID_Buku := idkembali;
writeln('Data Peminjam: ');
// For loop untuk mencari data buku
for i := 1 to (lenbuku) do
begin
if arrBuku[i].ID_Buku = idkembali then
begin
judulbuku := arrBuku[i].Judul_Buku;
arrBuku[i].Jumlah_Buku := arrBuku[i].Jumlah_Buku + 1;
end;
end;
// Untuk menampilkan Username, Judul Buku, Tanggal Peminjaman, serta Tanggal Batas Pengembalian
for i:= 1 to (lenhistorypeminjaman) do
begin
if (arrHistoryPeminjaman[i].ID_Buku = idkembali) and (arrHistoryPeminjaman[i].Username = UserIn.Username) then // tambah username untuk mengantisipasi ada 1 buku yang dipinjam 2 user
begin
writeln('Username: ', arrHistoryPeminjaman[i].Username);
writeln('Judul_Buku: ', judulbuku);
write('Tanggal Peminjaman: ');
writelnDate(arrHistoryPeminjaman[i].Tanggal_Peminjaman);
write('Tanggal Batas Pengembalian: ');
writelnDate(arrHistoryPeminjaman[i].Tanggal_Batas_Pengembalian);
TahunBatasKembali := arrHistoryPeminjaman[i].Tanggal_Batas_Pengembalian.YYYY;
BulanBatasKembali := arrHistoryPeminjaman[i].Tanggal_Batas_Pengembalian.MM;
HariBatasKembali := arrHistoryPeminjaman[i].Tanggal_Batas_Pengembalian.DD;
arrHistoryPeminjaman[i].Status_Pengembalian := true;
end;
end;
// Pengguna menginput tanggal bertipe string
write('Masukkan tanggal hari ini: ');
readln(tanggalkembalistring);
// untuk mengubah type tanggal yang berbentuk string menjadi type date
arrHistoryPengembalian[lenhistorypengembalian + 1].Tanggal_Pengembalian := ParseDate(tanggalkembalistring);
arrHistoryPengembalian[lenhistorypengembalian + 1].Username := UserIn.Username;
TahunKembali := arrHistoryPengembalian[lenhistorypengembalian + 1].Tanggal_Pengembalian.YYYY;
BulanKembali := arrHistoryPengembalian[lenhistorypengembalian + 1].Tanggal_Pengembalian.MM;
HariKembali := arrHistoryPengembalian[lenhistorypengembalian + 1].Tanggal_Pengembalian.DD;
lenhistorypengembalian := lenhistorypengembalian + 1;
// Membandingkan tanggal batas kembali dengan tanggal kembali untuk mengeluarkan output
// berupa message yang telah ditentukan
if (TahunBatasKembali = TahunKembali) then
begin
if (BulanBatasKembali = BulanKembali) then
begin
if (HariBatasKembali >= HariKembali) then
begin
writeln('Terima kasih sudah meminjam');
end else
begin
denda(TahunKembali, BulanKembali, HariKembali, TahunBatasKembali, BulanBatasKembali, HariBatasKembali);
end;
end else if (BulanBatasKembali > BulanKembali) then
begin
writeln('Terima kasih sudah meminjam');
end else
begin
denda(TahunKembali, BulanKembali, HariKembali, TahunBatasKembali, BulanBatasKembali, HariBatasKembali);
end;
end else if (TahunBatasKembali > TahunKembali) then
begin
writeln('Terima kasih sudah meminjam');
end else
begin
denda(TahunKembali, BulanKembali, HariKembali, TahunBatasKembali, BulanBatasKembali, HariBatasKembali);
end;
writeln();
writeln('Ketik 0 untuk kembali ke menu.');
readln();
ClrScr;
end;
procedure PrintHistoryPengembalian (var arrHistoryPengembalian : KembaliArr);
{Menulis elemen-elemen dari arrHistoryPengembalian ke layar dengan format sesuai data riwayat pengembalian}
{I.S. : arrHistoryPengembalian sudah berisi data dari file riwayat pengembalian dan/atau modifikasi di main program}
{F.S. : arrHistoryPengembalian tercetak ke layar sesuai format data riwayat pengembalian}
{' | ' digunakan untuk pemisah antar kolom}
{ KAMUS LOKAL }
var
k : integer;
{ ALGORITMA }
begin
for k := 1 to (lenHistoryPengembalian) do
begin
write(k);
write(' | ');
write(arrHistoryPengembalian[k].Username);
write(' | ');
write(arrHistoryPengembalian[k].ID_Buku);
write(' | ');
WriteDate(arrHistoryPengembalian[k].Tanggal_Pengembalian);
writeln();
end;
writeln();
writeln('Ketik 0 untuk kembali ke menu.');
readln();
ClrScr;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.