text stringlengths 14 6.51M |
|---|
unit GLDStandardObjectsFrame;
interface
uses
SysUtils, Classes, Controls, Forms, Buttons, StdCtrls,
GLDTypes, GLDSystem;
type
TGLDParamsFrameType =
(GLD_PARAMS_FRAME_NONE,
GLD_PARAMS_FRAME_BOX,
GLD_PARAMS_FRAME_PYRAMID,
GLD_PARAMS_FRAME_CYLINDER,
GLD_PARAMS_FRAME_CONE,
GLD_PARAMS_FRAME_TORUS,
GLD_PARAMS_FRAME_SPHERE,
GLD_PARAMS_FRAME_TUBE);
TGLDStandardObjectsFrame = class(TFrame)
SB_StandardObjects: TScrollBox;
GB_ObjectType: TGroupBox;
SB_Box: TSpeedButton;
SB_Pyramid: TSpeedButton;
SB_Cylinder: TSpeedButton;
SB_Cone: TSpeedButton;
SB_Torus: TSpeedButton;
SB_Sphere: TSpeedButton;
SB_Tube: TSpeedButton;
procedure SpeedButtonClick(Sender: TObject);
private
FParamsFrame: TFrame;
FDrawer: TGLDDrawer;
function GetParamsFrameType: TGLDParamsFrameType;
procedure SetParamsFrameType(Value: TGLDParamsFrameType);
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure SetEditedObject;
procedure SetParamsFrameParams(AObject: TObject);
property ParamsFrameType: TGLDParamsFrameType read GetParamsFrameType write SetParamsFrameType;
property Drawer: TGLDDrawer read FDrawer write FDrawer;
end;
function GLDXParamsFrameType(AType: TGLDSysClassType): TGLDParamsFrameType;
procedure Register;
implementation
{$R *.dfm}
uses
{$include GLDObjects.inc},
{$include GLDObjectParamsFrames.inc};
constructor TGLDStandardObjectsFrame.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FParamsFrame := nil;
FDrawer := nil;
end;
destructor TGLDStandardObjectsFrame.Destroy;
begin
FParamsFrame.Free;
inherited Destroy;
end;
procedure TGLDStandardObjectsFrame.SetEditedObject;
begin
if not Assigned(FDrawer) then Exit;
if Assigned(FDrawer.EditedObject) then
begin
SetParamsFrameType(GLDXParamsFrameType(FDrawer.EditedObject.SysClassType));
SetParamsFrameParams(FDrawer.EditedObject);
end;
end;
procedure TGLDStandardObjectsFrame.SetParamsFrameParams(AObject: TObject);
begin
if not Assigned(AObject) then Exit;
case GetParamsFrameType of
GLD_PARAMS_FRAME_BOX:
if AObject is TGLDBox then
with TGLDBox(AObject) do
TGLDBoxParamsFrame(FParamsFrame).SetParams(Name, Color.Color3ub,
Length, Width, Height, LengthSegs, WidthSegs, HeightSegs);
GLD_PARAMS_FRAME_PYRAMID:
if AObject is TGLDPyramid then
with TGLDPyramid(AObject) do
TGLDPyramidParamsFrame(FParamsFrame).SetParams(Name, Color.Color3ub,
Width, Depth, Height, WidthSegs, DepthSegs, HeightSegs);
GLD_PARAMS_FRAME_CYLINDER:
if AObject is TGLDCylinder then
with TGLDCylinder(AObject) do
TGLDCylinderParamsFrame(FParamsFrame).SetParams(Name, Color.Color3ub,
Radius, Height, HeightSegs, CapSegs, Sides, StartAngle, SweepAngle);
GLD_PARAMS_FRAME_CONE:
if AObject is TGLDCone then
with TGLDCone(AObject) do
TGLDConeParamsFrame(FParamsFrame).SetParams(Name, Color.Color3ub,
BaseRadius, TopRadius, Height, HeightSegs, CapSegs, Sides, StartAngle, SweepAngle);
GLD_PARAMS_FRAME_TORUS:
if AObject is TGLDTorus then
with TGLDTorus(AObject) do
TGLDTorusParamsFrame(FParamsFrame).SetParams(Name, Color.Color3ub,
Radius1, Radius2, Segments, Sides, StartAngle1, SweepAngle1, StartAngle2, SweepAngle2);
GLD_PARAMS_FRAME_SPHERE:
if AObject is TGLDSphere then
with TGLDSphere(AObject) do
TGLDSphereParamsFrame(FParamsFrame).SetParams(Name, Color.Color3ub,
Radius, Segments, Sides, StartAngle1, SweepAngle1, StartAngle2, SweepAngle2);
GLD_PARAMS_FRAME_TUBE:
if AObject is TGLDTube then
with TGLDTube(AObject) do
TGLDTubeParamsFrame(FParamsFrame).SetParams(Name, Color.Color3ub,
InnerRadius, OuterRadius, Height, HeightSegs, CapSegs, Sides, StartAngle, SweepAngle);
end;
end;
procedure TGLDStandardObjectsFrame.Notification(AComponent: TComponent; Operation: TOperation);
begin
if Assigned(FDrawer) and (AComponent = FDrawer.Owner) and
(Operation = opRemove) then FDrawer := nil;
inherited Notification(AComponent, Operation);
end;
procedure TGLDStandardObjectsFrame.SpeedButtonClick(Sender: TObject);
begin
if not Assigned(FDrawer) then Exit;
if Sender = SB_Box then
begin
SetParamsFrameType(GLD_PARAMS_FRAME_BOX);
FDrawer.StartDrawing(TGLDBox);
end else
if Sender = SB_Pyramid then
begin
SetParamsFrameType(GLD_PARAMS_FRAME_PYRAMID);
FDrawer.StartDrawing(TGLDPyramid);
end else
if Sender = SB_Cylinder then
begin
SetParamsFrameType(GLD_PARAMS_FRAME_CYLINDER);
FDrawer.StartDrawing(TGLDCylinder);
end else
if Sender = SB_Cone then
begin
SetParamsFrameType(GLD_PARAMS_FRAME_CONE);
FDrawer.StartDrawing(TGLDCone);
end else
if Sender = SB_Torus then
begin
SetParamsFrameType(GLD_PARAMS_FRAME_TORUS);
FDrawer.StartDrawing(TGLDTorus);
end else
if Sender = SB_Sphere then
begin
SetParamsFrameType(GLD_PARAMS_FRAME_SPHERE);
FDrawer.StartDrawing(TGLDSphere);
end else
if Sender = SB_Tube then
begin
SetParamsFrameType(GLD_PARAMS_FRAME_TUBE);
FDrawer.StartDrawing(TGLDTube);
end;
end;
function TGLDStandardObjectsFrame.GetParamsFrameType: TGLDParamsFrameType;
begin
Result := GLD_PARAMS_FRAME_NONE;
if not Assigned(FParamsFrame) then Exit;
if FParamsFrame is TGLDBoxParamsFrame then Result := GLD_PARAMS_FRAME_BOX else
if FParamsFrame is TGLDPyramidParamsFrame then Result := GLD_PARAMS_FRAME_PYRAMID else
if FParamsFrame is TGLDCylinderParamsFrame then Result := GLD_PARAMS_FRAME_CYLINDER else
if FParamsFrame is TGLDConeParamsFrame then Result := GLD_PARAMS_FRAME_CONE else
if FParamsFrame is TGLDTorusParamsFrame then Result := GLD_PARAMS_FRAME_TORUS else
if FParamsFrame is TGLDSphereParamsFrame then Result := GLD_PARAMS_FRAME_SPHERE else
if FParamsFrame is TGLDTubeParamsFrame then Result := GLD_PARAMS_FRAME_TUBE;
end;
procedure TGLDStandardObjectsFrame.SetParamsFrameType(Value: TGLDParamsFrameType);
begin
//if GetParamsFrameType = Value then Exit;
FParamsFrame.Free;
FParamsFrame := nil;
case Value of
GLD_PARAMS_FRAME_BOX:
begin
FParamsFrame := TGLDBoxParamsFrame.Create(Self);
TGLDBoxParamsFrame(FParamsFrame).Drawer := FDrawer;
end;
GLD_PARAMS_FRAME_PYRAMID:
begin
FParamsFrame := TGLDPyramidParamsFrame.Create(Self);
TGLDPyramidParamsFrame(FParamsFrame).Drawer := FDrawer;
end;
GLD_PARAMS_FRAME_CYLINDER:
begin
FParamsFrame := TGLDCylinderParamsFrame.Create(Self);
TGLDCylinderParamsFrame(FParamsFrame).Drawer := FDrawer;
end;
GLD_PARAMS_FRAME_CONE:
begin
FParamsFrame := TGLDConeParamsFrame.Create(Self);
TGLDConeParamsFrame(FParamsFrame).Drawer := FDrawer;
end;
GLD_PARAMS_FRAME_TORUS:
begin
FParamsFrame := TGLDTorusParamsFrame.Create(Self);
TGLDTorusParamsFrame(FParamsFrame).Drawer := FDrawer;
end;
GLD_PARAMS_FRAME_SPHERE:
begin
FParamsFrame := TGLDSphereParamsFrame.Create(Self);
TGLDSphereParamsFrame(FParamsFrame).Drawer := FDrawer;
end;
GLD_PARAMS_FRAME_TUBE:
begin
FParamsFrame := TGLDTubeParamsFrame.Create(Self);
TGLDTubeParamsFrame(FParamsFrame).Drawer := FDrawer;
end;
end;
if Value <> GLD_PARAMS_FRAME_NONE then
begin
FParamsFrame.Top := GB_ObjectType.Top + GB_ObjectType.Height + 10;
FParamsFrame.Parent := Self.SB_StandardObjects;
if Assigned(FDrawer) then FDrawer.IOFrame := FParamsFrame;
end;
end;
function GLDXParamsFrameType(AType: TGLDSysClassType): TGLDParamsFrameType;
begin
case AType of
GLD_SYSCLASS_BOX: Result := GLD_PARAMS_FRAME_BOX;
GLD_SYSCLASS_PYRAMID: Result := GLD_PARAMS_FRAME_PYRAMID;
GLD_SYSCLASS_CYLINDER: Result := GLD_PARAMS_FRAME_CYLINDER;
GLD_SYSCLASS_CONE: Result := GLD_PARAMS_FRAME_CONE;
GLD_SYSCLASS_TORUS: Result := GLD_PARAMS_FRAME_TORUS;
GLD_SYSCLASS_SPHERE: Result := GLD_PARAMS_FRAME_SPHERE;
GLD_SYSCLASS_TUBE: Result := GLD_PARAMS_FRAME_TUBE;
else Result := GLD_PARAMS_FRAME_NONE;
end;
end;
procedure Register;
begin
RegisterComponents('GLDraw', [TGLDStandardObjectsFrame]);
end;
end.
|
(*
Category: SWAG Title: POINTERS, LINKING, LISTS, TREES
Original name: 0026.PAS
Description: Sorting Linked Lists
Author: LEE BARKER
Date: 08-25-94 09:10
*)
{
│ I'm looking for a routine to swap two nodes in a double
│ linked list or a complete sort.
There has been a thread on the TP conf area in CIS on quick
sorting a (double) linked list. To swap two nodes, remove one,
then add it in where desired. Quick sample-
}
type
s5 = string[5];
ntp = ^nodetype;
nodetype = record
prv,nxt : ntp;
data : s5;
end;
const
nbr : array[0..9] of string[5] = ('ZERO','ONE','TWO',
'THREE','FOUR','FIVE','SIX','SEVEN','EIGHT','NINE');
var
node,root : ntp;
i : integer;
procedure swap (var n1,n2 : ntp);
var n : ntp;
begin
n := n1;
n1 := n2;
n2 := n;
end;
procedure addnode (var n1,n2 : ntp);
begin
swap(n1^.nxt,n2^.prv^.nxt);
swap(n1^.prv,n2^.prv);
end;
procedure getnode(i:integer);
var n : ntp;
begin
getmem(n,sizeof(nodetype));
n^.nxt := n;
n^.prv := n;
n^.data := nbr[i];
if root=nil
then root := n
else addnode(n,root);
end;
begin
root := nil;
for i := 0 to 9 do
begin
getnode(i);
node := root;
writeln;
writeln('The linked now is-');
repeat
writeln(node^.data);
node := node^.nxt;
until node = root;
end;
end.
|
{******************************************************************************}
{ }
{ Delphi OPENSSL Library }
{ Copyright (c) 2016 Luca Minuti }
{ https://bitbucket.org/lminuti/delphi-openssl }
{ }
{******************************************************************************}
{ }
{ 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 OpenSSL.Core;
interface
uses
System.SysUtils, OpenSSL.Api_11;
type
EOpenSSL = class(Exception);
EOpenSSLError = class(EOpenSSL)
private
FErrorCode: Integer;
public
constructor Create(AErrorCode: Integer; const AMessage: string);
property ErrorCode: Integer read FErrorCode;
end;
TOpenSSLBase = class(TObject)
public
constructor Create; virtual;
end;
function Base64Encode(const AData: Pointer;
const ASize: Integer): TBytes; overload;
function Base64Decode(const AData: Pointer;
const ASize: Integer): TBytes; overload;
function Base64Encode(const AData: TBytes): TBytes; overload;
function Base64Decode(const AData: TBytes): TBytes; overload;
function BytesToHex(const AData: TBytes; ALowerCase: Boolean = True): string;
function HexToBytes(const AData: Pointer; ASize: Integer): TBytes; overload;
function HexToBytes(const AData: string): TBytes; overload;
function BIO_flush(b: PBIO): Integer;
function BIO_get_mem_data(b: PBIO; pp: Pointer): Integer;
function BIO_get_mem_ptr(b: PBIO; pp: Pointer): Integer;
function BIO_to_string(b: PBIO; Encoding: TEncoding): string; overload;
function BIO_to_string(b: PBIO): string; overload;
function EVP_GetSalt: TBytes;
procedure EVP_GetKeyIV(const APassword: TBytes; ACipher: PEVP_CIPHER;
const ASalt: TBytes; out Key, IV: TBytes); overload;
{ Password will be encoded in UTF-8 if you want another encodig use the TBytes version }
procedure EVP_GetKeyIV(const APassword: string; ACipher: PEVP_CIPHER;
const ASalt: TBytes; out Key, IV: TBytes); overload;
function LastOpenSSLError: string;
procedure RaiseOpenSSLError(const AMessage: string = '');
implementation
function Base64Encode(const AData: Pointer; const ASize: Integer): TBytes;
const
BASE64_ENCODE: array[0..64] of Byte = (
// A..Z
$41, $42, $43, $44, $45, $46, $47, $48, $49, $4A, $4B, $4C, $4D,
$4E, $4F, $50, $51, $52, $53, $54, $55, $56, $57, $58, $59, $5A,
// a..z
$61, $62, $63, $64, $65, $66, $67, $68, $69, $6A, $6B, $6C, $6D,
$6E, $6F, $70, $71, $72, $73, $74, $75, $76, $77, $78, $79, $7A,
// 0..9
$30, $31, $32, $33, $34, $35, $36, $37, $38, $39,
// +, /, =
$2B, $2F, $3D
);
var
B: Byte;
B64: array [0..3] of Byte;
I, SrcIndex, DstIndex: Integer;
Src: PByte;
begin
if (AData = nil) or (ASize = 0) then
begin
Result := nil;
Exit;
end;
SetLength(Result, ((ASize + 2) div 3) * 4);
Src := AData;
SrcIndex := 0;
DstIndex := 0;
while (SrcIndex < ASize) do
begin
B := Src[SrcIndex];
Inc(SrcIndex);
B64[0] := B shr 2;
B64[1] := (B and $03) shl 4;
if (SrcIndex < ASize) then
begin
B := Src[SrcIndex];
Inc(SrcIndex);
B64[1] := B64[1] + (B shr 4);
B64[2] := (B and $0F) shl 2;
if (SrcIndex < ASize) then
begin
B := Src[SrcIndex];
Inc(SrcIndex);
B64[2] := B64[2] + (B shr 6);
B64[3] := B and $3F;
end
else
B64[3] := $40;
end
else
begin
B64[2] := $40;
B64[3] := $40;
end;
for I := 0 to 3 do
begin
Assert(B64[I] < Length(BASE64_ENCODE));
Assert(DstIndex < Length(Result));
Result[DstIndex] := BASE64_ENCODE[B64[I]];
Inc(DstIndex);
end;
end;
SetLength(Result, DstIndex);
end;
function Base64Encode(const AData: TBytes): TBytes;
begin
if Assigned(AData) then
Result := Base64Encode(@AData[0], Length(AData))
else Result := nil;
end;
function Base64Decode(const AData: Pointer; const ASize: Integer): TBytes;
const
BASE64_DECODE: array[0..255] of Byte = (
$FE, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF,
$FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF,
$FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $3E, $FF, $FF, $FF, $3F,
$34, $35, $36, $37, $38, $39, $3A, $3B, $3C, $3D, $FF, $FF, $FE, $FF, $FF, $FF,
$FF, $00, $01, $02, $03, $04, $05, $06, $07, $08, $09, $0A, $0B, $0C, $0D, $0E,
$0F, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $FF, $FF, $FF, $FF, $FF,
$FF, $1A, $1B, $1C, $1D, $1E, $1F, $20, $21, $22, $23, $24, $25, $26, $27, $28,
$29, $2A, $2B, $2C, $2D, $2E, $2F, $30, $31, $32, $33, $FF, $FF, $FF, $FF, $FF,
$FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF,
$FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF,
$FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF,
$FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF,
$FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF,
$FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF,
$FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF,
$FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF
);
var
B: Byte;
C: Cardinal;
Src: PByte;
SrcIndex, DstIndex, Count: Integer;
begin
if (AData = nil) or (ASize = 0) then
begin
Result := nil;
Exit;
end;
SetLength(Result, (ASize div 4) * 3 + 4);
Src := AData;
SrcIndex := 0;
DstIndex := 0;
C := 0;
Count := 4;
while (SrcIndex < ASize) do
begin
B := BASE64_DECODE[Src[SrcIndex]];
if (B = $FE) then
Break
else if (B <> $FF) then
begin
C := (C shl 6) or B;
Dec(Count);
if (Count = 0) then
begin
Result[DstIndex + 2] := Byte(C);
Result[DstIndex + 1] := Byte(C shr 8);
Result[DstIndex ] := Byte(C shr 16);
Inc(DstIndex, 3);
C := 0;
Count := 4;
end;
end;
Inc(SrcIndex);
end;
if (Count = 1) then
begin
Result[DstIndex + 1] := Byte(C shr 2);
Result[DstIndex ] := Byte(C shr 10);
Inc(DstIndex, 2);
end
else if (Count = 2) then
begin
Result[DstIndex] := Byte(C shr 4);
Inc(DstIndex);
end;
SetLength(Result, DstIndex);
end;
function Base64Decode(const AData: TBytes): TBytes;
begin
if Assigned(AData) then
Result := Base64Decode(@AData[0], Length(AData))
else Result := nil;
end;
function BufferToHex(const AData: Pointer; ASize: Integer; ALowerCase: Boolean): string;
type
PHexCharMap = ^THexCharMap;
THexCharMap = array[0..15] of Char;
const
HEXCHAR_MAPL: THexCharMap = (
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
);
HEXCHAR_MAPU: THexCharMap = (
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
);
var
pData: PByte;
pRet: PChar;
pMap: PHexCharMap;
begin
if ALowerCase then
pMap := @HEXCHAR_MAPL
else pMap := @HEXCHAR_MAPU;
pData := AData;
SetLength(Result, 2 * ASize);
pRet := PChar(Result);
while ASize > 0 do
begin
pRet^ := pMap[(pData^ and $F0) shr 4];
Inc(pRet);
pRet^ := pMap[pData^ and $0F];
Inc(pRet);
Dec(ASize);
Inc(pData);
end;
end;
function BytesToHex(const AData: TBytes; ALowerCase: Boolean): string;
begin
Result := BufferToHex(Pointer(AData), Length(AData), ALowerCase);
end;
function HexToBytes(const AData: Pointer; ASize: Integer): TBytes;
function HexByteToByte(B: Byte): Byte;
begin
case Chr(B) of
'0'..'9':
Result := Ord(B) - Ord('0');
'a'..'f':
Result := Ord(B) - Ord('a') + 10;
'A'..'F':
Result := Ord(B) - Ord('A') + 10;
else
begin
raise EConvertError.CreateFmt('HexToBytes: %d', [Ord(B)]);
end;
end;
end;
function HexWordToByte(W: Word): Byte;
var
B0, B1: Byte;
C: array[0..1] of Byte absolute W;
begin
B0 := HexByteToByte(C[0]);
B1 := HexByteToByte(C[1]);
Byte(Result) := B0 shl 4 + B1;
end;
var
nLen, nIndex: Integer;
pData: PWord;
begin
if ASize = 0 then
begin
Result := nil;
Exit;
end;
if ASize and 1 <> 0 then
raise EConvertError.Create('HexToBytes');
nLen := ASize shr 1;
SetLength(Result, nLen);
nIndex := 0;
pData := AData;
while nIndex < nLen do
begin
Result[nIndex] := HexWordToByte(pData^);
Inc(pData);
Inc(nIndex);
end;
end;
function HexToBytes(const AData: string): TBytes;
var
B: TBytes;
begin
B := TEncoding.Default.GetBytes(AData);
Result := HexToBytes(Pointer(B), Length(B));
end;
function BIO_flush(b: PBIO): Integer;
begin
Result := BIO_ctrl(b, BIO_CTRL_FLUSH, 0, nil);
end;
function BIO_get_mem_data(b: PBIO; pp: Pointer): Integer;
begin
Result := BIO_ctrl(b, BIO_CTRL_INFO, 0, pp);
end;
function BIO_get_mem_ptr(b: PBIO; pp: Pointer): Integer;
begin
Result := BIO_ctrl(b, BIO_C_GET_BUF_MEM_PTR, 0, pp);
end;
function BIO_to_string(b: PBIO; Encoding: TEncoding): string;
const
BuffSize = 1024;
var
Buffer: TBytes;
begin
Result := '';
SetLength(Buffer, BuffSize);
while BIO_read(b, buffer, BuffSize) > 0 do
begin
Result := Result + Encoding.GetString(Buffer);
end;
end;
function BIO_to_string(b: PBIO): string; overload;
begin
Result := BIO_to_string(b, TEncoding.ANSI);
end;
function EVP_GetSalt: TBytes;
begin
SetLength(result, PKCS5_SALT_LEN);
RAND_pseudo_bytes(@result[0], PKCS5_SALT_LEN);
end;
procedure EVP_GetKeyIV(const APassword: TBytes; ACipher: PEVP_CIPHER; const ASalt: TBytes;
out Key, IV: TBytes);
begin
SetLength(Key, EVP_MAX_KEY_LENGTH);
SetLength(iv, EVP_MAX_IV_LENGTH);
EVP_BytesToKey(ACipher, EVP_md5, @ASalt[0], @APassword[0], Length(APassword), 1, @Key[0], @IV[0]);
end;
procedure EVP_GetKeyIV(const APassword: string; ACipher: PEVP_CIPHER; const ASalt: TBytes;
out Key, IV: TBytes);
var
B: TBytes;
begin
B := TEncoding.UTF8.GetBytes(APassword);
EVP_GetKeyIV(B, ACipher, ASalt, Key, IV);
end;
function LastOpenSSLError: string;
var
ErrCode: Integer;
begin
ErrCode := ERR_get_error;
Result := SSL_error(ErrCode);
end;
procedure RaiseOpenSSLError(const AMessage: string);
var
ErrCode: Integer;
ErrMsg, FullMsg: string;
begin
ErrCode := ERR_get_error;
ErrMsg := SSL_error(ErrCode);
if AMessage = '' then
FullMsg := ErrMsg
else FullMsg := AMessage + ': ' + ErrMsg;
raise EOpenSSLError.Create(ErrCode, FullMsg);
end;
{ EOpenSSLError }
constructor EOpenSSLError.Create(AErrorCode: Integer; const AMessage: string);
begin
FErrorCode := AErrorCode;
inherited Create(AMessage);
end;
{ TOpenSSLBase }
constructor TOpenSSLBase.Create;
begin
inherited;
end;
end.
|
unit pangocairo;
interface
uses pangolib, cairolib, pangocairolib, cairo, pango, glib;
type
IPangoCairoFontMap = interface(IPangoFontMap) // todo ginterface
['{99B6172B-64C1-44E4-8030-AC30C08F6F1D}']
procedure SetDefault;
function GetFontType: TCairoFontType;
procedure SetResolution(dpi: double);
function GetResolution: Double;
property FontType: TCairoFontType read GetFontType;
property Resolution: Double read GetResolution write SetResolution;
end;
IPangoCairoFont = interface(IPangoFont)
['{B174B51D-EBBE-42AA-B6B8-4058931B8924}']
function GetScaledFont: ICairoScaledFont; cdecl;
property ScaledFont: ICairoScaledFont read GetScaledFont;
end;
TPangoCairoFontMap = class(TPangoFontMap, IPangoCairoFontMap)
protected
procedure SetDefault;
function GetFontType: TCairoFontType;
procedure SetResolution(dpi: double);
function GetResolution: Double;
public
constructor Create; virtual;
constructor CreateForFontType(fonttype: TCairoFontType);
constructor CreateDefault;
end;
IPangoCairoContext = interface(ICairoContext)
['{C58A313B-244F-4FC9-A713-DD39C11A76C0}']
procedure PangoUpdateContext(pc: IPangoContext);
procedure PangoUpdateLayout(layout: IPangoLayout);
procedure PangoShowErrorUnderline(x, y, width, height: double);
function PangoCreateContext: IPangoContext;
function PangoCreateLayout: IPangoLayout;
procedure PangoShowGlyphString(font: IPangoFont; glyphs: PPangoGlyphString);
procedure PangoShowGlyphItem(text: PAnsiChar; glyphItem: PPangoGlyphItem);
procedure PangoShowLayoutLine(line: PPangoLayoutLine);
procedure PangoShowLayout(layout: IPangoLayout);
procedure PangoGlyphStringPath(font: IPangoFont; glyphs: PPangoGlyphString);
procedure PangoLayoutLinePath(line: PPangoLayoutLine);
procedure PangoLayoutPath(layout: IPangoLayout);
procedure PangoErrorUnderlinePath(x, y, width, height: double);
end;
TPangoCairoFont = class(TPangoFont, IPangoCairoFont)
protected
function GetScaledFont: ICairoScaledFont; cdecl;
end;
TPangoCairoContext = class(TCairoContext, IPangoCairoContext)
protected
procedure PangoUpdateContext(pc: IPangoContext);
procedure PangoUpdateLayout(layout: IPangoLayout);
procedure PangoShowErrorUnderline(x, y, width, height: double);
function PangoCreateContext: IPangoContext;
function PangoCreateLayout: IPangoLayout;
procedure PangoShowGlyphString(font: IPangoFont; glyphs: PPangoGlyphString);
procedure PangoShowGlyphItem(text: PAnsiChar; glyphItem: PPangoGlyphItem);
procedure PangoShowLayoutLine(line: PPangoLayoutLine);
procedure PangoShowLayout(layout: IPangoLayout);
procedure PangoGlyphStringPath(font: IPangoFont; glyphs: PPangoGlyphString);
procedure PangoLayoutLinePath(line: PPangoLayoutLine);
procedure PangoLayoutPath(layout: IPangoLayout);
procedure PangoErrorUnderlinePath(x, y, width, height: double);
end;
implementation
{ TPangoCairoFontMap }
constructor TPangoCairoFontMap.Create;
begin
CreateInternal(pango_cairo_font_map_new);
end;
constructor TPangoCairoFontMap.CreateDefault;
begin
CreateInternal(g_object_ref(pango_cairo_font_map_get_default));
end;
constructor TPangoCairoFontMap.CreateForFontType(fonttype: TCairoFontType);
begin
CreateInternal(pango_cairo_font_map_new_for_font_type(fonttype));
end;
function TPangoCairoFontMap.GetFontType: TCairoFontType;
begin
Result := pango_cairo_font_map_get_font_type(GetHandle);
end;
function TPangoCairoFontMap.GetResolution: Double;
begin
Result := pango_cairo_font_map_get_resolution(GetHandle);
end;
procedure TPangoCairoFontMap.SetDefault;
begin
pango_cairo_font_map_set_default(GetHandle);
end;
procedure TPangoCairoFontMap.SetResolution(dpi: double);
begin
pango_cairo_font_map_set_resolution(GetHandle, dpi);
end;
{ TPangoCairoFont }
function TPangoCairoFont.GetScaledFont: ICairoScaledFont;
begin
Result := TCairoScaledFont.CreateInternal(pango_cairo_font_get_scaled_font(GetHandle));
end;
{ TPangoCairoContext }
function TPangoCairoContext.PangoCreateContext: IPangoContext;
begin
Result := TPangoContext.CreateInternal(pango_cairo_create_context(Context));
end;
function TPangoCairoContext.PangoCreateLayout: IPangoLayout;
begin
Result := TPangoLayout.CreateInternal(pango_cairo_create_layout(Context));
end;
procedure TPangoCairoContext.PangoErrorUnderlinePath(x, y, width,
height: double);
begin
pango_cairo_error_underline_path(Context, x, y, width, height);
end;
procedure TPangoCairoContext.PangoGlyphStringPath(font: IPangoFont;
glyphs: PPangoGlyphString);
begin
pango_cairo_glyph_string_path(Context, GObjectHandle(font), glyphs);
end;
procedure TPangoCairoContext.PangoLayoutLinePath(line: PPangoLayoutLine);
begin
pango_cairo_layout_line_path(Context, line);
end;
procedure TPangoCairoContext.PangoLayoutPath(layout: IPangoLayout);
begin
pango_cairo_layout_path(Context, GObjectHandle(layout));
end;
procedure TPangoCairoContext.PangoShowErrorUnderline(x, y, width,
height: double);
begin
pango_cairo_show_error_underline(Context, x, y, width, height);
end;
procedure TPangoCairoContext.PangoShowGlyphItem(text: PAnsiChar;
glyphItem: PPangoGlyphItem);
begin
pango_cairo_show_glyph_item(Context, text, glyphItem);
end;
procedure TPangoCairoContext.PangoShowGlyphString(font: IPangoFont;
glyphs: PPangoGlyphString);
begin
pango_cairo_show_glyph_string(Context, GObjectHandle(font), glyphs);
end;
procedure TPangoCairoContext.PangoShowLayout(layout: IPangoLayout);
begin
pango_cairo_show_layout(Context, GObjectHandle(layout));
end;
procedure TPangoCairoContext.PangoShowLayoutLine(line: PPangoLayoutLine);
begin
pango_cairo_show_layout_line(Context, line);
end;
procedure TPangoCairoContext.PangoUpdateLayout(layout: IPangoLayout);
begin
pango_cairo_update_layout(Context, GObjectHandle(layout));
end;
procedure TPangoCairoContext.PangoUpdateContext(pc: IPangoContext);
begin
pango_cairo_update_context(Context, GObjectHandle(pc));
end;
end. |
unit EqualsOpTest;
interface
uses
DUnitX.TestFramework,
uIntX;
type
[TestFixture]
TEqualsOpTest = class(TObject)
public
[Test]
procedure Equals2IntX();
[Test]
procedure EqualsZeroIntX();
[Test]
procedure EqualsIntIntX();
[Test]
procedure EqualsNullIntX();
[Test]
procedure Equals2IntXOp();
end;
implementation
[Test]
procedure TEqualsOpTest.Equals2IntX();
var
int1, int2: TIntX;
begin
int1 := TIntX.Create(8);
int2 := TIntX.Create(8);
Assert.IsTrue(int1.Equals(int2));
end;
[Test]
procedure TEqualsOpTest.EqualsZeroIntX();
begin
Assert.IsFalse(TIntX.Create(0) = 1);
end;
[Test]
procedure TEqualsOpTest.EqualsIntIntX();
var
int1: TIntX;
begin
int1 := TIntX.Create(8);
Assert.IsTrue(int1 = 8);
end;
[Test]
procedure TEqualsOpTest.EqualsNullIntX();
var
int1: TIntX;
begin
int1 := TIntX.Create(8);
Assert.IsFalse(int1 = Default (TIntX));
end;
[Test]
procedure TEqualsOpTest.Equals2IntXOp();
var
int1, int2: TIntX;
begin
int1 := TIntX.Create(8);
int2 := TIntX.Create(8);
Assert.IsTrue(int1 = int2);
end;
initialization
TDUnitX.RegisterTestFixture(TEqualsOpTest);
end.
|
unit NewFrontiers.GUI.PropertyChanged;
interface
type TPropertyChangedObject = class
protected
procedure propertyChanged(aPropertyname: string);
end;
implementation
uses NewFrontiers.GUI.Binding;
{ TPropertyChangedObject }
procedure TPropertyChangedObject.propertyChanged(aPropertyname: string);
begin
TBindingDictionary.getInstance.propertyChanged(self, aPropertyname);
end;
end.
|
{******************************************************************************}
{ }
{ Delphi JOSE Library }
{ Copyright (c) 2015-2017 Paolo Rossi }
{ https://github.com/paolo-rossi/delphi-jose-jwt }
{ }
{******************************************************************************}
{ }
{ 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 JOSE.Signing.RSA;
interface
uses
System.SysUtils,
IdGlobal,
IdCTypes,
IdSSLOpenSSLHeaders,
JOSE.Encoding.Base64;
const
PKCS1_SIGNATURE_PUBKEY:RawByteString = '-----BEGIN RSA PUBLIC KEY-----';
type
TRSAAlgorithm = (RS256, RS384, RS512);
TRSAAlgorithmHelper = record helper for TRSAAlgorithm
procedure FromString(const AValue: string);
function ToString: string;
end;
TRSA = class
private
class var FOpenSSLHandle: HMODULE;
class var _PEM_read_bio_RSA_PUBKEY: function(bp : PBIO; x : PPRSA; cb : ppem_password_cb; u: Pointer) : PRSA cdecl;
class var _EVP_MD_CTX_create: function: PEVP_MD_CTX cdecl;
class var _EVP_MD_CTX_destroy: procedure(ctx: PEVP_MD_CTX); cdecl;
class procedure LoadOpenSSL;
public
class function Sign(const AInput, AKey: TBytes; AAlg: TRSAAlgorithm): TBytes;
class function Verify(const AInput, ASignature, AKey: TBytes; AAlg: TRSAAlgorithm): Boolean;
class function VerifyPublicKey(const AKey: TBytes): Boolean;
class function VerifyPrivateKey(const AKey: TBytes): Boolean;
end;
implementation
uses
WinApi.Windows,
System.AnsiStrings;
// Get OpenSSL error and message text
function ERR_GetErrorMessage_OpenSSL : String;
var locErrMsg: array [0..160] of Char;
begin
ERR_error_string( ERR_get_error, @locErrMsg );
result := String( System.AnsiStrings.StrPas( PAnsiChar(@locErrMsg) ) );
end;
{ TRSAAlgorithmHelper }
procedure TRSAAlgorithmHelper.FromString(const AValue: string);
begin
if AValue = 'RS256' then
Self := RS256
else if AValue = 'RS384' then
Self := RS384
else if AValue = 'RS512' then
Self := RS512
else
raise Exception.Create('Invalid RSA algorithm type');
end;
function TRSAAlgorithmHelper.ToString: string;
begin
case Self of
RS256: Result := 'RS256';
RS384: Result := 'RS384';
RS512: Result := 'RS512';
end;
end;
{ TRSA }
class function TRSA.Sign(const AInput, AKey: TBytes;
AAlg: TRSAAlgorithm): TBytes;
var
PrivKeyBIO: pBIO;
PrivKey: pEVP_PKEY;
rsa: pRSA;
locCtx: PEVP_MD_CTX;
locSHA: PEVP_MD;
slen: Integer;
sig: Pointer;
begin
LoadOpenSSL;
// Load Private RSA Key into RSA object
PrivKeyBIO := BIO_new(BIO_s_mem);
try
BIO_write(PrivKeyBIO, @AKey[0], Length(AKey));
rsa := PEM_read_bio_RSAPrivateKey(PrivKeyBIO, nil, nil, nil);
if rsa = nil then
raise Exception.Create('[RSA] Unable to load private key: '+ERR_GetErrorMessage_OpenSSL);
finally
BIO_free(PrivKeyBIO);
end;
try
// Extract Private key from RSA object
PrivKey := EVP_PKEY_new();
if EVP_PKEY_set1_RSA(PrivKey, rsa) <> 1 then
raise Exception.Create('[RSA] Unable to extract private key: '+ERR_GetErrorMessage_OpenSSL);
try
case AAlg of
RS256: locSHA := EVP_sha256();
RS384: locSHA := EVP_sha384();
RS512: locSHA := EVP_sha512();
else
raise Exception.Create('[RSA] Unsupported signing algorithm!');
end;
locCtx := _EVP_MD_CTX_create;
try
if EVP_DigestSignInit( locCtx, NIL, locSHA, NIL, PrivKey ) <> 1 then
raise Exception.Create('[RSA] Unable to init context: '+ERR_GetErrorMessage_OpenSSL);
if EVP_DigestSignUpdate( locCtx, @AInput[0], Length(AInput) ) <> 1 then
raise Exception.Create('[RSA] Unable to update context with payload: '+ERR_GetErrorMessage_OpenSSL);
// Get signature, first read signature len
EVP_DigestSignFinal( locCtx, nil, @slen );
sig := OPENSSL_malloc(slen);
try
EVP_DigestSignFinal( locCtx, sig, @slen );
setLength(Result, slen);
move(sig^, Result[0], slen);
finally
CRYPTO_free(sig);
end;
finally
_EVP_MD_CTX_destroy(locCtx);
end;
finally
EVP_PKEY_free(PrivKey);
end;
finally
RSA_Free(rsa);
end;
end;
class function TRSA.Verify(const AInput, ASignature, AKey: TBytes;
AAlg: TRSAAlgorithm): Boolean;
var
PubKeyBIO: pBIO;
PubKey: pEVP_PKEY;
rsa: pRSA;
locCtx: PEVP_MD_CTX;
locSHA: PEVP_MD;
begin
LoadOpenSSL;
Result := False;
// Load Public RSA Key into RSA object
PubKeyBIO := BIO_new(BIO_s_mem);
try
BIO_write(PubKeyBIO, @AKey[0], Length(AKey));
if CompareMem(@PKCS1_SIGNATURE_PUBKEY[1], @AKey[0], length(PKCS1_SIGNATURE_PUBKEY)) then
rsa := PEM_read_bio_RSAPublicKey(PubKeyBIO, nil, nil, nil)
else
rsa := _PEM_read_bio_RSA_PUBKEY(PubKeyBIO, nil, nil, nil);
if rsa = nil then
raise Exception.Create('[RSA] Unable to load public key: '+ERR_GetErrorMessage_OpenSSL);
finally
BIO_free(PubKeyBIO);
end;
try
// Extract Public key from RSA object
PubKey := EVP_PKEY_new();
try
if EVP_PKEY_set1_RSA(PubKey,rsa) <> 1 then
raise Exception.Create('[RSA] Unable to extract public key: '+ERR_GetErrorMessage_OpenSSL);
case AAlg of
RS256: locSHA := EVP_sha256();
RS384: locSHA := EVP_sha384();
RS512: locSHA := EVP_sha512();
else
raise Exception.Create('[RSA] Unsupported signing algorithm!');
end;
locCtx := _EVP_MD_CTX_create;
try
if EVP_DigestVerifyInit( locCtx, NIL, locSHA, NIL, PubKey ) <> 1 then
raise Exception.Create('[RSA] Unable to init context: '+ERR_GetErrorMessage_OpenSSL);
if EVP_DigestVerifyUpdate( locCtx, @AInput[0], Length(AInput) ) <> 1 then
raise Exception.Create('[RSA] Unable to update context with payload: '+ERR_GetErrorMessage_OpenSSL);
result := ( EVP_DigestVerifyFinal( locCtx, PAnsiChar(@ASignature[0]), length(ASignature) ) = 1 );
finally
_EVP_MD_CTX_destroy(locCtx);
end;
finally
EVP_PKEY_free(PubKey);
end;
finally
RSA_Free(rsa);
end;
end;
class function TRSA.VerifyPrivateKey(const AKey: TBytes): Boolean;
var
PubKeyBIO: pBIO;
rsa: pRSA;
begin
LoadOpenSSL;
// Load Public RSA Key
PubKeyBIO := BIO_new(BIO_s_mem);
try
BIO_write(PubKeyBIO, @AKey[0], Length(AKey));
rsa := PEM_read_bio_RSAPrivateKey(PubKeyBIO, nil, nil, nil);
Result := (rsa <> nil);
if Result then
RSA_Free(rsa);
finally
BIO_free(PubKeyBIO);
end;
end;
class function TRSA.VerifyPublicKey(const AKey: TBytes): Boolean;
var
PubKeyBIO: pBIO;
rsa: pRSA;
begin
LoadOpenSSL;
// Load Public RSA Key
PubKeyBIO := BIO_new(BIO_s_mem);
try
BIO_write(PubKeyBIO, @AKey[0], Length(AKey));
if CompareMem(@PKCS1_SIGNATURE_PUBKEY[1], @AKey[0], length(PKCS1_SIGNATURE_PUBKEY)) then
rsa := PEM_read_bio_RSAPublicKey(PubKeyBIO, nil, nil, nil)
else
rsa := _PEM_read_bio_RSA_PUBKEY(PubKeyBIO, nil, nil, nil);
Result := (rsa <> nil);
if Result then
RSA_Free(rsa);
finally
BIO_free(PubKeyBIO);
end;
end;
class procedure TRSA.LoadOpenSSL;
begin
if FOpenSSLHandle = 0 then
begin
if not IdSSLOpenSSLHeaders.Load then
raise Exception.Create('[RSA] Unable to load OpenSSL DLLs');
if @EVP_DigestVerifyInit = nil then
raise Exception.Create('[RSA] Please, use OpenSSL 1.0.0. or newer!');
FOpenSSLHandle := LoadLibrary('libeay32.dll');
if FOpenSSLHandle = 0 then
raise Exception.Create('[RSA] Unable to load libeay32.dll!');
_PEM_read_bio_RSA_PUBKEY := GetProcAddress(FOpenSSLHandle, 'PEM_read_bio_RSA_PUBKEY');
if @_PEM_read_bio_RSA_PUBKEY = nil then
raise Exception.Create('[RSA] Unable to get proc address for ''PEM_read_bio_RSA_PUBKEY''');
_EVP_MD_CTX_create := GetProcAddress(FOpenSSLHandle, 'EVP_MD_CTX_create');
if @_EVP_MD_CTX_create = nil then
raise Exception.Create('[RSA] Unable to get proc address for ''EVP_MD_CTX_create''');
_EVP_MD_CTX_destroy := GetProcAddress(FOpenSSLHandle, 'EVP_MD_CTX_destroy');
if @_EVP_MD_CTX_create = nil then
raise Exception.Create('[RSA] Unable to get proc address for ''EVP_MD_CTX_destroy''');
end;
end;
initialization
TRSA.FOpenSSLHandle := 0;
TRSA._PEM_read_bio_RSA_PUBKEY := nil;
TRSA._EVP_MD_CTX_create := nil;
TRSA._EVP_MD_CTX_destroy := nil;
end.
|
Program readByLineAndChar;
VAR ch: CHAR;
line:STRING;
charsRead, charsWritten:LONGINT;
linesRead, linesWritten:LONGINT;
mode:(byChars, byLines);
BEGIN
mode:=byChars;
charsRead :=0;
charsWritten :=0;
linesRead:=0;
linesWritten:=0;
CASE mode OF
byChars: BEGIN
REPEAT
Read(input, ch);
charsRead:=charsRead+1;
Write(output, ch);
charsWritten:=charsWritten+1;
UNTIL Eof(input);
END;
byLines: BEGIN
REPEAT
ReadLn(input, line);
linesRead:=linesRead+1;
(*Filter remove Empty*)
IF Length(line) <> 0 THEN BEGIN
WriteLn(output, line);
linesWritten:=linesWritten+1;
END;
UNTIL Eof(input);
END;
END;
CASE mode OF
byChars:BEGIN
WriteLn('chars read = ', charsRead, ' chars Written = ', charsWritten,'.');
END;
byLines:BEGIN
WriteLn('lines read = ', linesRead, ' lines Written = ', linesWritten,'.');
END;
END;
END. |
unit StatusUpdaterThread;
interface
uses
System.Classes;
type
StatusUpdater = class(TThread)
private
{ Private declarations }
protected
procedure Execute; override;
end;
implementation
{
Important: Methods and properties of objects in visual components can only be
used in a method called using Synchronize, for example,
Synchronize(UpdateCaption);
and UpdateCaption could look like,
procedure StatusUpdater.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end;
or
Synchronize(
procedure
begin
Form1.Caption := 'Updated in thread via an anonymous method'
end
)
);
where an anonymous method is passed.
Similarly, the developer can call the Queue method with similar parameters as
above, instead passing another TThread class as the first parameter, putting
the calling thread in a queue with the other thread.
}
{ StatusUpdater }
uses MainForm, QueueForm;
procedure StatusUpdater.Execute;
begin
while 3>0 do
begin
if QueueForm.QueueRunning then Sleep(100) else Sleep(400);
Form1.StatusBar1.Panels[1].Text := MainForm.Status;
Form1.StatusBar1.Panels[0].Text := MainForm.LessStatus;
if (QueueForm.QueueRunning) or (MainForm.Processing) then
begin
Form1.StatusBar1.Panels[2].Text := '/';
Sleep(150);
Form1.StatusBar1.Panels[0].Text := MainForm.LessStatus + '.';
Form1.StatusBar1.Panels[2].Text := '|';
Sleep(150);
Form1.StatusBar1.Panels[0].Text := MainForm.LessStatus + '..';
Form1.StatusBar1.Panels[2].Text := '\';
Sleep(150);
Form1.StatusBar1.Panels[0].Text := MainForm.LessStatus + '...';
Form1.StatusBar1.Panels[2].Text := '–';
end else
Form1.StatusBar1.Panels[2].Text := 'S';
end;
end;
end.
|
unit Geometry;
interface
uses BattleField;
type
{ Represents a point or vector on a 2d plane }
Vector = record
x: double;
y: double;
end;
IntVector = record
x: integer;
y: integer;
end;
{ Represents a pair of poins, a line segment or a rectangle on a 2d plane }
Rect = record
p1: Vector;
p2: Vector;
end;
const
COLLISION_RADIUS: double = 0.60;
NOWHERE: IntVector = (x:10000; y:10000);
{ Vector functions }
function v(x, y: double) : Vector;
function fc(vec: IntVector) : Vector;
function fc(x, y: integer) : Vector;
function iv(x, y: integer) : IntVector;
function iv(vec: Vector) : IntVector;
function len(vec: Vector) : double;
{ Vector operators }
Operator - (a: Vector) v: Vector;
Operator = (a: Vector; b: Vector) v : boolean;
Operator + (a: Vector; b: Vector) v : Vector;
Operator - (a: Vector; b: Vector) v : Vector;
Operator * (a: Vector; b: double) v : Vector;
Operator * (a: double; b: Vector) v : Vector;
Operator + (a: IntVector; b: IntVector) v : IntVector;
Operator - (a: IntVector; b: IntVector) v : IntVector;
Operator = (a: IntVector; b: IntVector) v : Boolean;
{ Rect functions }
function r(a, b: Vector) : Rect;
procedure rect_normalize(var r: Rect);
{ Collision detection functions }
function dist(v1, v2: Vector) : double;
function distance_point_line(p: Vector; l: Rect) : double;
function point_in_rect(p: Vector; r: Rect) : Boolean;
function collision_point_segment(p: Vector; s: Rect; radius: double) : Boolean;
function collision_field_segment(vec: IntVector; s: Rect) : Boolean;
function first_collision(var f: BField; s: Rect) : IntVector;
implementation
uses math, Types, StaticConfig;
{ Creates a vector }
function v(x, y: double) : Vector;
begin
v.x := x;
v.y := y;
end;
{ Returns the centre point of field }
function fc(vec: IntVector) : Vector;
begin
fc := fc(vec.x, vec.y);
end;
{ Returns field's center }
function fc(x, y: integer) : Vector;
begin
fc := v(x * FIELD_WIDTH + 0.5 * FIELD_WIDTH, y * FIELD_HEIGHT + 0.5 * FIELD_HEIGHT);
end;
function iv(x, y: integer) : IntVector;
begin
iv.x := x;
iv.y := y;
end;
{ Converts floating-point coordinates to coordinates of a field }
function iv(vec: Vector) : IntVector;
begin
iv.x := trunc(vec.x / FIELD_WIDTH);
iv.y := trunc(vec.y / FIELD_HEIGHT);
end;
function len(vec: Vector) : double;
begin
len := sqrt(intpower(vec.x, 2) + intpower(vec.y, 2));
end;
{ Vector operators }
Operator - (a: Vector) v: Vector;
begin
v := a * (-1);
end;
Operator = (a: Vector; b: Vector) v : boolean;
begin
v := (trunc(a.x) = trunc(b.x)) and (trunc(a.y) = trunc(b.y));
end;
Operator + (a: Vector; b: Vector) v : Vector;
begin
v.x := a.x + b.x;
v.y := a.y + b.y;
end;
Operator - (a: Vector; b: Vector) v : Vector;
begin
v := a + (-b);
end;
Operator * (a: Vector; b: double) v : Vector;
begin
v.x := a.x * b;
v.y := a.y * b;
end;
Operator * (a: double; b: Vector) v : Vector;
begin
v := b * a;
end;
Operator + (a: IntVector; b: IntVector) v : IntVector;
begin
v.x := a.x + b.x;
v.y := a.y + b.y;
end;
Operator - (a: IntVector; b: IntVector) v : IntVector;
begin
v.x := a.x - b.x;
v.y := a.y - b.y;
end;
Operator = (a: IntVector; b: IntVector) v : Boolean;
begin
v := (a.x = b.x) and (a.y = b.y);
end;
{ Rect functions }
{ Creates a rect }
function r(a, b: Vector) : Rect;
begin
r.p1 := a;
r.p2 := b;
end;
procedure rect_normalize(var r: Rect);
var
x1, y1, x2, y2: double;
begin
x1 := min(r.p1.x, r.p2.x);
y1 := min(r.p1.y, r.p2.y);
x2 := max(r.p1.x, r.p2.x);
y2 := max(r.p1.y, r.p2.y);
r.p1 := v(x1, y1);
r.p2 := v(x2, y2);
end;
{ Collision detection }
function dist(v1, v2: Vector) : double;
begin
dist := len(v1 - v2);
end;
{ Counts the euclidean distance between a line and point on a 2d plane }
function distance_point_line(p: Vector; l: Rect) : double;
begin
distance_point_line :=
(l.p1.y - l.p2.y) * p.x +
(l.p2.x - l.p1.x) * p.y +
l.p1.x * l.p2.y - l.p2.x * l.p1.y;
distance_point_line := abs(distance_point_line);
distance_point_line := distance_point_line / dist(l.p1, l.p2);
end;
{ Checks if a point is inside of a rectangle }
function point_in_rect(p: Vector; r: Rect) : Boolean;
begin
rect_normalize(r);
point_in_rect :=
(r.p1.x <= p.x) and (p.x <= r.p2.x) and
(r.p1.y <= p.y) and (p.y <= r.p2.y);
end;
{ Checks if a point is at most at distance radius from a line segment }
function collision_point_segment(p: Vector; s: Rect; radius: double) : Boolean;
var
r: Rect;
begin
{ Check if the point lays in a sensible rectangle delimiting the segment }
r := s;
rect_normalize(r);
r.p1 := r.p1 - v(radius * FIELD_WIDTH, radius * FIELD_HEIGHT);
r.p2 := r.p2 + v(radius * FIELD_WIDTH, radius * FIELD_HEIGHT);
if not point_in_rect(p, r) then
begin
collision_point_segment := false;
exit;
end;
{ If the point is in the rectangle, it is sufficient to check the distance
to the line }
collision_point_segment := distance_point_line(p, s) < max(FIELD_HEIGHT, FIELD_WIDTH) * radius;
end;
{ Checks for intersection between a field and line segment }
function collision_field_segment(vec: IntVector; s: Rect) : Boolean;
begin
collision_field_segment := collision_point_segment(fc(vec), s, COLLISION_RADIUS);
end;
function first_collision(var f: BField; s: Rect) : IntVector;
var
r: Rect;
best: IntVector;
b, e: IntVector;
i, j: integer;
begin
r := s;
rect_normalize(r);
best := NOWHERE;
b := iv(r.p1);
e := iv(r.p2);
for j := max(b.y, 0) to min(e.y, f.height - 1) do
for i := max(b.x, 0) to min(e.x, f.width - 1) do
if (f.arr[i, j].hp <> 0) and
(dist(fc(i, j), s.p1) < dist(fc(best), s.p1)) and
collision_field_segment(iv(i, j), s) then
best := iv(i, j);
first_collision := best;
end;
begin
end.
|
(* ************************************************ *)
(* *)
(* Advanced Encryption Standard (AES) *)
(* Interface Unit v1.0 *)
(* *)
(* *)
(* Copyright (c) 2002 Jorlen Young *)
(* *)
(* *)
(* *)
(* Description: *)
(* *)
(* Based on ElASE.pas unit package *)
(* *)
(* This is the standard interface for an AES encryption algorithm. *)
(* Pass to functions EncryptString and DecryptString *)
(* It is easy to encrypt strings. *)
(* *)
(* Author: Yang Zehui 2004.12.03 *)
(* *)
(* ************************************************ *)
{ 2012.02.02 fixed by catgirlfighter for UNICODE strings }
//2019.08.14 Felipe: added modified encrypt/decrypt stream functions
unit AES;
{$I CatarinkaX.inc}
interface
uses
SysUtils, Classes, Math, ElAES;
type
TKeyBit = (kb128, kb192, kb256);
{ function StrToHex(Value: AnsiString): AnsiString;
function HexToStr(Value: AnsiString): AnsiString; }
function StreamToHex(f: TStream): String;
procedure HexToStream(s: string; f: TStream);
function EncryptString(Value: String; Key: String): String;
function DecryptString(Value: String; Key: String): String;
procedure EncryptStream(Stream, OutStrm: TStream; Key: string;
KeyBit: TKeyBit = kb256);
procedure DecryptStream(Stream, OutStrm: TStream; Key: string;
KeyBit: TKeyBit = kb256);
implementation
{ function StrToHex(Value: AnsiString): AnsiString;
var
I: Integer;
begin
Result := '';
for I := 1 to Length(Value) do
Result := Result + IntToHex(Ord(Value[I]), 2);
end;
function HexToStr(Value: AnsiString): AnsiString;
var
I: Integer;
begin
Result := '';
for I := 1 to Length(Value) do
begin
if ((I mod 2) = 1) then
Result := Result + Chr(StrToInt('0x'+ Copy(Value, I, 2)));
end;
end; }
function HexN(s: Char): Byte;
begin
Result := 0;
case s of
// '0': result := 0;
'1':
Result := 1;
'2':
Result := 2;
'3':
Result := 3;
'4':
Result := 4;
'5':
Result := 5;
'6':
Result := 6;
'7':
Result := 7;
'8':
Result := 8;
'9':
Result := 9;
'A':
Result := 10;
'B':
Result := 11;
'C':
Result := 12;
'D':
Result := 13;
'E':
Result := 14;
'F':
Result := 15;
end;
end;
function StreamToHex(f: TStream): String;
var
i: integer;
b: Byte;
begin
f.Position := 0;
Result := '';
for i := 0 to f.Size - 1 do
begin
f.ReadBuffer(b, 1);
Result := Result + IntToHex(b, 2);
end;
end;
procedure HexToStream(s: string; f: TStream);
var
i: integer;
n: Byte;
begin
s := UPPERCASE(s);
for i := 1 to length(s) do
if i mod 2 = 1 then
n := HexN(s[i]) * 16
else
begin
n := n + HexN(s[i]);
f.WriteBuffer(n, 1);
end;
end;
{ Value and Key length must be > 0 }
function EncryptString(Value: String; Key: String): String;
var
SS, DS: TStringStream;
AESKey: TAESKey256;
begin
Result := '';
SS := TStringStream.Create(Value);
DS := TStringStream.Create('');
try
// DS.WriteBuffer(Size, SizeOf(Size)); WTF???
FillChar(AESKey, SizeOf(AESKey), 0);
Move(PChar(Key)^, AESKey, Min(SizeOf(AESKey),
SizeOf(Key[1]) * length(Key)));
EncryptAESStreamECB(SS, 0, AESKey, DS);
Result := StreamToHex(DS);
finally
SS.Free;
DS.Free;
end;
end;
{ Value and Key length must be > 0 }
function DecryptString(Value: String; Key: String): String;
var
SS: TStringStream;
DS: TStringStream;
AESKey: TAESKey256;
begin
Result := '';
SS := TStringStream.Create('');
HexToStream(Value, SS);
DS := TStringStream.Create('');
try
// SS.ReadBuffer(Size, SizeOf(Size)); WTF???
FillChar(AESKey, SizeOf(AESKey), 0);
Move(PChar(Key)^, AESKey, Min(SizeOf(AESKey),
SizeOf(Key[1]) * length(Key)));
DecryptAESStreamECB(SS, 0 { SS.Size - SS.Position } , AESKey, DS);
Result := DS.DataString;
finally
SS.Free;
DS.Free;
end;
end;
{ -- Stream encryption function defaults to 256-bit key decryption -- }
procedure EncryptStream(Stream, OutStrm: TStream; Key: string;
KeyBit: TKeyBit = kb256);
var
Count: Int64;
AESKey128: TAESKey128;
AESKey192: TAESKey192;
AESKey256: TAESKey256;
begin
Stream.Position := 0;
Count := Stream.Size;
OutStrm.Write(Count, SizeOf(Count));
try
{ -- 128-bit key with a maximum length of 16 characters -- }
if KeyBit = kb128 then
begin
FillChar(AESKey128, SizeOf(AESKey128), 0 );
Move(PChar(Key)^, AESKey128, Min(SizeOf(AESKey128), Length(Key)));
EncryptAESStreamECB(Stream, 0, AESKey128, OutStrm);
end;
{ -- 192-bit key with a maximum length of 24 characters -- }
if KeyBit = kb192 then
begin
FillChar(AESKey192, SizeOf(AESKey192), 0 );
Move(PChar(Key)^, AESKey192, Min(SizeOf(AESKey192), Length(Key)));
EncryptAESStreamECB(Stream, 0, AESKey192, OutStrm);
end;
{ -- 256-bit key with a maximum length of 32 characters -- }
if KeyBit = kb256 then
begin
FillChar(AESKey256, SizeOf(AESKey256), 0 );
Move(PChar(Key)^, AESKey256, Min(SizeOf(AESKey256), Length(Key)));
EncryptAESStreamECB(Stream, 0, AESKey256, OutStrm);
end;
finally
end;
end;
{ -- Stream decryption function is decrypted by default with 256-bit key -- }
procedure DecryptStream(Stream, OutStrm: TStream; Key: string;
KeyBit: TKeyBit = kb256);
var
Count, OutPos: Int64;
AESKey128: TAESKey128;
AESKey192: TAESKey192;
AESKey256: TAESKey256;
begin
Stream.Position := 0;
OutPos :=OutStrm.Position;
Stream.ReadBuffer(Count, SizeOf(Count));
try
{ -- 128-bit key with a maximum length of 16 characters -- }
if KeyBit = kb128 then
begin
FillChar(AESKey128, SizeOf(AESKey128), 0 );
Move(PChar(Key)^, AESKey128, Min(SizeOf(AESKey128), Length(Key)));
DecryptAESStreamECB(Stream, Stream.Size - Stream.Position,
AESKey128, OutStrm);
end;
{ -- 192-bit key with a maximum length of 24 characters -- }
if KeyBit = kb192 then
begin
FillChar(AESKey192, SizeOf(AESKey192), 0 );
Move(PChar(Key)^, AESKey192, Min(SizeOf(AESKey192), Length(Key)));
DecryptAESStreamECB(Stream, Stream.Size - Stream.Position,
AESKey192, OutStrm);
end;
{ -- 256-bit key with a maximum length of 32 characters -- }
if KeyBit = kb256 then
begin
FillChar(AESKey256, SizeOf(AESKey256), 0 );
Move(PChar(Key)^, AESKey256, Min(SizeOf(AESKey256), Length(Key)));
DecryptAESStreamECB(Stream, Stream.Size - Stream.Position,
AESKey256, OutStrm);
end;
OutStrm.Size := OutPos + Count;
OutStrm.Position := OutPos;
finally
end;
end;
end.
|
unit UMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ActnList, UPostfix, StdCtrls;
type
TfrmMain = class(TForm)
alMain: TActionList;
processString: TAction;
editInput: TEdit;
btnConvert: TButton;
editResult: TEdit;
procedure FormCreate(Sender: TObject);
procedure processStringExecute(Sender: TObject);
procedure editInputKeyPress(Sender: TObject; var Key: Char);
private
resultString: String;
function getResult(inStr: String): String;
procedure redrawResult;
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
{$R *.dfm}
{ TfrmMain }
function TfrmMain.getResult(inStr: String): String;
var
rank: Integer;
begin
rank := calcRank(inStr);
if rank = 1 then
result := 'Полученная строка: ' + toPostfix(inStr) + ' её ранг равен 1'
else
result := 'Ошибка! Ранг исходной строки: ' + IntToStr(rank);
end;
procedure TfrmMain.redrawResult;
begin
editResult.Text := resultString;
end;
procedure TfrmMain.FormCreate(Sender: TObject);
begin
resultString := '';
end;
procedure TfrmMain.processStringExecute(Sender: TObject);
begin
if editInput.Text <> 'Введите строку' then
resultString := getResult(editInput.Text)
else
resultString := 'Ошибка! Введите строку';
redrawResult;
end;
procedure TfrmMain.editInputKeyPress(Sender: TObject; var Key: Char);
begin
if key = #13 then
begin
key := #0;
processStringExecute(Self);
end;
end;
end.
|
{Ingresar una matriz de N x M de enteros resolver mediante procedimientos o funciones los siguientes
puntos y mostrar el resultado:
(Maximo de filas y columnas:6).
a. Dado un número, calcular cuantas veces se repite (puede no estar).
b. Indicar cuántos elementos son nulos, positivos y negativos.
c. Intercambiar la fila K con la fila H (K y H menor o igual que N)}
Program Eje1;
Type
TM = array[1..6, 1..6] of integer;
Procedure LeerMatriz(Var Mat:TM; Var N,M:byte);
Var
i,j:byte;
begin
write('Ingrese la cantidad de filas (menor a 6): ');readln(N);
write('Ingrese la cantidad de columnas(menor a 6): ');readln(M);
For i:= 1 to N do
For j:= 1 to M do
begin
write('Ingrese un numero para fila y columna',i:3,j:3,' : ');readln(Mat[i,j]);
end;
end;
Procedure Imprime(Mat:TM; N,M:byte);
Var
i,j:byte;
begin
For i:= 1 to N do
begin
For j:= 1 to M do
write(Mat[i,j]:4);
writeln; // Al terminar la fila i, salta a la siguiente linea, esta es necesaria para que al imprimirla este bien de manera visual.
end;
end;
Function Repeticiones(Mat:TM; N,M:byte; Num:integer):byte; //Resuelve A.
Var
i,j,Cont:byte;
begin
Cont:= 0;
For i:= 1 to N do
For j:= 1 to M do
begin
If (Mat[i,j] = Num) then
Cont:= Cont + 1;
end;
Repeticiones:= Cont;
end;
Procedure CuentaPosNeg(Mat:TM; N,M:byte); //Resuelve B.
Var
i,j,ContP,ContN,Cont0:byte;
begin
ContP:= 0; //Contador para positivos.
ContN:= 0; //Contador para negativos.
Cont0:= 0; //Contador para nulos.
For i:= 1 to N do
For j:= 1 to M do
begin
If (Mat[i,j] > 0) then
ContP:= ContP + 1
Else
if (Mat[i,j] < 0) then
ContN:= ContN + 1
Else
Cont0:= Cont0 + 1;
end;
writeln('La cantidad de elementos positivos en la matriz son: ',ContP);
writeln('La cantidad de elementos negativos en la matriz son: ',ContN);
writeln('La cantidad de elementos nulos en la matriz son: ',Cont0);
end;
Procedure IntercambiarFilas(Var Mat:TM; N,M:byte);// Resuelve C
Var
j,K,H,aux:byte;
begin
write('Ingrese una de las filas a intercambiar: ');readln(K);
write('Ingrese la otra fila para intercambiar: ');readln(H);
For j:= 1 to M do
begin
If (K <= N) and (H <= N) then
begin
aux:= Mat[K,j];
Mat[K,j]:= Mat[H,j];
Mat[H,j]:= aux;
end;
end;
end;
Var
Mat:TM;
N,M,Aux:byte;
Num:integer;
Begin
LeerMatriz(Mat,N,M);
writeln;
writeln('Matriz');
Imprime(Mat,N,M);
writeln;
CuentaPosNeg(Mat,N,M);
writeln;
write('Ingrese un numero para saber si esta: ');readln(Num);
Aux:= Repeticiones(Mat,N,M,Num);
If (Aux = 0) then
writeln('El numero ingresado no esta en la matriz')
Else
writeln('La cantidad de veces que ',Num,' se repite son: ',Aux);
writeln;
IntercambiarFilas(Mat,N,M);
writeln;
writeln('Matriz con filas intercambiadas');
Imprime(Mat,N,M);
end.
|
unit GridController;
interface
uses
Generics.Collections, FMX.Grid;
type
TGridFillRow<T> = reference to procedure(Obj: T; Cols: TArray<string>);
TGridController<T: class> = class
private
FGrid: TStringGrid;
FItems: TList<T>;
FFillRow: TGridFillRow<T>;
procedure FillGrid;
function GetSelected: T;
public
constructor Create(AGrid: TStringGrid; AItems: TList<T>; AFillRow: TGridFillRow<T>);
destructor Destroy; override;
property Selected: T read GetSelected;
end;
implementation
{ TGridController<T> }
constructor TGridController<T>.Create(AGrid: TStringGrid; AItems: TList<T>; AFillRow: TGridFillRow<T>);
begin
FGrid := AGrid;
FItems := AItems;
FFillRow := AFillRow;
FillGrid;
end;
destructor TGridController<T>.Destroy;
begin
FItems.Free;
inherited;
end;
procedure TGridController<T>.FillGrid;
var
Item: T;
I, J: Integer;
Cols: TArray<string>;
begin
for I := 0 to FGrid.RowCount - 1 do
for J := 0 to FGrid.ColumnCount - 1 do
FGrid.Cells[J, I] := '';
FGrid.RowCount := 1;
if FItems.Count > 0 then
begin
FGrid.RowCount := FItems.Count;
for I := 0 to FItems.Count - 1 do
begin
Item := FItems[I];
SetLength(Cols, FGrid.ColumnCount);
FFillRow(Item, Cols);
for J := 0 to FGrid.ColumnCount - 1 do
FGrid.Cells[J, I] := Cols[J];
end;
end;
end;
function TGridController<T>.GetSelected: T;
begin
if FGrid.Selected < 0 then Exit(nil);
Result := FItems[FGrid.Selected];
// Result := T(FGrid.Columns[0].CellControlByRow(FGrid.Selected).Tag);
end;
end.
|
(*----------------------------------------------------------------------------*
* Direct3D sample from DirectX 9.0 SDK December 2006 *
* Delphi adaptation by Alexey Barkovoy (e-mail: directx@clootie.ru) *
* *
* Supported compilers: Delphi 5,6,7,9; FreePascal 2.0 *
* *
* Latest version can be downloaded from: *
* http://www.clootie.ru *
* http://sourceforge.net/projects/delphi-dx9sdk *
*----------------------------------------------------------------------------*
* $Id: SkinnedMeshUnit.pas,v 1.17 2007/02/05 22:21:13 clootie Exp $
*----------------------------------------------------------------------------*)
//--------------------------------------------------------------------------------------
// File: SkinnedMesh.cpp
//
// Starting point for new Direct3D applications
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
{$I DirectX.inc}
unit SkinnedMeshUnit;
interface
uses
Windows, SysUtils, Math,
DXTypes, Direct3D9, D3DX9, dxerr9, StrSafe,
DXUT, DXUTcore, DXUTenum, DXUTmisc, DXUTgui, DXUTSettingsDlg;
{.$DEFINE DEBUG_VS} // Uncomment this line to debug vertex shaders
{.$DEFINE DEBUG_PS} // Uncomment this line to debug pixel shaders
const
MESHFILENAME = 'tiny\tiny.x';
UINT_MAX = High(LongWord);
const
g_wszShaderSource: array[0..3] of PWideChar =
(
'skinmesh1.vsh',
'skinmesh2.vsh',
'skinmesh3.vsh',
'skinmesh4.vsh'
);
type
// enum for various skinning modes possible
TMethod =
(
D3DNONINDEXED,
D3DINDEXED,
SOFTWARE,
D3DINDEXEDVS,
D3DINDEXEDHLSLVS,
NONE
);
//--------------------------------------------------------------------------------------
// Name: struct D3DXFRAME_DERIVED
// Desc: Structure derived from D3DXFRAME so we can add some app-specific
// info that will be stored with each frame
//--------------------------------------------------------------------------------------
PD3DXFrameDerived = ^TD3DXFrameDerived;
TD3DXFrameDerived = packed record
Name: PAnsiChar;
TransformationMatrix: TD3DXMatrix;
pMeshContainer: PD3DXMeshContainer;
pFrameSibling: PD3DXFrame;
pFrameFirstChild: PD3DXFrame;
////////////////////////////////////////////
CombinedTransformationMatrix: TD3DXMatrixA16;
end;
PD3DXMaterialArray = ^TD3DXMaterialArray;
TD3DXMaterialArray = array[0..MaxInt div SizeOf(TD3DXMaterial) - 1] of TD3DXMaterial;
PIDirect3DTexture9Array = ^TIDirect3DTexture9Array;
TIDirect3DTexture9Array = array[0..MaxInt div SizeOf(IDirect3DTexture9) - 1] of IDirect3DTexture9;
PD3DXMatrixPointerArray = ^TD3DXMatrixPointerArray;
TD3DXMatrixPointerArray = array[0..MaxInt div SizeOf(Pointer) - 1] of PD3DXMatrix;
PD3DXMatrixArray = ^TD3DXMatrixArray;
TD3DXMatrixArray = array[0..MaxInt div SizeOf(TD3DXMatrix) - 1] of TD3DXMatrix;
PD3DXAttributeRangeArray = ^TD3DXAttributeRangeArray;
TD3DXAttributeRangeArray = array[0..MaxInt div SizeOf(TD3DXAttributeRange) - 1] of TD3DXAttributeRange;
//--------------------------------------------------------------------------------------
// Name: struct D3DXMESHCONTAINER_DERIVED
// Desc: Structure derived from D3DXMESHCONTAINER so we can add some app-specific
// info that will be stored with each mesh
//--------------------------------------------------------------------------------------
PD3DXMeshContainerDerived = ^TD3DXMeshContainerDerived;
TD3DXMeshContainerDerived = packed record { public D3DXMESHCONTAINER }
Name: PAnsiChar;
MeshData: TD3DXMeshData;
pMaterials: PD3DXMaterialArray;
pEffects: PD3DXEffectInstance;
NumMaterials: DWORD;
pAdjacency: PDWORD;
pSkinInfo: ID3DXSkinInfo;
pNextMeshContainer: PD3DXMeshContainer;
////////////////////////////////////////////
ppTextures: PIDirect3DTexture9Array; // array of textures, entries are NULL if no texture specified
// SkinMesh info
pOrigMesh: ID3DXMesh;
pAttributeTable: array of TD3DXAttributeRange;
NumAttributeGroups: DWORD;
NumInfl: DWORD;
pBoneCombinationBuf:ID3DXBuffer;
ppBoneMatrixPtrs: PD3DXMatrixPointerArray;
pBoneOffsetMatrices:PD3DXMatrixArray;
NumPaletteEntries: DWORD;
UseSoftwareVP: Boolean;
iAttributeSW: DWORD; // used to denote the split between SW and HW if necessary for non-indexed skinning
end;
//--------------------------------------------------------------------------------------
// Name: class CAllocateHierarchy
// Desc: Custom version of ID3DXAllocateHierarchy with custom methods to create
// frames and meshcontainers.
//--------------------------------------------------------------------------------------
CAllocateHierarchy = class(ID3DXAllocateHierarchy)
public
function CreateFrame(Name: PAnsiChar; out ppNewFrame: PD3DXFrame): HResult; override;
function CreateMeshContainer(Name: PAnsiChar; const pMeshData: TD3DXMeshData;
pMaterials: PD3DXMaterial; pEffectInstances: PD3DXEffectInstance;
NumMaterials: DWORD; pAdjacency: PDWORD; pSkinInfo: ID3DXSkinInfo;
out ppMeshContainerOut: PD3DXMeshContainer): HResult; override;
function DestroyFrame(pFrameToFree: PD3DXFrame): HResult; override;
function DestroyMeshContainer(pMeshContainerToFree: PD3DXMeshContainer): HResult; override;
public
// constructor Create;
end;
//--------------------------------------------------------------------------------------
// Global variables
//--------------------------------------------------------------------------------------
var
g_pFont: ID3DXFont; // Font for drawing text
g_pTextSprite: ID3DXSprite; // Sprite for batching draw text calls
g_pEffect: ID3DXEffect; // D3DX effect interface
g_ArcBall: CD3DArcBall; // Arcball for model control
g_bShowHelp: Boolean = True; // If true, it renders the UI control text
g_DialogResourceManager: CDXUTDialogResourceManager; // manager for shared resources of dialogs
g_SettingsDlg: CD3DSettingsDlg; // Device settings dialog
g_HUD: CDXUTDialog; // dialog for standard controls
g_SampleUI: CDXUTDialog; // dialog for sample specific controls
g_pFrameRoot: PD3DXFrame;
g_pAnimController: ID3DXAnimationController;
g_vObjectCenter: TD3DXVector3; // Center of bounding sphere of object
g_fObjectRadius: Single; // Radius of bounding sphere of object
g_SkinningMethod: TMethod = D3DNONINDEXED; // Current skinning method
g_pBoneMatrices: array of TD3DXMatrixA16;
g_NumBoneMatricesMax: LongWord = 0;
g_pIndexedVertexShader: array[0..3] of IDirect3DVertexShader9;
g_matView: TD3DXMatrixA16; // View matrix
g_matProj: TD3DXMatrixA16; // Projection matrix
g_matProjT: TD3DXMatrixA16; // Transpose of projection matrix (for asm shader)
g_dwBehaviorFlags: DWORD; // Behavior flags of the 3D device
g_bUseSoftwareVP: Boolean; // Flag to indicate whether software vp is
// required due to lack of hardware
//--------------------------------------------------------------------------------------
// UI control IDs
//--------------------------------------------------------------------------------------
const
IDC_TOGGLEFULLSCREEN = 1;
IDC_TOGGLEREF = 3;
IDC_CHANGEDEVICE = 4;
IDC_METHOD = 5;
//--------------------------------------------------------------------------------------
// Forward declarations
//--------------------------------------------------------------------------------------
function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall;
function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall;
function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall;
procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall;
procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall;
procedure OnLostDevice(pUserContext: Pointer); stdcall;
procedure OnDestroyDevice(pUserContext: Pointer); stdcall;
procedure InitApp;
//HRESULT LoadMesh( IDirect3DDevice9* pd3dDevice, WCHAR* strFileName, ID3DXMesh** ppMesh );
procedure RenderText;
procedure DrawMeshContainer(const pd3dDevice: IDirect3DDevice9; pMeshContainerBase: PD3DXMeshContainer; pFrameBase: PD3DXFrame);
procedure DrawFrame(const pd3dDevice: IDirect3DDevice9; pFrame: PD3DXFrame);
function SetupBoneMatrixPointersOnMesh(pMeshContainerBase: PD3DXMeshContainer): HRESULT;
function SetupBoneMatrixPointers(pFrame: PD3DXFrame): HRESULT;
procedure UpdateFrameMatrices(pFrameBase: PD3DXFrame; pParentMatrix: PD3DXMatrix);
procedure UpdateSkinningMethod(pFrameBase: PD3DXFrame);
function GenerateSkinnedMesh(const pd3dDevice: IDirect3DDevice9; pMeshContainer: PD3DXMeshContainerDerived): HRESULT;
procedure ReleaseAttributeTable(pFrameBase: PD3DXFrame);
procedure CreateCustomDXUTobjects;
procedure DestroyCustomDXUTobjects;
implementation
//--------------------------------------------------------------------------------------
// Name: AllocateName()
// Desc: Allocates memory for a string to hold the name of a frame or mesh
//--------------------------------------------------------------------------------------
//Clootie: AllocateName == StrNew in Delphi
(*HRESULT AllocateName( LPCSTR Name, LPSTR *pNewName )
{
UINT cbLength;
if( Name != NULL )
{
cbLength = (UINT)strlen(Name) + 1;
*pNewName = new CHAR[cbLength];
if (*pNewName == NULL)
return E_OUTOFMEMORY;
memcpy( *pNewName, Name, cbLength*sizeof(CHAR) );
}
else
{
*pNewName = NULL;
}
return S_OK;
}*)
//--------------------------------------------------------------------------------------
// Name: CAllocateHierarchy::CreateFrame()
// Desc:
//--------------------------------------------------------------------------------------
function CAllocateHierarchy.CreateFrame(Name: PAnsiChar;
out ppNewFrame: PD3DXFrame): HResult;
var
pFrame: PD3DXFrameDerived;
begin
Result := S_OK;
// Start clean
ppNewFrame := nil;
// Create a new frame
New(pFrame); // {PD3DXFrameDerived}
try try
// Clear the new frame
ZeroMemory(pFrame, SizeOf(TD3DXFrameDerived));
// Duplicate the name string
pFrame.Name:= StrNew(Name);
// Initialize other data members of the frame
D3DXMatrixIdentity(pFrame.TransformationMatrix);
D3DXMatrixIdentity(pFrame.CombinedTransformationMatrix);
ppNewFrame := PD3DXFrame(pFrame);
pFrame := nil;
except
on EOutOfMemory do Result:= E_OUTOFMEMORY;
else raise;
end;
finally
Dispose(pFrame);
end;
end;
//--------------------------------------------------------------------------------------
// Name: CAllocateHierarchy::CreateMeshContainer()
// Desc:
//--------------------------------------------------------------------------------------
function CAllocateHierarchy.CreateMeshContainer(Name: PAnsiChar;
const pMeshData: TD3DXMeshData; pMaterials: PD3DXMaterial;
pEffectInstances: PD3DXEffectInstance; NumMaterials: DWORD;
pAdjacency: PDWORD; pSkinInfo: ID3DXSkinInfo;
out ppMeshContainerOut: PD3DXMeshContainer): HResult;
var
pNewMeshContainer: PD3DXMeshContainerDerived;
pNewBoneOffsetMatrices: PD3DXMatrixArray;
pd3dDevice: IDirect3DDevice9;
pMesh: ID3DXMesh;
NumFaces: LongWord;
iMaterial: Integer;
NumBones: DWORD;
iBone: Integer;
strTexturePath: array[0..MAX_PATH-1] of WideChar;
wszBuf: array[0..MAX_PATH-1] of WideChar;
begin
pNewMeshContainer := nil;
pNewBoneOffsetMatrices := nil;
// Start clean
ppMeshContainerOut := nil;
Result:= E_FAIL;
try try
// This sample does not handle patch meshes, so fail when one is found
if (pMeshData._Type <> D3DXMESHTYPE_MESH) then Exit;
// Get the pMesh interface pointer out of the mesh data structure
pMesh := pMeshData.pMesh as ID3DXMesh;
// this sample does not FVF compatible meshes, so fail when one is found
if (pMesh.GetFVF = 0) then Exit;
// Allocate the overloaded structure to return as a D3DXMESHCONTAINER
New(pNewMeshContainer); // = new D3DXMESHCONTAINER_DERIVED;
// Clear the new mesh container
FillChar(pNewMeshContainer^, 0, SizeOf(TD3DXMeshContainerDerived));
//---------------------------------
// Name
//---------------------------------
// Copy the name. All memory as input belongs to caller, interfaces can be addref'd though
pNewMeshContainer.Name := StrNew(Name);
//---------------------------------
// MeshData
//---------------------------------
// Get the device
Result := pMesh.GetDevice(pd3dDevice);
if FAILED(Result) then Exit;
NumFaces := pMesh.GetNumFaces;
// if no normals are in the mesh, add them
if (pMesh.GetFVF and D3DFVF_NORMAL = 0) then
begin
pNewMeshContainer.MeshData._Type := D3DXMESHTYPE_MESH;
// clone the mesh to make room for the normals
Result := pMesh.CloneMeshFVF(pMesh.GetOptions,
pMesh.GetFVF or D3DFVF_NORMAL,
pd3dDevice, ID3DXMesh(pNewMeshContainer.MeshData.pMesh));
if FAILED(Result) then Exit;
// get the new pMesh pointer back out of the mesh container to use
// NOTE: we do not release pMesh because we do not have a reference to it yet
pMesh := pNewMeshContainer.MeshData.pMesh as ID3DXMesh;
// now generate the normals for the pmesh
D3DXComputeNormals(pMesh, nil);
end
else // if no normals, just add a reference to the mesh for the mesh container
begin
pNewMeshContainer.MeshData.pMesh := pMesh;
pNewMeshContainer.MeshData._Type := D3DXMESHTYPE_MESH;
end;
//---------------------------------
// allocate memory to contain the material information. This sample uses
// the D3D9 materials and texture names instead of the EffectInstance style materials
pNewMeshContainer.NumMaterials := max(1, NumMaterials);
GetMem(pNewMeshContainer.pMaterials, SizeOf(TD3DXMaterial)*pNewMeshContainer.NumMaterials);
GetMem(pNewMeshContainer.ppTextures, SizeOf(IDirect3DTexture9)*pNewMeshContainer.NumMaterials);
//---------------------------------
// Adjacency
//---------------------------------
GetMem(pNewMeshContainer.pAdjacency, SizeOf(DWORD)*NumFaces*3);
CopyMemory(pNewMeshContainer.pAdjacency, pAdjacency, SizeOf(DWORD) * NumFaces*3);
ZeroMemory(pNewMeshContainer.ppTextures, SizeOf(IDirect3DTexture9) * pNewMeshContainer.NumMaterials);
// if materials provided, copy them
if (NumMaterials > 0) then
begin
CopyMemory(pNewMeshContainer.pMaterials, pMaterials, SizeOf(TD3DXMaterial) * NumMaterials);
for iMaterial := 0 to NumMaterials - 1 do
begin
if (pNewMeshContainer.pMaterials[iMaterial].pTextureFilename <> nil) then
begin
MultiByteToWideChar(CP_ACP, 0, pNewMeshContainer.pMaterials[iMaterial].pTextureFilename, -1, wszBuf, MAX_PATH);
wszBuf[MAX_PATH - 1] := #0;
DXUTFindDXSDKMediaFile(strTexturePath, MAX_PATH, wszBuf);
if FAILED(D3DXCreateTextureFromFileW(pd3dDevice, strTexturePath,
pNewMeshContainer.ppTextures[iMaterial]))
then pNewMeshContainer.ppTextures[iMaterial] := nil;
// don't remember a pointer into the dynamic memory, just forget the name after loading
pNewMeshContainer.pMaterials[iMaterial].pTextureFilename := nil;
end;
end;
end
else // if no materials provided, use a default one
begin
pNewMeshContainer.pMaterials[0].pTextureFilename := nil;
ZeroMemory(@pNewMeshContainer.pMaterials[0].MatD3D, SizeOf(TD3DMaterial9));
pNewMeshContainer.pMaterials[0].MatD3D.Diffuse.r := 0.5;
pNewMeshContainer.pMaterials[0].MatD3D.Diffuse.g := 0.5;
pNewMeshContainer.pMaterials[0].MatD3D.Diffuse.b := 0.5;
pNewMeshContainer.pMaterials[0].MatD3D.Specular := pNewMeshContainer.pMaterials[0].MatD3D.Diffuse;
end;
//---------------------------------
// SkinInfo
//---------------------------------
// if there is skinning information, save off the required data and then setup for HW skinning
if (pSkinInfo <> nil) then
begin
// first save off the SkinInfo and original mesh data
pNewMeshContainer.pSkinInfo := pSkinInfo;
pNewMeshContainer.pOrigMesh := pMesh;
// Will need an array of offset matrices to move the vertices from the figure space to the
// bone's space
NumBones := pSkinInfo.GetNumBones;
GetMem(pNewBoneOffsetMatrices, SizeOf(TD3DXMatrix)*NumBones);
// Get each of the bone offset matrices so that we don't need to get them later
for iBone := 0 to NumBones - 1 do
begin
pNewBoneOffsetMatrices[iBone] := pSkinInfo.GetBoneOffsetMatrix(iBone)^;
end;
// Copy the pointer
pNewMeshContainer.pBoneOffsetMatrices := pNewBoneOffsetMatrices;
pNewBoneOffsetMatrices := nil;
// GenerateSkinnedMesh will take the general skinning information and transform it to a
// HW friendly version
Result := GenerateSkinnedMesh(pd3dDevice, pNewMeshContainer);
if FAILED(Result) then Exit;
end;
// Copy the mesh container and return
ppMeshContainerOut := PD3DXMeshContainer(pNewMeshContainer);
pNewMeshContainer := nil;
Result := S_OK;
except
on EOutOfMemory do Result:= E_OUTOFMEMORY;
else raise;
end;
finally
FreeMem(pNewBoneOffsetMatrices);
pd3dDevice := nil;
// Call Destroy function to properly clean up the memory allocated
if (pNewMeshContainer <> nil) then DestroyMeshContainer(PD3DXMeshContainer(pNewMeshContainer));
end;
end;
//--------------------------------------------------------------------------------------
// Name: CAllocateHierarchy::DestroyFrame()
// Desc:
//--------------------------------------------------------------------------------------
function CAllocateHierarchy.DestroyFrame(pFrameToFree: PD3DXFrame): HResult;
begin
StrDispose(pFrameToFree.Name);
Dispose(pFrameToFree);
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// Name: CAllocateHierarchy::DestroyMeshContainer()
// Desc:
//--------------------------------------------------------------------------------------
function CAllocateHierarchy.DestroyMeshContainer(pMeshContainerToFree: PD3DXMeshContainer): HResult;
var
iMaterial: LongWord;
pMeshContainer: PD3DXMeshContainerDerived;
begin
pMeshContainer := PD3DXMeshContainerDerived(pMeshContainerToFree);
StrDispose(pMeshContainer.Name);
FreeMem(pMeshContainer.pAdjacency);
FreeMem(pMeshContainer.pMaterials);
FreeMem(pMeshContainer.pBoneOffsetMatrices);
// release all the allocated textures
if (pMeshContainer.ppTextures <> nil) then
for iMaterial := 0 to pMeshContainer.NumMaterials - 1 do
pMeshContainer.ppTextures[iMaterial] := nil;
FreeMem(pMeshContainer.ppTextures);
FreeMem(pMeshContainer.ppBoneMatrixPtrs);
SAFE_RELEASE(pMeshContainer.pBoneCombinationBuf);
SAFE_RELEASE(pMeshContainer.MeshData.pMesh);
SAFE_RELEASE(pMeshContainer.pSkinInfo);
SAFE_RELEASE(pMeshContainer.pOrigMesh);
Dispose(pMeshContainer);
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// Initialize the app
//--------------------------------------------------------------------------------------
procedure InitApp;
var
iY: Integer;
begin
// Initialize dialogs
g_SettingsDlg.Init(g_DialogResourceManager);
g_HUD.Init(g_DialogResourceManager);
g_SampleUI.Init(g_DialogResourceManager);
g_HUD.SetCallback(OnGUIEvent);
iY := 10; g_HUD.AddButton(IDC_TOGGLEFULLSCREEN, 'Toggle full screen', 35, iY, 125, 22);
Inc(iY, 24); g_HUD.AddButton(IDC_TOGGLEREF, 'Toggle REF (F3)', 35, iY, 125, 22);
Inc(iY, 24); g_HUD.AddButton(IDC_CHANGEDEVICE, 'Change device (F2)', 35, iY, 125, 22, VK_F2);
// Add mixed vp to the available vp choices in device settings dialog.
DXUTGetEnumeration.SetPossibleVertexProcessingList(True, False, False, True);
g_SampleUI.SetCallback(OnGUIEvent); iY := 10;
g_SampleUI.AddComboBox(IDC_METHOD, 0, iY, 230, 24, Ord('S'));
g_SampleUI.GetComboBox(IDC_METHOD).AddItem('Fixed function non-indexed (s)kinning', Pointer(D3DNONINDEXED));
g_SampleUI.GetComboBox(IDC_METHOD).AddItem('Fixed function indexed (s)kinning', Pointer(D3DINDEXED));
g_SampleUI.GetComboBox(IDC_METHOD).AddItem('Software (s)kinning', Pointer(SOFTWARE));
g_SampleUI.GetComboBox(IDC_METHOD).AddItem('ASM shader indexed (s)kinning', Pointer(D3DINDEXEDVS));
g_SampleUI.GetComboBox(IDC_METHOD).AddItem('HLSL shader indexed (s)kinning', Pointer(D3DINDEXEDHLSLVS));
// Supports all types of vertex processing, including mixed.
DXUTGetEnumeration.SetPossibleVertexProcessingList(True, True, True, True);
end;
//--------------------------------------------------------------------------------------
// Called during device initialization, this code checks the device for some
// minimum set of capabilities, and rejects those that don't pass by returning false.
//--------------------------------------------------------------------------------------
function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall;
var
pD3D: IDirect3D9;
begin
Result := False;
// Skip backbuffer formats that don't support alpha blending
pD3D := DXUTGetD3DObject;
if FAILED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType,
AdapterFormat, D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING,
D3DRTYPE_TEXTURE, BackBufferFormat))
then Exit;
// No fallback defined by this app, so reject any device that
// doesn't support at least ps2.0
if (pCaps.PixelShaderVersion < D3DPS_VERSION(2,0)) then Exit;
Result := True;
end;
//--------------------------------------------------------------------------------------
// This callback function is called immediately before a device is created to allow the
// application to modify the device settings. The supplied pDeviceSettings parameter
// contains the settings that the framework has selected for the new device, and the
// application can make any desired changes directly to this structure. Note however that
// DXUT will not correct invalid device settings so care must be taken
// to return valid device settings, otherwise IDirect3D9::CreateDevice() will fail.
//--------------------------------------------------------------------------------------
{static} var s_bFirstTime: Boolean = True;
function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall;
begin
// Turn vsync off
pDeviceSettings.pp.PresentationInterval := D3DPRESENT_INTERVAL_IMMEDIATE;
g_SettingsDlg.DialogControl.GetComboBox(DXUTSETTINGSDLG_PRESENT_INTERVAL).Enabled := False;
// If device doesn't support HW T&L or doesn't support 2.0 vertex shaders in HW
// then switch to SWVP.
if (pCaps.DevCaps and D3DDEVCAPS_HWTRANSFORMANDLIGHT = 0) or
(pCaps.VertexShaderVersion < D3DVS_VERSION(2,0))
then pDeviceSettings.BehaviorFlags := D3DCREATE_SOFTWARE_VERTEXPROCESSING;
// If the hardware cannot do vertex blending, use software vertex processing.
if (pCaps.MaxVertexBlendMatrices < 2)
then pDeviceSettings.BehaviorFlags := D3DCREATE_SOFTWARE_VERTEXPROCESSING;
// If using hardware vertex processing, change to mixed vertex processing
// so there is a fallback.
if (pDeviceSettings.BehaviorFlags and D3DCREATE_HARDWARE_VERTEXPROCESSING <> 0)
then pDeviceSettings.BehaviorFlags := D3DCREATE_MIXED_VERTEXPROCESSING;
// Debugging vertex shaders requires either REF or software vertex processing
// and debugging pixel shaders requires REF.
{$IFDEF DEBUG_VS}
if (pDeviceSettings.DeviceType <> D3DDEVTYPE_REF) then
with pDeviceSettings do
begin
BehaviorFlags := BehaviorFlags and not D3DCREATE_HARDWARE_VERTEXPROCESSING;
BehaviorFlags := BehaviorFlags and not D3DCREATE_PUREDEVICE;
BehaviorFlags := BehaviorFlags or D3DCREATE_SOFTWARE_VERTEXPROCESSING;
end;
{$ENDIF}
{$IFDEF DEBUG_PS}
pDeviceSettings.DeviceType := D3DDEVTYPE_REF;
{$ENDIF}
// For the first device created if its a REF device, optionally display a warning dialog box
if s_bFirstTime then
begin
s_bFirstTime := False;
if (pDeviceSettings.DeviceType = D3DDEVTYPE_REF) then DXUTDisplaySwitchingToREFWarning;
end;
Result:= True;
end;
//--------------------------------------------------------------------------------------
// Called either by CreateMeshContainer when loading a skin mesh, or when
// changing methods. This function uses the pSkinInfo of the mesh
// container to generate the desired drawable mesh and bone combination
// table.
//--------------------------------------------------------------------------------------
function GenerateSkinnedMesh(const pd3dDevice: IDirect3DDevice9;
pMeshContainer: PD3DXMeshContainerDerived): HRESULT;
var
d3dCaps: TD3DCaps9;
rgBoneCombinations: PD3DXBoneCombination;
cInfl: DWORD;
i: Integer;
iInfl: Integer;
pMeshTmp: ID3DXMesh;
NumMaxFaceInfl: DWORD;
Flags: DWORD;
pIB: IDirect3DIndexBuffer9;
MaxMatrices: LongWord;
NewFVF: DWORD;
pMesh: ID3DXMesh;
pDecl: TFVFDeclaration;
pDeclCur: PD3DVertexElement9;
begin
Result := S_OK;
pd3dDevice.GetDeviceCaps(d3dCaps);
if (pMeshContainer.pSkinInfo = nil) then Exit;
g_bUseSoftwareVP := False;
pMeshContainer.MeshData.pMesh := nil;
pMeshContainer.pBoneCombinationBuf := nil;
try
// if non-indexed skinning mode selected, use ConvertToBlendedMesh to generate drawable mesh
if (g_SkinningMethod = D3DNONINDEXED) then
begin
Result := pMeshContainer.pSkinInfo.ConvertToBlendedMesh
(
pMeshContainer.pOrigMesh,
D3DXMESH_MANAGED or D3DXMESHOPT_VERTEXCACHE,
pMeshContainer.pAdjacency,
nil, nil, nil,
@pMeshContainer.NumInfl,
pMeshContainer.NumAttributeGroups,
pMeshContainer.pBoneCombinationBuf,
ID3DXMesh(pMeshContainer.MeshData.pMesh)
);
if FAILED(Result) then Exit;
// If the device can only do 2 matrix blends, ConvertToBlendedMesh cannot approximate all meshes to it
// Thus we split the mesh in two parts: The part that uses at most 2 matrices and the rest. The first is
// drawn using the device's HW vertex processing and the rest is drawn using SW vertex processing.
rgBoneCombinations := PD3DXBoneCombination(pMeshContainer.pBoneCombinationBuf.GetBufferPointer);
// look for any set of bone combinations that do not fit the caps
for i := 0 to pMeshContainer.NumAttributeGroups - 1 do
begin
cInfl := 0;
pMeshContainer.iAttributeSW := i;
for iInfl := 0 to pMeshContainer.NumInfl - 1 do
begin
// if (rgBoneCombinations[pMeshContainer.iAttributeSW].BoneId[iInfl] <> UINT_MAX)
if (rgBoneCombinations.BoneId[iInfl] <> UINT_MAX) then Inc(cInfl);
end;
if (cInfl > d3dCaps.MaxVertexBlendMatrices) then Break;
Inc(rgBoneCombinations);
end;
// if there is both HW and SW, add the Software Processing flag
if (pMeshContainer.iAttributeSW < pMeshContainer.NumAttributeGroups) then
begin
Result := ID3DXMesh(pMeshContainer.MeshData.pMesh).CloneMeshFVF(D3DXMESH_SOFTWAREPROCESSING or ID3DXMesh(pMeshContainer.MeshData.pMesh).GetOptions,
ID3DXMesh(pMeshContainer.MeshData.pMesh).GetFVF,
pd3dDevice, pMeshTmp);
if FAILED(Result) then Exit;
// pMeshContainer.MeshData.pMesh := nil;
pMeshContainer.MeshData.pMesh := pMeshTmp;
pMeshTmp := nil;
end;
end
// if indexed skinning mode selected, use ConvertToIndexedsBlendedMesh to generate drawable mesh
else if (g_SkinningMethod = D3DINDEXED) then
begin
Flags := D3DXMESHOPT_VERTEXCACHE;
Result := pMeshContainer.pOrigMesh.GetIndexBuffer(pIB);
if FAILED(Result) then Exit;
Result := pMeshContainer.pSkinInfo.GetMaxFaceInfluences(pIB, pMeshContainer.pOrigMesh.GetNumFaces, NumMaxFaceInfl);
pIB := nil;
if FAILED(Result) then Exit;
// 12 entry palette guarantees that any triangle (4 independent influences per vertex of a tri)
// can be handled
NumMaxFaceInfl := min(NumMaxFaceInfl, 12);
if (d3dCaps.MaxVertexBlendMatrixIndex + 1 < NumMaxFaceInfl) then
begin
// HW does not support indexed vertex blending. Use SW instead
pMeshContainer.NumPaletteEntries := min(256, pMeshContainer.pSkinInfo.GetNumBones);
pMeshContainer.UseSoftwareVP := True;
g_bUseSoftwareVP := True;
Flags := Flags or D3DXMESH_SYSTEMMEM;
end else
begin
// using hardware - determine palette size from caps and number of bones
// If normals are present in the vertex data that needs to be blended for lighting, then
// the number of matrices is half the number specified by MaxVertexBlendMatrixIndex.
pMeshContainer.NumPaletteEntries := min(( d3dCaps.MaxVertexBlendMatrixIndex + 1 ) div 2,
pMeshContainer.pSkinInfo.GetNumBones);
pMeshContainer.UseSoftwareVP := False;
Flags := Flags or D3DXMESH_MANAGED;
end;
Result := pMeshContainer.pSkinInfo.ConvertToIndexedBlendedMesh
(
pMeshContainer.pOrigMesh,
Flags,
pMeshContainer.NumPaletteEntries,
pMeshContainer.pAdjacency,
nil, nil, nil,
@pMeshContainer.NumInfl,
pMeshContainer.NumAttributeGroups,
pMeshContainer.pBoneCombinationBuf,
ID3DXMesh(pMeshContainer.MeshData.pMesh));
if FAILED(Result) then Exit;
end
// if vertex shader indexed skinning mode selected, use ConvertToIndexedsBlendedMesh to generate drawable mesh
else if (g_SkinningMethod = D3DINDEXEDVS) or (g_SkinningMethod = D3DINDEXEDHLSLVS) then
begin
// Get palette size
// First 9 constants are used for other data. Each 4x3 matrix takes up 3 constants.
// (96 - 9) /3 i.e. Maximum constant count - used constants
MaxMatrices := 26;
pMeshContainer.NumPaletteEntries := min(MaxMatrices, pMeshContainer.pSkinInfo.GetNumBones);
Flags := D3DXMESHOPT_VERTEXCACHE;
if (d3dCaps.VertexShaderVersion >= D3DVS_VERSION(1, 1)) then
begin
pMeshContainer.UseSoftwareVP := False;
Flags := Flags or D3DXMESH_MANAGED;
end else
begin
pMeshContainer.UseSoftwareVP := True;
g_bUseSoftwareVP := True;
Flags := Flags or D3DXMESH_SYSTEMMEM;
end;
pMeshContainer.MeshData.pMesh := nil;
Result := pMeshContainer.pSkinInfo.ConvertToIndexedBlendedMesh
(
pMeshContainer.pOrigMesh,
Flags,
pMeshContainer.NumPaletteEntries,
pMeshContainer.pAdjacency,
nil, nil, nil,
@pMeshContainer.NumInfl,
pMeshContainer.NumAttributeGroups,
pMeshContainer.pBoneCombinationBuf,
ID3DXMesh(pMeshContainer.MeshData.pMesh));
if FAILED(Result) then Exit;
// FVF has to match our declarator. Vertex shaders are not as forgiving as FF pipeline
NewFVF := (ID3DXMesh(pMeshContainer.MeshData.pMesh).GetFVF and D3DFVF_POSITION_MASK) or (D3DFVF_NORMAL or D3DFVF_TEX1 or D3DFVF_LASTBETA_UBYTE4);
if (NewFVF <> ID3DXMesh(pMeshContainer.MeshData.pMesh).GetFVF) then
begin
Result := ID3DXMesh(pMeshContainer.MeshData.pMesh).CloneMeshFVF(ID3DXMesh(pMeshContainer.MeshData.pMesh).GetOptions, NewFVF, pd3dDevice, pMesh);
if not FAILED(Result) then
begin
// pMeshContainer.MeshData.pMesh := nil;
pMeshContainer.MeshData.pMesh := pMesh;
pMesh := nil;
end;
end;
Result := ID3DXMesh(pMeshContainer.MeshData.pMesh).GetDeclaration(pDecl);
if FAILED(Result) then Exit;
// the vertex shader is expecting to interpret the UBYTE4 as a D3DCOLOR, so update the type
// NOTE: this cannot be done with CloneMesh, that would convert the UBYTE4 data to float and then to D3DCOLOR
// this is more of a "cast" operation
pDeclCur := @pDecl;
while (pDeclCur.Stream <> $ff) do
begin
if (pDeclCur.Usage = D3DDECLUSAGE_BLENDINDICES) and (pDeclCur.UsageIndex = 0)
then pDeclCur._Type := D3DDECLTYPE_D3DCOLOR;
Inc(pDeclCur);
end;
Result := ID3DXMesh(pMeshContainer.MeshData.pMesh).UpdateSemantics(pDecl);
if FAILED(Result) then Exit;
// allocate a buffer for bone matrices, but only if another mesh has not allocated one of the same size or larger
if (g_NumBoneMatricesMax < pMeshContainer.pSkinInfo.GetNumBones) then
begin
g_NumBoneMatricesMax := pMeshContainer.pSkinInfo.GetNumBones;
// Allocate space for blend matrices
g_pBoneMatrices := nil;
SetLength(g_pBoneMatrices, g_NumBoneMatricesMax);
end;
end
// if software skinning selected, use GenerateSkinnedMesh to create a mesh that can be used with UpdateSkinnedMesh
else if (g_SkinningMethod = SOFTWARE) then
begin
Result := pMeshContainer.pOrigMesh.CloneMeshFVF(D3DXMESH_MANAGED, pMeshContainer.pOrigMesh.GetFVF,
pd3dDevice, ID3DXMesh(pMeshContainer.MeshData.pMesh));
if FAILED(Result) then Exit;
Result := ID3DXMesh(pMeshContainer.MeshData.pMesh).GetAttributeTable(nil, @pMeshContainer.NumAttributeGroups);
if FAILED(Result) then Exit;
pMeshContainer.pAttributeTable := nil;
SetLength(pMeshContainer.pAttributeTable, pMeshContainer.NumAttributeGroups);
Result := ID3DXMesh(pMeshContainer.MeshData.pMesh).GetAttributeTable(@pMeshContainer.pAttributeTable[0], nil);
if FAILED(Result) then Exit;
// allocate a buffer for bone matrices, but only if another mesh has not allocated one of the same size or larger
if (g_NumBoneMatricesMax < pMeshContainer.pSkinInfo.GetNumBones) then
begin
g_NumBoneMatricesMax := pMeshContainer.pSkinInfo.GetNumBones;
// Allocate space for blend matrices
g_pBoneMatrices := nil;
SetLength(g_pBoneMatrices, g_NumBoneMatricesMax);
end;
end
else // invalid g_SkinningMethod value
begin
// return failure due to invalid skinning method value
Result := E_INVALIDARG;
end;
except
on EOutOfMemory do
Result := E_OUTOFMEMORY;
end;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has been
// created, which will happen during application initialization and windowed/full screen
// toggles. This is the best location to create D3DPOOL_MANAGED resources since these
// resources need to be reloaded whenever the device is destroyed. Resources created
// here should be released in the OnDestroyDevice callback.
//--------------------------------------------------------------------------------------
function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
var
Alloc: CAllocateHierarchy;
dwShaderFlags: DWORD;
str, strPath, strCWD: array[0..MAX_PATH-1] of WideChar;
pLastSlash: PWideChar;
cp: TD3DDeviceCreationParameters;
begin
Result:= g_DialogResourceManager.OnCreateDevice(pd3dDevice);
if V_Failed(Result) then Exit;
Result:= g_SettingsDlg.OnCreateDevice(pd3dDevice);
if V_Failed(Result) then Exit;
Alloc:= CAllocateHierarchy.Create;
// Initialize the font
Result := D3DXCreateFont(pd3dDevice, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH or FF_DONTCARE,
'Arial', g_pFont);
if V_Failed(Result) then Exit;
// Define DEBUG_VS and/or DEBUG_PS to debug vertex and/or pixel shaders with the
// shader debugger. Debugging vertex shaders requires either REF or software vertex
// processing, and debugging pixel shaders requires REF. The
// D3DXSHADER_FORCE_*_SOFTWARE_NOOPT flag improves the debug experience in the
// shader debugger. It enables source level debugging, prevents instruction
// reordering, prevents dead code elimination, and forces the compiler to compile
// against the next higher available software target, which ensures that the
// unoptimized shaders do not exceed the shader model limitations. Setting these
// flags will cause slower rendering since the shaders will be unoptimized and
// forced into software. See the DirectX documentation for more information about
// using the shader debugger.
dwShaderFlags := D3DXFX_NOT_CLONEABLE;
{$IFDEF DEBUG}
// Set the D3DXSHADER_DEBUG flag to embed debug information in the shaders.
// Setting this flag improves the shader debugging experience, but still allows
// the shaders to be optimized and to run exactly the way they will run in
// the release configuration of this program.
dwShaderFlags := dwShaderFlags or D3DXSHADER_DEBUG;
{$ENDIF}
{$IFDEF DEBUG_VS}
dwShaderFlags := dwShaderFlags or D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT;
{$ENDIF}
{$IFDEF DEBUG_PS}
dwShaderFlags := dwShaderFlags or D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT;
{$ENDIF}
// Read the D3DX effect file
Result:= DXUTFindDXSDKMediaFile(str, MAX_PATH, 'SkinnedMesh.fx');
if V_Failed(Result) then Exit;
// If this fails, there should be debug output as to
// they the .fx file failed to compile
Result:= D3DXCreateEffectFromFileW(pd3dDevice, str, nil, nil, dwShaderFlags,
nil, g_pEffect, nil);
if V_Failed(Result) then Exit;
// Load the mesh
Result:= DXUTFindDXSDKMediaFile(str, MAX_PATH, MESHFILENAME);
if V_Failed(Result) then Exit;
StringCchCopy(strPath, MAX_PATH, str);
pLastSlash := WideStrRScan(strPath, '\');
if Assigned(pLastSlash) then
begin
pLastSlash^ := #0;
Inc(pLastSlash);
end else
begin
//todo: FPC: Remove after FPC 2.0 will be available...
StringCchCopy(strPath, MAX_PATH, WideString('.'));
pLastSlash := str;
end;
GetCurrentDirectoryW(MAX_PATH, strCWD);
SetCurrentDirectoryW(strPath);
Result:= D3DXLoadMeshHierarchyFromXW(pLastSlash, D3DXMESH_MANAGED, pd3dDevice,
Alloc, nil, g_pFrameRoot, g_pAnimController);
if V_Failed(Result) then Exit;
Result:= SetupBoneMatrixPointers(g_pFrameRoot);
if V_Failed(Result) then Exit;
Result:= D3DXFrameCalculateBoundingSphere(g_pFrameRoot, g_vObjectCenter, g_fObjectRadius);
if V_Failed(Result) then Exit;
SetCurrentDirectoryW(strCWD);
// Obtain the behavior flags
pd3dDevice.GetCreationParameters(cp);
g_dwBehaviorFlags := cp.BehaviorFlags;
FreeAndNil(Alloc);
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has been
// reset, which will happen after a lost device scenario. This is the best location to
// create D3DPOOL_DEFAULT resources since these resources need to be reloaded whenever
// the device is lost. Resources created here should be released in the OnLostDevice
// callback.
//--------------------------------------------------------------------------------------
function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
var
fAspect: Single;
dwShaderFlags: DWORD;
iInfl: DWORD;
pCode: ID3DXBuffer;
str: array[0..MAX_PATH-1] of WideChar;
begin
Result:= g_DialogResourceManager.OnResetDevice;
if V_Failed(Result) then Exit;
Result:= g_SettingsDlg.OnResetDevice;
if V_Failed(Result) then Exit;
if Assigned(g_pFont) then
begin
Result:= g_pFont.OnResetDevice;
if V_Failed(Result) then Exit;
end;
if Assigned(g_pEffect) then
begin
Result:= g_pEffect.OnResetDevice;
if V_Failed(Result) then Exit;
end;
// Create a sprite to help batch calls when drawing many lines of text
Result:= D3DXCreateSprite(pd3dDevice, g_pTextSprite);
if V_Failed(Result) then Exit;
// Setup render state
pd3dDevice.SetRenderState(D3DRS_LIGHTING, iTrue);
pd3dDevice.SetRenderState(D3DRS_DITHERENABLE, iTrue);
pd3dDevice.SetRenderState(D3DRS_ZENABLE, iTrue);
pd3dDevice.SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW);
pd3dDevice.SetRenderState(D3DRS_AMBIENT, $33333333);
pd3dDevice.SetRenderState(D3DRS_NORMALIZENORMALS, iTrue);
pd3dDevice.SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
pd3dDevice.SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
// load the indexed vertex shaders
dwShaderFlags := 0;
{$IFDEF DEBUG}
// Set the D3DXSHADER_DEBUG flag to embed debug information in the shaders.
// Setting this flag improves the shader debugging experience, but still allows
// the shaders to be optimized and to run exactly the way they will run in
// the release configuration of this program.
dwShaderFlags := dwShaderFlags or D3DXSHADER_DEBUG;
{$ENDIF}
{$IFDEF DEBUG_VS}
dwShaderFlags := dwShaderFlags or D3DXSHADER_DEBUG or D3DXSHADER_SKIPVALIDATION;
{$ENDIF}
{$IFDEF DEBUG_PS}
dwShaderFlags := dwShaderFlags or D3DXSHADER_DEBUG or D3DXSHADER_SKIPVALIDATION;
{$ENDIF}
for iInfl := 0 to 3 do
begin
// Assemble the vertex shader file
DXUTFindDXSDKMediaFile(str, MAX_PATH, g_wszShaderSource[iInfl]);
Result := D3DXAssembleShaderFromFileW(str, nil, nil, dwShaderFlags, @pCode, nil);
if Failed(Result) then Exit;
// Create the vertex shader
Result := pd3dDevice.CreateVertexShader(PDWORD(pCode.GetBufferPointer),
g_pIndexedVertexShader[iInfl]);
if Failed(Result) then Exit;
pCode := nil;
end;
// Setup the projection matrix
fAspect := pBackBufferSurfaceDesc.Width / pBackBufferSurfaceDesc.Height;
D3DXMatrixPerspectiveFovLH(g_matProj, D3DX_PI/4, fAspect,
g_fObjectRadius/64.0, g_fObjectRadius*200.0);
pd3dDevice.SetTransform(D3DTS_PROJECTION, g_matProj);
D3DXMatrixTranspose(g_matProjT, g_matProj);
// Setup the arcball parameters
g_ArcBall.SetWindow(pBackBufferSurfaceDesc.Width, pBackBufferSurfaceDesc.Height, 0.85);
g_ArcBall.SetTranslationRadius(g_fObjectRadius);
g_HUD.SetLocation(pBackBufferSurfaceDesc.Width-170, 0);
g_HUD.SetSize(170, 170);
g_SampleUI.SetLocation(3, 45);
g_SampleUI.SetSize(240, 70);
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called once at the beginning of every frame. This is the
// best location for your application to handle updates to the scene, but is not
// intended to contain actual rendering calls, which should instead be placed in the
// OnFrameRender callback.
//--------------------------------------------------------------------------------------
procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
var
matWorld: TD3DXMatrixA16;
vEye, vAt, vUp: TD3DXVector3;
begin
// Setup world matrix
D3DXMatrixTranslation(matWorld, -g_vObjectCenter.x,
-g_vObjectCenter.y,
-g_vObjectCenter.z);
D3DXMatrixMultiply(matWorld, matWorld, g_ArcBall.GetRotationMatrix^);
D3DXMatrixMultiply(matWorld, matWorld, g_ArcBall.GetTranslationMatrix^);
pd3dDevice.SetTransform(D3DTS_WORLD, matWorld);
vEye := D3DXVector3(0, 0, -2*g_fObjectRadius);
vAt := D3DXVector3(0, 0, 0);
vUp := D3DXVector3(0, 1, 0);
D3DXMatrixLookAtLH(g_matView, vEye, vAt, vUp);
pd3dDevice.SetTransform(D3DTS_VIEW, g_matView);
if (g_pAnimController <> nil) then
g_pAnimController.AdvanceTime(fElapsedTime, nil);
UpdateFrameMatrices(g_pFrameRoot, @matWorld);
end;
//--------------------------------------------------------------------------------------
// Called to render a mesh in the hierarchy
//--------------------------------------------------------------------------------------
procedure DrawMeshContainer(const pd3dDevice: IDirect3DDevice9; pMeshContainerBase: PD3DXMeshContainer; pFrameBase: PD3DXFrame);
var
pMeshContainer: PD3DXMeshContainerDerived;
pFrame: PD3DXFrameDerived;
i, iMaterial, iAttrib, iPaletteEntry, iPass: Integer;
pBoneComb: PD3DXBoneCombination;
iMatrixIndex: LongWord;
numPasses: LongWord;
NumBlend: LongWord;
AttribIdPrev: DWORD;
matTemp: TD3DXMatrixA16;
d3dCaps: TD3DCaps9;
vConst: TD3DXVector4;
color1: TD3DXColor;
color2: TD3DXColor;
ambEmm: TD3DXColor;
Identity: TD3DXMatrix;
cBones: DWORD;
iBone: DWORD;
pbVerticesSrc: PByte;
pbVerticesDest: PByte;
begin
pMeshContainer := PD3DXMeshContainerDerived(pMeshContainerBase);
pFrame := PD3DXFrameDerived(pFrameBase);
pd3dDevice.GetDeviceCaps(d3dCaps);
// first check for skinning
if (pMeshContainer.pSkinInfo <> nil) then
begin
if (g_SkinningMethod = D3DNONINDEXED) then
begin
AttribIdPrev := UNUSED32;
pBoneComb := PD3DXBoneCombination(pMeshContainer.pBoneCombinationBuf.GetBufferPointer);
// Draw using default vtx processing of the device (typically HW)
for iAttrib := 0 to pMeshContainer.NumAttributeGroups - 1 do
begin
NumBlend := 0;
for i := 0 to pMeshContainer.NumInfl - 1 do
begin
if (pBoneComb.BoneId[i] <> UINT_MAX) then NumBlend := i;
end;
if (d3dCaps.MaxVertexBlendMatrices >= NumBlend + 1) then
begin
// first calculate the world matrices for the current set of blend weights and get the accurate count of the number of blends
for i := 0 to pMeshContainer.NumInfl - 1 do
begin
iMatrixIndex := pBoneComb.BoneId[i];
if (iMatrixIndex <> UINT_MAX) then
begin
D3DXMatrixMultiply(matTemp, pMeshContainer.pBoneOffsetMatrices[iMatrixIndex], pMeshContainer.ppBoneMatrixPtrs[iMatrixIndex]^);
V(pd3dDevice.SetTransform(D3DTS_WORLDMATRIX(i), matTemp));
end;
end;
V(pd3dDevice.SetRenderState(D3DRS_VERTEXBLEND, NumBlend));
// lookup the material used for this subset of faces
if (AttribIdPrev <> pBoneComb.AttribId) or (AttribIdPrev = UNUSED32) then
begin
V(pd3dDevice.SetMaterial(pMeshContainer.pMaterials[pBoneComb.AttribId].MatD3D));
V(pd3dDevice.SetTexture(0, pMeshContainer.ppTextures[pBoneComb.AttribId]));
AttribIdPrev := pBoneComb.AttribId;
end;
// draw the subset now that the correct material and matrices are loaded
V(ID3DXMesh(pMeshContainer.MeshData.pMesh).DrawSubset(iAttrib));
end;
Inc(pBoneComb);
end;
// refetch it
pBoneComb := PD3DXBoneCombination(pMeshContainer.pBoneCombinationBuf.GetBufferPointer);
// If necessary, draw parts that HW could not handle using SW
if (pMeshContainer.iAttributeSW < pMeshContainer.NumAttributeGroups) then
begin
AttribIdPrev := UNUSED32;
V(pd3dDevice.SetSoftwareVertexProcessing(True));
for iAttrib := pMeshContainer.iAttributeSW to pMeshContainer.NumAttributeGroups - 1 do
begin
NumBlend := 0;
for i := 0 to pMeshContainer.NumInfl - 1 do
begin
if (pBoneComb.BoneId[i] <> UINT_MAX) then NumBlend := i;
end;
if (d3dCaps.MaxVertexBlendMatrices < NumBlend + 1) then
begin
// first calculate the world matrices for the current set of blend weights and get the accurate count of the number of blends
for i := 0 to pMeshContainer.NumInfl - 1do
begin
iMatrixIndex := pBoneComb.BoneId[i];
if (iMatrixIndex <> UINT_MAX) then
begin
D3DXMatrixMultiply(matTemp, pMeshContainer.pBoneOffsetMatrices[iMatrixIndex], pMeshContainer.ppBoneMatrixPtrs[iMatrixIndex]^);
V(pd3dDevice.SetTransform(D3DTS_WORLDMATRIX(i), matTemp));
end;
end;
V(pd3dDevice.SetRenderState(D3DRS_VERTEXBLEND, NumBlend));
// lookup the material used for this subset of faces
if (AttribIdPrev <> pBoneComb.AttribId) or (AttribIdPrev = UNUSED32) then
begin
V(pd3dDevice.SetMaterial(pMeshContainer.pMaterials[pBoneComb.AttribId].MatD3D));
V(pd3dDevice.SetTexture(0, pMeshContainer.ppTextures[pBoneComb.AttribId]));
AttribIdPrev := pBoneComb.AttribId;
end;
// draw the subset now that the correct material and matrices are loaded
V(ID3DXMesh(pMeshContainer.MeshData.pMesh).DrawSubset(iAttrib));
end;
Inc(pBoneComb);
end;
V(pd3dDevice.SetSoftwareVertexProcessing(False));
end;
V(pd3dDevice.SetRenderState(D3DRS_VERTEXBLEND, 0));
end
else if (g_SkinningMethod = D3DINDEXED) then
begin
// if hw doesn't support indexed vertex processing, switch to software vertex processing
if pMeshContainer.UseSoftwareVP then
begin
// If hw or pure hw vertex processing is forced, we can't render the
// mesh, so just exit out. Typical applications should create
// a device with appropriate vertex processing capability for this
// skinning method.
if (g_dwBehaviorFlags and D3DCREATE_HARDWARE_VERTEXPROCESSING <> 0) then Exit;
V(pd3dDevice.SetSoftwareVertexProcessing(True));
end;
// set the number of vertex blend indices to be blended
if (pMeshContainer.NumInfl = 1)
then V(pd3dDevice.SetRenderState(D3DRS_VERTEXBLEND, D3DVBF_0WEIGHTS))
else V(pd3dDevice.SetRenderState(D3DRS_VERTEXBLEND, pMeshContainer.NumInfl - 1));
if (pMeshContainer.NumInfl <> 0) then
V(pd3dDevice.SetRenderState(D3DRS_INDEXEDVERTEXBLENDENABLE, iTrue));
// for each attribute group in the mesh, calculate the set of matrices in the palette and then draw the mesh subset
pBoneComb := PD3DXBoneCombination(pMeshContainer.pBoneCombinationBuf.GetBufferPointer);
for iAttrib := 0 to pMeshContainer.NumAttributeGroups - 1 do
begin
// first calculate all the world matrices
for iPaletteEntry := 0 to pMeshContainer.NumPaletteEntries - 1 do
begin
iMatrixIndex := pBoneComb.BoneId[iPaletteEntry];
if (iMatrixIndex <> UINT_MAX) then
begin
D3DXMatrixMultiply(matTemp, pMeshContainer.pBoneOffsetMatrices[iMatrixIndex], pMeshContainer.ppBoneMatrixPtrs[iMatrixIndex]^);
V(pd3dDevice.SetTransform(D3DTS_WORLDMATRIX(iPaletteEntry), matTemp));
end;
end;
// setup the material of the mesh subset - REMEMBER to use the original pre-skinning attribute id to get the correct material id
V(pd3dDevice.SetMaterial(pMeshContainer.pMaterials[pBoneComb.AttribId].MatD3D));
V(pd3dDevice.SetTexture(0, pMeshContainer.ppTextures[pBoneComb.AttribId]));
// finally draw the subset with the current world matrix palette and material state
V(ID3DXMesh(pMeshContainer.MeshData.pMesh).DrawSubset(iAttrib));
Inc(pBoneComb);
end;
// reset blending state
V(pd3dDevice.SetRenderState(D3DRS_INDEXEDVERTEXBLENDENABLE, iFalse));
V(pd3dDevice.SetRenderState(D3DRS_VERTEXBLEND, 0));
// remember to reset back to hw vertex processing if software was required
if pMeshContainer.UseSoftwareVP then V(pd3dDevice.SetSoftwareVertexProcessing(False));
end
else if (g_SkinningMethod = D3DINDEXEDVS) then
begin
// Use COLOR instead of UBYTE4 since Geforce3 does not support it
// vConst.w should be 3, but due to COLOR/UBYTE4 issue, mul by 255 and add epsilon
vConst := D3DXVector4(1.0, 0.0, 0.0, 765.01);
if pMeshContainer.UseSoftwareVP then
begin
// If hw or pure hw vertex processing is forced, we can't render the
// mesh, so just exit out. Typical applications should create
// a device with appropriate vertex processing capability for this
// skinning method.
if (g_dwBehaviorFlags and D3DCREATE_HARDWARE_VERTEXPROCESSING <> 0) then Exit;
V(pd3dDevice.SetSoftwareVertexProcessing(True));
end;
V(pd3dDevice.SetVertexShader(g_pIndexedVertexShader[pMeshContainer.NumInfl - 1]));
pBoneComb := PD3DXBoneCombination(pMeshContainer.pBoneCombinationBuf.GetBufferPointer);
for iAttrib := 0 to pMeshContainer.NumAttributeGroups - 1 do
begin
// first calculate all the world matrices
for iPaletteEntry := 0 to pMeshContainer.NumPaletteEntries - 1 do
begin
iMatrixIndex := pBoneComb.BoneId[iPaletteEntry];
if (iMatrixIndex <> UINT_MAX) then
begin
D3DXMatrixMultiply(matTemp, pMeshContainer.pBoneOffsetMatrices[iMatrixIndex], pMeshContainer.ppBoneMatrixPtrs[iMatrixIndex]^);
D3DXMatrixMultiplyTranspose(matTemp, matTemp, g_matView);
V(pd3dDevice.SetVertexShaderConstantF(iPaletteEntry*3 + 9, PSingle(@matTemp), 3));
end;
end;
// Sum of all ambient and emissive contribution
color1 := (pMeshContainer.pMaterials[pBoneComb.AttribId].MatD3D.Ambient);
color2 := D3DXColor(0.25, 0.25, 0.25, 1.0);
D3DXColorModulate(ambEmm, color1, color2);
D3DXColorAdd(ambEmm, ambEmm, pMeshContainer.pMaterials[pBoneComb.AttribId].MatD3D.Emissive);
// set material color properties
V(pd3dDevice.SetVertexShaderConstantF(8, PSingle(@pMeshContainer.pMaterials[pBoneComb.AttribId].MatD3D.Diffuse), 1));
V(pd3dDevice.SetVertexShaderConstantF(7, PSingle(@ambEmm), 1));
vConst.y := pMeshContainer.pMaterials[pBoneComb.AttribId].MatD3D.Power;
V(pd3dDevice.SetVertexShaderConstantF(0, PSingle(@vConst), 1));
V(pd3dDevice.SetTexture(0, pMeshContainer.ppTextures[pBoneComb.AttribId]));
// finally draw the subset with the current world matrix palette and material state
V(ID3DXMesh(pMeshContainer.MeshData.pMesh).DrawSubset(iAttrib));
Inc(pBoneComb);
end;
// remember to reset back to hw vertex processing if software was required
if pMeshContainer.UseSoftwareVP then V(pd3dDevice.SetSoftwareVertexProcessing(False));
V(pd3dDevice.SetVertexShader(nil));
end
else if (g_SkinningMethod = D3DINDEXEDHLSLVS) then
begin
//todo: Check here.....
if (pMeshContainer.UseSoftwareVP) then
begin
// If hw or pure hw vertex processing is forced, we can't render the
// mesh, so just exit out. Typical applications should create
// a device with appropriate vertex processing capability for this
// skinning method.
if (g_dwBehaviorFlags and D3DCREATE_HARDWARE_VERTEXPROCESSING <> 0) then Exit;
V(pd3dDevice.SetSoftwareVertexProcessing(True));
end;
pBoneComb := PD3DXBoneCombination(pMeshContainer.pBoneCombinationBuf.GetBufferPointer);
for iAttrib := 0 to pMeshContainer.NumAttributeGroups - 1 do
begin
// first calculate all the world matrices
for iPaletteEntry := 0 to pMeshContainer.NumPaletteEntries - 1 do
begin
iMatrixIndex := pBoneComb.BoneId[iPaletteEntry];
if (iMatrixIndex <> UINT_MAX) then
begin
D3DXMatrixMultiply(matTemp, pMeshContainer.pBoneOffsetMatrices[iMatrixIndex], pMeshContainer.ppBoneMatrixPtrs[iMatrixIndex]^);
D3DXMatrixMultiply(g_pBoneMatrices[iPaletteEntry], matTemp, g_matView);
end;
end;
V(g_pEffect.SetMatrixArray('mWorldMatrixArray', @g_pBoneMatrices[0], pMeshContainer.NumPaletteEntries));
// Sum of all ambient and emissive contribution
color1 := (pMeshContainer.pMaterials[pBoneComb.AttribId].MatD3D.Ambient);
color2 := D3DXColor(0.25, 0.25, 0.25, 1.0);
D3DXColorModulate(ambEmm, color1, color2);
D3DXColorAdd(ambEmm, ambEmm, pMeshContainer.pMaterials[pBoneComb.AttribId].MatD3D.Emissive);
// set material color properties
V(g_pEffect.SetVector('MaterialDiffuse', PD3DXVector4(@pMeshContainer.pMaterials[pBoneComb.AttribId].MatD3D.Diffuse)^));
V(g_pEffect.SetVector('MaterialAmbient', PD3DXVector4(@ambEmm)^));
// setup the material of the mesh subset - REMEMBER to use the original pre-skinning attribute id to get the correct material id
V(pd3dDevice.SetTexture(0, pMeshContainer.ppTextures[pBoneComb.AttribId]));
// Set CurNumBones to select the correct vertex shader for the number of bones
V(g_pEffect.SetInt('CurNumBones', pMeshContainer.NumInfl - 1));
// Start the effect now all parameters have been updated
V(g_pEffect._Begin(@numPasses, D3DXFX_DONOTSAVESTATE));
for iPass := 0 to numPasses - 1 do
begin
V(g_pEffect.BeginPass(iPass));
// draw the subset with the current world matrix palette and material state
// if iAttrib = 1 then
V(ID3DXMesh(pMeshContainer.MeshData.pMesh).DrawSubset(iAttrib));
V(g_pEffect.EndPass);
end;
V(g_pEffect._End);
V(pd3dDevice.SetVertexShader(nil));
Inc(pBoneComb);
end;
// remember to reset back to hw vertex processing if software was required
if pMeshContainer.UseSoftwareVP then
V(pd3dDevice.SetSoftwareVertexProcessing(False));
end
else if (g_SkinningMethod = SOFTWARE) then
begin
cBones := pMeshContainer.pSkinInfo.GetNumBones;
// set up bone transforms
for iBone := 0 to cBones - 1 do
begin
D3DXMatrixMultiply
(
g_pBoneMatrices[iBone], // output
pMeshContainer.pBoneOffsetMatrices[iBone],
pMeshContainer.ppBoneMatrixPtrs[iBone]^
);
end;
// set world transform
D3DXMatrixIdentity(Identity);
V(pd3dDevice.SetTransform(D3DTS_WORLD, Identity));
V(pMeshContainer.pOrigMesh.LockVertexBuffer(D3DLOCK_READONLY, Pointer(pbVerticesSrc)));
V(ID3DXMesh(pMeshContainer.MeshData.pMesh).LockVertexBuffer(0, Pointer(pbVerticesDest)));
// generate skinned mesh
pMeshContainer.pSkinInfo.UpdateSkinnedMesh(@g_pBoneMatrices[0], nil, pbVerticesSrc, pbVerticesDest);
V(pMeshContainer.pOrigMesh.UnlockVertexBuffer);
V(ID3DXMesh(pMeshContainer.MeshData.pMesh).UnlockVertexBuffer);
for iAttrib := 0 to pMeshContainer.NumAttributeGroups - 1 do
begin
V(pd3dDevice.SetMaterial((pMeshContainer.pMaterials[pMeshContainer.pAttributeTable[iAttrib].AttribId].MatD3D)));
V(pd3dDevice.SetTexture(0, pMeshContainer.ppTextures[pMeshContainer.pAttributeTable[iAttrib].AttribId]));
V(ID3DXMesh(pMeshContainer.MeshData.pMesh).DrawSubset(pMeshContainer.pAttributeTable[iAttrib].AttribId));
end;
end
else // bug out as unsupported mode
begin
Exit;
end;
end
else // standard mesh, just draw it after setting material properties
begin
V(pd3dDevice.SetTransform(D3DTS_WORLD, pFrame.CombinedTransformationMatrix));
for iMaterial := 0 to pMeshContainer.NumMaterials - 1 do
begin
V(pd3dDevice.SetMaterial(pMeshContainer.pMaterials[iMaterial].MatD3D));
V(pd3dDevice.SetTexture(0, pMeshContainer.ppTextures[iMaterial]));
V(ID3DXMesh(pMeshContainer.MeshData.pMesh).DrawSubset(iMaterial));
end;
end;
end;
//--------------------------------------------------------------------------------------
// Called to render a frame in the hierarchy
//--------------------------------------------------------------------------------------
procedure DrawFrame(const pd3dDevice: IDirect3DDevice9; pFrame: PD3DXFrame);
var
pMeshContainer: PD3DXMeshContainer;
begin
pMeshContainer := pFrame.pMeshContainer;
while (pMeshContainer <> nil) do
begin
DrawMeshContainer(pd3dDevice, pMeshContainer, pFrame);
pMeshContainer := pMeshContainer.pNextMeshContainer;
end;
if (pFrame.pFrameSibling <> nil) then DrawFrame(pd3dDevice, pFrame.pFrameSibling);
if (pFrame.pFrameFirstChild <> nil) then DrawFrame(pd3dDevice, pFrame.pFrameFirstChild);
end;
//--------------------------------------------------------------------------------------
// This callback function will be called at the end of every frame to perform all the
// rendering calls for the scene, and it will also be called if the window needs to be
// repainted. After this function has returned, DXUT will call
// IDirect3DDevice9::Present to display the contents of the next buffer in the swap chain
//--------------------------------------------------------------------------------------
procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
const
IsWireframe: array[False..True] of DWORD = (D3DFILL_SOLID, D3DFILL_WIREFRAME);
var
light: TD3DLight9;
vecLightDirUnnormalized: TD3DXVector3;
vLightDir: TD3DXVector4;
begin
// If the settings dialog is being shown, then
// render it instead of rendering the app's scene
if g_SettingsDlg.Active then
begin
g_SettingsDlg.OnRender(fElapsedTime);
Exit;
end;
// Clear the render target and the zbuffer
pd3dDevice.Clear(0, nil, D3DCLEAR_TARGET or D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB(0, 66, 75, 121), 1.0, 0);
// Setup the light
vecLightDirUnnormalized := D3DXVector3(0.0, -1.0, 1.0);
ZeroMemory(@light, SizeOf(TD3DLIGHT9));
light._Type := D3DLIGHT_DIRECTIONAL;
light.Diffuse.r := 1.0;
light.Diffuse.g := 1.0;
light.Diffuse.b := 1.0;
D3DXVec3Normalize(light.Direction, vecLightDirUnnormalized);
light.Position.x := 0.0;
light.Position.y := -1.0;
light.Position.z := 1.0;
light.Range := 1000.0;
V(pd3dDevice.SetLight(0, light));
V(pd3dDevice.LightEnable(0, True));
// Set the projection matrix for the vertex shader based skinning method
if (g_SkinningMethod = D3DINDEXEDVS) then
begin
V(pd3dDevice.SetVertexShaderConstantF(2, PSingle(@g_matProjT), 4));
end else
if (g_SkinningMethod = D3DINDEXEDHLSLVS) then
begin
V(g_pEffect.SetMatrix('mViewProj', g_matProj));
end;
// Set Light for vertex shader
vLightDir := D3DXVector4(0.0, 1.0, -1.0, 0.0);
D3DXVec4Normalize(vLightDir, vLightDir);
V(pd3dDevice.SetVertexShaderConstantF(1, @vLightDir.x, 1));
V(g_pEffect.SetVector('lhtDir', vLightDir));
// Begin the scene
if SUCCEEDED(pd3dDevice.BeginScene) then
begin
DrawFrame(pd3dDevice, g_pFrameRoot);
RenderText;
V(g_HUD.OnRender(fElapsedTime));
V(g_SampleUI.OnRender(fElapsedTime));
// End the scene.
pd3dDevice.EndScene;
end;
end;
//--------------------------------------------------------------------------------------
// Render the help and statistics text. This function uses the ID3DXFont interface for
// efficient text rendering.
//--------------------------------------------------------------------------------------
procedure RenderText;
var
txtHelper: CDXUTTextHelper;
pd3dsdBackBuffer: PD3DSurfaceDesc;
begin
// The helper object simply helps keep track of text position, and color
// and then it calls pFont->DrawText( m_pSprite, strMsg, -1, &rc, DT_NOCLIP, m_clr );
// If NULL is passed in as the sprite object, then it will work however the
// pFont->DrawText() will not be batched together. Batching calls will improves performance.
pd3dsdBackBuffer := DXUTGetBackBufferSurfaceDesc;
txtHelper := CDXUTTextHelper.Create(g_pFont, g_pTextSprite, 15);
// Output statistics
txtHelper._Begin;
txtHelper.SetInsertionPos(5, 5);
txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 0.0, 1.0));
txtHelper.DrawTextLine(DXUTGetFrameStats(True)); // Show FPS
txtHelper.DrawTextLine(DXUTGetDeviceStats);
txtHelper.SetForegroundColor( D3DXCOLOR( 1.0, 1.0, 1.0, 1.0 ));
// Output statistics
case g_SkinningMethod of
D3DNONINDEXED: txtHelper.DrawTextLine('Using fixed-function non-indexed skinning'#10);
D3DINDEXED: txtHelper.DrawTextLine('Using fixed-function indexed skinning'#10);
SOFTWARE: txtHelper.DrawTextLine('Using software skinning'#10);
D3DINDEXEDVS: txtHelper.DrawTextLine('Using assembly vertex shader indexed skinning'#10);
D3DINDEXEDHLSLVS: txtHelper.DrawTextLine('Using HLSL vertex shader indexed skinning'#10);
else
txtHelper.DrawTextLine( 'No skinning'#10);
end;
// Draw help
if g_bShowHelp then
begin
txtHelper.SetInsertionPos(10, pd3dsdBackBuffer.Height-15*6);
txtHelper.SetForegroundColor(D3DXCOLOR(1.0, 0.75, 0.0, 1.0 ));
txtHelper.DrawTextLine('Controls (F1 to hide):');
txtHelper.SetInsertionPos(40, pd3dsdBackBuffer.Height-15*5);
txtHelper.DrawTextLine('Rotate model: Left click drag'#10 +
'Zoom: Middle click drag'#10 +
'Pane: Right click drag'#10 +
'Quit: ESC');
end else
begin
txtHelper.SetInsertionPos(10, pd3dsdBackBuffer.Height-15*2);
txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 1.0, 1.0));
txtHelper.DrawTextLine('Press F1 for help');
end;
// If software vp is required and we are using a hwvp device,
// the mesh is not being displayed and we output an error message here.
if g_bUseSoftwareVP and (g_dwBehaviorFlags and D3DCREATE_HARDWARE_VERTEXPROCESSING <> 0) then
begin
txtHelper.SetInsertionPos(5, 85);
txtHelper.SetForegroundColor(D3DXColor(1.0, 0.0, 0.0, 1.0));
txtHelper.DrawTextLine('The HWVP device does not support this skinning method.'#10 +
'Select another skinning method or switch to mixed or software VP.');
end;
txtHelper._End;
txtHelper.Free;
end;
//--------------------------------------------------------------------------------------
// Before handling window messages, DXUT passes incoming windows
// messages to the application through this callback function. If the application sets
// *pbNoFurtherProcessing to TRUE, then DXUT will not process this message.
//--------------------------------------------------------------------------------------
function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall;
begin
Result:= 0;
// Always allow dialog resource manager calls to handle global messages
// so GUI state is updated correctly
pbNoFurtherProcessing := g_DialogResourceManager.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
if g_SettingsDlg.IsActive then
begin
g_SettingsDlg.MsgProc(hWnd, uMsg, wParam, lParam);
Exit;
end;
// Give the dialogs a chance to handle the message first
pbNoFurtherProcessing := g_HUD.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
pbNoFurtherProcessing := g_SampleUI.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
// Pass all remaining windows messages to arcball so it can respond to user input
g_ArcBall.HandleMessages( hWnd, uMsg, wParam, lParam );
end;
//--------------------------------------------------------------------------------------
// As a convenience, DXUT inspects the incoming windows messages for
// keystroke messages and decodes the message parameters to pass relevant keyboard
// messages to the application. The framework does not remove the underlying keystroke
// messages, which are still passed to the application's MsgProc callback.
//--------------------------------------------------------------------------------------
procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall;
begin
if bKeyDown then
begin
case nChar of
VK_F1: g_bShowHelp := not g_bShowHelp;
end;
end;
end;
//--------------------------------------------------------------------------------------
// Handles the GUI events
//--------------------------------------------------------------------------------------
procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall;
var
NewSkinningMethod: TMethod;
begin
case nControlID of
IDC_TOGGLEFULLSCREEN: DXUTToggleFullScreen;
IDC_TOGGLEREF: DXUTToggleREF;
IDC_CHANGEDEVICE: with g_SettingsDlg do Active := not Active;
IDC_METHOD:
begin
NewSkinningMethod := TMETHOD(size_t(CDXUTComboBox(pControl).GetSelectedData));
// If the selected skinning method is different than the current one
if (g_SkinningMethod <> NewSkinningMethod) then
begin
g_SkinningMethod := NewSkinningMethod;
// update the meshes to the new skinning method
UpdateSkinningMethod(g_pFrameRoot);
end;
end;
end;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has
// entered a lost state and before IDirect3DDevice9::Reset is called. Resources created
// in the OnResetDevice callback should be released here, which generally includes all
// D3DPOOL_DEFAULT resources. See the "Lost Devices" section of the documentation for
// information about lost devices.
//--------------------------------------------------------------------------------------
procedure OnLostDevice; stdcall;
var
iInfl: DWORD;
begin
g_DialogResourceManager.OnLostDevice;
g_SettingsDlg.OnLostDevice;
if Assigned(g_pFont) then g_pFont.OnLostDevice;
if Assigned(g_pEffect) then g_pEffect.OnLostDevice;
g_pTextSprite := nil;
// Release the vertex shaders
for iInfl := 0 to 3 do g_pIndexedVertexShader[iInfl] := nil;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has
// been destroyed, which generally happens as a result of application termination or
// windowed/full screen toggles. Resources created in the OnCreateDevice callback
// should be released here, which generally includes all D3DPOOL_MANAGED resources.
//--------------------------------------------------------------------------------------
procedure OnDestroyDevice; stdcall;
var
Alloc: CAllocateHierarchy;
begin
g_DialogResourceManager.OnDestroyDevice;
g_SettingsDlg.OnDestroyDevice;
SAFE_RELEASE(g_pEffect);
SAFE_RELEASE(g_pFont);
Alloc:= CAllocateHierarchy.Create;
D3DXFrameDestroy(g_pFrameRoot, Alloc);
g_pAnimController := nil;
Alloc.Free;
end;
//--------------------------------------------------------------------------------------
// Called to setup the pointers for a given bone to its transformation matrix
//--------------------------------------------------------------------------------------
function SetupBoneMatrixPointersOnMesh(pMeshContainerBase: PD3DXMeshContainer): HRESULT;
var
iBone, cBones: Integer;
pFrame: PD3DXFrameDerived;
pMeshContainer: PD3DXMeshContainerDerived;
begin
pMeshContainer := PD3DXMeshContainerDerived(pMeshContainerBase);
// if there is a skinmesh, then setup the bone matrices
if (pMeshContainer.pSkinInfo <> nil) then
begin
cBones := pMeshContainer.pSkinInfo.GetNumBones;
// pMeshContainer.ppBoneMatrixPtrs := new D3DXMATRIX*[cBones];
try
GetMem(pMeshContainer.ppBoneMatrixPtrs, SizeOf(PD3DXMatrix)*cBones);
except
Result:= E_OUTOFMEMORY;
Exit;
end;
for iBone := 0 to cBones - 1 do
begin
pFrame := PD3DXFrameDerived(D3DXFrameFind(g_pFrameRoot, pMeshContainer.pSkinInfo.GetBoneName(iBone)));
if (pFrame = nil) then
begin
Result:= E_FAIL;
Exit;
end;
pMeshContainer.ppBoneMatrixPtrs[iBone] := @pFrame.CombinedTransformationMatrix;
end;
end;
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// Called to setup the pointers for a given bone to its transformation matrix
//--------------------------------------------------------------------------------------
function SetupBoneMatrixPointers(pFrame: PD3DXFrame): HRESULT;
begin
if (pFrame.pMeshContainer <> nil) then
begin
Result := SetupBoneMatrixPointersOnMesh(pFrame.pMeshContainer);
if FAILED(Result) then Exit;
end;
if (pFrame.pFrameSibling <> nil) then
begin
Result := SetupBoneMatrixPointers(pFrame.pFrameSibling);
if FAILED(Result) then Exit;
end;
if (pFrame.pFrameFirstChild <> nil) then
begin
Result := SetupBoneMatrixPointers(pFrame.pFrameFirstChild);
if FAILED(Result) then Exit;
end;
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// update the frame matrices
//--------------------------------------------------------------------------------------
procedure UpdateFrameMatrices(pFrameBase: PD3DXFrame; pParentMatrix: PD3DXMatrix);
var
pFrame: PD3DXFrameDerived;
begin
pFrame := PD3DXFrameDerived(pFrameBase);
// Concatenate all matrices in the chain
if (pParentMatrix <> nil)
then D3DXMatrixMultiply(pFrame.CombinedTransformationMatrix, pFrame.TransformationMatrix, pParentMatrix^)
else pFrame.CombinedTransformationMatrix := pFrame.TransformationMatrix;
// Call siblings
if Assigned(pFrame.pFrameSibling)
then UpdateFrameMatrices(pFrame.pFrameSibling, pParentMatrix);
// Call children
if Assigned(pFrame.pFrameFirstChild)
then UpdateFrameMatrices(pFrame.pFrameFirstChild, @pFrame.CombinedTransformationMatrix);
end;
//--------------------------------------------------------------------------------------
// update the skinning method
//--------------------------------------------------------------------------------------
procedure UpdateSkinningMethod(pFrameBase: PD3DXFrame);
var
pFrame: PD3DXFrameDerived;
pMeshContainer: PD3DXMeshContainerDerived;
begin
pFrame := PD3DXFrameDerived(pFrameBase);
pMeshContainer := PD3DXMeshContainerDerived(pFrame.pMeshContainer);
while (pMeshContainer <> nil) do
begin
GenerateSkinnedMesh(DXUTGetD3DDevice, pMeshContainer);
pMeshContainer := PD3DXMeshContainerDerived(pMeshContainer.pNextMeshContainer);
end;
if (pFrame.pFrameSibling <> nil) then UpdateSkinningMethod(pFrame.pFrameSibling);
if (pFrame.pFrameFirstChild <> nil) then UpdateSkinningMethod(pFrame.pFrameFirstChild);
end;
procedure ReleaseAttributeTable(pFrameBase: PD3DXFrame);
var
pFrame: PD3DXFrameDerived;
pMeshContainer: PD3DXMeshContainerDerived;
begin
pFrame := PD3DXFrameDerived(pFrameBase);
pMeshContainer := PD3DXMeshContainerDerived(pFrame.pMeshContainer);
while (pMeshContainer <> nil) do
begin
pMeshContainer.pAttributeTable:= nil; {delete[]}
pMeshContainer := PD3DXMeshContainerDerived(pMeshContainer.pNextMeshContainer);
end;
if (pFrame.pFrameSibling <> nil) then
begin
ReleaseAttributeTable(pFrame.pFrameSibling);
end;
if (pFrame.pFrameFirstChild <> nil) then
begin
ReleaseAttributeTable(pFrame.pFrameFirstChild);
end;
end;
procedure CreateCustomDXUTobjects;
begin
g_DialogResourceManager:= CDXUTDialogResourceManager.Create; // manager for shared resources of dialogs
g_SettingsDlg:= CD3DSettingsDlg.Create; // Device settings dialog
g_ArcBall:= CD3DArcBall.Create;
g_HUD:= CDXUTDialog.Create;
g_SampleUI:= CDXUTDialog.Create;
end;
procedure DestroyCustomDXUTobjects;
begin
FreeAndNil(g_DialogResourceManager);
FreeAndNil(g_SettingsDlg);
FreeAndNil(g_ArcBall);
FreeAndNil(g_HUD);
FreeAndNil(g_SampleUI);
end;
end.
|
(*----------------------------------------------------------------------------*
* Direct3D sample from DirectX 9.0 SDK December 2006 *
* Delphi adaptation by Alexey Barkovoy (e-mail: directx@clootie.ru) *
* *
* Supported compilers: Delphi 5,6,7,9; FreePascal 2.0 *
* *
* Latest version can be downloaded from: *
* http://www.clootie.ru *
* http://sourceforge.net/projects/delphi-dx9sdk *
*----------------------------------------------------------------------------*
* $Id: ProgressiveMeshUnit.pas,v 1.17 2007/02/05 22:21:11 clootie Exp $
*----------------------------------------------------------------------------*)
//--------------------------------------------------------------------------------------
// File: ProgressiveMesh.cpp
//
// Starting point for new Direct3D applications
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
{$I DirectX.inc}
unit ProgressiveMeshUnit;
interface
uses
Windows, SysUtils,
DXTypes, Direct3D9, D3DX9,
DXUT, DXUTcore, DXUTenum, DXUTmesh, DXUTmisc, DXUTgui, DXUTSettingsDlg;
{.$DEFINE DEBUG_VS} // Uncomment this line to debug vertex shaders
{.$DEFINE DEBUG_PS} // Uncomment this line to debug pixel shaders
const
MESHFILENAME = 'dwarf\dwarf.x';
type
PD3DXMaterialArray = ^TD3DXMaterialArray;
TD3DXMaterialArray = array[0..0] of TD3DXMaterial;
PIDirect3DTexture9Array = ^IDirect3DTexture9Array;
IDirect3DTexture9Array = array[0..0] of IDirect3DTexture9;
PID3DXPMeshArray = ^TID3DXPMeshArray;
TID3DXPMeshArray = array [0..0] of ID3DXPMesh;
PD3DMaterial9Array = ^TD3DMaterial9Array;
TD3DMaterial9Array = array [0..0] of TD3DMaterial9;
//--------------------------------------------------------------------------------------
// Global variables
//--------------------------------------------------------------------------------------
var
g_pFont: ID3DXFont = nil; // Font for drawing text
g_pTextSprite: ID3DXSprite = nil; // Sprite for batching draw text calls
g_pEffect: ID3DXEffect = nil; // D3DX effect interface
g_Camera: CModelViewerCamera; // A model viewing camera
g_bShowHelp: Boolean = True; // If true, it renders the UI control text
g_DialogResourceManager: CDXUTDialogResourceManager; // manager for shared resources of dialogs
g_SettingsDlg: CD3DSettingsDlg; // Device settings dialog
g_HUD: CDXUTDialog; // dialog for standard controls
g_SampleUI: CDXUTDialog; // dialog for sample specific controls
g_ppPMeshes: PID3DXPMeshArray = nil;
g_pPMeshFull: ID3DXPMesh = nil;
g_cPMeshes: DWORD = 0;
g_iPMeshCur: DWORD;
g_mtrlMeshMaterials: PD3DMaterial9Array = nil;
g_ppMeshTextures: PIDirect3DTexture9Array = nil; // Array of textures, entries are nil if no texture specified
g_dwNumMaterials: DWORD = 0; // Number of materials
g_mWorldCenter: TD3DXMatrixA16;
g_vObjectCenter: TD3DXVector3; // Center of bounding sphere of object
g_fObjectRadius: Single; // Radius of bounding sphere of object
g_bShowOptimized: Boolean = True;
//--------------------------------------------------------------------------------------
// UI control IDs
//--------------------------------------------------------------------------------------
const
IDC_TOGGLEFULLSCREEN = 1;
IDC_TOGGLEREF = 3;
IDC_CHANGEDEVICE = 4;
IDC_DETAIL = 5;
IDC_DETAILLABEL = 6;
IDC_USEOPTIMIZED = 7;
//--------------------------------------------------------------------------------------
// Forward declarations
//--------------------------------------------------------------------------------------
function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall;
function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall;
function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall;
procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall;
procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall;
procedure OnLostDevice(pUserContext: Pointer); stdcall;
procedure OnDestroyDevice(pUserContext: Pointer); stdcall;
procedure InitApp;
procedure RenderText;
procedure SetNumVertices(dwNumVertices: DWORD);
procedure CreateCustomDXUTobjects;
procedure DestroyCustomDXUTobjects;
implementation
uses Math;
//--------------------------------------------------------------------------------------
// Initialize the app
//--------------------------------------------------------------------------------------
procedure InitApp;
var
iY: Integer;
begin
// Initialize dialogs
g_SettingsDlg.Init(g_DialogResourceManager);
g_HUD.Init(g_DialogResourceManager);
g_SampleUI.Init(g_DialogResourceManager);
g_HUD.SetCallback(OnGUIEvent);
iY := 10; g_HUD.AddButton(IDC_TOGGLEFULLSCREEN, 'Toggle full screen', 35, iY, 125, 22);
Inc(iY, 24); g_HUD.AddButton(IDC_TOGGLEREF, 'Toggle REF (F3)', 35, iY, 125, 22);
Inc(iY, 24); g_HUD.AddButton(IDC_CHANGEDEVICE, 'Change device (F2)', 35, iY, 125, 22, VK_F2);
g_SampleUI.EnableKeyboardInput(True);
g_SampleUI.SetCallback(OnGUIEvent);
iY := 10; g_SampleUI.AddStatic(IDC_DETAILLABEL, 'Level of Detail:', 0, iY, 200, 16);
g_SampleUI.AddCheckBox(IDC_USEOPTIMIZED, 'Use optimized mesh', 50, iY, 200, 20, True);
Inc(iY, 16); g_SampleUI.AddSlider(IDC_DETAIL, 10, iY, 200, 16, 4, 4, 4);
g_Camera.SetButtonMasks(MOUSE_LEFT_BUTTON, MOUSE_WHEEL, 0);
end;
//--------------------------------------------------------------------------------------
// Called during device initialization, this code checks the device for some
// minimum set of capabilities, and rejects those that don't pass by returning false.
//--------------------------------------------------------------------------------------
function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall;
var
pD3D: IDirect3D9;
begin
Result := False;
// No fallback defined by this app, so reject any device that
// doesn't support at least ps2.0
if (pCaps.PixelShaderVersion < D3DPS_VERSION(2,0)) then Exit;
// Skip backbuffer formats that don't support alpha blending
pD3D := DXUTGetD3DObject;
if FAILED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType,
AdapterFormat, D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING,
D3DRTYPE_TEXTURE, BackBufferFormat))
then Exit;
Result := True;
end;
//--------------------------------------------------------------------------------------
// This callback function is called immediately before a device is created to allow the
// application to modify the device settings. The supplied pDeviceSettings parameter
// contains the settings that the framework has selected for the new device, and the
// application can make any desired changes directly to this structure. Note however that
// DXUT will not correct invalid device settings so care must be taken
// to return valid device settings, otherwise IDirect3D9::CreateDevice() will fail.
//--------------------------------------------------------------------------------------
{static} var s_bFirstTime: Boolean = True;
function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall;
begin
// Turn vsync off
pDeviceSettings.pp.PresentationInterval := D3DPRESENT_INTERVAL_IMMEDIATE;
g_SettingsDlg.DialogControl.GetComboBox(DXUTSETTINGSDLG_PRESENT_INTERVAL).Enabled := False;
// If device doesn't support HW T&L or doesn't support 1.1 vertex shaders in HW
// then switch to SWVP.
if (pCaps.DevCaps and D3DDEVCAPS_HWTRANSFORMANDLIGHT = 0) or
(pCaps.VertexShaderVersion < D3DVS_VERSION(1,1))
then pDeviceSettings.BehaviorFlags := D3DCREATE_SOFTWARE_VERTEXPROCESSING;
// Debugging vertex shaders requires either REF or software vertex processing
// and debugging pixel shaders requires REF.
{$IFDEF DEBUG_VS}
if (pDeviceSettings.DeviceType <> D3DDEVTYPE_REF) then
with pDeviceSettings do
begin
BehaviorFlags := BehaviorFlags and not D3DCREATE_HARDWARE_VERTEXPROCESSING;
BehaviorFlags := BehaviorFlags and not D3DCREATE_PUREDEVICE;
BehaviorFlags := BehaviorFlags or D3DCREATE_SOFTWARE_VERTEXPROCESSING;
end;
{$ENDIF}
{$IFDEF DEBUG_PS}
pDeviceSettings.DeviceType := D3DDEVTYPE_REF;
{$ENDIF}
// For the first device created if its a REF device, optionally display a warning dialog box
if s_bFirstTime then
begin
s_bFirstTime := False;
if (pDeviceSettings.DeviceType = D3DDEVTYPE_REF) then DXUTDisplaySwitchingToREFWarning;
end;
Result:= True;
end;
procedure SetNumVertices(dwNumVertices: DWORD);
begin
g_pPMeshFull.SetNumVertices(dwNumVertices);
// If current pm valid for desired value, then set the number of vertices directly
if ((dwNumVertices >= g_ppPMeshes[g_iPMeshCur].GetMinVertices) and
(dwNumVertices <= g_ppPMeshes[g_iPMeshCur].GetMaxVertices)) then
begin
g_ppPMeshes[g_iPMeshCur].SetNumVertices(dwNumVertices);
end else // Search for the right one
begin
g_iPMeshCur := g_cPMeshes - 1;
// Look for the correct "bin"
while (g_iPMeshCur > 0) do
begin
// If number of vertices is less than current max then we found one to fit
if (dwNumVertices >= g_ppPMeshes[g_iPMeshCur].GetMinVertices)
then Break;
Dec(g_iPMeshCur, 1);
end;
// Set the vertices on the newly selected mesh
g_ppPMeshes[g_iPMeshCur].SetNumVertices(dwNumVertices);
end;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has been
// created, which will happen during application initialization and windowed/full screen
// toggles. This is the best location to create D3DPOOL_MANAGED resources since these
// resources need to be reloaded whenever the device is destroyed. Resources created
// here should be released in the OnDestroyDevice callback.
//--------------------------------------------------------------------------------------
function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
var
dwShaderFlags: DWORD;
str: array[0..MAX_PATH-1] of WideChar;
pAdjacencyBuffer: ID3DXBuffer;
pD3DXMtrlBuffer: ID3DXBuffer;
d3dxMaterials: PD3DXMaterialArray;
dw32BitFlag: DWORD;
pMesh: ID3DXMesh;
pPMesh: ID3DXPMesh;
pLastSlash: PWideChar;
strCWD: array[0..MAX_PATH-1] of WideChar;
pTempMesh: ID3DXMesh;
Epsilons: TD3DXWeldEpsilons;
i: Integer;
pVertexBuffer: IDirect3DVertexBuffer9;
pVertices: Pointer;
m: TD3DXMatrixA16;
cVerticesMin, cVerticesMax, cVerticesPerMesh: Integer;
iPMesh: Integer;
vecEye: TD3DXVector3;
vecAt: TD3DXVector3;
begin
Result:= g_DialogResourceManager.OnCreateDevice(pd3dDevice);
if V_Failed(Result) then Exit;
Result:= g_SettingsDlg.OnCreateDevice(pd3dDevice);
if V_Failed(Result) then Exit;
Result:= S_OK;
try try
// Initialize the font
Result:= D3DXCreateFont(pd3dDevice, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH or FF_DONTCARE,
'Arial', g_pFont);
if V_Failed(Result) then Exit;
// Define DEBUG_VS and/or DEBUG_PS to debug vertex and/or pixel shaders with the
// shader debugger. Debugging vertex shaders requires either REF or software vertex
// processing, and debugging pixel shaders requires REF. The
// D3DXSHADER_FORCE_*_SOFTWARE_NOOPT flag improves the debug experience in the
// shader debugger. It enables source level debugging, prevents instruction
// reordering, prevents dead code elimination, and forces the compiler to compile
// against the next higher available software target, which ensures that the
// unoptimized shaders do not exceed the shader model limitations. Setting these
// flags will cause slower rendering since the shaders will be unoptimized and
// forced into software. See the DirectX documentation for more information about
// using the shader debugger.
dwShaderFlags := D3DXFX_NOT_CLONEABLE;
{$IFDEF DEBUG}
// Set the D3DXSHADER_DEBUG flag to embed debug information in the shaders.
// Setting this flag improves the shader debugging experience, but still allows
// the shaders to be optimized and to run exactly the way they will run in
// the release configuration of this program.
dwShaderFlags := dwShaderFlags or D3DXSHADER_DEBUG;
{$ENDIF}
{$IFDEF DEBUG_VS}
dwShaderFlags := dwShaderFlags or D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT;
{$ENDIF}
{$IFDEF DEBUG_PS}
dwShaderFlags := dwShaderFlags or D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT;
{$ENDIF}
// Read the D3DX effect file
Result:= DXUTFindDXSDKMediaFile(str, MAX_PATH, WideString('ProgressiveMesh.fx'));
if V_Failed(Result) then Exit;
// If this fails, there should be debug output as to
// they the .fx file failed to compile
Result:= D3DXCreateEffectFromFileW(pd3dDevice, str, nil, nil, dwShaderFlags,
nil, g_pEffect, nil);
if V_Failed(Result) then Exit;
Result:= g_pEffect.SetTechnique('RenderScene');
if V_Failed(Result) then Exit;
// Load the mesh
Result:= DXUTFindDXSDKMediaFile(str, MAX_PATH, WideString(MESHFILENAME));
if V_Failed(Result) then Exit;
Result:= D3DXLoadMeshFromXW(str, D3DXMESH_MANAGED, pd3dDevice,
@pAdjacencyBuffer, @pD3DXMtrlBuffer, nil,
@g_dwNumMaterials, pMesh);
if V_Failed(Result) then Exit;
// Change the current directory to the mesh's directory so we can
// find the textures.
pLastSlash := WideStrRScan(str, '\');
if (pLastSlash <> nil) then(pLastSlash + 1)^ := #0;
GetCurrentDirectoryW(MAX_PATH, strCWD);
SetCurrentDirectoryW(str);
dw32BitFlag := (pMesh.GetOptions and D3DXMESH_32BIT);
// Perform simple cleansing operations on mesh
Result := D3DXCleanMesh(D3DXCLEAN_SIMPLIFICATION, pMesh, pAdjacencyBuffer.GetBufferPointer, pTempMesh,
pAdjacencyBuffer.GetBufferPointer, nil);
if FAILED(Result) then
begin
g_dwNumMaterials := 0;
Exit;
end;
SAFE_RELEASE(pMesh);
pMesh := pTempMesh;
// Perform a weld to try and remove excess vertices.
// Weld the mesh using all epsilons of 0.0f. A small epsilon like 1e-6 works well too
ZeroMemory(@Epsilons, SizeOf(TD3DXWeldEpsilons));
Result := D3DXWeldVertices(pMesh, 0, @Epsilons,
pAdjacencyBuffer.GetBufferPointer,
pAdjacencyBuffer.GetBufferPointer, nil, nil);
if FAILED(Result) then
begin
g_dwNumMaterials := 0;
Exit;
end;
// Verify validity of mesh for simplification
Result := D3DXValidMesh(pMesh, pAdjacencyBuffer.GetBufferPointer, nil);
if FAILED(Result) then
begin
g_dwNumMaterials := 0;
Exit;
end;
// Allocate a material/texture arrays
d3dxMaterials := PD3DXMaterialArray(pD3DXMtrlBuffer.GetBufferPointer);
GetMem(g_mtrlMeshMaterials, SizeOf(TD3DMaterial9)*g_dwNumMaterials);
GetMem(g_ppMeshTextures, SizeOf(IDirect3DTexture9)*g_dwNumMaterials);
ZeroMemory(g_ppMeshTextures, SizeOf(IDirect3DTexture9)*g_dwNumMaterials);
// Copy the materials and load the textures
for i := 0 to g_dwNumMaterials - 1 do
begin
g_mtrlMeshMaterials[i] := d3dxMaterials[i].MatD3D;
g_mtrlMeshMaterials[i].Ambient := g_mtrlMeshMaterials[i].Diffuse;
// Find the path to the texture and create that texture
MultiByteToWideChar(CP_ACP, 0, d3dxMaterials[i].pTextureFilename, -1, str, MAX_PATH);
str[MAX_PATH - 1] := #0;
if FAILED(D3DXCreateTextureFromFileW(pd3dDevice, str, g_ppMeshTextures[i]))
then g_ppMeshTextures[i] := nil;
end;
SAFE_RELEASE(pD3DXMtrlBuffer);
// Restore the current directory
SetCurrentDirectoryW(strCWD);
// Lock the vertex buffer, to generate a simple bounding sphere
Result := pMesh.GetVertexBuffer(pVertexBuffer);
if FAILED(Result) then Exit;
// goto End;
Result := pVertexBuffer.Lock(0, 0, pVertices, D3DLOCK_NOSYSLOCK);
if FAILED(Result) then Exit;
Result := D3DXComputeBoundingSphere(PD3DXVector3(pVertices), pMesh.GetNumVertices,
D3DXGetFVFVertexSize(pMesh.GetFVF),
g_vObjectCenter, g_fObjectRadius);
pVertexBuffer.Unlock;
SAFE_RELEASE(pVertexBuffer);
if FAILED(Result) then Exit;
begin
D3DXMatrixTranslation(g_mWorldCenter, -g_vObjectCenter.x,
-g_vObjectCenter.y,
-g_vObjectCenter.z);
D3DXMatrixScaling(m, 2.0 / g_fObjectRadius,
2.0 / g_fObjectRadius,
2.0 / g_fObjectRadius);
D3DXMatrixMultiply(g_mWorldCenter, g_mWorldCenter, m);
end;
// If the mesh is missing normals, generate them.
if (pMesh.GetFVF and D3DFVF_NORMAL = 0) then
begin
Result := pMesh.CloneMeshFVF(dw32BitFlag or D3DXMESH_MANAGED, pMesh.GetFVF or D3DFVF_NORMAL,
pd3dDevice, pTempMesh);
if FAILED(Result) then Exit;
D3DXComputeNormals( pTempMesh, nil);
pMesh := nil;
pMesh := pTempMesh;
end;
// Generate progressive meshes
Result := D3DXGeneratePMesh(pMesh, pAdjacencyBuffer.GetBufferPointer,
nil, nil, 1, D3DXMESHSIMP_VERTEX, pPMesh);
if FAILED(Result) then Exit;
cVerticesMin := pPMesh.GetMinVertices;
cVerticesMax := pPMesh.GetMaxVertices;
cVerticesPerMesh := (cVerticesMax - cVerticesMin + 10) div 10;
g_cPMeshes := Max(1, DWORD(Ceil((cVerticesMax - cVerticesMin + 1) / cVerticesPerMesh)));
GetMem(g_ppPMeshes, SizeOf(ID3DXPMesh)*g_cPMeshes);
ZeroMemory(g_ppPMeshes, SizeOf(ID3DXPMesh)*g_cPMeshes);
// Clone full size pmesh
Result := pPMesh.ClonePMeshFVF(D3DXMESH_MANAGED or D3DXMESH_VB_SHARE, pPMesh.GetFVF, pd3dDevice, g_pPMeshFull);
if FAILED(Result) then Exit;
// Clone all the separate pmeshes
for iPMesh := 0 to g_cPMeshes - 1 do
begin
Result := pPMesh.ClonePMeshFVF(D3DXMESH_MANAGED or D3DXMESH_VB_SHARE, pPMesh.GetFVF, pd3dDevice, g_ppPMeshes[iPMesh]);
if FAILED(Result) then Exit;
// Trim to appropriate space
Result := g_ppPMeshes[iPMesh].TrimByVertices(cVerticesMin + cVerticesPerMesh * iPMesh, cVerticesMin + cVerticesPerMesh * (iPMesh+1), nil, nil);
if FAILED(Result) then Exit;
Result := g_ppPMeshes[iPMesh].OptimizeBaseLOD(D3DXMESHOPT_VERTEXCACHE, nil);
if FAILED(Result) then Exit;
end;
// Set current to be maximum number of vertices
g_iPMeshCur := g_cPMeshes - 1;
Result := g_ppPMeshes[g_iPMeshCur].SetNumVertices(cVerticesMax);
if FAILED(Result) then Exit;
Result := g_pPMeshFull.SetNumVertices(cVerticesMax);
if FAILED(Result) then Exit;
// Set up the slider to reflect the vertices range the mesh has
g_SampleUI.GetSlider(IDC_DETAIL).SetRange(g_ppPMeshes[0].GetMinVertices, g_ppPMeshes[g_cPMeshes-1].GetMaxVertices);
g_SampleUI.GetSlider(IDC_DETAIL).Value := g_ppPMeshes[g_iPMeshCur].GetNumVertices;
// Setup the camera's view parameters
begin
vecEye := D3DXVector3(0.0, 0.0, -5.0);
vecAt := D3DXVector3(0.0, 0.0, -0.0);
g_Camera.SetViewParams(vecEye, vecAt);
end;
except
on EOutOfMemory do Result := E_OUTOFMEMORY;
end;
finally
SAFE_RELEASE(pAdjacencyBuffer);
SAFE_RELEASE(pD3DXMtrlBuffer);
SAFE_RELEASE(pMesh);
SAFE_RELEASE(pPMesh);
if FAILED(Result) then
begin
if Assigned(g_ppPMeshes) then
for iPMesh := 0 to g_cPMeshes - 1 do SAFE_RELEASE(g_ppPMeshes[iPMesh]);
if Assigned(g_ppPMeshes) then FreeMem(g_ppPMeshes);
g_ppPMeshes := nil;
g_cPMeshes := 0;
SAFE_RELEASE(g_pPMeshFull)
end;
end;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has been
// reset, which will happen after a lost device scenario. This is the best location to
// create D3DPOOL_DEFAULT resources since these resources need to be reloaded whenever
// the device is lost. Resources created here should be released in the OnLostDevice
// callback.
//--------------------------------------------------------------------------------------
function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
var
fAspectRatio: Single;
begin
Result:= g_DialogResourceManager.OnResetDevice;
if V_Failed(Result) then Exit;
Result:= g_SettingsDlg.OnResetDevice;
if V_Failed(Result) then Exit;
if Assigned(g_pFont) then
begin
Result:= g_pFont.OnResetDevice;
if V_Failed(Result) then Exit;
end;
if Assigned(g_pEffect) then
begin
Result:= g_pEffect.OnResetDevice;
if V_Failed(Result) then Exit;
end;
// Create a sprite to help batch calls when drawing many lines of text
Result:= D3DXCreateSprite(pd3dDevice, g_pTextSprite);
if V_Failed(Result) then Exit;
// Setup the camera's projection parameters
fAspectRatio := pBackBufferSurfaceDesc.Width / pBackBufferSurfaceDesc.Height;
g_Camera.SetProjParams(D3DX_PI/4, fAspectRatio, 0.1, 1000.0);
g_Camera.SetWindow(pBackBufferSurfaceDesc.Width, pBackBufferSurfaceDesc.Height);
g_HUD.SetLocation(pBackBufferSurfaceDesc.Width-170, 0);
g_HUD.SetSize(170, 170);
g_SampleUI.SetLocation(0, pBackBufferSurfaceDesc.Height-50);
g_SampleUI.SetSize(pBackBufferSurfaceDesc.Width, 50);
g_SampleUI.GetControl(IDC_DETAILLABEL).SetLocation(( pBackBufferSurfaceDesc.Width - 200 ) div 2, 10);
g_SampleUI.GetControl(IDC_USEOPTIMIZED).SetLocation(pBackBufferSurfaceDesc.Width - 130, 5);
g_SampleUI.GetControl(IDC_DETAIL).SetSize(pBackBufferSurfaceDesc.Width - 20, 16);
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called once at the beginning of every frame. This is the
// best location for your application to handle updates to the scene, but is not
// intended to contain actual rendering calls, which should instead be placed in the
// OnFrameRender callback.
//--------------------------------------------------------------------------------------
procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
begin
// Update the camera's position based on user input
g_Camera.FrameMove(fElapsedTime);
end;
//--------------------------------------------------------------------------------------
// This callback function will be called at the end of every frame to perform all the
// rendering calls for the scene, and it will also be called if the window needs to be
// repainted. After this function has returned, DXUT will call
// IDirect3DDevice9::Present to display the contents of the next buffer in the swap chain
//--------------------------------------------------------------------------------------
procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
var
mWorld: TD3DXMatrixA16;
mView: TD3DXMatrixA16;
mProj: TD3DXMatrixA16;
mWorldViewProjection: TD3DXMatrixA16;
m: TD3DXMatrixA16;
i: Integer;
cPasses: Integer;
p: Integer;
begin
// If the settings dialog is being shown, then
// render it instead of rendering the app's scene
if g_SettingsDlg.Active then
begin
g_SettingsDlg.OnRender(fElapsedTime);
Exit;
end;
// Clear the render target and the zbuffer
V(pd3dDevice.Clear(0, nil, D3DCLEAR_TARGET or D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB(0, 66, 75, 121), 1.0, 0));
// Render the scene
if SUCCEEDED(pd3dDevice.BeginScene) then
begin
// Get the projection & view matrix from the camera class
D3DXMatrixMultiply(mWorld, g_mWorldCenter, g_Camera.GetWorldMatrix^);
mProj := g_Camera.GetProjMatrix^;
mView := g_Camera.GetViewMatrix^;
// mWorldViewProjection = mWorld * mView * mProj;
D3DXMatrixMultiply(m, mView, mProj);
D3DXMatrixMultiply(mWorldViewProjection, mWorld, m);
if Assigned(g_ppPMeshes) then
begin
// Update the effect's variables. Instead of using strings, it would
// be more efficient to cache a handle to the parameter by calling
// ID3DXEffect::GetParameterByName
V(g_pEffect.SetMatrix('g_mWorldViewProjection', mWorldViewProjection));
V(g_pEffect.SetMatrix('g_mWorld', mWorld));
// Set and draw each of the materials in the mesh
for i := 0 to g_dwNumMaterials - 1 do
begin
V(g_pEffect.SetVector('g_vDiffuse', PD3DXVector4(@g_mtrlMeshMaterials[i])^));
V(g_pEffect.SetTexture('g_txScene', g_ppMeshTextures[i]));
V(g_pEffect._Begin(@cPasses, 0));
for p := 0 to cPasses - 1 do
begin
V(g_pEffect.BeginPass(p));
if g_bShowOptimized
then V(g_ppPMeshes[g_iPMeshCur].DrawSubset(i))
else V(g_pPMeshFull.DrawSubset(i));
V(g_pEffect.EndPass);
end;
V(g_pEffect._End);
end;
end;
RenderText;
V(g_HUD.OnRender(fElapsedTime));
V(g_SampleUI.OnRender(fElapsedTime));
V(pd3dDevice.EndScene);
end;
end;
//--------------------------------------------------------------------------------------
// Render the help and statistics text. This function uses the ID3DXFont interface for
// efficient text rendering.
//--------------------------------------------------------------------------------------
procedure RenderText;
var
pd3dsdBackBuffer: PD3DSurfaceDesc;
txtHelper: CDXUTTextHelper;
begin
// The helper object simply helps keep track of text position, and color
// and then it calls pFont->DrawText( m_pSprite, strMsg, -1, &rc, DT_NOCLIP, m_clr );
// If NULL is passed in as the sprite object, then it will work however the
// pFont->DrawText() will not be batched together. Batching calls will improves performance.
pd3dsdBackBuffer := DXUTGetBackBufferSurfaceDesc;
txtHelper := CDXUTTextHelper.Create(g_pFont, g_pTextSprite, 15);
// Output statistics
txtHelper._Begin;
txtHelper.SetInsertionPos(5, 5);
txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 0.0, 1.0 ));
txtHelper.DrawTextLine(DXUTGetFrameStats(True)); // Show FPS
txtHelper.DrawTextLine(DXUTGetDeviceStats);
txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 1.0, 1.0));
if g_bShowOptimized then
txtHelper.DrawTextLine(PWideChar(WideFormat(
'Using optimized mesh %d of %d'#10+
'Current mesh vertices range: %u / %u'#10+
'Absolute vertices range: %u / %u'#10+
'Current vertices: %d'#10, [
g_iPMeshCur + 1, g_cPMeshes,
g_ppPMeshes[g_iPMeshCur].GetMinVertices,
g_ppPMeshes[g_iPMeshCur].GetMaxVertices,
g_ppPMeshes[0].GetMinVertices,
g_ppPMeshes[g_cPMeshes-1].GetMaxVertices,
g_ppPMeshes[g_iPMeshCur].GetNumVertices])))
else
txtHelper.DrawTextLine(PWideChar(WideFormat('Using unoptimized mesh'#10+
'Mesh vertices range: %u / %u'#10+
'Current vertices: %d'#10, [
g_pPMeshFull.GetMinVertices,
g_pPMeshFull.GetMaxVertices,
g_pPMeshFull.GetNumVertices])));
// Draw help
if g_bShowHelp then
begin
txtHelper.SetInsertionPos(10, pd3dsdBackBuffer.Height-15*7);
txtHelper.SetForegroundColor(D3DXColor(1.0, 0.75, 0.0, 1.0 ));
txtHelper.DrawTextLine('Controls (F1 to hide):');
txtHelper.SetInsertionPos(40, pd3dsdBackBuffer.Height-15*6);
txtHelper.DrawTextLine('Rotate mesh: Left click drag'#10+
'Zoom: mouse wheel'#10+
'Quit: ESC');
end else
begin
txtHelper.SetInsertionPos(10, pd3dsdBackBuffer.Height-15*4);
txtHelper.SetForegroundColor(D3DXColor(1.0, 0.75, 0.0, 1.0 ));
txtHelper.DrawTextLine('Press F1 for help');
end;
txtHelper._End;
txtHelper.Free;
end;
//--------------------------------------------------------------------------------------
// Before handling window messages, DXUT passes incoming windows
// messages to the application through this callback function. If the application sets
// *pbNoFurtherProcessing to TRUE, then DXUT will not process this message.
//--------------------------------------------------------------------------------------
function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall;
begin
Result:= 0;
// Always allow dialog resource manager calls to handle global messages
// so GUI state is updated correctly
pbNoFurtherProcessing := g_DialogResourceManager.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
if g_SettingsDlg.IsActive then
begin
g_SettingsDlg.MsgProc(hWnd, uMsg, wParam, lParam);
Exit;
end;
// Give the dialogs a chance to handle the message first
pbNoFurtherProcessing := g_HUD.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
pbNoFurtherProcessing := g_SampleUI.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
// Pass all remaining windows messages to camera so it can respond to user input
g_Camera.HandleMessages(hWnd, uMsg, wParam, lParam);
end;
//--------------------------------------------------------------------------------------
// As a convenience, DXUT inspects the incoming windows messages for
// keystroke messages and decodes the message parameters to pass relevant keyboard
// messages to the application. The framework does not remove the underlying keystroke
// messages, which are still passed to the application's MsgProc callback.
//--------------------------------------------------------------------------------------
procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall;
begin
if bKeyDown then
begin
case nChar of
VK_F1: g_bShowHelp := not g_bShowHelp;
end;
end;
end;
//--------------------------------------------------------------------------------------
// Handles the GUI events
//--------------------------------------------------------------------------------------
procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall;
begin
case nControlID of
IDC_TOGGLEFULLSCREEN: DXUTToggleFullScreen;
IDC_TOGGLEREF: DXUTToggleREF;
IDC_CHANGEDEVICE: with g_SettingsDlg do Active := not Active;
IDC_DETAIL: SetNumVertices((pControl as CDXUTSlider).Value);
IDC_USEOPTIMIZED: g_bShowOptimized := (pControl as CDXUTCheckBox).Checked;
end;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has
// entered a lost state and before IDirect3DDevice9::Reset is called. Resources created
// in the OnResetDevice callback should be released here, which generally includes all
// D3DPOOL_DEFAULT resources. See the "Lost Devices" section of the documentation for
// information about lost devices.
//--------------------------------------------------------------------------------------
procedure OnLostDevice; stdcall;
begin
g_DialogResourceManager.OnLostDevice;
g_SettingsDlg.OnLostDevice;
if Assigned(g_pFont) then g_pFont.OnLostDevice;
if Assigned(g_pEffect) then g_pEffect.OnLostDevice;
SAFE_RELEASE(g_pTextSprite);
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has
// been destroyed, which generally happens as a result of application termination or
// windowed/full screen toggles. Resources created in the OnCreateDevice callback
// should be released here, which generally includes all D3DPOOL_MANAGED resources.
//--------------------------------------------------------------------------------------
procedure OnDestroyDevice; stdcall;
var
i: Integer;
begin
g_DialogResourceManager.OnDestroyDevice;
g_SettingsDlg.OnDestroyDevice;
SAFE_RELEASE(g_pEffect);
SAFE_RELEASE(g_pFont);
for i := 0 to g_dwNumMaterials - 1 do SAFE_RELEASE(g_ppMeshTextures[i]);
FreeMem(g_ppMeshTextures);
SAFE_RELEASE( g_pPMeshFull );
for i := 0 to g_cPMeshes - 1 do SAFE_RELEASE(g_ppPMeshes[i]);
g_cPMeshes := 0;
FreeMem(g_ppPMeshes);
FreeMem(g_mtrlMeshMaterials);
g_dwNumMaterials := 0;
end;
procedure CreateCustomDXUTobjects;
begin
g_DialogResourceManager:= CDXUTDialogResourceManager.Create; // manager for shared resources of dialogs
g_SettingsDlg:= CD3DSettingsDlg.Create; // Device settings dialog
g_Camera:= CModelViewerCamera.Create;
g_HUD := CDXUTDialog.Create;
g_SampleUI:= CDXUTDialog.Create;
end;
procedure DestroyCustomDXUTobjects;
begin
FreeAndNil(g_DialogResourceManager);
FreeAndNil(g_SettingsDlg);
FreeAndNil(g_Camera);
FreeAndNil(g_HUD);
FreeAndNil(g_SampleUI);
end;
end.
|
unit OrcamentoItens.Model.Interf;
interface
uses TESTORCAMENTOITENS.Entidade.Model, ormbr.container.objectset.interfaces;
type
IOrcamentoItensModel = interface
['{03181149-B5E8-4325-A1D4-550E60ADCD2E}']
function Entidade(AValue: TTESTORCAMENTOITENS): IOrcamentoItensModel; overload;
function Entidade: TTESTORCAMENTOITENS; overload;
function DAO: IContainerObjectSet<TTESTORCAMENTOITENS>;
end;
implementation
end.
|
UNIT lista2;
INTERFACE
uses lista;
TYPE
pListaM = ^TListaM;
TListaM = RECORD
id : Longint;
Nomb_Marker : String;
tamanio : integer;
coordenadas : integer;
figprimitivas : pTPrimitiva;
siguiente : pListaM;
END;
VAR
NM : String;
ID : longint;
TM : Integer;
CM : Integer;
IMPLEMENTATION
PROCEDURE Lista_Inicializar_M(VAR Lm : PListaM); BEGIN
Lm := nil;
END;
FUNCTION Lista_Agregar_M(VAR Lm : pListaM;VAR M : pTConjuntoFiguras;n:String): boolean;
VAR
temp, ultimo : pListaM;
BEGIN
new(temp);
temp^.Nomb_Marker := NM;
temp^.id := ID;
temp^.tamanio := TM;
temp^.coordenadas :=TM;
temp^.figprimitivas := Lista_RegresaPrimitivas(M,n);
temp^.siguiente := nil;
IF Lm = nil THEN BEGIN
Lm := temp;
END
ELSE BEGIN
ultimo := Lm;
WHILE ultimo^.siguiente <> nil DO BEGIN
ultimo := ultimo^.siguiente;
END;
ultimo^.siguiente := temp;
END;
Lista_Agregar_M:=true;
END;
FUNCTION NumElems_M(Lm : pListaM):integer;
VAR
temp : pListaM;
Elementos : integer;
BEGIN
IF Lm = nil THEN BEGIN
NumElems_M := 0
END
ELSE BEGIN
Elementos := 1;
temp := Lm;
WHILE temp^.siguiente <> nil DO BEGIN
Elementos := Elementos + 1;
temp := temp^.siguiente;
END;
NumElems_M := Elementos;
END;
END;
FUNCTION Lista_Buscar_M(Lm : pListaM; N : String): boolean;
VAR
temp : pListaM;
NElem, i : Integer;
Figura : boolean;
BEGIN
i := 0;
Figura := False;
temp := Lm;
NElem := NumElems_M(temp);
WHILE i < NElem DO BEGIN
IF N = temp^.Nomb_Marker THEN BEGIN
Figura := True;
i := NElem;
NM := temp^.Nomb_Marker ;
END
ELSE BEGIN
i := i + 1;
temp := temp^.siguiente;
END;
END;
Lista_Buscar_M:=Figura;
END;
END.
|
unit ToolExcel;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, AdvGlowButton, AdvToolBar;
type
TFrmToolExcel = class(TForm)
ToolBarExcelFonts: TAdvToolBar;
ButtonSmallFont: TAdvGlowButton;
ButtonLargeFont: TAdvGlowButton;
ButtonShowExcel: TAdvGlowButton;
ButtonDrawBordert: TAdvGlowButton;
ButtonClearBordert: TAdvGlowButton;
procedure ButtonLargeFontClick(Sender: TObject);
procedure ButtonSmallFontClick(Sender: TObject);
procedure ButtonDrawBordertClick(Sender: TObject);
procedure ButtonClearBordertClick(Sender: TObject);
procedure ButtonShowExcelClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FrmToolExcel: TFrmToolExcel;
implementation
uses
Grid1, Dialog1;
{$R *.dfm}
procedure TFrmToolExcel.ButtonLargeFontClick(Sender: TObject);
begin
FrmGrid1.ButtonLargeFontClick(Sender);
end;
procedure TFrmToolExcel.ButtonSmallFontClick(Sender: TObject);
begin
FrmGrid1.ButtonSmallFontClick(Sender);
end;
procedure TFrmToolExcel.ButtonDrawBordertClick(Sender: TObject);
begin
FrmGrid1.ButtonDrawBordertClick(Sender);
end;
procedure TFrmToolExcel.ButtonClearBordertClick(Sender: TObject);
begin
FrmGrid1.ButtonClearBordertClick(Sender);
end;
procedure TFrmToolExcel.ButtonShowExcelClick(Sender: TObject);
begin
FrmGrid1.ButtonShowExcelClick(Sender);
end;
procedure TFrmToolExcel.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
try
if FrmDialog1.Caption<>'' then FrmDialog1.ButtonExcelTool.Visible:=true;
except
end;
end;
end.
|
unit GLDCylinder;
interface
uses
Classes, GL, GLDTypes, GLDConst, GLDClasses, GLDObjects;
type
TGLDCylinder = class(TGLDEditableObject)
private
FRadius: GLfloat;
FHeight: GLfloat;
FHeightSegs: GLushort;
FCapSegs: GLushort;
FSides: GLushort;
FStartAngle: GLfloat;
FSweepAngle: GLfloat;
FSidePoints: PGLDVector3fArray;
FTopPoints: PGLDVector3fArray;
FBottomPoints: PGLDVector3fArray;
FSideNormals: PGLDVector3fArray;
FTopNormals: PGLDVector3fArray;
FBottomNormals: PGLDVector3fArray;
function GetMode: GLubyte;
function GetSidePoint(i, j: GLushort): PGLDVector3f;
function GetTopPoint(i, j: GLushort): PGLDVector3f;
function GetBottomPoint(i, j: GLushort): PGLDVector3f;
procedure SetRadius(Value: GLfloat);
procedure SetHeight(Value: GLfloat);
procedure SetHeightSegs(Value: GLushort);
procedure SetCapSegs(Value: GLushort);
procedure SetSides(Value: GLushort);
procedure SetStartAngle(Value: GLfloat);
procedure SetSweepAngle(Value: GLfloat);
function GetParams: TGLDCylinderParams;
procedure SetParams(Value: TGLDCylinderParams);
protected
procedure CalcBoundingBox; override;
procedure CreateGeometry; override;
procedure DestroyGeometry; override;
procedure DoRender; override;
procedure SimpleRender; override;
public
constructor Create(AOwner: TPersistent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
class function SysClassType: TGLDSysClassType; override;
class function VisualObjectClassType: TGLDVisualObjectClass; override;
class function RealName: string; override;
procedure LoadFromStream(Stream: TStream); override;
procedure SaveToStream(Stream: TStream); override;
function CanConvertTo(_ClassType: TClass): GLboolean; override;
function ConvertTo(Dest: TPersistent): GLboolean; override;
function ConvertToTriMesh(Dest: TPersistent): GLboolean;
function ConvertToQuadMesh(Dest: TPersistent): GLboolean;
function ConvertToPolyMesh(Dest: TPersistent): GLboolean;
property Params: TGLDCylinderParams read GetParams write SetParams;
published
property Radius: GLfloat read FRadius write SetRadius;
property Height: GLfloat read FHeight write SetHeight;
property HeightSegs: GLushort read FHeightSegs write SetHeightSegs default GLD_CYLINDER_HEIGHTSEGS_DEFAULT;
property CapSegs: Glushort read FCapSegs write SetCapSegs default GLD_CYLINDER_CAPSEGS_DEFAULT;
property Sides: GLushort read FSides write SetSides default GLD_CYLINDER_SIDES_DEFAULT;
property StartAngle: GLfloat read FStartAngle write SetStartAngle;
property SweepAngle: GLfloat read FSweepAngle write SetSweepAngle;
end;
implementation
uses
SysUtils, GLDGizmos, GLDX, GLDMesh, GLDUtils;
var
vCylinderCounter: GLuint = 0;
constructor TGLDCylinder.Create(AOwner: TPersistent);
begin
inherited Create(AOwner);
Inc(vCylinderCounter);
FName := GLD_CYLINDER_STR + IntToStr(vCylinderCounter);
FRadius := GLD_STD_CYLINDERPARAMS.Radius;
FHeight := GLD_STD_CYLINDERPARAMS.Height;
FHeightSegs := GLD_STD_CYLINDERPARAMS.HeightSegs;
FCapSegs := GLD_STD_CYLINDERPARAMS.CapSegs;
FSides := GLD_STD_CYLINDERPARAMS.Sides;
FStartAngle := GLD_STD_CYLINDERPARAMS.StartAngle;
FSweepAngle := GLD_STD_CYLINDERPARAMS.SweepAngle;
FPosition.Vector3f := GLD_STD_PLANEPARAMS.Position;
FRotation.Params := GLD_STD_PLANEPARAMS.Rotation;
CreateGeometry;
end;
destructor TGLDCylinder.Destroy;
begin
inherited Destroy;
end;
procedure TGLDCylinder.Assign(Source: TPersistent);
begin
if (Source = nil) or (Source = Self) then Exit;
if not (Source is TGLDCylinder) then Exit;
inherited Assign(Source);
SetParams(TGLDCylinder(Source).GetParams);
end;
procedure TGLDCylinder.DoRender;
var
iSegs, iP: GLushort;
begin
for iSegs := 0 to FHeightSegs - 1 do
begin
glBegin(GL_QUAD_STRIP);
for iP := 2 to FSides + 2 do
begin
glNormal3fv(@FSideNormals^[iSegs * (FSides + 3) + iP]);
glVertex3fv(@FSidePoints^[iSegs * (FSides + 3) + iP]);
glNormal3fv(@FSideNormals^[(iSegs + 1) * (FSides + 3) + iP]);
glVertex3fv(@FSidePoints^[(iSegs + 1) * (FSides + 3) + iP]);
end;
glEnd;
end;
for iSegs := 0 to FCapSegs - 1 do
begin
glBegin(GL_QUAD_STRIP);
for iP := 2 to FSides + 2 do
begin
glNormal3fv(@FTopNormals^[iSegs * (FSides + 3) + iP]);
glVertex3fv(@FTopPoints^[iSegs * (FSides + 3) + iP]);
glNormal3fv(@FTopNormals^[(iSegs + 1) * (FSides + 3) + iP]);
glVertex3fv(@FTopPoints^[(iSegs + 1) * (FSides + 3) + iP]);
end;
glEnd;
glBegin(GL_QUAD_STRIP);
for iP := 2 to FSides + 2 do
begin
glNormal3fv(@FBottomNormals^[(iSegs + 1) * (FSides + 3) + iP]);
glVertex3fv(@FBottomPoints^[(iSegs + 1) * (FSides + 3) + iP]);
glNormal3fv(@FBottomNormals^[iSegs * (FSides + 3) + iP]);
glVertex3fv(@FBottomPoints^[iSegs * (FSides + 3) + iP]);
end;
glEnd;
end;
end;
procedure TGLDCylinder.SimpleRender;
var
iSegs, iP: GLushort;
begin
for iSegs := 0 to FHeightSegs - 1 do
begin
glBegin(GL_QUAD_STRIP);
for iP := 2 to FSides + 2 do
begin
glVertex3fv(@FSidePoints^[iSegs * (FSides + 3) + iP]);
glVertex3fv(@FSidePoints^[(iSegs + 1) * (FSides + 3) + iP]);
end;
glEnd;
end;
for iSegs := 0 to FCapSegs - 1 do
begin
glBegin(GL_QUAD_STRIP);
for iP := 2 to FSides + 2 do
begin
glVertex3fv(@FTopPoints^[iSegs * (FSides + 3) + iP]);
glVertex3fv(@FTopPoints^[(iSegs + 1) * (FSides + 3) + iP]);
end;
glEnd;
glBegin(GL_QUAD_STRIP);
for iP := 2 to FSides + 2 do
begin
glVertex3fv(@FBottomPoints^[(iSegs + 1) * (FSides + 3) + iP]);
glVertex3fv(@FBottomPoints^[iSegs * (FSides + 3) + iP]);
end;
glEnd;
end;
end;
procedure TGLDCylinder.CalcBoundingBox;
begin
FBoundingBox := GLDXCalcBoundingBox(
[GLDXVector3fArrayData(FSidePoints, (FSides + 1) * (FHeightSegs + 1)),
GLDXVector3fArrayData(FTopPoints, (FSides + 1) * FCapSegs + 1),
GLDXVector3fArrayData(FBottomPoints, (FSides + 1) * FCapSegs + 1)]);
end;
procedure TGLDCylinder.CreateGeometry;
var
iSegs, iP: GLushort;
A, R: GLfloat;
begin
if FHeightSegs < 1 then FHeightSegs := 1 else
if FHeightSegs > 1000 then FHeightSegs := 1000;
if FCapSegs < 1 then FCapSegs := 1 else
if FCapSegs > 1000 then FCapSegs := 1000;
ReallocMem(FSidePoints, (FSides + 3) * (FHeightSegs + 1) * SizeOf(TGLDVector3f));
ReallocMem(FSideNormals, (FSides + 3) * (FHeightSegs + 1) * SizeOf(TGLDVector3f));
ReallocMem(FTopPoints, ((FSides + 3) * (FCapSegs + 1)) * SizeOf(TGLDVector3f));
ReallocMem(FTopNormals, ((FSides + 3) * (FCapSegs + 1)) * SizeOf(TGLDVector3f));
ReallocMem(FBottomPoints, ((FSides + 3) * (FCapSegs + 1)) * SizeOf(TGLDVector3f));
ReallocMem(FBottomNormals, ((FSides + 3) * (FCapSegs + 1)) * SizeOf(TGLDVector3f));
A := GLDXGetAngleStep(FStartAngle, FSweepAngle, FSides);
R := FRadius / FCapSegs;
for iSegs := 0 to FHeightSegs do
for iP := 1 to FSides + 3 do
begin
FSidePoints^[iSegs * (FSides + 3) + iP] := GLDXVector3f(
GLDXCoSinus(StartAngle + (iP - 2) * A) * FRadius,
-(iSegs * (FHeight / FHeightSegs)) + (FHeight / 2),
-GLDXSinus(StartAngle + (iP - 2) * A) * FRadius);
end;
for iSegs := 0 to FCapSegs do
for iP := 1 to FSides + 3 do
begin
FTopPoints^[iSegs * (FSides + 3) + iP] := GLDXVector3f(
GLDXCoSinus(FStartAngle + (iP - 2) * A) * iSegs * R,
(FHeight / 2),
-GLDXSinus(FStartAngle + (iP - 2) * A) * iSegs * R);
FBottomPoints^[(iSegs * (FSides + 3)) + iP] :=
FTopPoints^[(iSegs * (FSides + 3)) + iP];
FBottomPoints^[(iSegs * (FSides + 3)) + iP].Y := -(FHeight / 2);
end;
FModifyList.ModifyPoints(
[GLDXVector3fArrayData(FSidePoints, (FSides + 3) * (FHeightSegs + 1)),
GLDXVector3fArrayData(FTopPoints, (FSides + 3) * (FCapSegs + 1)),
GLDXVector3fArrayData(FBottomPoints, (FSides + 3) * (FCapSegs + 1))]);
GLDXCalcQuadPatchNormals(GLDXQuadPatchData3f(
GLDXVector3fArrayData(FSidePoints, (FHeightSegs + 1) * (FSides + 3)),
GLDXVector3fArrayData(FSideNormals, (FHeightSegs + 1) * (FSides + 3)),
FHeightSegs, FSides + 2));
if FCapSegs > 1 then
begin
GLDXCalcQuadPatchNormals(GLDXQuadPatchData3f(
GLDXVector3fArrayData(FTopPoints, (FCapSegs + 1) * (FSides + 3)),
GLDXVector3fArrayData(FTopNormals, (FCapSegs + 1) * (FSides + 3)),
FCapSegs, FSides + 2));
GLDXCalcQuadPatchNormals(GLDXQuadPatchData3f(
GLDXVector3fArrayData(FBottomPoints, (FCapSegs + 1) * (FSides + 3)),
GLDXVector3fArrayData(FBottomNormals, (FCapSegs + 1) * (FSides + 3)),
FCapSegs, FSides + 2));
for iP := 1 to (FCapSegs + 1) * (FSides + 3) do
FBottomNormals^[iP] := GLDXVectorNeg(FBottomNormals^[iP]);
end;
CalcBoundingBox;
end;
procedure TGLDCylinder.DestroyGeometry;
begin
if FSidePoints <> nil then ReallocMem(FSidePoints, 0);
if FTopPoints <>nil then ReallocMem(FTopPoints, 0);
if FBottomPoints <> nil then ReallocMem(FBottomPoints, 0);
if FSideNormals <> nil then ReallocMem(FSideNormals, 0);
if FTopNormals <> nil then ReallocMem(FTopNormals, 0);
if FBottomNormals <> nil then ReallocMem(FBottomNormals, 0);
FSidePoints := nil; FTopPoints := nil; FBottomPoints := nil;
FSideNormals := nil; FTopNormals := nil; FBottomNormals := nil;
end;
class function TGLDCylinder.SysClassType: TGLDSysClassType;
begin
Result := GLD_SYSCLASS_CYLINDER;
end;
class function TGLDCylinder.VisualObjectClassType: TGLDVisualObjectClass;
begin
Result := TGLDCylinder;
end;
class function TGLDCylinder.RealName: string;
begin
Result := GLD_CYLINDER_STR;
end;
procedure TGLDCylinder.LoadFromStream(Stream: TStream);
begin
inherited LoadFromStream(Stream);
Stream.Read(FRadius, SizeOf(GLfloat));
Stream.Read(FHeight, SizeOf(GLfloat));
Stream.Read(FHeightSegs, SizeOf(GLushort));
Stream.Read(FCapSegs, SizeOf(GLushort));
Stream.Read(FSides, SizeOf(GLushort));
Stream.Read(FStartAngle, SizeOf(GLfloat));
Stream.Read(FSweepAngle, SizeOf(GLfloat));
CreateGeometry;
end;
procedure TGLDCylinder.SaveToStream(Stream: TStream);
begin
inherited SaveToStream(Stream);
Stream.Write(FRadius, SizeOf(GLfloat));
Stream.Write(FHeight, SizeOf(GLfloat));
Stream.Write(FHeightSegs, SizeOf(GLushort));
Stream.Write(FCapSegs, SizeOf(GLushort));
Stream.Write(FSides, SizeOf(GLushort));
Stream.Write(FStartAngle, SizeOf(GLfloat));
Stream.Write(FSweepAngle, SizeOf(GLfloat));
end;
function TGLDCylinder.CanConvertTo(_ClassType: TClass): GLboolean;
begin
Result := (_ClassType = TGLDCylinder) or
(_ClassType = TGLDTriMesh) or
(_ClassType = TGLDQuadMesh) or
(_ClassType = TGLDPolyMesh);
end;
{$WARNINGS OFF}
function TGLDCylinder.ConvertTo(Dest: TPersistent): GLboolean;
begin
Result := False;
if not Assigned(Dest) then Exit;
if Dest.ClassType = Self.ClassType then
begin
Dest.Assign(Self);
Result := True;
end else
if Dest is TGLDTriMesh then
Result := ConvertToTriMesh(Dest) else
if Dest is TGLDQuadMesh then
Result := ConvertToQuadMesh(Dest) else
if Dest is TGLDPolyMesh then
Result := ConvertToPolyMesh(Dest);
end;
function TGLDCylinder.ConvertToTriMesh(Dest: TPersistent): GLboolean;
var
M: GLubyte;
PC: GLuint;
Offset: array[1..2] of GLuint;
si, i, j: GLushort;
F: TGLDTriFace;
begin
Result := False;
if not Assigned(Dest) then Exit;
if not (Dest is TGLDTriMesh) then Exit;
M := GetMode;
case M of
0: PC := 2 + 2 * FSides * FCapSegs + (FHeightSegs + 1) * FSides;
1: PC := 2 + 2 * (FSides + 1) * FCapSegs + (FHeightSegs + 1) * (FSides + 1);
end;
with TGLDTriMesh(Dest) do
begin
DeleteVertices;
VertexCapacity := PC;
F.Smoothing := GLD_SMOOTH_ALL;
if M = 0 then
begin
Offset[1] := (FHeightSegs + 1) * FSides;
Offset[2] := Offset[1] + 1 + FSides * FCapSegs;
for i := 1 to FHeightSegs + 1 do
for j := 1 to FSides do
AddVertex(GetSidePoint(i, j)^, True);
AddVertex(GetTopPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := 1 to FSides do
AddVertex(GetTopPoint(i + 1, j)^, True);
AddVertex(GetBottomPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := FSides downto 1 do
AddVertex(GetBottomPoint(i + 1, j)^, True);
for i := 1 to FHeightSegs do
for j := 1 to FSides do
begin
F.Point1 := (i - 1) * FSides + j;
F.Point2 := i * FSides + j;
if j = FSides then
F.Point3 := (i - 1) * FSides + 1
else F.Point3 := (i - 1) * FSides + j + 1;
AddFace(F);
F.Point2 := i * FSides + j;
if j = FSides then
begin
F.Point1 := (i - 1) * FSides + 1;
F.Point3 := i * FSides + 1;
end else
begin
F.Point1 := (i - 1) * FSides + j + 1;
F.Point3 := i * FSides + j + 1;
end;
AddFace(F);
end;
for si := 1 to 2 do
begin
for j := 1 to FSides do
begin
F.Point1 := Offset[si] + 1;
F.Point2 := Offset[si] + j + 1;
if j = FSides then
F.Point3 := Offset[si] + 2
else F.Point3 := Offset[si] + j + 2;
AddFace(F);
end;
if FCapSegs > 1 then
begin
for i := 0 to FCapSegs - 2 do
for j := 1 to FSides do
begin
F.Point1 := Offset[si] + 1 + i * FSides + j;
F.Point2 := Offset[si] + 1 + (i + 1) * FSides + j;
if j = FSides then
F.Point3 := Offset[si] + 1 + i * FSides + 1
else F.Point3 := Offset[si] + 1 + i * FSides + j + 1;
AddFace(F);
F.Point2 := Offset[si] + 1 + (i + 1) * FSides + j;
if j = FSides then
begin
F.Point1 := Offset[si] + 1 + i * FSides + 1;
F.Point3 := Offset[si] + 1 + (i + 1) * FSides + 1;
end else
begin
F.Point1 := Offset[si] + 1 + i * FSides + j + 1;
F.Point3 := Offset[si] + 1 + (i + 1) * FSides + j + 1;
end;
AddFace(F);
end;
end;
end;
end else
if M = 1 then
begin
Offset[1] := (FHeightSegs + 1) * (FSides + 1);
Offset[2] := Offset[1] + 1 + FCapSegs * (FSides + 1);
for i := 1 to FHeightSegs + 1 do
for j := 1 to FSides + 1 do
AddVertex(GetSidePoint(i, j)^, True);
AddVertex(GetTopPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := 1 to FSides + 1 do
AddVertex(GetTopPoint(i + 1, j)^, True);
AddVertex(GetBottomPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := FSides + 1 downto 1 do
AddVertex(GetBottomPoint(i + 1, j)^, True);
for i := 1 to FHeightSegs do
for j := 1 to FSides do
begin
F.Point1 := (i - 1) * (FSides + 1) + j;
F.Point2 := i * (FSides + 1) + j;
F.Point3 := (i - 1) * (FSides + 1) + j + 1;
AddFace(F);
F.Point1 := (i - 1) * (FSides + 1) + j + 1;
F.Point2 := i * (FSides + 1) + j;
F.Point3 := i * (FSides + 1) + j + 1;
AddFace(F);
end;
for si := 1 to 2 do
begin
for j := 1 to FSides do
begin
F.Point1 := Offset[si] + 1;
F.Point2 := Offset[si] + 1 + j;
F.Point3 := Offset[si] + 1 + j + 1;
AddFace(F);
end;
if FCapSegs > 1 then
begin
for i := 0 to FCapSegs - 2 do
for j := 1 to FSides do
begin
F.Point1 := Offset[si] + 1 + i * (FSides + 1) + j;
F.Point2 := Offset[si] + 1 + (i + 1) * (FSides + 1) + j;
F.Point3 := Offset[si] + 1 + i * (FSides + 1) + j + 1;
AddFace(F);
F.Point1 := Offset[si] + 1 + i * (FSides + 1) + j + 1;
F.Point2 := Offset[si] + 1 + (i + 1) * (FSides + 1) + j;
F.Point3 := Offset[si] + 1 + (i + 1) * (FSides + 1) + j + 1;
AddFace(F);
end;
end;
end;
end;
CalcNormals;
CalcBoundingBox;
PGLDColor4f(Color.GetPointer)^ := Self.FColor.Color4f;
PGLDVector4f(Position.GetPointer)^ := Self.FPosition.Vector4f;
PGLDRotation3D(Rotation.GetPointer)^ := Self.FRotation.Params;
TGLDTriMesh(Dest).Selected := Self.Selected;
TGLDTriMesh(Dest).Name := Self.Name;
end;
Result := True;
end;
function TGLDCylinder.ConvertToQuadMesh(Dest: TPersistent): GLboolean;
var
M: GLubyte;
PC: GLuint;
Offset: array[1..2] of GLuint;
si, i, j: GLushort;
F: TGLDQuadFace;
begin
Result := False;
if not Assigned(Dest) then Exit;
if not (Dest is TGLDQuadMesh) then Exit;
M := GetMode;
case M of
0: PC := 2 + 2 * FSides * FCapSegs + (FHeightSegs + 1) * FSides;
1: PC := 2 + 2 * (FSides + 1) * FCapSegs + (FHeightSegs + 1) * (FSides + 1);
end;
with TGLDQuadMesh(Dest) do
begin
DeleteVertices;
VertexCapacity := PC;
F.Smoothing := GLD_SMOOTH_ALL;
if M = 0 then
begin
Offset[1] := (FHeightSegs + 1) * FSides;
Offset[2] := Offset[1] + 1 + FSides * FCapSegs;
for i := 1 to FHeightSegs + 1 do
for j := 1 to FSides do
AddVertex(GetSidePoint(i, j)^, True);
AddVertex(GetTopPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := 1 to FSides do
AddVertex(GetTopPoint(i + 1, j)^, True);
AddVertex(GetBottomPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := FSides downto 1 do
AddVertex(GetBottomPoint(i + 1, j)^, True);
for i := 1 to FHeightSegs do
for j := 1 to FSides do
begin
F.Point1 := (i - 1) * FSides + j;
F.Point2 := i * FSides + j;
if j = FSides then
begin
F.Point3 := i * FSides + 1;
F.Point4 := (i - 1) * FSides + 1;
end else
begin
F.Point3 := i * FSides + j + 1;
F.Point4 := (i - 1) * FSides + j + 1;
end;
AddFace(F);
end;
for si := 1 to 2 do
begin
for j := 1 to FSides do
begin
F.Point1 := Offset[si] + 1;
F.Point2 := Offset[si] + j + 1;
if j = FSides then
F.Point3 := Offset[si] + 2
else F.Point3 := Offset[si] + j + 2;
F.Point4 := F.Point1;
AddFace(F);
end;
if FCapSegs > 1 then
begin
for i := 0 to FCapSegs - 2 do
for j := 1 to FSides do
begin
F.Point1 := Offset[si] + 1 + i * FSides + j;
F.Point2 := Offset[si] + 1 + (i + 1) * FSides + j;
if j = FSides then
begin
F.Point3 := Offset[si] + 1 + (i + 1) * FSides + 1;
F.Point4 := Offset[si] + 1 + i * FSides + 1;
end else
begin
F.Point3 := Offset[si] + 1 + (i + 1) * FSides + j + 1;
F.Point4 := Offset[si] + 1 + i * FSides + j + 1;
end;
AddFace(F);
end;
end;
end;
end else
if M = 1 then
begin
Offset[1] := (FHeightSegs + 1) * (FSides + 1);
Offset[2] := Offset[1] + 1 + FCapSegs * (FSides + 1);
for i := 1 to FHeightSegs + 1 do
for j := 1 to FSides + 1 do
AddVertex(GetSidePoint(i, j)^, True);
AddVertex(GetTopPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := 1 to FSides + 1 do
AddVertex(GetTopPoint(i + 1, j)^, True);
AddVertex(GetBottomPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := FSides + 1 downto 1 do
AddVertex(GetBottomPoint(i + 1, j)^, True);
for i := 1 to FHeightSegs do
for j := 1 to FSides do
begin
F.Point1 := (i - 1) * (FSides + 1) + j;
F.Point2 := i * (FSides + 1) + j;
F.Point3 := i * (FSides + 1) + j + 1;
F.Point4 := (i - 1) * (FSides + 1) + j + 1;
AddFace(F);
end;
for si := 1 to 2 do
begin
for j := 1 to FSides do
begin
F.Point1 := Offset[si] + 1;
F.Point2 := Offset[si] + 1 + j;
F.Point3 := Offset[si] + 1 + j + 1;
F.Point4 := F.Point1;
AddFace(F);
end;
if FCapSegs > 1 then
begin
for i := 0 to FCapSegs - 2 do
for j := 1 to FSides do
begin
F.Point1 := Offset[si] + 1 + i * (FSides + 1) + j;
F.Point2 := Offset[si] + 1 + (i + 1) * (FSides + 1) + j;
F.Point3 := Offset[si] + 1 + (i + 1) * (FSides + 1) + j + 1;
F.Point4 := Offset[si] + 1 + i * (FSides + 1) + j + 1;
AddFace(F);
end;
end;
end;
end;
CalcNormals;
CalcBoundingBox;
PGLDColor4f(Color.GetPointer)^ := Self.FColor.Color4f;
PGLDVector4f(Position.GetPointer)^ := Self.FPosition.Vector4f;
PGLDRotation3D(Rotation.GetPointer)^ := Self.FRotation.Params;
TGLDQuadMesh(Dest).Selected := Self.Selected;
TGLDQuadMesh(Dest).Name := Self.Name;
end;
Result := True;
end;
function TGLDCylinder.ConvertToPolyMesh(Dest: TPersistent): GLboolean;
var
M: GLubyte;
PC: GLuint;
Offset: array[1..2] of GLuint;
si, i, j: GLushort;
P: TGLDPolygon;
begin
Result := False;
if not Assigned(Dest) then Exit;
if not (Dest is TGLDPolyMesh) then Exit;
M := GetMode;
case M of
0: PC := 2 + 2 * FSides * FCapSegs + (FHeightSegs + 1) * FSides;
1: PC := 2 + 2 * (FSides + 1) * FCapSegs + (FHeightSegs + 1) * (FSides + 1);
end;
with TGLDPolyMesh(Dest) do
begin
DeleteVertices;
VertexCapacity := PC;
if M = 0 then
begin
Offset[1] := (FHeightSegs + 1) * FSides;
Offset[2] := Offset[1] + 1 + FSides * FCapSegs;
for i := 1 to FHeightSegs + 1 do
for j := 1 to FSides do
AddVertex(GetSidePoint(i, j)^, True);
AddVertex(GetTopPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := 1 to FSides do
AddVertex(GetTopPoint(i + 1, j)^, True);
AddVertex(GetBottomPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := FSides downto 1 do
AddVertex(GetBottomPoint(i + 1, j)^, True);
for i := 1 to FHeightSegs do
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 4);
P.Data^[1] := (i - 1) * FSides + j;
P.Data^[2] := i * FSides + j;
if j = FSides then
begin
P.Data^[3] := i * FSides + 1;
P.Data^[4] := (i - 1) * FSides + 1;
end else
begin
P.Data^[3] := i * FSides + j + 1;
P.Data^[4] := (i - 1) * FSides + j + 1;
end;
AddFace(P);
end;
for si := 1 to 2 do
begin
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 3);
P.Data^[1] := Offset[si] + 1;
P.Data^[2] := Offset[si] + j + 1;
if j = FSides then
P.Data^[3] := Offset[si] + 2
else P.Data^[3] := Offset[si] + j + 2;
//F.Point4 := F.Point1;
AddFace(P);
end;
if FCapSegs > 1 then
begin
for i := 0 to FCapSegs - 2 do
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 4);
P.Data^[1] := Offset[si] + 1 + i * FSides + j;
P.Data^[2] := Offset[si] + 1 + (i + 1) * FSides + j;
if j = FSides then
begin
P.Data^[3] := Offset[si] + 1 + (i + 1) * FSides + 1;
P.Data^[4] := Offset[si] + 1 + i * FSides + 1;
end else
begin
P.Data^[3] := Offset[si] + 1 + (i + 1) * FSides + j + 1;
P.Data^[4] := Offset[si] + 1 + i * FSides + j + 1;
end;
AddFace(P);
end;
end;
end;
end else
if M = 1 then
begin
Offset[1] := (FHeightSegs + 1) * (FSides + 1);
Offset[2] := Offset[1] + 1 + FCapSegs * (FSides + 1);
for i := 1 to FHeightSegs + 1 do
for j := 1 to FSides + 1 do
AddVertex(GetSidePoint(i, j)^, True);
AddVertex(GetTopPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := 1 to FSides + 1 do
AddVertex(GetTopPoint(i + 1, j)^, True);
AddVertex(GetBottomPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := FSides + 1 downto 1 do
AddVertex(GetBottomPoint(i + 1, j)^, True);
for i := 1 to FHeightSegs do
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 4);
P.Data^[1] := (i - 1) * (FSides + 1) + j;
P.Data^[2] := i * (FSides + 1) + j;
P.Data^[3] := i * (FSides + 1) + j + 1;
P.Data^[4] := (i - 1) * (FSides + 1) + j + 1;
AddFace(P);
end;
for si := 1 to 2 do
begin
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 3);
P.Data^[1] := Offset[si] + 1;
P.Data^[2] := Offset[si] + 1 + j;
P.Data^[3] := Offset[si] + 1 + j + 1;
//F.Point4 := F.Point1;
AddFace(P);
end;
if FCapSegs > 1 then
begin
for i := 0 to FCapSegs - 2 do
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 4);
P.Data^[1] := Offset[si] + 1 + i * (FSides + 1) + j;
P.Data^[2] := Offset[si] + 1 + (i + 1) * (FSides + 1) + j;
P.Data^[3] := Offset[si] + 1 + (i + 1) * (FSides + 1) + j + 1;
P.Data^[4] := Offset[si] + 1 + i * (FSides + 1) + j + 1;
AddFace(P);
end;
end;
end;
end;
CalcNormals;
CalcBoundingBox;
PGLDColor4f(Color.GetPointer)^ := Self.FColor.Color4f;
PGLDVector4f(Position.GetPointer)^ := Self.FPosition.Vector4f;
PGLDRotation3D(Rotation.GetPointer)^ := Self.FRotation.Params;
TGLDPolyMesh(Dest).Selected := Self.Selected;
TGLDPolyMesh(Dest).Name := Self.Name;
end;
Result := True;
end;
{$WARNINGS ON}
function TGLDCylinder.GetMode: GLubyte;
begin
if GLDXGetAngle(FStartAngle, FSweepAngle) = 360 then
Result := 0
else Result := 1;
end;
function TGLDCylinder.GetSidePoint(i, j: GLushort): PGLDVector3f;
begin
Result := @FSidePoints^[(i - 1) * (FSides + 3) + j + 1];
end;
function TGLDCylinder.GetTopPoint(i, j: GLushort): PGLDVector3f;
begin
Result := @FTopPoints^[(i - 1) * (FSides + 3) + j + 1];
end;
function TGLDCylinder.GetBottomPoint(i, j: GLushort): PGLDVector3f;
begin
Result := @FBottomPoints^[(i - 1) * (FSides + 3) + j + 1];
end;
procedure TGLDCylinder.SetRadius(Value: GLfloat);
begin
if FRadius = Value then Exit;
FRadius := Value;
CreateGeometry;
Change;
end;
procedure TGLDCylinder.SetHeight(Value: GLfloat);
begin
if FHeight = Value then Exit;
FHeight := Value;
CreateGeometry;
Change;
end;
procedure TGLDCylinder.SetHeightSegs(Value: GLushort);
begin
if FHeightSegs = Value then Exit;
FHeightSegs := Value;
CreateGeometry;
Change;
end;
procedure TGLDCylinder.SetCapSegs(Value: GLushort);
begin
if FCapSegs = Value then Exit;
FCapSegs := Value;
CreateGeometry;
Change;
end;
procedure TGLDCylinder.SetSides(Value: GLushort);
begin
if FSides = Value then Exit;
FSides := Value;
CreateGeometry;
Change;
end;
procedure TGLDCylinder.SetStartAngle(Value: GLfloat);
begin
if FStartAngle = Value then Exit;
FStartAngle := Value;
CreateGeometry;
Change;
end;
procedure TGLDCylinder.SetSweepAngle(Value: GLfloat);
begin
if FSweepAngle = Value then Exit;
FSweepAngle := Value;
CreateGeometry;
Change;
end;
function TGLDCylinder.GetParams: TGLDCylinderParams;
begin
Result := GLDXCylinderParams(FColor.Color3ub, FRadius, FHeight,
FHeightSegs, FCapSegs, FSides, FStartAngle, FSweepAngle,
FPosition.Vector3f, FRotation.Params);
end;
procedure TGLDCylinder.SetParams(Value: TGLDCylinderParams);
begin
if GLDXCylinderParamsEqual(GetParams, Value) then Exit;
PGLDColor3f(FColor.GetPointer)^ := GLDXColor3f(Value.Color);
FRadius := Value.Radius;
FHeight := Value.Height;
FHeightSegs := Value.HeightSegs;
FCapSegs := Value.CapSegs;
FSides := Value.Sides;
FStartAngle := Value.StartAngle;
FSweepAngle := Value.SweepAngle;
PGLDVector3f(FPosition.GetPointer)^ := Value.Position;
PGLDRotation3D(FRotation.GetPointer)^ := Value.Rotation;
CreateGeometry;
Change;
end;
end.
|
unit uDuck;
interface
uses
uFly, uQuack, Windows;
type
TDuck=class
protected
FlyBehavior:IFlyBehavior;
QuackBehavior:IQuackBehavior;
public
procedure PerformQuack;
procedure Swim;
procedure Display;virtual;abstract;
procedure PerformFly;
procedure SetFlyBehavior(FB:IFlyBehavior);
procedure SetQuackBehavior(QB:IQuackBehavior);
end;
TMallardDuck=class(TDuck)
public
constructor Create;
procedure Display;override;
end;
TModelDuck=class(TDuck)
public
constructor Create;
procedure Display;override;
end;
implementation
{ TDuck }
procedure TDuck.PerformFly;
begin
FlyBehavior.Fly;
end;
procedure TDuck.PerformQuack;
begin
QuackBehavior.Quack;
end;
procedure TDuck.SetFlyBehavior(FB: IFlyBehavior);
begin
FlyBehavior:=FB;
end;
procedure TDuck.SetQuackBehavior(QB: IQuackBehavior);
begin
QuackBehavior:=QB;
end;
procedure TDuck.Swim;
begin
MessageBox(0,'All ducks float, even decoys!', 'Duck!', MB_OK);
end;
{ TMallardDuck }
constructor TMallardDuck.Create;
begin
QuackBehavior:=TQuack.Create;
FlyBehavior:=TFlyWithWings.Create;
end;
procedure TMallardDuck.Display;
begin
MessageBox(0,'I`m a real Mallard duck', 'Mallard Duck!', MB_OK);
end;
{ TModelDuck }
constructor TModelDuck.Create;
begin
FlyBehavior:=TFlyNoWay.Create;
QuackBehavior:=TQuack.Create;
end;
procedure TModelDuck.Display;
begin
MessageBox(0,'I`m a model duck', 'Model Duck!', MB_OK);
end;
end.
|
{: GLHiddenLineShader<p>
A shader that renders hidden (back-faced) lines differently from visible
(front) lines. Polygon offset is used to displace fragments depths a little
so that there is no z-fighting in rendering the same geometry multiple times.<p>
<b>History : </b><font size=-1><ul>
<li>05/03/10 - DanB - More state added to TGLStateCache
<li>06/06/07 - DaStr - Added $I GLScene.inc
Added GLColor to uses (BugtrackerID = 1732211)
<li>25/02/07 - DaStr - Moved registration to GLSceneRegister.pas
<li>25/09/04 - NelC - Fixed bug of disabled blend (thx Carlos)
<li>05/02/04 - NelC - Fixed memory leak in TGLHiddenLineShader.Destroy (thx Achim Hammes)
<li>13/12/03 - NelC - Added SurfaceLit, ShadeModel
<li>05/12/03 - NelC - Added ForceMaterial
<li>03/12/03 - NelC - Creation. Modified from the HiddenLineShader in
the multipass demo.
</ul></font>
}
unit GLHiddenLineShader;
interface
{$I GLScene.inc}
uses
Classes, GLMaterial, OpenGL1x, OpenGLTokens, GLCrossPlatform, GLScene, GLColor,
GLBaseClasses, GLRenderContextInfo, GLState;
type
TGLLineSettings = class(TGLUpdateAbleObject)
private
{ Private Declarations }
FColor : TGLColor;
FWidth : Single;
FPattern : TGLushort;
FForceMaterial : Boolean;
procedure SetPattern(const value: TGLushort);
procedure SetColor(const v : TGLColor);
procedure SetWidth(const Value: Single);
procedure SetForceMaterial(v : boolean);
public
{ Public Declarations }
constructor Create(AOwner: TPersistent); override;
destructor Destroy; override;
procedure Apply(var rci : TRenderContextInfo);
procedure UnApply(var rci : TRenderContextInfo);
published
{ Published Declarations }
property Width : Single read FWidth write SetWidth;
property Color : TGLColor read FColor write SetColor;
property Pattern : TGLushort read FPattern write SetPattern default $FFFF;
{: Set ForceMaterial to true to enforce the application of the line settings
for objects that sets their own color, line width and pattern. }
property ForceMaterial : Boolean read FForceMaterial write SetForceMaterial default false;
end;
TGLHiddenLineShader = class(TGLShader)
private
FPassCount : integer;
FLineSmooth : Boolean;
FSolid : Boolean;
FBackGroundColor : TGLColor;
FFrontLine : TGLLineSettings;
FBackLine : TGLLineSettings;
FLighting : Boolean;
FShadeModel : TGLShadeModel;
procedure SetlineSmooth(v : boolean);
procedure SetSolid(v : boolean);
procedure SetBackgroundColor(AColor: TGLColor);
procedure SetLighting(v : boolean);
procedure SetShadeModel(const val : TGLShadeModel);
protected
procedure DoApply(var rci : TRenderContextInfo; Sender : TObject); override;
function DoUnApply(var rci : TRenderContextInfo) : Boolean; override;
public
{ Public Declarations }
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
published
{ Published Declarations }
property FrontLine : TGLLineSettings read FFrontLine write FFrontLine;
property BackLine : TGLLineSettings read FBackLine write FBackLine;
{: Line smoothing control }
property LineSmooth : Boolean read FlineSmooth write SetlineSmooth default false;
{: Solid controls if you can see through the front-line wireframe. }
property Solid : Boolean read FSolid write SetSolid default false;
{: Color used for solid fill. }
property BackgroundColor: TGLColor read FBackgroundColor write SetBackgroundColor;
{: When Solid is True, determines if lighting or background color is used. }
property SurfaceLit : Boolean read FLighting write SetLighting default true;
{: Shade model.<p>
Default is "Smooth".<p> }
property ShadeModel : TGLShadeModel read FShadeModel write SetShadeModel default smDefault;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------
// ------------------ TGLLineSettings ------------------
// ------------------
// Create
//
constructor TGLLineSettings.Create(AOwner: TPersistent);
begin
inherited;
FColor:=TGLColor.Create(Self);
FColor.Initialize(clrGray20);
FWidth:=2;
Pattern:=$FFFF;
ForceMaterial:=false;
end;
// Destroy
//
destructor TGLLineSettings.Destroy;
begin
FColor.Free;
inherited;
end;
// SetPattern
//
procedure TGLLineSettings.SetPattern(const value: TGLushort);
begin
if FPattern<>value then begin
FPattern:=Value;
NotifyChange(self);
end;
end;
// SetColor
//
procedure TGLLineSettings.SetColor(const v: TGLColor);
begin
FColor.Color:=v.Color;
NotifyChange(Self);
end;
// SetWidth
//
procedure TGLLineSettings.SetWidth(const Value: Single);
begin
FWidth := Value;
NotifyChange(Self);
end;
var IgnoreMatSave : boolean;
// Apply
//
procedure TGLLineSettings.Apply(var rci : TRenderContextInfo);
begin
rci.GLStates.LineWidth := Width;
glColor4fv(Color.AsAddress);
if Pattern<>$FFFF then begin
rci.GLStates.Enable(stLineStipple);
glLineStipple(1, Pattern);
end
else
rci.GLStates.Disable(stLineStipple);
if ForceMaterial then begin
IgnoreMatSave:=rci.ignoreMaterials;
rci.ignoreMaterials:=true;
end;
end;
// UnApply
//
procedure TGLLineSettings.UnApply(var rci : TRenderContextInfo);
begin
if ForceMaterial then rci.ignoreMaterials:=IgnoreMatSave;
end;
// SetForceMaterial
//
procedure TGLLineSettings.SetForceMaterial(v: boolean);
begin
if FForceMaterial<>v then begin
FForceMaterial:=v;
NotifyChange(self);
end;
end;
// ------------------
// ------------------ TGLHiddenLineShader ------------------
// ------------------
// Create
//
constructor TGLHiddenLineShader.Create(AOwner : TComponent);
begin
inherited;
FFrontLine := TGLLineSettings.Create(self);
FBackLine := TGLLineSettings.Create(self);
FSolid:=false;
FBackgroundColor:=TGLColor.Create(Self);
FBackgroundColor.Initialize(clrBtnFace);
FLineSmooth:=False;
FLighting:=true;
FShadeModel:=smDefault;
end;
// Destroy
//
destructor TGLHiddenLineShader.Destroy;
begin
FFrontLine.Free;
FBackLine.Free;
FBackgroundColor.Free;
inherited;
end;
// DoApply
//
procedure TGLHiddenLineShader.DoApply(var rci: TRenderContextInfo; Sender : TObject);
begin
FPassCount:=1;
rci.GLStates.PushAttrib([sttEnable, sttCurrent, sttPolygon, sttHint,
sttDepthBuffer, sttLine, sttLighting]);
if solid then begin
// draw filled front faces in first pass
rci.GLStates.PolygonMode := pmFill;
rci.GLStates.CullFaceMode := cmBack;
if FLighting then begin
case ShadeModel of
smDefault, smSmooth : glShadeModel(GL_SMOOTH);
smFlat : glShadeModel(GL_FLAT);
end
end
else
begin
rci.GLStates.Disable(stLighting);
glColor4fv(FBackgroundColor.AsAddress); // use background color
end;
// enable and adjust polygon offset
rci.GLStates.Enable(stPolygonOffsetFill);
end
else begin
rci.GLStates.Disable(stLighting);
// draw back lines in first pass
FBackLine.Apply(rci);
rci.GLStates.CullFaceMode := cmFront;
rci.GLStates.PolygonMode := pmLines;
// enable and adjust polygon offset
rci.GLStates.Enable(stPolygonOffsetLine);
end;
rci.GLStates.SetPolygonOffset(1, 2);
end;
// DoUnApply
//
function TGLHiddenLineShader.DoUnApply(var rci: TRenderContextInfo): Boolean;
procedure SetLineSmoothBlend;
begin
if LineSmooth then begin
rci.GLStates.LineSmoothHint := hintNicest;
rci.GLStates.Enable(stLineSmooth);
end else begin
rci.GLStates.Disable(stLineSmooth);
end;
if LineSmooth or (FBackLine.FColor.Alpha<1) or (FFrontLine.FColor.Alpha<1) then begin
rci.GLStates.Enable(stBlend);
rci.GLStates.SetBlendFunc(bfSrcAlpha, bfOneMinusSrcAlpha);
end else begin
rci.GLStates.Disable(stBlend);
end;
end;
begin
case FPassCount of
1 : begin
// draw front line in 2nd pass
FPassCount:=2;
FBackLine.UnApply(rci);
FFrontLine.Apply(rci);
SetLineSmoothBlend;
if solid and FLighting then
rci.GLStates.Disable(stLighting);
rci.GLStates.PolygonMode := pmLines;
rci.GLStates.CullFaceMode := cmBack;
if solid then
rci.GLStates.Disable(stPolygonOffsetFill)
else
rci.GLStates.Disable(stPolygonOffsetLine);
Result:=True;
end;
2 : begin
FFrontLine.UnApply(rci);
rci.GLStates.PopAttrib;
Result:=false;
end;
else
Assert(False);
Result:=False;
end;
end;
// SetBackgroundColor
//
procedure TGLHiddenLineShader.SetBackgroundColor(AColor: TGLColor);
begin
FBackgroundColor.Color:=AColor.Color;
NotifyChange(Self);
end;
// SetlineSmooth
//
procedure TGLHiddenLineShader.SetlineSmooth(v: boolean);
begin
if FlineSmooth<>v then begin
FlineSmooth:=v;
NotifyChange(self);
end;
end;
// SetLighting
//
procedure TGLHiddenLineShader.SetLighting(v: boolean);
begin
if FLighting<>v then begin
FLighting:=v;
NotifyChange(self);
end;
end;
// SetSolid
//
procedure TGLHiddenLineShader.SetSolid(v: boolean);
begin
if FSolid<>v then begin
FSolid:=v;
NotifyChange(self);
end;
end;
// SetShadeModel
//
procedure TGLHiddenLineShader.SetShadeModel(const val : TGLShadeModel);
begin
if FShadeModel<>val then begin
FShadeModel:=val;
NotifyChange(Self);
end;
end;
end.
|
unit DSA.List_Stack_Queue.QueueCompare;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
DSA.Interfaces.DataStructure,
DSA.List_Stack_Queue.ArrayListQueue,
DSA.List_Stack_Queue.LoopListQueue,
DSA.List_Stack_Queue.LinkedListQueue;
procedure Main;
implementation
function testTime(q: specialize IQueue<integer>; opCount: integer): string;
var
startTime, endTime: cardinal;
i: integer;
begin
Randomize;
startTime := TThread.GetTickCount64;
for i := 0 to opCount - 1 do
q.EnQueue(Random(integer.MaxValue));
for i := 0 to opCount - 1 do
q.DeQueue;
endTime := TThread.GetTickCount64;
Result := FloatToStr((endTime - startTime) / 1000);
end;
type
TArrayListQueue_int = specialize TArrayListQueue<integer>;
TLoopListQueue_int = specialize TLoopListQueue<integer>;
TLinkedListQueue_int = specialize TLinkedListQueue<integer>;
procedure Main;
var
ArrayQueue: TArrayListQueue_int;
LoopQueue: TLoopListQueue_int;
LinkedListQueue: TLinkedListQueue_int;
vTime: string;
opCount: integer;
begin
opCount := 1000000;
ArrayQueue := TArrayListQueue_int.Create();
vTime := testTime(ArrayQueue, opCount);
Writeln('ArrayQueue, time: ' + vTime + ' s');
LoopQueue := TLoopListQueue_int.Create();
vTime := testTime(LoopQueue, opCount);
Writeln('LoopQueue, time: ' + vTime + ' s');
LinkedListQueue := TLinkedListQueue_int.Create();
vTime := testTime(LinkedListQueue, opCount);
Writeln('LinkedlistQueue, time: ' + vTime + ' s');
end;
end.
|
unit User;
interface
uses Windows, Messages, SysUtils, Classes, IBQuery, IBSQL, IBDatabase, Db, IBStoredProc,
Dbun, Variants, Dialogs;
type
TUser = class(TDbunObject)
private
FUserName: string;
FUserFullName: string;
FPassword: string;
FPasswordHash: string;
FUserID: Integer;
FUserIDExt: Integer;
FNote :string;
FEMAIL : string;
public
FUseMD5 : Boolean;
property UserName: string read FUserName write FUserName;
property UserFullName: string read FUserFullName write FUserFullName;
property UserID: Integer read FUserID write FUserID;
property Password: string read FPassword write FPassword;
property UserIDExt: Integer read FUserIDExt write FUserIDExt;
property Note:String read FNote write FNote;
property EMAIL:String read FEMAIL write FEMAIL;
function FillDataBy(KeyValue: Variant): Boolean; override;
function FillDataByAuth(Name, Passwd: string): Boolean;
function Insert: Boolean; override;
function Update: Boolean; override;
function Delete: Boolean; override;
function AddUserToRole(RoleID: Integer): Boolean;
function DelUserFromRole(RoleID: Integer): Boolean;
function IsUserInRole(RoleID: Integer): Boolean;
procedure NewUser(theUserName, theFullName, thePassword, theNote, theEMAIL: string; ExtID: Integer; ID: Integer = -1);
constructor Create(AOwner: TComponent; AConnection: TIBDatabase; Query: TIBQuery = nil); override;
end;
implementation
{ TUser }
constructor TUser.Create(AOwner: TComponent; AConnection: TIBDatabase;
Query: TIBQuery);
begin
inherited;
FUserName := '';
FUserFullName := '';
FPassword := '';
FUserID := -1;
FNote := '';
FEMAIl := '';
end;
function TUser.FillDataBy(KeyValue: Variant): Boolean;
var
sql: string;
queryRes: TIBQuery;
begin
Result := false;
if not Assigned(FDataQuery) then
begin
FDataQuery := TIBQuery.Create(nil);
FDataQuery.Transaction := Connection.DefaultTransaction;
sql := 'select *' +
' from USERS' +
' where id_user = ' + VarToStr(KeyValue);
FDataQuery.SQL.Text := sql;
try
FDataQuery.Open;
except
on E:Exception do
begin
MessageDlg('Виникла помилка:"' +
e.Message + '"', mtError, [mbOk], 0);
Exit;
end;
end;
queryRes := FDataQuery;
end else begin
queryRes := FDataQuery;
FDataQuery := nil;
end;
if queryRes.RecordCount <= 0 then
begin
if Assigned(FDataQuery) then
begin
FDataQuery.Free;
FDataQuery := nil;
end;
Exit;
end;
FUserID := KeyValue;
FUserName := queryRes.FieldByName('name').AsString;
FUserFullName := queryRes.FieldByName('full_name').AsString;
FPassword := queryRes.FieldByName('passwd').AsString;
FUserIDExt := queryRes.FieldByName('id_user_ext').AsInteger;
if queryRes['NOTE'] <> Null
then FNOte := queryRes['NOTE']
else FNOte := '';
if queryRes['EMAIL'] <> Null
then FEMAIL := queryRes['EMAIL']
else FEMAIL := '';
// Если отбор был самостоятельный
if Assigned(FDataQuery) then FDataQuery.Free;
Result := true;
end;
procedure TUser.NewUser(theUserName, theFullName, thePassword, theNote, theEMAIL: string; ExtID: Integer; ID: Integer = -1);
begin
FUserID := ID;
FUserName := theUserName;
FPassword := thePassword;
FUserFullName := theFullName;
FUserIDExt := ExtID;
FNote := theNote;
FEMAIL := theEMAIL;
end;
function TUser.AddUserToRole(RoleID: Integer): Boolean;
var
sqlInsUserToRole: TIBSQL;
sql: string;
begin
Result := false;
if IsUserInRole(RoleID) then Exit;
sqlInsUserToRole := TIBSQL.Create(nil);
sqlInsUserToRole.Database := FConnection;
sqlInsUserToRole.Transaction := FInputTransaction;
sql := 'insert into users_roles (id_role, id_user) values (' +
IntToStr(RoleID) + ', ' + IntToStr(FUserID) + ')';
sqlInsUserToRole.SQL.Text := sql;
StartInputTransaction;
try
sqlInsUserToRole.ExecQuery;
CommitInputTransaction;
except
on E:Exception do
begin
MessageDlg('Виникла помилка:"' +
e.Message + '"', mtError, [mbOk], 0);
RollbackInputTransaction;
Exit;
end;
end;
sqlInsUserToRole.Free;
Result := true;
end;
function TUser.Insert: Boolean;
var
stprInsUser: TIBStoredProc;
begin
Result := false;
stprInsUser := TIBStoredProc.Create(nil);
stprInsUser.Database := FConnection;
stprInsUser.Transaction := FInputTransaction;
stprInsUser.StoredProcName := 'INSERT_USER';
StartInputTransaction;
try
stprInsUser.Prepare;
stprInsUser.ParamByName('ppasswd').AsString := FPassword;
stprInsUser.ParamByName('pname').AsString := FUserName;
stprInsUser.ParamByName('pfull_name').AsString := FUserFullName;
stprInsUser.ParamByName('pid_user_ext').AsInteger := FUserIDExt;
stprInsUser.ExecProc;
CommitInputTransaction;
except
on E:Exception do
begin
MessageDlg('Виникла помилка:"' +
e.Message + '"', mtError, [mbOk], 0);
RollbackInputTransaction;
Exit;
end;
end;
FUserID := stprInsUser.ParamByName('pid_user').AsInteger;
stprInsUser.Free;
Result := true;
end;
function TUser.Update: Boolean;
var
sqlUpdUser: TIBSQL;
sql: string;
begin
Result := false;
sqlUpdUser := TIBSQL.Create(nil);
sqlUpdUser.Database := FConnection;
sqlUpdUser.Transaction := FInputTransaction;
sql := 'update users set ' +
'name = ''' + FUserName + ''', ' +
'full_name = ''' + FUserFullName + ''', ' +
'passwd = ''' + FPassword + ''', ' +
'id_user_ext = ' + IntToStr(FUserIDExt) + ' ' +
'where id_user = ' + IntToStr(FUserID);
sqlUpdUser.SQL.Text := sql;
StartInputTransaction;
try
sqlUpdUser.ExecQuery;
CommitInputTransaction;
except
on E:Exception do
begin
MessageDlg('Виникла помилка:"' +
e.Message + '"', mtError, [mbOk], 0);
RollbackInputTransaction;
Exit;
end;
end;
sqlUpdUser.Free;
Result := true;
end;
function TUser.Delete: Boolean;
begin
Result := false;
end;
function TUser.IsUserInRole(RoleID: Integer): Boolean;
var
queryInRole: TIBQuery;
sql: string;
begin
Result := false;
queryInRole := TIBQuery.Create(nil);
queryInRole.Database := FConnection;
queryInRole.Transaction := FConnection.DefaultTransaction;
sql := 'select * from users_roles where id_user = ' + IntToStr(FUserID) +
' and id_role = ' + IntToStr(RoleID);
queryInRole.SQL.Text := sql;
try
queryInRole.Open;
except
on E:Exception do
begin
MessageDlg('Виникла помилка:"' +
e.Message + '"', mtError, [mbOk], 0);
Exit;
end;
end;
if queryInRole.RecordCount > 0 then Result := true;
queryInRole.Free;
end;
function TUser.DelUserFromRole(RoleID: Integer): Boolean;
var
sqlDelUserFromRole: TIBSQL;
sql: string;
begin
Result := false;
if not IsUserInRole(RoleID) then Exit;
sqlDelUserFromRole := TIBSQL.Create(nil);
sqlDelUserFromRole.Database := FConnection;
sqlDelUserFromRole.Transaction := FInputTransaction;
sql := 'delete from users_roles where id_role = ' + IntToStr(RoleID) +
' and id_user = ' + IntToStr(FUserID);
sqlDelUserFromRole.SQL.Text := sql;
StartInputTransaction;
try
sqlDelUserFromRole.ExecQuery;
CommitInputTransaction;
except
on e:Exception do
begin
MessageDlg('Виникла помилка:"' +
e.Message + '"', mtError, [mbOk], 0);
RollbackInputTransaction;
Exit;
end;
end;
sqlDelUserFromRole.Free;
Result := true;
end;
function TUser.FillDataByAuth(Name, Passwd: string): Boolean;
var
sql: string;
queryRes: TIBQuery;
StrMD5:function (Buffer : shortString): shortstring; stdcall;
DLLInstance:THandle;
begin
Result := false;
if not Assigned(FDataQuery) then
begin
FDataQuery := TIBQuery.Create(nil);
FDataQuery.Transaction := Connection.DefaultTransaction;
if FUseMD5
then begin
if FileExists('Md5dll.dll')
then begin
DLLInstance := LoadLibrary('Md5dll.dll');
@StrMD5 :=GetProcAddress(DLLInstance, 'StrMD5');
end;
FPasswordHash := StrMD5(Passwd);
end;
if not FUseMD5 then
sql := 'select *' +
' from ACCESS_USER_SELECT ' +
' where name = ''' + Name + ''' and passwd = ''' + Passwd + ''''
else
sql := 'select *' +
' from ACCESS_USER_SELECT ' +
' where name = ''' + Name + ''' and passwd_md5_hash = ''' + FPasswordHash + '''';
FDataQuery.SQL.Text := sql;
try
FDataQuery.Open;
except
on E: Exception do
begin
MessageDlg('Виникла помилка:"' +
e.Message + '"', mtError, [mbOk], 0);
sql := e.Message;
Exit;
end;
end;
queryRes := FDataQuery;
end else begin
queryRes := FDataQuery;
FDataQuery := nil;
end;
if queryRes.RecordCount <= 0 then
begin
if Assigned(FDataQuery) then
begin
FDataQuery.Free;
FDataQuery := nil;
end;
Exit;
end;
FUserID := queryRes.FieldByName('id_user').AsInteger;
FUserName := queryRes.FieldByName('name').AsString;
FUserFullName := queryRes.FieldByName('full_name').AsString;
FPassword := queryRes.FieldByName('passwd').AsString;
FUserIDExt := queryRes.FieldByName('id_user_ext').AsInteger;
// Если отбор был самостоятельный
if Assigned(FDataQuery) then FDataQuery.Free;
Result := true;
end;
end.
|
{*************************************************************
Author: Stéphane Vander Clock (SVanderClock@Arkadia.com)
www: http://www.arkadia.com
EMail: SVanderClock@Arkadia.com
product: QuickSortList function
Version: 3.05
Description: TALIntegerList or TALDoubleList that work exactly
like TstringList but with integer or Double.
Legal issues: Copyright (C) 1999-2005 by Arkadia Software Engineering
This software is provided 'as-is', without any express
or implied warranty. In no event will the author 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.
4. You must register this software by sending a picture
postcard to the author. Use a nice stamp and mention
your name, street address, EMail address and any
comment you like to say.
Know bug :
History :
Link :
Please send all your feedback to SVanderClock@Arkadia.com
**************************************************************}
unit ALQuickSortList;
interface
uses Classes;
Type
{----------------------------------------------------------------------------------}
TALQuickSortListCompare = function(List: TObject; Index1, Index2: Integer): Integer;
{-----------------------------------}
TALBaseQuickSortList = class(TObject)
private
FList: PPointerList;
FCount: Integer;
FCapacity: Integer;
FSorted: Boolean;
FDuplicates: TDuplicates;
procedure SetSorted(Value: Boolean);
procedure QuickSort(L, R: Integer; SCompare: TALQuickSortListCompare);
protected
function Get(Index: Integer): Pointer;
procedure Grow;
procedure Put(Index: Integer; Item: Pointer);
procedure Notify(Ptr: Pointer; Action: TListNotification); virtual;
procedure SetCapacity(NewCapacity: Integer);
procedure SetCount(NewCount: Integer);
function CompareItems(const Index1, Index2: Integer): Integer; virtual;
procedure ExchangeItems(Index1, Index2: Integer);
procedure InsertItem(Index: Integer; Item: Pointer);
procedure Insert(Index: Integer; Item: Pointer);
property List: PPointerList read FList;
public
Constructor Create;
destructor Destroy; override;
procedure Clear;
procedure Delete(Index: Integer);
class procedure Error(const Msg: string; Data: Integer); overload;
class procedure Error(Msg: PResStringRec; Data: Integer); overload;
procedure Exchange(Index1, Index2: Integer);
function Expand: TALBaseQuickSortList;
procedure CustomSort(Compare: TALQuickSortListCompare); virtual;
procedure Sort; virtual;
property Sorted: Boolean read FSorted write SetSorted;
property Capacity: Integer read FCapacity write SetCapacity;
property Count: Integer read FCount write SetCount;
property Duplicates: TDuplicates read FDuplicates write FDuplicates;
end;
{---------------------------------------}
PALIntegerListItem = ^TALIntegerListItem;
TALIntegerListItem = record
FInteger: integer;
FObject: TObject;
end;
{------------------------------------------}
TALIntegerList = class(TALBaseQuickSortList)
private
function GetItem(Index: Integer): Integer;
procedure SetItem(Index: Integer; const Item: Integer);
function GetObject(Index: Integer): TObject;
procedure PutObject(Index: Integer; AObject: TObject);
protected
procedure Notify(Ptr: Pointer; Action: TListNotification); override;
procedure InsertItem(Index: Integer; const item: integer; AObject: TObject);
function CompareItems(const Index1, Index2: Integer): Integer; override;
public
function IndexOf(Item: Integer): Integer;
function IndexOfObject(AObject: TObject): Integer;
function Add(const Item: integer): Integer;
Function AddObject(const Item: integer; AObject: TObject): Integer;
function Find(item: Integer; var Index: Integer): Boolean;
procedure Insert(Index: Integer; const item: integer);
procedure InsertObject(Index: Integer; const item: integer; AObject: TObject);
property Items[Index: Integer]: Integer read GetItem write SetItem; default;
property Objects[Index: Integer]: TObject read GetObject write PutObject;
end;
{-------------------------------------}
PALDoubleListItem = ^TALDoubleListItem;
TALDoubleListItem = record
FDouble: Double;
FObject: TObject;
end;
{------------------------------------------}
TALDoubleList = class(TALBaseQuickSortList)
private
function GetItem(Index: Integer): Double;
procedure SetItem(Index: Integer; const Item: Double);
function GetObject(Index: Integer): TObject;
procedure PutObject(Index: Integer; AObject: TObject);
protected
procedure Notify(Ptr: Pointer; Action: TListNotification); override;
procedure InsertItem(Index: Integer; const item: Double; AObject: TObject);
function CompareItems(const Index1, Index2: Integer): Integer; override;
public
function IndexOf(Item: Double): Integer;
function IndexOfObject(AObject: TObject): Integer;
function Add(const Item: Double): Integer;
Function AddObject(const Item: Double; AObject: TObject): Integer;
function Find(item: Double; var Index: Integer): Boolean;
procedure Insert(Index: Integer; const item: Double);
procedure InsertObject(Index: Integer; const item: Double; AObject: TObject);
property Items[Index: Integer]: Double read GetItem write SetItem; default;
property Objects[Index: Integer]: TObject read GetObject write PutObject;
end;
implementation
uses RTLConsts;
{ TQuickSortList }
{***********************************************************************************}
function AlBaseQuickSortListCompare(List: TObject; Index1, Index2: Integer): Integer;
Begin
result := TALBaseQuickSortList(List).CompareItems(Index1, Index2);
end;
{**************************************}
constructor TALBaseQuickSortList.Create;
begin
FList:= nil;
FCount:= 0;
FCapacity:= 0;
FSorted := False;
FDuplicates := dupIgnore;
end;
{**************************************}
destructor TALBaseQuickSortList.Destroy;
begin
Clear;
end;
{***********************************}
procedure TALBaseQuickSortList.Clear;
begin
SetCount(0);
SetCapacity(0);
end;
{***********************************************************************}
procedure TALBaseQuickSortList.InsertItem(Index: Integer; Item: Pointer);
begin
if FCount = FCapacity then Grow;
if Index < FCount then System.Move(
FList^[Index],
FList^[Index + 1],
(FCount - Index) * SizeOf(Pointer)
);
FList^[Index] := Item;
Inc(FCount);
if Item <> nil then
Notify(Item, lnAdded);
end;
{********************************************************************}
procedure TALBaseQuickSortList.ExchangeItems(Index1, Index2: Integer);
var Item: Pointer;
begin
Item := FList^[Index1];
FList^[Index1] := FList^[Index2];
FList^[Index2] := Item;
end;
{****************************************************}
procedure TALBaseQuickSortList.Delete(Index: Integer);
var Temp: Pointer;
begin
if (Index < 0) or (Index >= FCount) then Error(@SListIndexError, Index);
Temp := Get(Index);
Dec(FCount);
if Index < FCount then System.Move(
FList^[Index + 1],
FList^[Index],
(FCount - Index) * SizeOf(Pointer)
);
if Temp <> nil then Notify(Temp, lnDeleted);
end;
{***************************************************************}
procedure TALBaseQuickSortList.Exchange(Index1, Index2: Integer);
begin
{Warning: Do not call Exchange on a sorted list except to swap two identical
strings with different associated objects. Exchange does not check whether
the list is sorted, and can destroy the sort order of a sorted list.}
if (Index1 < 0) or (Index1 >= FCount) then Error(@SListIndexError, Index1);
if (Index2 < 0) or (Index2 >= FCount) then Error(@SListIndexError, Index2);
ExchangeItems(Index1, Index2);
end;
{*******************************************************************}
procedure TALBaseQuickSortList.Insert(Index: Integer; Item: Pointer);
begin
if Sorted then Error(@SSortedListError, 0);
if (Index < 0) or (Index > FCount) then Error(@SListIndexError, Index);
InsertItem(Index, Item);
end;
{****************************************************************}
procedure TALBaseQuickSortList.Put(Index: Integer; Item: Pointer);
var Temp: Pointer;
begin
if Sorted then Error(@SSortedListError, 0);
if (Index < 0) or (Index >= FCount) then Error(@SListIndexError, Index);
if Item <> FList^[Index] then begin
Temp := FList^[Index];
FList^[Index] := Item;
if Temp <> nil then Notify(Temp, lnDeleted);
if Item <> nil then Notify(Item, lnAdded);
end;
end;
{*********************************************************}
function TALBaseQuickSortList.Get(Index: Integer): Pointer;
begin
if (Index < 0) or (Index >= FCount) then Error(@SListIndexError, Index);
Result := FList^[Index];
end;
{***************************************************************************}
class procedure TALBaseQuickSortList.Error(const Msg: string; Data: Integer);
{---------------------------}
function ReturnAddr: Pointer;
asm
MOV EAX,[EBP+4]
end;
begin
raise EListError.CreateFmt(Msg, [Data]) at ReturnAddr;
end;
{****************************************************************************}
class procedure TALBaseQuickSortList.Error(Msg: PResStringRec; Data: Integer);
begin
TALBaseQuickSortList.Error(LoadResString(Msg), Data);
end;
{*********************************************************}
function TALBaseQuickSortList.Expand: TALBaseQuickSortList;
begin
if FCount = FCapacity then Grow;
Result := Self;
end;
{**********************************}
procedure TALBaseQuickSortList.Grow;
var Delta: Integer;
begin
if FCapacity > 64 then Delta := FCapacity div 4
else if FCapacity > 8 then Delta := 16
else Delta := 4;
SetCapacity(FCapacity + Delta);
end;
{***************************************************************}
procedure TALBaseQuickSortList.SetCapacity(NewCapacity: Integer);
begin
if (NewCapacity < FCount) or (NewCapacity > MaxListSize) then Error(@SListCapacityError, NewCapacity);
if NewCapacity <> FCapacity then begin
ReallocMem(FList, NewCapacity * SizeOf(Pointer));
FCapacity := NewCapacity;
end;
end;
{*********************************************************}
procedure TALBaseQuickSortList.SetCount(NewCount: Integer);
var I: Integer;
begin
if (NewCount < 0) or (NewCount > MaxListSize) then Error(@SListCountError, NewCount);
if NewCount > FCapacity then SetCapacity(NewCount);
if NewCount > FCount then FillChar(FList^[FCount], (NewCount - FCount) * SizeOf(Pointer), 0)
else for I := FCount - 1 downto NewCount do Delete(I);
FCount := NewCount;
end;
{*****************************************************************************}
procedure TALBaseQuickSortList.Notify(Ptr: Pointer; Action: TListNotification);
begin
//virtual
end;
{*******************************************************}
procedure TALBaseQuickSortList.SetSorted(Value: Boolean);
begin
if FSorted <> Value then begin
if Value then Sort;
FSorted := Value;
end;
end;
{*****************************************************************************************}
procedure TALBaseQuickSortList.QuickSort(L, R: Integer; SCompare: TALQuickSortListCompare);
var I, J, P: Integer;
begin
repeat
I := L;
J := R;
P := (L + R) shr 1;
repeat
while SCompare(Self, I, P) < 0 do Inc(I);
while SCompare(Self, J, P) > 0 do Dec(J);
if I <= J then begin
ExchangeItems(I, J);
if P = I then P := J
else if P = J then P := I;
Inc(I);
Dec(J);
end;
until I > J;
if L < J then QuickSort(L, J, SCompare);
L := I;
until I >= R;
end;
{**************************************************************************}
procedure TALBaseQuickSortList.CustomSort(Compare: TALQuickSortListCompare);
begin
if not Sorted and (FCount > 1) then QuickSort(0, FCount - 1, Compare);
end;
{**********************************}
procedure TALBaseQuickSortList.Sort;
begin
CustomSort(AlBaseQuickSortListCompare);
end;
{********************************************************************************}
function TALBaseQuickSortList.CompareItems(const Index1, Index2: Integer): Integer;
begin
Result := 0;
end;
{ TALIntegerList }
{********************************************************}
function TALIntegerList.Add(const Item: integer): Integer;
begin
Result := AddObject(Item, nil);
end;
{********************************************************************************}
function TALIntegerList.AddObject(const Item: integer; AObject: TObject): Integer;
begin
if not Sorted then Result := FCount
else if Find(Item, Result) then
case Duplicates of
dupIgnore: Exit;
dupError: Error(@SDuplicateString, 0);
end;
InsertItem(Result, Item, AObject);
end;
{*****************************************************************************************}
procedure TALIntegerList.InsertItem(Index: Integer; const item: integer; AObject: TObject);
Var aPALIntegerListItem: PALIntegerListItem;
begin
New(aPALIntegerListItem);
aPALIntegerListItem^.FInteger := item;
aPALIntegerListItem^.FObject := AObject;
try
inherited InsertItem(index,aPALIntegerListItem);
except
Dispose(aPALIntegerListItem);
raise;
end;
end;
{***************************************************************************}
function TALIntegerList.CompareItems(const Index1, Index2: integer): Integer;
begin
result := PALIntegerListItem(Get(Index1))^.FInteger - PALIntegerListItem(Get(Index2))^.FInteger;
end;
{***********************************************************************}
function TALIntegerList.Find(item: Integer; var Index: Integer): Boolean;
var L, H, I, C: Integer;
begin
Result := False;
L := 0;
H := FCount - 1;
while L <= H do begin
I := (L + H) shr 1;
C := GetItem(I) - item;
if C < 0 then L := I + 1
else begin
H := I - 1;
if C = 0 then begin
Result := True;
if Duplicates <> dupAccept then L := I;
end;
end;
end;
Index := L;
end;
{*******************************************************}
function TALIntegerList.GetItem(Index: Integer): Integer;
begin
Result := PALIntegerListItem(Get(index))^.FInteger
end;
{******************************************************}
function TALIntegerList.IndexOf(Item: Integer): Integer;
begin
if not Sorted then Begin
Result := 0;
while (Result < FCount) and (GetItem(result) <> Item) do Inc(Result);
if Result = FCount then Result := -1;
end
else if not Find(Item, Result) then Result := -1;
end;
{*******************************************************************}
procedure TALIntegerList.Insert(Index: Integer; const Item: Integer);
begin
InsertObject(Index, index, nil);
end;
{*******************************************************************************************}
procedure TALIntegerList.InsertObject(Index: Integer; const item: integer; AObject: TObject);
Var aPALIntegerListItem: PALIntegerListItem;
begin
New(aPALIntegerListItem);
aPALIntegerListItem^.FInteger := item;
aPALIntegerListItem^.FObject := AObject;
try
inherited insert(index,aPALIntegerListItem);
except
Dispose(aPALIntegerListItem);
raise;
end;
end;
{***********************************************************************}
procedure TALIntegerList.Notify(Ptr: Pointer; Action: TListNotification);
begin
if Action = lnDeleted then dispose(ptr);
inherited Notify(Ptr, Action);
end;
{********************************************************************}
procedure TALIntegerList.SetItem(Index: Integer; const Item: Integer);
Var aPALIntegerListItem: PALIntegerListItem;
begin
New(aPALIntegerListItem);
aPALIntegerListItem^.FInteger := item;
aPALIntegerListItem^.FObject := nil;
Try
Put(Index, aPALIntegerListItem);
except
Dispose(aPALIntegerListItem);
raise;
end;
end;
{*********************************************************}
function TALIntegerList.GetObject(Index: Integer): TObject;
begin
if (Index < 0) or (Index >= FCount) then Error(@SListIndexError, Index);
Result := PALIntegerListItem(Get(index))^.FObject;
end;
{***************************************************************}
function TALIntegerList.IndexOfObject(AObject: TObject): Integer;
begin
for Result := 0 to Count - 1 do
if GetObject(Result) = AObject then Exit;
Result := -1;
end;
{*******************************************************************}
procedure TALIntegerList.PutObject(Index: Integer; AObject: TObject);
begin
if (Index < 0) or (Index >= FCount) then Error(@SListIndexError, Index);
PALIntegerListItem(Get(index))^.FObject := AObject;
end;
{ TALDoubleList }
{********************************************************}
function TALDoubleList.Add(const Item: Double): Integer;
begin
Result := AddObject(Item, nil);
end;
{********************************************************************************}
function TALDoubleList.AddObject(const Item: Double; AObject: TObject): Integer;
begin
if not Sorted then Result := FCount
else if Find(Item, Result) then
case Duplicates of
dupIgnore: Exit;
dupError: Error(@SDuplicateString, 0);
end;
InsertItem(Result, Item, AObject);
end;
{*****************************************************************************************}
procedure TALDoubleList.InsertItem(Index: Integer; const item: Double; AObject: TObject);
Var aPALDoubleListItem: PALDoubleListItem;
begin
New(aPALDoubleListItem);
aPALDoubleListItem^.FDouble := item;
aPALDoubleListItem^.FObject := AObject;
try
inherited InsertItem(index,aPALDoubleListItem);
except
Dispose(aPALDoubleListItem);
raise;
end;
end;
{*******************************************************************}
function TALDoubleList.CompareItems(const Index1, Index2: integer): Integer;
var aDouble: Double;
begin
aDouble := PALDoubleListItem(Get(Index1))^.FDouble - PALDoubleListItem(Get(Index2))^.FDouble;
if adouble < 0 then result := -1
else if adouble > 0 then result := 1
else result := 0;
end;
{***********************************************************************}
function TALDoubleList.Find(item: Double; var Index: Integer): Boolean;
var L, H, I, C: Integer;
{-----------------------------------------------------}
Function internalCompareDouble(D1,D2: Double): Integer;
Var aDouble: Double;
Begin
aDouble := D1 - D2;
if adouble < 0 then result := -1
else if adouble > 0 then result := 1
else result := 0;
end;
begin
Result := False;
L := 0;
H := FCount - 1;
while L <= H do begin
I := (L + H) shr 1;
C := internalCompareDouble(GetItem(I),item);
if C < 0 then L := I + 1
else begin
H := I - 1;
if C = 0 then begin
Result := True;
if Duplicates <> dupAccept then L := I;
end;
end;
end;
Index := L;
end;
{*******************************************************}
function TALDoubleList.GetItem(Index: Integer): Double;
begin
Result := PALDoubleListItem(Get(index))^.FDouble
end;
{******************************************************}
function TALDoubleList.IndexOf(Item: Double): Integer;
begin
if not Sorted then Begin
Result := 0;
while (Result < FCount) and (GetItem(result) <> Item) do Inc(Result);
if Result = FCount then Result := -1;
end
else if not Find(Item, Result) then Result := -1;
end;
{*******************************************************************}
procedure TALDoubleList.Insert(Index: Integer; const Item: Double);
begin
InsertObject(Index, index, nil);
end;
{*******************************************************************************************}
procedure TALDoubleList.InsertObject(Index: Integer; const item: Double; AObject: TObject);
Var aPALDoubleListItem: PALDoubleListItem;
begin
New(aPALDoubleListItem);
aPALDoubleListItem^.FDouble := item;
aPALDoubleListItem^.FObject := AObject;
try
inherited insert(index,aPALDoubleListItem);
except
Dispose(aPALDoubleListItem);
raise;
end;
end;
{***********************************************************************}
procedure TALDoubleList.Notify(Ptr: Pointer; Action: TListNotification);
begin
if Action = lnDeleted then dispose(ptr);
inherited Notify(Ptr, Action);
end;
{********************************************************************}
procedure TALDoubleList.SetItem(Index: Integer; const Item: Double);
Var aPALDoubleListItem: PALDoubleListItem;
begin
New(aPALDoubleListItem);
aPALDoubleListItem^.FDouble := item;
aPALDoubleListItem^.FObject := nil;
Try
Put(Index, aPALDoubleListItem);
except
Dispose(aPALDoubleListItem);
raise;
end;
end;
{*********************************************************}
function TALDoubleList.GetObject(Index: Integer): TObject;
begin
if (Index < 0) or (Index >= FCount) then Error(@SListIndexError, Index);
Result := PALDoubleListItem(Get(index))^.FObject;
end;
{***************************************************************}
function TALDoubleList.IndexOfObject(AObject: TObject): Integer;
begin
for Result := 0 to Count - 1 do
if GetObject(Result) = AObject then Exit;
Result := -1;
end;
{*******************************************************************}
procedure TALDoubleList.PutObject(Index: Integer; AObject: TObject);
begin
if (Index < 0) or (Index >= FCount) then Error(@SListIndexError, Index);
PALDoubleListItem(Get(index))^.FObject := AObject;
end;
end. |
unit glCurrency;
interface
uses
SysUtils, Classes, IdHTTP;
type
TglCurrency = class(TComponent)
private
fAuthentication: boolean;
fLogin: string;
fPassword: string;
fPort: integer;
fHost: string;
fHTTP: TidHTTP;
fImportList: TStringList;
function ParseValRBC(instr: string): Currency;
protected
{ Protected declarations }
public
function GetCBRFRates(var USD, EUR, GBP, AUD, UAH: Currency): boolean;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Authentication: boolean read fAuthentication write fAuthentication;
property Login: string read fLogin write fLogin;
property Password: string read fPassword write fPassword;
property Port: integer read fPort write fPort;
property Host: string read fHost write fHost;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Golden Line', [TglCurrency]);
end;
{ TglCurrency }
constructor TglCurrency.Create(AOwner: TComponent);
begin
inherited;
fHTTP := TidHTTP.Create(self);
fImportList := TStringList.Create;
end;
destructor TglCurrency.Destroy;
begin
fHTTP.Free;
fImportList.Free;
inherited;
end;
function TglCurrency.GetCBRFRates(var USD, EUR, GBP, AUD,
UAH: Currency): boolean;
var
i: integer;
SubStr: string[10];
begin
// настраиваем блин прокси
with fHTTP.ProxyParams do
begin
BasicAuthentication := fAuthentication;
ProxyUsername := fLogin;
ProxyPassword := fPassword;
ProxyPort := fPort;
ProxyServer := fHost;
end;
// скачиваем файло
fImportList.Text := fHTTP.Get('http://www.rbc.ru/out/802.csv');
if Trim(fImportList.Text) = '' then
begin
result := false;
exit;
end;
fHTTP.Disconnect;
// ищем нужные строки
for i := 0 to fImportList.Count - 1 do
begin
SubStr := fImportList[i];
if SubStr = 'USD ЦБ РФ,' then
USD := ParseValRBC(fImportList[i]);
if SubStr = 'EUR ЦБ РФ,' then
EUR := ParseValRBC(fImportList[i]);
if SubStr = 'AUD ЦБ РФ,' then
AUD := ParseValRBC(fImportList[i]);
if SubStr = 'GBP ЦБ РФ,' then
GBP := ParseValRBC(fImportList[i]);
if SubStr = 'UAH ЦБ РФ,' then
UAH := ParseValRBC(fImportList[i]);
end;
result := true;
end;
function TglCurrency.ParseValRBC(instr: string): Currency;
var
s: string;
m, p: integer;
begin
// [USD ЦБ РФ,1 Доллар США,22/12,30.5529,-0.1658]
s := instr;
// [1 Доллар США,22/12,30.5529,-0.1658]
Delete(s, 1, pos(',', s));
// [1]
m := StrToInt(Copy(s, 1, pos(' ', s) - 1));
// [12,30.5529,-0.1658]
Delete(s, 1, pos('/', s));
// [30.5529,-0.1658]
Delete(s, 1, pos(',', s));
// [30.5529]
Delete(s, pos(',', s), 20);
// [30,5529]
p := pos('.', s);
Delete(s, p, 1);
Insert(',', s, p);
// результат делим на "M"
result := StrToCurr(s) / m;
end;
end.
|
// ----------- Parse::Easy::Runtime -----------
// https://github.com/MahdiSafsafi/Parse-Easy
// --------------------------------------------
unit Parse.Easy.Parser.Rule;
interface
uses
System.Classes,
System.SysUtils;
type
TRuleFlag = (rfAccept);
TRuleFlags = set of TRuleFlag;
TRule = class(TObject)
private
FIndex: Integer;
FID: Integer;
FNumberOfItems: Integer;
FActionIndex: Integer;
FFlags: TRuleFlags;
public
constructor Create; virtual;
property Id: Integer read FID write FID;
property Index: Integer read FIndex write FIndex;
property NumberOfItems: Integer read FNumberOfItems write FNumberOfItems;
property ActionIndex: Integer read FActionIndex write FActionIndex;
property Flags: TRuleFlags read FFlags write FFlags;
end;
implementation
{ TRule }
constructor TRule.Create;
begin
FFlags := [];
end;
end.
|
unit LogDataMain;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls,
ExtCtrls, IniFiles, Menus, DB, ADODB, IdBaseComponent, IdComponent, IdUDPBase,
IdUDPServer, IdGlobal, IdSocketHandle;
type
TFrmLogData = class(TForm)
Label3: TLabel;
Label4: TLabel;
Timer1: TTimer;
StartTimer: TTimer;
MainMenu1: TMainMenu;
V1: TMenuItem;
N1: TMenuItem;
N2: TMenuItem;
A1: TMenuItem;
IdUDPServerLog: TIdUDPServer;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure WriteLogFile();
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure StartTimerTimer(Sender: TObject);
procedure N1Click(Sender: TObject);
procedure A1Click(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure IdUDPServerLogUDPRead(AThread: TIdUDPListenerThread; AData: TIdBytes; ABinding: TIdSocketHandle);
private
LogMsgList: TStringList;
m_boRemoteClose: Boolean;
{ Private declarations }
//写入数据
procedure WriteAccess(FileName,s0, s1, s2, s3, s4, s5, s6, s7, s8: String);
public
//建立Access文件,如果文件存在则失败
function CreateAccessFile(FileName:String;PassWord:string=''):boolean;
//连接数据库
procedure ConnectedAccess(FileName:String;PassWord:string='');
procedure MyMessage(var MsgData: TWmCopyData); message WM_COPYDATA;
//判断表是否存在(用异常判断)
function TableExists(log:string):Boolean;
{ Public declarations }
end;
var
FrmLogData: TFrmLogData;
sLogFile: String;
boBusy: Boolean = false;//20080928 增加判断TTimer 是否重入
boIsRaedLog: Boolean = false;//20080928 是否在接收日志
//声明连接字符串
Const
SConnectionString = 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=%s;'
+'Jet OLEDB:Database Password=%s;';
implementation
uses LDShare, Grobal2, HUtil32,ComObj,ActiveX,LogSelect,DM,About;
{$R *.DFM}
//-----------------------------MDB数据库操作-----------------------------------
//连接数据库
procedure TFrmLogData.ConnectedAccess(FileName:String;PassWord:string='');
begin
with DMFrm.ADOconn do
begin
ConnectionString:=format(SConnectionString,[FileName,PassWord]);
connected:=true;
end;
end;
//写入数据
procedure TFrmLogData.WriteAccess(FileName,s0, s1, s2, s3, s4, s5, s6, s7, s8: String);
var Str2:string;
begin
Str2:=s0;
if not DMFrm.ADOconn.Connected then ConnectedAccess(FileName,'');
case strtoint(s0) of
0:Str2:='取回物品';//取回物品
1:Str2:='存放物品';//存放物品
2:Str2:='炼制药品';//炼制药品
3:Str2:='持久消失';//持久消失
4:Str2:='捡起物品';//捡起物品
5:Str2:='制造物品';//制造物品
6:Str2:='毁掉物品';//毁掉物品
7:Str2:='扔掉物品';//扔掉物品
8:Str2:='交易物品';//交易物品
9:Str2:='购买物品'; //购买物品
10:Str2:='出售物品';//出售物品
11:Str2:='使用物品';//使用物品
12:Str2:='人物升级';//人物升级
13:Str2:='减少金币';//减少金币
14:Str2:='增加金币';//增加金币
15:Str2:='死亡掉落';//死亡掉落
16:Str2:='掉落物品';//掉落物品
17:Str2:='等级调整';//等级调整
18:Str2:='无效代码';//无效代码
19:Str2:='人物死亡';//人物死亡
20:Str2:='升级成功';//升级成功
21:Str2:='升级失败';//升级失败
22:Str2:='城堡取钱';//城堡取钱
23:Str2:='城堡存钱';//城堡存钱
24:Str2:='升级取回';//升级取回
25:Str2:='武器升级';//武器升级
26:Str2:='背包减少';//背包减少
27:Str2:='改变城主';//改变城主
28:Str2:='元宝改变';//元宝改变
29:Str2:='能量改变';//能量改变
30:Str2:='商铺购买';//商铺购买
31:Str2:='装备升级';//装备升级
32:Str2:='寄售物品';//寄售物品
33:Str2:='寄售购买';//寄售购买
34:Str2:='个人商店';//个人商店
35:Str2:='行会酒泉';//行会酒泉
36:Str2:='挑战物品';//挑战物品
37:Str2:='挖人形怪';//挖人形怪
38:Str2:='NPC 酿酒';//NPC 酿酒
39:Str2:='获得矿石';//获得矿石
40:Str2:='开启宝箱';
41:Str2:='粹练物品';
111,112,113,114,115,116:Str2:='成长改变';
end;
with DMFrm.ADOQuery1 do begin
close;
SQL.Clear;
SQL.Add('Insert Into Log (动作,地图,X坐标,Y坐标,');
SQL.Add('人物名称,物品名称,物品ID,记录,交易对像,时间)');
SQL.Add(' Values(:a0,:a1,:a2,:a3,:a4,:a5,:a6,:a7,:a8,:a9)');
parameters.ParamByName('a0').DataType:=Ftstring;
parameters.ParamByName('a0').Value :=Trim(Str2);
parameters.ParamByName('a1').DataType :=Ftstring;
parameters.ParamByName('a1').Value :=Trim(s1);
parameters.ParamByName('a2').DataType:=Ftinteger;
parameters.ParamByName('a2').Value :=strToint(Trim(s2));
parameters.ParamByName('a3').DataType :=Ftinteger;
parameters.ParamByName('a3').Value :=strToint(Trim(s3));
parameters.ParamByName('a4').DataType :=Ftstring;
parameters.ParamByName('a4').Value :=Trim(s4);
parameters.ParamByName('a5').DataType :=Ftstring;
parameters.ParamByName('a5').Value :=Trim(s5);
parameters.ParamByName('a6').DataType :=Ftstring;
parameters.ParamByName('a6').Value :=Trim(s6);
parameters.ParamByName('a7').DataType :=Ftstring;
parameters.ParamByName('a7').Value :=Trim(s7);
parameters.ParamByName('a8').DataType :=Ftstring;
parameters.ParamByName('a8').Value :=Trim(s8);
parameters.ParamByName('a9').DataType :=Ftdate;
parameters.ParamByName('a9').Value :=now();
ExecSQL;
end;
end;
//判断表是否存在(用异常判断)
function TFrmLogData.TableExists(log:string):Boolean;
begin
Result:=False;
try
with DMFrm.ADOQuery1 do
begin
close;
SQL.Clear;
SQL.Add('select top 1 动作 from '+log);
open;
Result:=True;
end;
except
Result:=False;
end;
end;
function GetTempPathFileName():string;
//取得临时文件名
var
SPath,SFile:array [0..254] of char;
begin
GetTempPath(254,SPath);
GetTempFileName(SPath,'~SM',0,SFile);
result:=SFile;
DeleteFile(PChar(result));
end;
//建立Access文件,如果文件存在则失败
function TFrmLogData.CreateAccessFile(FileName:String;PassWord:string=''):boolean;
var
STempFileName:string;
vCatalog:OleVariant;
begin
STempFileName:=GetTempPathFileName;
try
vCatalog:=CreateOleObject('ADOX.Catalog');
vCatalog.Create(format(SConnectionString,[STempFileName,PassWord]));
result:=CopyFile(PChar(STempFileName),PChar(FileName),True);
DeleteFile(STempFileName);
except
result:=false;
end;
end;
//--------------------------------------------------------------------------
procedure TFrmLogData.FormCreate(Sender: TObject);
var
nX, nY: Integer;
begin
g_dwGameCenterHandle := Str_ToInt(ParamStr(1), 0);
nX := Str_ToInt(ParamStr(2), -1);
nY := Str_ToInt(ParamStr(3), -1);
if (nX >= 0) or (nY >= 0) then begin
Left := nX;
Top := nY;
end;
m_boRemoteClose := False;
SendGameCenterMsg(SG_FORMHANDLE, IntToStr(Self.Handle));
SendGameCenterMsg(SG_STARTNOW, '正在启动日志服务器...');
LogMsgList := TStringList.Create;
StartTimer.Enabled := True;
end;
procedure TFrmLogData.FormDestroy(Sender: TObject);
begin
LogMsgList.Free;
end;
procedure TFrmLogData.IdUDPServerLogUDPRead(AThread: TIdUDPListenerThread; AData: TIdBytes; ABinding: TIdSocketHandle);
var
LogStr: String absolute AData;
begin
LogMsgList.Add(LogStr);
end;
procedure TFrmLogData.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
if m_boRemoteClose then exit;
if Application.MessageBox('是否确认退出服务器?',
'提示信息',
MB_YESNO + MB_ICONQUESTION) = IDYES then begin
end else CanClose := False;
end;
procedure TFrmLogData.Timer1Timer(Sender: TObject);
begin
if boBusy then Exit;
boBusy:= True;
try
WriteLogFile();
finally
boBusy:= False;
end;
end;
procedure TFrmLogData.WriteLogFile();
var
I: Integer;
Year, Month, Day: Word;
S10,s0, s1, s2, s3, s4, s5, s6, s7, s8, sA,sB,sC: String;
begin
try
DecodeDate(Date, Year, Month, Day);
//目录不存在,则创建目录
if not FileExists(sBaseDir) then CreateDirectoryA(PChar(sBaseDir), nil);
sLogFile :=sBaseDir + IntToStr(Year) + '-' + IntToString(Month) + '-' + IntToString(Day)+ '.mdb';
Label4.Caption := sLogFile;
//日志文件不存在,则创建
if not FileExists(sLogFile) then begin
DMFrm.ADOconn.Connected:=False;
CreateAccessFile(sLogFile,'');
end;
//如果没有连接数据库,则连接数据库
if not DMFrm.ADOconn.Connected then ConnectedAccess(sLogFile,''); //连接数据库
//日志文件存在
if FileExists(sLogFile) then begin
if (not TableExists('Log')) then begin //表不存在,则创建表
with DMFrm.ADOQuery1 do begin //创建数据表
close;
SQL.Clear;
SQL.Add('Create Table Log (编号 Counter,动作 string,地图 string,X坐标 integer,Y坐标 integer,');
SQL.Add('人物名称 string,物品名称 string,物品ID string,记录 string,交易对像 string,时间 DateTime)');
ExecSQL;
end;
end else begin //写入数据
for I := LogMsgList.Count - 1 downto 0 do begin //处理数据
if (LogMsgList.Count <= 0) or boIsRaedLog then Break;
s10 := LogMsgList.Strings[I];
if (s10 <> '') then begin
s10 := GetValidStr3(s10, sA, [' ']);
s10 := GetValidStr3(s10, sB, [' ']);
s10 := GetValidStr3(s10, sC, [' ']);
s10 := GetValidStr3(s10, s0, [' ']);
s10 := GetValidStr3(s10, s1, [' ']);
s10 := GetValidStr3(s10, s2, [' ']);
s10 := GetValidStr3(s10, s3, [' ']);
s10 := GetValidStr3(s10, s4, [' ']);
s10 := GetValidStr3(s10, s5, [' ']);
s10 := GetValidStr3(s10, s6, [' ']);
s10 := GetValidStr3(s10, s7, [' ']);
s10 := GetValidStr3(s10, s8, [' ']);
if (S0<>'') and (s1 <> '') and (s2 <> '') and (s3 <> '') and
(S4<>'') and (s5 <> '') and (s6 <> '') and (s7 <> '') and
(s8 <> '') then begin
if boIsRaedLog then Break;
//写入数据表
WriteAccess(sLogFile, s0, s1, s2, s3, s4, s5, s6, s7, s8);
LogMsgList.Delete(I);//20080928 修改
end;
end;
end;
//LogMsgList.Clear;//20080928 注释
end;
end;
except
end;
end;
procedure TFrmLogData.MyMessage(var MsgData: TWmCopyData);
var
sData: String;
//ProgramType: TProgamType;
wIdent: Word;
begin
wIdent := HiWord(MsgData.From);
// ProgramType:=TProgamType(LoWord(MsgData.From));
sData := StrPas(MsgData.CopyDataStruct^.lpData);
case wIdent of //
GS_QUIT: begin
m_boRemoteClose := True;
Close();
end;
1: ;
2: ;
3: ;
end; // case
end;
procedure TFrmLogData.StartTimerTimer(Sender: TObject);
var
Conf: TIniFile;
boMinimize: Boolean;
begin
boMinimize:= False;
StartTimer.Enabled := False;
Conf := TIniFile.Create('.\LogData.ini');
if Conf <> nil then begin
sBaseDir := Conf.ReadString('Setup', 'BaseDir', sBaseDir);
sServerName := Conf.ReadString('Setup', 'Caption', sServerName);
sServerName := Conf.ReadString('Setup', 'ServerName', sServerName);
nServerPort := Conf.ReadInteger('Setup', 'Port', nServerPort);
boMinimize := Conf.ReadBool('Setup', 'Minimize', True);
Conf.Free;
end;
Caption := sCaption + ' (' + sServerName + ')';
IdUDPServerLog.DefaultPort := nServerPort;
try
IdUDPServerLog.Active := True;
except
Application.MessageBox(PChar(IntToStr(nServerPort)+'端口被占用。'), '提示', MB_OK + MB_ICONSTOP);
end;
if boMinimize then Application.Minimize;//最小化窗口
SendGameCenterMsg(SG_STARTOK, '日志服务器启动完成...');
end;
procedure TFrmLogData.N1Click(Sender: TObject);
begin
LogFrm := TLogFrm.Create(Owner);
LogFrm.ShowModal;
LogFrm.Free;
end;
procedure TFrmLogData.A1Click(Sender: TObject);
begin
AboutFrm := TAboutFrm.Create(Owner);
AboutFrm.Open();
AboutFrm.Free;
end;
procedure TFrmLogData.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Application.Terminate;
end;
end.
|
//
// Created by the DataSnap proxy generator.
// 26/06/2020 08:45:06
//
unit Guia.Proxy;
interface
uses System.JSON, Datasnap.DSProxyRest, Datasnap.DSClientRest, Data.DBXCommon, Data.DBXClient, Data.DBXDataSnap, Data.DBXJSON, Datasnap.DSProxy, System.Classes, System.SysUtils, Data.DB, Data.SqlExpr, Data.DBXDBReaders, Data.DBXCDSReaders, Data.FireDACJSONReflect, Data.DBXJSONReflect;
type
IDSRestCachedTFDJSONDataSets = interface;
TServerMethodsClient = class(TDSAdminRestClient)
private
FLoadCategoriasCommand: TDSRestCommand;
FLoadCategoriasCommand_Cache: TDSRestCommand;
FLoadDestaquePrincipalCommand: TDSRestCommand;
FLoadDestaquePrincipalCommand_Cache: TDSRestCommand;
FLoadComercioCategoriaCommand: TDSRestCommand;
FLoadComercioCategoriaCommand_Cache: TDSRestCommand;
FLoadSubCategoriaCommand: TDSRestCommand;
FLoadSubCategoriaCommand_Cache: TDSRestCommand;
FLoadFotosPorSecaoCommand: TDSRestCommand;
FLoadFotosPorSecaoCommand_Cache: TDSRestCommand;
FLoadComercioPesquisaCommand: TDSRestCommand;
FLoadComercioPesquisaCommand_Cache: TDSRestCommand;
FLoadDestaqueFavoritoCommand: TDSRestCommand;
FLoadDestaqueFavoritoCommand_Cache: TDSRestCommand;
FRecebeNotificacaoCommand: TDSRestCommand;
FVerificaUsuarioAvaliouCommand: TDSRestCommand;
FLoadComercioCommand: TDSRestCommand;
FLoadComercioCommand_Cache: TDSRestCommand;
FLoadAvaliacoesCommand: TDSRestCommand;
FLoadAvaliacoesCommand_Cache: TDSRestCommand;
FVerificaCelularDuplicadoCommand: TDSRestCommand;
FVerificaCelularDuplicadoCommand_Cache: TDSRestCommand;
FDownloadIdUsuarioCommand: TDSRestCommand;
FDownloadIdUsuarioCommand_Cache: TDSRestCommand;
FDownloadUsuarioCommand: TDSRestCommand;
FDownloadUsuarioCommand_Cache: TDSRestCommand;
FDownloadUsuarioIdCommand: TDSRestCommand;
FDownloadUsuarioIdCommand_Cache: TDSRestCommand;
FUpdateUsuarioCommand: TDSRestCommand;
FInsertUsuarioCommand: TDSRestCommand;
FControleFavoritoCommand: TDSRestCommand;
FRegistrarDispositivoCommand: TDSRestCommand;
FIsFavoritoCommand: TDSRestCommand;
FSQLServerCommand: TDSRestCommand;
FSQLServerCommand_Cache: TDSRestCommand;
FUpdateAcessoUsuCommand: TDSRestCommand;
FSalvaHistoricoUsuCommand: TDSRestCommand;
FgetControleCommand: TDSRestCommand;
FgetControleCommand_Cache: TDSRestCommand;
FgetNotificacoesCommand: TDSRestCommand;
FgetNotificacoesCommand_Cache: TDSRestCommand;
FgetAvaliacaoCompletaCommand: TDSRestCommand;
FgetAvaliacaoCompletaCommand_Cache: TDSRestCommand;
FSalvaAvaliacaoCommand: TDSRestCommand;
FDeletePushCommand: TDSRestCommand;
FgetAnunciosCommand: TDSRestCommand;
FgetAnunciosCommand_Cache: TDSRestCommand;
FAtivaPushCommand: TDSRestCommand;
FNovoComercioCommand: TDSRestCommand;
FComercioCadastradoCommand: TDSRestCommand;
FUpdateRaioUsuarioCommand: TDSRestCommand;
FGravaUltimaPosicaoUsuarioCommand: TDSRestCommand;
public
constructor Create(ARestConnection: TDSRestConnection); overload;
constructor Create(ARestConnection: TDSRestConnection; AInstanceOwner: Boolean); overload;
destructor Destroy; override;
function LoadCategorias(AIdPush: string; ARaio: Integer; const ARequestFilter: string = ''): TFDJSONDataSets;
function LoadCategorias_Cache(AIdPush: string; ARaio: Integer; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets;
function LoadDestaquePrincipal(AIdPush: string; ARaio: Integer; const ARequestFilter: string = ''): TFDJSONDataSets;
function LoadDestaquePrincipal_Cache(AIdPush: string; ARaio: Integer; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets;
function LoadComercioCategoria(AIdPush: string; ARaio: Integer; IdCategoria: Integer; IdSubCategoria: Integer; const ARequestFilter: string = ''): TFDJSONDataSets;
function LoadComercioCategoria_Cache(AIdPush: string; ARaio: Integer; IdCategoria: Integer; IdSubCategoria: Integer; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets;
function LoadSubCategoria(AIdPush: string; ARaio: Integer; IdCategoria: Integer; const ARequestFilter: string = ''): TFDJSONDataSets;
function LoadSubCategoria_Cache(AIdPush: string; ARaio: Integer; IdCategoria: Integer; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets;
function LoadFotosPorSecao(ARaio: Integer; vIdCat: Integer; APesquisa: string; AIdPush: string; const ARequestFilter: string = ''): TFDJSONDataSets;
function LoadFotosPorSecao_Cache(ARaio: Integer; vIdCat: Integer; APesquisa: string; AIdPush: string; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets;
function LoadComercioPesquisa(ARaio: Integer; FPesquisa: string; AIdPush: string; const ARequestFilter: string = ''): TFDJSONDataSets;
function LoadComercioPesquisa_Cache(ARaio: Integer; FPesquisa: string; AIdPush: string; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets;
function LoadDestaqueFavorito(AIdPush: string; ARaio: Integer; vIdUsu: Integer; const ARequestFilter: string = ''): TFDJSONDataSets;
function LoadDestaqueFavorito_Cache(AIdPush: string; ARaio: Integer; vIdUsu: Integer; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets;
function RecebeNotificacao(AKeyPush: string; const ARequestFilter: string = ''): Boolean;
function VerificaUsuarioAvaliou(AIdUsu: Integer; AIdCom: Integer; const ARequestFilter: string = ''): Boolean;
function LoadComercio(idComercio: Integer; const ARequestFilter: string = ''): TFDJSONDataSets;
function LoadComercio_Cache(idComercio: Integer; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets;
function LoadAvaliacoes(idComercio: Integer; nStart: Integer; const ARequestFilter: string = ''): TFDJSONDataSets;
function LoadAvaliacoes_Cache(idComercio: Integer; nStart: Integer; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets;
function VerificaCelularDuplicado(vCelular: string; const ARequestFilter: string = ''): TFDJSONDataSets;
function VerificaCelularDuplicado_Cache(vCelular: string; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets;
function DownloadIdUsuario(vCelular: string; const ARequestFilter: string = ''): TFDJSONDataSets;
function DownloadIdUsuario_Cache(vCelular: string; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets;
function DownloadUsuario(vCelular: string; const ARequestFilter: string = ''): TFDJSONDataSets;
function DownloadUsuario_Cache(vCelular: string; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets;
function DownloadUsuarioId(fIdUsu: Integer; const ARequestFilter: string = ''): TFDJSONDataSets;
function DownloadUsuarioId_Cache(fIdUsu: Integer; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets;
function UpdateUsuario(FNome: string; FCelular: string; FSenha: string; FID: Integer; const ARequestFilter: string = ''): Boolean;
function InsertUsuario(FNome: string; FCelular: string; FSenha: string; const ARequestFilter: string = ''): Boolean;
procedure ControleFavorito(FIdUsu: Integer; FIdCom: Integer; FAction: string);
procedure RegistrarDispositivo(ADeviceToken: string; AIdUsu: Integer);
function IsFavorito(FIdUsu: Integer; FIdCom: Integer; const ARequestFilter: string = ''): Boolean;
function SQLServer(cSql: string; const ARequestFilter: string = ''): TFDJSONDataSets;
function SQLServer_Cache(cSql: string; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets;
function UpdateAcessoUsu(vIdUsu: Integer; const ARequestFilter: string = ''): Boolean;
function SalvaHistoricoUsu(hIdUsu: Integer; hIdCat: Integer; hIdSubCat: Integer; hIdCom: Integer; hPqsUsu: string; const ARequestFilter: string = ''): Boolean;
function getControle(const ARequestFilter: string = ''): TFDJSONDataSets;
function getControle_Cache(const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets;
function getNotificacoes(AIdUsu: Integer; const ARequestFilter: string = ''): TFDJSONDataSets;
function getNotificacoes_Cache(AIdUsu: Integer; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets;
function getAvaliacaoCompleta(AIdAvaliacao: Integer; const ARequestFilter: string = ''): TFDJSONDataSets;
function getAvaliacaoCompleta_Cache(AIdAvaliacao: Integer; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets;
procedure SalvaAvaliacao(AIdCom: Integer; AIdUsu: Integer; AAmbiente: Single; AAtendimento: Single; ALimpeza: Single; ALocalizacao: Single; APreco: Single; AMedia: Single; AComentario: string);
procedure DeletePush(AIdUsu: Integer; AIdPush: Integer);
function getAnuncios(AIdCom: Integer; const ARequestFilter: string = ''): TFDJSONDataSets;
function getAnuncios_Cache(AIdCom: Integer; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets;
procedure AtivaPush(AKeyPush: string; AAtiva: Boolean);
procedure NovoComercio(ACnpj: string; ARazao: string; AEmail: string; AFone: string; AContato: string);
function ComercioCadastrado(ACNPJ: string; const ARequestFilter: string = ''): Boolean;
function UpdateRaioUsuario(AIdUsuario: Integer; ARaio: Integer; const ARequestFilter: string = ''): Boolean;
procedure GravaUltimaPosicaoUsuario(ALatitude: string; ALongitude: string; ADeviceToken: string);
end;
IDSRestCachedTFDJSONDataSets = interface(IDSRestCachedObject<TFDJSONDataSets>)
end;
TDSRestCachedTFDJSONDataSets = class(TDSRestCachedObject<TFDJSONDataSets>, IDSRestCachedTFDJSONDataSets, IDSRestCachedCommand)
end;
const
TServerMethods_LoadCategorias: array [0..2] of TDSRestParameterMetaData =
(
(Name: 'AIdPush'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: 'ARaio'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets')
);
TServerMethods_LoadCategorias_Cache: array [0..2] of TDSRestParameterMetaData =
(
(Name: 'AIdPush'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: 'ARaio'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: ''; Direction: 4; DBXType: 26; TypeName: 'String')
);
TServerMethods_LoadDestaquePrincipal: array [0..2] of TDSRestParameterMetaData =
(
(Name: 'AIdPush'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: 'ARaio'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets')
);
TServerMethods_LoadDestaquePrincipal_Cache: array [0..2] of TDSRestParameterMetaData =
(
(Name: 'AIdPush'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: 'ARaio'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: ''; Direction: 4; DBXType: 26; TypeName: 'String')
);
TServerMethods_LoadComercioCategoria: array [0..4] of TDSRestParameterMetaData =
(
(Name: 'AIdPush'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: 'ARaio'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: 'IdCategoria'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: 'IdSubCategoria'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets')
);
TServerMethods_LoadComercioCategoria_Cache: array [0..4] of TDSRestParameterMetaData =
(
(Name: 'AIdPush'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: 'ARaio'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: 'IdCategoria'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: 'IdSubCategoria'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: ''; Direction: 4; DBXType: 26; TypeName: 'String')
);
TServerMethods_LoadSubCategoria: array [0..3] of TDSRestParameterMetaData =
(
(Name: 'AIdPush'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: 'ARaio'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: 'IdCategoria'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets')
);
TServerMethods_LoadSubCategoria_Cache: array [0..3] of TDSRestParameterMetaData =
(
(Name: 'AIdPush'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: 'ARaio'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: 'IdCategoria'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: ''; Direction: 4; DBXType: 26; TypeName: 'String')
);
TServerMethods_LoadFotosPorSecao: array [0..4] of TDSRestParameterMetaData =
(
(Name: 'ARaio'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: 'vIdCat'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: 'APesquisa'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: 'AIdPush'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets')
);
TServerMethods_LoadFotosPorSecao_Cache: array [0..4] of TDSRestParameterMetaData =
(
(Name: 'ARaio'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: 'vIdCat'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: 'APesquisa'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: 'AIdPush'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: ''; Direction: 4; DBXType: 26; TypeName: 'String')
);
TServerMethods_LoadComercioPesquisa: array [0..3] of TDSRestParameterMetaData =
(
(Name: 'ARaio'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: 'FPesquisa'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: 'AIdPush'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets')
);
TServerMethods_LoadComercioPesquisa_Cache: array [0..3] of TDSRestParameterMetaData =
(
(Name: 'ARaio'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: 'FPesquisa'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: 'AIdPush'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: ''; Direction: 4; DBXType: 26; TypeName: 'String')
);
TServerMethods_LoadDestaqueFavorito: array [0..3] of TDSRestParameterMetaData =
(
(Name: 'AIdPush'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: 'ARaio'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: 'vIdUsu'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets')
);
TServerMethods_LoadDestaqueFavorito_Cache: array [0..3] of TDSRestParameterMetaData =
(
(Name: 'AIdPush'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: 'ARaio'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: 'vIdUsu'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: ''; Direction: 4; DBXType: 26; TypeName: 'String')
);
TServerMethods_RecebeNotificacao: array [0..1] of TDSRestParameterMetaData =
(
(Name: 'AKeyPush'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: ''; Direction: 4; DBXType: 4; TypeName: 'Boolean')
);
TServerMethods_VerificaUsuarioAvaliou: array [0..2] of TDSRestParameterMetaData =
(
(Name: 'AIdUsu'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: 'AIdCom'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: ''; Direction: 4; DBXType: 4; TypeName: 'Boolean')
);
TServerMethods_LoadComercio: array [0..1] of TDSRestParameterMetaData =
(
(Name: 'idComercio'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets')
);
TServerMethods_LoadComercio_Cache: array [0..1] of TDSRestParameterMetaData =
(
(Name: 'idComercio'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: ''; Direction: 4; DBXType: 26; TypeName: 'String')
);
TServerMethods_LoadAvaliacoes: array [0..2] of TDSRestParameterMetaData =
(
(Name: 'idComercio'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: 'nStart'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets')
);
TServerMethods_LoadAvaliacoes_Cache: array [0..2] of TDSRestParameterMetaData =
(
(Name: 'idComercio'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: 'nStart'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: ''; Direction: 4; DBXType: 26; TypeName: 'String')
);
TServerMethods_VerificaCelularDuplicado: array [0..1] of TDSRestParameterMetaData =
(
(Name: 'vCelular'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets')
);
TServerMethods_VerificaCelularDuplicado_Cache: array [0..1] of TDSRestParameterMetaData =
(
(Name: 'vCelular'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: ''; Direction: 4; DBXType: 26; TypeName: 'String')
);
TServerMethods_DownloadIdUsuario: array [0..1] of TDSRestParameterMetaData =
(
(Name: 'vCelular'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets')
);
TServerMethods_DownloadIdUsuario_Cache: array [0..1] of TDSRestParameterMetaData =
(
(Name: 'vCelular'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: ''; Direction: 4; DBXType: 26; TypeName: 'String')
);
TServerMethods_DownloadUsuario: array [0..1] of TDSRestParameterMetaData =
(
(Name: 'vCelular'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets')
);
TServerMethods_DownloadUsuario_Cache: array [0..1] of TDSRestParameterMetaData =
(
(Name: 'vCelular'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: ''; Direction: 4; DBXType: 26; TypeName: 'String')
);
TServerMethods_DownloadUsuarioId: array [0..1] of TDSRestParameterMetaData =
(
(Name: 'fIdUsu'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets')
);
TServerMethods_DownloadUsuarioId_Cache: array [0..1] of TDSRestParameterMetaData =
(
(Name: 'fIdUsu'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: ''; Direction: 4; DBXType: 26; TypeName: 'String')
);
TServerMethods_UpdateUsuario: array [0..4] of TDSRestParameterMetaData =
(
(Name: 'FNome'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: 'FCelular'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: 'FSenha'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: 'FID'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: ''; Direction: 4; DBXType: 4; TypeName: 'Boolean')
);
TServerMethods_InsertUsuario: array [0..3] of TDSRestParameterMetaData =
(
(Name: 'FNome'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: 'FCelular'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: 'FSenha'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: ''; Direction: 4; DBXType: 4; TypeName: 'Boolean')
);
TServerMethods_ControleFavorito: array [0..2] of TDSRestParameterMetaData =
(
(Name: 'FIdUsu'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: 'FIdCom'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: 'FAction'; Direction: 1; DBXType: 26; TypeName: 'string')
);
TServerMethods_RegistrarDispositivo: array [0..1] of TDSRestParameterMetaData =
(
(Name: 'ADeviceToken'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: 'AIdUsu'; Direction: 1; DBXType: 6; TypeName: 'Integer')
);
TServerMethods_IsFavorito: array [0..2] of TDSRestParameterMetaData =
(
(Name: 'FIdUsu'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: 'FIdCom'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: ''; Direction: 4; DBXType: 4; TypeName: 'Boolean')
);
TServerMethods_SQLServer: array [0..1] of TDSRestParameterMetaData =
(
(Name: 'cSql'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets')
);
TServerMethods_SQLServer_Cache: array [0..1] of TDSRestParameterMetaData =
(
(Name: 'cSql'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: ''; Direction: 4; DBXType: 26; TypeName: 'String')
);
TServerMethods_UpdateAcessoUsu: array [0..1] of TDSRestParameterMetaData =
(
(Name: 'vIdUsu'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: ''; Direction: 4; DBXType: 4; TypeName: 'Boolean')
);
TServerMethods_SalvaHistoricoUsu: array [0..5] of TDSRestParameterMetaData =
(
(Name: 'hIdUsu'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: 'hIdCat'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: 'hIdSubCat'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: 'hIdCom'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: 'hPqsUsu'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: ''; Direction: 4; DBXType: 4; TypeName: 'Boolean')
);
TServerMethods_getControle: array [0..0] of TDSRestParameterMetaData =
(
(Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets')
);
TServerMethods_getControle_Cache: array [0..0] of TDSRestParameterMetaData =
(
(Name: ''; Direction: 4; DBXType: 26; TypeName: 'String')
);
TServerMethods_getNotificacoes: array [0..1] of TDSRestParameterMetaData =
(
(Name: 'AIdUsu'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets')
);
TServerMethods_getNotificacoes_Cache: array [0..1] of TDSRestParameterMetaData =
(
(Name: 'AIdUsu'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: ''; Direction: 4; DBXType: 26; TypeName: 'String')
);
TServerMethods_getAvaliacaoCompleta: array [0..1] of TDSRestParameterMetaData =
(
(Name: 'AIdAvaliacao'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets')
);
TServerMethods_getAvaliacaoCompleta_Cache: array [0..1] of TDSRestParameterMetaData =
(
(Name: 'AIdAvaliacao'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: ''; Direction: 4; DBXType: 26; TypeName: 'String')
);
TServerMethods_SalvaAvaliacao: array [0..8] of TDSRestParameterMetaData =
(
(Name: 'AIdCom'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: 'AIdUsu'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: 'AAmbiente'; Direction: 1; DBXType: 27; TypeName: 'Single'),
(Name: 'AAtendimento'; Direction: 1; DBXType: 27; TypeName: 'Single'),
(Name: 'ALimpeza'; Direction: 1; DBXType: 27; TypeName: 'Single'),
(Name: 'ALocalizacao'; Direction: 1; DBXType: 27; TypeName: 'Single'),
(Name: 'APreco'; Direction: 1; DBXType: 27; TypeName: 'Single'),
(Name: 'AMedia'; Direction: 1; DBXType: 27; TypeName: 'Single'),
(Name: 'AComentario'; Direction: 1; DBXType: 26; TypeName: 'string')
);
TServerMethods_DeletePush: array [0..1] of TDSRestParameterMetaData =
(
(Name: 'AIdUsu'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: 'AIdPush'; Direction: 1; DBXType: 6; TypeName: 'Integer')
);
TServerMethods_getAnuncios: array [0..1] of TDSRestParameterMetaData =
(
(Name: 'AIdCom'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets')
);
TServerMethods_getAnuncios_Cache: array [0..1] of TDSRestParameterMetaData =
(
(Name: 'AIdCom'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: ''; Direction: 4; DBXType: 26; TypeName: 'String')
);
TServerMethods_AtivaPush: array [0..1] of TDSRestParameterMetaData =
(
(Name: 'AKeyPush'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: 'AAtiva'; Direction: 1; DBXType: 4; TypeName: 'Boolean')
);
TServerMethods_NovoComercio: array [0..4] of TDSRestParameterMetaData =
(
(Name: 'ACnpj'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: 'ARazao'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: 'AEmail'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: 'AFone'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: 'AContato'; Direction: 1; DBXType: 26; TypeName: 'string')
);
TServerMethods_ComercioCadastrado: array [0..1] of TDSRestParameterMetaData =
(
(Name: 'ACNPJ'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: ''; Direction: 4; DBXType: 4; TypeName: 'Boolean')
);
TServerMethods_UpdateRaioUsuario: array [0..2] of TDSRestParameterMetaData =
(
(Name: 'AIdUsuario'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: 'ARaio'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: ''; Direction: 4; DBXType: 4; TypeName: 'Boolean')
);
TServerMethods_GravaUltimaPosicaoUsuario: array [0..2] of TDSRestParameterMetaData =
(
(Name: 'ALatitude'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: 'ALongitude'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: 'ADeviceToken'; Direction: 1; DBXType: 26; TypeName: 'string')
);
implementation
function TServerMethodsClient.LoadCategorias(AIdPush: string; ARaio: Integer; const ARequestFilter: string): TFDJSONDataSets;
begin
if FLoadCategoriasCommand = nil then
begin
FLoadCategoriasCommand := FConnection.CreateCommand;
FLoadCategoriasCommand.RequestType := 'GET';
FLoadCategoriasCommand.Text := 'TServerMethods.LoadCategorias';
FLoadCategoriasCommand.Prepare(TServerMethods_LoadCategorias);
end;
FLoadCategoriasCommand.Parameters[0].Value.SetWideString(AIdPush);
FLoadCategoriasCommand.Parameters[1].Value.SetInt32(ARaio);
FLoadCategoriasCommand.Execute(ARequestFilter);
if not FLoadCategoriasCommand.Parameters[2].Value.IsNull then
begin
FUnMarshal := TDSRestCommand(FLoadCategoriasCommand.Parameters[2].ConnectionHandler).GetJSONUnMarshaler;
try
Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FLoadCategoriasCommand.Parameters[2].Value.GetJSONValue(True)));
if FInstanceOwner then
FLoadCategoriasCommand.FreeOnExecute(Result);
finally
FreeAndNil(FUnMarshal)
end
end
else
Result := nil;
end;
function TServerMethodsClient.LoadCategorias_Cache(AIdPush: string; ARaio: Integer; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets;
begin
if FLoadCategoriasCommand_Cache = nil then
begin
FLoadCategoriasCommand_Cache := FConnection.CreateCommand;
FLoadCategoriasCommand_Cache.RequestType := 'GET';
FLoadCategoriasCommand_Cache.Text := 'TServerMethods.LoadCategorias';
FLoadCategoriasCommand_Cache.Prepare(TServerMethods_LoadCategorias_Cache);
end;
FLoadCategoriasCommand_Cache.Parameters[0].Value.SetWideString(AIdPush);
FLoadCategoriasCommand_Cache.Parameters[1].Value.SetInt32(ARaio);
FLoadCategoriasCommand_Cache.ExecuteCache(ARequestFilter);
Result := TDSRestCachedTFDJSONDataSets.Create(FLoadCategoriasCommand_Cache.Parameters[2].Value.GetString);
end;
function TServerMethodsClient.LoadDestaquePrincipal(AIdPush: string; ARaio: Integer; const ARequestFilter: string): TFDJSONDataSets;
begin
if FLoadDestaquePrincipalCommand = nil then
begin
FLoadDestaquePrincipalCommand := FConnection.CreateCommand;
FLoadDestaquePrincipalCommand.RequestType := 'GET';
FLoadDestaquePrincipalCommand.Text := 'TServerMethods.LoadDestaquePrincipal';
FLoadDestaquePrincipalCommand.Prepare(TServerMethods_LoadDestaquePrincipal);
end;
FLoadDestaquePrincipalCommand.Parameters[0].Value.SetWideString(AIdPush);
FLoadDestaquePrincipalCommand.Parameters[1].Value.SetInt32(ARaio);
FLoadDestaquePrincipalCommand.Execute(ARequestFilter);
if not FLoadDestaquePrincipalCommand.Parameters[2].Value.IsNull then
begin
FUnMarshal := TDSRestCommand(FLoadDestaquePrincipalCommand.Parameters[2].ConnectionHandler).GetJSONUnMarshaler;
try
Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FLoadDestaquePrincipalCommand.Parameters[2].Value.GetJSONValue(True)));
if FInstanceOwner then
FLoadDestaquePrincipalCommand.FreeOnExecute(Result);
finally
FreeAndNil(FUnMarshal)
end
end
else
Result := nil;
end;
function TServerMethodsClient.LoadDestaquePrincipal_Cache(AIdPush: string; ARaio: Integer; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets;
begin
if FLoadDestaquePrincipalCommand_Cache = nil then
begin
FLoadDestaquePrincipalCommand_Cache := FConnection.CreateCommand;
FLoadDestaquePrincipalCommand_Cache.RequestType := 'GET';
FLoadDestaquePrincipalCommand_Cache.Text := 'TServerMethods.LoadDestaquePrincipal';
FLoadDestaquePrincipalCommand_Cache.Prepare(TServerMethods_LoadDestaquePrincipal_Cache);
end;
FLoadDestaquePrincipalCommand_Cache.Parameters[0].Value.SetWideString(AIdPush);
FLoadDestaquePrincipalCommand_Cache.Parameters[1].Value.SetInt32(ARaio);
FLoadDestaquePrincipalCommand_Cache.ExecuteCache(ARequestFilter);
Result := TDSRestCachedTFDJSONDataSets.Create(FLoadDestaquePrincipalCommand_Cache.Parameters[2].Value.GetString);
end;
function TServerMethodsClient.LoadComercioCategoria(AIdPush: string; ARaio: Integer; IdCategoria: Integer; IdSubCategoria: Integer; const ARequestFilter: string): TFDJSONDataSets;
begin
if FLoadComercioCategoriaCommand = nil then
begin
FLoadComercioCategoriaCommand := FConnection.CreateCommand;
FLoadComercioCategoriaCommand.RequestType := 'GET';
FLoadComercioCategoriaCommand.Text := 'TServerMethods.LoadComercioCategoria';
FLoadComercioCategoriaCommand.Prepare(TServerMethods_LoadComercioCategoria);
end;
FLoadComercioCategoriaCommand.Parameters[0].Value.SetWideString(AIdPush);
FLoadComercioCategoriaCommand.Parameters[1].Value.SetInt32(ARaio);
FLoadComercioCategoriaCommand.Parameters[2].Value.SetInt32(IdCategoria);
FLoadComercioCategoriaCommand.Parameters[3].Value.SetInt32(IdSubCategoria);
FLoadComercioCategoriaCommand.Execute(ARequestFilter);
if not FLoadComercioCategoriaCommand.Parameters[4].Value.IsNull then
begin
FUnMarshal := TDSRestCommand(FLoadComercioCategoriaCommand.Parameters[4].ConnectionHandler).GetJSONUnMarshaler;
try
Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FLoadComercioCategoriaCommand.Parameters[4].Value.GetJSONValue(True)));
if FInstanceOwner then
FLoadComercioCategoriaCommand.FreeOnExecute(Result);
finally
FreeAndNil(FUnMarshal)
end
end
else
Result := nil;
end;
function TServerMethodsClient.LoadComercioCategoria_Cache(AIdPush: string; ARaio: Integer; IdCategoria: Integer; IdSubCategoria: Integer; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets;
begin
if FLoadComercioCategoriaCommand_Cache = nil then
begin
FLoadComercioCategoriaCommand_Cache := FConnection.CreateCommand;
FLoadComercioCategoriaCommand_Cache.RequestType := 'GET';
FLoadComercioCategoriaCommand_Cache.Text := 'TServerMethods.LoadComercioCategoria';
FLoadComercioCategoriaCommand_Cache.Prepare(TServerMethods_LoadComercioCategoria_Cache);
end;
FLoadComercioCategoriaCommand_Cache.Parameters[0].Value.SetWideString(AIdPush);
FLoadComercioCategoriaCommand_Cache.Parameters[1].Value.SetInt32(ARaio);
FLoadComercioCategoriaCommand_Cache.Parameters[2].Value.SetInt32(IdCategoria);
FLoadComercioCategoriaCommand_Cache.Parameters[3].Value.SetInt32(IdSubCategoria);
FLoadComercioCategoriaCommand_Cache.ExecuteCache(ARequestFilter);
Result := TDSRestCachedTFDJSONDataSets.Create(FLoadComercioCategoriaCommand_Cache.Parameters[4].Value.GetString);
end;
function TServerMethodsClient.LoadSubCategoria(AIdPush: string; ARaio: Integer; IdCategoria: Integer; const ARequestFilter: string): TFDJSONDataSets;
begin
if FLoadSubCategoriaCommand = nil then
begin
FLoadSubCategoriaCommand := FConnection.CreateCommand;
FLoadSubCategoriaCommand.RequestType := 'GET';
FLoadSubCategoriaCommand.Text := 'TServerMethods.LoadSubCategoria';
FLoadSubCategoriaCommand.Prepare(TServerMethods_LoadSubCategoria);
end;
FLoadSubCategoriaCommand.Parameters[0].Value.SetWideString(AIdPush);
FLoadSubCategoriaCommand.Parameters[1].Value.SetInt32(ARaio);
FLoadSubCategoriaCommand.Parameters[2].Value.SetInt32(IdCategoria);
FLoadSubCategoriaCommand.Execute(ARequestFilter);
if not FLoadSubCategoriaCommand.Parameters[3].Value.IsNull then
begin
FUnMarshal := TDSRestCommand(FLoadSubCategoriaCommand.Parameters[3].ConnectionHandler).GetJSONUnMarshaler;
try
Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FLoadSubCategoriaCommand.Parameters[3].Value.GetJSONValue(True)));
if FInstanceOwner then
FLoadSubCategoriaCommand.FreeOnExecute(Result);
finally
FreeAndNil(FUnMarshal)
end
end
else
Result := nil;
end;
function TServerMethodsClient.LoadSubCategoria_Cache(AIdPush: string; ARaio: Integer; IdCategoria: Integer; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets;
begin
if FLoadSubCategoriaCommand_Cache = nil then
begin
FLoadSubCategoriaCommand_Cache := FConnection.CreateCommand;
FLoadSubCategoriaCommand_Cache.RequestType := 'GET';
FLoadSubCategoriaCommand_Cache.Text := 'TServerMethods.LoadSubCategoria';
FLoadSubCategoriaCommand_Cache.Prepare(TServerMethods_LoadSubCategoria_Cache);
end;
FLoadSubCategoriaCommand_Cache.Parameters[0].Value.SetWideString(AIdPush);
FLoadSubCategoriaCommand_Cache.Parameters[1].Value.SetInt32(ARaio);
FLoadSubCategoriaCommand_Cache.Parameters[2].Value.SetInt32(IdCategoria);
FLoadSubCategoriaCommand_Cache.ExecuteCache(ARequestFilter);
Result := TDSRestCachedTFDJSONDataSets.Create(FLoadSubCategoriaCommand_Cache.Parameters[3].Value.GetString);
end;
function TServerMethodsClient.LoadFotosPorSecao(ARaio: Integer; vIdCat: Integer; APesquisa: string; AIdPush: string; const ARequestFilter: string): TFDJSONDataSets;
begin
if FLoadFotosPorSecaoCommand = nil then
begin
FLoadFotosPorSecaoCommand := FConnection.CreateCommand;
FLoadFotosPorSecaoCommand.RequestType := 'GET';
FLoadFotosPorSecaoCommand.Text := 'TServerMethods.LoadFotosPorSecao';
FLoadFotosPorSecaoCommand.Prepare(TServerMethods_LoadFotosPorSecao);
end;
FLoadFotosPorSecaoCommand.Parameters[0].Value.SetInt32(ARaio);
FLoadFotosPorSecaoCommand.Parameters[1].Value.SetInt32(vIdCat);
FLoadFotosPorSecaoCommand.Parameters[2].Value.SetWideString(APesquisa);
FLoadFotosPorSecaoCommand.Parameters[3].Value.SetWideString(AIdPush);
FLoadFotosPorSecaoCommand.Execute(ARequestFilter);
if not FLoadFotosPorSecaoCommand.Parameters[4].Value.IsNull then
begin
FUnMarshal := TDSRestCommand(FLoadFotosPorSecaoCommand.Parameters[4].ConnectionHandler).GetJSONUnMarshaler;
try
Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FLoadFotosPorSecaoCommand.Parameters[4].Value.GetJSONValue(True)));
if FInstanceOwner then
FLoadFotosPorSecaoCommand.FreeOnExecute(Result);
finally
FreeAndNil(FUnMarshal)
end
end
else
Result := nil;
end;
function TServerMethodsClient.LoadFotosPorSecao_Cache(ARaio: Integer; vIdCat: Integer; APesquisa: string; AIdPush: string; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets;
begin
if FLoadFotosPorSecaoCommand_Cache = nil then
begin
FLoadFotosPorSecaoCommand_Cache := FConnection.CreateCommand;
FLoadFotosPorSecaoCommand_Cache.RequestType := 'GET';
FLoadFotosPorSecaoCommand_Cache.Text := 'TServerMethods.LoadFotosPorSecao';
FLoadFotosPorSecaoCommand_Cache.Prepare(TServerMethods_LoadFotosPorSecao_Cache);
end;
FLoadFotosPorSecaoCommand_Cache.Parameters[0].Value.SetInt32(ARaio);
FLoadFotosPorSecaoCommand_Cache.Parameters[1].Value.SetInt32(vIdCat);
FLoadFotosPorSecaoCommand_Cache.Parameters[2].Value.SetWideString(APesquisa);
FLoadFotosPorSecaoCommand_Cache.Parameters[3].Value.SetWideString(AIdPush);
FLoadFotosPorSecaoCommand_Cache.ExecuteCache(ARequestFilter);
Result := TDSRestCachedTFDJSONDataSets.Create(FLoadFotosPorSecaoCommand_Cache.Parameters[4].Value.GetString);
end;
function TServerMethodsClient.LoadComercioPesquisa(ARaio: Integer; FPesquisa: string; AIdPush: string; const ARequestFilter: string): TFDJSONDataSets;
begin
if FLoadComercioPesquisaCommand = nil then
begin
FLoadComercioPesquisaCommand := FConnection.CreateCommand;
FLoadComercioPesquisaCommand.RequestType := 'GET';
FLoadComercioPesquisaCommand.Text := 'TServerMethods.LoadComercioPesquisa';
FLoadComercioPesquisaCommand.Prepare(TServerMethods_LoadComercioPesquisa);
end;
FLoadComercioPesquisaCommand.Parameters[0].Value.SetInt32(ARaio);
FLoadComercioPesquisaCommand.Parameters[1].Value.SetWideString(FPesquisa);
FLoadComercioPesquisaCommand.Parameters[2].Value.SetWideString(AIdPush);
FLoadComercioPesquisaCommand.Execute(ARequestFilter);
if not FLoadComercioPesquisaCommand.Parameters[3].Value.IsNull then
begin
FUnMarshal := TDSRestCommand(FLoadComercioPesquisaCommand.Parameters[3].ConnectionHandler).GetJSONUnMarshaler;
try
Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FLoadComercioPesquisaCommand.Parameters[3].Value.GetJSONValue(True)));
if FInstanceOwner then
FLoadComercioPesquisaCommand.FreeOnExecute(Result);
finally
FreeAndNil(FUnMarshal)
end
end
else
Result := nil;
end;
function TServerMethodsClient.LoadComercioPesquisa_Cache(ARaio: Integer; FPesquisa: string; AIdPush: string; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets;
begin
if FLoadComercioPesquisaCommand_Cache = nil then
begin
FLoadComercioPesquisaCommand_Cache := FConnection.CreateCommand;
FLoadComercioPesquisaCommand_Cache.RequestType := 'GET';
FLoadComercioPesquisaCommand_Cache.Text := 'TServerMethods.LoadComercioPesquisa';
FLoadComercioPesquisaCommand_Cache.Prepare(TServerMethods_LoadComercioPesquisa_Cache);
end;
FLoadComercioPesquisaCommand_Cache.Parameters[0].Value.SetInt32(ARaio);
FLoadComercioPesquisaCommand_Cache.Parameters[1].Value.SetWideString(FPesquisa);
FLoadComercioPesquisaCommand_Cache.Parameters[2].Value.SetWideString(AIdPush);
FLoadComercioPesquisaCommand_Cache.ExecuteCache(ARequestFilter);
Result := TDSRestCachedTFDJSONDataSets.Create(FLoadComercioPesquisaCommand_Cache.Parameters[3].Value.GetString);
end;
function TServerMethodsClient.LoadDestaqueFavorito(AIdPush: string; ARaio: Integer; vIdUsu: Integer; const ARequestFilter: string): TFDJSONDataSets;
begin
if FLoadDestaqueFavoritoCommand = nil then
begin
FLoadDestaqueFavoritoCommand := FConnection.CreateCommand;
FLoadDestaqueFavoritoCommand.RequestType := 'GET';
FLoadDestaqueFavoritoCommand.Text := 'TServerMethods.LoadDestaqueFavorito';
FLoadDestaqueFavoritoCommand.Prepare(TServerMethods_LoadDestaqueFavorito);
end;
FLoadDestaqueFavoritoCommand.Parameters[0].Value.SetWideString(AIdPush);
FLoadDestaqueFavoritoCommand.Parameters[1].Value.SetInt32(ARaio);
FLoadDestaqueFavoritoCommand.Parameters[2].Value.SetInt32(vIdUsu);
FLoadDestaqueFavoritoCommand.Execute(ARequestFilter);
if not FLoadDestaqueFavoritoCommand.Parameters[3].Value.IsNull then
begin
FUnMarshal := TDSRestCommand(FLoadDestaqueFavoritoCommand.Parameters[3].ConnectionHandler).GetJSONUnMarshaler;
try
Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FLoadDestaqueFavoritoCommand.Parameters[3].Value.GetJSONValue(True)));
if FInstanceOwner then
FLoadDestaqueFavoritoCommand.FreeOnExecute(Result);
finally
FreeAndNil(FUnMarshal)
end
end
else
Result := nil;
end;
function TServerMethodsClient.LoadDestaqueFavorito_Cache(AIdPush: string; ARaio: Integer; vIdUsu: Integer; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets;
begin
if FLoadDestaqueFavoritoCommand_Cache = nil then
begin
FLoadDestaqueFavoritoCommand_Cache := FConnection.CreateCommand;
FLoadDestaqueFavoritoCommand_Cache.RequestType := 'GET';
FLoadDestaqueFavoritoCommand_Cache.Text := 'TServerMethods.LoadDestaqueFavorito';
FLoadDestaqueFavoritoCommand_Cache.Prepare(TServerMethods_LoadDestaqueFavorito_Cache);
end;
FLoadDestaqueFavoritoCommand_Cache.Parameters[0].Value.SetWideString(AIdPush);
FLoadDestaqueFavoritoCommand_Cache.Parameters[1].Value.SetInt32(ARaio);
FLoadDestaqueFavoritoCommand_Cache.Parameters[2].Value.SetInt32(vIdUsu);
FLoadDestaqueFavoritoCommand_Cache.ExecuteCache(ARequestFilter);
Result := TDSRestCachedTFDJSONDataSets.Create(FLoadDestaqueFavoritoCommand_Cache.Parameters[3].Value.GetString);
end;
function TServerMethodsClient.RecebeNotificacao(AKeyPush: string; const ARequestFilter: string): Boolean;
begin
if FRecebeNotificacaoCommand = nil then
begin
FRecebeNotificacaoCommand := FConnection.CreateCommand;
FRecebeNotificacaoCommand.RequestType := 'GET';
FRecebeNotificacaoCommand.Text := 'TServerMethods.RecebeNotificacao';
FRecebeNotificacaoCommand.Prepare(TServerMethods_RecebeNotificacao);
end;
FRecebeNotificacaoCommand.Parameters[0].Value.SetWideString(AKeyPush);
FRecebeNotificacaoCommand.Execute(ARequestFilter);
Result := FRecebeNotificacaoCommand.Parameters[1].Value.GetBoolean;
end;
function TServerMethodsClient.VerificaUsuarioAvaliou(AIdUsu: Integer; AIdCom: Integer; const ARequestFilter: string): Boolean;
begin
if FVerificaUsuarioAvaliouCommand = nil then
begin
FVerificaUsuarioAvaliouCommand := FConnection.CreateCommand;
FVerificaUsuarioAvaliouCommand.RequestType := 'GET';
FVerificaUsuarioAvaliouCommand.Text := 'TServerMethods.VerificaUsuarioAvaliou';
FVerificaUsuarioAvaliouCommand.Prepare(TServerMethods_VerificaUsuarioAvaliou);
end;
FVerificaUsuarioAvaliouCommand.Parameters[0].Value.SetInt32(AIdUsu);
FVerificaUsuarioAvaliouCommand.Parameters[1].Value.SetInt32(AIdCom);
FVerificaUsuarioAvaliouCommand.Execute(ARequestFilter);
Result := FVerificaUsuarioAvaliouCommand.Parameters[2].Value.GetBoolean;
end;
function TServerMethodsClient.LoadComercio(idComercio: Integer; const ARequestFilter: string): TFDJSONDataSets;
begin
if FLoadComercioCommand = nil then
begin
FLoadComercioCommand := FConnection.CreateCommand;
FLoadComercioCommand.RequestType := 'GET';
FLoadComercioCommand.Text := 'TServerMethods.LoadComercio';
FLoadComercioCommand.Prepare(TServerMethods_LoadComercio);
end;
FLoadComercioCommand.Parameters[0].Value.SetInt32(idComercio);
FLoadComercioCommand.Execute(ARequestFilter);
if not FLoadComercioCommand.Parameters[1].Value.IsNull then
begin
FUnMarshal := TDSRestCommand(FLoadComercioCommand.Parameters[1].ConnectionHandler).GetJSONUnMarshaler;
try
Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FLoadComercioCommand.Parameters[1].Value.GetJSONValue(True)));
if FInstanceOwner then
FLoadComercioCommand.FreeOnExecute(Result);
finally
FreeAndNil(FUnMarshal)
end
end
else
Result := nil;
end;
function TServerMethodsClient.LoadComercio_Cache(idComercio: Integer; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets;
begin
if FLoadComercioCommand_Cache = nil then
begin
FLoadComercioCommand_Cache := FConnection.CreateCommand;
FLoadComercioCommand_Cache.RequestType := 'GET';
FLoadComercioCommand_Cache.Text := 'TServerMethods.LoadComercio';
FLoadComercioCommand_Cache.Prepare(TServerMethods_LoadComercio_Cache);
end;
FLoadComercioCommand_Cache.Parameters[0].Value.SetInt32(idComercio);
FLoadComercioCommand_Cache.ExecuteCache(ARequestFilter);
Result := TDSRestCachedTFDJSONDataSets.Create(FLoadComercioCommand_Cache.Parameters[1].Value.GetString);
end;
function TServerMethodsClient.LoadAvaliacoes(idComercio: Integer; nStart: Integer; const ARequestFilter: string): TFDJSONDataSets;
begin
if FLoadAvaliacoesCommand = nil then
begin
FLoadAvaliacoesCommand := FConnection.CreateCommand;
FLoadAvaliacoesCommand.RequestType := 'GET';
FLoadAvaliacoesCommand.Text := 'TServerMethods.LoadAvaliacoes';
FLoadAvaliacoesCommand.Prepare(TServerMethods_LoadAvaliacoes);
end;
FLoadAvaliacoesCommand.Parameters[0].Value.SetInt32(idComercio);
FLoadAvaliacoesCommand.Parameters[1].Value.SetInt32(nStart);
FLoadAvaliacoesCommand.Execute(ARequestFilter);
if not FLoadAvaliacoesCommand.Parameters[2].Value.IsNull then
begin
FUnMarshal := TDSRestCommand(FLoadAvaliacoesCommand.Parameters[2].ConnectionHandler).GetJSONUnMarshaler;
try
Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FLoadAvaliacoesCommand.Parameters[2].Value.GetJSONValue(True)));
if FInstanceOwner then
FLoadAvaliacoesCommand.FreeOnExecute(Result);
finally
FreeAndNil(FUnMarshal)
end
end
else
Result := nil;
end;
function TServerMethodsClient.LoadAvaliacoes_Cache(idComercio: Integer; nStart: Integer; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets;
begin
if FLoadAvaliacoesCommand_Cache = nil then
begin
FLoadAvaliacoesCommand_Cache := FConnection.CreateCommand;
FLoadAvaliacoesCommand_Cache.RequestType := 'GET';
FLoadAvaliacoesCommand_Cache.Text := 'TServerMethods.LoadAvaliacoes';
FLoadAvaliacoesCommand_Cache.Prepare(TServerMethods_LoadAvaliacoes_Cache);
end;
FLoadAvaliacoesCommand_Cache.Parameters[0].Value.SetInt32(idComercio);
FLoadAvaliacoesCommand_Cache.Parameters[1].Value.SetInt32(nStart);
FLoadAvaliacoesCommand_Cache.ExecuteCache(ARequestFilter);
Result := TDSRestCachedTFDJSONDataSets.Create(FLoadAvaliacoesCommand_Cache.Parameters[2].Value.GetString);
end;
function TServerMethodsClient.VerificaCelularDuplicado(vCelular: string; const ARequestFilter: string): TFDJSONDataSets;
begin
if FVerificaCelularDuplicadoCommand = nil then
begin
FVerificaCelularDuplicadoCommand := FConnection.CreateCommand;
FVerificaCelularDuplicadoCommand.RequestType := 'GET';
FVerificaCelularDuplicadoCommand.Text := 'TServerMethods.VerificaCelularDuplicado';
FVerificaCelularDuplicadoCommand.Prepare(TServerMethods_VerificaCelularDuplicado);
end;
FVerificaCelularDuplicadoCommand.Parameters[0].Value.SetWideString(vCelular);
FVerificaCelularDuplicadoCommand.Execute(ARequestFilter);
if not FVerificaCelularDuplicadoCommand.Parameters[1].Value.IsNull then
begin
FUnMarshal := TDSRestCommand(FVerificaCelularDuplicadoCommand.Parameters[1].ConnectionHandler).GetJSONUnMarshaler;
try
Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FVerificaCelularDuplicadoCommand.Parameters[1].Value.GetJSONValue(True)));
if FInstanceOwner then
FVerificaCelularDuplicadoCommand.FreeOnExecute(Result);
finally
FreeAndNil(FUnMarshal)
end
end
else
Result := nil;
end;
function TServerMethodsClient.VerificaCelularDuplicado_Cache(vCelular: string; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets;
begin
if FVerificaCelularDuplicadoCommand_Cache = nil then
begin
FVerificaCelularDuplicadoCommand_Cache := FConnection.CreateCommand;
FVerificaCelularDuplicadoCommand_Cache.RequestType := 'GET';
FVerificaCelularDuplicadoCommand_Cache.Text := 'TServerMethods.VerificaCelularDuplicado';
FVerificaCelularDuplicadoCommand_Cache.Prepare(TServerMethods_VerificaCelularDuplicado_Cache);
end;
FVerificaCelularDuplicadoCommand_Cache.Parameters[0].Value.SetWideString(vCelular);
FVerificaCelularDuplicadoCommand_Cache.ExecuteCache(ARequestFilter);
Result := TDSRestCachedTFDJSONDataSets.Create(FVerificaCelularDuplicadoCommand_Cache.Parameters[1].Value.GetString);
end;
function TServerMethodsClient.DownloadIdUsuario(vCelular: string; const ARequestFilter: string): TFDJSONDataSets;
begin
if FDownloadIdUsuarioCommand = nil then
begin
FDownloadIdUsuarioCommand := FConnection.CreateCommand;
FDownloadIdUsuarioCommand.RequestType := 'GET';
FDownloadIdUsuarioCommand.Text := 'TServerMethods.DownloadIdUsuario';
FDownloadIdUsuarioCommand.Prepare(TServerMethods_DownloadIdUsuario);
end;
FDownloadIdUsuarioCommand.Parameters[0].Value.SetWideString(vCelular);
FDownloadIdUsuarioCommand.Execute(ARequestFilter);
if not FDownloadIdUsuarioCommand.Parameters[1].Value.IsNull then
begin
FUnMarshal := TDSRestCommand(FDownloadIdUsuarioCommand.Parameters[1].ConnectionHandler).GetJSONUnMarshaler;
try
Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FDownloadIdUsuarioCommand.Parameters[1].Value.GetJSONValue(True)));
if FInstanceOwner then
FDownloadIdUsuarioCommand.FreeOnExecute(Result);
finally
FreeAndNil(FUnMarshal)
end
end
else
Result := nil;
end;
function TServerMethodsClient.DownloadIdUsuario_Cache(vCelular: string; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets;
begin
if FDownloadIdUsuarioCommand_Cache = nil then
begin
FDownloadIdUsuarioCommand_Cache := FConnection.CreateCommand;
FDownloadIdUsuarioCommand_Cache.RequestType := 'GET';
FDownloadIdUsuarioCommand_Cache.Text := 'TServerMethods.DownloadIdUsuario';
FDownloadIdUsuarioCommand_Cache.Prepare(TServerMethods_DownloadIdUsuario_Cache);
end;
FDownloadIdUsuarioCommand_Cache.Parameters[0].Value.SetWideString(vCelular);
FDownloadIdUsuarioCommand_Cache.ExecuteCache(ARequestFilter);
Result := TDSRestCachedTFDJSONDataSets.Create(FDownloadIdUsuarioCommand_Cache.Parameters[1].Value.GetString);
end;
function TServerMethodsClient.DownloadUsuario(vCelular: string; const ARequestFilter: string): TFDJSONDataSets;
begin
if FDownloadUsuarioCommand = nil then
begin
FDownloadUsuarioCommand := FConnection.CreateCommand;
FDownloadUsuarioCommand.RequestType := 'GET';
FDownloadUsuarioCommand.Text := 'TServerMethods.DownloadUsuario';
FDownloadUsuarioCommand.Prepare(TServerMethods_DownloadUsuario);
end;
FDownloadUsuarioCommand.Parameters[0].Value.SetWideString(vCelular);
FDownloadUsuarioCommand.Execute(ARequestFilter);
if not FDownloadUsuarioCommand.Parameters[1].Value.IsNull then
begin
FUnMarshal := TDSRestCommand(FDownloadUsuarioCommand.Parameters[1].ConnectionHandler).GetJSONUnMarshaler;
try
Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FDownloadUsuarioCommand.Parameters[1].Value.GetJSONValue(True)));
if FInstanceOwner then
FDownloadUsuarioCommand.FreeOnExecute(Result);
finally
FreeAndNil(FUnMarshal)
end
end
else
Result := nil;
end;
function TServerMethodsClient.DownloadUsuario_Cache(vCelular: string; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets;
begin
if FDownloadUsuarioCommand_Cache = nil then
begin
FDownloadUsuarioCommand_Cache := FConnection.CreateCommand;
FDownloadUsuarioCommand_Cache.RequestType := 'GET';
FDownloadUsuarioCommand_Cache.Text := 'TServerMethods.DownloadUsuario';
FDownloadUsuarioCommand_Cache.Prepare(TServerMethods_DownloadUsuario_Cache);
end;
FDownloadUsuarioCommand_Cache.Parameters[0].Value.SetWideString(vCelular);
FDownloadUsuarioCommand_Cache.ExecuteCache(ARequestFilter);
Result := TDSRestCachedTFDJSONDataSets.Create(FDownloadUsuarioCommand_Cache.Parameters[1].Value.GetString);
end;
function TServerMethodsClient.DownloadUsuarioId(fIdUsu: Integer; const ARequestFilter: string): TFDJSONDataSets;
begin
if FDownloadUsuarioIdCommand = nil then
begin
FDownloadUsuarioIdCommand := FConnection.CreateCommand;
FDownloadUsuarioIdCommand.RequestType := 'GET';
FDownloadUsuarioIdCommand.Text := 'TServerMethods.DownloadUsuarioId';
FDownloadUsuarioIdCommand.Prepare(TServerMethods_DownloadUsuarioId);
end;
FDownloadUsuarioIdCommand.Parameters[0].Value.SetInt32(fIdUsu);
FDownloadUsuarioIdCommand.Execute(ARequestFilter);
if not FDownloadUsuarioIdCommand.Parameters[1].Value.IsNull then
begin
FUnMarshal := TDSRestCommand(FDownloadUsuarioIdCommand.Parameters[1].ConnectionHandler).GetJSONUnMarshaler;
try
Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FDownloadUsuarioIdCommand.Parameters[1].Value.GetJSONValue(True)));
if FInstanceOwner then
FDownloadUsuarioIdCommand.FreeOnExecute(Result);
finally
FreeAndNil(FUnMarshal)
end
end
else
Result := nil;
end;
function TServerMethodsClient.DownloadUsuarioId_Cache(fIdUsu: Integer; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets;
begin
if FDownloadUsuarioIdCommand_Cache = nil then
begin
FDownloadUsuarioIdCommand_Cache := FConnection.CreateCommand;
FDownloadUsuarioIdCommand_Cache.RequestType := 'GET';
FDownloadUsuarioIdCommand_Cache.Text := 'TServerMethods.DownloadUsuarioId';
FDownloadUsuarioIdCommand_Cache.Prepare(TServerMethods_DownloadUsuarioId_Cache);
end;
FDownloadUsuarioIdCommand_Cache.Parameters[0].Value.SetInt32(fIdUsu);
FDownloadUsuarioIdCommand_Cache.ExecuteCache(ARequestFilter);
Result := TDSRestCachedTFDJSONDataSets.Create(FDownloadUsuarioIdCommand_Cache.Parameters[1].Value.GetString);
end;
function TServerMethodsClient.UpdateUsuario(FNome: string; FCelular: string; FSenha: string; FID: Integer; const ARequestFilter: string): Boolean;
begin
if FUpdateUsuarioCommand = nil then
begin
FUpdateUsuarioCommand := FConnection.CreateCommand;
FUpdateUsuarioCommand.RequestType := 'GET';
FUpdateUsuarioCommand.Text := 'TServerMethods.UpdateUsuario';
FUpdateUsuarioCommand.Prepare(TServerMethods_UpdateUsuario);
end;
FUpdateUsuarioCommand.Parameters[0].Value.SetWideString(FNome);
FUpdateUsuarioCommand.Parameters[1].Value.SetWideString(FCelular);
FUpdateUsuarioCommand.Parameters[2].Value.SetWideString(FSenha);
FUpdateUsuarioCommand.Parameters[3].Value.SetInt32(FID);
FUpdateUsuarioCommand.Execute(ARequestFilter);
Result := FUpdateUsuarioCommand.Parameters[4].Value.GetBoolean;
end;
function TServerMethodsClient.InsertUsuario(FNome: string; FCelular: string; FSenha: string; const ARequestFilter: string): Boolean;
begin
if FInsertUsuarioCommand = nil then
begin
FInsertUsuarioCommand := FConnection.CreateCommand;
FInsertUsuarioCommand.RequestType := 'GET';
FInsertUsuarioCommand.Text := 'TServerMethods.InsertUsuario';
FInsertUsuarioCommand.Prepare(TServerMethods_InsertUsuario);
end;
FInsertUsuarioCommand.Parameters[0].Value.SetWideString(FNome);
FInsertUsuarioCommand.Parameters[1].Value.SetWideString(FCelular);
FInsertUsuarioCommand.Parameters[2].Value.SetWideString(FSenha);
FInsertUsuarioCommand.Execute(ARequestFilter);
Result := FInsertUsuarioCommand.Parameters[3].Value.GetBoolean;
end;
procedure TServerMethodsClient.ControleFavorito(FIdUsu: Integer; FIdCom: Integer; FAction: string);
begin
if FControleFavoritoCommand = nil then
begin
FControleFavoritoCommand := FConnection.CreateCommand;
FControleFavoritoCommand.RequestType := 'GET';
FControleFavoritoCommand.Text := 'TServerMethods.ControleFavorito';
FControleFavoritoCommand.Prepare(TServerMethods_ControleFavorito);
end;
FControleFavoritoCommand.Parameters[0].Value.SetInt32(FIdUsu);
FControleFavoritoCommand.Parameters[1].Value.SetInt32(FIdCom);
FControleFavoritoCommand.Parameters[2].Value.SetWideString(FAction);
FControleFavoritoCommand.Execute;
end;
procedure TServerMethodsClient.RegistrarDispositivo(ADeviceToken: string; AIdUsu: Integer);
begin
if FRegistrarDispositivoCommand = nil then
begin
FRegistrarDispositivoCommand := FConnection.CreateCommand;
FRegistrarDispositivoCommand.RequestType := 'GET';
FRegistrarDispositivoCommand.Text := 'TServerMethods.RegistrarDispositivo';
FRegistrarDispositivoCommand.Prepare(TServerMethods_RegistrarDispositivo);
end;
FRegistrarDispositivoCommand.Parameters[0].Value.SetWideString(ADeviceToken);
FRegistrarDispositivoCommand.Parameters[1].Value.SetInt32(AIdUsu);
FRegistrarDispositivoCommand.Execute;
end;
function TServerMethodsClient.IsFavorito(FIdUsu: Integer; FIdCom: Integer; const ARequestFilter: string): Boolean;
begin
if FIsFavoritoCommand = nil then
begin
FIsFavoritoCommand := FConnection.CreateCommand;
FIsFavoritoCommand.RequestType := 'GET';
FIsFavoritoCommand.Text := 'TServerMethods.IsFavorito';
FIsFavoritoCommand.Prepare(TServerMethods_IsFavorito);
end;
FIsFavoritoCommand.Parameters[0].Value.SetInt32(FIdUsu);
FIsFavoritoCommand.Parameters[1].Value.SetInt32(FIdCom);
FIsFavoritoCommand.Execute(ARequestFilter);
Result := FIsFavoritoCommand.Parameters[2].Value.GetBoolean;
end;
function TServerMethodsClient.SQLServer(cSql: string; const ARequestFilter: string): TFDJSONDataSets;
begin
if FSQLServerCommand = nil then
begin
FSQLServerCommand := FConnection.CreateCommand;
FSQLServerCommand.RequestType := 'GET';
FSQLServerCommand.Text := 'TServerMethods.SQLServer';
FSQLServerCommand.Prepare(TServerMethods_SQLServer);
end;
FSQLServerCommand.Parameters[0].Value.SetWideString(cSql);
FSQLServerCommand.Execute(ARequestFilter);
if not FSQLServerCommand.Parameters[1].Value.IsNull then
begin
FUnMarshal := TDSRestCommand(FSQLServerCommand.Parameters[1].ConnectionHandler).GetJSONUnMarshaler;
try
Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FSQLServerCommand.Parameters[1].Value.GetJSONValue(True)));
if FInstanceOwner then
FSQLServerCommand.FreeOnExecute(Result);
finally
FreeAndNil(FUnMarshal)
end
end
else
Result := nil;
end;
function TServerMethodsClient.SQLServer_Cache(cSql: string; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets;
begin
if FSQLServerCommand_Cache = nil then
begin
FSQLServerCommand_Cache := FConnection.CreateCommand;
FSQLServerCommand_Cache.RequestType := 'GET';
FSQLServerCommand_Cache.Text := 'TServerMethods.SQLServer';
FSQLServerCommand_Cache.Prepare(TServerMethods_SQLServer_Cache);
end;
FSQLServerCommand_Cache.Parameters[0].Value.SetWideString(cSql);
FSQLServerCommand_Cache.ExecuteCache(ARequestFilter);
Result := TDSRestCachedTFDJSONDataSets.Create(FSQLServerCommand_Cache.Parameters[1].Value.GetString);
end;
function TServerMethodsClient.UpdateAcessoUsu(vIdUsu: Integer; const ARequestFilter: string): Boolean;
begin
if FUpdateAcessoUsuCommand = nil then
begin
FUpdateAcessoUsuCommand := FConnection.CreateCommand;
FUpdateAcessoUsuCommand.RequestType := 'GET';
FUpdateAcessoUsuCommand.Text := 'TServerMethods.UpdateAcessoUsu';
FUpdateAcessoUsuCommand.Prepare(TServerMethods_UpdateAcessoUsu);
end;
FUpdateAcessoUsuCommand.Parameters[0].Value.SetInt32(vIdUsu);
FUpdateAcessoUsuCommand.Execute(ARequestFilter);
Result := FUpdateAcessoUsuCommand.Parameters[1].Value.GetBoolean;
end;
function TServerMethodsClient.SalvaHistoricoUsu(hIdUsu: Integer; hIdCat: Integer; hIdSubCat: Integer; hIdCom: Integer; hPqsUsu: string; const ARequestFilter: string): Boolean;
begin
if FSalvaHistoricoUsuCommand = nil then
begin
FSalvaHistoricoUsuCommand := FConnection.CreateCommand;
FSalvaHistoricoUsuCommand.RequestType := 'GET';
FSalvaHistoricoUsuCommand.Text := 'TServerMethods.SalvaHistoricoUsu';
FSalvaHistoricoUsuCommand.Prepare(TServerMethods_SalvaHistoricoUsu);
end;
FSalvaHistoricoUsuCommand.Parameters[0].Value.SetInt32(hIdUsu);
FSalvaHistoricoUsuCommand.Parameters[1].Value.SetInt32(hIdCat);
FSalvaHistoricoUsuCommand.Parameters[2].Value.SetInt32(hIdSubCat);
FSalvaHistoricoUsuCommand.Parameters[3].Value.SetInt32(hIdCom);
FSalvaHistoricoUsuCommand.Parameters[4].Value.SetWideString(hPqsUsu);
FSalvaHistoricoUsuCommand.Execute(ARequestFilter);
Result := FSalvaHistoricoUsuCommand.Parameters[5].Value.GetBoolean;
end;
function TServerMethodsClient.getControle(const ARequestFilter: string): TFDJSONDataSets;
begin
if FgetControleCommand = nil then
begin
FgetControleCommand := FConnection.CreateCommand;
FgetControleCommand.RequestType := 'GET';
FgetControleCommand.Text := 'TServerMethods.getControle';
FgetControleCommand.Prepare(TServerMethods_getControle);
end;
FgetControleCommand.Execute(ARequestFilter);
if not FgetControleCommand.Parameters[0].Value.IsNull then
begin
FUnMarshal := TDSRestCommand(FgetControleCommand.Parameters[0].ConnectionHandler).GetJSONUnMarshaler;
try
Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FgetControleCommand.Parameters[0].Value.GetJSONValue(True)));
if FInstanceOwner then
FgetControleCommand.FreeOnExecute(Result);
finally
FreeAndNil(FUnMarshal)
end
end
else
Result := nil;
end;
function TServerMethodsClient.getControle_Cache(const ARequestFilter: string): IDSRestCachedTFDJSONDataSets;
begin
if FgetControleCommand_Cache = nil then
begin
FgetControleCommand_Cache := FConnection.CreateCommand;
FgetControleCommand_Cache.RequestType := 'GET';
FgetControleCommand_Cache.Text := 'TServerMethods.getControle';
FgetControleCommand_Cache.Prepare(TServerMethods_getControle_Cache);
end;
FgetControleCommand_Cache.ExecuteCache(ARequestFilter);
Result := TDSRestCachedTFDJSONDataSets.Create(FgetControleCommand_Cache.Parameters[0].Value.GetString);
end;
function TServerMethodsClient.getNotificacoes(AIdUsu: Integer; const ARequestFilter: string): TFDJSONDataSets;
begin
if FgetNotificacoesCommand = nil then
begin
FgetNotificacoesCommand := FConnection.CreateCommand;
FgetNotificacoesCommand.RequestType := 'GET';
FgetNotificacoesCommand.Text := 'TServerMethods.getNotificacoes';
FgetNotificacoesCommand.Prepare(TServerMethods_getNotificacoes);
end;
FgetNotificacoesCommand.Parameters[0].Value.SetInt32(AIdUsu);
FgetNotificacoesCommand.Execute(ARequestFilter);
if not FgetNotificacoesCommand.Parameters[1].Value.IsNull then
begin
FUnMarshal := TDSRestCommand(FgetNotificacoesCommand.Parameters[1].ConnectionHandler).GetJSONUnMarshaler;
try
Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FgetNotificacoesCommand.Parameters[1].Value.GetJSONValue(True)));
if FInstanceOwner then
FgetNotificacoesCommand.FreeOnExecute(Result);
finally
FreeAndNil(FUnMarshal)
end
end
else
Result := nil;
end;
function TServerMethodsClient.getNotificacoes_Cache(AIdUsu: Integer; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets;
begin
if FgetNotificacoesCommand_Cache = nil then
begin
FgetNotificacoesCommand_Cache := FConnection.CreateCommand;
FgetNotificacoesCommand_Cache.RequestType := 'GET';
FgetNotificacoesCommand_Cache.Text := 'TServerMethods.getNotificacoes';
FgetNotificacoesCommand_Cache.Prepare(TServerMethods_getNotificacoes_Cache);
end;
FgetNotificacoesCommand_Cache.Parameters[0].Value.SetInt32(AIdUsu);
FgetNotificacoesCommand_Cache.ExecuteCache(ARequestFilter);
Result := TDSRestCachedTFDJSONDataSets.Create(FgetNotificacoesCommand_Cache.Parameters[1].Value.GetString);
end;
function TServerMethodsClient.getAvaliacaoCompleta(AIdAvaliacao: Integer; const ARequestFilter: string): TFDJSONDataSets;
begin
if FgetAvaliacaoCompletaCommand = nil then
begin
FgetAvaliacaoCompletaCommand := FConnection.CreateCommand;
FgetAvaliacaoCompletaCommand.RequestType := 'GET';
FgetAvaliacaoCompletaCommand.Text := 'TServerMethods.getAvaliacaoCompleta';
FgetAvaliacaoCompletaCommand.Prepare(TServerMethods_getAvaliacaoCompleta);
end;
FgetAvaliacaoCompletaCommand.Parameters[0].Value.SetInt32(AIdAvaliacao);
FgetAvaliacaoCompletaCommand.Execute(ARequestFilter);
if not FgetAvaliacaoCompletaCommand.Parameters[1].Value.IsNull then
begin
FUnMarshal := TDSRestCommand(FgetAvaliacaoCompletaCommand.Parameters[1].ConnectionHandler).GetJSONUnMarshaler;
try
Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FgetAvaliacaoCompletaCommand.Parameters[1].Value.GetJSONValue(True)));
if FInstanceOwner then
FgetAvaliacaoCompletaCommand.FreeOnExecute(Result);
finally
FreeAndNil(FUnMarshal)
end
end
else
Result := nil;
end;
function TServerMethodsClient.getAvaliacaoCompleta_Cache(AIdAvaliacao: Integer; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets;
begin
if FgetAvaliacaoCompletaCommand_Cache = nil then
begin
FgetAvaliacaoCompletaCommand_Cache := FConnection.CreateCommand;
FgetAvaliacaoCompletaCommand_Cache.RequestType := 'GET';
FgetAvaliacaoCompletaCommand_Cache.Text := 'TServerMethods.getAvaliacaoCompleta';
FgetAvaliacaoCompletaCommand_Cache.Prepare(TServerMethods_getAvaliacaoCompleta_Cache);
end;
FgetAvaliacaoCompletaCommand_Cache.Parameters[0].Value.SetInt32(AIdAvaliacao);
FgetAvaliacaoCompletaCommand_Cache.ExecuteCache(ARequestFilter);
Result := TDSRestCachedTFDJSONDataSets.Create(FgetAvaliacaoCompletaCommand_Cache.Parameters[1].Value.GetString);
end;
procedure TServerMethodsClient.SalvaAvaliacao(AIdCom: Integer; AIdUsu: Integer; AAmbiente: Single; AAtendimento: Single; ALimpeza: Single; ALocalizacao: Single; APreco: Single; AMedia: Single; AComentario: string);
begin
if FSalvaAvaliacaoCommand = nil then
begin
FSalvaAvaliacaoCommand := FConnection.CreateCommand;
FSalvaAvaliacaoCommand.RequestType := 'GET';
FSalvaAvaliacaoCommand.Text := 'TServerMethods.SalvaAvaliacao';
FSalvaAvaliacaoCommand.Prepare(TServerMethods_SalvaAvaliacao);
end;
FSalvaAvaliacaoCommand.Parameters[0].Value.SetInt32(AIdCom);
FSalvaAvaliacaoCommand.Parameters[1].Value.SetInt32(AIdUsu);
FSalvaAvaliacaoCommand.Parameters[2].Value.SetSingle(AAmbiente);
FSalvaAvaliacaoCommand.Parameters[3].Value.SetSingle(AAtendimento);
FSalvaAvaliacaoCommand.Parameters[4].Value.SetSingle(ALimpeza);
FSalvaAvaliacaoCommand.Parameters[5].Value.SetSingle(ALocalizacao);
FSalvaAvaliacaoCommand.Parameters[6].Value.SetSingle(APreco);
FSalvaAvaliacaoCommand.Parameters[7].Value.SetSingle(AMedia);
FSalvaAvaliacaoCommand.Parameters[8].Value.SetWideString(AComentario);
FSalvaAvaliacaoCommand.Execute;
end;
procedure TServerMethodsClient.DeletePush(AIdUsu: Integer; AIdPush: Integer);
begin
if FDeletePushCommand = nil then
begin
FDeletePushCommand := FConnection.CreateCommand;
FDeletePushCommand.RequestType := 'GET';
FDeletePushCommand.Text := 'TServerMethods.DeletePush';
FDeletePushCommand.Prepare(TServerMethods_DeletePush);
end;
FDeletePushCommand.Parameters[0].Value.SetInt32(AIdUsu);
FDeletePushCommand.Parameters[1].Value.SetInt32(AIdPush);
FDeletePushCommand.Execute;
end;
function TServerMethodsClient.getAnuncios(AIdCom: Integer; const ARequestFilter: string): TFDJSONDataSets;
begin
if FgetAnunciosCommand = nil then
begin
FgetAnunciosCommand := FConnection.CreateCommand;
FgetAnunciosCommand.RequestType := 'GET';
FgetAnunciosCommand.Text := 'TServerMethods.getAnuncios';
FgetAnunciosCommand.Prepare(TServerMethods_getAnuncios);
end;
FgetAnunciosCommand.Parameters[0].Value.SetInt32(AIdCom);
FgetAnunciosCommand.Execute(ARequestFilter);
if not FgetAnunciosCommand.Parameters[1].Value.IsNull then
begin
FUnMarshal := TDSRestCommand(FgetAnunciosCommand.Parameters[1].ConnectionHandler).GetJSONUnMarshaler;
try
Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FgetAnunciosCommand.Parameters[1].Value.GetJSONValue(True)));
if FInstanceOwner then
FgetAnunciosCommand.FreeOnExecute(Result);
finally
FreeAndNil(FUnMarshal)
end
end
else
Result := nil;
end;
function TServerMethodsClient.getAnuncios_Cache(AIdCom: Integer; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets;
begin
if FgetAnunciosCommand_Cache = nil then
begin
FgetAnunciosCommand_Cache := FConnection.CreateCommand;
FgetAnunciosCommand_Cache.RequestType := 'GET';
FgetAnunciosCommand_Cache.Text := 'TServerMethods.getAnuncios';
FgetAnunciosCommand_Cache.Prepare(TServerMethods_getAnuncios_Cache);
end;
FgetAnunciosCommand_Cache.Parameters[0].Value.SetInt32(AIdCom);
FgetAnunciosCommand_Cache.ExecuteCache(ARequestFilter);
Result := TDSRestCachedTFDJSONDataSets.Create(FgetAnunciosCommand_Cache.Parameters[1].Value.GetString);
end;
procedure TServerMethodsClient.AtivaPush(AKeyPush: string; AAtiva: Boolean);
begin
if FAtivaPushCommand = nil then
begin
FAtivaPushCommand := FConnection.CreateCommand;
FAtivaPushCommand.RequestType := 'GET';
FAtivaPushCommand.Text := 'TServerMethods.AtivaPush';
FAtivaPushCommand.Prepare(TServerMethods_AtivaPush);
end;
FAtivaPushCommand.Parameters[0].Value.SetWideString(AKeyPush);
FAtivaPushCommand.Parameters[1].Value.SetBoolean(AAtiva);
FAtivaPushCommand.Execute;
end;
procedure TServerMethodsClient.NovoComercio(ACnpj: string; ARazao: string; AEmail: string; AFone: string; AContato: string);
begin
if FNovoComercioCommand = nil then
begin
FNovoComercioCommand := FConnection.CreateCommand;
FNovoComercioCommand.RequestType := 'GET';
FNovoComercioCommand.Text := 'TServerMethods.NovoComercio';
FNovoComercioCommand.Prepare(TServerMethods_NovoComercio);
end;
FNovoComercioCommand.Parameters[0].Value.SetWideString(ACnpj);
FNovoComercioCommand.Parameters[1].Value.SetWideString(ARazao);
FNovoComercioCommand.Parameters[2].Value.SetWideString(AEmail);
FNovoComercioCommand.Parameters[3].Value.SetWideString(AFone);
FNovoComercioCommand.Parameters[4].Value.SetWideString(AContato);
FNovoComercioCommand.Execute;
end;
function TServerMethodsClient.ComercioCadastrado(ACNPJ: string; const ARequestFilter: string): Boolean;
begin
if FComercioCadastradoCommand = nil then
begin
FComercioCadastradoCommand := FConnection.CreateCommand;
FComercioCadastradoCommand.RequestType := 'GET';
FComercioCadastradoCommand.Text := 'TServerMethods.ComercioCadastrado';
FComercioCadastradoCommand.Prepare(TServerMethods_ComercioCadastrado);
end;
FComercioCadastradoCommand.Parameters[0].Value.SetWideString(ACNPJ);
FComercioCadastradoCommand.Execute(ARequestFilter);
Result := FComercioCadastradoCommand.Parameters[1].Value.GetBoolean;
end;
function TServerMethodsClient.UpdateRaioUsuario(AIdUsuario: Integer; ARaio: Integer; const ARequestFilter: string): Boolean;
begin
if FUpdateRaioUsuarioCommand = nil then
begin
FUpdateRaioUsuarioCommand := FConnection.CreateCommand;
FUpdateRaioUsuarioCommand.RequestType := 'GET';
FUpdateRaioUsuarioCommand.Text := 'TServerMethods.UpdateRaioUsuario';
FUpdateRaioUsuarioCommand.Prepare(TServerMethods_UpdateRaioUsuario);
end;
FUpdateRaioUsuarioCommand.Parameters[0].Value.SetInt32(AIdUsuario);
FUpdateRaioUsuarioCommand.Parameters[1].Value.SetInt32(ARaio);
FUpdateRaioUsuarioCommand.Execute(ARequestFilter);
Result := FUpdateRaioUsuarioCommand.Parameters[2].Value.GetBoolean;
end;
procedure TServerMethodsClient.GravaUltimaPosicaoUsuario(ALatitude: string; ALongitude: string; ADeviceToken: string);
begin
if FGravaUltimaPosicaoUsuarioCommand = nil then
begin
FGravaUltimaPosicaoUsuarioCommand := FConnection.CreateCommand;
FGravaUltimaPosicaoUsuarioCommand.RequestType := 'GET';
FGravaUltimaPosicaoUsuarioCommand.Text := 'TServerMethods.GravaUltimaPosicaoUsuario';
FGravaUltimaPosicaoUsuarioCommand.Prepare(TServerMethods_GravaUltimaPosicaoUsuario);
end;
FGravaUltimaPosicaoUsuarioCommand.Parameters[0].Value.SetWideString(ALatitude);
FGravaUltimaPosicaoUsuarioCommand.Parameters[1].Value.SetWideString(ALongitude);
FGravaUltimaPosicaoUsuarioCommand.Parameters[2].Value.SetWideString(ADeviceToken);
FGravaUltimaPosicaoUsuarioCommand.Execute;
end;
constructor TServerMethodsClient.Create(ARestConnection: TDSRestConnection);
begin
inherited Create(ARestConnection);
end;
constructor TServerMethodsClient.Create(ARestConnection: TDSRestConnection; AInstanceOwner: Boolean);
begin
inherited Create(ARestConnection, AInstanceOwner);
end;
destructor TServerMethodsClient.Destroy;
begin
FLoadCategoriasCommand.DisposeOf;
FLoadCategoriasCommand_Cache.DisposeOf;
FLoadDestaquePrincipalCommand.DisposeOf;
FLoadDestaquePrincipalCommand_Cache.DisposeOf;
FLoadComercioCategoriaCommand.DisposeOf;
FLoadComercioCategoriaCommand_Cache.DisposeOf;
FLoadSubCategoriaCommand.DisposeOf;
FLoadSubCategoriaCommand_Cache.DisposeOf;
FLoadFotosPorSecaoCommand.DisposeOf;
FLoadFotosPorSecaoCommand_Cache.DisposeOf;
FLoadComercioPesquisaCommand.DisposeOf;
FLoadComercioPesquisaCommand_Cache.DisposeOf;
FLoadDestaqueFavoritoCommand.DisposeOf;
FLoadDestaqueFavoritoCommand_Cache.DisposeOf;
FRecebeNotificacaoCommand.DisposeOf;
FVerificaUsuarioAvaliouCommand.DisposeOf;
FLoadComercioCommand.DisposeOf;
FLoadComercioCommand_Cache.DisposeOf;
FLoadAvaliacoesCommand.DisposeOf;
FLoadAvaliacoesCommand_Cache.DisposeOf;
FVerificaCelularDuplicadoCommand.DisposeOf;
FVerificaCelularDuplicadoCommand_Cache.DisposeOf;
FDownloadIdUsuarioCommand.DisposeOf;
FDownloadIdUsuarioCommand_Cache.DisposeOf;
FDownloadUsuarioCommand.DisposeOf;
FDownloadUsuarioCommand_Cache.DisposeOf;
FDownloadUsuarioIdCommand.DisposeOf;
FDownloadUsuarioIdCommand_Cache.DisposeOf;
FUpdateUsuarioCommand.DisposeOf;
FInsertUsuarioCommand.DisposeOf;
FControleFavoritoCommand.DisposeOf;
FRegistrarDispositivoCommand.DisposeOf;
FIsFavoritoCommand.DisposeOf;
FSQLServerCommand.DisposeOf;
FSQLServerCommand_Cache.DisposeOf;
FUpdateAcessoUsuCommand.DisposeOf;
FSalvaHistoricoUsuCommand.DisposeOf;
FgetControleCommand.DisposeOf;
FgetControleCommand_Cache.DisposeOf;
FgetNotificacoesCommand.DisposeOf;
FgetNotificacoesCommand_Cache.DisposeOf;
FgetAvaliacaoCompletaCommand.DisposeOf;
FgetAvaliacaoCompletaCommand_Cache.DisposeOf;
FSalvaAvaliacaoCommand.DisposeOf;
FDeletePushCommand.DisposeOf;
FgetAnunciosCommand.DisposeOf;
FgetAnunciosCommand_Cache.DisposeOf;
FAtivaPushCommand.DisposeOf;
FNovoComercioCommand.DisposeOf;
FComercioCadastradoCommand.DisposeOf;
FUpdateRaioUsuarioCommand.DisposeOf;
FGravaUltimaPosicaoUsuarioCommand.DisposeOf;
inherited;
end;
end.
|
{--------------------------------------------------------}
{
{ Rotinas de comunicacao serial
{
{ Autor: José Antonio Borges
{
{ Em 26/04/98
{
{--------------------------------------------------------}
Unit dvComm;
interface
uses
windows, messages, sysUtils;
function inicLink (porta: word; vel: longint; nbits, nstop: byte; tipoParid: byte): integer;
{ Obs: nbits= 5, 6, 7, 8; nstop = 1, 2 }
{ paridade: 0-sem, 1-impar, 2-par }
{ erros: 0 = ok }
{ ERRO_DCB_COMM = erro ao montar dcb }
{ ERRO_ABRE_COMM = erro ao abrir porta com }
{ ERRO_CONF_COMM = erro ao configurar porta com }
procedure finalLink;
procedure escLink (c: char);
Function chegouLink: boolean;
procedure leLink (var c: char);
function erroLink: integer;
var
comId: integer;
const
ERRO_DCB_COMM = 1; { erro ao montar dcb }
ERRO_ABRE_COMM = 2; { erro ao abrir porta com }
ERRO_CONF_COMM = 3; { erro ao configurar porta com }
Implementation
{ constantes, tipos e variaveis }
const
TAMBUFREC = 65000; // 8192; { tamanho dos buffers }
TAMBUFTRANS = 4096;
var
modemDCB: TDCB; { controles da comunicacao }
erroCom: boolean;
ncBufLocal: integer; { controles do intermediário de recepçao }
pbuf: integer;
{--------------------------------------------------------}
{ inicializacao das interrupcoes
{--------------------------------------------------------}
function inicLink (porta: word;
vel: longint; nbits, nstop: byte;
tipoParid: byte): integer;
var
modemInit: array [0..80] of char;
cmdOpen: array [0..5] of char;
num: string [7];
{--------------------------------------------------------}
procedure configDCB;
const dcb_Binary = $00000001;
(*
DWORD fBinary :1;
DWORD fParity :1;
DWORD fOutxCtsFlow :1;
DWORD fOutxDsrFlow :1;
DWORD fDtrControl :2;
DWORD fDsrSensitivity :1;
DWORD fTXContinueOnXoff :1;
DWORD fOutX :1;
DWORD fInX :1;
DWORD fErrorChar :1;
DWORD fNull :1;
DWORD fRtsControl :2;
DWORD fAbortOnError :1;
DWORD fDummy2 :17;
*)
var
cmd: string;
par: char;
begin
case tipoParid of
1: par := 'O';
2: par := 'E';
else
par := 'N';
end;
cmd := 'COM' + intToStr (porta) + ':' +
' baud=' + intToStr (vel) +
' parity=' + par +
' data=' + intToStr (nbits) +
' stop=' + intToStr (nstop);
strPCopy (modemInit, cmd);
if not buildCommDCB (modemInit, modemDCB) then
begin
inicLink := ERRO_DCB_COMM;
exit;
end;
modemDCB.flags := modemDCB.flags or $1011 {dcb_Binary};
end;
{--------------------------------------------------------}
begin
if porta <= 0 then
begin
inicLink := ERRO_CONF_COMM;
exit;
end;
strCopy (cmdOpen, 'COM');
str (porta, num); num := num + #$0;
strCat (cmdOpen, @num[1]);
{$R-}
try
comId := CreateFile(cmdOpen,
GENERIC_READ or GENERIC_WRITE,
0, // Not shared
nil, // No security attributes
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0 // No template
) ;
except
comId := -1;
end;
{$R+}
if comId < 0 then
begin
inicLink := ERRO_ABRE_COMM;
exit;
end;
configDCB;
if not setCommState (comId, modemDCB) then
begin
inicLink := ERRO_CONF_COMM;
exit;
end;
SetupComm(comId, TAMBUFREC, TAMBUFTRANS);
inicLink := 0;
erroCom := false;
ncBufLocal := 0;
pbuf := 1;
end;
{--------------------------------------------------------}
{ finalizacao das comunicações
{--------------------------------------------------------}
procedure finalLink;
begin
if comId = 0 then exit;
CloseHandle (comId);
comId := 0;
end;
{--------------------------------------------------------}
{ escreve um byte na porta serial
{--------------------------------------------------------}
procedure escLink (c: char);
var nSent: DWORD;
begin
if comId = 0 then exit;
WriteFile(comId, c, 1, nSent, nil );
erroCom := nSent = 0;
end;
{--------------------------------------------------------}
{ ativa processamento do windows
{--------------------------------------------------------}
procedure processWindowsQueue;
var
M: TMsg;
begin
while PeekMessage(M, 0, 0, 0, pm_Remove) do
begin
TranslateMessage(M);
DispatchMessage(M);
end;
end;
{--------------------------------------------------------}
{ ve se chegou dado na porta serial
{--------------------------------------------------------}
function chegouLink: boolean;
var
dummy: DWORD;
comStat: TCOMSTAT;
begin
processWindowsQueue;
chegouLink := false;
if comId = 0 then exit;
ClearCommError(comId, dummy, @comStat);
chegouLink := comStat.cbInQue <> 0;
end;
{--------------------------------------------------------}
{ le um dado do buffer local
{--------------------------------------------------------}
procedure leLink (var c: char);
var nRead: DWORD;
begin
if comId <> 0 then
begin
repeat
processWindowsQueue;
until chegoulink;
ReadFile (comId, c, 1, nRead, nil);
end
else
nread := 0;
erroCom := nRead = 0;
end;
{--------------------------------------------------------}
{ verifica o erro e zera ele
{--------------------------------------------------------}
function erroLink: integer;
begin
erroLink := integer (erroCom) and 1;
erroCom := false;
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)
private
fItems: TObjectList;
procedure OnItemDestroyed(aSender: TObject);
public
constructor Create;
destructor Destroy; override;
// IInterfacedObjectList
protected
function get_Count: Integer;
function get_Item(const aIndex: Integer): IUnknown;
function get_Object(const aIndex: Integer): TObject;
function Add(const aInterface: IInterface): Integer; overload;
function Add(const aObject: TObject): Integer; overload;
procedure Delete(const aIndex: Integer);
function IndexOf(const aObject: TObject): Integer; overload;
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;
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;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
function TInterfacedObjectList.Add(const aInterface: IInterface): Integer;
var
i: IInterfacedObject;
begin
if NOT Supports(aInterface, IInterfacedObject, i) then
raise EInvalidOperation.CreateFmt('Items added to a %s must implement IInterfacedObject', [ClassName]);
result := Add(i.AsObject);
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
function TInterfacedObjectList.Add(const aObject: 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 := aObject;
if Assigned(aObject) then
begin
aObject.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(aObject, IInterfacedObject, intf)
and (NOT intf.IsReferenceCounted)
and Supports(aObject, IOn_Destroy, onDestroy) then
onDestroy.Add(OnItemDestroyed);
end;
result := fItems.Add(item);
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure TInterfacedObjectList.Delete(const aIndex: Integer);
begin
fItems.Delete(aIndex);
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.IndexOf(const aObject: TObject): Integer;
begin
for result := 0 to Pred(fItems.Count) do
if TListItem(fItems[result]).ItemObject = aObject then
EXIT;
result := -1;
end;
end.
|
unit AFSplitter;
interface
uses
HashAlg_U;
// "Standard" version; uses SHA-1
// n - Set to the number of stripes
function AFSplit(input: Ansistring; n: integer; var output: Ansistring): boolean; overload;
function AFMerge(input: Ansistring; n: integer; var output: Ansistring): boolean; overload;
// User specified hash algorithm
// n - Set to the number of stripes
function AFSplit(input: Ansistring; n: integer; hashAlg: THashAlg; var output: Ansistring): boolean; overload;
function AFMerge(input: Ansistring; n: integer; hashAlg: THashAlg; var output: Ansistring): boolean; overload;
implementation
uses
HashValue_U,
HashAlgSHA1_U,
SDUEndianIntegers;
function GetRandom(len: integer): Ansistring; forward;
function RepeatedHash(input: Ansistring; hashAlg: THashAlg; var output: Ansistring): boolean; forward;
function Process(stripeData: Ansistring; totalBlockCount: integer; blockLength: integer; hashAlg: THashAlg; var output: Ansistring): boolean; forward;
function GetBlock(stripeData: Ansistring; totalBlockCount: integer; blockLength: integer; blockNumber: integer; var output: Ansistring): boolean; forward;
function GetRandom(len: integer): string;
var
retVal: string;
i: integer;
begin
for i:=1 to len do
begin
retVal := retVal + Ansichar(random(256));
// xxx - debug use only - retVal := retVal + char(0);
{ TODO 2 -otdk -csecurity : this is not a secure PRNG - is it used anywhere it shouldnt be? }
end;
Result:= retVal;
end;
// Hash input repeatedly until a string with the same length is produced
function RepeatedHash(input: Ansistring; hashAlg: THashAlg; var output: Ansistring): boolean;
var
allOK: boolean;
digestSizeBytes: integer;
inputDivDigestBytes: integer;
inputModDigestBytes: integer;
i, j: integer;
tmpString: string;
hashOutput: THashValue;
begin
allOK := TRUE;
output := '';
hashOutput := THashValue.Create();
try
// Hash output
digestSizeBytes := (hashAlg.HashLength div 8);
inputDivDigestBytes := (length(input) div digestSizeBytes);
inputModDigestBytes := (length(input) mod digestSizeBytes);
for i:=0 to (inputDivDigestBytes-1) do
begin
tmpString := SDUBigEndian32ToString(SDUDWORDToBigEndian32(i));
for j:=0 to (digestSizeBytes-1) do
begin
// +1 because strings start from 1
tmpString := tmpString + input[((i*digestSizeBytes) + j + 1)];
end;
hashAlg.HashString(tmpString, hashOutput);
output := output + hashOutput.ValueAsBinary;
end;
if (inputModDigestBytes > 0) then
begin
tmpString := SDUBigEndian32ToString(SDUDWORDToBigEndian32(inputDivDigestBytes));
for j:=0 to (inputModDigestBytes-1) do
begin
// +1 because strings start from 1
tmpString := tmpString + input[((inputDivDigestBytes*digestSizeBytes) + j + 1)];
end;
hashAlg.HashString(tmpString, hashOutput);
tmpString := hashOutput.ValueAsBinary;
for j:=0 to (inputModDigestBytes-1) do
begin
// +1 because strings start from 1
output := output + tmpString[j + 1];
end;
end;
finally
hashOutput.Free();
end;
Result := allOK;
end;
function AFSplit(input: AnsiString; n: integer; var output: AnsiString): boolean;
var
hashAlg: THashAlg;
begin
// Hash output
hashAlg := THashAlgSHA1.Create(nil);
try
Result := AFSplit(input, n, hashAlg, output);
finally
hashAlg.Free();
end;
end;
function AFSplit(input: AnsiString; n: integer; hashAlg: THashAlg; var output: AnsiString): boolean;
var
allOK: boolean;
i, j: integer;
randomStripeData: string;
calcStripe: string;
processedStripes: string;
blockLength: integer;
begin
allOK := TRUE;
blockLength := length(input);
randomStripeData := '';
for i:=1 to (n-1) do
begin
// Get random block "i"
randomStripeData := randomStripeData + GetRandom(blockLength);
end;
Process(randomStripeData, n, blockLength, hashAlg, processedStripes);
// XOR last hash output with input
calcStripe := '';
for j:=1 to blockLength do
begin
calcStripe := calcStripe + Ansichar((ord(processedStripes[j]) XOR ord(input[j])));
end;
// Store result as random block "n" as output
output := randomStripeData + calcStripe;
Result := allOK;
end;
// Process blocks 1 - (n-1)
function Process(stripeData: Ansistring; totalBlockCount: integer; blockLength: integer; hashAlg: THashAlg; var output: Ansistring): boolean;
var
allOK: boolean;
prev: string;
i, j: integer;
tmpData: string;
hashedBlock: string;
blockN: string;
begin
allOK := TRUE;
prev := StringOfChar(#0, blockLength);
// -1 because we don't process the last block
for i:=1 to (totalBlockCount-1) do
begin
// Get block "i"
GetBlock(stripeData, totalBlockCount, blockLength, i, blockN);
// XOR previous block output with current stripe
tmpData := '';
for j:=1 to length(prev) do
begin
tmpData := tmpData + Ansichar((ord(prev[j]) XOR ord(blockN[j])));
end;
// Hash output
RepeatedHash(tmpData, hashAlg, hashedBlock);
// Setup for next iteration
prev := hashedBlock;
end;
// Store last hashing result as output
output := prev;
Result := allOK;
end;
// Get the "blockNumber" block out of "totalBlockCount"
function GetBlock(stripeData: Ansistring; totalBlockCount: integer; blockLength: integer; blockNumber: integer; var output: Ansistring): boolean;
var
allOK: boolean;
i: integer;
begin
allOK := TRUE;
// xxx - sanity checking
// Get block "i"
output := '';
for i:=0 to (blockLength-1) do
begin
// -1 because block numbers start from 1
// +1 because strings start from 1
output := output + stripeData[(((blockNumber-1) * blockLength) + i + 1)];
end;
Result := allOK;
end;
function AFMerge(input: string; n: integer; var output: string): boolean;
var
hashAlg: THashAlg;
begin
// Hash output
hashAlg := THashAlgSHA1.Create(nil);
try
Result := AFMerge(input, n, hashAlg, output);
finally
hashAlg.Free();
end;
end;
function AFMerge(input: Ansistring; n: integer; hashAlg: THashAlg; var output: Ansistring): boolean;
var
allOK: boolean;
i: integer;
processedStripes: string;
blockLength: integer;
lastBlock: string;
begin
allOK := TRUE;
blockLength := (length(input) div n);
Process(input, n, blockLength, hashAlg,processedStripes);
// Get block "i"
GetBlock(input, n, blockLength, n, lastBlock);
// XOR last hash output with last block to obtain original data
output := '';
for i:=1 to blockLength do
begin
output := output + Ansichar((ord(processedStripes[i]) XOR ord(lastBlock[i])));
end;
Result := allOK;
end;
END.
|
unit uFrmNewBarCode;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, siComp, siLangRT, PaiDeForms;
type
TFrmNewBarcode = class(TFrmParentForms)
EditBarcode: TEdit;
Panel1: TPanel;
Panel3: TPanel;
Panel6: TPanel;
Label1: TLabel;
Label3: TLabel;
btOK: TButton;
btCancel: TButton;
lbQty: TLabel;
edtQty: TEdit;
procedure btOKClick(Sender: TObject);
procedure btCancelClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure EditBarcodeKeyPress(Sender: TObject; var Key: Char);
private
BarCode : String;
public
function Start(var Barcode:String; var Qty: Double):Boolean;
end;
implementation
uses uDMGlobal, uMsgBox, uMsgConstant, uCharFunctions;
{$R *.DFM}
procedure TFrmNewBarcode.btOKClick(Sender: TObject);
begin
if Trim(EditBarCode.Text) = '' then
begin
EditBarCode.SetFocus;
raise exception.create('Barcode can not be empty');
end;
BarCode := Trim(EditBarCode.Text);
ModalResult := mrOK;
end;
function TFrmNewBarcode.Start(var Barcode:String; var Qty: Double):Boolean;
begin
EditBarCode.Text := '';
edtQty.Text := '';
ShowModal;
Result := (ModalResult = mrOK);
Barcode := EditBarCode.Text;
Qty := StrToFloatDef(edtQty.Text, 0);
end;
procedure TFrmNewBarcode.btCancelClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TFrmNewBarcode.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
Action := caFree;
end;
procedure TFrmNewBarcode.EditBarcodeKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
if Key = #32 then
Key := #0;
end;
end.
|
{
Autor: Vinícius Lopes de Melo
Data: 17/06/2014
Link: https://github.com/viniciuslopesmelo/Aplicacao-Delphi
}
unit untDMConexao;
interface
uses
SysUtils, Classes, DBXFirebird, DB,
SqlExpr, WideStrings, Dialogs, Forms,
DBXCommon;
type
TDMConexao = class(TDataModule)
ConexaoApp: TSQLConnection;
procedure DataModuleCreate(Sender: TObject);
protected
transactionApp : TDBXTransaction;
public
function confirmarTransacao: Boolean;
function iniciarTransacao: Boolean;
function reverterTransacao: Boolean;
function atualizarConexaoAplicativo: Boolean;
end;
var
DMConexao: TDMConexao;
implementation
// Usualmente não é recomendo que um DataModule enxergue um Form.
// Nesse caso tive de enxergar somente para criar o objeto do Form
// quando fosse para atualizar a conexao da aplicação.
uses
untFrmPrincipal, untDMPrincipal;
{$R *.dfm}
procedure TDMConexao.DataModuleCreate(Sender: TObject);
begin
atualizarConexaoAplicativo;
end;
function TDMConexao.atualizarConexaoAplicativo: Boolean;
begin
try
ConexaoApp.Connected := False;
ConexaoApp.Connected := True;
if (FormPrincipal = nil) then
Application.CreateForm(TFormPrincipal, FormPrincipal);
except
on E:Exception do
begin
DMPrincipal.imprimirMensagem('Não foi possível se conectar a base de dados.' + sLineBreak + sLineBreak +
'Erro: ' + E.Message,
'Erro');
Application.ProcessMessages;
Application.Terminate;
end;
end;
end;
function TDMConexao.confirmarTransacao: Boolean;
begin
ConexaoApp.CommitFreeAndNil(transactionApp);
end;
function TDMConexao.iniciarTransacao: Boolean;
begin
transactionApp := ConexaoApp.BeginTransaction;
end;
function TDMConexao.reverterTransacao: Boolean;
begin
ConexaoApp.RollbackFreeAndNil(transactionApp);
end;
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: VO relacionado à tabela [FISCAL_NOTA_FISCAL_ENTRADA]
The MIT License
Copyright: Copyright (C) 2014 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
*******************************************************************************}
unit FiscalNotaFiscalEntradaVO;
{$mode objfpc}{$H+}
interface
uses
VO, Classes, SysUtils, FGL;
type
TFiscalNotaFiscalEntradaVO = class(TVO)
private
FID: Integer;
FID_NFE_CABECALHO: Integer;
FCOMPETENCIA: String;
FCFOP_ENTRADA: Integer;
FVALOR_RATEIO_FRETE: Extended;
FVALOR_CUSTO_MEDIO: Extended;
FVALOR_ICMS_ANTECIPADO: Extended;
FVALOR_BC_ICMS_ANTECIPADO: Extended;
FVALOR_BC_ICMS_CREDITADO: Extended;
FVALOR_BC_PIS_CREDITADO: Extended;
FVALOR_BC_COFINS_CREDITADO: Extended;
FVALOR_BC_IPI_CREDITADO: Extended;
FCST_CREDITO_ICMS: String;
FCST_CREDITO_PIS: String;
FCST_CREDITO_COFINS: String;
FCST_CREDITO_IPI: String;
FVALOR_ICMS_CREDITADO: Extended;
FVALOR_PIS_CREDITADO: Extended;
FVALOR_COFINS_CREDITADO: Extended;
FVALOR_IPI_CREDITADO: Extended;
FQTDE_PARCELA_CREDITO_PIS: Integer;
FQTDE_PARCELA_CREDITO_COFINS: Integer;
FQTDE_PARCELA_CREDITO_ICMS: Integer;
FQTDE_PARCELA_CREDITO_IPI: Integer;
FALIQUOTA_CREDITO_ICMS: Extended;
FALIQUOTA_CREDITO_PIS: Extended;
FALIQUOTA_CREDITO_COFINS: Extended;
FALIQUOTA_CREDITO_IPI: Extended;
published
property Id: Integer read FID write FID;
property IdNfeCabecalho: Integer read FID_NFE_CABECALHO write FID_NFE_CABECALHO;
property Competencia: String read FCOMPETENCIA write FCOMPETENCIA;
property CfopEntrada: Integer read FCFOP_ENTRADA write FCFOP_ENTRADA;
property ValorRateioFrete: Extended read FVALOR_RATEIO_FRETE write FVALOR_RATEIO_FRETE;
property ValorCustoMedio: Extended read FVALOR_CUSTO_MEDIO write FVALOR_CUSTO_MEDIO;
property ValorIcmsAntecipado: Extended read FVALOR_ICMS_ANTECIPADO write FVALOR_ICMS_ANTECIPADO;
property ValorBcIcmsAntecipado: Extended read FVALOR_BC_ICMS_ANTECIPADO write FVALOR_BC_ICMS_ANTECIPADO;
property ValorBcIcmsCreditado: Extended read FVALOR_BC_ICMS_CREDITADO write FVALOR_BC_ICMS_CREDITADO;
property ValorBcPisCreditado: Extended read FVALOR_BC_PIS_CREDITADO write FVALOR_BC_PIS_CREDITADO;
property ValorBcCofinsCreditado: Extended read FVALOR_BC_COFINS_CREDITADO write FVALOR_BC_COFINS_CREDITADO;
property ValorBcIpiCreditado: Extended read FVALOR_BC_IPI_CREDITADO write FVALOR_BC_IPI_CREDITADO;
property CstCreditoIcms: String read FCST_CREDITO_ICMS write FCST_CREDITO_ICMS;
property CstCreditoPis: String read FCST_CREDITO_PIS write FCST_CREDITO_PIS;
property CstCreditoCofins: String read FCST_CREDITO_COFINS write FCST_CREDITO_COFINS;
property CstCreditoIpi: String read FCST_CREDITO_IPI write FCST_CREDITO_IPI;
property ValorIcmsCreditado: Extended read FVALOR_ICMS_CREDITADO write FVALOR_ICMS_CREDITADO;
property ValorPisCreditado: Extended read FVALOR_PIS_CREDITADO write FVALOR_PIS_CREDITADO;
property ValorCofinsCreditado: Extended read FVALOR_COFINS_CREDITADO write FVALOR_COFINS_CREDITADO;
property ValorIpiCreditado: Extended read FVALOR_IPI_CREDITADO write FVALOR_IPI_CREDITADO;
property QtdeParcelaCreditoPis: Integer read FQTDE_PARCELA_CREDITO_PIS write FQTDE_PARCELA_CREDITO_PIS;
property QtdeParcelaCreditoCofins: Integer read FQTDE_PARCELA_CREDITO_COFINS write FQTDE_PARCELA_CREDITO_COFINS;
property QtdeParcelaCreditoIcms: Integer read FQTDE_PARCELA_CREDITO_ICMS write FQTDE_PARCELA_CREDITO_ICMS;
property QtdeParcelaCreditoIpi: Integer read FQTDE_PARCELA_CREDITO_IPI write FQTDE_PARCELA_CREDITO_IPI;
property AliquotaCreditoIcms: Extended read FALIQUOTA_CREDITO_ICMS write FALIQUOTA_CREDITO_ICMS;
property AliquotaCreditoPis: Extended read FALIQUOTA_CREDITO_PIS write FALIQUOTA_CREDITO_PIS;
property AliquotaCreditoCofins: Extended read FALIQUOTA_CREDITO_COFINS write FALIQUOTA_CREDITO_COFINS;
property AliquotaCreditoIpi: Extended read FALIQUOTA_CREDITO_IPI write FALIQUOTA_CREDITO_IPI;
end;
TListaFiscalNotaFiscalEntradaVO = specialize TFPGObjectList<TFiscalNotaFiscalEntradaVO>;
implementation
initialization
Classes.RegisterClass(TFiscalNotaFiscalEntradaVO);
finalization
Classes.UnRegisterClass(TFiscalNotaFiscalEntradaVO);
end.
|
// Cette unité sert pour la lecture d'un fichier texte. Il permet de retourner
// le type MIME ainsi que le contenu d'un fichier.
unit uniteLecteurFichierTexte;
interface
// Utilisation de la superclasse pour créer cette sous-classe.
uses SysUtils, uniteLecteurFichier;
type
// Nom de la classe. Hérite de la classe LecteurFichier.
LecteurFichierTexte = class ( LecteurFichier )
public
// Cette fonction retourne le type MIME d'un fichier de type texte.
// @return une chaîne de caractères représentant le type MIME.
function getType : String; override;
// Cette fonction retourne le contenu d'un fichier texte
// @return une chaîne de caractères du contenu d'un fichier texte.
function lireContenu : WideString;
end;
implementation
function LecteurFichierTexte.getType : String;
begin
// Retourne au programme appelant le type MIME d'un fichier après
// l'extraction de l'extension d'un chemin d'accès.
if ( extractFileExt( chemin ) = '.htm' ) then
result := 'text/htm'
else if ( extractFileExt( chemin ) = '.html' ) then
result := 'text/html'
else if ( extractFileExt( chemin ) = '.xml' ) then
result := 'text/xml'
else if ( extractFileExt( chemin ) = '.txt' ) then
result := 'text/plain'
else
begin
// C'est un fichier de type inconnu. La valeur par défaut est
// retournée.
result := getType;
end;
end;
function LecteurFichierTexte.lireContenu : WideString;
var
// Contenu textuel lu à partir du fichier.
contenuFichier : WideString;
// Sert pour la manipulation d'un fichier texte comme l'ouverture et
// la lecture.
fichierTexte : TextFile;
// Conserve une ligne de texte lue dans le fichier.
ligneTexte : String;
begin
// Le contenu est blanc est départ puisque cette variable sert pour la
// concaténation d'une chaîne de caractères.
contenuFichier := '';
// Lien entre la variable de type fichier et le chemin d'accès sur le disque.
assignFile( fichierTexte, chemin );
// Contrôle de l'entrée/sortie lors de l'ouverture du fichier en lecture.
{$i-}
reset( fichierTexte );
{$i+}
// Si le fichier ne s'est pas ouvert, une exception est lancée.
if IOresult <> 0 then
raise Exception.create( 'Erreur Entrée / Sortie' );
// Tant que ce n'est pas la fin du fichier, une ligne est lue dans le fichier.
while not eof( fichierTexte ) do
begin
// Lecture d' une ligne dans le fichier.
readln( fichierTexte, ligneTexte );
// Concaténation entre l'ancien contenu de la variable contenuFichier, de
// la ligne lue dans le fichier et le caractère Entrée.
contenuFichier := contenuFichier + ligneTexte + #13#10;
end;
// Fermeture du fichier.
close( fichierTexte );
// Retourne le contenu du fichier texte au programme appelant.
result := contenuFichier;
end;
end.
|
unit uDataBaseFunctions;
{
Database function
Developer: Rodrigo Costa - 05/08/02
}
interface
uses db, ADOdb, stdctrls, Sysutils, uMsgBox, xBase, uLanguageFunctions,
uStringFunctions{, Variants};
procedure CheckRequired(MyDataSet : TDataSet);
function MyLocate(MyDataSet : TDataSet;
var NewString : String;
const KeyFields: string;
const KeyValues: Variant;
Options: TLocateOptions) : Boolean;
function SystemDeleteBranch(quFreeSQL : TADOQuery; TableName: String; FieldName : String; Path : String; CheckSystem, RealDelete : Boolean) : Boolean;
function SystemDeleteItem(quFreeSQL : TADOQuery; TableName: String;aFields, aValues : array of String;
aFieldTypes : array of TFieldType; CheckSystem, RealDelete : Boolean) : Boolean;
function SystemRestoreItem(quFreeSQL : TADOQuery; TableName: String;aFields, aValues : array of String;
aFieldTypes : array of TFieldType) : Boolean;
function SystemRestoreBranch(quFreeSQL : TADOQuery; TableName: String; FieldName : String; Path : String) : Boolean;
function SubSystemDeleteRestore(quFreeSQL : TADOQuery; TableName : String; aFields, aValues : array of String;
aFieldTypes : array of TFieldType;
IsBranch : Boolean; CheckSystem, RealDelete, IsRestore : Boolean) : Boolean;
function GetTableKeys(quFreeSQL : TADOQuery; TableName: String) : Variant;
function HandleDataBaseError(StrErro : String; var RetMessage : String) : String;
function GetFieldSpc(cIndex : String; LblDataSet : TDataSet;
IsRetValor : Boolean) : String;
procedure CheckEditState(MyDataSet : TDataSet);
procedure CheckActive(MyDataSet : TDataSet);
procedure CheckNetRefresh(MyDataSet : TDataSet);
procedure DeleteSub(MyDataSet : TDataSet;
Chave : String;
OldValor : Variant);
procedure AtuIncSub(SubSet : TDataSet;
SubCod, MasterCod : String);
procedure FillSecondSearch(brwDataSet : TDataSet; FirstIndex : integer;
Combo : TComboBox);
function AdjustFieldDisplayName(FieldName : String) : String;
function RealDisplayName(FieldName:String ): String;
function ConvSQLValue(SQLField : TField; SQLValue : String) : String;
function ConvTypeSQLValue(FieldType : TFieldType; SQLValue : String) : String;
function TestFieldQuery(FieldType : TFieldType; strValue : String) : Boolean;
function TestFill(Field: TField; DisplayName: String): Boolean;
function QuoteField(FieldType : TFieldType; Value : String): String;
implementation
procedure CheckRequired(MyDataSet : TDataSet);
const
CheckTypes = [ftString, ftSmallint, ftInteger, ftWord, ftBoolean, ftFloat,
ftCurrency, ftBCD, ftDate, ftTime, ftDateTime, ftBytes, ftVarBytes];
var
I: Integer;
begin
with MyDataSet do
begin
if State in dsEditModes then
UpdateRecord;
for I := 0 to FieldCount - 1 do
with TField(Fields[I]) do
if Required and not ReadOnly and (FieldKind = fkData) and
(DataType in CheckTypes) and (Trim(TField(Fields[I]).AsString) = '') then
begin
MsgBox(DisplayName + ' não pode ser vazio', vbOkOnly + vbInformation);
FocusControl;
SysUtils.Abort;
end;
end;
end;
function MyLocate(MyDataSet : TDataSet;
var NewString : String;
const KeyFields: string;
const KeyValues: Variant;
Options: TLocateOptions) : Boolean;
var
i, PosKey, LenKeyValue : Integer;
AuxStr, SearchStr : String;
begin
// Modificação do Locate para poder achar letras acentuadas
Result := MyDataSet.Locate(KeyFields, KeyValues, Options);
LenKeyValue := Length(KeyValues);
NewString := '';
if not Result then
if not (VarType(KeyValues) = varArray) then
begin
SearchStr := KeyValues;
for PosKey := Length(SearchStr) downto 1 do
for i := 0 to High(aAcento) do
if UpperCase(SearchStr[PosKey]) = UpperCase(aAcento[i, 0]) then
begin
AuxStr := SearchStr;
AuxStr[PosKey] := aAcento[i, 1][1];
Result := MyDataSet.Locate(KeyFields, AuxStr, Options);
if Result then
begin
NewString := AuxStr;
Exit;
end;
end;
end;
end;
function SystemDeleteBranch(quFreeSQL : TADOQuery; TableName: String; FieldName : String; Path : String; CheckSystem, RealDelete : Boolean) : Boolean;
begin
Result := SubSystemDeleteRestore(quFreeSQL, TableName, [FieldName], [Path], [ftString], True, CheckSystem, RealDelete, False);
end;
function SystemDeleteItem(quFreeSQL : TADOQuery; TableName: String;aFields, aValues : array of String;
aFieldTypes : array of TFieldType; CheckSystem, RealDelete : Boolean) : Boolean;
begin
Result := SubSystemDeleteRestore(quFreeSQL, TableName, aFields, aValues, aFieldTypes, False, CheckSystem, RealDelete, False);
end;
function SystemRestoreItem(quFreeSQL : TADOQuery; TableName: String;aFields, aValues : array of String;
aFieldTypes : array of TFieldType) : Boolean;
begin
Result := SubSystemDeleteRestore(quFreeSQL, TableName, aFields, aValues, aFieldTypes, False, False, False, True);
end;
function SystemRestoreBranch(quFreeSQL : TADOQuery; TableName: String; FieldName : String; Path : String) : Boolean;
begin
Result := SubSystemDeleteRestore(quFreeSQL, TableName, [FieldName], [Path], [ftString], True, False, False, True);
end;
function SubSystemDeleteRestore(quFreeSQL : TADOQuery; TableName : String; aFields, aValues : array of String;
aFieldTypes : array of TFieldType;
IsBranch : Boolean; CheckSystem, RealDelete, IsRestore : Boolean) : Boolean;
var
i : integer;
strSQL, strSQLWhere : String;
begin
Result := True;
with quFreeSQL do
begin
// Teste se e registro System
strSQLWhere := '';
strSQL := 'SELECT System FROM ' + TableName +
' WHERE ';
if not IsBranch then
begin
for i := Low(aFields) to High(aFields) do
begin
IncString(StrSQLWhere, aFields[i] + ' = ' +
ConvTypeSQLValue(aFieldTypes[i], aValues[i]));
if i < High(aFields) then
begin
IncString(StrSQLWhere, ' AND ');
end;
end;
end
else
begin
for i := Low(aFields) to High(aFields) do
begin
IncString(StrSQLWhere, aFields[i] + ' like ' +
ConvTypeSQLValue(aFieldTypes[i], aValues[i] + '%'));
if i < High(aFields) then
IncString(StrSQLWhere, ' AND ');
end;
end;
if CheckSystem then
begin
if Active then
Close;
SQL.Text := strSQL + strSQLWhere;
Open;
if Fields[0].AsBoolean then
begin
MsgBox('System item cannot be deleted.', vbOkOnly + vbInformation);
Result := False;
Exit;
end;
end;
if RealDelete then
begin
// Delecao Real
try
Close;
SQL.Text := 'DELETE FROM ' + TableName + ' WHERE ' + strSQLWhere;
ExecSQL;
except
Result := False;
MsgBox('Item cannot be deleted.', vbOkOnly + vbInformation);
end;
end
else
begin
Close;
// Delecao ou restauracao Marcada
if IsRestore then
SQL.Text := 'UPDATE ' + TableName + ' SET Desativado = 0 WHERE ' + strSQLWhere
else if not RealDelete then
SQL.Text := 'UPDATE ' + TableName + ' SET Desativado = 1 WHERE ' + strSQLWhere;
ExecSQL;
end;
end;
end;
function GetTableKeys(quFreeSQL : TADOQuery; TableName: String) : Variant;
var
aKeys : Variant;
P: Integer;
begin
aKeys := VarArrayCreate([0, 0], varOleStr);
aKeys[0] := '';
// Retiro o nome do usuario caso ele exista
if UpperCase(LeftStr(TableName, 4)) = 'DBO.' then
TableName := RightStr(TableName, Length(TableName)-4);
with quFreeSQL do
begin
Close;
SQL.Text := 'exec sp_System_dbKeys ' +#39 + TableName + #39;
Open;
while not eof do
begin
aKeys[VarArrayHighBound(aKeys, 1)] := quFreeSQL.Fields[3].AsString;
Next;
if not Eof then
VarArrayRedim(aKeys, VarArrayHighBound(aKeys, 1)+1);
end;
Close;
end;
Result := aKeys;
end;
function HandleDataBaseError(StrErro : String; var RetMessage : String) : String;
function GetFieldGen(TpErro, strErro : String) : String;
var
PosErro : integer;
strField : String;
lEntrou : Boolean;
begin
lEntrou := False;
{ Obtem o campo do erro }
PosErro := Pos(TpErro, UpperCase(strErro)) + Length(TpErro) + 1;
while not ( (Copy(strErro, PosErro, 1) = Chr(39)) or
(Copy(strErro, PosErro, 1) = ' ') ) do
begin
if (Copy(strErro, PosErro, 1) = '_') or lEntrou then
begin
lEntrou := True;
if Copy(strErro, PosErro, 1) <> '_' then
IncString(strField, Copy(strErro, PosErro, 1));
end;
Inc(PosErro);
end;
Result := strField;
end;
function GetFieldNull(TpErro, strErro : String) : String;
var
PosErro : integer;
strField : String;
begin
{ Obtem o campo do erro }
PosErro := Pos(TpErro, UpperCase(strErro)) + 7;
// teste de outro erro de null
if Copy(strErro, PosErro, 1) = Chr(39) then
Inc(PosErro);
while not ( (Copy(strErro, PosErro, 1) = Chr(39)) or
(Copy(strErro, PosErro, 1) = ' ') ) do
begin
IncString(strField, Copy(strErro, PosErro, 1));
Inc(PosErro);
end;
Result := strField;
end;
{ Funcao principal }
var
strError : String;
begin
strError := Trim(UpperCase(strErro));
if Pos('PRIMARY KEY', strError) > 0 then
// Erro de chave primaria
begin
Result := GetFieldGen('PK_', strError);
RetMessage := ' cannot be duplicated';
end
else if Pos('FOREIGN KEY', strError) > 0 then
// Erro de chave secundaria
begin
Result := GetFieldGen('FK_', strError);
RetMessage := ' has dependente';
end
else if Pos('UNIQUE KEY', strError) > 0 then
// Erro de chave secundaria
begin
Result := GetFieldGen('UK_', strError);
RetMessage := ' cannot be duplicated';
end
else if Pos('DUPLICATED', strError) > 0 then
// Erro de duplicacao
begin
Result := GetFieldGen('DUP_', strError);
RetMessage := ' cannot be duplicated';
end
else if Pos('NULL', strError) > 0 then
// Erro de chave secundaria
begin
Result := GetFieldNull('COLUMN', strError);
RetMessage := ' cannot be empty';
end
else if Pos('INSERT DUPLICATE KEY ROW', strError) > 0 then
// Erro de chave secundaria
begin
Result := GetFieldGen('COLUMN', strError);
RetMessage := ' cannot be duplicated._Record already exist.';
end
else
{ erro desconhecido }
begin
Result := '';
RetMessage := '';
end;
end;
function GetFieldSpc(cIndex : String; LblDataSet : TDataSet;
IsRetValor : Boolean) : String;
var
i : integer;
nLenInd : integer;
cTemp, cLabelInd : String;
begin
{ seta variaveis iniciais }
cTemp := '';
cLabelInd := '';
nLenInd := Length(cIndex) + 1;
for i := 1 to nLenInd do
begin
if (cIndex[i] = ';') or
(i = nLenInd) then
begin
if IsRetValor then
cLabelInd := cLabelInd + LblDataSet.FieldByName(cTemp).AsString
else
cLabelInd := cLabelInd + LblDataSet.FieldByName(cTemp).DisplayName;
cTemp := '';
if i < nLenInd then
cLabelInd := cLabelInd + ';';
end
else
begin
cTemp := cTemp + cIndex[i];
end;
end;
Result := cLabelInd;
end;
procedure CheckEditState(MyDataSet : TDataSet);
begin
if not (MyDataSet.State in dsEditModes) then
MyDataSet.Edit;
end;
procedure CheckActive(MyDataSet : TDataSet);
begin
if (not MyDataSet.Active) then
MyDataSet.Open
else
MyDataSet.Refresh;
end;
procedure CheckNetRefresh(MyDataSet : TDataSet);
begin
if MyDataSet.Active then
MyDataSet.Refresh;
end;
procedure DeleteSub(MyDataSet : TDataSet;
Chave : String;
OldValor : Variant);
begin
{ Depois de deletar, deve-se deletar os
Subitens do master }
with MyDataSet do
begin
try
DisableControls;
AutoCalcFields := False;
while Locate(Chave, OldValor, []) do
begin
Delete;
end;
finally
EnableControls;
AutoCalcFields := True;
end;
end;
end;
procedure AtuIncSub(SubSet : TDataSet;
SubCod, MasterCod : String);
begin
with SubSet do
begin
try
DisableControls;
AutoCalcFields := False;
First;
while not Eof do
begin
CheckEditState(SubSet);
FieldByName(SubCod).Value := MasterCod;
Post;
end;
finally
AutoCalcFields := True;
EnableControls;
end;
end;
end;
procedure FillSecondSearch(brwDataSet : TDataSet; FirstIndex : integer;
Combo : TComboBox);
var
i : integer;
begin
with brwDataSet do
begin
Combo.Items.Clear;
Combo.Items.Add('< none >');
for i := 0 to FieldCount -1 do
if i <> FirstIndex then
Combo.Items.Add(Fields[i].DisplayName);
Combo.ItemIndex := 0;
end;
end;
function AdjustFieldDisplayName(FieldName : String) : String;
begin
if (RightStr(FieldName, 2) = ' ^') or (RightStr(FieldName, 2) = ' v') then
Result := LeftStr(FieldName, Length(FieldName) - 2)
else
Result := FieldName;
end;
function RealDisplayName(FieldName:String ): String;
var
S: String;
i: integer;
begin
S := AdjustFieldDisplayName(FieldName);
Result := '';
for i := 1 to length(S) do
if S[i] <> '~' then
Result := Result + S[i]
else
Result := Result + ' ';
end;
function ConvSQLValue(SQLField : TField; SQLValue : String) : String;
begin
Result := ConvTypeSQLValue(SQLField.DataType, SQLValue);
end;
function ConvTypeSQLValue(FieldType : TFieldType; SQLValue : String) : String;
begin
if FieldType in [ftString, ftDateTime, ftDate, ftMemo] then
Result := Chr(39) + SQLValue + Chr(39)
else
Result := SQLValue;
end;
function TestFieldQuery(FieldType : TFieldType; strValue : String) : Boolean;
var
TestValue : Real;
Code : Integer;
begin
if not (FieldType in [ftString, ftDateTime, ftDate, ftMemo]) then
begin
// Field e numero
Val(strValue, TestValue, Code);
Result := (Code = 0);
end
else
begin
Result := True;
end;
end;
function TestFill(Field: TField; DisplayName: String): Boolean;
begin
if Field.AsString = '' then
begin
MsgBox('Fields must be filled [' + DisplayName + ']!', vbInformation + vbOkOnly);
Field.FocusControl;
Result := False;
end
else
Result := True;
end;
function QuoteField(FieldType : TFieldType; Value : String) : String;
begin
if FieldType in [ftString, ftDateTime, ftDate, ftMemo] then
Result := QuotedStr(Value)
else
Result := Value;
end;
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: Controller relacionado à tabela [ECF_CONFIGURACAO]
The MIT License
Copyright: Copyright (C) 2014 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com</p>
Albert Eije (T2Ti.COM)
@version 2.0
*******************************************************************************}
unit ConfiguracaoController;
{$MODE Delphi}
interface
uses
Classes, SysUtils, DB, LCLIntf, LCLType, LMessages, Forms,
VO, EcfConfiguracaoVO, EcfPosicaoComponentesVO;
type
TEcfConfiguracaoController = class(TPersistent)
private
public
class function ConsultaObjeto(pFiltro: String): TEcfConfiguracaoVO;
class procedure GravarPosicaoComponentes(pListaPosicaoComponentes: TListaEcfPosicaoComponentesVO);
end;
implementation
uses T2TiORM,
EcfResolucaoVO, EcfImpressoraVO, EcfCaixaVO, EcfEmpresaVO, EcfConfiguracaoBalancaVO,
EcfRelatorioGerencialVO, EcfConfiguracaoLeitorSerVO;
class function TEcfConfiguracaoController.ConsultaObjeto(pFiltro: String): TEcfConfiguracaoVO;
var
Filtro: String;
begin
try
Result := TEcfConfiguracaoVO.Create;
Result := TEcfConfiguracaoVO(TT2TiORM.ConsultarUmObjeto(Result, pFiltro, True));
//Exercício: crie o método para popular esses objetos automaticamente no T2TiORM
Result.EcfResolucaoVO := TEcfResolucaoVO(TT2TiORM.ConsultarUmObjeto(Result.EcfResolucaoVO, 'ID='+IntToStr(Result.IdEcfResolucao), True));
Filtro := 'ID_ECF_RESOLUCAO='+IntToStr(Result.EcfResolucaoVO.Id);
Result.EcfResolucaoVO.ListaEcfPosicaoComponentesVO := TListaEcfPosicaoComponentesVO(TT2TiORM.Consultar(TEcfPosicaoComponentesVO.Create, Filtro, True));
Result.EcfImpressoraVO := TEcfImpressoraVO(TT2TiORM.ConsultarUmObjeto(Result.EcfImpressoraVO, 'ID='+IntToStr(Result.IdEcfImpressora), True));
Result.EcfCaixaVO := TEcfCaixaVO(TT2TiORM.ConsultarUmObjeto(Result.EcfCaixaVO, 'ID='+IntToStr(Result.IdEcfCaixa), True));
Result.EcfEmpresaVO := TEcfEmpresaVO(TT2TiORM.ConsultarUmObjeto(Result.EcfEmpresaVO, 'ID='+IntToStr(Result.IdEcfEmpresa), True));
Filtro := 'ID_ECF_CONFIGURACAO = ' + IntToStr(Result.Id);
Result.EcfConfiguracaoBalancaVO := TEcfConfiguracaoBalancaVO(TT2TiORM.ConsultarUmObjeto(Result.EcfConfiguracaoBalancaVO, Filtro, True));
Result.EcfRelatorioGerencialVO := TEcfRelatorioGerencialVO(TT2TiORM.ConsultarUmObjeto(Result.EcfRelatorioGerencialVO, Filtro, True));
Result.EcfConfiguracaoLeitorSerVO := TEcfConfiguracaoLeitorSerVO(TT2TiORM.ConsultarUmObjeto(Result.EcfConfiguracaoLeitorSerVO, Filtro, True));
finally
end;
end;
class procedure TEcfConfiguracaoController.GravarPosicaoComponentes(pListaPosicaoComponentes: TListaEcfPosicaoComponentesVO);
var
I: Integer;
PosicaoComponenteVO: TEcfPosicaoComponentesVO;
Filtro: String;
begin
try
for I := 0 to pListaPosicaoComponentes.Count - 1 do
begin
Filtro := 'ID_ECF_RESOLUCAO = ' + IntToStr(pListaPosicaoComponentes.Items[I].IdEcfResolucao) + ' and NOME = ' + QuotedStr(pListaPosicaoComponentes.Items[I].Nome);
PosicaoComponenteVO := TEcfPosicaoComponentesVO.Create;
PosicaoComponenteVO := TEcfPosicaoComponentesVO(TT2TiORM.ConsultarUmObjeto(PosicaoComponenteVO, Filtro, True));
if Assigned(PosicaoComponenteVO) then
begin
pListaPosicaoComponentes.Items[I].Id := PosicaoComponenteVO.Id;
if PosicaoComponenteVO.ToJSONString <> pListaPosicaoComponentes.Items[I].ToJSONString then
TT2TiORM.Alterar(pListaPosicaoComponentes.Items[I]);
FreeAndNil(PosicaoComponenteVO);
end;
end;
finally
end;
end;
end.
|
(*----------------------------------------------------------------------------*
* Direct3D sample from DirectX 9.0 SDK December 2006 *
* Delphi adaptation by Alexey Barkovoy (e-mail: directx@clootie.ru) *
* *
* Supported compilers: Delphi 5,6,7,9; FreePascal 2.0 *
* *
* Latest version can be downloaded from: *
* http://www.clootie.ru *
* http://sourceforge.net/projects/delphi-dx9sdk *
*----------------------------------------------------------------------------*
* $Id: MultiAnimationUnit.pas,v 1.8 2007/02/05 22:21:10 clootie Exp $
*----------------------------------------------------------------------------*)
//--------------------------------------------------------------------------------------
// File: MultiAnimation.cpp
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
{$I DirectX.inc}
unit MultiAnimationUnit;
interface
uses
Windows, Classes, SysUtils, StrSafe,
DXTypes, DirectSound, Direct3D9, D3DX9,
DXUT, DXUTcore, DXUTenum, DXUTmisc, DXUTgui, DXUTsound, DXUTSettingsDlg,
MultiAnimationLib, Tiny;
{.$DEFINE DEBUG_VS} // Uncomment this line to debug vertex shaders
{.$DEFINE DEBUG_PS} // Uncomment this line to debug pixel shaders
const
TXFILE_FLOOR = 'floor.jpg';
FLOOR_TILECOUNT = 2;
//--------------------------------------------------------------------------------------
// Global variables
//--------------------------------------------------------------------------------------
var
g_pFont: ID3DXFont; // Font for drawing text
g_pTextSprite: ID3DXSprite; // Sprite for batching draw text calls
g_pEffect: ID3DXEffect; // D3DX effect interface
g_Camera: CFirstPersonCamera; // A model viewing camera
g_DialogResourceManager: CDXUTDialogResourceManager; // manager for shared resources of dialogs
g_SettingsDlg: CD3DSettingsDlg; // Device settings dialog
g_HUD: CDXUTDialog; // dialog for standard controls
g_SampleUI: CDXUTDialog; // dialog for sample specific controls
g_pMeshFloor: ID3DXMesh; // floor geometry
g_mxFloor: TD3DXMatrixA16; // floor world xform
g_MatFloor: TD3DMaterial9; // floor material
g_pTxFloor: IDirect3DTexture9; // floor texture
g_DSound: CSoundManager; // DirectSound class
g_MultiAnim: CMultiAnim; // the MultiAnim class for holding Tiny's mesh and frame hierarchy
g_v_pCharacters: TTinyList; // array of character objects; each can be associated with any of the CMultiAnims
g_dwFollow: DWORD = $ffffffff; // which character the camera should follow; 0xffffffff for static camera
g_bShowHelp: Boolean = True; // If true, it renders the UI control text
g_bPlaySounds: Boolean = True; // whether to play sounds
g_fLastAnimTime: Double = 0.0; // Time for the animations
//--------------------------------------------------------------------------------------
// UI control IDs
//--------------------------------------------------------------------------------------
const
IDC_TOGGLEFULLSCREEN = 1;
IDC_TOGGLEREF = 3;
IDC_CHANGEDEVICE = 4;
IDC_ADDTINY = 5;
IDC_NEXTVIEW = 6;
IDC_PREVVIEW = 7;
IDC_ENABLESOUND = 8;
IDC_CONTROLTINY = 9;
IDC_RELEASEALL = 10;
IDC_RESETCAMERA = 11;
IDC_RESETTIME = 12;
//--------------------------------------------------------------------------------------
// Forward declarations
//--------------------------------------------------------------------------------------
function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall;
function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall;
function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall;
procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall;
procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall;
procedure OnLostDevice(pUserContext: Pointer); stdcall;
procedure OnDestroyDevice(pUserContext: Pointer); stdcall;
procedure InitApp;
procedure RenderText;
procedure CreateCustomDXUTobjects;
procedure DestroyCustomDXUTobjects;
implementation
//--------------------------------------------------------------------------------------
// Initialize the app
//--------------------------------------------------------------------------------------
procedure InitApp;
var
iY: Integer;
vEye: TD3DXVector3;
vAt: TD3DXVector3;
begin
// Initialize dialogs
g_SettingsDlg.Init(g_DialogResourceManager);
g_HUD.Init(g_DialogResourceManager);
g_SampleUI.Init(g_DialogResourceManager);
g_HUD.SetCallback(OnGUIEvent);
iY := 10; g_HUD.AddButton(IDC_TOGGLEFULLSCREEN, 'Toggle full screen', 35, iY, 125, 22);
Inc(iY, 24); g_HUD.AddButton(IDC_TOGGLEREF, 'Toggle REF (F3)', 35, iY, 125, 22);
Inc(iY, 24); g_HUD.AddButton(IDC_CHANGEDEVICE, 'Change device (F2)', 35, iY, 125, 22, VK_F2);
g_SampleUI.SetCallback(OnGUIEvent); iY := 10;
g_SampleUI.AddButton(IDC_ADDTINY,'Add Instance', 45, iY, 120, 24);
Inc(iY, 26); g_SampleUI.AddButton(IDC_NEXTVIEW,'(N)ext View', 45, iY, 120, 24, Ord('N'));
Inc(iY, 26); g_SampleUI.AddButton(IDC_PREVVIEW,'(P)revious View', 45, iY, 120, 24, Ord('P'));
Inc(iY, 26); g_SampleUI.AddButton(IDC_RESETCAMERA,'(R)eset view', 45, iY, 120, 24, Ord('R'));
Inc(iY, 26); g_SampleUI.AddCheckBox(IDC_ENABLESOUND,'Enable sound', 25, iY, 140, 24, True);
Inc(iY, 26); g_SampleUI.AddCheckBox(IDC_CONTROLTINY,'(C)ontrol this instance', 25, iY, 140, 24, False, Ord('C'));
g_SampleUI.GetCheckBox(IDC_CONTROLTINY).Visible := False;
g_SampleUI.GetCheckBox(IDC_CONTROLTINY).Enabled := False;
Inc(iY, 26); g_SampleUI.AddButton(IDC_RELEASEALL,'Auto-control all', 45, iY, 120, 24);
Inc(iY, 26); g_SampleUI.AddButton(IDC_RESETTIME,'Reset time', 45, iY, 120, 24);
// Setup the camera with view matrix
vEye := D3DXVector3(0.5, 0.55, -0.2);
vAt := D3DXVector3(0.5, 0.125, 0.5);
g_Camera.SetViewParams(vEye, vAt);
g_Camera.SetScalers(0.01, 1.0); // Camera movement parameters
end;
//--------------------------------------------------------------------------------------
// Called during device initialization, this code checks the device for some
// minimum set of capabilities, and rejects those that don't pass by returning false.
//--------------------------------------------------------------------------------------
function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall;
var
pD3D: IDirect3D9;
begin
Result := False;
// Skip backbuffer formats that don't support alpha blending
pD3D := DXUTGetD3DObject;
if FAILED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType,
AdapterFormat, D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING,
D3DRTYPE_TEXTURE, BackBufferFormat))
then Exit;
// Need to support ps 2.0
if (pCaps.PixelShaderVersion < D3DPS_VERSION(2,0)) then Exit;
// Need to support A8R8G8B8 textures
if FAILED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType,
AdapterFormat, 0,
D3DRTYPE_TEXTURE, D3DFMT_A8R8G8B8))
then Exit;
Result := True;
end;
//--------------------------------------------------------------------------------------
// This callback function is called immediately before a device is created to allow the
// application to modify the device settings. The supplied pDeviceSettings parameter
// contains the settings that the framework has selected for the new device, and the
// application can make any desired changes directly to this structure. Note however that
// DXUT will not correct invalid device settings so care must be taken
// to return valid device settings, otherwise IDirect3D9::CreateDevice() will fail.
//--------------------------------------------------------------------------------------
{static} var s_bFirstTime: Boolean = True;
function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall;
begin
// If device doesn't support HW T&L or doesn't support 1.1 vertex shaders in HW
// then switch to SWVP.
if (pCaps.DevCaps and D3DDEVCAPS_HWTRANSFORMANDLIGHT = 0) or
(pCaps.VertexShaderVersion < D3DVS_VERSION(1,1))
then pDeviceSettings.BehaviorFlags := D3DCREATE_SOFTWARE_VERTEXPROCESSING;
// If the hardware cannot do vertex blending, use software vertex processing.
if (pCaps.MaxVertexBlendMatrices < 2)
then pDeviceSettings.BehaviorFlags := D3DCREATE_SOFTWARE_VERTEXPROCESSING;
// If using hardware vertex processing, change to mixed vertex processing
// so there is a fallback.
if (pDeviceSettings.BehaviorFlags and D3DCREATE_HARDWARE_VERTEXPROCESSING <> 0)
then pDeviceSettings.BehaviorFlags := D3DCREATE_MIXED_VERTEXPROCESSING;
// Debugging vertex shaders requires either REF or software vertex processing
// and debugging pixel shaders requires REF.
{$IFDEF DEBUG_VS}
if (pDeviceSettings.DeviceType <> D3DDEVTYPE_REF) then
with pDeviceSettings do
begin
BehaviorFlags := BehaviorFlags and not D3DCREATE_HARDWARE_VERTEXPROCESSING;
BehaviorFlags := BehaviorFlags and not D3DCREATE_PUREDEVICE;
BehaviorFlags := BehaviorFlags or D3DCREATE_SOFTWARE_VERTEXPROCESSING;
end;
{$ENDIF}
{$IFDEF DEBUG_PS}
pDeviceSettings.DeviceType := D3DDEVTYPE_REF;
{$ENDIF}
// For the first device created if its a REF device, optionally display a warning dialog box
if s_bFirstTime then
begin
s_bFirstTime := False;
if (pDeviceSettings.DeviceType = D3DDEVTYPE_REF) then DXUTDisplaySwitchingToREFWarning;
end;
Result:= True;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has been
// created, which will happen during application initialization and windowed/full screen
// toggles. This is the best location to create D3DPOOL_MANAGED resources since these
// resources need to be reloaded whenever the device is destroyed. Resources created
// here should be released in the OnDestroyDevice callback.
//--------------------------------------------------------------------------------------
function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
var
str: array[0..MAX_PATH-1] of WideChar;
dwShaderFlags: DWORD;
mx: TD3DXMatrix;
begin
Result:= g_DialogResourceManager.OnCreateDevice(pd3dDevice);
if V_Failed(Result) then Exit;
Result:= g_SettingsDlg.OnCreateDevice(pd3dDevice);
if V_Failed(Result) then Exit;
// Initialize the font
Result := D3DXCreateFont(pd3dDevice, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH or FF_DONTCARE,
'Arial', g_pFont);
if V_Failed(Result) then Exit;
// Initialize floor textures
Result:= DXUTFindDXSDKMediaFile(str, MAX_PATH, TXFILE_FLOOR);
if V_Failed(Result) then Exit;
Result:= D3DXCreateTextureFromFileW(pd3dDevice, str, g_pTxFloor);
if V_Failed(Result) then Exit;
// Define DEBUG_VS and/or DEBUG_PS to debug vertex and/or pixel shaders with the
// shader debugger. Debugging vertex shaders requires either REF or software vertex
// processing, and debugging pixel shaders requires REF. The
// D3DXSHADER_FORCE_*_SOFTWARE_NOOPT flag improves the debug experience in the
// shader debugger. It enables source level debugging, prevents instruction
// reordering, prevents dead code elimination, and forces the compiler to compile
// against the next higher available software target, which ensures that the
// unoptimized shaders do not exceed the shader model limitations. Setting these
// flags will cause slower rendering since the shaders will be unoptimized and
// forced into software. See the DirectX documentation for more information about
// using the shader debugger.
dwShaderFlags := D3DXFX_NOT_CLONEABLE;
{$IFDEF DEBUG}
// Set the D3DXSHADER_DEBUG flag to embed debug information in the shaders.
// Setting this flag improves the shader debugging experience, but still allows
// the shaders to be optimized and to run exactly the way they will run in
// the release configuration of this program.
dwShaderFlags := dwShaderFlags or D3DXSHADER_DEBUG;
{$ENDIF}
{$IFDEF DEBUG_VS}
dwShaderFlags := dwShaderFlags or D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT;
{$ENDIF}
{$IFDEF DEBUG_PS}
dwShaderFlags := dwShaderFlags or D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT;
{$ENDIF}
// Read the D3DX effect file
Result:= DXUTFindDXSDKMediaFile(str, MAX_PATH, 'MultiAnimation.fx');
if V_Failed(Result) then Exit;
// If this fails, there should be debug output as to
// they the .fx file failed to compile
Result:= D3DXCreateEffectFromFileW(pd3dDevice, str, nil, nil, dwShaderFlags,
nil, g_pEffect, nil);
if V_Failed(Result) then Exit;
g_pEffect.SetTechnique('RenderScene');
// floor geometry transform
D3DXMatrixRotationX(g_mxFloor, -D3DX_PI / 2.0);
D3DXMatrixRotationY(mx, D3DX_PI / 4.0);
D3DXMatrixMultiply(g_mxFloor, g_mxFloor, mx);
D3DXMatrixTranslation(mx, 0.5, 0.0, 0.5);
D3DXMatrixMultiply(g_mxFloor, g_mxFloor, mx);
// set material for floor
g_MatFloor.Diffuse := D3DXColor(1.0, 1.0, 1.0, 0.75);
g_MatFloor.Ambient := D3DXColor(1.0, 1.0, 1.0, 1.0);
g_MatFloor.Specular := D3DXColor(0.0, 0.0, 0.0, 1.0);
g_MatFloor.Emissive := D3DXColor(0.0, 0.0, 0.0, 0.0);
g_MatFloor.Power := 0.0;
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has been
// reset, which will happen after a lost device scenario. This is the best location to
// create D3DPOOL_DEFAULT resources since these resources need to be reloaded whenever
// the device is lost. Resources created here should be released in the OnLostDevice
// callback.
//--------------------------------------------------------------------------------------
function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
var
// set up MultiAnim
sXFile: array[0..MAX_PATH-1] of WideChar;
str: array[0..MAX_PATH-1] of WideChar;
AH: CMultiAnimAllocateHierarchy;
caps: TD3DCaps9;
i: Integer;
fAspectRatio: Single;
pTiny: CTiny;
pMAEffect: ID3DXEffect;
pMesh: ID3DXMesh;
dwNumVx: DWORD;
type
TVx = packed record
vPos: TD3DXVector3;
vNorm: TD3DXVector3;
fTex: array[0..1] of Single;
end;
var
pVx: ^TVx;
begin
Result:= g_DialogResourceManager.OnResetDevice;
if V_Failed(Result) then Exit;
Result:= g_SettingsDlg.OnResetDevice;
if V_Failed(Result) then Exit;
Result:= DXUTFindDXSDKMediaFile(str, MAX_PATH, 'MultiAnimation.fx');
if V_Failed(Result) then Exit;
Result:= DXUTFindDXSDKMediaFile(sXFile, MAX_PATH, 'tiny_4anim.x');
if V_Failed(Result) then Exit;
AH:= CMultiAnimAllocateHierarchy.Create;
try
AH.SetMA(g_MultiAnim);
Result := g_MultiAnim.Setup(pd3dDevice, sXFile, str, AH);
if V_Failed(Result) then Exit;
finally
AH.Free;
end;
// get device caps
pd3dDevice.GetDeviceCaps(caps);
// Select the technique that fits the shader version.
// We could have used ValidateTechnique()/GetNextValidTechnique() to find the
// best one, but this is convenient for our purposes.
g_MultiAnim.SetTechnique('Skinning20');
// Restore steps for tiny instances
for i:= 0 to g_v_pCharacters.Count - 1 do
begin
g_v_pCharacters[i].RestoreDeviceObjects(pd3dDevice);
end;
// If there is no instance, make sure we have at least one.
if (g_v_pCharacters.Count = 0) then
begin
try
pTiny := CTiny.Create;
except
Result:= E_OUTOFMEMORY;
Exit;
end;
{Result := }pTiny.Setup(g_MultiAnim, g_v_pCharacters, g_DSound, 0.0);
pTiny.SetSounds(g_bPlaySounds);
end;
if Assigned(g_pFont) then
begin
Result:= g_pFont.OnResetDevice;
if V_Failed(Result) then Exit;
end;
if Assigned(g_pEffect) then
begin
Result:= g_pEffect.OnResetDevice;
if V_Failed(Result) then Exit;
end;
pMAEffect := g_MultiAnim.GetEffect;
if Assigned(pMAEffect) then
begin
pMAEffect.OnResetDevice;
pMAEffect := nil;
end;
// Create a sprite to help batch calls when drawing many lines of text
Result:= D3DXCreateSprite(pd3dDevice, g_pTextSprite);
if V_Failed(Result) then Exit;
// Setup the camera's projection parameters
fAspectRatio := pBackBufferSurfaceDesc.Width / pBackBufferSurfaceDesc.Height;
g_Camera.SetProjParams(D3DX_PI/3, fAspectRatio, 0.001, 100.0);
// set lighting
pd3dDevice.SetRenderState(D3DRS_LIGHTING, iTrue);
pd3dDevice.SetRenderState(D3DRS_AMBIENT, D3DCOLOR_ARGB(255, 255, 255, 255));
pd3dDevice.LightEnable(0, True);
pd3dDevice.SetRenderState(D3DRS_NORMALIZENORMALS, iTrue);
// create the floor geometry
Result := D3DXCreatePolygon(pd3dDevice, 1.2, 4, pMesh, nil);
if V_Failed(Result) then Exit;
Result:= pMesh.CloneMeshFVF(D3DXMESH_WRITEONLY, D3DFVF_XYZ or D3DFVF_NORMAL or D3DFVF_TEX1, pd3dDevice, g_pMeshFloor);
if V_Failed(Result) then Exit;
pMesh := nil;
dwNumVx := g_pMeshFloor.GetNumVertices;
// Initialize its texture coordinates
Result := g_pMeshFloor.LockVertexBuffer(0, Pointer(pVx));
if FAILED(Result) then Exit;
for i := 0 to dwNumVx - 1 do
begin
if Abs(pVx.vPos.x) < 0.01 then
begin
if (pVx.vPos.y > 0) then
begin
pVx.fTex[ 0 ] := 0.0;
pVx.fTex[ 1 ] := 0.0;
end else
if (pVx.vPos.y < 0.0) then
begin
pVx.fTex[ 0 ] := 1.0 * FLOOR_TILECOUNT;
pVx.fTex[ 1 ] := 1.0 * FLOOR_TILECOUNT;
end else
begin
pVx.fTex[ 0 ] := 0.5 * FLOOR_TILECOUNT;
pVx.fTex[ 1 ] := 0.5 * FLOOR_TILECOUNT;
end;
end else
if (pVx.vPos.x > 0.0) then
begin
pVx.fTex[ 0 ] := 1.0 * FLOOR_TILECOUNT;
pVx.fTex[ 1 ] := 0.0;
end else
begin
pVx.fTex[ 0 ] := 0.0;
pVx.fTex[ 1 ] := 1.0 * FLOOR_TILECOUNT;
end;
Inc(pVx);
end;
g_pMeshFloor.UnlockVertexBuffer;
// reset the timer
g_fLastAnimTime := DXUTGetGlobalTimer.GetTime;
// Adjust the dialog parameters.
g_HUD.SetLocation(pBackBufferSurfaceDesc.Width-170, 0);
g_HUD.SetSize(170, 170);
g_SampleUI.SetLocation(pBackBufferSurfaceDesc.Width-170, pBackBufferSurfaceDesc.Height-270);
g_SampleUI.SetSize(170, 220);
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called once at the beginning of every frame. This is the
// best location for your application to handle updates to the scene, but is not
// intended to contain actual rendering calls, which should instead be placed in the
// OnFrameRender callback.
//--------------------------------------------------------------------------------------
procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
var
i: Integer;
begin
for i:= 0 to g_v_pCharacters.Count - 1 do
g_v_pCharacters[i].Animate(fTime - g_fLastAnimTime);
g_fLastAnimTime := fTime;
// Update the camera's position based on user input
g_Camera.FrameMove(fElapsedTime);
end;
//--------------------------------------------------------------------------------------
// This callback function will be called at the end of every frame to perform all the
// rendering calls for the scene, and it will also be called if the window needs to be
// repainted. After this function has returned, DXUT will call
// IDirect3DDevice9::Present to display the contents of the next buffer in the swap chain
//--------------------------------------------------------------------------------------
procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
var
// set up the camera
mx, mxView, mxProj: TD3DXMatrixA16;
vEye: TD3DXVector3;
vLightDir: TD3DXVector3;
pChar: CTiny;
vCharPos: TD3DXVector3;
vCharFacing: TD3DXVector3;
vAt, vUp: TD3DXVector3;
pBackBufferSurfaceDesc: PD3DSurfaceDesc;
fAspectRatio: Single;
pMAEffect: ID3DXEffect;
vec: TD3DXVector4;
i, p, cPasses: Integer;
begin
// If the settings dialog is being shown, then
// render it instead of rendering the app's scene
if g_SettingsDlg.Active then
begin
g_SettingsDlg.OnRender(fElapsedTime);
Exit;
end;
pd3dDevice.Clear(0, nil, D3DCLEAR_TARGET or D3DCLEAR_ZBUFFER,
D3DCOLOR_ARGB(0, $3F, $AF, $FF), 1.0, 0);
if SUCCEEDED(pd3dDevice.BeginScene) then
begin
// set up the camera
// are we following a tiny, or an independent arcball camera?
if (g_dwFollow = $ffffffff) then
begin
// Light direction is same as camera front (reversed)
D3DXVec3Scale(vLightDir, g_Camera.GetWorldAhead^, -1);
// set static transforms
mxView := g_Camera.GetViewMatrix^;
mxProj := g_Camera.GetProjMatrix^;
V(pd3dDevice.SetTransform(D3DTS_VIEW, mxView));
V(pd3dDevice.SetTransform(D3DTS_PROJECTION, mxProj));
vEye := g_Camera.GetEyePt^;
end else
begin
// set follow transforms
pChar := g_v_pCharacters[ g_dwFollow ];
pChar.GetPosition(vCharPos);
pChar.GetFacing(vCharFacing);
vEye := D3DXVector3(vCharPos.x, 0.25, vCharPos.z);
vAt := D3DXVector3(vCharPos.x, 0.0125, vCharPos.z);
vUp := D3DXVector3(0.0, 1.0, 0.0);
vCharFacing.x := vCharFacing.x * 0.25;
vCharFacing.y := 0.0;
vCharFacing.z := vCharFacing.z * 0.25;
// vEye -= vCharFacing;
D3DXVec3Subtract(vEye, vEye, vCharFacing);
// vAt += vCharFacing;
D3DXVec3Add(vAt, vAt, vCharFacing);
D3DXMatrixLookAtLH(mxView, vEye, vAt, vUp);
V(pd3dDevice.SetTransform(D3DTS_VIEW, mxView));
pBackBufferSurfaceDesc := DXUTGetBackBufferSurfaceDesc;
fAspectRatio := pBackBufferSurfaceDesc.Width / pBackBufferSurfaceDesc.Height;
D3DXMatrixPerspectiveFovLH(mxProj, D3DX_PI / 3, fAspectRatio, 0.1, 100.0);
V(pd3dDevice.SetTransform(D3DTS_PROJECTION, mxProj));
// Set the light direction and normalize
D3DXVec3Subtract(vLightDir, vEye, vAt);
D3DXVec3Normalize(vLightDir, vLightDir);
end;
// set view-proj
D3DXMatrixMultiply( mx, mxView, mxProj);
g_pEffect.SetMatrix('g_mViewProj', mx);
pMAEffect := g_MultiAnim.GetEffect;
if Assigned(pMAEffect) then
begin
pMAEffect.SetMatrix('g_mViewProj', mx);
end;
// Set the light direction so that the
// visible side is lit.
vec := D3DXVector4(vLightDir.x, vLightDir.y, vLightDir.z, 1.0);
g_pEffect.SetVector('lhtDir', vec);
if Assigned(pMAEffect) then pMAEffect.SetVector('lhtDir', vec);
pMAEffect := nil;
// set the fixed function shader for drawing the floor
V(pd3dDevice.SetFVF(g_pMeshFloor.GetFVF));
// Draw the floor
V(g_pEffect.SetTexture('g_txScene', g_pTxFloor));
V(g_pEffect.SetMatrix('g_mWorld', g_mxFloor));
V(g_pEffect._Begin(@cPasses, 0 ));
for p := 0 to cPasses - 1 do
begin
V(g_pEffect.BeginPass(p));
V(g_pMeshFloor.DrawSubset(0));
V(g_pEffect.EndPass);
end;
V(g_pEffect._End);
// draw each tiny
for i:= 0 to g_v_pCharacters.Count - 1 do
with g_v_pCharacters[i] do
begin
// set the time to update the hierarchy
AdvanceTime(fElapsedTime, @vEye);
// draw the mesh
Draw;
end;
//
// Output text information
//
RenderText;
V(g_HUD.OnRender(fElapsedTime));
V(g_SampleUI.OnRender(fElapsedTime));
pd3dDevice.EndScene;
end;
end;
//--------------------------------------------------------------------------------------
// Render the help and statistics text. This function uses the ID3DXFont interface for
// efficient text rendering.
//--------------------------------------------------------------------------------------
procedure RenderText;
var
txtHelper: CDXUTTextHelper;
pd3dsdBackBuffer: PD3DSurfaceDesc;
i: Integer;
pChar: CTiny;
v_sReport: TStringList;
begin
// The helper object simply helps keep track of text position, and color
// and then it calls pFont->DrawText( m_pSprite, strMsg, -1, &rc, DT_NOCLIP, m_clr );
// If NULL is passed in as the sprite object, then it will work fine however the
// pFont->DrawText() will not be batched together. Batching calls will improves perf.
txtHelper:= CDXUTTextHelper.Create(g_pFont, g_pTextSprite, 15);
try
// Output statistics
txtHelper._Begin;
txtHelper.SetInsertionPos(2, 0);
txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 0.0, 1.0));
txtHelper.DrawTextLine(DXUTGetFrameStats);
txtHelper.DrawTextLine(DXUTGetDeviceStats);
pd3dsdBackBuffer := DXUTGetBackBufferSurfaceDesc;
// Dump out the FPS and device stats
txtHelper.SetInsertionPos(5, 37);
txtHelper.DrawFormattedTextLine(' Time: %2.3f', [DXUTGetGlobalTimer.GetTime]);
txtHelper.DrawFormattedTextLine(' Number of models: %d', [g_v_pCharacters.Count]);
txtHelper.SetInsertionPos(5, 70);
// We can only display either the behavior text or help text,
// with the help text having priority.
if g_bShowHelp then
begin
// output data for T[m_dwFollow]
if (Integer(g_dwFollow) <> -1) then
begin
txtHelper.DrawTextLine('Press F1 to hide animation info'#10+
'Quit: Esc');
if (g_v_pCharacters[g_dwFollow].IsUserControl) then
begin
txtHelper.SetInsertionPos(pd3dsdBackBuffer.Width - 150, 150);
txtHelper.DrawTextLine(' Tiny control:'#10+
'Move forward'#10+
'Run forward'#10+
'Turn'#10);
txtHelper.SetInsertionPos(pd3dsdBackBuffer.Width - 55, 150);
txtHelper.DrawTextLine(''#10+
'W'#10+
'Shift-W'#10+
'A,D'#10);
end;
v_sReport:= TStringList.Create;
try
pChar := g_v_pCharacters[g_dwFollow];
pChar.Report(v_sReport);
txtHelper.SetInsertionPos(5, pd3dsdBackBuffer.Height - 115);
for i := 0 to 5 do txtHelper.DrawTextLine(PWideChar(WideString(v_sReport[i])));
txtHelper.DrawTextLine(PWideChar(WideString(v_sReport[16])));
txtHelper.SetInsertionPos(210, pd3dsdBackBuffer.Height - 85);
for i := 6 to 10 do txtHelper.DrawTextLine(PWideChar(WideString(v_sReport[i])));
txtHelper.SetInsertionPos(370, pd3dsdBackBuffer.Height - 85);
for i := 11 to 15 do txtHelper.DrawTextLine(PWideChar(WideString(v_sReport[i])));
finally
FreeAndNil(v_sReport);
end;
end else
txtHelper.DrawTextLine(''#10+
'Quit: Esc');
end else
begin
if (g_dwFollow <> $ffffffff)
then txtHelper.DrawTextLine('Press F1 to display animation info'#10+
'Quit: Esc')
else txtHelper.DrawTextLine(''#10+
'Quit: Esc');
end;
txtHelper._End;
finally
txtHelper.Free;
end;
end;
//--------------------------------------------------------------------------------------
// Before handling window messages, DXUT passes incoming windows
// messages to the application through this callback function. If the application sets
// *pbNoFurtherProcessing to TRUE, then DXUT will not process this message.
//--------------------------------------------------------------------------------------
function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall;
begin
Result:= 0;
// Always allow dialog resource manager calls to handle global messages
// so GUI state is updated correctly
pbNoFurtherProcessing := g_DialogResourceManager.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
if g_SettingsDlg.IsActive then
begin
g_SettingsDlg.MsgProc(hWnd, uMsg, wParam, lParam);
Exit;
end;
// Give the dialogs a chance to handle the message first
pbNoFurtherProcessing := g_HUD.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
pbNoFurtherProcessing := g_SampleUI.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
// Pass messages to camera class for camera movement if the
// global camera if active
if (-1 = Integer(g_dwFollow)) then g_Camera.HandleMessages(hWnd, uMsg, wParam, lParam);
end;
//--------------------------------------------------------------------------------------
// As a convenience, DXUT inspects the incoming windows messages for
// keystroke messages and decodes the message parameters to pass relevant keyboard
// messages to the application. The framework does not remove the underlying keystroke
// messages, which are still passed to the application's MsgProc callback.
//--------------------------------------------------------------------------------------
procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall;
begin
if bKeyDown then
begin
case nChar of
VK_F1: g_bShowHelp := not g_bShowHelp;
end;
end;
end;
//--------------------------------------------------------------------------------------
// Handles the GUI events
//--------------------------------------------------------------------------------------
procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall;
var
pTiny: CTiny;
i: Integer;
pChar: CTiny;
begin
case nControlID of
IDC_TOGGLEFULLSCREEN: DXUTToggleFullScreen;
IDC_TOGGLEREF: DXUTToggleREF;
IDC_CHANGEDEVICE: with g_SettingsDlg do Active := not Active;
IDC_ADDTINY:
begin
pTiny := CTiny.Create;
if SUCCEEDED(pTiny.Setup(g_MultiAnim, g_v_pCharacters, g_DSound, DXUTGetGlobalTimer.GetTime))
then pTiny.SetSounds(g_bPlaySounds)
else pTiny.Free;
end;
IDC_NEXTVIEW:
if (g_v_pCharacters.Count <> 0) then
begin
if (g_dwFollow = $ffffffff) then g_dwFollow := 0
else if (Integer(g_dwFollow) = g_v_pCharacters.Count - 1) then g_dwFollow := $ffffffff
else Inc(g_dwFollow);
if (g_dwFollow = $ffffffff) then
begin
g_SampleUI.GetCheckBox(IDC_CONTROLTINY).Enabled := False;
g_SampleUI.GetCheckBox(IDC_CONTROLTINY).Visible := False;
end else
begin
g_SampleUI.GetCheckBox(IDC_CONTROLTINY).Enabled := True;
g_SampleUI.GetCheckBox(IDC_CONTROLTINY).Visible := True;
g_SampleUI.GetCheckBox(IDC_CONTROLTINY).Checked := g_v_pCharacters[g_dwFollow].IsUserControl;
end;
end;
IDC_PREVVIEW:
if (g_v_pCharacters.Count <> 0) then
begin
if (g_dwFollow = $ffffffff) then g_dwFollow := g_v_pCharacters.Count - 1
else if (g_dwFollow = 0) then g_dwFollow := $ffffffff
else Dec(g_dwFollow);
if (g_dwFollow = $ffffffff) then
begin
g_SampleUI.GetCheckBox(IDC_CONTROLTINY).Enabled := False;
g_SampleUI.GetCheckBox(IDC_CONTROLTINY).Visible := False;
end else
begin
g_SampleUI.GetCheckBox(IDC_CONTROLTINY).Enabled := True;
g_SampleUI.GetCheckBox(IDC_CONTROLTINY).Visible := True;
g_SampleUI.GetCheckBox(IDC_CONTROLTINY).Checked := g_v_pCharacters[g_dwFollow].IsUserControl;
end;
end;
IDC_RESETCAMERA:
begin
g_dwFollow := $ffffffff;
g_SampleUI.GetCheckBox(IDC_CONTROLTINY).Enabled := False;
g_SampleUI.GetCheckBox(IDC_CONTROLTINY).Visible := False;
end;
IDC_ENABLESOUND:
begin
g_bPlaySounds := (pControl as CDXUTCheckBox).Checked;
for i := 0 to g_v_pCharacters.Count - 1 do
g_v_pCharacters[i].SetSounds(g_bPlaySounds);
end;
IDC_CONTROLTINY:
if (g_dwFollow <> $ffffffff) then
begin
pChar := g_v_pCharacters[g_dwFollow];
if (pControl as CDXUTCheckBox).Checked
then pChar.SetUserControl
else pChar.SetAutoControl;
end;
IDC_RELEASEALL:
begin
for i := 0 to g_v_pCharacters.Count - 1 do
g_v_pCharacters[i].SetAutoControl;
g_SampleUI.GetCheckBox(IDC_CONTROLTINY).Checked := False;
end;
IDC_RESETTIME:
begin
DXUTGetGlobalTimer.Reset;
g_fLastAnimTime := DXUTGetGlobalTimer.GetTime;
for i := 0 to g_v_pCharacters.Count - 1 do
g_v_pCharacters[i].ResetTime;
end;
end;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has
// entered a lost state and before IDirect3DDevice9::Reset is called. Resources created
// in the OnResetDevice callback should be released here, which generally includes all
// D3DPOOL_DEFAULT resources. See the "Lost Devices" section of the documentation for
// information about lost devices.
//--------------------------------------------------------------------------------------
procedure OnLostDevice; stdcall;
var
pMAEffect: ID3DXEffect;
i: Integer;
AH: CMultiAnimAllocateHierarchy;
begin
g_DialogResourceManager.OnLostDevice;
g_SettingsDlg.OnLostDevice;
if Assigned(g_pFont) then g_pFont.OnLostDevice;
if Assigned(g_pEffect) then g_pEffect.OnLostDevice;
pMAEffect := g_MultiAnim.GetEffect;
if Assigned(pMAEffect) then
begin
pMAEffect.OnLostDevice;
pMAEffect := nil;
end;
SAFE_RELEASE(g_pTextSprite);
SAFE_RELEASE(g_pMeshFloor);
for i := 0 to g_v_pCharacters.Count - 1 do
g_v_pCharacters[i].InvalidateDeviceObjects;
AH:= CMultiAnimAllocateHierarchy.Create;
try
AH.SetMA(g_MultiAnim);
g_MultiAnim.Cleanup(AH);
finally
AH.Free;
end;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has
// been destroyed, which generally happens as a result of application termination or
// windowed/full screen toggles. Resources created in the OnCreateDevice callback
// should be released here, which generally includes all D3DPOOL_MANAGED resources.
//--------------------------------------------------------------------------------------
procedure OnDestroyDevice; stdcall;
begin
g_DialogResourceManager.OnDestroyDevice;
g_SettingsDlg.OnDestroyDevice;
SAFE_RELEASE(g_pEffect);
SAFE_RELEASE(g_pFont);
SAFE_RELEASE(g_pTxFloor);
SAFE_RELEASE(g_pMeshFloor);
end;
procedure CreateCustomDXUTobjects;
begin
g_DialogResourceManager:= CDXUTDialogResourceManager.Create; // manager for shared resources of dialogs
g_SettingsDlg:= CD3DSettingsDlg.Create; // Device settings dialog
g_Camera:= CFirstPersonCamera.Create; // A model viewing camera
g_HUD:= CDXUTDialog.Create; // manages the 3D UI
g_SampleUI:= CDXUTDialog.Create; // dialog for sample specific controls
g_DSound:= CSoundManager.Create; // DirectSound class
g_MultiAnim:= CMultiAnim.Create; // the MultiAnim class for holding Tiny's mesh and frame hierarchy
g_v_pCharacters:= TTinyList.Create; // array of character objects; each can be associated with any of the CMultiAnims
end;
procedure DestroyCustomDXUTobjects;
begin
FreeAndNil(g_DialogResourceManager);
FreeAndNil(g_SettingsDlg);
FreeAndNil(g_DSound);
FreeAndNil(g_MultiAnim);
FreeAndNil(g_v_pCharacters);
FreeAndNil(g_Camera);
FreeAndNil(g_HUD);
FreeAndNil(g_SampleUI);
end;
end.
|
{$I-,Q-,R-,S-}
{Problema 6: Lexicon Vacuno [Vladimir Novakovski, 2002]
Pocos saben que las vacas tienen su propio diccionario con W (1 <= W
<= 600) palabras, cada una conteniendo no más de 25 de los caracteres
'a'..'z'. Debido a que su sistema de comunicación, basado en mugidos,
no es muy preciso, algunas veces ellas oyen palabras que no tienen
ningún sentido. Por ejemplo, Bessie una vez recibió un mensaje que
decía "browndcodw". Y resulta ser que el mensaje deseado era
"browncow". Las dos letras "d"s eran ruido de otra partes del corral.
Las vacas quieren que usted las ayude a descifrar un mensaje recibido
(también contiendo únicamente caracteres en el rango 'a'..'z') de
longitud de L (1 <= L <= 300) caracteres que está un poco enredado. En
particular, ellas saben que el mensaje tiene algunas letras extra, y
ellas quieren que usted determine el menor número de letras que deben
ser removidas para hacer que el mensaje sea una secuencia de palabras
del diccionario.
NOMBRE DEL PROBLEMA: lexicon
FORMATO DE ENTRADA:
* Línea 1: Dos enteros separados por espacio, respectivamente: W y L
* Líneas 2: L caracteres (seguidos por un carácter de nueva línea, por
supuesto): el mensaje recibido
* Líneas 3..W+2: El diccionario de las vacas, una palabra por línea.
ENTRADA EJEMPLO (archivo lexicon.in):
6 10
browndcodw
cow
milk
white
black
brown
farmer
FORMATO DE SALIDA:
* Línea 1: Una solo entero que es el mínimo número de caracteres que
necesitan ser removidos para hacer el mensaje una secuencia de
palabras del diccionario.
SALIDA EJEMPLO (archivo lexicon.OUT):
}
const
max = 301;
maxword = 601;
var
fe,fs : text;
n,m,sol : longint;
cad : array[1..max] of char;
list : array[1..maxword] of string[26];
best : array[1..max] of longint;
cont : array[1..maxword] of longint;
be : array[1..131072] of byte;
procedure open;
var
i : longint;
begin
assign(fe,'lexicon.in'); reset(fe);
assign(fs,'lexicon.out'); rewrite(fs);
settextbuf(fe,be);
readln(fe,m,n);
for i:=1 to n do
begin
read(fe,cad[i]);
best[i]:=i;
end;
readln(fe);
for i:=1 to m do
begin
readln(fe,list[i]);
cont[i]:=length(list[i]);
end;
close(fe);
end;
procedure comprueba(x,y : longint);
var
i,j,k : longint;
begin
j:=x; k:=0;
for i:=1 to cont[y] do
begin
while (list[y,i] <> cad[j]) do
begin
inc(j);
inc(k);
end;
inc(j);
end;
if (best[x-1] + k < best[j-1]) then
best[j-1]:=best[x-1] + k;
end;
procedure work;
var
i,j : longint;
begin
for i:=1 to n do
begin
for j:=1 to m do
begin
if (i + cont[j]-1 <= n) and (cad[i] = list[j][1]) then
comprueba(i,j);
end;
if (best[i] + 1 < best[i+1]) then
best[i+1]:=best[i] + 1;
end;
end;
procedure closer;
begin
writeln(fs,best[n]);
close(fs);
end;
begin
open;
work;
closer;
end.
|
unit TextView;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Htmlview, StdCtrls, AmlView;
type
TTextViewer = class(TAmlViewer)
HtmlViewer: THTMLViewer;
private
procedure SetHeading(const AHeading : String);
procedure SetHTML(const AHtml : String);
public
constructor Create(AOwner : TComponent); override;
property Heading : String write SetHeading;
property Html : String write SetHTML;
end;
function ShowText(const AHeading, AText : String;
AWidth, AHeight : Integer) : TTextViewer;
implementation
uses Main;
{$R *.DFM}
constructor TTextViewer.Create(AOwner : TComponent);
begin
inherited Create(AOwner);
SetupHtmlViewerDefaults(HtmlViewer);
end;
procedure TTextViewer.SetHeading(const AHeading : String);
begin
Caption := AHeading;
end;
procedure TTextViewer.SetHTML(const AHtml : String);
begin
HtmlViewer.LoadFromBuffer(PChar(AHtml), Length(AHtml));
if HtmlViewer.DocumentTitle <> '' then
Caption := HtmlViewer.DocumentTitle;
end;
function ShowText(const AHeading, AText : String; AWidth, AHeight : Integer) : TTextViewer;
begin
Result := TTextViewer.Create(Application);
Result.AddressMgr := MainForm;
Result.DataMgr := MainForm.DataMgr;
Result.StatusDisplay := MainForm;
Result.Html := AText;
if AHeading <> '' then
Result.Heading := AHeading;
Result.Width := AWidth;
Result.Height := AHeight;
Result.Show;
end;
end.
|
unit DPM.Core.Package.PackageLatestVersionInfo;
interface
uses
DPM.Core.Types,
DPM.Core.Package.Interfaces;
type
TDPMPackageLatestVersionInfo = class(TInterfacedObject, IPackageLatestVersionInfo)
private
FId : string;
FLatestStableVersion: TPackageVersion;
FLatestVersion: TPackageVersion;
protected
function GetId: string;
function GetLatestStableVersion: TPackageVersion;
function GetLatestVersion: TPackageVersion;
procedure SetLatestStableVersion(const value : TPackageVersion);
procedure SetLatestVersion(const value : TPackageVersion);
public
constructor Create(const id : string; const latestStableVer : TPackageVersion; const latestVersion : TPackageVersion);
end;
implementation
{ TDPMPackageLatestVersionInfo }
constructor TDPMPackageLatestVersionInfo.Create(const id: string; const latestStableVer, latestVersion: TPackageVersion);
begin
FId := id;
FLatestStableVersion := latestStableVer;
FLatestVersion := latestVersion;
end;
function TDPMPackageLatestVersionInfo.GetId: string;
begin
result := FId;
end;
function TDPMPackageLatestVersionInfo.GetLatestStableVersion: TPackageVersion;
begin
result := FLatestStableVersion;
end;
function TDPMPackageLatestVersionInfo.GetLatestVersion: TPackageVersion;
begin
result := FLatestVersion;
end;
procedure TDPMPackageLatestVersionInfo.SetLatestStableVersion(const value: TPackageVersion);
begin
FLatestStableVersion := value;
end;
procedure TDPMPackageLatestVersionInfo.SetLatestVersion(const value: TPackageVersion);
begin
FLatestVersion := value;
end;
end.
|
// Copyright (c) 2009, ConTEXT Project Ltd
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// 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.
// Neither the name of ConTEXT Project Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
// 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 uHighlighter;
interface
{$I ConTEXT.inc}
{
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ConTEXTSynEdit, SynEdit, uCommon, Clipbrd, SynUniHighlighter,
ExtCtrls, SynEditHighlighter, uSafeRegistry,
SynEditTypes, uHighlighterProcs, uCommonClass;
type
THighlighter = class(TSynUniSyn)
private
public
end;
}
implementation
end.
|
unit Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls;
type
TScreenForm = class(TForm)
RenderTimer: TTimer;
Display: TPaintBox;
procedure DisplayPaint(Sender: TObject);
procedure RenderTimerTimer(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
private
{ Private declarations }
FBackBuffer: TBitmap;
FLevel: TBitmap;
FStaticCollision: TBitmap;
FDynamicCollision: array[Boolean] of TBitmap;
//first dimension is for different characters
//second dimension represents the states:
//0 = stand, 1 = walk, 2 = jump/InAir
FSprites: array[0..13] of array[0..2] of TBitmap;
FFlippedSprites: array[0..13] of array[0..2] of TBitmap;
FCamera_X: Integer;
FCamera_Y: Integer;
FNextCameraX: Integer;
FNextCameraY: Integer;
FScreenWidth: Integer;
FScreenHeight: Integer;
FFrameCounter: Integer;
FCurrentDC: Boolean;
FTargetDimensions: TRect;
FNumActiveScreens: Integer;
FOldDimension: TRect;
FOldStyle: TFormBorderStyle;
FImageFolder: string;
procedure LoadSprites;
procedure LoadSprite(AIndex: Integer; AStates: array of string);
procedure DrawRect(ATarget, ASource: TCanvas; AX, AY: Integer; ASRect: TRect);
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
procedure ToggleFullScreen;
end;
var
ScreenForm: TScreenForm;
implementation
uses
IOUtils,
PNGImage,
Level_1_1.Entities,
SyncObjs,
Math;
const
CSpriteWidth = 16;
CSpriteHeight = 16;
CHalfSpriteWidth = 8;
CHalfSpriteHeight = 8;
CNoDynCollision = clWhite;
CResolutionX = 256;
CResolutionY = 240;
{$R *.dfm}
{ TScreenForm }
constructor TScreenForm.Create(AOwner: TComponent);
begin
inherited;
if TDirectory.Exists('Images') then
FImageFolder := 'Images'
else
FImageFolder := '..\..\Images';
FBackBuffer := TBitmap.Create();
FBackBuffer.SetSize(256, 240);
FBackBuffer.PixelFormat := pf32bit;
FLevel := TBitmap.Create();
FLevel.LoadFromFile(TPath.Combine(FImageFolder, 'Level-1-1.bmp'));
FLevel.PixelFormat := pf32bit;
FStaticCollision := TBitmap.Create();
FStaticCollision.LoadFromFile(TPath.Combine(FImageFolder, 'Level-1-1-Collision.bmp'));
FStaticCollision.PixelFormat := pf32bit;
FDynamicCollision[False] := TBitmap.Create();
FDynamicCollision[False].SetSize(FStaticCollision.Width, FStaticCollision.Height);
FDynamicCollision[False].PixelFormat := pf32bit;
FDynamicCollision[False].Canvas.Brush.Color := CNoDynCollision;
FDynamicCollision[False].Canvas.Pen.Color := CNoDynCollision;
FDynamicCollision[False].Canvas.FillRect(FDynamicCollision[False].Canvas.ClipRect);
FDynamicCollision[True] := TBitmap.Create();
FDynamicCollision[True].SetSize(FStaticCollision.Width, FStaticCollision.Height);
FDynamicCollision[True].PixelFormat := pf32bit;
FDynamicCollision[True].Canvas.Brush.Color := CNoDynCollision;
FDynamicCollision[True].Canvas.Pen.Color := CNoDynCollision;
FDynamicCollision[True].Canvas.FillRect(FDynamicCollision[True].Canvas.ClipRect);
FNumActiveScreens := 1;
ClientHeight := FBackBuffer.Height * FNumActiveScreens;
ClientWidth := FBackBuffer.Width;
LoadSprites();
FScreenWidth := FBackBuffer.Width;
FScreenHeight := FBackBuffer.Height;
end;
procedure TScreenForm.DisplayPaint(Sender: TObject);
var
LSecondTarget: TRect;
begin
Display.Canvas.CopyMode := SRCCOPY;
Display.Canvas.StretchDraw(FTargetDimensions, FBackBuffer);
if FNumActiveScreens > 1 then
begin
LSecondTarget.Top := FTargetDimensions.Height;
LSecondTarget.Bottom := LSecondTarget.Top + LSecondTarget.Top;
LSecondTarget.Left := FTargetDimensions.Left;
LSecondTarget.Right := LSecondTarget.Left + FTargetDimensions.Width;
Display.Canvas.CopyRect(LSecondTarget,
FStaticCollision.Canvas, Rect(FCamera_X, FCamera_Y, FCamera_X + FBackBuffer.Width, FBackBuffer.Height));
Display.Canvas.CopyMode := SRCINVERT;
Display.Canvas.CopyRect(LSecondTarget,
FDynamicCollision[not FCurrentDC].Canvas, Rect(FCamera_X, FCamera_Y, FCamera_X + FBackBuffer.Width, FBackBuffer.Height));
end;
end;
procedure TScreenForm.DrawRect(ATarget, ASource: TCanvas; AX, AY: Integer;
ASRect: TRect);
var
LBlend: BLENDFUNCTION;
begin
LBlend.BlendOp := AC_SRC_OVER;
LBlend.BlendFlags := 0;
LBlend.SourceConstantAlpha := 255;
LBlend.AlphaFormat := AC_SRC_ALPHA;
Winapi.Windows.AlphaBlend(ATarget.Handle, AX, AY, ASRect.Width, ASRect.Height,
ASource.Handle, ASRect.Left, ASRect.Top, ASRect.Width, ASRect.Height, LBlend)
end;
procedure TScreenForm.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (Key = VK_RETURN) and (Shift = [ssAlt]) then
ToggleFullScreen();
if Key = VK_F1 then
begin
if FNumActiveScreens = 1 then
FNumActiveScreens := 2
else
FNumActiveScreens := 1;
FormResize(Self);
end;
end;
procedure TScreenForm.FormResize(Sender: TObject);
var
LWidth, LHeight: Integer;
begin
if (ClientHeight div FNumActiveScreens) < ClientWidth then
begin
LHeight := ClientHeight div FNumActiveScreens;
LWidth := Trunc(LHeight / CResolutionY * CResolutionX);
end
else
begin
LWidth := ClientWidth;
LHeight := Trunc(LWidth / CResolutionX * CResolutionY);
end;
FTargetDimensions.Left := (ClientWidth - LWidth) div 2;
FTargetDimensions.Top := 0;
FTargetDimensions.Right := FTargetDimensions.Left + LWidth;
FTargetDimensions.Bottom := FTargetDimensions.Top + LHeight;
end;
procedure TScreenForm.ToggleFullScreen;
begin
if BorderStyle <> bsNone then
begin
FOldStyle := BorderStyle;
FOldDimension.Location := Point(Left, Top);
FOldDimension.Size := TSize.Create(ClientWidth, ClientHeight);
BorderStyle := bsNone;
Left := 0;
Top := 0;
Width := Screen.Width;
Height := Screen.Height;
end
else
begin
BorderStyle := FOldStyle;
Left := FOldDimension.Left;
Top := FOldDimension.Top;
ClientWidth := FOldDimension.Width;
ClientHeight := FOldDimension.Height;
end;
end;
procedure TScreenForm.LoadSprite(AIndex: Integer; AStates: array of string);
var
LTemp: TPngImage;
i, LState: Integer;
begin
LTemp := TPngImage.Create();
try
LState := 0;
for i := LState to High(FSprites[0]) do
begin
if (i = LState) and (AStates[LState] <> '') then
begin
LTemp.LoadFromFile(TPath.Combine(FImageFolder, AStates[LState]));
end;
FSprites[AIndex, i] := TBitmap.Create();
FSprites[AIndex, i].Assign(LTemp);
FFlippedSprites[AIndex][i] := TBitmap.Create();
FFlippedSprites[AIndex][i].SetSize(LTemp.Width, LTemp.Height);
FFlippedSprites[AIndex][i].PixelFormat := pf32bit;
FFlippedSprites[AIndex][i].Canvas.CopyRect(Rect(FSprites[AIndex][i].Width - 1, 0, -1, FSprites[AIndex][i].Height), FSprites[AIndex][i].Canvas, FSprites[AIndex][i].Canvas.ClipRect);
if (LState < High(AStates)) then
Inc(LState);
end;
finally
LTemp.Free;
end;
end;
procedure TScreenForm.LoadSprites;
begin
LoadSprite(0,['Mario_Stand.png', 'Mario_Walk.png', 'Mario_Jump.png']);
LoadSprite(1, ['Mario_Dead.png']);
LoadSprite(2, ['Brick.png']);
LoadSprite(3, ['Gumba_Walk.png']);
LoadSprite(4, ['Gumba_Dead.png']);
LoadSprite(5, ['ItemBlock.png']);
LoadSprite(6, ['ItemBlock_Empty.png']);
LoadSprite(7, ['Coin_Spinning.png']);
LoadSprite(8, ['Koopa_Walk.png']);
LoadSprite(9, ['Koopa_Shell.png']);
LoadSprite(10, ['GameOver.png']);
LoadSprite(11, ['StartScreen.png']);
LoadSprite(12, ['Finish.png']);
LoadSprite(13, ['Null.png']);
end;
const
CCameraDeadZone = 80;
CActivityBorder = 40;
CStand = 0;
CWalk = 1;
CJump = 2;
CGravity = 0.3;
CEdgeIdent = 2;
CDeadZoneMin = 240;
CDeadZoneMax = 260;
procedure TScreenForm.RenderTimerTimer(Sender: TObject);
var
i: Integer;
LDummy: Boolean;
LTopEdgeLeft, LTopEdgeRight, LLeftEdgeTop, LLeftEdgeBottom, LRightEdgeTop, LRightEdgeBottom, LBottomEdgeLeft, LBottomEdgeRight: Integer;
LX, LY: Integer;
LRect: TRect;
LSprite: TBitmap;
LSpriteState, LSpriteFrame, LFrameCount, LFrameWidth: Integer;
LDynLeft, LDynRight, LDynTop, LDynDown, LTargetEnt, LNextEntity: Integer;
LBBLeft, LBBRight, LBBTop, LBBBottom: Integer;
begin
//reset dynamic collisionmask
FDynamicCollision[not FCurrentDC].Canvas.Brush.Color := CNoDynCollision;
FDynamicCollision[not FCurrentDC].Canvas.Pen.Color := CNoDynCollision;
FDynamicCollision[not FCurrentDC].Canvas.FillRect(FDynamicCollision[not FCurrentDC].Canvas.ClipRect);
//Draw Level
FCamera_X := FNextCameraX;
FCamera_Y := FNextCameraY;
FBackBuffer.Canvas.Draw(-FCamera_X, -FCamera_Y, FLevel);
for i := Low(GEntity) to High(GEntity) do
begin
//the following giant IF is executed per Entity. It evaluates if the Entity must be updated/painted
//and executes it's logik at the same run!
//execute only if active and has input or is near to the camera
if (GEntity[i].Active <> 0) and (GEntity[i].Input or (bfAlwaysUpdate in GEntity[i].BehaviorFlags) or (((GEntity[i].X - FCamera_X) >= -CActivityBorder) and ((GEntity[i].X - FCamera_X) < FScreenWidth + CActivityBorder))) and Boolean(Trunc(
//reset some values
TInterlocked.Exchange(LTargetEnt, CNoDynCollision)
//get input
+ Integer(GEntity[i].Input and Boolean(Trunc(TInterlocked.Exchange(GEntity[i].Vel_X, 2*((GetAsyncKeyState(VK_RIGHT) shr 31 and 1) - (GetAsyncKeyState(VK_LEFT) shr 31 and 1))))))
+ Integer(GEntity[i].Input and (GEntity[i].DownBlocked <> 0) and Boolean(Trunc(TInterlocked.Exchange(GEntity[i].Vel_Y, 6.5 * (GetAsyncKeyState(VK_SPACE) shr 31 and 1)))))
//apply velocity
+ Integer( (((GEntity[i].LeftBlocked = 0) and (GEntity[i].Vel_X < 0)) or ((GEntity[i].RightBlocked = 0) and (GEntity[i].Vel_X > 0))) and (TInterlocked.Exchange(GEntity[i].X, GEntity[i].X + GEntity[i].Vel_X) * 0 = 0))
//apply gravity
+ TInterlocked.Exchange(GEntity[i].Vel_Y, Max(-5, GEntity[i].Vel_Y - CGravity * GEntity[i].Gravity))
+ Integer((((GEntity[i].DownBlocked = 0) and (GEntity[i].Vel_Y < 0)) or ((GENtity[i].UpBlocked = 0) and (GEntity[i].Vel_Y > 0))) and
Boolean(Trunc(
TInterlocked.Exchange(GEntity[i].Y, GEntity[i].Y - GEntity[i].Vel_Y)
+ TInterlocked.Exchange(GEntity[i].InAirTimer, GEntity[i].InAirTimer + 1)
))
)
//////Collisiooncode...loooong!
//Trunc current position to pixels
+ TInterlocked.Exchange(LX, Trunc(GEntity[i].X))
+ TInterlocked.Exchange(LY, Trunc(GEntity[i].Y))
+ TInterlocked.Exchange(LBBLeft, LX - GEntity[i].bbWidth div 2)
+ TInterlocked.Exchange(LBBRight, LX + GEntity[i].bbWidth div 2 - 1)
+ TInterlocked.Exchange(LBBTop, LY - GEntity[i].bbHeight div 2)
+ TInterlocked.Exchange(LBBBottom, LY + GEntity[i].bbHeight div 2 - 1)
//do checks only if we are alive and do not ignore it!
+ Integer(not (bfIgnoreCollision in GEntity[i].BehaviorFlags) and (GEntity[i].Live > 0)
and Boolean(Trunc(
//collision checks
//static collision
//get collision values of edges of BoundingBox
//TopEdge
+ TInterlocked.Exchange(LTopEdgeLeft, FStaticCollision.Canvas.Pixels[LBBLeft + CEdgeIdent, LBBTop])
+ TInterlocked.Exchange(LTopEdgeRight, FStaticCollision.Canvas.Pixels[LBBRight - CEdgeIdent, LBBTop])
//LeftEdge
+ TInterlocked.Exchange(LLeftEdgeTop, FStaticCollision.Canvas.Pixels[LBBLeft, LBBTop + CEdgeIdent])
+ TInterlocked.Exchange(LLeftEdgeBottom, FStaticCollision.Canvas.Pixels[LBBLeft, LBBBottom - CEdgeIdent])
//RightEdge
+ TInterlocked.Exchange(LRightEdgeTop, FStaticCollision.Canvas.Pixels[LBBRight, LBBTop + CEdgeIdent])
+ TInterlocked.Exchange(LRightEdgeBottom, FStaticCollision.Canvas.Pixels[LBBRight, LBBBottom - CEdgeIdent])
//BottomEdge
+ TInterlocked.Exchange(LBottomEdgeLeft, FStaticCollision.Canvas.Pixels[LBBLeft + CEdgeIdent, LBBBottom])
+ TInterlocked.Exchange(LBottomEdgeRight, FStaticCollision.Canvas.Pixels[LBBRight - CEdgeIdent, LBBBottom])
//combine 2 corners each edge to determine if walking into the given direction is possible
+ TInterlocked.Exchange(GEntity[i].LeftBlocked, LLeftEdgeTop + LLeftEdgeBottom)
+ TInterlocked.Exchange(GEntity[i].RightBlocked, LRightEdgeTop + LRightEdgeBottom)
+ TInterlocked.Exchange(GEntity[i].UpBlocked, LTopEdgeLeft + LTopEdgeRight)
+ TInterlocked.Exchange(GEntity[i].DownBlocked, LBottomEdgeLeft + LBottomEdgeRight)
//Dynamic Collision
//get collision values of edges of BoundingBox
//TopEdge
+ TInterlocked.Exchange(LTopEdgeLeft, FDynamicCollision[FCurrentDC].Canvas.Pixels[LBBLeft + CEdgeIdent, LBBTop])
+ TInterlocked.Exchange(LTopEdgeRight, FDynamicCollision[FCurrentDC].Canvas.Pixels[LBBRight - CEdgeIdent, LBBTop])
//LeftEdge
+ TInterlocked.Exchange(LLeftEdgeTop, FDynamicCollision[FCurrentDC].Canvas.Pixels[LBBLeft, LBBTop + CEdgeIdent])
+ TInterlocked.Exchange(LLeftEdgeBottom, FDynamicCollision[FCurrentDC].Canvas.Pixels[LBBLeft, LBBBottom - CEdgeIdent])
//RightEdge
+ TInterlocked.Exchange(LRightEdgeTop, FDynamicCollision[FCurrentDC].Canvas.Pixels[LBBRight, LBBTop + CEdgeIdent])
+ TInterlocked.Exchange(LRightEdgeBottom, FDynamicCollision[FCurrentDC].Canvas.Pixels[LBBRight, LBBBottom - CEdgeIdent])
//BottomEdge
+ TInterlocked.Exchange(LBottomEdgeLeft, FDynamicCollision[FCurrentDC].Canvas.Pixels[LBBLeft + CEdgeIdent, LBBBottom])
+ TInterlocked.Exchange(LBottomEdgeRight, FDynamicCollision[FCurrentDC].Canvas.Pixels[LBBRight - CEdgeIdent, LBBBottom])
//combine 2 corners each edge to determine if walking into the given direction is possible
+ TInterlocked.Exchange(LDynLeft, IfThen((LLeftEdgeTop <> CNoDynCollision) and (LLeftEdgeTop <> i), LLeftEdgeTop, LLeftEdgeBottom))
+ TInterlocked.Exchange(LDynRight, IfThen((LRightEdgeTop <> CNoDynCollision) and (LRightEdgeTop <> i), LRightEdgeTop, LRightEdgeBottom))
+ TInterlocked.Exchange(LDynTop, IfThen((LTopEdgeLeft <> CNoDynCollision) and (LTopEdgeLeft <> i), LTopEdgeLeft, LTopEdgeRight))
+ TInterlocked.Exchange(LDynDown, IfThen((LBottomEdgeLeft <> CNoDynCollision) and (LBottomEdgeLeft <> i), LBottomEdgeLeft, LBottomEdgeRight))
// //if collided and not collided with self, add to entity collision state
+ TInterlocked.Exchange(GEntity[i].LeftBlocked, GEntity[i].LeftBlocked + IfThen((LDynLeft <> CNoDynCollision) and (LDynLeft <> i), LDynLeft, 0))
+ TInterlocked.Exchange(GEntity[i].RightBlocked, GEntity[i].RightBlocked + IfThen((LDynRight <> CNoDynCollision) and (LDynRight <> i), LDynRight, 0))
+ TInterlocked.Exchange(GEntity[i].UpBlocked, GEntity[i].UpBlocked + IfThen((LDynTop <> CNoDynCollision) and (LDynTop <> i), LDynTop, 0))
+ TInterlocked.Exchange(GEntity[i].DownBlocked, GEntity[i].DownBlocked + IfThen((LDynDown <> CNoDynCollision) and (LDynDown <> i), LDynDown, 0))
// //determine entity we collided with if exists
+ TInterlocked.Exchange(LTargetEnt, IfThen((LDynRight <> i) and (LDynRight <> CNoDynCollision), LDynRight, CNoDynCollision))
+ TInterlocked.Exchange(LTargetEnt, IfThen((LDynLeft <> i) and (LDynLeft <> CNoDynCollision), LDynLeft, LTargetEnt))
+ TInterlocked.Exchange(LTargetEnt, IfThen((LDynDown <> i) and (LDynDown <> CNoDynCollision), LDynDown, LTargetEnt))
+ TInterlocked.Exchange(LTargetEnt, IfThen((LDynTop <> i) and (LDynTop <> CNoDynCollision), LDynTop, LTargetEnt))
)))
//end of collisioncode!!!
//positional correction in case we are inside an obstacle
//do not correct Horizontal position if fallspeed was higher then walkspeed and we collided with floor to avoid being pushed of blocks we jumped on
//wen just a few pixels on the blocks
+ Integer(((Abs(GEntity[i].Vel_X) >= Abs(GEntity[i].Vel_Y)) or (GEntity[i].DownBlocked = 0)) and Boolean(
Integer( (GEntity[i].LeftBlocked <> 0) and Boolean(Trunc(TInterlocked.Exchange(GEntity[i].X, GEntity[i].X + 1))))
+ Integer( (GEntity[i].RightBlocked <> 0) and Boolean(Trunc(TInterlocked.Exchange(GEntity[i].X, GEntity[i].X - 1))))
))
+ Integer( (GEntity[i].UpBlocked <> 0) and Boolean(Trunc(TInterlocked.Exchange(GEntity[i].Y, GEntity[i].Y + 1))))
+ Integer( (GEntity[i].DownBlocked <> 0) and Boolean(Trunc(TInterlocked.Exchange(GEntity[i].Y, LY - 1))))
//bounce/reset velocity when colliding to reset falling momentum
+ Integer( (((GEntity[i].LeftBlocked <> 0) and (GEntity[i].Vel_X < 0)) or ((GEntity[i].RightBlocked <> 0) and (GEntity[i].Vel_X > 0)))
and Boolean(Trunc(
TInterlocked.Exchange(GEntity[i].Vel_X, GEntity[i].Vel_X * -GEntity[i].BounceX)
)))
+ Integer( (((GEntity[i].UpBlocked <> 0) and (GEntity[i].Vel_Y > 0)) or ((GEntity[i].DownBlocked <> 0) and (GEntity[i].Vel_Y < 0)))
and Boolean(Trunc(
TInterlocked.Exchange(GEntity[i].Vel_Y, GEntity[i].Vel_Y * -GEntity[i].BounceY))
+ TInterlocked.Exchange(GEntity[i].InAirTimer, 0)
)
)
+ TInterlocked.Increment(GEntity[i].LastColliderTime)
//if we collided with another entity(which we didn collide with in the last frame), which is alive and not in our team, attack and take damage!
+ Integer((LTargetEnt <> CNoDynCollision) and (GEntity[LTargetEnt].Active <> 0) and (GEntity[LTargetEnt].Team <> GEntity[i].Team)
and (((GEntity[i].LastCollider <> LTargetEnt) and (GEntity[LTargetEnt].LastCollider <> i))
or ((GEntity[i].LastColliderTime > 5) and (GEntity[LTargetEnt].LastColliderTime > 5))
)
and Boolean(Trunc(
+ Integer((LTargetEnt = LDynTop) and (GEntity[LTargetEnt].Live > 0) and Boolean(Trunc(
TInterlocked.Add(GEntity[LTargetEnt].Live, -GEntity[i].DamageTop*GEntity[LTargetEnt].VulnerableBottom)
+ TInterlocked.Add(GEntity[i].Live, -GEntity[LTargetEnt].DamageBottom*GEntity[i].VulnerableTop)
)))
+ Integer((LTargetEnt = LDynDown) and (GEntity[LTargetEnt].Live > 0) and Boolean(Trunc(
TInterlocked.Add(GEntity[LTargetEnt].Live, -GEntity[i].DamageBottom*GEntity[LTargetEnt].VulnerableTop)
+ TInterlocked.Add(GEntity[i].Live, -GEntity[LTargetEnt].DamageTop*GEntity[i].VulnerableBottom)
)))
+ Integer((LTargetEnt = LDynLeft) and (GEntity[LTargetEnt].Live > 0) and Boolean(Trunc(
TInterlocked.Add(GEntity[LTargetEnt].Live, -GEntity[i].DamageLeft*GEntity[LTargetEnt].VulnerableRight)
+ TInterlocked.Add(GEntity[i].Live, -GEntity[LTargetEnt].DamageRight*GEntity[i].VulnerableLeft)
)))
+ Integer((LTargetEnt = LDynRight) and (GEntity[LTargetEnt].Live > 0) and Boolean(Trunc(
TInterlocked.Add(GEntity[LTargetEnt].Live, -GEntity[i].DamageRight*GEntity[LTargetEnt].VulnerableLeft)
+ TInterlocked.Add(GEntity[i].Live, -GEntity[LTargetEnt].DamageLeft*GEntity[i].VulnerableRight)
)))
//store us as lastcollider in targetent so it does not interact with us on next frame
+ TInterlocked.Exchange(GEntity[LTargetEnt].LastCollider, i)
+ TInterlocked.Exchange(GEntity[LTargetEnt].LastColliderTime, 0)
+ TInterlocked.Exchange(GEntity[i].LastCollider, LTargetEnt)
+ TInterlocked.Exchange(GEntity[i].LastColliderTime, 0)
)))
//check DeadZone
+ Integer((GEntity[i].Y > CDeadZoneMin) and (GEntity[i].Y < CDeadZoneMax) and Boolean(
+ TInterlocked.Exchange(GEntity[i].Live, 0)
))
//camera movement
+ Integer((bfCameraFollows in GENtity[i].BehaviorFlags) and Boolean(
+ TInterlocked.Exchange(FNextCameraY, Trunc(GEntity[i].Y) div CDeadZoneMax * FScreenHeight)
+ Integer((GEntity[i].X - FCamera_X > FScreenWidth-CCameraDeadZone) and Boolean(TInterlocked.Exchange(FNextCameraX, Min(FLevel.Width - FScreenWidth, Trunc(FCamera_X + (GEntity[i].X - FCamera_X - FScreenWidth + CCameraDeadZone))))))
+ Integer((GEntity[i].X - FCamera_X < CCameraDeadZone) and Boolean(TInterlocked.Exchange(FNextCameraX, Max(0, Trunc(FCamera_X + (GEntity[i].X - FCamera_X - CCameraDeadZone))))))
))
+ Integer((bfCameraCenters in GEntity[i].BehaviorFlags) and Boolean(
TInterlocked.Exchange(FNextCameraX, Trunc(GEntity[i].X - FScreenWidth div 2))
+ TInterlocked.Exchange(FNextCameraY, Trunc(GEntity[i].Y - FScreenHeight div 2))
))
+ TInterlocked.Add(GEntity[i].LiveTime, -1)
//check if we died and take actions if this is true
+ Integer(((GEntity[i].Live < 1) or (GEntity[i].LiveTime = 0)) and Boolean(Trunc(
Integer((GEntity[i].LiveTime = 0) and Boolean(TInterlocked.Exchange(LNextEntity, GEntity[i].ReplaceOnTimeOut)))
+ Integer((GEntity[i].Live < 1) and Boolean(TInterlocked.Exchange(LNextEntity, GEntity[i].ReplaceOnDead)))
//deactivate us so we are removed next frame
+ TInterlocked.Exchange(GEntity[i].Active, 0)
//replace with entity if specified
+ Integer((LNextEntity > 0) and Boolean(Trunc(
+ TInterlocked.Exchange(LNextEntity, i + LNextEntity)
+ TInterlocked.Exchange(GEntity[LNextEntity].Active, 1)
+ TInterlocked.Exchange(GEntity[LNextEntity].LastCollider, GEntity[i].LastCollider)
+ Integer((sfCopyPosition in GEntity[LNextEntity].SpawnFlags) and Boolean(Trunc(
+ TInterlocked.Exchange(GEntity[LNextEntity].X, GEntity[i].X)
+ TInterlocked.Exchange(GEntity[LNextEntity].Y, GEntity[i].Y)
)))
)))
)))
//check our current state(standing, walking, Jumping/InAir)
+ TInterlocked.Exchange(LSpriteState, CStand)
+ Integer((GEntity[i].Vel_X <> 0) and Boolean(Trunc(TInterlocked.Exchange(LSpriteState, CWalk))))
+ Integer(((GEntity[i].DownBlocked = 0) and (GEntity[i].InAirTimer > 1)) and Boolean(Trunc(TInterlocked.Exchange(LSpriteState, CJump))))
//check if we need to use a flipped version of our image or the normal one
+ Integer((not GEntity[i].NoDirection) and (GEntity[i].InAirTimer <= 1) and (GEntity[i].Vel_X <> 0)
and (Boolean((GEntity[i].Vel_X < 0) and Boolean(Trunc(
+ TInterlocked.Exchange(GEntity[i].Orientation, -1) * 0 - 1
)))
or Boolean(
TInterlocked.Exchange(GEntity[i].Orientation, 1)
))
)
+ Integer(((GEntity[i].Orientation < 0) and
Boolean(Trunc(
Integer(TInterlocked.Exchange<TBitmap>(LSprite, FFlippedSprites[GEntity[i].Sprite][LSpriteState])) * 0 - 1
))) or
Boolean(Trunc(
Integer(TInterlocked.Exchange<TBitmap>(LSprite, FSprites[GEntity[i].Sprite][LSpriteState]))
))
)
//Calculate current Frame of sprite to display
+ Integer(((GEntity[i].Frames > 0) and Boolean(
TInterlocked.Exchange(LFrameCount, GEntity[i].Frames) * 0 - 1))
or
Boolean(TInterlocked.Exchange(LFrameCount, (LSprite.Width div CSpriteWidth)))
)
+ TInterlocked.Exchange(LFrameWidth, LSprite.Width div LFrameCount)
+ TInterlocked.Exchange(LSpriteFrame, FFrameCounter div (50 div 16) mod LFrameCount)
//Translate EntityPosition
+ TInterlocked.Exchange(LX, Trunc(GEntity[i].X - LFrameWidth div 2 - FCamera_X))
+ TInterlocked.Exchange(LY, Trunc(GEntity[i].Y - LSprite.Height div 2 - FCamera_Y))
//recalculate the BB area
+ TInterlocked.Exchange(LBBLeft, Trunc(GEntity[i].X) - GEntity[i].bbWidth div 2)
+ TInterlocked.Exchange(LBBRight, Trunc(GEntity[i].X) + GEntity[i].bbWidth div 2)
+ TInterlocked.Exchange(LBBTop, Trunc(GEntity[i].Y) - GEntity[i].bbHeight div 2 )
+ TInterlocked.Exchange(LBBBottom, Trunc(GEntity[i].Y) + GEntity[i].bbHeight div 2)
)*0-1)
then
begin
//Draw Entity
FDynamicCollision[not FCurrentDC].Canvas.Brush.Color := TColor(i);
FDynamicCollision[not FCurrentDC].Canvas.Pen.Color := TColor(i);
FDynamicCollision[not FCurrentDC].Canvas.Rectangle(LBBLeft, LBBTop, LBBRight, LBBBottom);
// //debugstuff
// FDynamicCollision[not FCurrentDC].Canvas.Pixels[LBBLeft + CEdgeIdent, LBBTop] := clFuchsia;
// FDynamicCollision[FCurrentDC].Canvas.Pixels[LBBRight - CEdgeIdent - 1, LBBTop] := clFuchsia;
// //LeftEdge
// FDynamicCollision[not FCurrentDC].Canvas.Pixels[LBBLeft, LBBTop + CEdgeIdent]:= clFuchsia;
// FDynamicCollision[not FCurrentDC].Canvas.Pixels[LBBLeft, LBBBottom - 1 - CEdgeIdent]:= clFuchsia;
// //RightEdge
// FDynamicCollision[not FCurrentDC].Canvas.Pixels[LBBRight - 1, LBBTop + CEdgeIdent]:= clFuchsia;
// FDynamicCollision[not FCurrentDC].Canvas.Pixels[LBBRight - 1, LBBBottom - CEdgeIdent - 1]:= clFuchsia;
// //BottomEdge
// FDynamicCollision[not FCurrentDC].Canvas.Pixels[LBBLeft + CEdgeIdent, LBBBottom - 1]:= clFuchsia;
// FDynamicCollision[not FCurrentDC].Canvas.Pixels[LBBRight - 1 - CEdgeIdent, LBBBottom - 1]:= clFuchsia;
// //debugstuff
DrawRect(FBackBUffer.Canvas, LSprite.Canvas, LX, LY,
Rect(LSpriteFrame*LFrameWidth, 0, LSpriteFrame*LFrameWidth + LFrameWidth, LSprite.Height));
end;
end;
Display.Repaint();
FCurrentDC := not FCurrentDC;
Inc(FFrameCounter);
end;
end.
|
unit Services.Tour;
interface
uses
Classes,
XData.Server.Module,
XData.Service.Common,
System.Generics.Collections;
type
[ServiceContract]
ITourService = interface(IInvokable)
['{ADDC3977-6CEF-4854-9C65-CFB22FAE691D}']
[HttpGet]
function Levels : TList<string>;
[HttpGet]
function Tours( const ALevel:String ): TList<string>;
[HttpGet]
function Tour( const ALevel, AName: String ): TStream;
end;
[ServiceImplementation]
TTourService = class(TInterfacedObject, ITourService)
function Levels : TList<string>;
function Tours( const ALevel:String ): TList<string>;
function Tour( const ALevel, AName: String ): TStream;
end;
implementation
uses
Controllers.Tour;
{ TTourService }
function TTourService.Levels: TList<string>;
begin
Result := TList<string>.Create;
TTourController.GetLevels(Result);
end;
function TTourService.Tour(const ALevel, AName: String): TStream;
begin
Result := TMemoryStream.Create;
TTourController.GetTour(ALevel, AName, Result);
end;
function TTourService.Tours( const ALevel:String ): TList<string>;
begin
Result := TList<string>.Create;
TTourController.ListTours(ALevel, Result);
end;
initialization
RegisterServiceType(TypeInfo(ITourService));
RegisterServiceType(TTourService);
end.
|
unit CDPAsignacionTerceros;
interface
uses
SysUtils, Classes, DB, DBTables, Windows, Forms;
type
TDPAsignacionTerceros = class(TDataModule)
QKilosSalida: TQuery;
QEnvase: TQuery;
QAux: TQuery;
QKilosSalidaTercero: TQuery;
QKilosEntrada: TQuery;
QSalidasTerceros: TQuery;
QAuxAct: TQuery;
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
private
{ Private declarations }
sEmpresaTerceros: string;
QPrecioMedio, QAlbFacturado, QAlbDevolucion: TQuery;
function SQLPropios( const ACategoria: string ): string;
function SQLTerceros( const ACategoria: string ): string;
procedure AsignarKilos( const AEmpresa, ACentro, AProducto: string;
const AFechaIni, AFechaFin: TDateTime; const ADestino: string; const AKilos: Real );
procedure AsignarKilosxEntrada( const AEmpresa, ACentro, AProducto, ACategoria: string;
const AFechaIni, AFechaFin: TDateTime; const ADestino: string; const AKilos: Real );
function SepararKilosLinea( const ADestino: string; const AKilos: Real ): real;
procedure PreparaQuerys(const ACentro, AProducto, ACategoria: string);
function AlbaranFacturado( const AEmpresa: string; const ACentro: String; const AAlbaran: integer; AFecha: string): Boolean;
function EsDevolucion( const AEmpresa: string; const ACentro: String; const AAlbaran: integer; AFecha: string): Boolean;
procedure CalcularPrecioMedioVenta( const AEmpresa, ACentro, AProducto: String; AFechaIni, AFechaFin: TDateTime; var vPMV: currency);
function ObtenerMaxLineaAlbaran(AEmpresa, ACentro, AAlbaran, AFecha: String): integer;
procedure ActualizarSalidas ( const ACategoria, ADestino: string; AKilosParaAsignar: real);
function BuscarKilosAsignadosAlb ( const AEmpresa, ACentro, AAlbaran, AFecha, AProducto, ACategoria: string; ALinea: Integer ): real;
procedure InsertarSalidasTerceros(const QSalidas: TQuery; const ACategoria, ADestino: string; const AKilosParaAsignar: currency);
procedure BorrarTercero (const AEmpresa, ACentro, AProducto: String; const AFechaIni, AFechaFin: TDateTime);
procedure QuitarTerceroSalidas (const AEmpresa, ACentro, AProducto: String; const AFechaIni, AFechaFin: TDateTime);
function AbrirTransaccion(DB: TDataBase): boolean;
procedure AceptarTransaccion(DB: TDataBase);
procedure CancelarTransaccion(DB: TDataBase);
function SQLEntrada(const AEmpresa, ACentro, AProducto, ACosechero: string): string;
function ObtenerLineaAlbaran ( const AEmpresa, ACentro: String; const AFecha: TDateTime; const AAlbaran, AIdLinea: integer): integer;
public
{ Public declarations }
procedure AsignarKilosTerceros( const AEmpresa, ACentro, AProducto, ACategoria, ACosechero: string;
const AFechaIni, AFechaFin: TDateTime; const AKilos: Real );
procedure BorrarDatosAsignados(const AEmpresa, ACentro, AProducto: String; const AFechaIni, AFechaFin: TDateTime);
end;
var
DPAsignacionTerceros: TDPAsignacionTerceros;
implementation
{$R *.dfm}
uses Dialogs, CDAPrincipal, Math, bMath;
function TDPAsignacionTerceros.SQLPropios( const ACategoria: string ): string;
begin
result:= ' select * ';
result:= result + ' from frf_salidas_l ' + #13 + #10;
result:= result + ' where empresa_sl = :empresa ' + #13 + #10;
result:= result + ' and centro_salida_sl = :centro ' + #13 + #10;
result:= result + ' and fecha_sl between :fechaini and :fechafin ' + #13 + #10;
result:= result + ' and producto_sl = :producto ' + #13 + #10;
if ACategoria = 'D' then
begin
result:= result + ' and (categoria_sl = ''2B'' or categoria_sl = ''3B'') ' + #13 + #10;
end
else
begin
result:= result + ' and categoria_sl = ' + QuotedStr( ACategoria ) + ' ' + #13 + #10;
end;
// result:= result + ' and emp_procedencia_sl = :empresa or emp_procedencia_sl is null ' + #13 + #10;
// result := result + ' and (importe_neto_sl/kilos_sl) between :pmvdesde and :pmvhasta ' + #13 + #10;
result := result + ' and kilos_sl <> 0 ' + #13 + #10;
result:= result + ' order by fecha_sl, id_linea_albaran_sl ';
end;
function TDPAsignacionTerceros.SQLTerceros( const ACategoria: string ): string;
begin
result:= ' select * ';
result:= result + ' from frf_salidas_l ' + #13 + #10;
result:= result + ' where empresa_sl = :empresa ' + #13 + #10;
result:= result + ' and centro_salida_sl = :centro ' + #13 + #10;
result:= result + ' and fecha_sl between :fechaini and :fechafin ' + #13 + #10;
result:= result + ' and producto_sl = :producto ' + #13 + #10;
if ACategoria = 'D' then
begin
result:= result + ' and categoria_sl in (''2B'',''3B'') ' + #13 + #10;
end
else
begin
result:= result + ' and categoria_sl = ' + QuotedStr( ACategoria ) + ' ' + #13 + #10;
end;
result:= result + ' and emp_procedencia_sl = ' + QuotedStr( sEmpresaTerceros ) + ' ' + #13 + #10;
result:= result + ' order by fecha_sl desc ';
end;
function TDPAsignacionTerceros.SQLEntrada( const AEmpresa, ACentro, AProducto, ACosechero: string): string;
begin
if ((DAPrincipal.EsAgrupacionTomate(AProducto)) and (ACentro = '1')) or
((AProducto = 'CAL') and (ACentro = '1')) then
begin
result:= ' select empresa_e, centro_e, numero_entrada_e, fecha_e, cosechero_e, producto_e, ' +
' round( sum( ( porcen_primera_e * total_kgs_e2l ) / 100 ), 2) primera, ' +
' round( sum( ( porcen_segunda_e * total_kgs_e2l ) / 100 ), 2) segunda, ' +
' round( sum( ( porcen_tercera_e * total_kgs_e2l ) / 100 ), 2) tercera, ' +
' round( sum( ( porcen_destrio_e * total_kgs_e2l ) / 100 ), 2) destrio, ' +
' round( sum( ( aporcen_merma_e * total_kgs_e2l ) / 100 ), 2) merma ';
result:= result + ' from frf_entradas2_l, frf_escandallo ';
result:= result + ' where empresa_e2l = :empresa ';
result:= result + ' and centro_e2l in (:centro,6) '; //= :centro '; Se buscan compras en centro 1 - los llanos y 6 - Tenerife. Luego se asignaran ventas del centro 1
result:= result + ' and fecha_e2l between :fechaini and :fechafin ';
result:= result + ' and producto_e2l = :producto ';
if Trim(ACosechero) <> '' then
result:= result + ' and cosechero_e2l in ( ' + ACosechero + ' ) ';
result:= result + ' and empresa_e = empresa_e2l ';
result:= result + ' and centro_e = centro_e2l ';
result:= result + ' and numero_entrada_e = numero_entrada_e2l ';
result:= result + ' and fecha_e = fecha_e2l ';
result:= result + ' and producto_e = producto_e2l';
result:= result + ' and cosechero_e = cosechero_e2l ';
end;
end;
procedure TDPAsignacionTerceros.DataModuleCreate(Sender: TObject);
begin
sEmpresaTerceros:= '501';
with QEnvase do
begin
SQL.Clear;
SQL.Add( ' select peso_variable_e, peso_neto_e, unidades_e ');
SQL.Add( ' from frf_envases ');
SQL.Add( ' where envase_e = :envase ');
SQL.Add( ' and producto_e = :producto ');
//Prepare;
end;
with QSalidasTerceros do
begin
SQL.Clear;
SQL.Add(' select * ');
SQL.Add(' from frf_salidas_terceros ');
SQl.Add(' where envase_st = "" ');
end;
QSalidasTerceros.Open;
end;
procedure TDPAsignacionTerceros.DataModuleDestroy(Sender: TObject);
procedure Desprepara( var VQuery: TQuery );
begin
VQuery.Cancel;
VQuery.Close;
if VQuery.Prepared then
VQuery.UnPrepare;
end;
begin
//Desprepara( QEnvase );
QSalidasTerceros.Close;
end;
procedure TDPAsignacionTerceros.PreparaQuerys(const ACentro, AProducto, ACategoria: string);
begin
QPrecioMedio := TQuery.Create(Self);
with QPrecioMedio do
begin
DataBaseName := 'DBPrincipal';
SQL.Clear;
SQL.Add(' select sum(CASE when kilos_sl = 0 then 0 else importe_neto_sl/kilos_sl END)/count(*) precio_medio ');
SQL.Add(' from frf_salidas_l ');
SQL.Add(' where empresa_sl = :empresa ');
SQL.Add(' and centro_salida_sl = :centro ');
SQL.Add(' and fecha_sl between :fechaini and :fechafin ');
SQL.Add(' and producto_sl = :producto ');
SQL.Add(' and categoria_sl = ' + QuotedStr( ACategoria ) );
Prepare;
end;
QAlbFacturado := TQuery.Create(Self);
with QAlbFacturado do
begin
DataBaseName := 'DBPrincipal';
SQL.Clear;
SQL.Add(' select n_factura_sc from frf_salidas_c ');
SQL.Add(' where empresa_sc = :empresa ');
SQL.Add(' and centro_salida_sc = :centro ');
SQL.Add(' and n_albaran_sc = :albaran ');
SQL.Add(' and fecha_sc = :fecha ');
Prepare;
end;
QAlbDevolucion := TQuery.Create(Self);
with QAlbDevolucion do
begin
DataBaseName := 'DBPrincipal';
SQL.Clear;
SQL.Add(' select * from frf_salidas_c ');
SQL.Add(' where empresa_sc = :empresa ');
SQL.Add(' and centro_salida_sc = :centro ');
SQL.Add(' and n_albaran_sc = :albaran ');
SQL.Add(' and fecha_sc = :fecha ');
SQL.Add(' and es_transito_sc = 2 '); //Tipo Salida: Devolucion
Prepare;
end;
QKilosEntrada := TQuery.Create(Self);
if ((DAPrincipal.EsAgrupacionTomate(AProducto)) and (ACentro = '1')) or
((AProducto = 'CAL') and (ACentro = '1')) then
begin
with QKilosEntrada do
begin
DataBaseName := 'DBPrincipal';
SQL.Clear;
SQL.Add(' select empresa_e, centro_e, numero_entrada_e, fecha_e, cosechero_e, producto_e, ');
SQL.Add(' round( sum( ( porcen_primera_e * total_kgs_e2l ) / 100 ), 2) primera, ');
SQL.Add(' round( sum( ( porcen_segunda_e * total_kgs_e2l ) / 100 ), 2) segunda, ');
SQL.Add(' round( sum( ( porcen_tercera_e * total_kgs_e2l ) / 100 ), 2) tercera, ');
SQL.Add(' round( sum( ( porcen_destrio_e * total_kgs_e2l ) / 100 ), 2) destrio, ');
SQL.Add(' round( sum( ( aporcen_merma_e * total_kgs_e2l ) / 100 ), 2) merma ');
SQL.Add(' from frf_entradas2_l, frf_escandallo ');
SQL.Add(' where empresa_e2l = :empresa ');
SQL.Add(' and centro_e2l in (:centro, 6) '); //= :centro ');
SQL.Add(' and fecha_e2l between :fechaini and :fechafin ');
SQL.Add(' and producto_e2l = :producto ');
SQL.Add(' and cosechero_e2l in ( :cosechero) ');
SQL.Add(' and empresa_e = empresa_e2l ');
SQL.Add(' and centro_e = centro_e2l ');
SQL.Add(' and numero_entrada_e = numero_entrada_e2l ');
SQL.Add(' and fecha_e = fecha_e2l ');
SQL.Add(' and producto_e = producto_e2l ');
SQL.Add(' and cosechero_e = cosechero_e2l ');
SQL.Add(' group by empresa_e, centro_e, numero_entrada_e, fecha_e, cosechero_e, producto_e ');
SQL.Add(' order by empresa_e, centro_e, producto_e, fecha_e, numero_entrada_e ');
end
end
else if ACentro = '3' then
begin
with QKilosEntrada do
begin
DataBaseName := 'DBPrincipal';
SQL.Clear;
SQL.Add(' select ');
SQL.Add(' 0 primera, ');
SQL.Add(' 0 segunda, ');
SQL.Add(' round(sum(total_kgs_e2l)) tercera, ');
SQL.Add(' 0 destrio, ');
SQL.Add(' 0 merma ');
SQL.Add(' from frf_entradas2_l ');
SQL.Add(' where empresa_e2l = :empresa ');
SQL.Add(' and centro_e2l = :centro ');
SQL.Add(' and fecha_e2l between :fechaini and :fechafin ');
SQL.Add(' and producto_e2l = :producto ');
SQL.Add(' and cosechero_e2l in ( :cosechero ) ');
end;
end
else
begin
with QKilosEntrada do
begin
DataBaseName := 'DBPrincipal';
SQL.Clear;
SQL.Clear;
SQL.Add(' select ');
SQL.Add(' round(sum(total_kgs_e2l)) primera, ');
SQL.Add(' 0 segunda, ');
SQL.Add(' 0 tercera, ');
SQL.Add(' 0 destrio, ');
SQL.Add(' 0 merma ');
SQL.Add(' from frf_entradas2_l ');
SQL.Add(' where empresa_e2l = :empresa ');
SQL.Add(' and centro_e2l = :centro ');
SQL.Add(' and fecha_e2l between :fechaini and :fechafin ');
SQL.Add(' and producto_e2l = :producto ');
SQL.Add(' and cosechero_e2l in ( :cosechero ) ');
end;
end;
QKilosEntrada.Prepare;
end;
procedure TDPAsignacionTerceros.AsignarKilosTerceros( const AEmpresa, ACentro, AProducto, ACategoria, ACosechero: string;
const AFechaIni, AFechaFin: TDateTime; const AKilos: Real );
begin
PreparaQuerys(ACentro, AProducto, ACategoria);
if AKilos < 0 then
begin
QKilosSalida.SQL.Clear;
QKilosSalida.SQL.Add( SQLTerceros( ACategoria ) );
AsignarKilos( AEmpresa, ACentro, AProducto, AFechaIni, AFechaFin, AEmpresa, Abs( AKilos ) );
end
else
if AKilos > 0 then
begin
QKilosSalida.SQL.Clear;
QKilosSalida.SQL.Add( SQLPropios( ACategoria ) );
QKilosEntrada.Close;
QKilosEntrada.ParamByName('empresa').AsString := AEmpresa;
QKilosEntrada.ParamByName('centro').AsString := ACentro;
QKilosEntrada.ParamByName('fechaini').AsDateTime := AFechaIni;
QKilosEntrada.ParamByName('fechafin').AsDateTime := AFechaFin;
QKilosEntrada.ParamByName('producto').AsString := AProducto;
QKilosEntrada.ParamByName('cosechero').AsString := ACosechero;
QKilosEntrada.Open;
AsignarKilosxEntrada( AEmpresa, ACentro, AProducto, ACategoria, AFechaIni, AFechaFin, sEmpresaTerceros, AKilos );
end;
end;
procedure TDPAsignacionTerceros.CalcularPrecioMedioVenta(const AEmpresa, ACentro, AProducto: String; AFechaIni, AFechaFin: TDateTime;var vPMV: currency);
begin
with QPrecioMedio do
begin
if Active then
Close;
ParamByName('empresa').AsString := AEmpresa;
ParamByName('centro').AsString := ACentro;
ParamByName('fechaini').AsDateTime := AFechaIni;
ParamByName('fechafin').AsDateTime := AFechaFin;
ParamByName('producto').AsString := AProducto;
Open;
vPMV := FieldByName('precio_medio').AsFloat;
end;
end;
function TDPAsignacionTerceros.AlbaranFacturado(const AEmpresa, ACentro: String; const AAlbaran: integer; AFecha: string): Boolean;
begin
with QAlbFacturado do
begin
if Active then
Close;
ParamByName('empresa').AsString := AEmpresa;
ParamByName('centro').AsString := ACentro;
ParamByName('albaran').AsInteger := AAlbaran;
ParamByName('fecha').AsString := AFecha;
Open;
Result := (FieldByName('n_factura_sc').AsString <> '');
end;
end;
function TDPAsignacionTerceros.EsDevolucion(const AEmpresa, ACentro: String;
const AAlbaran: integer; AFecha: string): Boolean;
begin
with QAlbDevolucion do
begin
if Active then
Close;
ParamByName('empresa').AsString := AEmpresa;
ParamByName('centro').AsString := ACentro;
ParamByName('albaran').AsInteger := AAlbaran;
ParamByName('fecha').AsString := AFecha;
Open;
Result := not IsEmpty;
end;
end;
function TDPAsignacionTerceros.ObtenerLineaAlbaran ( const AEmpresa, ACentro: String; const AFecha:TDateTime; const AAlbaran, AIdLinea: integer): integer;
begin
with QAux do
begin
SQL.Clear;
SQL.Add(' select nvl(max(id_linea_tercero_st), 0) max_linea ');
SQL.Add(' from frf_salidas_terceros ');
SQL.Add(' where empresa_st = :empresa ');
SQL.Add(' and centro_salida_st = :centro ');
SQL.Add(' and n_albaran_st = :albaran ');
SQL.Add(' and fecha_st = :fecha ');
SQL.Add(' and id_linea_albaran_st = :id_linea ');
ParamByName('empresa').AsString := AEmpresa;
ParamByName('centro').AsString := ACentro;
ParamByName('albaran').Asinteger := AAlbaran;
ParamByName('fecha').AsDateTime := AFecha;
ParamByName('id_linea').AsInteger := AIdLinea;
Open;
result := FieldByName('max_linea').AsInteger + 1;
Close;
end;
end;
function TDPAsignacionTerceros.ObtenerMaxLineaAlbaran(AEmpresa, ACentro, AAlbaran, AFecha: String): integer;
begin
with QAux do
begin
if Active then
Close;
SQL.Clear;
SQL.Add(' select max(id_linea_albaran_sl) n_linea from frf_salidas_l ');
SQL.Add(' where empresa_sl = :empresa ');
SQL.Add(' and centro_salida_sl = :centro ');
SQL.Add(' and n_albaran_sl = :albaran ');
SQL.Add(' and fecha_sl = :fecha ');
ParamByName('empresa').AsString := AEmpresa;
ParamByName('centro').AsString := ACentro;
ParamByName('albaran').AsString := AAlbaran;
ParamByName('fecha').AsString := AFecha;
Open;
Result := FieldByName('n_linea').AsInteger;
end;
end;
procedure TDPAsignacionTerceros.AsignarKilos( const AEmpresa, ACentro, AProducto: string; const AFechaIni, AFechaFin: TDateTime; const ADestino: string; const AKilos: Real );
var
rAux, rSep: Real;
rPMV, rPMVDesde, rPMVHasta: currency;
begin
rPMV := 0;
rAux:= AKilos;
CalcularPrecioMedioVenta(AEmpresa, ACentro, AProducto, AFechaIni, AFechaFin, rPMV);
rPMVDesde := (rPMV * 70) / 100; //70% del precio medio de venta
rPMVHasta := (rPMV * 120) / 100; //120% del precio medio de venta
QKilosSalida.ParamByName('empresa').AsString:= AEmpresa;
QKilosSalida.ParamByName('centro').AsString:= ACentro;
QKilosSalida.ParamByName('producto').AsString:= AProducto;
QKilosSalida.ParamByName('fechaini').AsDateTime:= AFechaIni;
QKilosSalida.ParamByName('fechafin').AsDateTime:= AFechaFin;
QKilosSalida.ParamByName('pmvdesde').AsFloat:= rPMVDesde;
QKilosSalida.ParamByName('pmvhasta').AsFloat:= rPMVHasta;
QKilosSalida.Open;
if not QKilosSalida.IsEmpty then
begin
while rAux > 0 do
begin
if ( AlbaranFacturado(QKilosSalida.FieldByName('empresa_sl').AsString, QKilosSalida.FieldByName('centro_salida_sl').AsString,
QKilosSalida.FieldByName('n_albaran_sl').AsInteger, QKilosSalida.FieldByName('fecha_sl').AsString) ) and
( not EsDevolucion(QKilosSalida.FieldByName('empresa_sl').AsString, QKilosSalida.FieldByName('centro_salida_sl').AsString,
QKilosSalida.FieldByName('n_albaran_sl').AsInteger, QKilosSalida.FieldByName('fecha_sl').AsString) ) then
begin
if rAux >= QKilosSalida.FieldByName('kilos_sl').AsFloat then
begin
QKilosSalida.Edit;
QKilosSalida.FieldByName('emp_procedencia_sl').AsString:= ADestino;
QKilosSalida.Post;
rAux:= rAux - QKilosSalida.FieldByName('kilos_sl').AsFloat;
end
else
begin
rSep:= SepararKilosLinea( ADestino, rAux );
if rSep = 0 then
rAux := 0
else
rAux:= rAux - rSep;
end;
end;
QKilosSalida.Next;
end;
end;
QKilosSalida.Close;
end;
procedure TDPAsignacionTerceros.AsignarKilosxEntrada( const AEmpresa, ACentro, AProducto, ACategoria: string; const AFechaIni, AFechaFin: TDateTime; const ADestino: string; const AKilos: Real );
var
rKilosEntrada,
rKilosAsignadosAlb, rKilosDisponiblesAlb, rKilosParaAsignar: Real;
rPMV, rPMVDesde, rPMVHasta: currency;
dFechaAlbIni, dFechaAlbFin: TDateTime;
begin
//Recorremos las entradas del cosechero 0 para el producto y entre las fechas.
while not QKilosEntrada.Eof do
begin
dFechaAlbIni := QKilosEntrada.FieldByName('fecha_e').AsDateTime;
dFechaAlbFin := QKilosEntrada.FieldByName('fecha_e').AsDateTime + 30;
rPMV := 0;
if ACategoria = '1' then
rKilosEntrada:= QKilosEntrada.FieldByName('primera').AsFloat
else if ACategoria = '2' then
rKilosEntrada:= QKilosEntrada.FieldByName('segunda').AsFloat
else if ACategoria = '3' then
rKilosEntrada:= QKilosEntrada.FieldByName('tercera').AsFloat
else if (ACategoria = '2B') or (ACategoria = '3B') then
rKilosEntrada:= QKilosEntrada.FieldByName('destrio').AsFloat
else if ACategoria = 'B' then
rKilosEntrada:= QKilosEntrada.FieldByName('merma').AsFloat
else
rKilosEntrada:= 0;
CalcularPrecioMedioVenta(AEmpresa, ACentro, AProducto, dFechaAlbIni, dFechaAlbFin, rPMV);
rPMVDesde := (rPMV * 70) / 100; //70% del precio medio de venta
rPMVHasta := (rPMV * 120) / 100; //120% del precio medio de venta
QKilosSalida.ParamByName('empresa').AsString:= AEmpresa;
QKilosSalida.ParamByName('centro').AsString:= ACentro;
QKilosSalida.ParamByName('producto').AsString:= AProducto;
QKilosSalida.ParamByName('fechaini').AsDateTime:= dFechaAlbIni;
QKilosSalida.ParamByName('fechafin').AsDateTime:= dFechaAlbFin; //AFechaIni + 30 dias
// QKilosSalida.ParamByName('pmvdesde').AsFloat:= rPMVDesde;
// QKilosSalida.ParamByName('pmvhasta').AsFloat:= rPMVHasta;
QKilosSalida.Open;
while (not QKilosSalida.Eof) and (bRoundTo(rKilosEntrada, 2) > 0) do
begin
rKilosAsignadosAlb := BuscarKilosAsignadosAlb(QKilosSalida.FieldByName('empresa_sl').AsString, QKilosSalida.FieldByName('centro_salida_sl').AsString,
QKilosSalida.FieldByName('n_albaran_sl').AsString, QKilosSalida.FieldByName('fecha_sl').AsString,
QKilosSalida.FieldByName('producto_sl').AsString, QKilosSalida.FieldByName('categoria_sl').AsString,
QKilosSalida.FieldByName('id_linea_albaran_sl').AsInteger);
rKilosDisponiblesAlb := bRoundTo(QKilosSalida.FieldByName('kilos_sl').AsFloat - rKilosAsignadosAlb, 2);
if rKilosDisponiblesAlb > 0 then
begin
if ( AlbaranFacturado(QKilosSalida.FieldByName('empresa_sl').AsString, QKilosSalida.FieldByName('centro_salida_sl').AsString,
QKilosSalida.FieldByName('n_albaran_sl').AsInteger, QKilosSalida.FieldByName('fecha_sl').AsString) ) and
( not EsDevolucion(QKilosSalida.FieldByName('empresa_sl').AsString, QKilosSalida.FieldByName('centro_salida_sl').AsString,
QKilosSalida.FieldByName('n_albaran_sl').AsInteger, QKilosSalida.FieldByName('fecha_sl').AsString) ) then
begin
if rKilosEntrada >= rKilosDisponiblesAlb then
rKilosParaAsignar := rKilosDisponiblesAlb
else
rKilosParaAsignar := rKilosEntrada;
ActualizarSalidas(ACategoria, ADestino, rKilosParaAsignar);
rKilosEntrada := rKilosEntrada - rKilosParaAsignar;
end;
end;
QKilosSalida.Next;
end;
QKilosSalida.Close;
QKilosEntrada.Next;
end;
end;
function TDPAsignacionTerceros.AbrirTransaccion(DB: TDataBase): boolean;
var
T, Tiempo: Cardinal;
cont: integer;
flag: boolean;
begin
cont := 0;
flag := true;
while flag do
begin
//Abrimos transaccion si podemos
if DB.InTransaction then
begin
//Ya hay una transaccion abierta
inc(cont);
if cont = 3 then
begin
ShowMessage('En este momento no se puede llevar a cabo la operación seleccionada. ' + #10 + #13 + 'Por favor vuelva a intentarlo mas tarde..');
AbrirTransaccion := false;
Exit;
end;
//Esperar entre 1 y (1+cont) segundos
T := GetTickCount;
Tiempo := cont * 1000 + Random(1000);
while GetTickCount - T < Tiempo do Application.ProcessMessages;
end
else
begin
DB.StartTransaction;
flag := false;
end;
end;
AbrirTransaccion := true;
end;
procedure TDPAsignacionTerceros.AceptarTransaccion(DB: TDataBase);
begin
if DB.InTransaction then
begin
DB.Commit;
end;
end;
procedure TDPAsignacionTerceros.ActualizarSalidas ( const ACategoria, ADestino: string; AKilosParaAsignar: real);
var sAux: String;
begin
try
if not AbrirTransaccion(DAPrincipal.DBPrincipal) then
raise Exception.Create('Error al abrir transaccion en BD.');
//Actualizamos Albaran de Venta (Salidas)
QKilosSalida.Edit;
QKilosSalida.FieldByName('emp_procedencia_sl').AsString:= ADestino;
QKilosSalida.Post;
//Insertamos en frf_salidas_terceros
InsertarSalidasTerceros(QKilosSalida, ACategoria, ADestino, AKilosParaAsignar);
AceptarTransaccion(DAPrincipal.DBPrincipal);
except
on e: Exception do
begin
if DAPrincipal.DBPrincipal.InTransaction then
CancelarTransaccion(DAPrincipal.DBPrincipal);
sAux := QKilosSalida.FieldByName('empresa_sl').AsString + ' ' +
QKilosSalida.FieldByName('centro_salida_sl').AsString + ' ' +
QKilosSalida.FieldByName('fecha_sl').AsString + ' ' +
QKilosSalida.FieldByName('n_albaran_sl').AsString;
ShowMessage( 'ERROR: No se ha podido actualizar el albaran : ' + sAux + #13 + #10 + e.Message);
end;
end;
end;
function AbrirTransaccion(DB: TDataBase): Boolean;
var
T, Tiempo: Cardinal;
cont: integer;
flag: boolean;
begin
cont := 0;
flag := true;
while flag do
begin
//Abrimos transaccion si podemos
if DB.InTransaction then
begin
//Ya hay una transaccion abierta
inc(cont);
if cont = 3 then
begin
AbrirTransaccion := false;
Exit;
end;
//Esperar entre 1 y (1+cont) segundos
T := GetTickCount;
Tiempo := cont * 1000 + Random(1000);
while GetTickCount - T < Tiempo do Application.ProcessMessages;
end
else
begin
DB.StartTransaction;
flag := false;
end;
end;
AbrirTransaccion := true;
end;
procedure AceptarTransaccion(DB: TDataBase);
begin
if DB.InTransaction then
begin
DB.Commit;
end;
end;
procedure TDPAsignacionTerceros.CancelarTransaccion(DB: TDataBase);
begin
if DB.InTransaction then
begin
DB.Rollback;
end;
end;
procedure TDPAsignacionTerceros.BorrarDatosAsignados(const AEmpresa, ACentro, AProducto: String; const AFechaIni, AFechaFin: TDateTime);
var sAux: String;
begin
try
if not AbrirTransaccion(DAPrincipal.DBPrincipal) then
raise Exception.Create('Error al abrir transaccion en BD.');
BorrarTercero ( AEmpresa, ACentro, AProducto, AFechaini, AFechaFin );
QuitarTerceroSalidas ( AEmpresa, ACentro, AProducto, AFechaini, AFechaFin );
AceptarTransaccion(DAPrincipal.DBPrincipal);
except
on e: Exception do
begin
if DAPrincipal.DBPrincipal.InTransaction then
CancelarTransaccion(DAPrincipal.DBPrincipal);
sAux := QKilosSalida.FieldByName('empresa_sl').AsString + ' ' +
QKilosSalida.FieldByName('centro_salida_sl').AsString + ' ' +
QKilosSalida.FieldByName('fecha_sl').AsString + ' ' +
QKilosSalida.FieldByName('n_albaran_sl').AsString;
ShowMessage( 'ERROR: No se ha podido actualizar el albaran : ' + sAux + #13 + #10 + e.Message);
end;
end;
end;
procedure TDPAsignacionTerceros.BorrarTercero(const AEmpresa, ACentro,
AProducto: String; const AFechaIni, AFechaFin: TDateTime);
begin
with QAuxAct do
try
SQL.Clear;
SQL.Add(' delete frf_salidas_terceros ');
SQL.Add(' where empresa_st = :empresa ');
SQL.Add(' and centro_salida_st = :centro ');
SQL.Add(' and fecha_st between :fechaini and :fechafin ');
SQL.Add(' and producto_st = :producto ');
ParamByName('empresa').AsString := AEmpresa;
ParamByName('centro').AsString := ACentro;
ParamByName('fechaini').AsDateTime := AFechaIni;
ParamByName('fechafin').AsDateTime := AFechaFin;
ParamByName('producto').AsString := AProducto;
ExecSQL;
finally
Close;
end;
end;
procedure TDPAsignacionTerceros.QuitarTerceroSalidas(const AEmpresa, ACentro, AProducto: String; const AFechaIni, AFechaFin: TDateTime);
begin
with QAuxAct do
try
SQL.Clear;
SQL.Add(' update frf_salidas_l set emp_procedencia_sl = empresa_sl ');
SQL.Add(' where empresa_sl = :empresa ');
SQL.Add(' and centro_salida_sl = :centro ');
SQL.Add(' and fecha_sl between :fechaini and :fechafin ');
SQL.Add(' and producto_sl = :producto ');
SQL.Add(' and emp_procedencia_sl <> empresa_sl ');
ParamByName('empresa').AsString := AEmpresa;
ParamByName('centro').AsString := ACentro;
ParamByName('fechaini').AsDateTime := AFechaIni;
ParamByName('fechafin').AsDateTime := AFechaFin;
ParamByName('producto').AsString := AProducto;
ExecSQL;
finally
Close;
end;
end;
function TDPAsignacionTerceros.BuscarKilosAsignadosAlb ( const AEmpresa, ACentro, AAlbaran, AFecha, AProducto, ACategoria: string; ALinea: integer ): real;
begin
with QAux do
try
if Active then
Close;
SQL.Clear;
SQL.Add(' select nvl(sum(kilos_st), 0) kilos ');
SQL.Add(' from frf_salidas_terceros ');
SQL.Add(' where empresa_st = :empresa ');
SQL.Add(' and centro_salida_st = :centro ');
SQL.Add(' and n_albaran_st = :albaran ');
SQL.Add(' and fecha_st = :fecha ');
SQL.Add(' and producto_st = :producto ');
SQL.Add(' and categoria_st = :categoria ');
SQL.Add(' and id_linea_albaran_st = :idlinea ');
ParamByName('empresa').AsString := AEmpresa;
ParamByName('centro').AsString := ACentro;
ParamByName('albaran').AsString := AAlbaran;
ParamByName('fecha').AsString := AFecha;
ParamByName('producto').AsString := AProducto;
ParamByName('categoria').AsString := ACategoria;
ParamByName('idlinea').AsInteger := ALinea;
Open;
result := Fieldbyname('kilos').AsFloat;
finally
Close;
end;
end;
procedure TDPAsignacionTerceros.InsertarSalidasTerceros(const QSalidas: TQuery; const ACategoria, ADestino: string; const AKilosParaAsignar: currency);
var rPorcentaje: Real;
begin
rPorcentaje := AKilosParaAsignar / QSalidas.FieldByName('kilos_sl').AsFloat;
try
QSalidasTerceros.Insert;
QSalidasTerceros.FieldByName('empresa_st').AsString := QSalidas.FieldByName('empresa_sl').AsString;
QSalidasTerceros.FieldByName('centro_salida_st').AsString := QSalidas.FieldByName('centro_salida_sl').AsString;
QSalidasTerceros.FieldByName('n_albaran_st').AsString := QSalidas.FieldByName('n_albaran_sl').AsString;
QSalidasTerceros.FieldByName('fecha_st').AsString := QSalidas.FieldByName('fecha_sl').AsString;
QSalidasTerceros.FieldByName('id_linea_albaran_st').AsInteger := QSalidas.FieldByName('id_linea_albaran_sl').AsInteger;
QSalidasTerceros.FieldByName('producto_st').AsString := QSalidas.FieldByName('producto_sl').AsString;
QSalidasTerceros.FieldByName('envase_st').AsString := QSalidas.FieldByName('envase_sl').AsString;
QSalidasTerceros.FieldByName('categoria_st').AsString := QSalidas.FieldByName('categoria_sl').AsString;
QSalidasTerceros.FieldByName('kilos_st').AsFloat := AKilosParaAsignar;
QSalidasTerceros.FieldByName('cajas_st').Asfloat := rPorcentaje * QSalidas.FieldByName('cajas_sl').AsFloat;
QSalidasTerceros.FieldByName('importe_neto_st').AsFloat := rPorcentaje * QSalidas.FieldByName('importe_neto_sl').AsFloat;
QSalidasTerceros.FieldByName('iva_st').AsFloat := rPorcentaje * QSalidas.FieldByName('iva_sl').AsFloat;
QSalidasTerceros.FieldByName('importe_total_st').AsFloat := rPorcentaje * QSalidas.FieldByName('importe_total_sl').AsFloat;
QSalidasTerceros.FieldByName('emp_procedencia_st').AsString := ADestino;
QSalidasTerceros.FieldByName('empresa_entrada_st').AsString := QKilosEntrada.FieldByName('empresa_e').AsString;
QSalidasTerceros.FieldByName('centro_entrada_st').AsString := QKilosEntrada.FieldByName('centro_e').AsString;
QSalidasTerceros.FieldByName('numero_entrada_st').AsInteger := QKilosEntrada.FieldByName('numero_entrada_e').AsInteger;
QSalidasTerceros.FieldByName('fecha_entrada_st').AsDateTime := QKilosEntrada.FieldByName('fecha_e').AsDateTime;
QSalidasTerceros.FieldByName('id_linea_tercero_st').AsInteger := ObtenerLineaAlbaran(QSalidas.FieldByName('empresa_sl').AsString, QSalidas.FieldByName('centro_salida_sl').AsString,
QSalidas.FieldByName('fecha_sl').AsDateTime, QSalidas.FieldByName('n_albaran_sl').AsInteger, QSalidas.FieldByName('id_linea_albaran_sl').AsInteger );
QSalidasTerceros.Post;
except
raise;
end;
end;
function TDPAsignacionTerceros.SepararKilosLinea( const ADestino: string; const AKilos: Real ): real;
var
empresa_sl, centro_salida_sl, centro_origen_sl, producto_sl, envase_sl,
marca_sl, categoria_sl, calibre_sl, color_sl, unidad_precio_sl, tipo_iva_sl,
federacion_sl, cliente_sl, emp_procedencia_sl, tipo_palets_sl, comercial_sl: string;
n_albaran_sl, ref_transitos_sl, n_linea: integer;
fecha_sl: TDateTime;
precio_sl, porc_iva_sl: real;
cajas_1, n_palets_1, cajas_2, n_palets_2: integer;
kilos_1, importe_neto_1, iva_1, importe_total_1, kilos_2, importe_neto_2, iva_2, importe_total_2: real;
iUnidades: integer;
rPesoNetoCaja: real;
bPesoVariable: boolean;
rKilos: Real;
begin
(*
empresa_sl, centro_salida_sl, n_albaran_sl, fecha_sl, centro_origen_sl, producto_sl,
envase_sl, marca_sl, categoria_sl, calibre_sl, color_sl, ref_transitos_sl,
precio_sl, unidad_precio_sl, porc_iva_sl, tipo_iva_sl, federacion_sl, cliente_sl,
cajas_sl, kilos_sl, importe_neto_sl, iva_sl, importe_total_sl, n_palets_sl, emp_procedencia_sl
*)
result:= 0;
empresa_sl:= QKilosSalida.FieldByName('empresa_sl').AsString;
centro_salida_sl:= QKilosSalida.FieldByName('centro_salida_sl').AsString;
centro_origen_sl:= QKilosSalida.FieldByName('centro_origen_sl').AsString;
producto_sl:= QKilosSalida.FieldByName('producto_sl').AsString;
envase_sl:= QKilosSalida.FieldByName('envase_sl').AsString;
marca_sl:= QKilosSalida.FieldByName('marca_sl').AsString;
categoria_sl:= QKilosSalida.FieldByName('categoria_sl').AsString;
calibre_sl:= QKilosSalida.FieldByName('calibre_sl').AsString;
color_sl:= QKilosSalida.FieldByName('color_sl').AsString;
unidad_precio_sl:= QKilosSalida.FieldByName('unidad_precio_sl').AsString;
tipo_iva_sl:= QKilosSalida.FieldByName('tipo_iva_sl').AsString;
federacion_sl:= QKilosSalida.FieldByName('federacion_sl').AsString;
cliente_sl:= QKilosSalida.FieldByName('cliente_sl').AsString;
n_albaran_sl:= QKilosSalida.FieldByName('n_albaran_sl').AsInteger;
// if not QKilosSalida.FieldByName('ref_transitos_sl').IsNull then
// ref_transitos_sl:= QKilosSalida.FieldByName('ref_transitos_sl').AsInteger;
fecha_sl:= QKilosSalida.FieldByName('fecha_sl').AsDateTime;
precio_sl:= QKilosSalida.FieldByName('precio_sl').AsFloat;
porc_iva_sl:= QKilosSalida.FieldByName('porc_iva_sl').AsFloat;
emp_procedencia_sl:= QKilosSalida.FieldByName('emp_procedencia_sl').AsString;
tipo_palets_sl:= QKilosSalida.FieldByName('tipo_palets_sl').AsString;
comercial_sl:= QKilosSalida.FieldByName('comercial_sl').AsString;
QEnvase.ParamByName('envase').AsString:= QKilosSalida.FieldByName('envase_sl').AsString;
QEnvase.ParamByName('producto').AsString:= QKilosSalida.FieldByName('producto_sl').AsString;
QEnvase.Open;
if not QEnvase.IsEmpty then
begin
iUnidades:= QEnvase.FieldByName('unidades_e').AsInteger;
rPesoNetoCaja:= QEnvase.FieldByName('peso_neto_e').AsFloat;
if rPesoNetoCaja = 0 then
begin
if QKilosSalida.FieldByName('cajas_sl').AsFloat > 0 then
begin
rPesoNetoCaja:= SimpleRoundTo( QKilosSalida.FieldByName('kilos_sl').AsFloat / QKilosSalida.FieldByName('cajas_sl').AsFloat, -2 );
end
else
begin
rPesoNetoCaja:= 0;
end;
end;
bPesoVariable:= QEnvase.FieldByName('peso_variable_e').AsInteger <> 0;
end
else
begin
iUnidades:= 0;
if QKilosSalida.FieldByName('cajas_sl').AsFloat > 0 then
begin
rPesoNetoCaja:= SimpleRoundTo( QKilosSalida.FieldByName('kilos_sl').AsFloat / QKilosSalida.FieldByName('cajas_sl').AsFloat, -2 );
end
else
begin
rPesoNetoCaja:= 0;
end;
if rPesoNetoCaja = 0 then
begin
bPesoVariable:= True;
end
else
begin
bPesoVariable:= ( rPesoNetoCaja - Trunc( rPesoNetoCaja ) ) <> 0;
end;
end;
QEnvase.Close;
if not bPesoVariable then
begin
rKilos:= SimpleRoundTo( Trunc( AKilos / rPesoNetoCaja ) * rPesoNetoCaja, -2 );
end
else
begin
rKilos:= AKilos;
end;
kilos_1:= rKilos;
kilos_2:= QKilosSalida.FieldByName('kilos_sl').AsFloat - rKilos;
if rPesoNetoCaja > 0 then
begin
cajas_1:= Trunc( SimpleRoundTo( ( rKilos / rPesoNetoCaja ), 0 ) );
end
else
begin
cajas_1:= 0;
end;
cajas_2:= QKilosSalida.FieldByName('cajas_sl').AsInteger - cajas_1;
if QKilosSalida.FieldByName('kilos_sl').AsFloat > 0 then
begin
n_palets_1:= Trunc( SimpleRoundTo( ( rKilos * QKilosSalida.FieldByName('n_palets_sl').AsFloat ) / QKilosSalida.FieldByName('kilos_sl').AsFloat, 0 ) );
end
else
begin
n_palets_1:= 0;
end;
n_palets_2:= QKilosSalida.FieldByName('n_palets_sl').AsInteger - n_palets_1;
if Copy( QKilosSalida.FieldByName('unidad_precio_sl').AsString, 1, 1 ) = 'C' then
begin
importe_neto_1:= QKilosSalida.FieldByName('precio_sl').AsFloat * cajas_1;
end
else
if Copy( QKilosSalida.FieldByName('unidad_precio_sl').AsString, 1, 1 ) = 'U' then
begin
if iUnidades > 0 then
begin
importe_neto_1:= SimpleRoundTo( QKilosSalida.FieldByName('precio_sl').AsFloat * cajas_1 * iUnidades, -2 );
end
else
begin
importe_neto_1:= SimpleRoundTo( ( rKilos * QKilosSalida.FieldByName('importe_neto_sl').AsFloat ) / QKilosSalida.FieldByName('kilos_sl').AsFloat, -2 );
end;
end
else
begin
importe_neto_1:= QKilosSalida.FieldByName('precio_sl').AsFloat * kilos_1;
end;
importe_neto_1:= SimpleRoundTo( ( rKilos * QKilosSalida.FieldByName('importe_neto_sl').AsFloat ) / QKilosSalida.FieldByName('kilos_sl').AsFloat, -2 );
importe_neto_2:= QKilosSalida.FieldByName('importe_neto_sl').AsFloat - importe_neto_1;
iva_1:= SimpleRoundTo( ( importe_neto_1 * QKilosSalida.FieldByName('porc_iva_sl').AsFloat ) / 100, -2 );
iva_2:= QKilosSalida.FieldByName('iva_sl').AsFloat - iva_1;
importe_total_1:= importe_neto_1 + iva_1;
importe_total_2:= QKilosSalida.FieldByName('importe_total_sl').AsFloat - importe_total_1;
// n_linea := QKilosSalida.FieldByName('id_linea_albaran_sl').AsInteger;
n_linea := ObtenerMaxLineaAlbaran (QKilosSalida.FieldByName('empresa_sl').AsString, QKilosSalida.FieldByName('centro_salida_sl').AsString,
QKilosSalida.FieldByName('n_albaran_sl').AsString, QKilosSalida.FieldByName('fecha_sl').AsString);
if kilos_1 <> 0 then
begin
if not QKilosSalida.Database.InTransaction then
begin
QKilosSalida.Database.StartTransaction;
try
with QKilosSalida do
begin
Edit;
QKilosSalida.FieldByName('cajas_sl').AsInteger:= cajas_1;
QKilosSalida.FieldByName('n_palets_sl').AsInteger:= n_palets_1;
QKilosSalida.FieldByName('kilos_sl').AsFloat:= kilos_1;
QKilosSalida.FieldByName('importe_neto_sl').AsFloat:= importe_neto_1;
QKilosSalida.FieldByName('iva_sl').AsFloat:= iva_1;
QKilosSalida.FieldByName('importe_total_sl').AsFloat:= importe_total_1;
QKilosSalida.FieldByName('emp_procedencia_sl').AsString:= ADestino;
Post;
end;
with QKilosSalida do
begin
Insert;
QKilosSalida.FieldByName('empresa_sl').AsString:= empresa_sl;
QKilosSalida.FieldByName('centro_salida_sl').AsString:= centro_salida_sl;
QKilosSalida.FieldByName('centro_origen_sl').AsString:= centro_origen_sl;
QKilosSalida.FieldByName('producto_sl').AsString:= producto_sl;
QKilosSalida.FieldByName('envase_sl').AsString:= envase_sl;
QKilosSalida.FieldByName('marca_sl').AsString:= marca_sl;
QKilosSalida.FieldByName('categoria_sl').AsString:= categoria_sl;
QKilosSalida.FieldByName('calibre_sl').AsString:= calibre_sl;
QKilosSalida.FieldByName('color_sl').AsString:= color_sl;
QKilosSalida.FieldByName('unidad_precio_sl').AsString:= unidad_precio_sl;
QKilosSalida.FieldByName('tipo_iva_sl').AsString:= tipo_iva_sl;
QKilosSalida.FieldByName('federacion_sl').AsString:= federacion_sl;
QKilosSalida.FieldByName('cliente_sl').AsString:= cliente_sl;
QKilosSalida.FieldByName('n_albaran_sl').AsInteger:= n_albaran_sl;
// if IntToStr(ref_transitos_sl) <> '' then
// QKilosSalida.FieldByName('ref_transitos_sl').AsInteger:= ref_transitos_sl;
QKilosSalida.FieldByName('fecha_sl').AsDateTime:= fecha_sl;
QKilosSalida.FieldByName('precio_sl').AsFloat:= precio_sl;
QKilosSalida.FieldByName('porc_iva_sl').AsFloat:= porc_iva_sl;
QKilosSalida.FieldByName('cajas_sl').AsInteger:= cajas_2;
QKilosSalida.FieldByName('n_palets_sl').AsInteger:= n_palets_2;
QKilosSalida.FieldByName('kilos_sl').AsFloat:= kilos_2;
QKilosSalida.FieldByName('importe_neto_sl').AsFloat:= importe_neto_2;
QKilosSalida.FieldByName('iva_sl').AsFloat:= iva_2;
QKilosSalida.FieldByName('importe_total_sl').AsFloat:= importe_total_2;
QKilosSalida.FieldByName('emp_procedencia_sl').AsString:= emp_procedencia_sl;
QKilosSalida.FieldByName('tipo_palets_sl').AsString := tipo_palets_sl;
QKilosSalida.FieldByName('comercial_sl').AsString := comercial_sl;
QKilosSalida.FieldByName('id_linea_albaran_sl').AsInteger := n_linea + 1;
Post;
end;
QKilosSalida.Database.Commit;
result:= rKilos;
except
QKilosSalida.Database.Rollback;
ShowMessage('Error al separar lineas de salidas, por favor intentelo mas tarde.');
end;
end
else
begin
ShowMessage('En este momento no se pueden separar lineas de salidas, por favor intentelo mas tarde.');
end;
end
else
begin
ShowMessage('Kilos = 0.');
end;
end;
end.
|
//
// Generated by JavaToPas v1.5 20171018 - 171012
////////////////////////////////////////////////////////////////////////////////
unit android.service.voice.AlwaysOnHotwordDetector;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
android.content.ClipData;
type
JAlwaysOnHotwordDetector = interface;
JAlwaysOnHotwordDetectorClass = interface(JObjectClass)
['{6908C7D9-DF7A-43A2-B941-776024BD1DE1}']
function _GetRECOGNITION_FLAG_ALLOW_MULTIPLE_TRIGGERS : Integer; cdecl; // A: $19
function _GetRECOGNITION_FLAG_CAPTURE_TRIGGER_AUDIO : Integer; cdecl; // A: $19
function _GetRECOGNITION_MODE_USER_IDENTIFICATION : Integer; cdecl; // A: $19
function _GetRECOGNITION_MODE_VOICE_TRIGGER : Integer; cdecl; // A: $19
function _GetSTATE_HARDWARE_UNAVAILABLE : Integer; cdecl; // A: $19
function _GetSTATE_KEYPHRASE_ENROLLED : Integer; cdecl; // A: $19
function _GetSTATE_KEYPHRASE_UNENROLLED : Integer; cdecl; // A: $19
function _GetSTATE_KEYPHRASE_UNSUPPORTED : Integer; cdecl; // A: $19
function createEnrollIntent : JIntent; cdecl; // ()Landroid/content/Intent; A: $1
function createReEnrollIntent : JIntent; cdecl; // ()Landroid/content/Intent; A: $1
function createUnEnrollIntent : JIntent; cdecl; // ()Landroid/content/Intent; A: $1
function getSupportedRecognitionModes : Integer; cdecl; // ()I A: $1
function startRecognition(recognitionFlags : Integer) : boolean; cdecl; // (I)Z A: $1
function stopRecognition : boolean; cdecl; // ()Z A: $1
property RECOGNITION_FLAG_ALLOW_MULTIPLE_TRIGGERS : Integer read _GetRECOGNITION_FLAG_ALLOW_MULTIPLE_TRIGGERS;// I A: $19
property RECOGNITION_FLAG_CAPTURE_TRIGGER_AUDIO : Integer read _GetRECOGNITION_FLAG_CAPTURE_TRIGGER_AUDIO;// I A: $19
property RECOGNITION_MODE_USER_IDENTIFICATION : Integer read _GetRECOGNITION_MODE_USER_IDENTIFICATION;// I A: $19
property RECOGNITION_MODE_VOICE_TRIGGER : Integer read _GetRECOGNITION_MODE_VOICE_TRIGGER;// I A: $19
property STATE_HARDWARE_UNAVAILABLE : Integer read _GetSTATE_HARDWARE_UNAVAILABLE;// I A: $19
property STATE_KEYPHRASE_ENROLLED : Integer read _GetSTATE_KEYPHRASE_ENROLLED;// I A: $19
property STATE_KEYPHRASE_UNENROLLED : Integer read _GetSTATE_KEYPHRASE_UNENROLLED;// I A: $19
property STATE_KEYPHRASE_UNSUPPORTED : Integer read _GetSTATE_KEYPHRASE_UNSUPPORTED;// I A: $19
end;
[JavaSignature('android/service/voice/AlwaysOnHotwordDetector$Callback')]
JAlwaysOnHotwordDetector = interface(JObject)
['{DD81BCAE-A6C5-42D6-8CC9-0723B124BDC5}']
function createEnrollIntent : JIntent; cdecl; // ()Landroid/content/Intent; A: $1
function createReEnrollIntent : JIntent; cdecl; // ()Landroid/content/Intent; A: $1
function createUnEnrollIntent : JIntent; cdecl; // ()Landroid/content/Intent; A: $1
function getSupportedRecognitionModes : Integer; cdecl; // ()I A: $1
function startRecognition(recognitionFlags : Integer) : boolean; cdecl; // (I)Z A: $1
function stopRecognition : boolean; cdecl; // ()Z A: $1
end;
TJAlwaysOnHotwordDetector = class(TJavaGenericImport<JAlwaysOnHotwordDetectorClass, JAlwaysOnHotwordDetector>)
end;
const
TJAlwaysOnHotwordDetectorRECOGNITION_FLAG_ALLOW_MULTIPLE_TRIGGERS = 2;
TJAlwaysOnHotwordDetectorRECOGNITION_FLAG_CAPTURE_TRIGGER_AUDIO = 1;
TJAlwaysOnHotwordDetectorRECOGNITION_MODE_USER_IDENTIFICATION = 2;
TJAlwaysOnHotwordDetectorRECOGNITION_MODE_VOICE_TRIGGER = 1;
TJAlwaysOnHotwordDetectorSTATE_HARDWARE_UNAVAILABLE = -2;
TJAlwaysOnHotwordDetectorSTATE_KEYPHRASE_ENROLLED = 2;
TJAlwaysOnHotwordDetectorSTATE_KEYPHRASE_UNENROLLED = 1;
TJAlwaysOnHotwordDetectorSTATE_KEYPHRASE_UNSUPPORTED = -1;
implementation
end.
|
unit winCrypt;
interface
uses Windows;
const
// Algorithm classes
ALG_CLASS_ANY = (0);
ALG_CLASS_SIGNATURE = (1 shl 13);
ALG_CLASS_MSG_ENCRYPT = (2 shl 13);
ALG_CLASS_DATA_ENCRYPT = (3 shl 13);
ALG_CLASS_HASH = (4 shl 13);
ALG_CLASS_KEY_EXCHANGE = (5 shl 13);
ALG_CLASS_ALL = (7 shl 13);
// Algorithm types
ALG_TYPE_ANY = (0);
ALG_TYPE_DSS = (1 shl 9);
ALG_TYPE_RSA = (2 shl 9);
ALG_TYPE_BLOCK = (3 shl 9);
ALG_TYPE_STREAM = (4 shl 9);
ALG_TYPE_DH = (5 shl 9);
ALG_TYPE_SECURECHANNEL = (6 shl 9);
// Generic sub-ids
ALG_SID_ANY = (0);
// Some RSA sub-ids
ALG_SID_RSA_ANY = 0;
ALG_SID_RSA_PKCS = 1;
ALG_SID_RSA_MSATWORK = 2;
ALG_SID_RSA_ENTRUST = 3;
ALG_SID_RSA_PGP = 4;
// Some DSS sub-ids
//
ALG_SID_DSS_ANY = 0;
ALG_SID_DSS_PKCS = 1;
ALG_SID_DSS_DMS = 2;
// Block cipher sub ids
// DES sub_ids
ALG_SID_DES = 1;
ALG_SID_3DES = 3;
ALG_SID_DESX = 4;
ALG_SID_IDEA = 5;
ALG_SID_CAST = 6;
ALG_SID_SAFERSK64 = 7;
ALG_SID_SAFERSK128 = 8;
ALG_SID_3DES_112 = 9;
ALG_SID_CYLINK_MEK = 12;
ALG_SID_RC5 = 13;
ALG_SID_AES_128 = 14;
ALG_SID_AES_192 = 15;
ALG_SID_AES_256 = 16;
ALG_SID_AES = 17;
// Fortezza sub-ids
ALG_SID_SKIPJACK = 10;
ALG_SID_TEK = 11;
// KP_MODE
CRYPT_MODE_CBCI = 6; // ANSI CBC Interleaved
CRYPT_MODE_CFBP = 7; // ANSI CFB Pipelined
CRYPT_MODE_OFBP = 8; // ANSI OFB Pipelined
CRYPT_MODE_CBCOFM = 9; // ANSI CBC + OF Masking
CRYPT_MODE_CBCOFMI = 10; // ANSI CBC + OFM Interleaved
// RC2 sub-ids
ALG_SID_RC2 = 2;
// Stream cipher sub-ids
ALG_SID_RC4 = 1;
ALG_SID_SEAL = 2;
// Diffie-Hellman sub-ids
ALG_SID_DH_SANDF = 1;
ALG_SID_DH_EPHEM = 2;
ALG_SID_AGREED_KEY_ANY = 3;
ALG_SID_KEA = 4;
// Hash sub ids
ALG_SID_MD2 = 1;
ALG_SID_MD4 = 2;
ALG_SID_MD5 = 3;
ALG_SID_SHA = 4;
ALG_SID_SHA1 = 4;
ALG_SID_MAC = 5;
ALG_SID_RIPEMD = 6;
ALG_SID_RIPEMD160 = 7;
ALG_SID_SSL3SHAMD5 = 8;
ALG_SID_HMAC = 9;
ALG_SID_TLS1PRF = 10;
ALG_SID_HASH_REPLACE_OWF = 11;
// secure channel sub ids
ALG_SID_SSL3_MASTER = 1;
ALG_SID_SCHANNEL_MASTER_HASH = 2;
ALG_SID_SCHANNEL_MAC_KEY = 3;
ALG_SID_PCT1_MASTER = 4;
ALG_SID_SSL2_MASTER = 5;
ALG_SID_TLS1_MASTER = 6;
ALG_SID_SCHANNEL_ENC_KEY = 7;
// Our silly example sub-id
ALG_SID_EXAMPLE = 80;
// algorithm identifier definitions
CALG_MD2 = (ALG_CLASS_HASH or ALG_TYPE_ANY or ALG_SID_MD2);
CALG_MD4 = (ALG_CLASS_HASH or ALG_TYPE_ANY or ALG_SID_MD4);
CALG_MD5 = (ALG_CLASS_HASH or ALG_TYPE_ANY or ALG_SID_MD5);
CALG_SHA = (ALG_CLASS_HASH or ALG_TYPE_ANY or ALG_SID_SHA);
CALG_SHA1 = (ALG_CLASS_HASH or ALG_TYPE_ANY or ALG_SID_SHA1);
CALG_MAC = (ALG_CLASS_HASH or ALG_TYPE_ANY or ALG_SID_MAC);
CALG_RSA_SIGN = (ALG_CLASS_SIGNATURE or ALG_TYPE_RSA or ALG_SID_RSA_ANY);
CALG_DSS_SIGN = (ALG_CLASS_SIGNATURE or ALG_TYPE_DSS or ALG_SID_DSS_ANY);
CALG_NO_SIGN = (ALG_CLASS_SIGNATURE or ALG_TYPE_ANY or ALG_SID_ANY);
CALG_RSA_KEYX = (ALG_CLASS_KEY_EXCHANGE or ALG_TYPE_RSA or ALG_SID_RSA_ANY);
CALG_DES = (ALG_CLASS_DATA_ENCRYPT or ALG_TYPE_BLOCK or ALG_SID_DES);
CALG_3DES_112 = (ALG_CLASS_DATA_ENCRYPT or ALG_TYPE_BLOCK or ALG_SID_3DES_112);
CALG_3DES = (ALG_CLASS_DATA_ENCRYPT or ALG_TYPE_BLOCK or ALG_SID_3DES);
CALG_DESX = (ALG_CLASS_DATA_ENCRYPT or ALG_TYPE_BLOCK or ALG_SID_DESX);
CALG_RC2 = (ALG_CLASS_DATA_ENCRYPT or ALG_TYPE_BLOCK or ALG_SID_RC2);
CALG_RC4 = (ALG_CLASS_DATA_ENCRYPT or ALG_TYPE_STREAM or ALG_SID_RC4);
CALG_SEAL = (ALG_CLASS_DATA_ENCRYPT or ALG_TYPE_STREAM or ALG_SID_SEAL);
CALG_DH_SF = (ALG_CLASS_KEY_EXCHANGE or ALG_TYPE_DH or ALG_SID_DH_SANDF);
CALG_DH_EPHEM = (ALG_CLASS_KEY_EXCHANGE or ALG_TYPE_DH or ALG_SID_DH_EPHEM);
CALG_AGREEDKEY_ANY = (ALG_CLASS_KEY_EXCHANGE or ALG_TYPE_DH or ALG_SID_AGREED_KEY_ANY);
CALG_KEA_KEYX = (ALG_CLASS_KEY_EXCHANGE or ALG_TYPE_DH or ALG_SID_KEA);
CALG_HUGHES_MD5 = (ALG_CLASS_KEY_EXCHANGE or ALG_TYPE_ANY or ALG_SID_MD5);
CALG_SKIPJACK = (ALG_CLASS_DATA_ENCRYPT or ALG_TYPE_BLOCK or ALG_SID_SKIPJACK);
CALG_TEK = (ALG_CLASS_DATA_ENCRYPT or ALG_TYPE_BLOCK or ALG_SID_TEK);
CALG_CYLINK_MEK = (ALG_CLASS_DATA_ENCRYPT or ALG_TYPE_BLOCK or ALG_SID_CYLINK_MEK);
CALG_SSL3_SHAMD5 = (ALG_CLASS_HASH or ALG_TYPE_ANY or ALG_SID_SSL3SHAMD5);
CALG_SSL3_MASTER = (ALG_CLASS_MSG_ENCRYPT or ALG_TYPE_SECURECHANNEL or ALG_SID_SSL3_MASTER);
CALG_SCHANNEL_MASTER_HASH = (ALG_CLASS_MSG_ENCRYPT or ALG_TYPE_SECURECHANNEL or ALG_SID_SCHANNEL_MASTER_HASH);
CALG_SCHANNEL_MAC_KEY = (ALG_CLASS_MSG_ENCRYPT or ALG_TYPE_SECURECHANNEL or ALG_SID_SCHANNEL_MAC_KEY);
CALG_SCHANNEL_ENC_KEY = (ALG_CLASS_MSG_ENCRYPT or ALG_TYPE_SECURECHANNEL or ALG_SID_SCHANNEL_ENC_KEY);
CALG_PCT1_MASTER = (ALG_CLASS_MSG_ENCRYPT or ALG_TYPE_SECURECHANNEL or ALG_SID_PCT1_MASTER);
CALG_SSL2_MASTER = (ALG_CLASS_MSG_ENCRYPT or ALG_TYPE_SECURECHANNEL or ALG_SID_SSL2_MASTER);
CALG_TLS1_MASTER = (ALG_CLASS_MSG_ENCRYPT or ALG_TYPE_SECURECHANNEL or ALG_SID_TLS1_MASTER);
CALG_RC5 = (ALG_CLASS_DATA_ENCRYPT or ALG_TYPE_BLOCK or ALG_SID_RC5);
CALG_HMAC = (ALG_CLASS_HASH or ALG_TYPE_ANY or ALG_SID_HMAC);
CALG_TLS1PRF = (ALG_CLASS_HASH or ALG_TYPE_ANY or ALG_SID_TLS1PRF);
CALG_HASH_REPLACE_OWF = (ALG_CLASS_HASH or ALG_TYPE_ANY or ALG_SID_HASH_REPLACE_OWF);
CALG_AES_128 = (ALG_CLASS_DATA_ENCRYPT or ALG_TYPE_BLOCK or ALG_SID_AES_128);
CALG_AES_192 = (ALG_CLASS_DATA_ENCRYPT or ALG_TYPE_BLOCK or ALG_SID_AES_192);
CALG_AES_256 = (ALG_CLASS_DATA_ENCRYPT or ALG_TYPE_BLOCK or ALG_SID_AES_256);
CALG_AES = (ALG_CLASS_DATA_ENCRYPT or ALG_TYPE_BLOCK or ALG_SID_AES);
PROV_RSA_FULL = 1;
PROV_RSA_SIG = 2;
PROV_DSS = 3;
PROV_FORTEZZA = 4;
PROV_MS_EXCHANGE = 5;
PROV_SSL = 6;
PROV_RSA_SCHANNEL = 12;
PROV_DSS_DH = 13;
PROV_EC_ECDSA_SIG = 14;
PROV_EC_ECNRA_SIG = 15;
PROV_EC_ECDSA_FULL = 16;
PROV_EC_ECNRA_FULL = 17;
PROV_DH_SCHANNEL = 18;
PROV_SPYRUS_LYNKS = 20;
PROV_RNG = 21;
PROV_INTEL_SEC = 22;
PROV_REPLACE_OWF = 23;
PROV_RSA_AES = 24;
CRYPT_EXPORTABLE = $00000001;
CRYPT_USER_PROTECTED = $00000002;
CRYPT_CREATE_SALT = $00000004;
CRYPT_UPDATE_KEY = $00000008;
CRYPT_NO_SALT = $00000010;
CRYPT_PREGEN = $00000040;
CRYPT_RECIPIENT = $00000010;
CRYPT_INITIATOR = $00000040;
CRYPT_ONLINE = $00000080;
CRYPT_SF = $00000100;
CRYPT_CREATE_IV = $00000200;
CRYPT_KEK = $00000400;
CRYPT_DATA_KEY = $00000800;
CRYPT_VOLATILE = $00001000;
CRYPT_SGCKEY = $00002000;
CRYPT_ARCHIVABLE = $00004000;
RSA1024BIT_KEY = $04000000;
// dwFlags definitions for CryptDeriveKey
CRYPT_SERVER = $00000400;
KEY_LENGTH_MASK = $FFFF0000;
// dwFlag definitions for CryptExportKey
CRYPT_Y_ONLY = $00000001;
CRYPT_SSL2_FALLBACK = $00000002;
CRYPT_DESTROYKEY = $00000004;
CRYPT_OAEP = $00000040; // used with RSA encryptions/decryptions
// CryptExportKey, CryptImportKey,
// CryptEncrypt and CryptDecrypt
CRYPT_BLOB_VER3 = $00000080; // export version 3 of a blob type
CRYPT_IPSEC_HMAC_KEY = $00000100; // CryptImportKey only
// dwFlags definitions for CryptCreateHash
CRYPT_SECRETDIGEST = $00000001;
// dwFlags definitions for CryptHashData
CRYPT_OWF_REPL_LM_HASH = $00000001; // this is only for the OWF replacement CSP
// dwFlags definitions for CryptHashSessionKey
CRYPT_LITTLE_ENDIAN = $00000001;
// dwFlags definitions for CryptSignHash and CryptVerifySignature
CRYPT_NOHASHOID = $00000001;
CRYPT_TYPE2_FORMAT = $00000002;
CRYPT_X931_FORMAT = $00000004;
// dwFlag definitions for CryptSetProviderEx and CryptGetDefaultProvider
CRYPT_MACHINE_DEFAULT = $00000001;
CRYPT_USER_DEFAULT = $00000002;
CRYPT_DELETE_DEFAULT = $00000004;
// dwFlag definitions for CryptAcquireContext
CRYPT_NEWKEYSET = $00000008;
CRYPT_DELETEKEYSET = $00000010;
CRYPT_MACHINE_KEYSET = $00000020;
CRYPT_VERIFYCONTEXT = $F0000000;
MS_DEF_PROV = 'Microsoft Base Cryptographic Provider v1.0';
MS_ENHANCED_PROV = 'Microsoft Enhanced Cryptographic Provider v1.0';
MS_STRONG_PROV = 'Microsoft Strong Cryptographic Provider';
MS_DEF_RSA_SIG_PROV = 'Microsoft RSA Signature Cryptographic Provider';
MS_DEF_RSA_SCHANNEL_PROV = 'Microsoft RSA SChannel Cryptographic Provider';
MS_DEF_DSS_PROV = 'Microsoft Base DSS Cryptographic Provider';
MS_DEF_DSS_DH_PROV = 'Microsoft Base DSS and Diffie-Hellman Cryptographic Provider';
MS_ENH_DSS_DH_PROV = 'Microsoft Enhanced DSS and Diffie-Hellman Cryptographic Provider';
MS_DEF_DH_SCHANNEL_PROV = 'Microsoft DH SChannel Cryptographic Provider';
MS_SCARD_PROV = 'Microsoft Base Smart Card Crypto Provider';
//
// CryptGetProvParam
//
PP_ENUMALGS = 1;
PP_ENUMCONTAINERS = 2;
PP_IMPTYPE = 3;
PP_NAME = 4;
PP_VERSION = 5;
PP_CONTAINER = 6;
PP_CHANGE_PASSWORD = 7;
PP_KEYSET_SEC_DESCR = 8; // get/set security descriptor of keyset
PP_CERTCHAIN = 9; // for retrieving certificates from tokens
PP_KEY_TYPE_SUBTYPE = 10;
PP_PROVTYPE = 16;
PP_KEYSTORAGE = 17;
PP_APPLI_CERT = 18;
PP_SYM_KEYSIZE = 19;
PP_SESSION_KEYSIZE = 20;
PP_UI_PROMPT = 21;
PP_ENUMALGS_EX = 22;
PP_ENUMMANDROOTS = 25;
PP_ENUMELECTROOTS = 26;
PP_KEYSET_TYPE = 27;
PP_ADMIN_PIN = 31;
PP_KEYEXCHANGE_PIN = 32;
PP_SIGNATURE_PIN = 33;
PP_SIG_KEYSIZE_INC = 34;
PP_KEYX_KEYSIZE_INC = 35;
PP_UNIQUE_CONTAINER = 36;
PP_SGC_INFO = 37;
PP_USE_HARDWARE_RNG = 38;
PP_KEYSPEC = 39;
PP_ENUMEX_SIGNING_PROT = 40;
CRYPT_FIRST = 1;
CRYPT_NEXT = 2;
CRYPT_SGC_ENUM = 4;
CRYPT_IMPL_HARDWARE = 1;
CRYPT_IMPL_SOFTWARE = 2;
CRYPT_IMPL_MIXED = 3;
CRYPT_IMPL_UNKNOWN = 4;
CRYPT_IMPL_REMOVABLE = 8;
HP_HASHVAL = 2;
HP_HASHSIZE = 4;
type
HCRYPTPROV = THandle;
HCRYPTKEY = THandle;
HCRYPTHASH = THandle;
ALG_ID = LongWord;
TEnumAlgs = packed record
algID : ALG_ID;
dwBits : DWORD;
dwNameLen : DWORD;
szName : array [0..0] of AnsiChar;
end;
PEnumAlgs = ^TEnumAlgs;
TCryptoAPIBlob = record
cbData : DWORD;
pbData : PBYTE
end;
PCryptoAPIBlob = ^TCryptoAPIBlob;
TCryptIntegerBlob = TCryptoAPIBlob; PCryptIntegerBlob = ^TCryptIntegerBlob;
TCryptUINTBlob = TCryptoAPIBlob; PCryptUINTBlob = ^TCryptUINTBlob;
TCryptOBJIDBlob = TCryptoAPIBlob; PCryptOBJIDBlob = ^TCryptOBJIDBlob;
TCertNameBlob = TCryptoAPIBlob; PCertNameBlob = ^TCertNameBlob;
TCertRDNValueBlob = TCryptoAPIBlob; PCertRDNValueBlob = ^TCertRDNValueBlob;
TCertBlob = TCryptoAPIBlob; PCertBlob = ^TCertBlob;
TCRLBlob = TCryptoAPIBlob; PCRLBlob = ^TCRLBlob;
TDataBlob = TCryptoAPIBlob; PDataBlob = ^TDataBlob;
TCryptDataBlob = TCryptoAPIBlob; PCryptDataBlob = ^TCryptDataBlob;
TCryptHashBlob = TCryptoAPIBlob; PCryptHashBlob = ^TCryptHashBlob;
TCryptDigestBlob = TCryptoAPIBlob; PCryptDigestBlob = ^TCryptDigestBlob;
TCryptDerBlob = TCryptoAPIBlob; PCryptDerBlob = ^TCryptDerBlob;
TCryptAttrBlob = TCryptoAPIBlob; PCryptAttrBlob = ^TCryptAttrBlob;
//+-------------------------------------------------------------------------
// Cryptographic Key Provider Information
//
// CRYPT_KEY_PROV_INFO defines the CERT_KEY_PROV_INFO_PROP_ID's pvData.
//
// The CRYPT_KEY_PROV_INFO fields are passed to CryptAcquireContext
// to get a HCRYPTPROV handle. The optional CRYPT_KEY_PROV_PARAM fields are
// passed to CryptSetProvParam to further initialize the provider.
//
// The dwKeySpec field identifies the private key to use from the container
// For example, AT_KEYEXCHANGE or AT_SIGNATURE.
//--------------------------------------------------------------------------
TCryptKeyProvParam = record
dwParam : DWORD;
pbData : PBYTE;
cbData : DWORD;
dwFlags : DWORD
end;
PCryptKeyProvParam = ^TCryptKeyProvParam;
TCryptKeyProvInfo = record
pwszContainerName : PWideChar;
pwszProvName : PWideChar;
dwProvType : DWORD;
dwFlags : DWORD;
cProvParam : DWORD;
rgProvParam : PCryptKeyProvParam;
dwKeySpec : DWORD
end;
PCryptKeyProvInfo = ^TCryptKeyProvInfo;
TCryptAlgorithmIdentifier = record
pszObjId : PAnsiChar;
Parameters : TCryptObjIDBlob
end;
PCryptAlgorithmIdentifier = ^TCryptAlgorithmIdentifier;
// Following are the definitions of various algorithm object identifiers
// RSA
const
szOID_RSA = '1.2.840.113549';
szOID_PKCS = '1.2.840.113549.1';
szOID_RSA_HASH = '1.2.840.113549.2';
szOID_RSA_ENCRYPT = '1.2.840.113549.3';
szOID_PKCS_1 = '1.2.840.113549.1.1';
szOID_PKCS_2 = '1.2.840.113549.1.2';
szOID_PKCS_3 = '1.2.840.113549.1.3';
szOID_PKCS_4 = '1.2.840.113549.1.4';
szOID_PKCS_5 = '1.2.840.113549.1.5';
szOID_PKCS_6 = '1.2.840.113549.1.6';
szOID_PKCS_7 = '1.2.840.113549.1.7';
szOID_PKCS_8 = '1.2.840.113549.1.8';
szOID_PKCS_9 = '1.2.840.113549.1.9';
szOID_PKCS_10 = '1.2.840.113549.1.10';
szOID_PKCS_12 = '1.2.840.113549.1.12';
szOID_RSA_RSA = '1.2.840.113549.1.1.1';
szOID_RSA_MD2RSA = '1.2.840.113549.1.1.2';
szOID_RSA_MD4RSA = '1.2.840.113549.1.1.3';
szOID_RSA_MD5RSA = '1.2.840.113549.1.1.4';
szOID_RSA_SHA1RSA = '1.2.840.113549.1.1.5';
szOID_RSA_SETOAEP_RSA = '1.2.840.113549.1.1.6';
szOID_RSA_DH = '1.2.840.113549.1.3.1';
szOID_RSA_data = '1.2.840.113549.1.7.1';
szOID_RSA_signedData = '1.2.840.113549.1.7.2';
szOID_RSA_envelopedData = '1.2.840.113549.1.7.3';
szOID_RSA_signEnvData = '1.2.840.113549.1.7.4';
szOID_RSA_digestedData = '1.2.840.113549.1.7.5';
szOID_RSA_hashedData = '1.2.840.113549.1.7.5';
szOID_RSA_encryptedData = '1.2.840.113549.1.7.6';
szOID_RSA_emailAddr = '1.2.840.113549.1.9.1';
szOID_RSA_unstructName = '1.2.840.113549.1.9.2';
szOID_RSA_contentType = '1.2.840.113549.1.9.3';
szOID_RSA_messageDigest = '1.2.840.113549.1.9.4';
szOID_RSA_signingTime = '1.2.840.113549.1.9.5';
szOID_RSA_counterSign = '1.2.840.113549.1.9.6';
szOID_RSA_challengePwd = '1.2.840.113549.1.9.7';
szOID_RSA_unstructAddr = '1.2.840.113549.1.9.8';
szOID_RSA_extCertAttrs = '1.2.840.113549.1.9.9';
szOID_RSA_certExtensions = '1.2.840.113549.1.9.14';
szOID_RSA_SMIMECapabilities = '1.2.840.113549.1.9.15';
szOID_RSA_preferSignedData = '1.2.840.113549.1.9.15.1';
szOID_RSA_SMIMEalg = '1.2.840.113549.1.9.16.3';
szOID_RSA_SMIMEalgESDH = '1.2.840.113549.1.9.16.3.5';
szOID_RSA_SMIMEalgCMS3DESwrap = '1.2.840.113549.1.9.16.3.6';
szOID_RSA_SMIMEalgCMSRC2wrap = '1.2.840.113549.1.9.16.3.7';
szOID_RSA_MD2 = '1.2.840.113549.2.2';
szOID_RSA_MD4 = '1.2.840.113549.2.4';
szOID_RSA_MD5 = '1.2.840.113549.2.5';
szOID_RSA_RC2CBC = '1.2.840.113549.3.2';
szOID_RSA_RC4 = '1.2.840.113549.3.4';
szOID_RSA_DES_EDE3_CBC = '1.2.840.113549.3.7';
szOID_RSA_RC5_CBCPad = '1.2.840.113549.3.9';
szOID_ANSI_X942 = '1.2.840.10046';
szOID_ANSI_X942_DH = '1.2.840.10046.2.1';
szOID_X957 = '1.2.840.10040';
szOID_X957_DSA = '1.2.840.10040.4.1';
szOID_X957_SHA1DSA = '1.2.840.10040.4.3';
// ITU-T UsefulDefinitions
szOID_DS = '2.5';
szOID_DSALG = '2.5.8';
szOID_DSALG_CRPT = '2.5.8.1';
szOID_DSALG_HASH = '2.5.8.2';
szOID_DSALG_SIGN = '2.5.8.3';
szOID_DSALG_RSA = '2.5.8.1.1';
// NIST OSE Implementors' Workshop (OIW)
// http://nemo.ncsl.nist.gov/oiw/agreements/stable/OSI/12s_9506.w51
// http://nemo.ncsl.nist.gov/oiw/agreements/working/OSI/12w_9503.w51
szOID_OIW = '1.3.14';
// NIST OSE Implementors' Workshop (OIW) Security SIG algorithm identifiers
szOID_OIWSEC = '1.3.14.3.2';
szOID_OIWSEC_md4RSA = '1.3.14.3.2.2';
szOID_OIWSEC_md5RSA = '1.3.14.3.2.3';
szOID_OIWSEC_md4RSA2 = '1.3.14.3.2.4';
szOID_OIWSEC_desECB = '1.3.14.3.2.6';
szOID_OIWSEC_desCBC = '1.3.14.3.2.7';
szOID_OIWSEC_desOFB = '1.3.14.3.2.8';
szOID_OIWSEC_desCFB = '1.3.14.3.2.9';
szOID_OIWSEC_desMAC = '1.3.14.3.2.10';
szOID_OIWSEC_rsaSign = '1.3.14.3.2.11';
szOID_OIWSEC_dsa = '1.3.14.3.2.12';
szOID_OIWSEC_shaDSA = '1.3.14.3.2.13';
szOID_OIWSEC_mdc2RSA = '1.3.14.3.2.14';
szOID_OIWSEC_shaRSA = '1.3.14.3.2.15';
szOID_OIWSEC_dhCommMod = '1.3.14.3.2.16';
szOID_OIWSEC_desEDE = '1.3.14.3.2.17';
szOID_OIWSEC_sha = '1.3.14.3.2.18';
szOID_OIWSEC_mdc2 = '1.3.14.3.2.19';
szOID_OIWSEC_dsaComm = '1.3.14.3.2.20';
szOID_OIWSEC_dsaCommSHA = '1.3.14.3.2.21';
szOID_OIWSEC_rsaXchg = '1.3.14.3.2.22';
szOID_OIWSEC_keyHashSeal = '1.3.14.3.2.23';
szOID_OIWSEC_md2RSASign = '1.3.14.3.2.24';
szOID_OIWSEC_md5RSASign = '1.3.14.3.2.25';
szOID_OIWSEC_sha1 = '1.3.14.3.2.26';
szOID_OIWSEC_dsaSHA1 = '1.3.14.3.2.27';
szOID_OIWSEC_dsaCommSHA1 = '1.3.14.3.2.28';
szOID_OIWSEC_sha1RSASign = '1.3.14.3.2.29';
// NIST OSE Implementors' Workshop (OIW) Directory SIG algorithm identifiers
szOID_OIWDIR = '1.3.14.7.2';
szOID_OIWDIR_CRPT = '1.3.14.7.2.1';
szOID_OIWDIR_HASH = '1.3.14.7.2.2';
szOID_OIWDIR_SIGN = '1.3.14.7.2.3';
szOID_OIWDIR_md2 = '1.3.14.7.2.2.1';
szOID_OIWDIR_md2RSA = '1.3.14.7.2.3.1';
// INFOSEC Algorithms
// joint-iso-ccitt(2) country(16) us(840) organization(1) us-government(101) dod(2) id-infosec(1)
szOID_INFOSEC = '2.16.840.1.101.2.1';
szOID_INFOSEC_sdnsSignature = '2.16.840.1.101.2.1.1.1';
szOID_INFOSEC_mosaicSignature = '2.16.840.1.101.2.1.1.2';
szOID_INFOSEC_sdnsConfidentiality = '2.16.840.1.101.2.1.1.3';
szOID_INFOSEC_mosaicConfidentiality = '2.16.840.1.101.2.1.1.4';
szOID_INFOSEC_sdnsIntegrity = '2.16.840.1.101.2.1.1.5';
szOID_INFOSEC_mosaicIntegrity = '2.16.840.1.101.2.1.1.6';
szOID_INFOSEC_sdnsTokenProtection = '2.16.840.1.101.2.1.1.7';
szOID_INFOSEC_mosaicTokenProtection = '2.16.840.1.101.2.1.1.8';
szOID_INFOSEC_sdnsKeyManagement = '2.16.840.1.101.2.1.1.9';
szOID_INFOSEC_mosaicKeyManagement = '2.16.840.1.101.2.1.1.10';
szOID_INFOSEC_sdnsKMandSig = '2.16.840.1.101.2.1.1.11';
szOID_INFOSEC_mosaicKMandSig = '2.16.840.1.101.2.1.1.12';
szOID_INFOSEC_SuiteASignature = '2.16.840.1.101.2.1.1.13';
szOID_INFOSEC_SuiteAConfidentiality = '2.16.840.1.101.2.1.1.14';
szOID_INFOSEC_SuiteAIntegrity = '2.16.840.1.101.2.1.1.15';
szOID_INFOSEC_SuiteATokenProtection = '2.16.840.1.101.2.1.1.16';
szOID_INFOSEC_SuiteAKeyManagement = '2.16.840.1.101.2.1.1.17';
szOID_INFOSEC_SuiteAKMandSig = '2.16.840.1.101.2.1.1.18';
szOID_INFOSEC_mosaicUpdatedSig = '2.16.840.1.101.2.1.1.19';
szOID_INFOSEC_mosaicKMandUpdSig = '2.16.840.1.101.2.1.1.20';
szOID_INFOSEC_mosaicUpdatedInteg = '2.16.840.1.101.2.1.1.21';
type
//+-------------------------------------------------------------------------
// Type used for an extension to an encoded content
//
// Where the Value's CRYPT_OBJID_BLOB is in its encoded representation.
//--------------------------------------------------------------------------
TCertExtension = record
pszObjId : PAnsiChar;
fCritical : BOOL;
Value : TCryptObjIDBlob
end;
PCertExtension = ^TCertExtension;
//+-------------------------------------------------------------------------
// X509_EXTENSIONS
// szOID_CERT_EXTENSIONS
//
// pvStructInfo points to following CERT_EXTENSIONS.
//--------------------------------------------------------------------------
TCertExtensions = record
cExtensions : DWORD;
rgExtensions : PCertExtension
end;
PCertExtensions = ^TCertExtensions;
//+=========================================================================
// Certificate Store Data Structures and APIs
//==========================================================================
//+-------------------------------------------------------------------------
// In its most basic implementation, a cert store is simply a
// collection of certificates and/or CRLs. This is the case when
// a cert store is opened with all of its certificates and CRLs
// coming from a PKCS #7 encoded cryptographic message.
//
// Nonetheless, all cert stores have the following properties:
// - A public key may have more than one certificate in the store.
// For example, a private/public key used for signing may have a
// certificate issued for VISA and another issued for
// Mastercard. Also, when a certificate is renewed there might
// be more than one certificate with the same subject and
// issuer.
// - However, each certificate in the store is uniquely
// identified by its Issuer and SerialNumber.
// - There's an issuer of subject certificate relationship. A
// certificate's issuer is found by doing a match of
// pSubjectCert->Issuer with pIssuerCert->Subject.
// The relationship is verified by using
// the issuer's public key to verify the subject certificate's
// signature. Note, there might be X.509 v3 extensions
// to assist in finding the issuer certificate.
// - Since issuer certificates might be renewed, a subject
// certificate might have more than one issuer certificate.
// - There's an issuer of CRL relationship. An
// issuer's CRL is found by doing a match of
// pIssuerCert->Subject with pCrl->Issuer.
// The relationship is verified by using
// the issuer's public key to verify the CRL's
// signature. Note, there might be X.509 v3 extensions
// to assist in finding the CRL.
// - Since some issuers might support the X.509 v3 delta CRL
// extensions, an issuer might have more than one CRL.
// - The store shouldn't have any redundant certificates or
// CRLs. There shouldn't be two certificates with the same
// Issuer and SerialNumber. There shouldn't be two CRLs with
// the same Issuer, ThisUpdate and NextUpdate.
// - The store has NO policy or trust information. No
// certificates are tagged as being "root". Its up to
// the application to maintain a list of CertIds (Issuer +
// SerialNumber) for certificates it trusts.
// - The store might contain bad certificates and/or CRLs.
// The issuer's signature of a subject certificate or CRL may
// not verify. Certificates or CRLs may not satisfy their
// time validity requirements. Certificates may be
// revoked.
//
// In addition to the certificates and CRLs, properties can be
// stored. There are two predefined property IDs for a user
// certificate: CERT_KEY_PROV_HANDLE_PROP_ID and
// CERT_KEY_PROV_INFO_PROP_ID. The CERT_KEY_PROV_HANDLE_PROP_ID
// is a HCRYPTPROV handle to the private key assoicated
// with the certificate. The CERT_KEY_PROV_INFO_PROP_ID contains
// information to be used to call
// CryptAcquireContext and CryptSetProvParam to get a handle
// to the private key associated with the certificate.
//
// There exists two more predefined property IDs for certificates
// and CRLs, CERT_SHA1_HASH_PROP_ID and CERT_MD5_HASH_PROP_ID.
// If these properties don't already exist, then, a hash of the
// content is computed. (CERT_HASH_PROP_ID maps to the default
// hash algorithm, currently, CERT_SHA1_HASH_PROP_ID).
//
// There are additional APIs for creating certificate and CRL
// contexts not in a store (CertCreateCertificateContext and
// CertCreateCRLContext).
//
//--------------------------------------------------------------------------
HCERTSTORE = pointer;
//+-------------------------------------------------------------------------
// In a CRYPT_BIT_BLOB the last byte may contain 0-7 unused bits. Therefore, the
// overall bit length is cbData * 8 - cUnusedBits.
//--------------------------------------------------------------------------
TCryptBitBlob = record
cbData : DWORD;
pbData : PBYTE;
cUnusedBits : DWORD
end;
PCryptBitBlob = ^TCryptBitBlob;
//+-------------------------------------------------------------------------
// Public Key Info
//
// The PublicKey is the encoded representation of the information as it is
// stored in the bit string
//--------------------------------------------------------------------------
TCertPublicKeyInfo = record
Algorithm : TCryptAlgorithmIdentifier;
PublicKey : TCryptBitBlob
end;
PCertPublicKeyInfo = ^TCertPublicKeyInfo;
//+-------------------------------------------------------------------------
// Information stored in a certificate
//
// The Issuer, Subject, Algorithm, PublicKey and Extension BLOBs are the
// encoded representation of the information.
//--------------------------------------------------------------------------
TCertInfo = record
dwVersion : DWORD;
SerialNumber : TCryptIntegerBlob;
SignatureAlgorithm : TCryptAlgorithmIdentifier;
Issuer : TCertNameBlob;
NotBefore : TFileTime;
NotAfter : TFileTime;
Subject : TCertNameBlob;
SubjectPublicKeyInfo : TCertPublicKeyInfo;
IssuerUniqueId : TCryptBitBlob;
SubjectUniqueId : TCryptBitBlob;
cExtension : DWORD;
rgExtension : PCertExtension
end;
PCertInfo = ^TCertInfo;
//+-------------------------------------------------------------------------
// An entry in a CRL
//
// The Extension BLOBs are the encoded representation of the information.
//--------------------------------------------------------------------------
TCRLEntry = record
SerialNumber : TCryptIntegerBlob;
RevocationDate : TFileTime;
cExtension : DWORD;
rgExtension : PCertExtension
end;
PCRLEntry = ^TCRLEntry;
//+-------------------------------------------------------------------------
// Information stored in a CRL
//
// The Issuer, Algorithm and Extension BLOBs are the encoded
// representation of the information.
//--------------------------------------------------------------------------
TCRLInfo = record
dwVersion : DWORD;
SignatureAlgorithm : TCryptAlgorithmIdentifier;
Issuer : TCertNameBlob;
ThisUpdate : TFileTime;
NextUpdate : TFileTime;
cCRLEntry : DWORD;
rgCRLEntry : PCRLEntry;
cExtension : DWORD;
rgExtension : PCertExtension
end;
PCRLInfo = ^TCRLInfo;
//+-------------------------------------------------------------------------
// CRL versions
//--------------------------------------------------------------------------
const
CRL_V1 = 0;
CRL_V2 = 1;
type
//+-------------------------------------------------------------------------
// Certificate context.
//
// A certificate context contains both the encoded and decoded representation
// of a certificate. A certificate context returned by a cert store function
// must be freed by calling the CertFreeCertificateContext function. The
// CertDuplicateCertificateContext function can be called to make a duplicate
// copy (which also must be freed by calling CertFreeCertificateContext).
//--------------------------------------------------------------------------
TCertContext = record
dwCertEncodingType : DWORD;
pbCertEncoded : PBYTE;
cbCertEncoded : DWORD;
certInfo : PCertInfo;
certStore : HCERTSTORE
end;
PCertContext = ^TCertContext;
PCCertContext = ^TCertContext;
//+-------------------------------------------------------------------------
// CRL context.
//
// A CRL context contains both the encoded and decoded representation
// of a CRL. A CRL context returned by a cert store function
// must be freed by calling the CertFreeCRLContext function. The
// CertDuplicateCRLContext function can be called to make a duplicate
// copy (which also must be freed by calling CertFreeCRLContext).
//--------------------------------------------------------------------------
TCRLContext = record
dwCertEncodingType : DWORD;
pbCrlEncoded : PBYTE;
cbCrlEncoded : DWORD;
crlInfo : PCrlInfo;
certStore : HCertStore
end;
PCRLContext = ^TCRLContext;
TCTLUsage = record
cUsageIdentifier : DWORD;
rgpszUsageIdentifier : PPAnsiChar;
end;
PCTLUsage = ^TCTLUsage;
TCertEnhkeyUsage = TCTLUsage; PCertEnhkeyUsage = ^TCertEnhkeyUsage;
//+-------------------------------------------------------------------------
// Attributes
//
// Where the Value's PATTR_BLOBs are in their encoded representation.
//--------------------------------------------------------------------------
TCryptAttribute = record
pszObjId : PAnsiChar;
cValue : DWORD;
rgValue : PCryptAttrBlob
end;
PCryptAttribute = ^TCryptAttribute;
//+-------------------------------------------------------------------------
// An entry in a CTL
//--------------------------------------------------------------------------
TCTLEntry = record
SubjectIdentifier : TCryptDataBlob; // For example, its hash
cAttribute : DWORD;
rgAttribute : PCryptAttribute
end;
PCTLEntry = ^TCTLEntry;
//+-------------------------------------------------------------------------
// Information stored in a CTL
//--------------------------------------------------------------------------
TCTLInfo = record
dwVersion : DWORD;
SubjectUsage : TCTLUsage;
ListIdentifier : TCryptDataBlob; // OPTIONAL
SequenceNumber : TCryptIntegerBlob; // OPTIONAL
ThisUpdate : TFileTime;
NextUpdate : TFileTime; // OPTIONAL
SubjectAlgorithm : TCryptAlgorithmIdentifier;
cCTLEntry : DWORD;
rgCTLEntry : PCTLEntry; // OPTIONAL
cExtension : DWORD;
rgExtension : PCertExtension; // OPTIONAL
end;
PCTLInfo = ^TCTLInfo;
//+-------------------------------------------------------------------------
// CTL versions
//--------------------------------------------------------------------------
const
CTL_V1 = 0;
type
HCRYPTMSG = pointer;
//+-------------------------------------------------------------------------
// Certificate Trust List (CTL) context.
//
// A CTL context contains both the encoded and decoded representation
// of a CTL. Also contains an opened HCRYPTMSG handle to the decoded
// cryptographic signed message containing the CTL_INFO as its inner content.
// pbCtlContent is the encoded inner content of the signed message.
//
// The CryptMsg APIs can be used to extract additional signer information.
//--------------------------------------------------------------------------
TCTLContext = record
dwMsgAndCertEncodingType : DWORD;
pbCtlEncoded : PBYTE;
cbCtlEncoded : DWORD;
ctlInfo : PCTLInfo;
certStore : HCERTSTORE;
cryptMsg : HCRYPTMSG;
pbCtlContent : PBYTE;
cbCtlContent : DWORD
end;
PCTLContext = ^TCTLContext;
//+-------------------------------------------------------------------------
// Certificate, CRL and CTL property IDs
//
// See CertSetCertificateContextProperty or CertGetCertificateContextProperty
// for usage information.
//--------------------------------------------------------------------------
const
CERT_KEY_PROV_HANDLE_PROP_ID = 1;
CERT_KEY_PROV_INFO_PROP_ID = 2;
CERT_SHA1_HASH_PROP_ID = 3;
CERT_MD5_HASH_PROP_ID = 4;
CERT_HASH_PROP_ID = CERT_SHA1_HASH_PROP_ID;
CERT_KEY_CONTEXT_PROP_ID = 5;
CERT_KEY_SPEC_PROP_ID = 6;
CERT_IE30_RESERVED_PROP_ID = 7;
CERT_PUBKEY_HASH_RESERVED_PROP_ID = 8;
CERT_ENHKEY_USAGE_PROP_ID = 9;
CERT_CTL_USAGE_PROP_ID = CERT_ENHKEY_USAGE_PROP_ID;
CERT_NEXT_UPDATE_LOCATION_PROP_ID = 10;
CERT_FRIENDLY_NAME_PROP_ID = 11;
CERT_PVK_FILE_PROP_ID = 12;
CERT_DESCRIPTION_PROP_ID = 13;
CERT_ACCESS_STATE_PROP_ID = 14;
CERT_SIGNATURE_HASH_PROP_ID = 15;
CERT_SMART_CARD_DATA_PROP_ID = 16;
CERT_EFS_PROP_ID = 17;
CERT_FORTEZZA_DATA_PROP_ID = 18;
CERT_ARCHIVED_PROP_ID = 19;
CERT_KEY_IDENTIFIER_PROP_ID = 20;
CERT_AUTO_ENROLL_PROP_ID = 21;
CERT_PUBKEY_ALG_PARA_PROP_ID = 22;
CERT_CROSS_CERT_DIST_POINTS_PROP_ID = 23;
CERT_ISSUER_PUBLIC_KEY_MD5_HASH_PROP_ID = 24;
CERT_SUBJECT_PUBLIC_KEY_MD5_HASH_PROP_ID = 25;
CERT_ENROLLMENT_PROP_ID = 26;
CERT_DATE_STAMP_PROP_ID = 27;
CERT_ISSUER_SERIAL_NUMBER_MD5_HASH_PROP_ID = 28;
CERT_SUBJECT_NAME_MD5_HASH_PROP_ID = 29;
CERT_EXTENDED_ERROR_INFO_PROP_ID = 30;
// Note, 32 - 35 are reserved for the CERT, CRL, CTL and KeyId file element IDs.
// 36 - 63 are reserved for future element IDs.
CERT_RENEWAL_PROP_ID = 64;
CERT_ARCHIVED_KEY_HASH_PROP_ID = 65;
CERT_AUTO_ENROLL_RETRY_PROP_ID = 66;
CERT_AIA_URL_RETRIEVED_PROP_ID = 67;
CERT_FIRST_RESERVED_PROP_ID = 68;
CERT_LAST_RESERVED_PROP_ID = $00007FFF;
CERT_FIRST_USER_PROP_ID = $00008000;
CERT_LAST_USER_PROP_ID = $0000FFFF;
CERT_CREATE_SELFSIGN_NO_SIGN = 1;
CERT_CREATE_SELFSIGN_NO_KEY_INFO = 2;
//+-------------------------------------------------------------------------
// Certificate Store Provider Types
//--------------------------------------------------------------------------
CERT_STORE_PROV_MSG = PAnsiChar (1);
CERT_STORE_PROV_MEMORY = PAnsiChar (2);
CERT_STORE_PROV_FILE = PAnsiChar (3);
CERT_STORE_PROV_REG = PAnsiChar (4);
CERT_STORE_PROV_PKCS7 = PAnsiChar (5);
CERT_STORE_PROV_SERIALIZED = PAnsiChar (6);
CERT_STORE_PROV_FILENAME_A = PAnsiChar (7);
CERT_STORE_PROV_FILENAME_W = PAnsiChar (8);
CERT_STORE_PROV_FILENAME = CERT_STORE_PROV_FILENAME_W;
CERT_STORE_PROV_SYSTEM_A = PAnsiChar (9);
CERT_STORE_PROV_SYSTEM_W = PAnsiChar (10);
CERT_STORE_PROV_SYSTEM = CERT_STORE_PROV_SYSTEM_W;
CERT_STORE_PROV_COLLECTION = PAnsiChar (11);
CERT_STORE_PROV_SYSTEM_REGISTRY_A = PAnsiChar (12);
CERT_STORE_PROV_SYSTEM_REGISTRY_W = PAnsiChar (13);
CERT_STORE_PROV_SYSTEM_REGISTRY = CERT_STORE_PROV_SYSTEM_REGISTRY_W;
CERT_STORE_PROV_PHYSICAL_W = PAnsiChar (14);
CERT_STORE_PROV_PHYSICAL = CERT_STORE_PROV_PHYSICAL_W;
CERT_STORE_PROV_SMART_CARD_W = PAnsiChar (15);
CERT_STORE_PROV_SMART_CARD = CERT_STORE_PROV_SMART_CARD_W;
CERT_STORE_PROV_LDAP_W = PAnsiChar (16);
CERT_STORE_PROV_LDAP = CERT_STORE_PROV_LDAP_W;
sz_CERT_STORE_PROV_MEMORY = 'Memory';
sz_CERT_STORE_PROV_FILENAME_W = 'File';
sz_CERT_STORE_PROV_FILENAME = sz_CERT_STORE_PROV_FILENAME_W;
sz_CERT_STORE_PROV_SYSTEM_W = 'System';
sz_CERT_STORE_PROV_SYSTEM = sz_CERT_STORE_PROV_SYSTEM_W;
sz_CERT_STORE_PROV_PKCS7 = 'PKCS7';
sz_CERT_STORE_PROV_SERIALIZED = 'Serialized';
sz_CERT_STORE_PROV_COLLECTION = 'Collection';
sz_CERT_STORE_PROV_SYSTEM_REGISTRY_W = 'SystemRegistry';
sz_CERT_STORE_PROV_SYSTEM_REGISTRY = sz_CERT_STORE_PROV_SYSTEM_REGISTRY_W;
sz_CERT_STORE_PROV_PHYSICAL_W = 'Physical';
sz_CERT_STORE_PROV_PHYSICAL = sz_CERT_STORE_PROV_PHYSICAL_W;
sz_CERT_STORE_PROV_SMART_CARD_W = 'SmartCard';
sz_CERT_STORE_PROV_SMART_CARD = sz_CERT_STORE_PROV_SMART_CARD_W;
sz_CERT_STORE_PROV_LDAP_W = 'Ldap';
sz_CERT_STORE_PROV_LDAP = sz_CERT_STORE_PROV_LDAP_W;
//+-------------------------------------------------------------------------
// Certificate Store verify/results flags
//--------------------------------------------------------------------------
CERT_STORE_SIGNATURE_FLAG = $00000001;
CERT_STORE_TIME_VALIDITY_FLAG = $00000002;
CERT_STORE_REVOCATION_FLAG = $00000004;
CERT_STORE_NO_CRL_FLAG = $00010000;
CERT_STORE_NO_ISSUER_FLAG = $00020000;
CERT_STORE_BASE_CRL_FLAG = $00000100;
CERT_STORE_DELTA_CRL_FLAG = $00000200;
//+-------------------------------------------------------------------------
// Certificate Store open/property flags
//--------------------------------------------------------------------------
CERT_STORE_NO_CRYPT_RELEASE_FLAG = $00000001;
CERT_STORE_SET_LOCALIZED_NAME_FLAG = $00000002;
CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG = $00000004;
CERT_STORE_DELETE_FLAG = $00000010;
CERT_STORE_UNSAFE_PHYSICAL_FLAG = $00000020;
CERT_STORE_SHARE_STORE_FLAG = $00000040;
CERT_STORE_SHARE_CONTEXT_FLAG = $00000080;
CERT_STORE_MANIFOLD_FLAG = $00000100;
CERT_STORE_ENUM_ARCHIVED_FLAG = $00000200;
CERT_STORE_UPDATE_KEYID_FLAG = $00000400;
CERT_STORE_BACKUP_RESTORE_FLAG = $00000800;
CERT_STORE_READONLY_FLAG = $00008000;
CERT_STORE_OPEN_EXISTING_FLAG = $00004000;
CERT_STORE_CREATE_NEW_FLAG = $00002000;
CERT_STORE_MAXIMUM_ALLOWED_FLAG = $00001000;
//+-------------------------------------------------------------------------
// Certificate System Store Flag Values
//--------------------------------------------------------------------------
// Includes flags and location
CERT_SYSTEM_STORE_MASK = $FFFF0000;
CERT_SYSTEM_STORE_RELOCATE_FLAG = $80000000;
CERT_SYSTEM_STORE_UNPROTECTED_FLAG = $40000000;
// Location of the system store:
CERT_SYSTEM_STORE_LOCATION_MASK = $00FF0000;
CERT_SYSTEM_STORE_LOCATION_SHIFT = 16;
// Registry: HKEY_CURRENT_USER or HKEY_LOCAL_MACHINE
CERT_SYSTEM_STORE_CURRENT_USER_ID = 1;
CERT_SYSTEM_STORE_LOCAL_MACHINE_ID = 2;
// Registry: HKEY_LOCAL_MACHINE\Software\Microsoft\Cryptography\Services
CERT_SYSTEM_STORE_CURRENT_SERVICE_ID = 4;
CERT_SYSTEM_STORE_SERVICES_ID = 5;
// Registry: HKEY_USERS
CERT_SYSTEM_STORE_USERS_ID = 6;
// Registry: HKEY_CURRENT_USER\Software\Policies\Microsoft\SystemCertificates
CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY_ID = 7;
// Registry: HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\SystemCertificates
CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY_ID = 8;
// Registry: HKEY_LOCAL_MACHINE\Software\Microsoft\EnterpriseCertificates
CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE_ID = 9;
CERT_SYSTEM_STORE_CURRENT_USER = (CERT_SYSTEM_STORE_CURRENT_USER_ID shl CERT_SYSTEM_STORE_LOCATION_SHIFT);
CERT_SYSTEM_STORE_LOCAL_MACHINE = (CERT_SYSTEM_STORE_LOCAL_MACHINE_ID shl CERT_SYSTEM_STORE_LOCATION_SHIFT);
CERT_SYSTEM_STORE_CURRENT_SERVICE = (CERT_SYSTEM_STORE_CURRENT_SERVICE_ID shl CERT_SYSTEM_STORE_LOCATION_SHIFT);
CERT_SYSTEM_STORE_SERVICES = (CERT_SYSTEM_STORE_SERVICES_ID shl CERT_SYSTEM_STORE_LOCATION_SHIFT);
CERT_SYSTEM_STORE_USERS = (CERT_SYSTEM_STORE_USERS_ID shl CERT_SYSTEM_STORE_LOCATION_SHIFT);
CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY = (CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY_ID shl CERT_SYSTEM_STORE_LOCATION_SHIFT);
CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY = (CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY_ID shl CERT_SYSTEM_STORE_LOCATION_SHIFT);
CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE = (CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE_ID shl CERT_SYSTEM_STORE_LOCATION_SHIFT);
CERT_NAME_EMAIL_TYPE = 1;
CERT_NAME_RDN_TYPE = 2;
CERT_NAME_ATTR_TYPE = 3;
CERT_NAME_SIMPLE_DISPLAY_TYPE = 4;
CERT_NAME_FRIENDLY_DISPLAY_TYPE = 5;
CERT_NAME_DNS_TYPE = 6;
CERT_NAME_URL_TYPE = 7;
CERT_NAME_UPN_TYPE = 8;
//+-------------------------------------------------------------------------
// Certificate name flags
//--------------------------------------------------------------------------
CERT_NAME_ISSUER_FLAG = $1;
CERT_NAME_DISABLE_IE4_UTF8_FLAG = $00010000;
//
// MessageId: CRYPT_E_MSG_ERROR
//
// MessageText:
//
// An error occurred while performing an operation on a cryptographic message.
//
CRYPT_E_MSG_ERROR = $80091001;
//
// MessageId: CRYPT_E_UNKNOWN_ALGO
//
// MessageText:
//
// Unknown cryptographic algorithm.
//
CRYPT_E_UNKNOWN_ALGO = $80091002;
//
// MessageId: CRYPT_E_OID_FORMAT
//
// MessageText:
//
// The object identifier is poorly formatted.
//
CRYPT_E_OID_FORMAT = $80091003;
//
// MessageId: CRYPT_E_INVALID_MSG_TYPE
//
// MessageText:
//
// Invalid cryptographic message type.
//
CRYPT_E_INVALID_MSG_TYPE = $80091004;
//
// MessageId: CRYPT_E_UNEXPECTED_ENCODING
//
// MessageText:
//
// Unexpected cryptographic message encoding.
//
CRYPT_E_UNEXPECTED_ENCODING = $80091005;
//
// MessageId: CRYPT_E_AUTH_ATTR_MISSING
//
// MessageText:
//
// The cryptographic message does not contain an expected authenticated attribute.
//
CRYPT_E_AUTH_ATTR_MISSING = $80091006;
//
// MessageId: CRYPT_E_HASH_VALUE
//
// MessageText:
//
// The hash value is not correct.
//
CRYPT_E_HASH_VALUE = $80091007;
//
// MessageId: CRYPT_E_INVALID_INDEX
//
// MessageText:
//
// The index value is not valid.
//
CRYPT_E_INVALID_INDEX = $80091008;
//
// MessageId: CRYPT_E_ALREADY_DECRYPTED
//
// MessageText:
//
// The content of the cryptographic message has already been decrypted.
//
CRYPT_E_ALREADY_DECRYPTED = $80091009;
//
// MessageId: CRYPT_E_NOT_DECRYPTED
//
// MessageText:
//
// The content of the cryptographic message has not been decrypted yet.
//
CRYPT_E_NOT_DECRYPTED = $8009100A;
//
// MessageId: CRYPT_E_RECIPIENT_NOT_FOUND
//
// MessageText:
//
// The enveloped-data message does not contain the specified recipient.
//
CRYPT_E_RECIPIENT_NOT_FOUND = $8009100B;
//
// MessageId: CRYPT_E_CONTROL_TYPE
//
// MessageText:
//
// Invalid control type.
//
CRYPT_E_CONTROL_TYPE = $8009100C;
//
// MessageId: CRYPT_E_ISSUER_SERIALNUMBER
//
// MessageText:
//
// Invalid issuer and/or serial number.
//
CRYPT_E_ISSUER_SERIALNUMBER = $8009100D;
//
// MessageId: CRYPT_E_SIGNER_NOT_FOUND
//
// MessageText:
//
// Cannot find the original signer.
//
CRYPT_E_SIGNER_NOT_FOUND = $8009100E;
//
// MessageId: CRYPT_E_ATTRIBUTES_MISSING
//
// MessageText:
//
// The cryptographic message does not contain all of the requested attributes.
//
CRYPT_E_ATTRIBUTES_MISSING = $8009100F;
//
// MessageId: CRYPT_E_STREAM_MSG_NOT_READY
//
// MessageText:
//
// The streamed cryptographic message is not ready to return data.
//
CRYPT_E_STREAM_MSG_NOT_READY = $80091010;
//
// MessageId: CRYPT_E_STREAM_INSUFFICIENT_DATA
//
// MessageText:
//
// The streamed cryptographic message requires more data to complete the decode operation.
//
CRYPT_E_STREAM_INSUFFICIENT_DATA = $80091011;
//
// MessageId: CRYPT_I_NEW_PROTECTION_REQUIRED
//
// MessageText:
//
// The protected data needs to be re-protected.
//
CRYPT_I_NEW_PROTECTION_REQUIRED = $00091012;
//
// MessageId: CRYPT_E_BAD_LEN
//
// MessageText:
//
// The length specified for the output data was insufficient.
//
CRYPT_E_BAD_LEN = $80092001;
//
// MessageId: CRYPT_E_BAD_ENCODE
//
// MessageText:
//
// An error occurred during encode or decode operation.
//
CRYPT_E_BAD_ENCODE = $80092002;
//
// MessageId: CRYPT_E_FILE_ERROR
//
// MessageText:
//
// An error occurred while reading or writing to a file.
//
CRYPT_E_FILE_ERROR = $80092003;
//
// MessageId: CRYPT_E_NOT_FOUND
//
// MessageText:
//
// Cannot find object or property.
//
CRYPT_E_NOT_FOUND = $80092004;
//
// MessageId: CRYPT_E_EXISTS
//
// MessageText:
//
// The object or property already exists.
//
CRYPT_E_EXISTS = $80092005;
//
// MessageId: CRYPT_E_NO_PROVIDER
//
// MessageText:
//
// No provider was specified for the store or object.
//
CRYPT_E_NO_PROVIDER = $80092006;
//
// MessageId: CRYPT_E_SELF_SIGNED
//
// MessageText:
//
// The specified certificate is self signed.
//
CRYPT_E_SELF_SIGNED = $80092007;
//
// MessageId: CRYPT_E_DELETED_PREV
//
// MessageText:
//
// The previous certificate or CRL context was deleted.
//
CRYPT_E_DELETED_PREV = $80092008;
//
// MessageId: CRYPT_E_NO_MATCH
//
// MessageText:
//
// Cannot find the requested object.
//
CRYPT_E_NO_MATCH = $80092009;
//
// MessageId: CRYPT_E_UNEXPECTED_MSG_TYPE
//
// MessageText:
//
// The certificate does not have a property that references a private key.
//
CRYPT_E_UNEXPECTED_MSG_TYPE = $8009200A;
//
// MessageId: CRYPT_E_NO_KEY_PROPERTY
//
// MessageText:
//
// Cannot find the certificate and private key for decryption.
//
CRYPT_E_NO_KEY_PROPERTY = $8009200B;
//
// MessageId: CRYPT_E_NO_DECRYPT_CERT
//
// MessageText:
//
// Cannot find the certificate and private key to use for decryption.
//
CRYPT_E_NO_DECRYPT_CERT = $8009200C;
//
// MessageId: CRYPT_E_BAD_MSG
//
// MessageText:
//
// Not a cryptographic message or the cryptographic message is not formatted correctly.
//
CRYPT_E_BAD_MSG = $8009200D;
//
// MessageId: CRYPT_E_NO_SIGNER
//
// MessageText:
//
// The signed cryptographic message does not have a signer for the specified signer index.
//
CRYPT_E_NO_SIGNER = $8009200E;
//
// MessageId: CRYPT_E_PENDING_CLOSE
//
// MessageText:
//
// Final closure is pending until additional frees or closes.
//
CRYPT_E_PENDING_CLOSE = $8009200F;
//
// MessageId: CRYPT_E_REVOKED
//
// MessageText:
//
// The certificate is revoked.
//
CRYPT_E_REVOKED = $80092010;
//
// MessageId: CRYPT_E_NO_REVOCATION_DLL
//
// MessageText:
//
// No Dll or exported function was found to verify revocation.
//
CRYPT_E_NO_REVOCATION_DLL = $80092011;
//
// MessageId: CRYPT_E_NO_REVOCATION_CHECK
//
// MessageText:
//
// The revocation function was unable to check revocation for the certificate.
//
CRYPT_E_NO_REVOCATION_CHECK = $80092012;
//
// MessageId: CRYPT_E_REVOCATION_OFFLINE
//
// MessageText:
//
// The revocation function was unable to check revocation because the revocation server was offline.
//
CRYPT_E_REVOCATION_OFFLINE = $80092013;
//
// MessageId: CRYPT_E_NOT_IN_REVOCATION_DATABASE
//
// MessageText:
//
// The certificate is not in the revocation server's database.
//
CRYPT_E_NOT_IN_REVOCATION_DATABASE = $80092014;
//
// MessageId: CRYPT_E_INVALID_NUMERIC_STRING
//
// MessageText:
//
// The string contains a non-numeric character.
//
CRYPT_E_INVALID_NUMERIC_STRING = $80092020;
//
// MessageId: CRYPT_E_INVALID_PRINTABLE_STRING
//
// MessageText:
//
// The string contains a non-printable character.
//
CRYPT_E_INVALID_PRINTABLE_STRING = $80092021;
//
// MessageId: CRYPT_E_INVALID_IA5_STRING
//
// MessageText:
//
// The string contains a character not in the 7 bit ASCII character set.
//
CRYPT_E_INVALID_IA5_STRING = $80092022;
//
// MessageId: CRYPT_E_INVALID_X500_STRING
//
// MessageText:
//
// The string contains an invalid X500 name attribute key, oid, value or delimiter.
//
CRYPT_E_INVALID_X500_STRING = $80092023;
//
// MessageId: CRYPT_E_NOT_CHAR_STRING
//
// MessageText:
//
// The dwValueType for the CERT_NAME_VALUE is not one of the character strings. Most likely it is either a CERT_RDN_ENCODED_BLOB or CERT_TDN_OCTED_STRING.
//
CRYPT_E_NOT_CHAR_STRING = $80092024;
//
// MessageId: CRYPT_E_FILERESIZED
//
// MessageText:
//
// The Put operation can not continue. The file needs to be resized. However, there is already a signature present. A complete signing operation must be done.
//
CRYPT_E_FILERESIZED = $80092025;
//
// MessageId: CRYPT_E_SECURITY_SETTINGS
//
// MessageText:
//
// The cryptographic operation failed due to a local security option setting.
//
CRYPT_E_SECURITY_SETTINGS = $80092026;
//
// MessageId: CRYPT_E_NO_VERIFY_USAGE_DLL
//
// MessageText:
//
// No DLL or exported function was found to verify subject usage.
//
CRYPT_E_NO_VERIFY_USAGE_DLL = $80092027;
//
// MessageId: CRYPT_E_NO_VERIFY_USAGE_CHECK
//
// MessageText:
//
// The called function was unable to do a usage check on the subject.
//
CRYPT_E_NO_VERIFY_USAGE_CHECK = $80092028;
//
// MessageId: CRYPT_E_VERIFY_USAGE_OFFLINE
//
// MessageText:
//
// Since the server was offline, the called function was unable to complete the usage check.
//
CRYPT_E_VERIFY_USAGE_OFFLINE = $80092029;
//
// MessageId: CRYPT_E_NOT_IN_CTL
//
// MessageText:
//
// The subject was not found in a Certificate Trust List (CT;.
//
CRYPT_E_NOT_IN_CTL = $8009202A;
//
// MessageId: CRYPT_E_NO_TRUSTED_SIGNER
//
// MessageText:
//
// None of the signers of the cryptographic message or certificate trust list is trusted.
//
CRYPT_E_NO_TRUSTED_SIGNER = $8009202B;
//
// MessageId: CRYPT_E_MISSING_PUBKEY_PARA
//
// MessageText:
//
// The public key's algorithm parameters are missing.
//
CRYPT_E_MISSING_PUBKEY_PARA = $8009202C;
//
// MessageId: CRYPT_E_OSS_ERROR
//
// MessageText:
//
// OSS Certificate encode/decode error code base
//
// See asn1code.h for a definition of the OSS runtime errors. The OSS
// error values are offset by CRYPT_E_OSS_ERROR.
//
CRYPT_E_OSS_ERROR = $80093000;
function CryptAcquireContext(var hProv : HCRYPTPROV; pscContainer, pszProvider : PChar; dwProvType, dwFlags : DWORD) : BOOL; stdcall;
function CryptCreateHash(hProv : HCRYPTPROV; Algid : ALG_ID; hKey : HCRYPTKEY; dwFlags : DWORD; var hHash : HCRYPTHASH) : BOOL; stdcall;
function CryptHashData (hHash : HCRYPTHASH; data : PByte; dwDataLen : DWORD; dwFlags : DWORD) : BOOL; stdcall;
function CryptDeriveKey (hProv : HCRYPTPROV; Algid : ALG_ID; hBaseData : HCRYPTHASH; dwFlags : DWORD; var hKey : HCRYPTKEY) : BOOL; stdcall;
function CryptDestroyHash(hHash : HCRYPTHASH) : BOOL; stdcall;
function CryptDestroyKey(hKey : HCRYPTKEY) : BOOL; stdcall;
function CryptReleaseContext (hProv : HCRYPTPROV; dwFlags : DWORD) : BOOL; stdcall;
function CryptEncrypt(hKey : HCRYPTKEY; hHash : HCRYPTHASH; final : BOOL; dwFlags : DWORD; pbData : Pointer; var pdwDataLen : DWORD; dwBufLen : DWORD) : BOOL; stdcall;
function CryptDecrypt(hKey : HCRYPTKEY; hHash : HCRYPTHASH; Final : BOOL; dwFlags : DWORD; pbData : pointer; var pdwDataLen : DWORD) : BOOL; stdcall;
function CryptImportKey(hProv : HCRYPTPROV; pbData : Pointer; dwDataLen : DWORD; hPubKey : HCRYPTKEY; dwFlags : DWORD; var phKey : HCRYPTKEY) : BOOL; stdcall;
function CryptGetProvParam (hProv : HCRYPTPROV; dwparam : DWORD; pbData : Pointer; var pdwDataLen : DWORD; dwFlags : DWORD) : BOOL; stdcall;
function CertOpenStore (lpszStoreProvider : PAnsiChar;
dwEncodingType : DWORD;
hProv : HCRYPTPROV;
dwFlags : DWORD;
pvPara : pointer) : HCERTSTORE; stdcall;
function CertOpenSystemStore (hProv : HCRYPTPROV; szSubsystemProtocol : PChar) : HCERTSTORE; stdcall;
function CertCloseStore (certStore : HCERTSTORE; dwFlags : DWORD) : BOOL; stdcall;
function CertCreateSelfSignCertificate (hProv : HCRYPTPROV;
pSubjectIssuerBlob : PCertNameBlob;
dwFlags : DWORD;
pKeyProvInfo : PCryptKeyProvInfo;
pSignatureAlgorithm : PCryptAlgorithmIdentifier;
pStartTime :PSystemTime;
pEndTime : PSystemTime;
pExtensions : PCertExtensions) : PCCertContext; stdcall;
function CertEnumCertificatesInStore (certStore : HCERTSTORE; pPrevCertContext : PCCertContext) : PCCertContext; stdcall;
function CertFreeCertificateContext(pCertContext : PCCertContext) : BOOL; stdcall;
function CertGetNameStringA(certContext : pCCertContext;
dwType : DWORD;
dwFlags : DWORD;
pvTypePara : pointer;
pszNameString : PAnsiChar;
cchNameString : DWORD) : DWORD; stdcall;
function CertGetNameStringW(certContext : pCCertContext;
dwType : DWORD;
dwFlags : DWORD;
pvTypePara : pointer;
pszNameString : PWideChar;
cchNameString : DWORD) : DWORD; stdcall;
function CertGetNameString (certContext : pCCertContext;
dwType : DWORD;
dwFlags : DWORD;
pvTypePara : pointer;
pszNameString : PChar;
cchNameString : DWORD) : DWORD; stdcall;
function CryptGetHashParam (hHash : HCRYPTHASH; dwParam : DWORD; data : PByte; var dataLen : DWORD; flags : DWORD) : BOOL; stdcall;
implementation
const
cryptdll = 'advapi32.dll';
certdll = 'crypt32.dll';
{$ifdef UNICODE}
function CryptAcquireContext; external cryptdll name 'CryptAcquireContextW';
function CertOpenSystemStore; external certdll name 'CertOpenSystemStoreW';
function CertGetNameString; external certdll name 'CertGetNameStringW';
{$else}
function CryptAcquireContext; external cryptdll name 'CryptAcquireContextA';
function CertOpenSystemStore; external certdll name 'CertOpenSystemStoreA';
function CertGetNameString; external certdll name 'CertGetNameStringA';
{$endif}
function CryptCreateHash; external cryptdll;
function CryptHashData; external cryptdll;
function CryptDeriveKey; external cryptdll;
function CryptDestroyHash; external cryptdll;
function CryptDestroyKey; external cryptdll;
function CryptReleaseContext; external cryptdll;
function CryptEncrypt; external cryptdll;
function CryptDecrypt; external cryptdll;
function CryptImportKey; external cryptdll;
function CryptGetProvParam; external cryptdll;
function CryptGetHashParam; external cryptdll;
function CertOpenStore; external certdll;
function CertCloseStore; external certdll;
function CertCreateSelfSignCertificate; external certdll;
function CertEnumCertificatesInStore; external certdll;
function CertFreeCertificateContext; external certdll;
function CertGetNameStringA; external certdll;
function CertGetNameStringW; external certdll;
end.
|
unit fZeeBeTestCLI;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, JvBaseDlg,
JvBrowseFolder, Vcl.Mask;
type
TForm1 = class(TForm)
dlgBrowseForFolder: TJvBrowseForFolderDialog;
mmoCLIResults: TMemo;
btnDeployBPMFile: TButton;
lbledtBPMNFileFolder: TLabeledEdit;
lbledtBINFolder: TLabeledEdit;
lbledworkFlowBPMNFile: TLabeledEdit;
btnCreateWFInstance: TButton;
btnGetStatus: TButton;
medtOrderID: TMaskEdit;
lblOrderID: TLabel;
medtAmount: TMaskEdit;
lblAmount: TLabel;
btnCreateWorker: TButton;
lbledtJobName: TLabeledEdit;
btnPublishMessage: TButton;
lbledtMessage: TLabeledEdit;
lbledtCorrKey: TLabeledEdit;
lblJob2: TLabel;
procedure btnDeployBPMFileClick(Sender: TObject);
procedure lbledtBPMNFileFolderDblClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnCreateWFInstanceClick(Sender: TObject);
procedure btnGetStatusClick(Sender: TObject);
procedure btnCreateWorkerClick(Sender: TObject);
procedure FormClick(Sender: TObject);
procedure btnPublishMessageClick(Sender: TObject);
private
{ Private-Deklarationen }
fCLIResult: string;
fPathToCLI: string;
fBPMNFolder: string;
FBINFolder: string;
fAbort: Boolean;
procedure setBPMNFolder(const Value: string);
procedure SetBINFolder(const Value: string);
procedure CallZeBeeCLI_Async(const aCommand, aPara: string);
procedure CallZeBeeCLI(const aCommand, aPara: string);
procedure LogText(const aText: string);
public
{ Public-Deklarationen }
ZeeBeCLI: string;
property BPMNFolder: string read fBPMNFolder write setBPMNFolder;
property BINFolder:string read FBINFolder write SetBINFolder;
end;
var
Form1: TForm1;
implementation
uses Winapi.ShellAPI,
JclSysUtils;
{$R *.dfm}
function ExecuteFile(const FileName, Params, DefaultDir: string;
ShowCmd: Integer; Handle:THandle = 0): THandle;
var
aParams,aFileName: String;
zFileName, zParams, zDir: array[0..259] of Char; //7.11.01 259Zeichen aus TFileRec SysUtils
aHandle: THandle;
begin
aParams := Params;
aFileName := FileName;
{
If (Params = '')
then ParseExeFile(FileName,aFileName,aParams);
}
if Handle=0
then aHandle := Application.MainForm.Handle
else aHandle := Handle;
Result := ShellExecute(aHandle, nil,
StrPCopy(zFileName, aFileName), StrPCopy(zParams, aParams),
StrPCopy(zDir, DefaultDir), ShowCmd);
end;
procedure TForm1.btnCreateWFInstanceClick(Sender: TObject);
Var ErrorMessage: string;
aCommand: String;
begin
aCommand :=
Format('%sZBCtl.exe --insecure create instance %s'+
' --variables "{\"orderId\": %s, \"orderValue\": %s}"',
[BINFolder,
'order-process',
medtOrderID.Text,
medtAmount.Text]);
mmoCLIResults.Lines.Add(format('COMMAND %s',[aCommand]));
if JclSysUtils.Execute(
aCommand,
fCLIResult,
ErrorMessage) = ERROR_SUCCESS
then mmoCLIResults.Lines.Add(fCLIResult)
else mmoCLIResults.Lines.Add(ErrorMessage)
end;
procedure TForm1.btnCreateWorkerClick(Sender: TObject);
Var aCommand, aParas: String;
begin
{ aCommand := Format('create worker %s --handler "findstr .*"',[lbledtJobName.Text]); }
aCommand := Format('create worker %s --handler "ZeeBeWorkerGeneric.exe"',[lbledtJobName.Text]);
aParas := '';
CallZeBeeCLI_Async(aCommand,aParas);
end;
procedure TForm1.btnDeployBPMFileClick(Sender: TObject);
Var ErrorMessage: string;
begin
if JclSysUtils.Execute(
Format('%sZBCtl.exe --insecure deploy %s%s',
[BINFolder,
fBPMNFolder,
'order-process.bpmn']),
fCLIResult,
ErrorMessage) = ERROR_SUCCESS
then mmoCLIResults.Lines.Add(fCLIResult)
else mmoCLIResults.Lines.Add(ErrorMessage);
end;
procedure TForm1.btnGetStatusClick(Sender: TObject);
Var ErrorMessage: string;
begin
if JclSysUtils.Execute(
Format('%sZBCtl.exe --insecure status',
[BINFolder]),
fCLIResult,
ErrorMessage) = ERROR_SUCCESS
then mmoCLIResults.Lines.Add(fCLIResult)
else mmoCLIResults.Lines.Add(ErrorMessage);
end;
procedure TForm1.btnPublishMessageClick(Sender: TObject);
begin
CallZeBeeCLI(Format('publish message "%s"',[lbledtMessage.Text]), Format('--correlationKey="%s"',[lbledtCorrKey.Text]));
end;
procedure TForm1.CallZeBeeCLI(const aCommand, aPara: string);
Var ErrorMessage: string;
bCommand: String;
begin
bCommand := Format('%sZBCtl.exe --insecure %s %s',
[BINFolder, aCommand, aPara]);
fAbort := False;
mmoCLIResults.Lines.Add(format('COMMAND: %s',[bCommand]));
if JclSysUtils.Execute(
bCommand ,
fCLIResult,
ErrorMessage,
False, False,
@fAbort) = ERROR_SUCCESS
then mmoCLIResults.Lines.Add(fCLIResult)
else mmoCLIResults.Lines.Add(ErrorMessage)
end;
procedure TForm1.CallZeBeeCLI_Async(const aCommand, aPara: string);
Var ErrorMessage: string;
bCommand, aParas: String;
begin
bCommand := Format('%sZBCtl.exe --insecure %s %s',
[BINFolder, aCommand, aPara]);
mmoCLIResults.Lines.Add(format('COMMAND: %s',[bCommand]));
fAbort := False;
bCommand := Format('%sZBCtl.exe',
[BINFolder]);
aParas := Format('--insecure %s %s',
[aCommand, aPara]);
ExecuteFile(bCommand,aParas,BINFolder,SHOW_ICONWINDOW,Self.Handle);
end;
procedure TForm1.FormClick(Sender: TObject);
begin
fAbort := True;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
BPMNFolder := 'c:\Users\pmm\zeebe-docker-compose\bpmn\';
BINFolder := 'c:\Users\pmm\zeebe-docker-compose\bin\';
end;
procedure TForm1.lbledtBPMNFileFolderDblClick(Sender: TObject);
begin
if dlgBrowseForFolder.Execute(self.Handle)
then BPMNFolder := dlgBrowseForFolder.Directory;
end;
procedure TForm1.LogText(const aText: string);
begin
mmoCLIResults.Lines.Add(aText)
end;
procedure TForm1.SetBINFolder(const Value: string);
begin
FBINFolder := Value;
lbledtBINFolder.Text := Value;
end;
procedure TForm1.setBPMNFolder(const Value: string);
begin
fBPMNFolder := Value;
lbledtBPMNFileFolder.Text := Value;
end;
end.
|
{*************************************************************
Author: Stéphane Vander Clock (SVanderClock@Arkadia.com)
JCL
www: http://www.arkadia.com
EMail: SVanderClock@Arkadia.com
product: Alcinoe Mime function
Version: 3.05
Description: Function mime encode and decode from JCL and function
to get default Mime content type from file extension
Legal issues: Copyright (C) 1999-2005 by Arkadia Software Engineering
This software is provided 'as-is', without any express
or implied warranty. In no event will the author 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.
4. You must register this software by sending a picture
postcard to the author. Use a nice stamp and mention
your name, street address, EMail address and any
comment you like to say.
Know bug :
History :
Link :
Please send all your feedback to SVanderClock@Arkadia.com
**************************************************************}
unit ALFcnMime;
interface
uses Windows,
Classes,
sysutils;
{from JCL}
function ALMimeBase64EncodeString(const S: AnsiString): AnsiString;
function ALMimeBase64EncodeStringNoCRLF(const S: AnsiString): AnsiString;
function ALMimeBase64DecodeString(const S: AnsiString): AnsiString;
function ALMimeBase64EncodedSize(const InputSize: Cardinal): Cardinal;
function ALMimeBase64EncodedSizeNoCRLF(const InputSize: Cardinal): Cardinal;
function ALMimeBase64DecodedSize(const InputSize: Cardinal): Cardinal;
procedure ALMimeBase64Encode(const InputBuffer; const InputByteCount: Cardinal; out OutputBuffer);
procedure ALMimeBase64EncodeNoCRLF(const InputBuffer; const InputByteCount: Cardinal; out OutputBuffer);
procedure ALMimeBase64EncodeFullLines(const InputBuffer; const InputByteCount: Cardinal; out OutputBuffer);
function ALMimeBase64Decode(const InputBuffer; const InputBytesCount: Cardinal; out OutputBuffer): Cardinal;
function ALMimeBase64DecodePartial(const InputBuffer; const InputBytesCount: Cardinal; out OutputBuffer; var ByteBuffer: Cardinal; var ByteBufferSpace: Cardinal): Cardinal;
function ALMimeBase64DecodePartialEnd(out OutputBuffer; const ByteBuffer: Cardinal; const ByteBufferSpace: Cardinal): Cardinal;
{From indy}
procedure ALFillMimeContentTypeByExtList(AMIMEList : TStrings);
procedure ALFillExtByMimeContentTypeList(AMIMEList : TStrings);
Function ALGetDefaultFileExtFromMimeContentType(aContentType: String): String;
Function ALGetDefaultMIMEContentTypeFromExt(aExt: String): String;
{Mime content type list variable}
Var vAlMimeContentTypeByExtList: Tstrings; {.htm=text/html}
vAlExtbyMimeContentTypeList: Tstrings; {text/html=.htm}
implementation
Uses Registry,
inifiles,
alFcnString;
{--------------------------------------------}
type PALMimeBase64Byte4 = ^TALMimeBase64Byte4;
TALMimeBase64Byte4 = packed record
b1: Byte;
b2: Byte;
b3: Byte;
b4: Byte;
end;
PALMimeBase64Byte3 = ^TALMimeBase64Byte3;
TALMimeBase64Byte3 = packed record
b1: Byte;
b2: Byte;
b3: Byte;
end;
{-------------------------------------------------------------------------------}
{* Caution: For MimeEncodeStream and all other kinds of multi-buffered }
{* Mime encodings (i.e. Files etc.), BufferSize must be set to a multiple of 3 }
{* Even though the implementation of the Mime decoding routines below }
{* do not require a particular buffer size, they work fastest with sizes of }
{* multiples of four. The chosen size is a multiple of 3 and of 4 as well. }
{* The following numbers are, in addition, also divisible by 1024: }
{* $2400, $3000, $3C00, $4800, $5400, $6000, $6C00. }
const cALMime_Base64_Buffer_Size = $3000;
cALMime_Base64_Encoded_Line_Break = 76;
cALMime_Base64_Decoded_Line_Break = cALMime_Base64_Encoded_Line_Break div 4 * 3;
cALMime_Base64_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
);
cALMime_Base64_Pad_Char = Byte('=');
cAlMime_Base64_Decode_Table: array[Byte] of Cardinal = (
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 ALMimeBase64EncodeString(const S: AnsiString): AnsiString;
var L: Cardinal;
begin
if Pointer(S) <> nil then begin
L := PCardinal(Cardinal(S) - 4)^;
SetLength(Result, ALMimeBase64EncodedSize(L));
ALMimeBase64Encode(Pointer(S)^, L, Pointer(Result)^);
end
else Result := '';
end;
{***********************************************************************}
function ALMimeBase64EncodeStringNoCRLF(const S: AnsiString): AnsiString;
var L: Cardinal;
begin
if Pointer(S) <> nil then begin
L := PCardinal(Cardinal(S) - 4)^;
SetLength(Result, ALMimeBase64EncodedSizeNoCRLF(L));
ALMimeBase64EncodeNoCRLF(Pointer(S)^, L, Pointer(Result)^);
end
else Result := '';
end;
{*****************************************************************}
function ALMimeBase64DecodeString(const S: AnsiString): AnsiString;
var ByteBuffer, ByteBufferSpace: Cardinal;
L: Cardinal;
begin
if Pointer(S) <> nil then begin
L := PCardinal(Cardinal(S) - 4)^;
SetLength(Result, ALMimeBase64DecodedSize(L));
ByteBuffer := 0;
ByteBufferSpace := 4;
L := ALMimeBase64DecodePartial(Pointer(S)^, L, Pointer(Result)^, ByteBuffer, ByteBufferSpace);
Inc(L, ALMimeBase64DecodePartialEnd(Pointer(Cardinal(Result) + L)^, ByteBuffer, ByteBufferSpace));
SetLength(Result, L);
end
else Result := '';
end;
{******************************************************************************************}
procedure ALMimeBase64EncodeStream(const InputStream: TStream; const OutputStream: TStream);
var InputBuffer: array [0..CALMIME_Base64_BUFFER_SIZE - 1] of Byte;
OutputBuffer: array [0..((CALMIME_Base64_BUFFER_SIZE + 2) div 3) * 4 - 1] of Byte;
BytesRead: Integer;
begin
BytesRead := InputStream.Read(InputBuffer, SizeOf(InputBuffer));
while BytesRead > 0 do begin
ALMimeBase64Encode(InputBuffer, BytesRead, OutputBuffer);
OutputStream.Write(OutputBuffer, ALMimeBase64EncodedSize(BytesRead));
BytesRead := InputStream.Read(InputBuffer, SizeOf(InputBuffer));
end;
end;
{******************************************************************************************}
procedure ALMimeBase64DecodeStream(const InputStream: TStream; const OutputStream: TStream);
var ByteBuffer, ByteBufferSpace: Cardinal;
InputBuffer: array [0..(CALMIME_Base64_BUFFER_SIZE + 3) div 4 * 3 - 1] of Byte;
OutputBuffer: array [0..CALMIME_Base64_BUFFER_SIZE - 1] of Byte;
BytesRead: Integer;
begin
ByteBuffer := 0;
ByteBufferSpace := 4;
BytesRead := InputStream.Read(InputBuffer, SizeOf(InputBuffer));
while BytesRead > 0 do begin
OutputStream.Write(OutputBuffer, ALMimeBase64DecodePartial(InputBuffer, BytesRead, OutputBuffer, ByteBuffer, ByteBufferSpace));
BytesRead := InputStream.Read(InputBuffer, SizeOf(InputBuffer));
end;
OutputStream.Write(OutputBuffer, ALMimeBase64DecodePartialEnd(OutputBuffer, ByteBuffer, ByteBufferSpace));
end;
{********************************************************************}
function ALMimeBase64EncodedSize(const InputSize: Cardinal): Cardinal;
begin
if InputSize > 0 then Result := (InputSize + 2) div 3 * 4 + (InputSize - 1) div cALMIME_Base64_DECODED_LINE_BREAK * 2
else Result := InputSize;
end;
{**************************************************************************}
function ALMimeBase64EncodedSizeNoCRLF(const InputSize: Cardinal): Cardinal;
begin
Result := (InputSize + 2) div 3 * 4;
end;
{********************************************************************}
function ALMimeBase64DecodedSize(const InputSize: Cardinal): Cardinal;
begin
Result := (InputSize + 3) div 4 * 3;
end;
{************************************************************************************************}
procedure ALMimeBase64Encode(const InputBuffer; const InputByteCount: Cardinal; out OutputBuffer);
var IDelta, ODelta: Cardinal;
begin
ALMimeBase64EncodeFullLines(InputBuffer, InputByteCount, OutputBuffer);
IDelta := InputByteCount div CALMIME_Base64_DECODED_LINE_BREAK; // Number of lines processed so far.
ODelta := IDelta * (CALMIME_Base64_ENCODED_LINE_BREAK + 2);
IDelta := IDelta * CALMIME_Base64_DECODED_LINE_BREAK;
ALMimeBase64EncodeNoCRLF(Pointer(Cardinal(@InputBuffer) + IDelta)^, InputByteCount - IDelta, Pointer(Cardinal(@OutputBuffer) + ODelta)^);
end;
{*********************************************************************************************************}
procedure ALMimeBase64EncodeFullLines(const InputBuffer; const InputByteCount: Cardinal; out OutputBuffer);
var B, InnerLimit, OuterLimit: Cardinal;
InPtr: PALMimeBase64Byte3;
OutPtr: PALMimeBase64Byte4;
begin
{ Do we have enough input to encode a full line? }
if InputByteCount < CALMIME_Base64_DECODED_LINE_BREAK then Exit;
InPtr := @InputBuffer;
OutPtr := @OutputBuffer;
InnerLimit := Cardinal(InPtr);
Inc(InnerLimit, CALMIME_Base64_DECODED_LINE_BREAK);
OuterLimit := Cardinal(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 := CALMIME_Base64_ENCODE_TABLE[B and $3F];
B := B shr 6;
OutPtr^.b3 := CALMIME_Base64_ENCODE_TABLE[B and $3F];
B := B shr 6;
OutPtr^.b2 := CALMIME_Base64_ENCODE_TABLE[B and $3F];
B := B shr 6;
OutPtr^.b1 := CALMIME_Base64_ENCODE_TABLE[B];
Inc(OutPtr);
until Cardinal(InPtr) >= InnerLimit;
{ Write line break (CRLF). }
OutPtr^.b1 := 13;
OutPtr^.b2 := 10;
Inc(Cardinal(OutPtr), 2);
Inc(InnerLimit, CALMIME_Base64_DECODED_LINE_BREAK);
until InnerLimit > OuterLimit;
end;
{******************************************************************************************************}
procedure ALMimeBase64EncodeNoCRLF(const InputBuffer; const InputByteCount: Cardinal; out OutputBuffer);
var B, InnerLimit, OuterLimit: Cardinal;
InPtr: PALMimeBase64Byte3;
OutPtr: PALMimeBase64Byte4;
begin
if InputByteCount = 0 then Exit;
InPtr := @InputBuffer;
OutPtr := @OutputBuffer;
OuterLimit := InputByteCount div 3 * 3;
InnerLimit := Cardinal(InPtr);
Inc(InnerLimit, OuterLimit);
{ Last line loop. }
while Cardinal(InPtr) < 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 := CALMIME_Base64_ENCODE_TABLE[B and $3F];
B := B shr 6;
OutPtr^.b3 := CALMIME_Base64_ENCODE_TABLE[B and $3F];
B := B shr 6;
OutPtr^.b2 := CALMIME_Base64_ENCODE_TABLE[B and $3F];
B := B shr 6;
OutPtr^.b1 := CALMIME_Base64_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 := CALMIME_Base64_ENCODE_TABLE[B and $3F];
B := B shr 6;
OutPtr.b1 := CALMIME_Base64_ENCODE_TABLE[B];
OutPtr.b3 := CALMIME_Base64_PAD_CHAR; { Pad remaining 2 bytes. }
OutPtr.b4 := CALMIME_Base64_PAD_CHAR;
end;
2:
begin
B := InPtr^.b1;
B := B shl 8;
B := B or InPtr^.b2;
B := B shl 2;
OutPtr.b3 := CALMIME_Base64_ENCODE_TABLE[B and $3F];
B := B shr 6;
OutPtr.b2 := CALMIME_Base64_ENCODE_TABLE[B and $3F];
B := B shr 6;
OutPtr.b1 := CALMIME_Base64_ENCODE_TABLE[B];
OutPtr.b4 := CALMIME_Base64_PAD_CHAR; { Pad remaining byte. }
end;
end;
end;
{**********************************************************************************************************}
function ALMimeBase64Decode(const InputBuffer; const InputBytesCount: Cardinal; out OutputBuffer): Cardinal;
var ByteBuffer, ByteBufferSpace: Cardinal;
begin
ByteBuffer := 0;
ByteBufferSpace := 4;
Result := alMimeBase64DecodePartial(InputBuffer, InputBytesCount, OutputBuffer, ByteBuffer, ByteBufferSpace);
Inc(Result, alMimeBase64DecodePartialEnd(Pointer(Cardinal(@OutputBuffer) + Result)^, ByteBuffer, ByteBufferSpace));
end;
{**************************************************************************************************************************************************************************}
function ALMimeBase64DecodePartial(const InputBuffer; const InputBytesCount: Cardinal; out OutputBuffer; var ByteBuffer: Cardinal; var ByteBufferSpace: Cardinal): Cardinal;
var lByteBuffer, lByteBufferSpace, C: Cardinal;
InPtr, OuterLimit: ^Byte;
OutPtr: PALMimeBase64Byte3;
begin
if InputBytesCount > 0 then begin
InPtr := @InputBuffer;
Cardinal(OuterLimit) := Cardinal(InPtr) + InputBytesCount;
OutPtr := @OutputBuffer;
lByteBuffer := ByteBuffer;
lByteBufferSpace := ByteBufferSpace;
while InPtr <> OuterLimit do begin
{ Read from InputBuffer. }
C := CALMIME_Base64_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 := Cardinal(OutPtr) - Cardinal(@OutputBuffer);
end
else Result := 0;
end;
{*****************************************************************************************************************************}
function ALMimeBase64DecodePartialEnd(out OutputBuffer; const ByteBuffer: Cardinal; const ByteBufferSpace: Cardinal): Cardinal;
var lByteBuffer: Cardinal;
begin
case ByteBufferSpace of
1:
begin
lByteBuffer := ByteBuffer shr 2;
PALMimeBase64Byte3(@OutputBuffer)^.b2 := Byte(lByteBuffer);
lByteBuffer := lByteBuffer shr 8;
PALMimeBase64Byte3(@OutputBuffer)^.b1 := Byte(lByteBuffer);
Result := 2;
end;
2:
begin
lByteBuffer := ByteBuffer shr 4;
PALMimeBase64Byte3(@OutputBuffer)^.b1 := Byte(lByteBuffer);
Result := 1;
end;
else
Result := 0;
end;
end;
{*************************************************************}
procedure ALFillMimeContentTypeByExtList(AMIMEList : TStrings);
var reg: TRegistry;
KeyList: TStrings;
i: Integer;
aExt, aContentType: String;
begin
AMIMEList.Clear;
Reg := TRegistry.Create(KEY_READ);
try
KeyList := TStringList.create;
try
Reg.RootKey := HKEY_CLASSES_ROOT;
if Reg.OpenKeyReadOnly('\') then begin
Reg.GetKeyNames(KeyList);
Reg.CloseKey;
for i := 0 to KeyList.Count - 1 do begin
aExt := KeyList[i];
if (length(aExt) > 1) and (aExt[1] = '.') then begin
if reg.OpenKeyReadOnly('\' + aExt) then begin
aExt := Trim(aExt);
If (length(aExt) > 1) then begin
aContentType := trim(Reg.ReadString('Content Type'));
if aContentType <> '' then AMIMEList.Values[alLowerCase(aExt)] := AlLowerCase(aContentType);
end;
Reg.CloseKey;
end;
end;
end;
end;
finally
KeyList.Free;
end;
finally
reg.free;
end;
end;
{*************************************************************}
procedure ALFillExtByMimeContentTypeList(AMIMEList : TStrings);
var reg: TRegistry;
KeyList: TStrings;
i: Integer;
aExt, aContentType: String;
begin
AMIMEList.Clear;
Reg := TRegistry.Create(KEY_READ);
try
KeyList := TStringList.create;
try
Reg.RootKey := HKEY_CLASSES_ROOT;
if Reg.OpenKeyreadOnly('\MIME\Database\Content Type') then begin
Reg.GetKeyNames(KeyList);
Reg.CloseKey;
for i := 0 to KeyList.Count - 1 do begin
aContentType := KeyList[i];
If aContentType <> '' then begin
if Reg.OpenKeyreadOnly('\MIME\Database\Content Type\' + aContentType) then begin
aContenttype := trim(aContentType);
if aContentType <> '' then begin
aExt := reg.ReadString('Extension');
if aExt <> '' then begin
If (aExt[1] <> '.') then aExt := '.' + aExt;
AMIMEList.Values[alLowerCase(aContentType)] := AlLowerCase(aExt)
end;
end;
Reg.CloseKey;
end;
end;
end;
end;
finally
KeyList.Free;
end;
finally
reg.free;
end;
end;
{****************************************************************************}
Function ALGetDefaultFileExtFromMimeContentType(aContentType: String): String;
Var P: integer;
Index : Integer;
Begin
Result := '';
aContentType := ALLowerCase(aContentType);
P := AlPosEx(';',aContentType);
if (P > 0) then delete(aContentType,P,MaxInt);
aContentType := Trim(AContentType);
Index := vAlExtbyMimeContentTypeList.IndexOfName(aContentType);
if Index <> -1 then Result := vAlExtbyMimeContentTypeList.ValueFromIndex[Index];
end;
{****************************************************************}
Function ALGetDefaultMIMEContentTypeFromExt(aExt: String): String;
var Index : Integer;
LExt: string;
begin
LExt := AlLowerCase(trim(aExt));
If (LExt = '') or (LExt[1] <> '.') then LExt := '.' + LExt;
Index := vAlMimeContentTypeByExtList.IndexOfName(LExt);
if Index <> -1 then Result := vAlMimeContentTypeByExtList.ValueFromIndex[Index]
else Result := 'application/octet-stream';
end;
Initialization
vAlMimeContentTypeByExtList := ThashedStringList.Create;
vAlExtbyMimeContentTypeList := ThashedStringList.Create;
ALFillMimeContentTypeByExtList(vAlMimeContentTypeByExtList);
ALFillExtByMimeContentTypeList(vAlExtbyMimeContentTypeList);
finalization
vAlMimeContentTypeByExtList.Free;
vAlExtbyMimeContentTypeList.Free;
end.
|
unit Meteo;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, ComCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
ComboBox1: TComboBox;
Timer1: TTimer;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
public
{ Public declarations }
end;
//Здесь необходимо описать класс TMyThread:
TMyThread = class(TThread)
private
{ Private declarations }
protected
procedure Execute; override;
end;
var
Form1: TForm1;
MyThread: TMyThread;
ComHandle:THandle;
CurrentState:TComStat;
CodeError:Cardinal;
AvaibleBytes,RealRead:Cardinal;
DATA: array [0..1] of byte;
PData:^Pointer;
Buffer :PCommConfig;
Size: DWORD;
implementation
{$R *.dfm}
procedure WriteCOM(DATA_TO_WRITE:byte);
var nBytesWrite:Cardinal;
begin
WriteFile(ComHandle,DATA_TO_WRITE,1,nBytesWrite,nil);
end;
procedure TMyThread.Execute;
var it:integer;
begin
while(true) do
begin
for it := 0 to SizeOf(DATA) - 1 do DATA[it]:=0;
ClearCommError(ComHandle,CodeError,@CurrentState);
AvaibleBytes:=CurrentState.cbInQue;
if AvaibleBytes<>0 then
Begin
GetMem(PData,AvaibleBytes);
PData:=@DATA;
ReadFile(ComHandle,PData^,AvaibleBytes,RealRead,nil);
Form1.Memo1.Lines.Add(FloatToStr((DATA[1]*256 + DATA[0])/16)) ;
end;
sleep(500);
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var i:integer;
st:PWideChar;
begin
StringToWideChar(ComboBox1.Text,st,4);
st:=PWideChar(ComboBox1.Text);
ComHandle:=CreateFile(st,
GENERIC_READ or GENERIC_WRITE,
0,
nil,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0);
if ComHandle=INVALID_HANDLE_VALUE then
begin
MessageDLG('Ошибка открытия порта!',mtError,[mbOK],0);
Exit;
end;
GetMem(Buffer,SizeOf(TCommConfig));
Size:=0;
GetCommConfig(ComHandle,Buffer^,Size);
FreeMem(Buffer,SizeOf(TCommConfig));
GetMem(Buffer,Size);
GetCommConfig(ComHandle,Buffer^,Size);
Buffer^.dcb.BaudRate:=9600;
Buffer^.dcb.Parity:=NOPARITY;
Buffer^.dcb.StopBits:=ONESTOPBIT;
Buffer^.dcb.ByteSize:=8;
SetCommConfig(ComHandle,Buffer^,Size);
FreeMem(Buffer,Size);
PurgeComm(ComHandle,PURGE_RXCLEAR);
for i := 0 to SizeOf(DATA) - 1 do DATA[i]:=0;
MyThread:=TMyThread.Create(False);
MyThread.Priority:=tpNormal;
Memo1.Lines.Add('OK');
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
Form1.Timer1.Enabled:=False;
if ComHandle <> null then CloseHandle(ComHandle);
end;
end.
|
unit rtti_idebinder_iBindings;
interface
uses
rtti_broker_iBroker, Controls;
type
{ IRBBinderContext }
IRBBinderContext = interface
['{39F9470D-08ED-49CB-B0F7-2E11ED80316C}']
function GetDataQuery: IRBDataQuery;
function GetDataStore: IRBStore;
property DataQuery: IRBDataQuery read GetDataQuery;
property DataStore: IRBStore read GetDataStore;
end;
{ IRBDataBinder }
IRBDataBinder = interface
['{015ECE02-6F9E-4071-BDCE-63BD11F6FAD9}']
procedure Bind(AContainer: TWinControl; const AData: IRBData;
const ADataQuery: IRBDataQuery);
procedure DataChange;
function GetData: IRBData;
procedure SetData(AValue: IRBData);
property AData: IRBData read GetData write SetData;
end;
IRBTallyBinder = interface
['{15291FE4-A0AC-11E3-82F7-08002721C44F}']
procedure Bind(const AListControl: TWinControl; const AContext: IRBBinderContext;
const AClass: TClass);
procedure Reload;
function GetCurrentData: IRBData;
property CurrentData: IRBData read GetCurrentData;
end;
IRBBehavioralBinder = interface
['{8FA26A2F-57D6-44FA-B824-EACAC24E5FA3}']
procedure Bind(AContainer: TWinControl);
end;
IRBDesigner = interface
['{4E3E03A4-B21F-4194-B7A4-063B31038D4B}']
procedure Bind(AContainer: TWinControl; const AStore: IRBStore; const AFactory: IRBFactory;
const ADataQuery: IRBDataQuery; const ACtlClasses: IRBPersistClassRegister);
end;
implementation
end.
|
unit pSHHighlighter;
{$I SynEdit.inc}
interface
uses
{$IFDEF SYN_CLX}
Types,
QGraphics,
QSynEditTypes,
QSynEditHighlighter,
QSynHighlighterHashEntries,
{$ELSE}
Graphics,
Registry,
SynEditTypes,
SynEditHighlighter,
SynHighlighterHashEntries,
{$ENDIF}
SysUtils,
Classes,
pSHIntf;
const
SYNS_AttrWrongSymbol = 'Wrong Symbol'; //pavel
type
PIdentifierTable = ^TIdentifierTable;
TIdentifierTable = array[Char] of ByteBool;
PHashTable = ^THashTable;
THashTable = array[Char] of Integer;
type
TpSHHighlighter = class(TSynCustomHighlighter)
private
fRange: TRangeState;
fLine: PChar;
fLineNumber: Integer;
fProcTable: array[#0..#255] of TProcTableProc;
Run: LongInt;
fStringLen: Integer;
fToIdent: PChar;
fTokenPos: Integer;
fTokenID: TtkTokenKind;
fKeywords: TSynHashEntryList;
fDialect: TSQLDialect;
fSubDialect: TSQLSubDialect;
fCommentAttri: TSynHighlighterAttributes;
fDataTypeAttri: TSynHighlighterAttributes;
fDefaultPackageAttri: TSynHighlighterAttributes; // DJLP 2000-08-11
fExceptionAttri: TSynHighlighterAttributes;
fFunctionAttri: TSynHighlighterAttributes;
fIdentifierAttri: TSynHighlighterAttributes;
fKeyAttri: TSynHighlighterAttributes;
fNumberAttri: TSynHighlighterAttributes;
fPLSQLAttri: TSynHighlighterAttributes; // DJLP 2000-08-11
fSpaceAttri: TSynHighlighterAttributes;
fSQLPlusAttri: TSynHighlighterAttributes; // DJLP 2000-09-05
fStringAttri: TSynHighlighterAttributes;
fSymbolAttri: TSynHighlighterAttributes;
fTableNameAttri: TSynHighlighterAttributes;
fVariableAttri: TSynHighlighterAttributes;
fWrongSymbolAttri: TSynHighlighterAttributes; //pavel
fIdentifiersPtr: PIdentifierTable;
fmHashTablePtr: PHashTable;
FObjectNamesManager: IpSHObjectNamesManager;
FKeywordsManager: IpSHKeywordsManager;
fCustomStringsAttri: TSynHighlighterAttributes; //pavel
function KeyHash(ToHash: PChar): Integer;
function KeyComp(const aKey: string): Boolean;
procedure AndSymbolProc;
procedure AsciiCharProc;
procedure CRProc;
procedure EqualProc;
procedure GreaterProc;
procedure IdentProc;
procedure LFProc;
procedure LowerProc;
procedure MinusProc;
procedure NullProc;
procedure NumberProc;
procedure OrSymbolProc;
procedure PlusProc;
procedure SlashProc;
procedure SpaceProc;
procedure StringProc;
procedure SymbolProc;
procedure SymbolAssignProc;
procedure VariableProc;
procedure UnknownProc;
procedure AnsiCProc;
function IdentKind(MayBe: PChar): TtkTokenKind;
procedure MakeMethodTables;
procedure DoAddKeyword(AKeyword: string; AKind: integer);
procedure EnumerateKeywordsInternal(AKind: integer; KeywordList: string);
procedure SetDialect(Value: TSQLDialect);
procedure InitializeKeywordLists;
procedure SetSubDialect(const Value: TSQLSubDialect);
procedure SetKeywordsManager(const Value: IpSHKeywordsManager);
protected
function GetIdentChars: TSynIdentChars; override;
function GetSampleSource : String; override;
public
{$IFNDEF SYN_CPPB_1} class {$ENDIF}
function GetLanguageName: string; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
function GetDefaultAttribute(Index: integer): TSynHighlighterAttributes;
override;
function GetEol: Boolean; override;
function GetRange: Pointer; override;
function GetToken: string; override;
function GetTokenAttribute: TSynHighlighterAttributes; override;
function GetTokenID: TtkTokenKind;
function GetTokenKind: integer; override;
function GetTokenPos: Integer; override;
procedure Next; override;
procedure ResetRange; override;
procedure SetLine(NewValue: string; LineNumber: Integer); override;
procedure SetRange(Value: Pointer); override;
property ObjectNamesManager: IpSHObjectNamesManager
read FObjectNamesManager write FObjectNamesManager;
property KeywordsManager: IpSHKeywordsManager read FKeywordsManager
write SetKeywordsManager;
published
property CommentAttri: TSynHighlighterAttributes read fCommentAttri
write fCommentAttri;
property CustomStringsAttri: TSynHighlighterAttributes read fCustomStringsAttri
write fCustomStringsAttri;
property DataTypeAttri: TSynHighlighterAttributes read fDataTypeAttri
write fDataTypeAttri;
property DefaultPackageAttri: TSynHighlighterAttributes // DJLP 2000-08-11
read fDefaultPackageAttri write fDefaultPackageAttri;
property ExceptionAttri: TSynHighlighterAttributes read fExceptionAttri
write fExceptionAttri;
property FunctionAttri: TSynHighlighterAttributes read fFunctionAttri
write fFunctionAttri;
property IdentifierAttri: TSynHighlighterAttributes read fIdentifierAttri
write fIdentifierAttri;
property KeyAttri: TSynHighlighterAttributes read fKeyAttri write fKeyAttri;
property NumberAttri: TSynHighlighterAttributes read fNumberAttri
write fNumberAttri;
property PLSQLAttri: TSynHighlighterAttributes read fPLSQLAttri // DJLP 2000-08-11
write fPLSQLAttri;
property SpaceAttri: TSynHighlighterAttributes read fSpaceAttri
write fSpaceAttri;
property SQLPlusAttri: TSynHighlighterAttributes read fSQLPlusAttri // DJLP 2000-09-05
write fSQLPlusAttri;
property StringAttri: TSynHighlighterAttributes read fStringAttri
write fStringAttri;
property SymbolAttri: TSynHighlighterAttributes read fSymbolAttri
write fSymbolAttri;
property TableNameAttri: TSynHighlighterAttributes read fTableNameAttri
write fTableNameAttri;
property WrongSymbolAttri: TSynHighlighterAttributes read fWrongSymbolAttri //pavel
write fWrongSymbolAttri; //pavel
property VariableAttri: TSynHighlighterAttributes read fVariableAttri
write fVariableAttri;
property SQLDialect: TSQLDialect read fDialect write SetDialect;
property SQLSubDialect: TSQLSubDialect read fSubDialect write SetSubDialect;
end;
implementation
uses
{$IFDEF SYN_CLX}
QSynEditStrConst;
{$ELSE}
SynEditStrConst;
{$ENDIF}
var
Identifiers: TIdentifierTable;
mHashTable: THashTable;
IdentifiersMSSQL7: TIdentifierTable;
mHashTableMSSQL7: THashTable;
procedure MakeIdentTable;
var
c: char;
begin
FillChar(Identifiers, SizeOf(Identifiers), 0);
for c := 'a' to 'z' do
Identifiers[c] := TRUE;
for c := 'A' to 'Z' do
Identifiers[c] := TRUE;
for c := '0' to '9' do
Identifiers[c] := TRUE;
Identifiers['_'] := TRUE;
// Identifiers['#'] := TRUE; //Pavel - для интербэйса это не так, правка в KeyHash // DJLP 2000-09-05
Identifiers['$'] := TRUE; // DJLP 2000-09-05
FillChar(mHashTable, SizeOf(mHashTable), 0);
mHashTable['_'] := 1;
for c := 'a' to 'z' do
mHashTable[c] := 2 + Ord(c) - Ord('a');
for c := 'A' to 'Z' do
mHashTable[c] := 2 + Ord(c) - Ord('A');
Move(Identifiers, IdentifiersMSSQL7, SizeOf(Identifiers));
Move(mHashTable, mHashTableMSSQL7, SizeOf(mHashTable));
IdentifiersMSSQL7['@'] := TRUE;
mHashTableMSSQL7['@'] := mHashTableMSSQL7['Z'] + 1;
end;
function TpSHHighlighter.KeyHash(ToHash: PChar): Integer;
begin
Result := 0;
while fIdentifiersPtr[ToHash^] or ((SQLDialect <> sqlInterbase) and (ToHash^ = '#')) do begin
// эта правка была уместна, когда использовалось свойство TableNames
// or ((SQLDialect = sqlInterbase6) and (ToHash^ = ' ') and //pavel
// (fTokenID = tkString))) do //pavel
{$IFOPT Q-}
Result := 2 * Result + fmHashTablePtr[ToHash^];
{$ELSE}
Result := (2 * Result + fmHashTablePtr[ToHash^]) and $FFFFFF;
{$ENDIF}
inc(ToHash);
end;
Result := Result and $FF; // 255
fStringLen := ToHash - fToIdent;
end;
function TpSHHighlighter.KeyComp(const aKey: string): Boolean;
var
i: integer;
pKey1, pKey2: PChar;
begin
pKey1 := fToIdent;
// Note: fStringLen is always > 0 !
pKey2 := pointer(aKey);
for i := 1 to fStringLen do
begin
// if mHashTable[pKey1^] <> mHashTable[pKey2^] then
if fmHashTablePtr[pKey1^] <> fmHashTablePtr[pKey2^] then //pavel - непонятка, однако
begin
Result := FALSE;
exit;
end;
Inc(pKey1);
Inc(pKey2);
end;
Result := TRUE;
end;
procedure TpSHHighlighter.AndSymbolProc;
begin
fTokenID := tkSymbol;
Inc(Run);
if fLine[Run] in ['=', '&'] then Inc(Run);
end;
procedure TpSHHighlighter.AsciiCharProc;
begin
// Oracle SQL allows strings to go over multiple lines
if fLine[Run] = #0 then
NullProc
else begin
fTokenID := tkString;
// else it's end of multiline string
if SQLDialect <> sqlMySql then begin
if (Run > 0) or (fRange <> rsString) or (fLine[Run] <> #39) then begin
fRange := rsString;
repeat
Inc(Run);
until fLine[Run] in [#0, #10, #13, #39];
end;
if fLine[Run] = #39 then begin
Inc(Run);
fRange := rsUnknown;
end;
end
else begin
if (Run > 0) or (fRange <> rsString) or ((fLine[Run] <> #39) and (fLine[Run-1] <> '\')) then begin
fRange := rsString;
repeat
if (fLine[Run] <> '\') and (fLine[Run+1] = #39) then begin
Inc(Run);
break;
end;
Inc(Run);
until fLine[Run] in [#0, #10, #13];
end;
if (fLine[Run] = #39) and not(fLine[Run-1] = '\') then begin
Inc(Run);
fRange := rsUnknown;
end;
end;
end;
end;
procedure TpSHHighlighter.CRProc;
begin
fTokenID := tkSpace;
Inc(Run);
if fLine[Run] = #10 then Inc(Run);
end;
procedure TpSHHighlighter.EqualProc;
begin
fTokenID := tkSymbol;
Inc(Run);
if fLine[Run] in ['=', '>'] then Inc(Run);
end;
procedure TpSHHighlighter.GreaterProc;
begin
fTokenID := tkSymbol;
Inc(Run);
if fLine[Run] in ['=', '>'] then Inc(Run);
end;
procedure TpSHHighlighter.IdentProc;
begin
fTokenID := IdentKind((fLine + Run));
if (Run > 0) and ((fLine + Run - 1)^ = '.' ) then
fTokenID := tkIdentifier;
inc(Run, fStringLen);
{begin} // DJLP 2000-08-11
{
// какое-то явное даунение тов. DJLP //pavel
if fTokenID = tkComment then begin
while not (fLine[Run] in [#0, #10, #13]) do
Inc(Run);
end else
}
{end} // DJLP 2000-08-11
while fIdentifiersPtr[fLine[Run]] do inc(Run);
end;
procedure TpSHHighlighter.LFProc;
begin
fTokenID := tkSpace;
inc(Run);
end;
procedure TpSHHighlighter.LowerProc;
begin
fTokenID := tkSymbol;
Inc(Run);
case fLine[Run] of
'=': Inc(Run);
'<': begin
Inc(Run);
if fLine[Run] = '=' then Inc(Run);
end;
end;
end;
procedure TpSHHighlighter.MinusProc;
begin
Inc(Run);
if fLine[Run] = '-' then begin
fTokenID := tkComment;
repeat
Inc(Run);
until fLine[Run] in [#0, #10, #13];
end else
fTokenID := tkSymbol;
end;
procedure TpSHHighlighter.NullProc;
begin
fTokenID := tkNull;
end;
procedure TpSHHighlighter.NumberProc;
begin
inc(Run);
fTokenID := tkNumber;
while FLine[Run] in ['0'..'9', '.', '-'] do begin
case FLine[Run] of
'.':
if FLine[Run + 1] = '.' then break;
end;
inc(Run);
end;
end;
procedure TpSHHighlighter.OrSymbolProc;
begin
fTokenID := tkSymbol;
Inc(Run);
if fLine[Run] in ['=', '|'] then Inc(Run);
end;
procedure TpSHHighlighter.PlusProc;
begin
fTokenID := tkSymbol;
Inc(Run);
if fLine[Run] in ['=', '+'] then Inc(Run);
end;
procedure TpSHHighlighter.SlashProc;
begin
Inc(Run);
case fLine[Run] of
'*':
begin
fRange := rsComment;
fTokenID := tkComment;
repeat
Inc(Run);
if (fLine[Run] = '*') and (fLine[Run + 1] = '/') then begin
fRange := rsUnknown;
Inc(Run, 2);
break;
end;
until fLine[Run] in [#0, #10, #13];
end;
'=':
begin
Inc(Run);
fTokenID := tkSymbol;
end;
else
fTokenID := tkSymbol;
end;
end;
procedure TpSHHighlighter.SpaceProc;
begin
fTokenID := tkSpace;
repeat
Inc(Run);
until (fLine[Run] > #32) or (fLine[Run] in [#0, #10, #13]);
end;
procedure TpSHHighlighter.StringProc;
begin
fTokenID := tkString;
Inc(Run);
while not (fLine[Run] in [#0, #10, #13]) do begin
case fLine[Run] of
'\': if fLine[Run + 1] = #34 then
Inc(Run);
#34: if fLine[Run + 1] <> #34 then
begin
Inc(Run);
break;
end;
end;
Inc(Run);
end;
if (SQLDialect = sqlInterbase) and (SQLSubDialect >= ibdInterBase6) then
if Assigned(FObjectNamesManager) then
FObjectNamesManager.LinkSearchNotify(self, fLine + fTokenPos,
fTokenPos, Run - fTokenPos, fTokenID);
end;
procedure TpSHHighlighter.SymbolProc;
begin
Inc(Run);
fTokenID := tkSymbol;
end;
procedure TpSHHighlighter.SymbolAssignProc;
begin
fTokenID := tkSymbol;
Inc(Run);
if fLine[Run] = '=' then Inc(Run);
end;
procedure TpSHHighlighter.VariableProc;
var
i: integer;
begin
// MS SQL 7 uses @@ to indicate system functions/variables
if (SQLDialect = sqlMSSQL) and (fLine[Run] = '@') and (fLine[Run + 1] = '@')
then
IdentProc
{begin} //JDR 2000-25-2000
else if (SQLDialect in [sqlMySql, sqlOracle, sqlInterbase]) and (fLine[Run] = '@') then //pavel
SymbolProc
{end} //JDR 2000-25-2000
// Oracle uses the ':' character to indicate bind variables
{begin} //JJV 2000-11-16
// Ingres II also uses the ':' character to indicate variables
// Interbase also uses the ':' character to indicate variables in SP //pavel
else
if not (SQLDialect in [sqlOracle, sqlIngres, sqlInterbase]) and //pavel
(fLine[Run] = ':') then //pavel
{end} //JJV 2000-11-16
SymbolProc
else begin
fTokenID := tkVariable;
i := Run;
repeat
Inc(i);
until not (fIdentifiersPtr[fLine[i]]);
Run := i;
end;
end;
procedure TpSHHighlighter.UnknownProc;
begin
if (SQLDialect = sqlMySql) and (fLine[Run] = '#') and (Run = 0) then //DDH Changes from Tonci Grgin for MYSQL
begin
fTokenID := tkComment;
fRange := rsComment;
end else begin
{$IFDEF SYN_MBCSSUPPORT}
if FLine[Run] in LeadBytes then
Inc(Run,2)
else
{$ENDIF}
inc(Run);
fTokenID := tkUnknown;
end;
end;
procedure TpSHHighlighter.AnsiCProc;
begin
case fLine[Run] of
#0: NullProc;
#10: LFProc;
#13: CRProc;
else begin
fTokenID := tkComment;
if (SQLDialect = sqlMySql) and (fLine[Run] = '#') then begin //DDH Changes from Tonci Grgin for MYSQL
repeat
Inc(Run);
until fLine[Run] in [#0, #10, #13];
fRange := rsUnknown;
end
else begin
repeat
if (fLine[Run] = '*') and (fLine[Run + 1] = '/') then begin
fRange := rsUnknown;
Inc(Run, 2);
break;
end;
Inc(Run);
until fLine[Run] in [#0, #10, #13];
end;
end;
end;
end;
function TpSHHighlighter.IdentKind(MayBe: PChar): TtkTokenKind;
var
Entry: TSynHashEntry;
begin
fToIdent := MayBe;
Entry := fKeywords[KeyHash(MayBe)];
while Assigned(Entry) do begin
if Entry.KeywordLen > fStringLen then
break
else if Entry.KeywordLen = fStringLen then
if KeyComp(Entry.Keyword) then begin
Result := TtkTokenKind(Entry.Kind);
exit;
end;
Entry := Entry.Next;
end;
Result := tkIdentifier; //pavel
if Assigned(FObjectNamesManager) then //pavel
FObjectNamesManager.LinkSearchNotify(self, MayBe, Run, //pavel
fStringLen, Result); //pavel
// Result := tkIdentifier; //pavel
end;
procedure TpSHHighlighter.MakeMethodTables;
var
I: Char;
begin
for I := #0 to #255 do
case I of
#0: fProcTable[I] := NullProc;
#10: fProcTable[I] := LFProc;
#13: fProcTable[I] := CRProc;
#39: fProcTable[I] := AsciiCharProc;
'=': fProcTable[I] := EqualProc;
'>': fProcTable[I] := GreaterProc;
'<': fProcTable[I] := LowerProc;
'-': fProcTable[I] := MinusProc;
'|': fProcTable[I] := OrSymbolProc;
'+': fProcTable[I] := PlusProc;
'/': fProcTable[I] := SlashProc;
'&': fProcTable[I] := AndSymbolProc;
#34: fProcTable[I] := StringProc;
':', '@':
fProcTable[I] := VariableProc;
'A'..'Z', 'a'..'z', '_':
fProcTable[I] := IdentProc;
'0'..'9':
fProcTable[I] := NumberProc;
#1..#9, #11, #12, #14..#32:
fProcTable[I] := SpaceProc;
'^', '%', '*', '!':
fProcTable[I] := SymbolAssignProc;
'{', '}', ',','.',';', '?', '(', ')', '[', ']', '~', '#':
fProcTable[I] := SymbolProc;
else
fProcTable[I] := UnknownProc;
end;
end;
procedure TpSHHighlighter.DoAddKeyword(AKeyword: string; AKind: integer);
var
HashValue: integer;
begin
HashValue := KeyHash(PChar(AKeyword));
fKeywords[HashValue] := TSynHashEntry.Create(AKeyword, AKind);
end;
procedure TpSHHighlighter.EnumerateKeywordsInternal(AKind: integer;
KeywordList: string);
begin
EnumerateKeywords(AKind, KeywordList, IdentChars + [' '], DoAddKeyword);
end;
procedure TpSHHighlighter.SetDialect(Value: TSQLDialect);
begin
if (Value <> fDialect) then
begin
fDialect := Value;
InitializeKeywordLists;
end;
end;
procedure TpSHHighlighter.InitializeKeywordLists;
begin
fKeywords.Clear;
if (fDialect in [sqlMSSQL, sqlMSSQL2K]) then
begin
fIdentifiersPtr := @IdentifiersMSSQL7;
fmHashTablePtr := @mHashTableMSSQL7;
end else begin
fIdentifiersPtr := @Identifiers;
fmHashTablePtr := @mHashTable;
end;
if KeywordsManager <> nil then
begin
KeywordsManager.InitializeKeywordLists(Self, SQLSubDialect,
EnumerateKeywordsInternal);
end;
DefHighlightChange(Self);
end;
procedure TpSHHighlighter.SetSubDialect(const Value: TSQLSubDialect);
begin
if (Value <> fSubDialect) then
begin
fSubDialect := Value;
InitializeKeywordLists;
end;
end;
procedure TpSHHighlighter.SetKeywordsManager(
const Value: IpSHKeywordsManager);
begin
if (FKeywordsManager <> Value) then
begin
if Assigned(FKeywordsManager) then
FKeywordsManager.RemoveHighlighter(Self);
FKeywordsManager := Value;
if Assigned(FKeywordsManager) then
FKeywordsManager.AddHighlighter(Self);
InitializeKeywordLists;
end;
end;
function TpSHHighlighter.GetIdentChars: TSynIdentChars;
begin
Result := TSynValidStringChars;
if (fDialect = sqlMSSQL) or (fDialect = sqlMSSQL2K) then
Include(Result, '@')
{begin} // DJLP 2000-08-11
else if fDialect = sqlOracle then begin
Include(Result, '#');
Include(Result, '$');
end
else if fDialect = sqlInterbase then begin //pavel
Include(Result, '$');
end;
{end} // DJLP 2000-08-11
end;
function TpSHHighlighter.GetSampleSource: String;
begin
Result:= '';
case fDialect of
sqlStandard:
Result := '-- ansi sql sample source'#13#10 +
'select name , region'#13#10 +
'from cia'#13#10 +
'where area < 2000'#13#10 +
'and gdp > 5000000000';
sqlInterbase:
Result := '/* Interbase sample source */'#13#10 +
'SET TERM !! ;'#13#10 +
#13#10 +
'CREATE PROCEDURE HelloWorld(P_MSG VARCHAR(80)) AS'#13#10 +
'BEGIN'#13#10 +
' EXECUTE PROCEDURE WRITELN(:P_MSG);'#13#10 +
'END !!'#13#10 +
#13#10 +
'SET TERM ; !!';
sqlMySQL:
Result := '/* MySQL sample source*/'#13#10 +
'SET @variable= { 1 }'#13#10 +
#13#10 +
'CREATE TABLE sample ('#13#10 +
' id INT NOT NULL,'#13#10 +
' first_name CHAR(30) NOT NULL,'#13#10 +
' PRIMARY KEY (id),'#13#10 +
' INDEX name (first_name));'#13#10 +
#13#10 +
'SELECT DATE_ADD("1997-12-31 23:59:59",'#13#10 +
' INTERVAL 1 SECOND);'#13#10 +
#13#10 +
'# End of sample';
sqlOracle:
Result := 'PROMPT Oracle sample source'#13#10 +
'declare'#13#10 +
' x varchar2(2000);'#13#10 +
'begin -- Show some text here'#13#10 +
' select to_char(count(*)) into x'#13#10 +
' from tab;'#13#10 +
#13#10 +
' dbms_output.put_line(''Hello World: '' || x);'#13#10 +
'exception'#13#10 +
' when others then'#13#10 +
' null;'#13#10 +
'end;';
sqlSybase:
Result := '/* SyBase example source */'#13#10 +
'declare @Integer int'#13#10 +
#13#10 +
'/* Good for positive numbers only. */'#13#10 +
'select @Integer = 1000'#13#10 +
#13#10 +
'select "Positives Only" ='#13#10 +
' right(replicate("0",12) + '#13#10 +
' convert(varchar, @Integer),12)'#13#10 +
#13#10 +
'/* Good for positive and negative numbers. */'#13#10 +
'select @Integer = -1000'#13#10 +
#13#10 +
'select "Both Signs" ='#13#10 +
' substring( "- +", (sign(@Integer) + 2), 1) +'#13#10 +
' right(replicate("0",12) + '#13#10 +
' convert(varchar, abs(@Integer)),12)'#13#10 +
#13#10 +
'select @Integer = 1000'#13#10 +
#13#10 +
'select "Both Signs" ='#13#10 +
' substring( "- +", (sign(@Integer) + 2), 1) +'#13#10 +
' right(replicate("0",12) + '#13#10 +
' convert(varchar, abs(@Integer)),12)'#13#10 +
#13#10 +
'go';
sqlIngres:
Result := '/* Ingres example source */'#13#10 +
'DELETE'#13#10 +
'FROM t1'#13#10 +
'WHERE EXISTS'#13#10 +
'(SELECT t2.column1, t2.column2'#13#10 +
'FROM t2'#13#10 +
'WHERE t1.column1 = t2.column1 and'#13#10 +
't1.column2 = t2.column2)';
sqlMSSQL:
Result := '/* SQL Server 7 example source */'#13#10 +
'SET QUOTED_IDENTIFIER OFF'#13#10 +
'GO'#13#10 +
'SET ANSI_NULLS OFF'#13#10 +
'GO'#13#10 +
#13#10 +
'/* Object: Stored Procedure dbo.sp_PPQInsertOrder */'#13#10 +
'CREATE PROCEDURE sp_PPQInsertOrder'#13#10 +
' @Name varchar(25),'#13#10 +
' @Address varchar(255),'#13#10 +
' @ZipCode varchar(15)'#13#10 +
'As'#13#10 +
' INSERT INTO PPQOrders(Name, Address, ZipCode, OrderDate)'#13#10 +
' VALUES (@Name, @Address, @ZipCode, GetDate())'#13#10 +
#13#10 +
' SELECT SCOPE_IDENTITY()'#13#10 +
'GO';
sqlMSSQL2K:
Result := '/* SQL Server2000 example source */'#13#10 +
'SET QUOTED_IDENTIFIER OFF'#13#10 +
'GO'#13#10 +
'SET ANSI_NULLS OFF'#13#10 +
'GO'#13#10 +
#13#10 +
'/* Object: Stored Procedure dbo.sp_PPQInsertOrder */'#13#10 +
'CREATE PROCEDURE sp_PPQInsertOrder'#13#10 +
' @Name varchar(25),'#13#10 +
' @Address varchar(255),'#13#10 +
' @ZipCode varchar(15)'#13#10 +
'As'#13#10 +
' INSERT INTO PPQOrders(Name, Address, ZipCode, OrderDate)'#13#10 +
' VALUES (@Name, @Address, @ZipCode, GetDate())'#13#10 +
#13#10 +
' SELECT SCOPE_IDENTITY()'#13#10 +
'GO';
end;
end;
{$IFNDEF SYN_CPPB_1} class {$ENDIF}
function TpSHHighlighter.GetLanguageName: string;
begin
Result := SYNS_LangSQL;
end;
constructor TpSHHighlighter.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
fKeywords := TSynHashEntryList.Create;
fCommentAttri := TSynHighlighterAttributes.Create(SYNS_AttrComment);
fCommentAttri.Style := [fsItalic];
AddAttribute(fCommentAttri);
fCustomStringsAttri := TSynHighlighterAttributes.Create(SYNS_AttrDataType);
fCustomStringsAttri.Style := [fsBold];
fDataTypeAttri := TSynHighlighterAttributes.Create(SYNS_AttrDataType);
fDataTypeAttri.Style := [fsBold];
AddAttribute(fDataTypeAttri);
{begin} // DJLP 2000-08-11
fDefaultPackageAttri :=
TSynHighlighterAttributes.Create(SYNS_AttrDefaultPackage);
fDefaultPackageAttri.Style := [fsBold];
AddAttribute(fDefaultPackageAttri);
{end} // DJLP 2000-08-11
fExceptionAttri := TSynHighlighterAttributes.Create(SYNS_AttrException);
fExceptionAttri.Style := [fsItalic];
AddAttribute(fExceptionAttri);
fFunctionAttri := TSynHighlighterAttributes.Create(SYNS_AttrFunction);
fFunctionAttri.Style := [fsBold];
AddAttribute(fFunctionAttri);
fIdentifierAttri := TSynHighlighterAttributes.Create(SYNS_AttrIdentifier);
AddAttribute(fIdentifierAttri);
fKeyAttri := TSynHighlighterAttributes.Create(SYNS_AttrReservedWord);
fKeyAttri.Style := [fsBold];
AddAttribute(fKeyAttri);
fNumberAttri := TSynHighlighterAttributes.Create(SYNS_AttrNumber);
AddAttribute(fNumberAttri);
{begin} // DJLP 2000-08-11
fPLSQLAttri := TSynHighlighterAttributes.Create(SYNS_AttrPLSQL);
fPLSQLAttri.Style := [fsBold];
AddAttribute(fPLSQLAttri);
{end} // DJLP 2000-08-11
fSpaceAttri := TSynHighlighterAttributes.Create(SYNS_AttrSpace);
AddAttribute(fSpaceAttri);
{begin} // DJLP 2000-09-05
fSQLPlusAttri:=TSynHighlighterAttributes.Create(SYNS_AttrSQLPlus);
fSQLPlusAttri.Style := [fsBold];
AddAttribute(fSQLPlusAttri);
{end} // DJLP 2000-09-05
fStringAttri := TSynHighlighterAttributes.Create(SYNS_Attrstring);
AddAttribute(fStringAttri);
fSymbolAttri := TSynHighlighterAttributes.Create(SYNS_AttrSymbol);
AddAttribute(fSymbolAttri);
fTableNameAttri := TSynHighlighterAttributes.Create(SYNS_AttrTableName);
AddAttribute(fTableNameAttri);
fWrongSymbolAttri := TSynHighlighterAttributes.Create(SYNS_AttrWrongSymbol); //pavel
AddAttribute(fWrongSymbolAttri); //pavel
fVariableAttri := TSynHighlighterAttributes.Create(SYNS_AttrVariable);
AddAttribute(fVariableAttri);
SetAttributesOnChange(DefHighlightChange);
MakeMethodTables;
fDefaultFilter := SYNS_FilterSQL;
fRange := rsUnknown;
fDialect := sqlStandard;
SQLDialect := sqlSybase;
end;
destructor TpSHHighlighter.Destroy;
begin
fKeywords.Free;
inherited Destroy;
end;
procedure TpSHHighlighter.Assign(Source: TPersistent);
begin
inherited Assign(Source);
if (Source is TpSHHighlighter) then
SQLDialect := TpSHHighlighter(Source).SQLDialect;
end;
function TpSHHighlighter.GetDefaultAttribute(Index: integer):
TSynHighlighterAttributes;
begin
case Index of
SYN_ATTR_COMMENT: Result := fCommentAttri;
SYN_ATTR_IDENTIFIER: Result := fIdentifierAttri;
SYN_ATTR_KEYWORD: Result := fKeyAttri;
SYN_ATTR_STRING: Result := fStringAttri;
SYN_ATTR_WHITESPACE: Result := fSpaceAttri;
SYN_ATTR_SYMBOL: Result := fSymbolAttri;
else
Result := nil;
end;
end;
function TpSHHighlighter.GetEol: Boolean;
begin
Result := fTokenID = tkNull
end;
function TpSHHighlighter.GetRange: Pointer;
begin
Result := Pointer(fRange);
end;
function TpSHHighlighter.GetToken: string;
var
Len: LongInt;
begin
Len := Run - fTokenPos;
SetString(Result, (FLine + fTokenPos), Len);
end;
function TpSHHighlighter.GetTokenAttribute: TSynHighlighterAttributes;
begin
case GetTokenID of
tkComment: Result := fCommentAttri;
tkDatatype: Result := fDataTypeAttri;
tkDefaultPackage: Result := fDefaultPackageAttri; // DJLP 2000-08-11
tkException: Result := fExceptionAttri;
tkFunction: Result := fFunctionAttri;
tkIdentifier: Result := fIdentifierAttri;
tkKey: Result := fKeyAttri;
tkNumber: Result := fNumberAttri;
tkPLSQL: Result := fPLSQLAttri; // DJLP 2000-08-11
tkSpace: Result := fSpaceAttri;
tkSQLPlus: Result := fSQLPlusAttri; // DJLP 2000-08-11
tkString: Result := fStringAttri;
tkSymbol: Result := fSymbolAttri;
tkTableName: Result := fTableNameAttri;
tkVariable: Result := fVariableAttri;
tkUnknown: Result := fWrongSymbolAttri; //pavel
tkCustomStrings: Result := fCustomStringsAttri;
else
Result := nil;
end;
end;
function TpSHHighlighter.GetTokenID: TtkTokenKind;
begin
Result := fTokenId;
end;
function TpSHHighlighter.GetTokenKind: integer;
begin
Result := Ord(fTokenId);
end;
function TpSHHighlighter.GetTokenPos: Integer;
begin
Result := fTokenPos;
end;
procedure TpSHHighlighter.Next;
begin
fTokenPos := Run;
case fRange of
rsComment:
AnsiCProc;
rsString:
AsciiCharProc;
else
fProcTable[fLine[Run]];
end;
end;
procedure TpSHHighlighter.ResetRange;
begin
fRange := rsUnknown;
end;
procedure TpSHHighlighter.SetLine(NewValue: string; LineNumber: Integer);
begin
fLine := PChar(NewValue);
Run := 0;
fLineNumber := LineNumber;
Next;
end;
procedure TpSHHighlighter.SetRange(Value: Pointer);
begin
fRange := TRangeState(Value);
end;
initialization
MakeIdentTable;
{$IFNDEF SYN_CPPB_1}
RegisterPlaceableHighlighter(TpSHHighlighter);
{$ENDIF}
end.
|
// ************************************************************************
// ***************************** CEF4Delphi *******************************
// ************************************************************************
//
// CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based
// browser in Delphi applications.
//
// The original license of DCEF3 still applies to CEF4Delphi.
//
// For more information about CEF4Delphi visit :
// https://www.briskbard.com/index.php?lang=en&pageid=cef
//
// Copyright © 2017 Salvador Díaz Fau. All rights reserved.
//
// ************************************************************************
// ************ vvvv Original license and comments below vvvv *************
// ************************************************************************
(*
* Delphi Chromium Embedded 3
*
* Usage allowed under the restrictions of the Lesser GNU General Public License
* or alternatively the restrictions of the Mozilla Public License 1.1
*
* 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.
*
* Unit owner : Henri Gourvest <hgourvest@gmail.com>
* Web site : http://www.progdigy.com
* Repository : http://code.google.com/p/delphichromiumembedded/
* Group : http://groups.google.com/group/delphichromiumembedded
*
* Embarcadero Technologies, Inc is not permitted to use or redistribute
* this source code without explicit permission.
*
*)
unit uCEFChromiumOptions;
{$IFNDEF CPUX64}
{$ALIGN ON}
{$MINENUMSIZE 4}
{$ENDIF}
{$I cef.inc}
interface
uses
{$IFDEF DELPHI16_UP}
System.Classes,
{$ELSE}
Classes,
{$ENDIF}
uCEFTypes;
type
TChromiumOptions = class(TPersistent)
protected
FWindowlessFrameRate : Integer;
FJavascript : TCefState;
FJavascriptCloseWindows : TCefState;
FJavascriptAccessClipboard : TCefState;
FJavascriptDomPaste : TCefState;
FPlugins : TCefState;
FUniversalAccessFromFileUrls : TCefState;
FFileAccessFromFileUrls : TCefState;
FWebSecurity : TCefState;
FImageLoading : TCefState;
FImageShrinkStandaloneToFit : TCefState;
FTextAreaResize : TCefState;
FTabToLinks : TCefState;
FLocalStorage : TCefState;
FDatabases : TCefState;
FApplicationCache : TCefState;
FWebgl : TCefState;
FBackgroundColor : TCefColor;
FAcceptLanguageList : ustring;
public
constructor Create; virtual;
published
property Javascript : TCefState read FJavascript write FJavascript default STATE_DEFAULT;
property JavascriptCloseWindows : TCefState read FJavascriptCloseWindows write FJavascriptCloseWindows default STATE_DEFAULT;
property JavascriptAccessClipboard : TCefState read FJavascriptAccessClipboard write FJavascriptAccessClipboard default STATE_DEFAULT;
property JavascriptDomPaste : TCefState read FJavascriptDomPaste write FJavascriptDomPaste default STATE_DEFAULT;
property Plugins : TCefState read FPlugins write FPlugins default STATE_DEFAULT;
property UniversalAccessFromFileUrls : TCefState read FUniversalAccessFromFileUrls write FUniversalAccessFromFileUrls default STATE_DEFAULT;
property FileAccessFromFileUrls : TCefState read FFileAccessFromFileUrls write FFileAccessFromFileUrls default STATE_DEFAULT;
property WebSecurity : TCefState read FWebSecurity write FWebSecurity default STATE_DEFAULT;
property ImageLoading : TCefState read FImageLoading write FImageLoading default STATE_DEFAULT;
property ImageShrinkStandaloneToFit : TCefState read FImageShrinkStandaloneToFit write FImageShrinkStandaloneToFit default STATE_DEFAULT;
property TextAreaResize : TCefState read FTextAreaResize write FTextAreaResize default STATE_DEFAULT;
property TabToLinks : TCefState read FTabToLinks write FTabToLinks default STATE_DEFAULT;
property LocalStorage : TCefState read FLocalStorage write FLocalStorage default STATE_DEFAULT;
property Databases : TCefState read FDatabases write FDatabases default STATE_DEFAULT;
property ApplicationCache : TCefState read FApplicationCache write FApplicationCache default STATE_DEFAULT;
property Webgl : TCefState read FWebgl write FWebgl default STATE_DEFAULT;
property BackgroundColor : TCefColor read FBackgroundColor write FBackgroundColor default 0;
property AcceptLanguageList : ustring read FAcceptLanguageList write FAcceptLanguageList;
property WindowlessFrameRate : Integer read FWindowlessFrameRate write FWindowlessFrameRate default 30;
end;
implementation
constructor TChromiumOptions.Create;
begin
FWindowlessFrameRate := 30;
FJavascript := STATE_DEFAULT;
FJavascriptCloseWindows := STATE_DEFAULT;
FJavascriptAccessClipboard := STATE_DEFAULT;
FJavascriptDomPaste := STATE_DEFAULT;
FPlugins := STATE_DEFAULT;
FUniversalAccessFromFileUrls := STATE_DEFAULT;
FFileAccessFromFileUrls := STATE_DEFAULT;
FWebSecurity := STATE_DEFAULT;
FImageLoading := STATE_DEFAULT;
FImageShrinkStandaloneToFit := STATE_DEFAULT;
FTextAreaResize := STATE_DEFAULT;
FTabToLinks := STATE_DEFAULT;
FLocalStorage := STATE_DEFAULT;
FDatabases := STATE_DEFAULT;
FApplicationCache := STATE_DEFAULT;
FWebgl := STATE_DEFAULT;
FBackgroundColor := 0;
end;
end.
|
unit fMineSweeper2D;
interface
uses
Windows, Messages, SysUtils, Variants, Actions, Classes, Graphics, Controls,
Forms, Dialogs, ExtCtrls, StdCtrls, ComCtrls, ActnList, Menus, StrUtils,
uMinesClasses, uSimpleRenderer;
type
TfrmMineSweeper2D = class(TForm)
MinesPanel: TPanel;
Timer_GameTimer: TTimer;
MainMenu1: TMainMenu;
File1: TMenuItem;
ActionList1: TActionList;
Action_Exit: TAction;
N1: TMenuItem;
Exit1: TMenuItem;
Action_Restart: TAction;
Action_BeginnerGame: TAction;
Action_AdvancedGame: TAction;
Action_Intermediate: TAction;
Beginner1: TMenuItem;
Restart1: TMenuItem;
Advanced1: TMenuItem;
N2: TMenuItem;
Intermediate1: TMenuItem;
Action_ShowMoves: TAction;
Showmoves1: TMenuItem;
N3: TMenuItem;
PanelStatus: TPanel;
GroupBox1: TGroupBox;
Label_GameState: TLabel;
Label_GameTime: TLabel;
Label_MinesLeft: TLabel;
procedure FormCreate(Sender: TObject);
procedure Panel1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure Panel1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure Timer_GameTimerTimer(Sender: TObject);
procedure Action_ExitExecute(Sender: TObject);
procedure Action_RestartExecute(Sender: TObject);
procedure Action_BeginnerGameExecute(Sender: TObject);
procedure Action_IntermediateExecute(Sender: TObject);
procedure Action_AdvancedGameExecute(Sender: TObject);
procedure Label_GameStateClick(Sender: TObject);
procedure Label_GameStateMouseEnter(Sender: TObject);
procedure Label_GameStateMouseLeave(Sender: TObject);
procedure Action_ShowMovesExecute(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure GameStarted(Sender: TObject);
procedure GameWon(Sender: TObject);
procedure GameLost(Sender: TObject);
procedure GameReset(Sender: TObject);
procedure ResizeToFitPanel;
procedure RestartGame;
end;
var
frmMineSweeper2D: TfrmMineSweeper2D;
Mines : TMines;
Renderer : TMinesRenderer;
implementation
uses fGameHistory;
{$R *.dfm}
procedure TfrmMineSweeper2D.FormCreate(Sender: TObject);
begin
Randomize;
Show;
Mines := TMines.Create;
Mines.OnGameWon := GameWon;
Mines.OnGameLost := GameLost;
Mines.OnGameStarted := GameStarted;
Mines.OnGameReset := GameReset;
frmGameHistory := TfrmGameHistory.Create(self);
frmGameHistory.SetMines(Mines);
Renderer := TMinesRenderer.Create(Mines, MinesPanel);
Action_BeginnerGame.Execute;
end;
procedure TfrmMineSweeper2D.Panel1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
Panel : TPanel;
begin
Panel := TPanel(Sender);
Panel.BevelOuter := bvNone;
end;
procedure TfrmMineSweeper2D.Panel1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
Panel : TPanel;
begin
Panel := TPanel(Sender);
Panel.BevelOuter := bvRaised;
end;
procedure TfrmMineSweeper2D.ResizeToFitPanel;
begin
{ ClientHeight := MinesPanel.Top+MinesPanel.Height;
ClientWidth := MinesPanel.Left+MinesPanel.Width;//}
Height := MinesPanel.Top+MinesPanel.Height+50;
Width := MinesPanel.Left+MinesPanel.Width+12;//}
end;
procedure TfrmMineSweeper2D.Timer_GameTimerTimer(Sender: TObject);
var
s : string;
MinesLeft : integer;
begin
s := Format('000%0.0f',[Mines.GameTimePassed]);
Label_GameTime.Caption := RightStr(s,3);
MinesLeft := Mines.MineCount - Mines.FlagsPlaced;
if MinesLeft>= 0 then
begin
s := Format('000%d',[MinesLeft]);
Label_MinesLeft.Caption := RightStr(s,3);
end else
begin
s := Format('00%d',[abs(MinesLeft)]);
Label_MinesLeft.Caption := '-'+RightStr(s,2);
end;
if MinesLeft= 0 then
Label_MinesLeft.Font.Color := clGreen
else if MinesLeft < 0 then
Label_MinesLeft.Font.Color := clRed
else
Label_MinesLeft.Font.Color := clBlack;
end;
procedure TfrmMineSweeper2D.Action_ExitExecute(Sender: TObject);
begin
Close;
end;
procedure TfrmMineSweeper2D.Action_RestartExecute(Sender: TObject);
begin
RestartGame;
end;
procedure TfrmMineSweeper2D.RestartGame;
begin
Mines.BuildRandomMap(Mines.MineCount,Mines.CountX,Mines.CountY);
end;
procedure TfrmMineSweeper2D.Action_BeginnerGameExecute(Sender: TObject);
begin
Mines.BuildRandomMapSpecified(msBeginner);
end;
procedure TfrmMineSweeper2D.Action_IntermediateExecute(Sender: TObject);
begin
Mines.BuildRandomMapSpecified(msIntermediate);
end;
procedure TfrmMineSweeper2D.Action_AdvancedGameExecute(Sender: TObject);
begin
Mines.BuildRandomMapSpecified(msAdvanced);
end;
procedure TfrmMineSweeper2D.Label_GameStateClick(Sender: TObject);
begin
RestartGame;
end;
procedure TfrmMineSweeper2D.Label_GameStateMouseEnter(Sender: TObject);
begin
Label_GameState.Font.Style := Label_GameState.Font.Style + [fsUnderLine];
end;
procedure TfrmMineSweeper2D.Label_GameStateMouseLeave(Sender: TObject);
begin
Label_GameState.Font.Style := Label_GameState.Font.Style - [fsUnderLine];
end;
procedure TfrmMineSweeper2D.GameStarted(Sender: TObject);
begin
Label_GameState.Caption := 'Running!';
Label_GameState.Font.Color := clBlack;
end;
procedure TfrmMineSweeper2D.GameLost(Sender: TObject);
begin
Label_GameState.Caption := 'You lost!';
Label_GameState.Font.Color := clRed;
end;
procedure TfrmMineSweeper2D.GameReset(Sender: TObject);
begin
Label_GameState.Caption := 'Waiting';
Label_GameState.Font.Color := clBlack;
Renderer.Prepare;
Renderer.Render(false);
ResizeToFitPanel;
end;
procedure TfrmMineSweeper2D.GameWon(Sender: TObject);
begin
Label_GameState.Caption := 'You WON!';
Label_GameState.Font.Color := clGreen;
end;
procedure TfrmMineSweeper2D.Action_ShowMovesExecute(Sender: TObject);
begin
frmGameHistory.Show;
end;
end.
|
{-------------------------------------------------------------------------------
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/.
-------------------------------------------------------------------------------}
{===============================================================================
Concurrent tasks
©František Milt 2018-10-21
Version 1.1.3
To use this unit, create a descendant of class TCNTSTask and put the threaded
code into method Main (override it). Then pass instance of this class to an
instance of TCNTSManager. Manager will automatically start the task when
resources get available, or you can start the task manually (this will pause
other task when there are no running slots available).
You can call any public method of TCNTSTask from Main, but remember to protect
any shared data you want to use, tasks don't have any mean of thread-safety
protection. In Main, you should call method Cycle regularly if you want to use
integrated messaging system (in that case, also remember to override method
ProcessMessage - put a code that will process incoming messages there).
The implementation of method Main is entirely up to you, but suggested
template is as follows:
Function TTestTask.Main: Boolean;
begin
while not Terminated do
begin
Cycle;
[user code]
[progress signalling]
end;
Result := not Terminated;
end;
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Dependencies:
AuxTypes - github.com/ncs-sniper/Lib.AuxTypes
AuxClasses - github.com/ncs-sniper/Lib.AuxClasses
Messanger - github.com/ncs-sniper/Lib.Messanger
MemVector - github.com/ncs-sniper/Lib.MemVector
WinSyncObjs - github.com/ncs-sniper/Lib.WinSyncObjs
StrRect - github.com/ncs-sniper/Lib.StrRect
===============================================================================}
unit ConcurrentTasks;
{$IF not(Defined(WINDOWS) or Defined(MSWINDOWS))}
{$MESSAGE FATAL 'Unsupported operating system.'}
{$IFEND}
{$IFDEF FPC}
{$MODE Delphi}
{$DEFINE FPC_DisableWarns}
{$MACRO ON}
{$ENDIF}
interface
uses
Classes,
AuxTypes, AuxClasses, Messanger, WinSyncObjs;
{===============================================================================
Messages
===============================================================================}
const
CNTS_MSGR_ENDPOINT_MANAGER = 0;
CNTS_MSG_USER = 0;
CNTS_MSG_TERMINATE = 1;
CNTS_MSG_PROGRESS = 2;
CNTS_MSG_COMPLETED = 3;
type
TCNTSMessageEndpoint = TMsgrEndpointID;
TCNTSMessageParam = TMsgrParam;
TCNTSMessageResult = TMsgrParam;
TCNTSMessage = record
Sender: TCNTSMessageEndpoint;
Param1: TCNTSMessageParam;
Param2: TCNTSMessageParam;
Result: TCNTSMessageResult;
end;
TCNTSMessageEvent = procedure(Sender: TObject; var Msg: TCNTSMessage) of object;
{===============================================================================
--------------------------------------------------------------------------------
TCNTSTask
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TCNTSTask - declaration
===============================================================================}
TCNTSTask = class(TCustomObject)
private
fCommEndpoint: TMessangerEndpoint;
fPauseObject: TEvent;
fTerminated: Integer;
Function GetTerminated: Boolean;
procedure SetTerminated(Value: Boolean);
protected
procedure MessageHandler(Sender: TObject; Msg: TMsgrMessage; var Flags: TMsgrDispatchFlags); virtual;
public
procedure SetInternals(CommEndpoint: TMessangerEndpoint; PauseObject: TEvent); // static
procedure Execute; // static
Function PostMessage(Param1,Param2: TCNTSMessageParam): Boolean; virtual;
Function SendMessage(Param1,Param2: TCNTSMessageParam): TCNTSMessageResult; virtual;
procedure SignalProgress(Progress: Double); virtual;
procedure Cycle; virtual;
procedure ProcessMessage(var Msg: TCNTSMessage); virtual;
Function Main: Boolean; virtual; abstract;
property Terminated: Boolean read GetTerminated write SetTerminated;
end;
{===============================================================================
--------------------------------------------------------------------------------
TCNTSThread
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TCNTSThread - declaration
===============================================================================}
TCNTSThread = class(TThread)
private
fTaskObject: TCNTSTask;
fCommEndpoint: TMessangerEndpoint;
protected
procedure Execute; override;
public
constructor Create(TaskObject: TCNTSTask; CommEndpoint: TMessangerEndpoint; PauseObject: TEvent);
end;
{===============================================================================
--------------------------------------------------------------------------------
TCNTSManager
--------------------------------------------------------------------------------
===============================================================================}
TCNTSTaskState = (
tsReady, // not running
tsRunning, // running
tsQueued, // not running, paused
tsPaused, // running, paused
tsWaiting, // running, paused internally (can be automatically unpaused)
tsCompleted, // completed, returned true
tsAborted); // completed, returned false
TCNTSTaskItem = record
State: TCNTSTaskState;
TaskObject: TCNTSTask;
Progress: Double;
end;
PCNTSTaskItem = ^TCNTSTaskItem;
TCNTSTaskItemFull = record
PublicPart: TCNTSTaskItem;
CommEndpoint: TMessangerEndpoint;
PauseObject: TEvent;
AssignedThread: TCNTSThread;
end;
PCNTSTaskItemFull = ^TCNTSTaskItemFull;
TCNTSTasks = array of TCNTSTaskItemFull;
TCNTSTaskEvent = procedure(Sender: TObject; TaskIndex: Integer) of object;
{===============================================================================
TCNTSManager - declaration
===============================================================================}
{
Not derived from TCustomListObject because list growing and shrinking is not
of high importance in this class.
}
TCNTSManager = class(TCustomObject)
private
fOwnsTaskObjects: Boolean;
fTasks: TCNTSTasks;
fMaxConcurrentTasks: Integer;
fMessanger: TMessanger;
fCommEndpoint: TMessangerEndpoint;
fInternalAction: Boolean;
fOnMessage: TCNTSMessageEvent;
fOnTaskState: TCNTSTaskEvent;
fOnTaskProgress: TCNTSTaskEvent;
fOnTaskCompleted: TCNTSTaskEvent;
fOnTaskRemove: TCNTSTaskEvent;
fOnChange: TNotifyEvent;
Function GetTaskCount: Integer;
Function GetTask(Index: Integer): TCNTSTaskItem;
procedure SetMaxConcurrentTasks(Value: Integer);
protected
procedure MessageHandler(Sender: TObject; Msg: TMsgrMessage; var Flags: TMsgrDispatchFlags); virtual;
procedure ManageRunningTasks(IgnoreTask: Integer = -1); virtual;
public
class Function GetProcessorCount: Integer; virtual;
constructor Create(OwnsTaskObjects: Boolean = True);
destructor Destroy; override;
procedure Update(WaitTimeOut: LongWord = 0); virtual;
Function LowIndex: Integer; virtual;
Function HighIndex: Integer; virtual;
Function First: TCNTSTaskItem; virtual;
Function Last: TCNTSTaskItem; virtual;
Function IndexOfTask(TaskObject: TCNTSTask): Integer; overload; virtual;
Function IndexOfTask(CommEndpointID: TCNTSMessageEndpoint): Integer; overload; virtual;
Function AddTask(TaskObject: TCNTSTask): Integer; virtual;
procedure Insert(Index: Integer; TaskObject: TCNTSTask); virtual;
procedure Move(CurIdx, NewIdx: Integer); virtual;
procedure Exchange(Index1, Index2: Integer); virtual;
Function RemoveTask(TaskObject: TCNTSTask): Integer; virtual;
procedure DeleteTask(TaskIndex: Integer); virtual;
Function ExtractTask(TaskObject: TCNTSTask): TCNTSTask; virtual;
procedure ClearTasks; virtual;
procedure ClearCompletedTasks; virtual;
procedure StartTask(TaskIndex: Integer); virtual;
procedure PauseTask(TaskIndex: Integer); virtual;
procedure ResumeTask(TaskIndex: Integer); virtual;
procedure StopTask(TaskIndex: Integer); virtual;
procedure WaitForRunningTasksToComplete; virtual;
Function PostMessage(TaskIndex: Integer; Param1,Param2: TCNTSMessageParam): Boolean; virtual;
Function SendMessage(TaskIndex: Integer; Param1,Param2: TCNTSMessageParam): TCNTSMessageResult; virtual;
Function GetRunningTaskCount: Integer; virtual;
Function GetActiveTaskCount(CountPaused: Boolean = False): Integer; virtual;
property Tasks[Index: Integer]: TCNTSTaskItem read GetTask; default;
property TaskCount: Integer read GetTaskCount;
property MaxConcurrentTasks: Integer read fMaxConcurrentTasks write SetMaxConcurrentTasks;
property OnMessage: TCNTSMessageEvent read fOnMessage write fOnMessage;
property OnTaskState: TCNTSTaskEvent read fOnTaskState write fOnTaskState;
property OnTaskProgress: TCNTSTaskEvent read fOnTaskProgress write fOnTaskProgress;
property OnTaskCompleted: TCNTSTaskEvent read fOnTaskCompleted write fOnTaskCompleted;
property OnTaskRemove: TCNTSTaskEvent read fOnTaskRemove write fOnTaskRemove;
property OnChange: TNotifyEvent read fOnChange write fOnChange;
end;
implementation
uses
Windows, SysUtils;
{$IFDEF FPC_DisableWarns}
{$DEFINE FPCDWM}
{$DEFINE W4055:={$WARN 4055 OFF}} // Conversion between ordinals and pointers is not portable
{$DEFINE W5024:={$WARN 5024 OFF}} // Parameter "$1" not used
{$ENDIF}
{===============================================================================
External functions
===============================================================================}
procedure GetNativeSystemInfo(lpSystemInfo: PSystemInfo); stdcall; external kernel32;
{===============================================================================
--------------------------------------------------------------------------------
TCNTSTask
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TCNTSTask - implementation
===============================================================================}
{-------------------------------------------------------------------------------
TCNTSTask - private methods
-------------------------------------------------------------------------------}
Function TCNTSTask.GetTerminated: Boolean;
begin
Result := InterlockedExchangeAdd(fTerminated,0) <> 0;
end;
//------------------------------------------------------------------------------
procedure TCNTSTask.SetTerminated(Value: Boolean);
begin
If Value then InterlockedExchange(fTerminated,-1)
else InterlockedExchange(fTerminated,0);
end;
{-------------------------------------------------------------------------------
TCNTSTask - protected methods
-------------------------------------------------------------------------------}
{$IFDEF FPCDWM}{$PUSH}W4055 W5024{$ENDIF}
procedure TCNTSTask.MessageHandler(Sender: TObject; Msg: TMsgrMessage; var Flags: TMsgrDispatchFlags);
var
InternalMessage: TCNTSMessage;
begin
case Msg.Parameter1 of
CNTS_MSG_USER:
begin
InternalMessage.Sender := Msg.Sender;
InternalMessage.Param1 := Msg.Parameter2;
InternalMessage.Param2 := Msg.Parameter3;
InternalMessage.Result := 0;
ProcessMessage(InternalMessage);
If mdfSynchronousMessage in Flags then
TCNTSMessageResult(Pointer(Msg.Parameter4)^) := InternalMessage.Result;
end;
CNTS_MSG_TERMINATE:
Terminated := True;
end;
end;
{$IFDEF FPCDWM}{$POP}{$ENDIF}
{-------------------------------------------------------------------------------
TCNTSTask - public methods
-------------------------------------------------------------------------------}
procedure TCNTSTask.SetInternals(CommEndpoint: TMessangerEndpoint; PauseObject: TEvent);
begin
fCommEndpoint := CommEndpoint;
fCommEndpoint.OnMessageTraversing := MessageHandler;
fPauseObject := PauseObject;
end;
//------------------------------------------------------------------------------
procedure TCNTSTask.Execute;
begin
Cycle;
fCommEndpoint.SendMessage(CNTS_MSGR_ENDPOINT_MANAGER,CNTS_MSG_COMPLETED,Ord(Main),0,0)
end;
//------------------------------------------------------------------------------
Function TCNTSTask.PostMessage(Param1,Param2: TCNTSMessageParam): Boolean;
begin
Result := fCommEndpoint.SendMessage(CNTS_MSGR_ENDPOINT_MANAGER,CNTS_MSG_USER,Param1,Param2,0);
end;
//------------------------------------------------------------------------------
Function TCNTSTask.SendMessage(Param1,Param2: TCNTSMessageParam): TCNTSMessageResult;
begin
{$IFDEF FPCDWM}{$PUSH}W4055{$ENDIF}
fCommEndpoint.SendMessageAndWait(CNTS_MSGR_ENDPOINT_MANAGER,CNTS_MSG_USER,Param1,Param2,TMsgrParam(Addr(Result)));
{$IFDEF FPCDWM}{$POP}{$ENDIF}
end;
//------------------------------------------------------------------------------
procedure TCNTSTask.SignalProgress(Progress: Double);
var
ValueLo: TCNTSMessageParam;
ValueHi: TCNTSMessageParam;
begin
ValueLo := TCNTSMessageParam(UInt32(Addr(Progress)^));
{$IFDEF FPCDWM}{$PUSH}W4055{$ENDIF}
ValueHi := TCNTSMessageParam(PUInt32(PtrUInt(Addr(Progress)) + SizeOf(UInt32))^);
{$IFDEF FPCDWM}{$POP}{$ENDIF}
fCommEndpoint.SendMessage(CNTS_MSGR_ENDPOINT_MANAGER,CNTS_MSG_PROGRESS,ValueLo,ValueHi,0);
end;
//------------------------------------------------------------------------------
procedure TCNTSTask.Cycle;
begin
fCommEndpoint.Cycle(0); // do not wait
fPauseObject.WaitFor;
end;
//------------------------------------------------------------------------------
procedure TCNTSTask.ProcessMessage(var Msg: TCNTSMessage);
begin
Msg.Result := 0;
end;
{===============================================================================
--------------------------------------------------------------------------------
TCNTSThread
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TCNTSThread - declaration
===============================================================================}
{-------------------------------------------------------------------------------
TCNTSThread - protected methods
-------------------------------------------------------------------------------}
procedure TCNTSThread.Execute;
begin
fTaskObject.Execute;
end;
{-------------------------------------------------------------------------------
TCNTSThread - public methods
-------------------------------------------------------------------------------}
constructor TCNTSThread.Create(TaskObject: TCNTSTask; CommEndpoint: TMessangerEndpoint; PauseObject: TEvent);
begin
inherited Create(False);
Priority := tpLower;
FreeOnTerminate := False;
fTaskObject := TaskObject;
fCommEndpoint := CommEndpoint;
fTaskObject.SetInternals(CommEndpoint,PauseObject);
end;
{===============================================================================
--------------------------------------------------------------------------------
TCNTSManager
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TCNTSManager - declaration
===============================================================================}
{-------------------------------------------------------------------------------
TCNTSManager - private methods
-------------------------------------------------------------------------------}
Function TCNTSManager.GetTaskCount: Integer;
begin
Result := Length(fTasks);
end;
//------------------------------------------------------------------------------
Function TCNTSManager.GetTask(Index: Integer): TCNTSTaskItem;
begin
If (Index >= Low(fTasks)) and (Index <= High(fTasks)) then
Result := fTasks[Index].PublicPart
else
raise Exception.CreateFmt('TCNTSManager.GetTask: Index(%d) out of bounds.',[Index]);
end;
//------------------------------------------------------------------------------
procedure TCNTSManager.SetMaxConcurrentTasks(Value: Integer);
begin
If Value >= 1 then
begin
fMaxConcurrentTasks := Value;
ManageRunningTasks;
end
else raise Exception.CreateFmt('TCNTSManager.SetMaxConcurrentTasks: Cannot assign value smaller than 1 (%d).',[Value]);
end;
{-------------------------------------------------------------------------------
TCNTSManager - protected methods
-------------------------------------------------------------------------------}
procedure TCNTSManager.MessageHandler(Sender: TObject; Msg: TMsgrMessage; var Flags: TMsgrDispatchFlags);
var
InternalMessage: TCNTSMessage;
Index: Integer;
begin
case Msg.Parameter1 of
CNTS_MSG_USER:
begin
InternalMessage.Sender := Msg.Sender;
InternalMessage.Param1 := Msg.Parameter2;
InternalMessage.Param2 := Msg.Parameter3;
InternalMessage.Result := 0;
If Assigned(fOnMessage) then
fOnMessage(Self,InternalMessage);
If mdfSynchronousMessage in Flags then
{$IFDEF FPCDWM}{$PUSH}W4055{$ENDIF}
TCNTSMessageResult(Pointer(Msg.Parameter4)^) := InternalMessage.Result;
{$IFDEF FPCDWM}{$POP}{$ENDIF}
end;
CNTS_MSG_PROGRESS:
begin
Index := IndexOfTask(Msg.Sender);
If Index >= 0 then
begin
UInt32(Addr(fTasks[Index].PublicPart.Progress)^) := UInt32(Msg.Parameter2);
{$IFDEF FPCDWM}{$PUSH}W4055{$ENDIF}
PUInt32(PtrUInt(Addr(fTasks[Index].PublicPart.Progress)) + SizeOf(UInt32))^ := UInt32(Msg.Parameter3);
{$IFDEF FPCDWM}{$POP}{$ENDIF}
If Assigned(fOnTaskProgress) then
fOnTaskProgress(Sender,Index);
end;
end;
CNTS_MSG_COMPLETED:
begin
Index := IndexOfTask(Msg.Sender);
If Index >= 0 then
begin
If Assigned(fTasks[Index].AssignedThread) then
fTasks[Index].AssignedThread.WaitFor;
If Msg.Parameter2 <> 0 then
fTasks[Index].PublicPart.State := tsCompleted
else
fTasks[Index].PublicPart.State := tsAborted;
If Assigned(fOnTaskState) then
fOnTaskState(Self,Index);
If Assigned(fOnTaskCompleted) then
fOnTaskCompleted(Self,Index);
end;
ManageRunningTasks;
end;
end;
end;
//------------------------------------------------------------------------------
procedure TCNTSManager.ManageRunningTasks(IgnoreTask: Integer = -1);
var
RunCount: Integer;
i: Integer;
begin
fInternalAction := True;
try
RunCount := fMaxConcurrentTasks - GetRunningTaskCount;
If RunCount > 0 then
begin
For i := Low(fTasks) to High(fTasks) do
If RunCount > 0 then
begin
If (fTasks[i].PublicPart.State in [tsReady,tsWaiting]) and (i <> IgnoreTask) then
begin
StartTask(i);
Dec(RunCount);
end;
end
else Break{For i};
end
else If RunCount < 0 then
begin
For i := High(fTasks) downto Low(fTasks) do
If RunCount < 0 then
begin
If (fTasks[i].PublicPart.State = tsRunning) and (i <> IgnoreTask) then
begin
PauseTask(i);
Inc(RunCount);
end;
end
else Break{For i};
end;
finally
fInternalAction := False;
end;
end;
{-------------------------------------------------------------------------------
TCNTSManager - public methods
-------------------------------------------------------------------------------}
class Function TCNTSManager.GetProcessorCount: Integer;
var
SysInfo: TSystemInfo;
begin
GetNativeSystemInfo(@SysInfo);
Result := Integer(SysInfo.dwNumberOfProcessors);
If Result < 1 then
Result := 1;
end;
//------------------------------------------------------------------------------
constructor TCNTSManager.Create(OwnsTaskObjects: Boolean = True);
begin
inherited Create;
fOwnsTaskObjects := OwnsTaskObjects;
SetLength(fTasks,0);
fMaxConcurrentTasks := GetProcessorCount;
fMessanger := TMessanger.Create;
fCommEndpoint := fMessanger.CreateEndpoint(0);
fCommEndpoint.OnMessageTraversing := MessageHandler;
fInternalAction := False;
end;
//------------------------------------------------------------------------------
destructor TCNTSManager.Destroy;
begin
ClearTasks;
fCommEndpoint.Free;
fMessanger.Free;
SetLength(fTasks,0);
inherited;
end;
//------------------------------------------------------------------------------
procedure TCNTSManager.Update(WaitTimeOut: LongWord = 0);
begin
fCommEndpoint.Cycle(WaitTimeOut);
ManageRunningTasks;
end;
//------------------------------------------------------------------------------
Function TCNTSManager.LowIndex: Integer;
begin
Result := Low(fTasks);
end;
//------------------------------------------------------------------------------
Function TCNTSManager.HighIndex: Integer;
begin
Result := High(fTasks);
end;
//------------------------------------------------------------------------------
Function TCNTSManager.First: TCNTSTaskItem;
begin
Result := GetTask(LowIndex);
end;
//------------------------------------------------------------------------------
Function TCNTSManager.Last: TCNTSTaskItem;
begin
Result := GetTask(HighIndex);
end;
//------------------------------------------------------------------------------
Function TCNTSManager.IndexOfTask(TaskObject: TCNTSTask): Integer;
var
i: Integer;
begin
Result := -1;
For i := Low(fTasks) to High(fTasks) do
If fTasks[i].PublicPart.TaskObject = TaskObject then
begin
Result := i;
Break;
end;
end;
//-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
Function TCNTSManager.IndexOfTask(CommEndpointID: TCNTSMessageEndpoint): Integer;
var
i: Integer;
begin
Result := -1;
For i := Low(fTasks) to High(fTasks) do
If fTasks[i].CommEndpoint.EndpointID = CommEndpointID then
begin
Result := i;
Break;
end;
end;
//------------------------------------------------------------------------------
Function TCNTSManager.AddTask(TaskObject: TCNTSTask): Integer;
var
NewTaskItem: TCNTSTaskItemFull;
begin
NewTaskItem.PublicPart.State := tsReady;
NewTaskItem.PublicPart.TaskObject := TaskObject;
NewTaskItem.PublicPart.Progress := 0.0;
NewTaskItem.CommEndpoint := fMessanger.CreateEndpoint;
NewTaskItem.PauseObject := TEvent.Create(nil,True,True,'');
// thread is created only when the task is started
NewTaskItem.AssignedThread := nil;
SetLength(fTasks,Length(fTasks) + 1);
Result := High(fTasks);
fTasks[Result] := NewTaskItem;
If Assigned(fOnChange) then
fOnChange(Self);
If Assigned(fOnTaskState) then
fOnTaskState(Self,Result);
ManageRunningTasks;
end;
//------------------------------------------------------------------------------
procedure TCNTSManager.Insert(Index: Integer; TaskObject: TCNTSTask);
var
NewTaskItem: TCNTSTaskItemFull;
i: Integer;
begin
If (Index >= Low(fTasks)) and (Index <= High(fTasks)) then
begin
NewTaskItem.PublicPart.State := tsReady;
NewTaskItem.PublicPart.TaskObject := TaskObject;
NewTaskItem.PublicPart.Progress := 0.0;
NewTaskItem.CommEndpoint := fMessanger.CreateEndpoint;
NewTaskItem.PauseObject := TEvent.Create(nil,True,True,'');
NewTaskItem.AssignedThread := nil;
SetLength(fTasks,Length(fTasks) + 1);
For i := High(fTasks) downto Succ(Index) do
fTasks[i] := fTasks[i - 1];
fTasks[Index] := NewTaskItem;
If Assigned(fOnChange) then
fOnChange(Self);
If Assigned(fOnTaskState) then
fOnTaskState(Self,Index);
ManageRunningTasks;
end
else If Index = Length(fTasks) then
AddTask(TaskObject)
else
raise Exception.CreateFmt('TCNTSManager.Insert: Index (%d) out of bounds.',[Index]);
end;
//------------------------------------------------------------------------------
procedure TCNTSManager.Move(CurIdx, NewIdx: Integer);
var
TempItem: TCNTSTaskItemFull;
i: Integer;
begin
If CurIdx <> NewIdx then
begin
If (CurIdx < Low(fTasks)) or (CurIdx > High(fTasks)) then
raise Exception.CreateFmt('TCNTSManager.Move: CurIdx (%d) out of bounds.',[CurIdx]);
If (NewIdx < Low(fTasks)) or (NewIdx > High(fTasks)) then
raise Exception.CreateFmt('TCNTSManager.Move: NewIdx (%d) out of bounds.',[NewIdx]);
TempItem := fTasks[CurIdx];
If NewIdx > CurIdx then
For i := CurIdx to Pred(NewIdx) do
fTasks[i] := fTasks[i + 1]
else
For i := CurIdx downto Succ(NewIdx) do
fTasks[i] := fTasks[i - 1];
fTasks[NewIdx] := TempItem;
If Assigned(fOnChange) then
fOnChange(Self);
end;
end;
//------------------------------------------------------------------------------
procedure TCNTSManager.Exchange(Index1, Index2: Integer);
var
TempItem: TCNTSTaskItemFull;
begin
If Index1 <> Index2 then
begin
If (Index1 < Low(fTasks)) or (Index1 > High(fTasks)) then
raise Exception.CreateFmt('TCNTSManager.Exchange: Index1 (%d) out of bounds.',[Index1]);
If (Index2 < Low(fTasks)) or (Index2 > High(fTasks)) then
raise Exception.CreateFmt('TCNTSManager.Exchange: Index2 (%d) out of bounds.',[Index2]);
TempItem := fTasks[Index1];
fTasks[Index1] := fTasks[Index2];
fTasks[Index2] := TempItem;
If Assigned(fOnChange) then
fOnChange(Self);
end;
end;
//------------------------------------------------------------------------------
Function TCNTSManager.RemoveTask(TaskObject: TCNTSTask): Integer;
begin
Result := IndexOfTask(TaskObject);
If Result >= 0 then DeleteTask(Result);
end;
//------------------------------------------------------------------------------
procedure TCNTSManager.DeleteTask(TaskIndex: Integer);
var
i: Integer;
begin
If (TaskIndex >= Low(fTasks)) and (TaskIndex <= High(fTasks)) then
begin
If not(fTasks[TaskIndex].PublicPart.State in [tsRunning,tsPaused,tsWaiting]) then
begin
If Assigned(fTasks[TaskIndex].AssignedThread) then
begin
fTasks[TaskIndex].AssignedThread.WaitFor;
FreeAndNil(fTasks[TaskIndex].AssignedThread);
end;
If Assigned(fTasks[TaskIndex].CommEndpoint) then
begin
fTasks[TaskIndex].CommEndpoint.OnMessageTraversing := nil;
FreeAndNil(fTasks[TaskIndex].CommEndpoint);
end;
fTasks[TaskIndex].PauseObject.Free;
If fOwnsTaskObjects then
fTasks[TaskIndex].PublicPart.TaskObject.Free
else
If Assigned(fOnTaskRemove) then fOnTaskRemove(Self,TaskIndex);
For i := TaskIndex to Pred(High(fTasks)) do
fTasks[i] := fTasks[i + 1];
SetLength(fTasks,Length(fTasks) - 1);
If Assigned(fOnChange) then
fOnChange(Self);
end
else raise Exception.CreateFmt('TCNTSManager.DeleteTask: Cannot delete running task (#%d).',[TaskIndex]);
end
else raise Exception.CreateFmt('TCNTSManager.DeleteTask: Index (%d) out of bounds.',[TaskIndex]);
end;
//------------------------------------------------------------------------------
Function TCNTSManager.ExtractTask(TaskObject: TCNTSTask): TCNTSTask;
var
Index: Integer;
i: Integer;
begin
Index := IndexOfTask(TaskObject);
If Index >= 0 then
begin
If not(fTasks[Index].PublicPart.State in [tsRunning,tsPaused,tsWaiting]) then
begin
If Assigned(fTasks[Index].AssignedThread) then
begin
fTasks[Index].AssignedThread.WaitFor;
FreeAndNil(fTasks[Index].AssignedThread);
end;
If Assigned(fTasks[Index].CommEndpoint) then
begin
fTasks[Index].CommEndpoint.OnMessageTraversing := nil;
FreeAndNil(fTasks[Index].CommEndpoint);
end;
fTasks[Index].PauseObject.Free;
Result := fTasks[Index].PublicPart.TaskObject;
For i := Index to Pred(High(fTasks)) do
fTasks[i] := fTasks[i + 1];
SetLength(fTasks,Length(fTasks) - 1);
If Assigned(fOnChange) then
fOnChange(Self);
end
else raise Exception.CreateFmt('TCNTSManager.ExtractTask: Cannot extract running task (#%d).',[Index]);
end
else Result := nil;
end;
//------------------------------------------------------------------------------
procedure TCNTSManager.ClearTasks;
var
i: Integer;
OldMCT: Integer;
begin
OldMCT := fMaxConcurrentTasks;
fMaxConcurrentTasks := High(fMaxConcurrentTasks);
try
For i := Low(fTasks) to High(fTasks) do
If fTasks[i].PublicPart.State in [tsPaused,tsWaiting] then
ResumeTask(i);
For i := High(fTasks) downto Low(fTasks) do
begin
If fTasks[i].PublicPart.State = tsRunning then
begin
fTasks[i].PublicPart.TaskObject.Terminated := True;
fTasks[i].AssignedThread.WaitFor;
end;
fCommEndpoint.Cycle(0);
DeleteTask(i);
end;
If Assigned(fOnChange) then
fOnChange(Self);
finally
fMaxConcurrentTasks := OldMCT;
end;
end;
//------------------------------------------------------------------------------
procedure TCNTSManager.ClearCompletedTasks;
var
i: Integer;
begin
Update;
For i := High(fTasks) downto Low(fTasks) do
If fTasks[i].PublicPart.State = tsCompleted then
DeleteTask(i);
If Assigned(fOnChange) then
fOnChange(Self);
end;
//------------------------------------------------------------------------------
procedure TCNTSManager.StartTask(TaskIndex: Integer);
begin
If (TaskIndex >= Low(fTasks)) and (TaskIndex <= High(fTasks)) then
case fTasks[TaskIndex].PublicPart.State of
tsReady:
begin
fTasks[TaskIndex].PublicPart.State := tsRunning;
fTasks[TaskIndex].AssignedThread :=
TCNTSThread.Create(fTasks[TaskIndex].PublicPart.TaskObject,
fTasks[TaskIndex].CommEndpoint,
fTasks[TaskIndex].PauseObject);
ManageRunningTasks(TaskIndex);
If Assigned(fOnTaskState) then
fOnTaskState(Self,TaskIndex);
end;
tsQueued,
tsPaused,
tsWaiting:
ResumeTask(TaskIndex);
end
else raise Exception.CreateFmt('TCNTSManager.StartTask: Index (%d) out of bounds.',[TaskIndex]);
end;
//------------------------------------------------------------------------------
procedure TCNTSManager.PauseTask(TaskIndex: Integer);
begin
If (TaskIndex >= Low(fTasks)) and (TaskIndex <= High(fTasks)) then
case fTasks[TaskIndex].PublicPart.State of
tsReady:
begin
fTasks[TaskIndex].PublicPart.State := tsQueued;
If Assigned(fOnTaskState) then
fOnTaskState(Self,TaskIndex);
end;
tsRunning:
begin
If fInternalAction then
fTasks[TaskIndex].PublicPart.State := tsWaiting
else
fTasks[TaskIndex].PublicPart.State := tsPaused;
fTasks[TaskIndex].PauseObject.ResetEvent;
If Assigned(fOnTaskState) then
fOnTaskState(Self,TaskIndex);
ManageRunningTasks;
end;
tsWaiting:
begin
fTasks[TaskIndex].PublicPart.State := tsPaused;
If Assigned(fOnTaskState) then
fOnTaskState(Self,TaskIndex);
end;
end
else raise Exception.CreateFmt('TCNTSManager.StartTask: Index (%d) out of bounds.',[TaskIndex]);
end;
//------------------------------------------------------------------------------
procedure TCNTSManager.ResumeTask(TaskIndex: Integer);
begin
If (TaskIndex >= Low(fTasks)) and (TaskIndex <= High(fTasks)) then
case fTasks[TaskIndex].PublicPart.State of
tsQueued:
begin
fTasks[TaskIndex].PublicPart.State := tsReady;
If Assigned(fOnTaskState) then
fOnTaskState(Self,TaskIndex);
end;
tsPaused,
tsWaiting:
begin
fTasks[TaskIndex].PublicPart.State := tsRunning;
fTasks[TaskIndex].PauseObject.SetEvent;
ManageRunningTasks(TaskIndex);
If Assigned(fOnTaskState) then
fOnTaskState(Self,TaskIndex);
end;
end
else raise Exception.CreateFmt('TCNTSManager.StartTask: Index (%d) out of bounds.',[TaskIndex]);
end;
//------------------------------------------------------------------------------
procedure TCNTSManager.StopTask(TaskIndex: Integer);
begin
If (TaskIndex >= Low(fTasks)) and (TaskIndex <= High(fTasks)) then
begin
If fTasks[TaskIndex].PublicPart.State in [tsRunning,tsPaused,tsWaiting] then
begin
fCommEndpoint.SendMessage(fTasks[TaskIndex].CommEndpoint.EndpointID,CNTS_MSG_TERMINATE,0,0,0);
fTasks[TaskIndex].PublicPart.TaskObject.Terminated := True;
ResumeTask(TaskIndex);
end;
end
else raise Exception.CreateFmt('TCNTSManager.StartTask: Index (%d) out of bounds.',[TaskIndex]);
end;
//------------------------------------------------------------------------------
procedure TCNTSManager.WaitForRunningTasksToComplete;
var
i: Integer;
begin
For i := Low(fTasks) to High(fTasks) do
If fTasks[i].PublicPart.State = tsRunning then
fTasks[i].AssignedThread.WaitFor;
fCommEndpoint.Cycle(0);
end;
//------------------------------------------------------------------------------
Function TCNTSManager.PostMessage(TaskIndex: Integer; Param1,Param2: TCNTSMessageParam): Boolean;
begin
If (TaskIndex >= Low(fTasks)) and (TaskIndex <= High(fTasks)) then
Result := fCommEndpoint.SendMessage(fTasks[TaskIndex].CommEndpoint.EndpointID,CNTS_MSG_USER,Param1,Param2,0)
else
raise Exception.CreateFmt('TCNTSManager.PostMessage: Index (%d) out of bounds.',[TaskIndex]);
end;
//------------------------------------------------------------------------------
Function TCNTSManager.SendMessage(TaskIndex: Integer; Param1,Param2: TCNTSMessageParam): TCNTSMessageResult;
begin
If (TaskIndex >= Low(fTasks)) and (TaskIndex <= High(fTasks)) then
{$IFDEF FPCDWM}{$PUSH}W4055{$ENDIF}
fCommEndpoint.SendMessageAndWait(fTasks[TaskIndex].CommEndpoint.EndpointID,CNTS_MSG_USER,Param1,Param2,TMsgrParam(Addr(Result)))
{$IFDEF FPCDWM}{$POP}{$ENDIF}
else
raise Exception.CreateFmt('TCNTSManager.PostMessage: Index (%d) out of bounds.',[TaskIndex]);
end;
//------------------------------------------------------------------------------
Function TCNTSManager.GetRunningTaskCount: Integer;
var
i: Integer;
begin
Result := 0;
For i := Low(fTasks) to High(fTasks) do
If fTasks[i].PublicPart.State = tsRunning then
Inc(Result);
end;
//------------------------------------------------------------------------------
Function TCNTSManager.GetActiveTaskCount(CountPaused: Boolean = False): Integer;
var
i: Integer;
begin
Result := 0;
For i := Low(fTasks) to High(fTasks) do
begin
If fTasks[i].PublicPart.State in [tsReady,tsRunning] then
Inc(Result)
else If CountPaused and (fTasks[i].PublicPart.State in [tsQueued,tsPaused,tsWaiting]) then
Inc(Result);
end;
end;
end.
|
(*
Category: SWAG Title: MATH ROUTINES
Original name: 0045.PAS
Description: Calculate PI
Author: LOU DUCHEZ
Date: 11-02-93 10:31
*)
{
LOU DUCHEZ
ATTENTION, whoever was trying to calculate PI! Here's a swell program,
as a follow-up to a recent post of mine about approximating techniques!
}
program calcpi; { Calculates pi by getting the area of one-quarter of a
circle of radius 1, and then multiplying by 4. The area
is an approximation, derived by Simpson's method: see
previous post for explanation of that technique. }
uses
crt;
const
lowerbound = 0; { The interval we're evaluating is from 0 to 1. }
higherbound = 1; { I put the 0 and 1 here for clarity. }
var
incs : word;
quartpi,
h, x : real;
function y(x : real) : real; { Feed it an x-value, and it tells you the }
begin { corresponding y-value on the unit circle. }
y := sqrt(1 - x * x); { A no-brainer. }
end;
begin
{ I leave you to do the error-checking on input. }
clrscr;
write('Enter a WORD (1 - 32767) for the number of parabolas to do: ');
readln(incs);
{ The answer for a quarter of pi will be accumulated into QuartPi. }
quartpi := 0;
{ H is the interval to increment on. X is the "middle" x value for each
parabola in Simpson's method. Here it is set equal to one interval
above the lower bound: Simpson's method looks at points on either side
of "X", so my reasoning is obvious. Note also that, by magical
coincidence, the last evaluation will have "X" equal to the higher
bound of the interval minus H. }
h := (higherbound - lowerbound) / (1 + 2 * incs);
x := lowerbound + h;
{ This loop accumulates a value for pi/4. }
while incs > 0 do
begin
if x < 0 then
x := 0;
quartpi := quartpi + y(x - h) + 4 * y(x) + y(x + h);
{ Move X two increments to the right, and decrease the number of parabolas
we still have to do. }
x := x + 2 * h;
dec(incs);
end;
{ Simpson's method has you multiply the sum by H/3. }
quartpi := h * quartpi / 3;
{ Print answer. }
writeln(4 * quartpi : 12 : 8);
writeln('This has been a display of Simpson''s method. D''ohh!');
end.
|
unit Forms.Main;
interface
uses
System.SysUtils, System.Classes, JS, Web, WEBLib.Graphics, WEBLib.Controls,
WEBLib.Forms, WEBLib.Dialogs, Vcl.Controls, WEBLib.ExtCtrls, VCL.TMSFNCTypes, VCL.TMSFNCUtils,
VCL.TMSFNCGraphics, VCL.TMSFNCGraphicsTypes, VCL.TMSFNCMapsCommonTypes, Vcl.StdCtrls,
WEBLib.StdCtrls, VCL.TMSFNCCustomControl, VCL.TMSFNCWebBrowser, VCL.TMSFNCMaps, XData.Web.Client,
XData.Web.Connection;
type
TFrmMain = class(TWebForm)
WebPanel1: TWebPanel;
Map: TTMSFNCMaps;
cbLevel: TWebComboBox;
cbTour: TWebComboBox;
btnDisplay: TWebButton;
Connection: TXDataWebConnection;
Client: TXDataWebClient;
procedure ClientLoad(Response: TXDataClientResponse);
procedure ConnectionConnect(Sender: TObject);
procedure WebFormShow(Sender: TObject);
procedure cbLevelChange(Sender: TObject);
procedure btnDisplayClick(Sender: TObject);
private
FLevel : String;
{ Private declarations }
procedure AddTours(Response: TXDataClientResponse);
procedure AddLevels(Response: TXDataClientResponse);
procedure DisplayTour(Response: TXDataClientResponse);
procedure RequestLists;
public
{ Public declarations }
end;
var
FrmMain: TFrmMain;
implementation
{$R *.dfm}
uses
WEBLib.JSON;
const
REQ_LEVELS = 'ITourService.Levels';
REQ_TOURS = 'ITourService.Tours';
REQ_TOUR = 'ITourService.Tour';
procedure TFrmMain.AddLevels(Response: TXDataClientResponse);
var
LRoot: TJSONValue;
LValues: TJSONArray;
i : Integer;
begin
LRoot := TTMSFNCUtils.ParseJSON(Response.ResponseText);
cbLevel.Items.Clear;
LValues := TTMSFNCUtils.GetJSONValue(LRoot, 'value') as TJSONArray;
for i := 0 to TTMSFNCUtils.GetJSONArraySize(LValues)-1 do
begin
cbLevel.Items.Add(
LValues[i].Value
);
end;
end;
procedure TFrmMain.AddTours(Response: TXDataClientResponse);
var
LRoot: TJSONValue;
LValues: TJSONArray;
i : Integer;
begin
LRoot := TTMSFNCUtils.ParseJSON(Response.ResponseText);
cbTour.Items.Clear;
LValues := TTMSFNCUtils.GetJSONValue(LRoot, 'value') as TJSONArray;
for i := 0 to TTMSFNCUtils.GetJSONArraySize(LValues)-1 do
begin
cbTour.Items.Add(
LValues[i].Value
);
end;
end;
procedure TFrmMain.btnDisplayClick(Sender: TObject);
begin
if cbTour.ItemIndex > -1 then
begin
Client.RawInvoke( REQ_TOUR, [ FLevel, cbTour.Items[ cbTour.ItemIndex] ] );
end;
end;
procedure TFrmMain.cbLevelChange(Sender: TObject);
begin
FLevel := cbLevel.Items[ cbLevel.ItemIndex ];
Client.RawInvoke( REQ_TOURS, [ FLevel ] );
end;
procedure TFrmMain.ClientLoad(Response: TXDataClientResponse);
begin
if Response.StatusCode = 200 then
begin
if Response.RequestId = REQ_LEVELS then
begin
AddLevels(Response);
end;
if Response.RequestId = REQ_TOURS then
begin
AddTours(Response);
end;
if Response.RequestId = REQ_TOUR then
begin
DisplayTour(Response);
end;
end;
end;
procedure TFrmMain.ConnectionConnect(Sender: TObject);
begin
RequestLists;
end;
procedure TFrmMain.DisplayTour(Response: TXDataClientResponse);
begin
Map.LoadGPXFromText(Response.ResponseText);
end;
procedure TFrmMain.RequestLists;
begin
Client.RawInvoke( REQ_LEVELS, nil);
end;
procedure TFrmMain.WebFormShow(Sender: TObject);
begin
Connection.Connected := True;
end;
end. |
{*
* Outliner Lighto
* Copyright (C) 2011 Kostas Michalopoulos
*
* 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.
*
* Kostas Michalopoulos <badsector@runtimelegend.com>
*}
unit Tree;
interface
{$MODE OBJFPC}{$H+}
uses SysUtils, Nodes, Defines;
var
Root: TNode;
procedure CreateTree;
procedure DestroyTree;
function SaveTree(FileName: string; Root: TNode): Boolean;
function LoadTree(FileName: string; var Root: TNode): Boolean;
implementation
procedure CreateTree;
var
Node: TNode;
NodeStack: array [0..256] of TNode;
NSP: Integer;
begin
Root:=TNode.Create;
Node:=Root;
NSP:=0;
{ === CUTCUT === The code below is generated with olol2pas === CUTCUT === }
Node.NodeType:=ntNormal;
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Welcome to Outliner Lighto');
Node.NodeType:=ntNormal;
Node.Open:=True;
Node.WasOpen:=True;
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Outliner Lighto is a small outliner program for the console. An outliner progr' +
'am is simply a program that edits text structured in tree nodes. These nodes ca' +
'n be used for any purpose the user wants, like TODO lists, phonebooks, etc. Any' +
'thing that can be represented by a hierarchy can be stored in an outliner.');
Node.NodeType:=ntNormal;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('When working with Outliner Lighto you always have a "selected node", which is ' +
'the node you are currently working with.');
Node.NodeType:=ntNormal;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Use the arrow keys or hjkl (as in Vi) to change the selected node.');
Node.NodeType:=ntNormal;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Going up and down always move to the previous and next node in the current nod' +
'e''s parent node.');
Node.NodeType:=ntNormal;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Going left and right will "rise" from and "dive" into the node structure.');
Node.NodeType:=ntNormal;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Using C or Enter you can edit the selected node. With I and A you can add new ' +
'nodes.');
Node.NodeType:=ntNormal;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('By pressing the Space bar you can open and close nodes with subnodes.');
Node.NodeType:=ntNormal;
Node.Open:=True;
Node.WasOpen:=True;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Diving into a node will open it temporarily.');
Node.NodeType:=ntNormal;
Dec(NSP);
Node:=NodeStack[NSP];
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Select this node and dive into it (with the above node selected, press Down or' +
' j and then Right or l) for more tips.');
Node.NodeType:=ntNormal;
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Think of the outline as a tree:');
Node.NodeType:=ntNormal;
Node.Open:=True;
Node.WasOpen:=True;
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('There are branches (nodes) which in turn have more branches (sub-nodes)');
Node.NodeType:=ntNormal;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('And at the end of the branches there are leaves (nodes without subnodes)');
Node.NodeType:=ntNormal;
Dec(NSP);
Node:=NodeStack[NSP];
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Leaf nodes are always shown as white text with a blue ''o'' in front of them. Yo' +
'u can also think of them as ''bullets'' in a list.');
Node.NodeType:=ntNormal;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Branch nodes are shown in color with different colors depending on how "deep" ' +
'in the structure the node is.');
Node.NodeType:=ntNormal;
Node.Open:=True;
Node.WasOpen:=True;
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('The different colors are used to distinguish between the depths when there are' +
' many open branches on screen.');
Node.NodeType:=ntNormal;
Node.Open:=True;
Node.WasOpen:=True;
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Like');
Node.NodeType:=ntNormal;
Node.Open:=True;
Node.WasOpen:=True;
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('This');
Node.NodeType:=ntNormal;
Dec(NSP);
Node:=NodeStack[NSP];
Dec(NSP);
Node:=NodeStack[NSP];
Dec(NSP);
Node:=NodeStack[NSP];
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Trying to move below the last node will create a temporary node at the end. By' +
' editing this node you can make it permanent.');
Node.NodeType:=ntNormal;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('When adding a new node via A, I or using the method described above, Outliner ' +
'Lighto will create new nodes continuously until you don''t make one permanent by' +
' editing it. This way you can enter many new nodes in a row.');
Node.NodeType:=ntNormal;
Dec(NSP);
Node:=NodeStack[NSP];
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Other tasks');
Node.NodeType:=ntNormal;
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Editing text (the Edit Mode)');
Node.NodeType:=ntNormal;
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('By pressing C or Enter you will enter in "Edit Mode". In this mode you can edi' +
't the node''s text just by typing it. You can also use the following keys while ' +
'in this mode:');
Node.NodeType:=ntNormal;
Node.Open:=True;
Node.WasOpen:=True;
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Arrows will move you around');
Node.NodeType:=ntNormal;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Home will move you at the beginning of the text');
Node.NodeType:=ntNormal;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('End will move you at the end of the text');
Node.NodeType:=ntNormal;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Esc will cancel the edit. In some cases when a new node is being edited (like ' +
'when adding many items in a row via A or I) this will remove the node (don''t wo' +
'rry, the node will be removed only if there was no text in it)');
Node.NodeType:=ntNormal;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Delete will delete the character under the cursor');
Node.NodeType:=ntNormal;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Backspace will delete the character at the left and move the cursor there');
Node.NodeType:=ntNormal;
Dec(NSP);
Node:=NodeStack[NSP];
Dec(NSP);
Node:=NodeStack[NSP];
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Deleting and Pasting nodes');
Node.NodeType:=ntNormal;
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Using the D or Delete keys you can delete a node (you need to confirm the dele' +
'tion by pressing D or Delete again). When the node is deleted, it is not remove' +
'd completely from the memory but kept around to be pasted in some other place i' +
'n the tree.');
Node.NodeType:=ntNormal;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Using the P key you can paste a previously deleted node above the selected nod' +
'e. If the selected node is a temporary node created by Outliner Lighto without ' +
'text then the previously deleted node replaces the temporary node.');
Node.NodeType:=ntNormal;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Note that if you delete two nodes, the first node will be lost. Outliner Light' +
'o remembers only the last deleted node.');
Node.NodeType:=ntNormal;
Dec(NSP);
Node:=NodeStack[NSP];
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Moving nodes around (the Grab Mode)');
Node.NodeType:=ntNormal;
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('By pressing G you enter in the "Grab Mode" which you can use to move the selec' +
'ted node around the node hierarchy (think of it as grabbing the node from the h' +
'ierarchy and moving it around). While in Grab Mode the following keys apply:');
Node.NodeType:=ntNormal;
Node.Open:=True;
Node.WasOpen:=True;
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('In grab mode you use the arrow keys (sorry, no hjkl for the moment) to move th' +
'e node like you would change the selected node. With the up/down arrows you mov' +
'e the node in the same level. With the left/right arrows you demote and promote' +
' the node in the hierarchy.');
Node.NodeType:=ntNormal;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('To drop the node (leave the tree as you see it with the node at the point it i' +
's now), press G or Enter.');
Node.NodeType:=ntNormal;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('To cancel the operation and restore the tree as it was, press Escape.');
Node.NodeType:=ntNormal;
Dec(NSP);
Node:=NodeStack[NSP];
Dec(NSP);
Node:=NodeStack[NSP];
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Creating "tickable" nodes for automatic TODO lists, etc');
Node.NodeType:=ntNormal;
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('To change the type of a node, press T. This will switch it between "normal" an' +
'd "tickable".');
Node.NodeType:=ntNormal;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('A tickable leaf node can be ticked and unticked using X.');
Node.NodeType:=ntNormal;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('A tickable node with children is only ticked when all of its children are tick' +
'ed. Otherwise a percentage of the ticked children is shown with a different col' +
'or depending on the progress.');
Node.NodeType:=ntNormal;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Example');
Node.NodeType:=ntNormal;
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Stuff to do');
Node.NodeType:=ntTickable;
Node.Open:=True;
Node.WasOpen:=True;
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Make coffee');
Node.NodeType:=ntTickable;
Node.Tick:=True;
Node.Open:=True;
Node.WasOpen:=True;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Clean the house');
Node.NodeType:=ntTickable;
Node.Open:=True;
Node.WasOpen:=True;
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Clean the office');
Node.NodeType:=ntTickable;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Clean the kitchen');
Node.NodeType:=ntTickable;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Clean the hall');
Node.NodeType:=ntTickable;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Rest a bit');
Node.NodeType:=ntTickable;
Node.Tick:=True;
Dec(NSP);
Node:=NodeStack[NSP];
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Cook something');
Node.NodeType:=ntTickable;
Node.Tick:=True;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Clean the dishes');
Node.NodeType:=ntTickable;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Write some code');
Node.NodeType:=ntTickable;
Node.Open:=True;
Node.WasOpen:=True;
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Go online');
Node.NodeType:=ntTickable;
Node.Tick:=True;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Spend time on Reddit');
Node.NodeType:=ntTickable;
Node.Tick:=True;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Spend time on YouTube');
Node.NodeType:=ntTickable;
Node.Tick:=True;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Spend time on MSN');
Node.NodeType:=ntTickable;
Node.Tick:=True;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Spend time on Wikipedia');
Node.NodeType:=ntTickable;
Node.Tick:=True;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Read email');
Node.NodeType:=ntTickable;
Node.Tick:=True;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Implement the missing functionality');
Node.NodeType:=ntTickable;
Dec(NSP);
Node:=NodeStack[NSP];
Dec(NSP);
Node:=NodeStack[NSP];
Dec(NSP);
Node:=NodeStack[NSP];
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('A normal (non-tickable) leaf inside a tickable node will have a double dash in' +
' front of it and use a brighter color. This can be used to separate items in a ' +
'list without adding further hierarchy.');
Node.NodeType:=ntNormal;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Example');
Node.NodeType:=ntNormal;
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('To buy');
Node.NodeType:=ntTickable;
Node.Tick:=True;
Node.Open:=True;
Node.WasOpen:=True;
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('From the first level');
Node.NodeType:=ntNormal;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Meat');
Node.NodeType:=ntTickable;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Cheese');
Node.NodeType:=ntTickable;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Sugar');
Node.NodeType:=ntTickable;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('From the second level');
Node.NodeType:=ntNormal;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Milk');
Node.NodeType:=ntTickable;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Coffee');
Node.NodeType:=ntTickable;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Rice');
Node.NodeType:=ntTickable;
Dec(NSP);
Node:=NodeStack[NSP];
Dec(NSP);
Node:=NodeStack[NSP];
Dec(NSP);
Node:=NodeStack[NSP];
Dec(NSP);
Node:=NodeStack[NSP];
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('About');
Node.NodeType:=ntNormal;
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('Outliner Lighto was made by Kostas "Bad Sector" Michalopoulos');
Node.NodeType:=ntNormal;
Node.Open:=True;
Node.WasOpen:=True;
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('It was made in Free Pascal');
Node.NodeType:=ntNormal;
Node.Open:=True;
Node.WasOpen:=True;
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('http://freepascal.org');
Node.NodeType:=ntNormal;
Dec(NSP);
Node:=NodeStack[NSP];
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('You can find it at https://github.com/badsector/ol');
Node.NodeType:=ntNormal;
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('You can email me at badsectoracula@gmail.com');
Node.NodeType:=ntNormal;
Dec(NSP);
Node:=NodeStack[NSP];
Dec(NSP);
Node:=NodeStack[NSP];
NodeStack[NSP]:=Node;
Inc(NSP);
Node:=Node.AddStr('The program was inspired from "Hierarchical Notebook" by 0yvind Kolas');
Node.NodeType:=ntNormal;
Dec(NSP);
Node:=NodeStack[NSP];
Dec(NSP);
Node:=NodeStack[NSP];
{ === CUTCUT === The code above is generated with olol2pas === CUTCUT === }
end;
procedure DestroyTree;
begin
FreeAndNil(Root);
end;
function SaveTree(FileName: string; Root: TNode): Boolean;
var
f: TextFile;
begin
Assign(f, FileName);
{$I-}
ReWrite(f);
{$I+}
if IOResult <> 0 then Exit(False);
Result:=True;
WriteLn(f, 'NOTE');
WriteLn(f, 'NOTE Saved by Outliner Lighto version ', VERSION);
WriteLn(f, 'NOTE');
Root.Save(f);
WriteLn(f, 'STOP');
Close(f);
end;
function LoadTree(FileName: string; var Root: TNode): Boolean;
var
f: TextFile;
s, Cmd: string;
function FindTarget(Addr: string): TNode;
var
Parts: array of Integer;
s: string = '';
i: Integer;
begin
Addr:=Trim(Addr);
if Addr='' then Exit(nil);
SetLength(Parts, 0);
for i:=1 to Length(Addr) do begin
if Addr[i] in [' ', #9] then begin
if s <> '' then begin
SetLength(Parts, Length(Parts) + 1);
try
Parts[Length(Parts) - 1]:=StrToInt(s);
except
Result:=nil;
Exit;
end;
s:='';
end;
end else if Addr[i] in ['0'..'9'] then begin
s:=s + Addr[i];
end;
end;
if s <> '' then begin
SetLength(Parts, Length(Parts) + 1);
try
Parts[Length(Parts) - 1]:=StrToInt(s);
except
Result:=nil;
Exit;
end;
end;
Result:=Root;
for i:=0 to Length(Parts) - 1 do begin
if (Parts[i] >= 0) and (Parts[i] < Length(Result.Children)) then Result:=Result.Children[Parts[i]] else Exit(nil);
end;
if Result=Root then Result:=nil;
end;
procedure FixTarget(ANode: TNode);
var
i: Integer;
begin
if ANode.NodeType=ntPointer then
ANode.Target:=FindTarget(ANode.TargetAddress)
else begin
for i:=0 to Length(ANode.Children) - 1 do FixTarget(ANode.Children[i]);
end;
end;
begin
Assign(f, FileName);
{$I-}
Reset(f);
{$I+}
if IOResult <> 0 then Exit(False);
Result:=True;
DestroyTree;
while not Eof(f) do begin
Readln(f, s);
if Length(s) < 4 then continue;
Cmd:=Copy(s, 1, 4);
if Cmd='STOP' then break;
if Cmd='NODE' then begin
FreeAndNil(Root);
Root:=TNode.Create;
Root.Load(f);
end;
end;
Close(f);
FixTarget(Root);
end;
initialization
Root:=nil;
end.
|
unit uVarianteFunctions;
interface
uses DB, Sysutils;
function ConvVariant(FieldType : TFieldType; Value : String) : Variant;
function VarHigh(MyVariant : Variant) : integer;
function VarToNum(MyVariant : Variant) : Variant;
function VarToBol(MyVariant : Variant) : Variant;
function ConvVarArray(cString : String) : Variant;
implementation
function ConvVariant(FieldType : TFieldType; Value : String) : Variant;
begin
if FieldType in [ftString, ftDateTime, ftDate, ftMemo] then
Result := Value
else
Result := StrToInt(Value);
end;
function VarHigh(MyVariant : Variant) : integer;
begin
Result := VarArrayHighBound(MyVariant, VarArrayDimCount(MyVariant));
end;
function VarToNum(MyVariant : Variant) : Variant;
begin
if TVarData(MyVariant).VType <> varNull then
Result := MyVariant
else
Result := 0;
end;
function VarToBol(MyVariant : Variant) : Variant;
begin
if TVarData(MyVariant).VType <> varNull then
Result := MyVariant
else
Result := False;
end;
function ConvVarArray(cString : String) : Variant;
var
NewArray : Variant;
i : integer;
nLenInd, Count : integer;
cTemp : String;
begin
{ Testa se é necessário }
if Pos(';', cString) = 0 then
begin
Result := cString;
Exit;
end;
{ Rotina que converte uma string separada
por ; para Variant Array }
NewArray := VarArrayCreate([0, 10], varVariant);
{ seta variaveis iniciais }
cTemp := '';
nLenInd := Length(cString) + 1;
Count := -1;
for i := 1 to nLenInd do
begin
if (cString[i] = ';') or
(i = nLenInd) then
begin
{ acrescenta ao variant array }
Inc(Count);
NewArray[Count] := cTemp;
cTemp := '';
end
else
begin
cTemp := cTemp + cString[i];
end;
end;
Result := NewArray;
end;
end.
|
unit utf8util;
interface
// RFC 2279
function EncodeUTF8 (S: WideString): String;
function DecodeUTF8 (S: String): WideString;
// *** //
// Created: //
// October 2. 2004 //
// By R.M. Tegel //
// //
// Discription: //
// UTF8 Encode and Decode functions //
// Encode and Decode UTF to and from WideString //
// //
// Limitations: //
// 4-byte UTF decoding not supported. //
// No effort is done to mask 4-byte UTF character to two-byte WideChar //
// 4-byte characters will be replace by space (#32) //
// This should not affect further decoding. //
// //
// Background: //
// Created as independant UTF8 unit to support libsql //
// Targeted to be more effective than borland's implementation in D7+ //
// especially on large strings. //
// //
// License: //
// Modified Artistic License //
// The MAL license is compatible with almost any open-source license //
// Especially including but no limited to GPL, LGPL and BSD //
// Main issues about this licese: //
// You may use this unit for any legal purpose you see fit //
// You may freely modify and redistribute this unit as long as //
// you leave author(s) name(s) as contributor / original creator //
// You may use this unit in closed-source commercial applications //
// You may include this unit in your projects' source distribution //
// You may re-license this unit as GPL or BSD if needed for your project //
// //
// Happy Programming ;) //
// Rene //
// *** //
implementation
function EncodeUTF8(S: WideString): String;
var rl: Integer;
procedure Plus (c: byte);
begin
inc (rl);
//pre-allocation to improve performance:
if rl>length(Result) then
SetLength (Result, length(Result)+2048);
Result[rl] := char(c);
end;
var i: Integer;
c: Word;
begin
//alter this to length(S) * 2 if you expect a _lot_ ('only') of non-ascii
//for max speed.
SetLength (Result, 20+round (length(S) * 1.2));
rl := 0;
for i:=1 to length (S) do
begin
c := Word(S[i]);
if c<=$7F then //single byte in valid ascii range
Plus (c)
else
if c<$7FF then //two-byte unicode needed
begin
Plus ($C0 or (c shr 6));
Plus ($80 or (c and $3F));
end
else
begin //three byte unicode needed
//Note: widestring specifies only 2 bytes
//so, there is no need for encoding up to 4 bytes.
Plus ($E0 or (c shr 12));
Plus ($80 or ((c and $FFF) shr 6));
Plus ($80 or (c and $3F));
end;
end;
SetLength (Result, rl);
end;
function DecodeUTF8 (S: String): WideString;
var rl: Integer;
procedure Plus (c: word);
begin
inc (rl);
if (rl>length(Result)) then //alloc some extra mem
SetLength (Result, length(Result)+512);
Result[rl] := WideChar(c);
end;
var b,c,d: byte;
i,l: Integer;
begin
//Result := '';
SetLength (Result, length(S));
rl := 0;
i := 1;
l := length(S);
while i<=l do
begin
b := byte(S[i]);
if (b and $80)=0 then //7-bit
Plus (b)
else
if (b and $E0)=$C0 then //11-bit
begin
if i<l then //range check
c:=byte(S[i+1])
else
c:=$80;
if (c and $C0)<>$80 then
c := $80; //error. tag with zero. sorry.
b:=b and $1F;
c:=c and $3F;
plus (b shl 6 or c);
inc (i);
end
else
if (b and $F0) = $E0 then //16-bit
begin
if i<l then
c := byte(S[i+1])
else
c := $80;
if i<l-1 then
d := byte (S[i+2])
else
d := $80;
if (c and $C0)<>$80 then
c := $80; //error. tag with zero. sorry.
if (d and $C0)<>$80 then
d := $80; //error. tag with zero. sorry.
b := b and $0F;
c := c and $3F;
d := d and $3F;
plus ((b shl 12) or (c shl 6) or d);
inc (i,2);
end
else
begin //we have a problem here. a value > 16 bit was encoded
//obviously, this doesn't fit in a widestring..
//fix: leave blank ('space'). sorry.
Plus (ord(' '));
b := b shl 1;
repeat
b := b shl 1;
inc (i);
until (b and $80)=0;
end;
inc (i);
end;
SetLength (Result, rl);
end;
end.
|
unit LuaWrapper;
interface
{$IFDEF FPC}
{$mode objfpc}{$H+}
{$TYPEDADDRESS ON}
{$ENDIF}
{$I pLua.inc}
{$DEFINE TLuaAsComponent}
{$DEFINE TLuaHandlersAsIsObjectType}
uses
Classes, SysUtils,
lua,
pLua,
pLuaObject, pLuaRecord;
type
TLua = class;
TLuaOnException = procedure( Title: ansistring; Line: Integer; Msg: ansistring;
var handled : Boolean) {$IFDEF TLuaHandlersAsIsObjectType}of object{$ENDIF};
TLuaOnLoadLibs = procedure( LuaWrapper : TLua ) {$IFDEF TLuaHandlersAsIsObjectType}of object{$ENDIF};
{ TLUA }
TLUA=class{$IFDEF TLuaAsComponent}(TComponent){$ENDIF}
private
FOnException: TLuaOnException;
FOnLoadLibs: TLuaOnLoadLibs;
FUseDebug: Boolean;
FUserObj: TObject;
L : Plua_State;
FScript,
FLibFile,
FLibName: AnsiString;
FErrHandlerFunc: AnsiString;
FMethods : TStringList;
FErrHandler: Integer;
//Lua internal objects
FLuaObjects : TList;
FLuaClasses : TLuaClassList;
FLuaRecords : TLuaRecordList;
FintLuaRecords : TList;
FLuaDelegates : TList;
FClassTypesList : TLuaClassTypesList;
FRecordTypesList : TLuaRecordTypesList;
FLuaSelf : PLuaInstanceInfo;
procedure ClearObjects(LeakWarnings: boolean);
procedure ClearRecords;
function ExceptionBackTrace: string;
function GetLuaCPath: AnsiString;
function GetLuaPath: AnsiString;
function GetValue(valName : AnsiString): Variant;
procedure LoadScriptStr(const Script: string);
procedure PushErrorHandler;
procedure SetLibName(const Value: AnsiString);
procedure SetLuaCPath(const AValue: AnsiString);
procedure SetLuaPath(const AValue: AnsiString);
procedure OpenLibs;
procedure SetOnException(const AValue: TLuaOnException);
procedure SetOnLoadLibs(const AValue: TLuaOnLoadLibs);
procedure SetUseDebug(const AValue: Boolean);
procedure ErrorTest(errCode : Integer);
procedure HandleException(E : Exception);
procedure SetUserObj(AValue: TObject);
procedure SetValue(valName : AnsiString; const AValue: Variant);
procedure ExecuteScript(NArgs, NResults:integer);
public
constructor Create{$IFDEF TLuaAsComponent}(anOwner : TComponent); override;{$ENDIF}
{$IFDEF TLuaAsComponent}constructor Create;{$ENDIF}
destructor Destroy; override;
procedure Close;
procedure Open;
function Owns(Obj:TObject):boolean;
//mark given object as being ready for garbage collection
function ObjMarkFree(Obj:TObject):boolean;overload;
procedure ObjMarkFree(const Obj:TObjArray);overload;
//test internal state (global variable, etc)
procedure CheckIntegrity;
procedure GarbageCollect;
procedure LoadScript(const Script : AnsiString);
procedure LoadFile(const FileName:AnsiString);
//Loads function and saves it in lua state under given name.
//It's purpose is to run it multiple times without reloading.
procedure LoadFunctionFromFile(const FileName:string; const FunctionSaveAs:string);
procedure LoadFunctionFromScript(const Script:string; const FunctionSaveAs:string);
//Loads all functions with names FuncNames and bodies from FuncDumps
procedure LoadFunctionFromStrings(FuncNames:TStrings; FuncDumps:TStrings);
procedure Execute;
function ExecuteAsFunctionObj(const FunctionName:string):TObject;
function ExecuteAsFunctionObjList(const FunctionName:string):TObjArray;
procedure ExecuteAsFunctionStrList(const Script: string; ResultTable: TStrings; KeyTable:TStrings = nil);
procedure ExecuteAsFunction(const Script: string; const args:array of Variant; Results : PVariantArray = nil;
VariantHandler:TLuaVariantHandler = nil; CdataHandler:TLuaCdataHandler = nil);
procedure ExecuteCmd(Script:AnsiString);
procedure ExecuteAsRepl(const Script:String; out ReplResult:string);
procedure ExecuteFile(FileName : AnsiString);
//simple registering of C-function. No proper support for exception handling!!!
procedure RegisterLuaMethod(const aMethodName: AnsiString; Func: lua_CFunction);
//registering of pascal-function. Proper support for exception handling!!!
procedure RegisterLuaMethod(const aMethodName: AnsiString; Func: TLuaProc);
procedure RegisterLuaMethod(const aPackage, aMethodName: AnsiString; Func: TLuaProc);
procedure RegisterLuaTable(PropName: AnsiString; reader: lua_CFunction; writer : lua_CFunction = nil);
function FunctionExists(const aMethodName:AnsiString; TableIdx:Integer = LUA_GLOBALSINDEX) : Boolean;
function FunctionExists(const Package, aMethodName: AnsiString): Boolean;
function CallFunction( FunctionName :AnsiString;
const Args: array of Variant; //necessary to be able to call using [...] (array of const)
Results : PVariantArray = nil;
VariantHandler:TLuaVariantHandler = nil;
CdataHandler:TLuaCdataHandler = nil):Integer;overload;
function TableExists(const TableName:string):boolean;
function TableFunctionExists(TableName, FunctionName : AnsiString; out tblidx : Integer) : Boolean; overload;
function TableFunctionExists(TableName, FunctionName : AnsiString) : Boolean; overload;
function CallTableFunction( TableName, FunctionName :AnsiString;
const Args: array of Variant;
Results : PVariantArray = nil):Integer;
procedure ObjArraySet(const varName:String; const A:TObjArray; C: TLuaClassId; FreeGC:boolean = False; KeepRef:boolean = True);
procedure ObjSet(const varName:String; const O:TObject; C: TLuaClassId; FreeGC:boolean = False; KeepRef:boolean = True);
procedure ObjSetEmpty(const varName:String);
function ObjGet(const varName:string):TObject;
procedure GlobalVarClear(const varName:string);
procedure GlobalObjectNames(List: TStrings; LuaTypes: TLuaObjectTypes);
property ErrHandlerFunc : AnsiString read FErrHandlerFunc write FErrHandlerFunc;
property ScriptText: AnsiString read FScript write FScript;
property ScriptFile: AnsiString read FLibFile write FLibFile;
property LibName : AnsiString read FLibName write SetLibName;
property LuaState : Plua_State read L;
property LuaPath : AnsiString read GetLuaPath write SetLuaPath;
property LuaCPath : AnsiString read GetLuaCPath write SetLuaCPath;
property UseDebug : Boolean read FUseDebug write SetUseDebug;
property Value[valName : AnsiString] : Variant read GetValue write SetValue; default;
property OnException : TLuaOnException read FOnException write SetOnException;
property OnLoadLibs : TLuaOnLoadLibs read FOnLoadLibs write SetOnLoadLibs;
// singleton user-defined object. Freed on assign/destroy
property UserObj : TObject read FUserObj write SetUserObj;
end;
TLuaInternalState = class(TLua)
//class to be used by Lua handlers
public
property LuaObjects : TList read FLuaObjects;
property LuaClasses : TLuaClassList read FLuaClasses;
property intLuaRecords : TList read FintLuaRecords;
property LuaDelegates : TList read FLuaDelegates;
property LuaRecords : TLuaRecordList read FLuaRecords;
property ClassTypesList : TLuaClassTypesList read FClassTypesList;
property RecordTypesList : TLuaRecordTypesList read FRecordTypesList;
end;
{ TLUAThread }
TLUAThread=class
private
FMaster : TLUA;
FMethodName: AnsiString;
FTableName: AnsiString;
L : PLua_State;
FThreadName : AnsiString;
function GetIsValid: Boolean;
public
constructor Create(LUAInstance: TLUA; ThreadName : AnsiString);
destructor Destroy; override;
function Start(TableName : AnsiString; AMethodName : AnsiString; const ArgNames: array of AnsiString; var ErrorString : AnsiString) : Boolean;
function Resume(EllapsedTime : lua_Number; Args : array of Variant; var ErrorString : AnsiString) : Boolean;
property LuaState : Plua_State read L;
published
property IsValid : Boolean read GetIsValid;
property ThreadName : AnsiString read FThreadName;
property MethodName : AnsiString read FMethodName;
property TableName : AnsiString read FTableName;
end;
{ TLUAThreadList }
TLUAThreadList=class
private
FThreads : TList;
FLUAInstance : TLUA;
function GetCount: Integer;
function GetThread(index: integer): TLUAThread;
public
constructor Create(LUAInstance: TLUA);
destructor Destroy; override;
procedure Process(EllapsedTime : lua_Number; Args : array of Variant; var ErrorString : AnsiString);
function SpinUp(TableName, AMethodName, ThreadName : AnsiString; var ErrorString : AnsiString) : Boolean;
function IndexOf(ThreadName : AnsiString): Integer;
procedure Release(ThreadIndex : Integer);
property Thread[index:integer]: TLUAThread read GetThread;
published
property Count : Integer read GetCount;
end;
//To be used in Lua handlers
//Use carefully, it is global for Lua instance!!!
function LuaSelf(L : PLua_State):TLuaInternalState;
procedure LuaObjects_Free(S:TLuaInternalState; instance:PLuaInstanceInfo);
procedure LuaObjects_Add(S:TLuaInternalState; instance:PLuaInstanceInfo);
procedure LuaRecs_Free(S:TLuaInternalState; instance:PLuaRecordInstanceInfo);
implementation
uses
//Classes,
Variants;
const
Lua_Self = '__LuaWrapperSelf';
constructor TLUA.Create{$IFDEF TLuaAsComponent}(anOwner: TComponent){$ENDIF};
begin
{$IFDEF TLuaAsComponent}inherited;{$ENDIF}
FUseDebug := false;
FMethods := TStringList.Create;
FUserObj := nil;
FLuaObjects := TList.Create;
FLuaClasses := TLuaClassList.Create;
FintLuaRecords := TList.Create;
FLuaDelegates := TList.Create;
FLuaRecords := TLuaRecordList.Create;
FClassTypesList := TLuaClassTypesList.Create;
FRecordTypesList := TLuaRecordTypesList.Create;
FLibName:='main';
Open;
end;
{$IFDEF TLuaAsComponent}
constructor TLUA.Create;
begin
Create(nil);
end;
{$ENDIF}
procedure TLUA.ClearObjects(LeakWarnings:boolean);
// Frees/unregistered manually-tracked objects
var
i : Integer;
nfo : PLuaInstanceInfo;
begin
if FLuaObjects.Count > 0 then
Log('Warning!!! %d objects left unfreed.', [FLuaObjects.Count]);
i := FLuaObjects.Count-1;
while i > -1 do
begin
nfo := PLuaInstanceInfo(FLuaObjects[i]);
if LeakWarnings then
begin
//we cannot trust nfo^.obj is still valid here, so do not try to read ClassName via nfo^.obj.
//use only debug info when accesible.
if nfo^.LuaRef <> LUA_NOREF then
LogDebug('Lua object $%P (%s) has lua ref (%d) unfreed.',
[ Pointer(nfo^.obj), {$IFDEF DEBUG}nfo^.ClassName{$ELSE}'unknown'{$ENDIF}, nfo^.LuaRef ]);
LogDebug('Lua object $%P (%s) memory leak. Freeing...', [ Pointer(nfo^.obj), {$IFDEF DEBUG}nfo^.ClassName{$ELSE}'unknown'{$ENDIF} ]);
end;
try
LuaObjects_Free( TLuaInternalState(Self), nfo );
except
end;
dec(i);
end;
end;
procedure TLUA.ClearRecords;
var
i : Integer;
nfo : PLuaRecordInstanceInfo;
begin
i := FintLuaRecords.Count-1;
while i > -1 do
begin
nfo := PLuaRecordInstanceInfo(FintLuaRecords[i]);
if nfo^.l = l then
FintLuaRecords.Remove(nfo);
dec(i);
end;
end;
destructor TLUA.Destroy;
var instance:PLuaInstanceInfo;
rec_instance:PLuaRecordInstanceInfo;
begin
Close;
FreeAndNil(FUserObj);
FMethods.Free;
FreeAndNil(FLuaObjects);
FreeAndNil(FLuaClasses);
FreeAndNil(FintLuaRecords);
FreeAndNil(FLuaDelegates);
FreeAndNil(FLuaRecords);
FreeAndNil(FClassTypesList);
FreeAndNil(FRecordTypesList);
inherited;
end;
procedure TLUA.ExecuteScript(NArgs, NResults: integer);
var errCode:Integer;
msg:string;
begin
if L = nil then
Open;
try
if FErrHandler = -1 then
raise Exception.Create('No error handler installed');
if (lua_gettop(l) <= 0) or
(lua_type(L, lua_gettop(l) - Nargs) <> LUA_TFUNCTION) then
raise Exception.Create('No script is loaded at stack');
//ErrorTest(lua_pcall(L, 0, NResults, 0));
errCode:=lua_pcall(L, NArgs, NResults, FErrHandler);
if errCode <> 0 then
begin
msg := plua_tostring(l, -1);
HandleException(LuaException.Create(msg));
end;
finally
FErrHandler:=-1; //Make sure error handler is not re-used.
end;
end;
procedure TLUA.Execute;
begin
ExecuteScript(0,0);
end;
function TLUA.ExecuteAsFunctionObj(const FunctionName:string): TObject;
var tix:Integer;
StartTop:integer;
begin
Result:=nil;
StartTop:=lua_gettop(l);
try
PushErrorHandler;
//load function with name FunctionName on stack
lua_getglobal(l, PChar(FunctionName));
ExecuteScript(0,LUA_MULTRET);
tix:=lua_gettop(l);
if tix > 0 then
begin
if lua_type(L,-1) = LUA_TUSERDATA then
Result:=plua_getObject(l, tix)
else
lua_pop(l, 1);
end;
finally
plua_EnsureStackBalance(l, StartTop);
end;
end;
function TLUA.ExecuteAsFunctionObjList(const FunctionName: string): TObjArray;
var tix:Integer;
StartTop:integer;
O:TObject;
begin
SetLength(Result,0);
StartTop:=lua_gettop(l);
try
PushErrorHandler;
//load function with name FunctionName on stack
lua_getglobal(l, PChar(FunctionName));
ExecuteScript(0,LUA_MULTRET);
tix:=lua_gettop(l);
if tix > 0 then
begin
case lua_type(L,-1) of
LUA_TUSERDATA:
begin
O:=plua_getObject(l, tix);
SetLength(Result, 1);
Result[0]:=O;
end;
LUA_TTABLE:
begin
Result:=plua_getObjectTable(l, tix);
end;
else
lua_pop(l, 1);
end;
end;
finally
plua_EnsureStackBalance(l, StartTop);
end;
end;
procedure TLUA.LoadScriptStr(const Script:string);
//loads string on Lua stack
begin
//Can't use luaL_loadstring here, as Script can contain zeroes in bytecode strings
ErrorTest( luaL_loadbuffer(l, PChar(Script), Length(Script), 'dyn_str_script') );
end;
procedure TLUA.ExecuteAsFunctionStrList(const Script: string; ResultTable:TStrings; KeyTable:TStrings) ;
var StartTop:integer;
begin
ResultTable.Create;
StartTop:=lua_gettop(l);
try
PushErrorHandler;
LoadScriptStr(Script);
ExecuteScript(0,LUA_MULTRET);
plua_popstrings(l, ResultTable, KeyTable);
finally
plua_EnsureStackBalance(l, StartTop);
end;
end;
procedure TLUA.ExecuteAsFunction(const Script: string; const args: array of Variant; Results: PVariantArray;
VariantHandler:TLuaVariantHandler; CdataHandler:TLuaCdataHandler);
var StartTop, result_count, TopBeforeExecute:integer;
begin
StartTop:=lua_gettop(l);
try
PushErrorHandler;
TopBeforeExecute:=lua_gettop(l); //have to be called immediately before luaL_loadstring
LoadScriptStr(Script);
plua_pushvariants(l, args, False, VariantHandler);
ExecuteScript(Length(args), LUA_MULTRET);
if Results <> nil then
begin
result_count:=lua_gettop(l) - TopBeforeExecute;
Results^:=plua_popvariants(l, result_count, True, CdataHandler);
end;
finally
plua_EnsureStackBalance(l, StartTop);
end;
end;
procedure TLUA.ExecuteCmd(Script: AnsiString);
var StartTop:Integer;
begin
if L= nil then
Open;
StartTop:=lua_gettop(l);
try
PushErrorHandler;
ErrorTest(luaL_loadbuffer(L, PChar(Script), Length(Script), PChar(LibName)));
ExecuteScript(0,0);
finally
plua_EnsureStackBalance(l, StartTop);
end;
end;
function TLUA.ExceptionBackTrace:string;
var
FrameNumber,
FrameCount : longint;
Frames : PPointer;
begin
Result:='';
if RaiseList=nil then
exit;
Result:=BackTraceStrFunc(RaiseList^.Addr);
FrameCount:=RaiseList^.Framecount;
Frames:=RaiseList^.Frames;
for FrameNumber := 0 to FrameCount-1 do
Result:=Result + sLineBreak + BackTraceStrFunc(Frames[FrameNumber]);
end;
procedure TLUA.ExecuteAsRepl(const Script: String; out ReplResult: string);
var StartTop:Integer;
r:String;
ExceptThrown:boolean;
begin
ExceptThrown:=false;
ReplResult:='';
if L= nil then
Open;
StartTop:=lua_gettop(l);
try
try
PushErrorHandler;
ErrorTest(luaL_loadbuffer(L, PChar(Script), Length(Script), PChar(LibName)));
ExecuteScript(0,LUA_MULTRET); // LUA_MULTRET - нас интересуют _все_ результаты
except
on E:Exception do
begin
ReplResult:=E.Message + sLineBreak + ExceptionBackTrace;
ExceptThrown:=true;
end;
end;
//пока есть результаты - продолжаем выталкивать из стека
while lua_gettop(l) <> StartTop do
begin
if (not ExceptThrown) and (lua_type(L,-1) = LUA_TSTRING) then
begin
r := plua_tostring(l, -1);
ReplResult:=r + sLineBreak + ReplResult; //последний результат лежит на верху стека
end;
lua_pop(l, 1);
end;
finally
plua_EnsureStackBalance(l, StartTop);
end;
end;
procedure TLUA.ExecuteFile(FileName: AnsiString);
var
Script : AnsiString;
sl : TStringList;
StartTop: Integer;
begin
if L = nil then
Open;
StartTop:=lua_gettop(l);
try
PushErrorHandler;
ErrorTest(luaL_loadfile(L, PChar(FileName)));
ExecuteScript(0,0);
finally
plua_EnsureStackBalance(l, StartTop);
end;
end;
procedure TLUA.SetLuaPath(const AValue: AnsiString);
begin
lua_pushstring(L, 'package');
lua_gettable(L, LUA_GLOBALSINDEX);
lua_pushstring(L, 'path');
lua_pushstring(L, PChar(AValue));
lua_settable(L, -3);
end;
procedure TLUA.LoadFile(const FileName: AnsiString);
var StartTop:integer;
begin
if L = nil then
Open;
StartTop:=lua_gettop(l);
FLibFile := FileName;
FScript := '';
ErrorTest( luaL_loadfile(L, PChar(FileName)) );
plua_CheckStackBalance(l, StartTop+1);
end;
procedure TLUA.LoadFunctionFromFile(const FileName: string; const FunctionSaveAs:string);
var StartTop:integer;
begin
StartTop:=lua_gettop(l);
LoadFile(FileName);
lua_setglobal(L, PChar(FunctionSaveAs));
plua_CheckStackBalance(l, StartTop);
end;
procedure TLUA.LoadFunctionFromScript(const Script: string;
const FunctionSaveAs: string);
var StartTop:integer;
begin
StartTop:=lua_gettop(l);
LoadScript(Script);
lua_setglobal(L, PChar(FunctionSaveAs));
plua_CheckStackBalance(l, StartTop);
end;
procedure TLUA.LoadFunctionFromStrings(FuncNames: TStrings; FuncDumps: TStrings);
var i:Integer;
StartTop:integer;
begin
StartTop:=lua_gettop(l);
for i:=0 to FuncNames.Count-1 do
begin
LoadScriptStr(FuncDumps.Strings[i]);
lua_setglobal(L, PChar(FuncNames.Strings[i]));
end;
plua_CheckStackBalance(l, StartTop);
end;
procedure TLUA.LoadScript(const Script: AnsiString);
var StartTop:integer;
begin
if FScript <> Script then
Close;
if L = nil then
Open;
StartTop:=lua_gettop(l);
FScript := Trim(Script);
if FScript = '' then Exit;
FLibFile := '';
luaL_loadbuffer(L, PChar(Script), length(Script), PChar(LibName));
plua_CheckStackBalance(l, StartTop + 1);
end;
function TLUA.FunctionExists(const Package, aMethodName: AnsiString): Boolean;
var TopToBe, TableIdx:Integer;
begin
Result := False;
TopToBe:=lua_gettop(l);
try
lua_pushstring(L, PChar(Package));
lua_gettable(L, LUA_GLOBALSINDEX);
if lua_isnil(L, -1) then Exit;
TableIdx:=lua_gettop(l);
Result:=FunctionExists(aMethodName, TableIdx);
finally
plua_EnsureStackBalance(l, TopToBe);
end;
end;
function TLUA.FunctionExists(const aMethodName: AnsiString; TableIdx:Integer = LUA_GLOBALSINDEX): Boolean;
begin
lua_pushstring(L, PChar(aMethodName));
lua_rawget(L, TableIdx);
result := (not lua_isnil(L, -1)) and lua_isfunction(L, -1);
lua_pop(L, 1);
end;
procedure TLUA.RegisterLuaMethod(const aMethodName: AnsiString; Func: lua_CFunction);
begin
if L = nil then
Open;
lua_register(L, PChar(aMethodName), Func);
if FMethods.IndexOf(aMethodName) = -1 then
FMethods.AddObject(aMethodName, TObject(@Func))
else
FMethods.Objects[FMethods.IndexOf(aMethodName)] := TObject(@Func);
end;
procedure TLUA.RegisterLuaMethod(const aMethodName: AnsiString; Func: TLuaProc);
begin
if L = nil then
Open;
plua_RegisterMethod(l, aMethodName, Func);
end;
procedure TLUA.RegisterLuaMethod(const aPackage, aMethodName: AnsiString; Func: TLuaProc);
begin
if L = nil then
Open;
plua_RegisterMethod(l, aPackage, aMethodName, Func);
end;
procedure TLUA.RegisterLuaTable(PropName: AnsiString; reader: lua_CFunction;
writer: lua_CFunction);
begin
plua_RegisterLuaTable(l, PropName, reader, writer);
end;
procedure TLUA.SetLibName(const Value: AnsiString);
begin
FLibName := Value;
end;
procedure TLUA.SetLuaCPath(const AValue: AnsiString);
begin
lua_pushstring(L, 'package');
lua_gettable(L, LUA_GLOBALSINDEX);
lua_pushstring(L, 'cpath');
lua_pushstring(L, PChar(AValue));
lua_settable(L, -3);
end;
function TLUA.GetLuaPath: AnsiString;
begin
lua_pushstring(L, 'package');
lua_gettable(L, LUA_GLOBALSINDEX);
lua_pushstring(L, 'path');
lua_rawget(L, -2);
result := AnsiString(lua_tostring(L, -1));
end;
function TLUA.GetValue(valName : AnsiString): Variant;
var StartTop:Integer;
begin
StartTop:=lua_gettop(l);
result := NULL;
lua_pushstring(l, PChar(valName));
lua_rawget(l, LUA_GLOBALSINDEX);
try
result := plua_tovariant(l, -1);
finally
lua_pop(l, 1);
end;
plua_CheckStackBalance(l, StartTop);
end;
function TLUA.GetLuaCPath: AnsiString;
begin
lua_pushstring(L, 'package');
lua_gettable(L, LUA_GLOBALSINDEX);
lua_pushstring(L, 'cpath');
lua_rawget(L, -2);
result := AnsiString(lua_tostring(L, -1));
end;
function TLUA.CallFunction(FunctionName: AnsiString;
const Args: array of Variant; Results: PVariantArray = nil;
VariantHandler:TLuaVariantHandler = nil; CdataHandler:TLuaCdataHandler = nil): Integer;
var Package, FName:string;
TopToBe:Integer;
TableIdx:Integer;
begin
result := -1;
TopToBe:=lua_gettop(l);
try
try
//get a stack trace in case of error
PushErrorHandler;
//function name is complex - then first push its table on stack
plua_FuncNameParse(FunctionName, Package, FName);
if Package = '' then
begin
if FunctionExists(FunctionName) then
result := plua_callfunction(L, FunctionName, Args, Results, LUA_GLOBALSINDEX, FErrHandler, nil, VariantHandler, CdataHandler );
end
else
begin
if FunctionExists(Package, FName) then
begin
lua_pushstring(L, PChar(Package));
lua_gettable(L, LUA_GLOBALSINDEX);
TableIdx:=lua_gettop(l);
result := plua_callfunction(L, FName, Args, Results, TableIdx, FErrHandler, nil, VariantHandler, CdataHandler);
end;
end;
except
on E:Exception do
HandleException(E);
end;
finally
//error handler should be cleared here as well
plua_EnsureStackBalance(l, TopToBe);
end;
end;
function TLUA.TableExists(const TableName:string): boolean;
begin
Result:=pLua_TableExists(l, TableName);
end;
procedure TLUA.Close;
begin
FErrHandler:=-1;
if L <> nil then
begin
lua_close(L);
L := nil;
ClearObjects(True);
ClearRecords;
if FLuaSelf <> nil then
begin
plua_instance_free(nil, FLuaSelf);
end;
end;
FLibFile:='';
FScript:='';
end;
procedure TLUA.PushErrorHandler;
var Package, FName : string;
std_handler : boolean;
begin
std_handler := true;
if FErrHandlerFunc <> '' then
begin
plua_FuncNameParse(FErrHandlerFunc, Package, FName);
std_handler :=not ( (Package <> '') and (FName <> '') and FunctionExists(Package, FName) );
end;
if std_handler then
begin
// standard Lua stack tracer by default
Package := 'debug';
FName := 'traceback';
end;
//push error handler on stack to be able to reference it everywhere
// http://tinylittlelife.org/?p=254
lua_getglobal(L, PChar(Package));
//-1 is the top of the stack
lua_getfield(L, -1, PChar(FName));
//traceback is on top, remove package name from 2nd spot
lua_remove(L, -2);
FErrHandler:=lua_gettop(L);
end;
procedure TLUA.Open;
begin
if L <> nil then
Close;
L := lua_open;
OpenLibs;
//Register self in Lua VM to be able call from Lua code/native handlers
FLuaSelf:=plua_pushexisting_special(l, Self, nil, False);
lua_setglobal( L, PChar(Lua_Self) );
end;
function LuaSelf(L: PLua_State): TLuaInternalState;
var StartTop:Integer;
begin
StartTop:=lua_gettop(l);
Result:=TLuaInternalState(plua_GlobalObjectGet(l, Lua_Self));
//global VM object MUST BE registered, otherwise something really wrong.
if Result = nil then
plua_RaiseException(l, StartTop, 'Global Lua VM Self pointer is not registered');
if Result.ClassType <> TLUA then
plua_RaiseException(l, StartTop, 'Global Lua VM Self must be of type %s, but has type %s', [TLUA.ClassName, Result.ClassName]);
plua_CheckStackBalance(l, StartTop);
end;
procedure LuaObjects_Add(S:TLuaInternalState; instance:PLuaInstanceInfo);
begin
S.LuaObjects.Add( instance );
{$IFDEF DEBUG_LUA}
DumpStackTrace;
{$ENDIF}
end;
procedure LuaRecs_Free(S: TLuaInternalState; instance: PLuaRecordInstanceInfo);
var i:integer;
C:PLuaClassInfo;
RecInfo:PLuaRecordInfo;
begin
if instance^.OwnsInstance then
begin
RecInfo:=S.LuaRecords.RecInfoById[ instance^.RecordId ];
RecInfo^.Release(instance^.RecordPointer, nil);
end;
Freemem(instance);
end;
procedure LuaObjects_Free(S:TLuaInternalState; instance:PLuaInstanceInfo);
var i:integer;
C:PLuaClassInfo;
begin
i:=S.LuaObjects.IndexOf(instance);
if i <> -1 then
begin
if instance^.OwnsObject then
begin
C:= S.LuaClasses.ClassInfoById[ instance^.ClassId ];
if assigned(C^.Release) then
C^.Release(instance^.obj, nil)
else
instance^.obj.Free;
end;
if Instance^.Delegate <> nil then
Instance^.Delegate.Free;
Dispose(instance);
S.LuaObjects.Delete(i);
end;
end;
function TLUA.Owns(Obj: TObject): boolean;
var info:PLuaInstanceInfo;
begin
Result:=False;
info:=plua_GetObjectInfo(l, Obj);
if info = nil then Exit;
Result:=info^.OwnsObject;
end;
function TLUA.ObjMarkFree(Obj: TObject):boolean;
begin
Result:=False;
if l <> nil then
Result:=plua_ObjectMarkFree(l, Obj);
end;
procedure TLUA.ObjMarkFree(const Obj: TObjArray);
var n:integer;
begin
if l <> nil then
for n:=0 to High(Obj) do
plua_ObjectMarkFree(l, Obj[n]);
end;
procedure TLUA.CheckIntegrity;
begin
//Lua Self has its own checks
LuaSelf(l);
end;
procedure TLUA.GarbageCollect;
begin
if l <> nil then
lua_gc(l, LUA_GCCOLLECT, 0);
end;
procedure TLUA.OpenLibs;
var
I : Integer;
begin
luaL_openlibs(L);
if UseDebug then
luaopen_debug(L);
lua_settop(L, 0);
for I := 0 to FMethods.Count -1 do
RegisterLUAMethod(FMethods[I], lua_CFunction(Pointer(FMethods.Objects[I])));
FRecordTypesList.RegisterTo(L);
FClassTypesList.RegisterTo(L);
if assigned(FOnLoadLibs) then
FOnLoadLibs(self);
end;
procedure TLUA.SetOnException(const AValue: TLuaOnException);
begin
if FOnException=AValue then exit;
FOnException:=AValue;
end;
procedure TLUA.SetOnLoadLibs(const AValue: TLuaOnLoadLibs);
begin
if FOnLoadLibs=AValue then exit;
FOnLoadLibs:=AValue;
if (L <> nil) and (FOnLoadLibs <> nil) then
FOnLoadLibs(self);
end;
procedure TLUA.SetUseDebug(const AValue: Boolean);
begin
if FUseDebug=AValue then exit;
FUseDebug:=AValue;
end;
procedure TLUA.ErrorTest(errCode: Integer);
var
msg : AnsiString;
begin
if errCode <> 0 then
begin
msg := plua_tostring(l, -1);
lua_pop(l, 1);
HandleException(LuaException.Create(msg));
end;
end;
procedure TLUA.HandleException(E: Exception);
var
title, msg : AnsiString;
line : Integer;
handled : Boolean;
begin
handled := false;
if assigned(FOnException) then
begin
plua_spliterrormessage(e.Message, title, line, msg);
FOnException(title, line, msg, handled);
end;
if not handled then
//To raise the same exception, we need to construct another object.
//Otherwise it will crash later.
raise LuaException.Create(E.Message + sLineBreak + ExceptionBackTrace);
end;
procedure TLUA.SetUserObj(AValue: TObject);
begin
if FUserObj = AValue then Exit;
FreeAndNil(FUserObj);
FUserObj := AValue;
end;
procedure TLUA.SetValue(valName : AnsiString; const AValue: Variant);
var StartTop:Integer;
begin
StartTop:=lua_gettop(l);
if VarIsType(AValue, varString) then
begin
lua_pushliteral(l, PChar(valName));
lua_pushstring(l, PChar(AnsiString(AValue)));
lua_settable(L, LUA_GLOBALSINDEX);
end
else
begin
lua_pushliteral(l, PChar(valName));
plua_pushvariant(l, AValue);
lua_settable(L, LUA_GLOBALSINDEX);
end;
plua_CheckStackBalance(l, StartTop);
end;
function TLUA.CallTableFunction(TableName, FunctionName: AnsiString;
const Args: array of Variant; Results: PVariantArray): Integer;
var
tblidx : integer;
begin
try
if TableFunctionExists(TableName, FunctionName, tblidx) then
begin
lua_pushvalue(l, tblidx);
tblidx := lua_gettop(l);
result := plua_callfunction(l, FunctionName, args, results, tblidx)
end
else
result := -1;
except
on E: LuaException do
HandleException(E);
end;
end;
procedure TLUA.ObjArraySet(const varName: String; const A: TObjArray; C: TLuaClassId; FreeGC:boolean; KeepRef:boolean);
var n, tix:integer;
StartTop:integer;
begin
StartTop:=lua_gettop(l);
{
//if global var already exists ...
lua_getglobal(L, PChar(varName) );
if not lua_isnil(L, -1) then
begin
// ... remove it
lua_pushnil( L );
lua_setglobal( L, PChar(varName) );
end;
lua_pop(L, -1); //balance stack
}
lua_newtable(L); // table
for n:=0 to High(A) do
begin
lua_pushinteger(L, n+1); // table,key
pLuaObject.plua_pushexisting(l, A[n], C, FreeGC, KeepRef);
lua_settable(L,-3); // table
end;
lua_setglobal( L, PChar(varName) );
plua_CheckStackBalance(l, StartTop);
end;
procedure TLUA.ObjSet(const varName: String; const O: TObject;
C: TLuaClassId; FreeGC: boolean; KeepRef:boolean);
begin
pLuaObject.plua_pushexisting(l, O, C, FreeGC, KeepRef);
lua_setglobal( L, PChar(varName) );
end;
procedure TLUA.ObjSetEmpty(const varName: String);
begin
lua_pushnil(l);
lua_setglobal( L, PChar(varName) );
end;
function TLUA.ObjGet(const varName: string): TObject;
begin
Result:=plua_GlobalObjectGet(l, varName);
end;
procedure TLUA.GlobalVarClear(const varName: string);
begin
lua_pushstring(l, PChar(varName));
lua_pushnil(l);
lua_settable(L, LUA_GLOBALSINDEX);
end;
procedure TLUA.GlobalObjectNames(List: TStrings; LuaTypes: TLuaObjectTypes);
const
LuaFunc = 'meta.GlobalObjects';
var ObjL, ResList:TStringList;
Res:TVariantArray;
begin
ObjL:=TStringList.Create;
ResList:=TStringList.Create;
ResList.Duplicates:=dupIgnore;
try
if lotFunction in LuaTypes then
begin
CallFunction(LuaFunc, [Integer(lotFunction)], @Res);
VarToStrings(Res[0], ObjL);
ResList.AddStrings(ObjL);
end;
if lotFunctionSource in LuaTypes then
begin
CallFunction(LuaFunc, [Integer(lotFunctionSource)], @Res);
VarToStrings(Res[0], ObjL);
ResList.AddStrings(ObjL);
end;
if lotGlobalVars in LuaTypes then
begin
CallFunction(LuaFunc, [Integer(lotGlobalVars)], @Res);
VarToStrings(Res[0], ObjL);
ResList.AddStrings(ObjL);
end;
ResList.Sort;
List.Clear;
List.AddStrings(ResList);
finally
ObjL.Free;
ResList.Free;
end;
end;
function TLUA.TableFunctionExists(TableName,
FunctionName: AnsiString; out tblidx : Integer): Boolean;
begin
lua_pushstring(L, PChar(TableName));
lua_rawget(L, LUA_GLOBALSINDEX);
result := lua_istable(L, -1);
if result then
begin
tblidx := lua_gettop(L);
lua_pushstring(L, PChar(FunctionName));
lua_rawget(L, -2);
result := lua_isfunction(L, -1);
lua_pop(L, 1);
end
else
begin
tblidx := -1;
lua_pop(L, 1);
end;
end;
function TLUA.TableFunctionExists(TableName, FunctionName: AnsiString
): Boolean;
var
tblidx : Integer;
begin
result := TableFunctionExists(TableName, FunctionName, tblidx);
if result then
lua_pop(L, 1);
end;
{ TLUAThread }
function TLUAThread.GetIsValid: Boolean;
begin
lua_getglobal(L, PChar(FThreadName));
result := not lua_isnil(L, 1);
lua_pop(L, 1);
end;
constructor TLUAThread.Create(LUAInstance: TLUA; ThreadName: AnsiString);
begin
L := lua_newthread(LUAInstance.LuaState);
FThreadName := ThreadName;
lua_setglobal(LUAInstance.LuaState, PChar(ThreadName));
FMaster := LUAInstance;
end;
destructor TLUAThread.Destroy;
begin
lua_pushnil(FMaster.LuaState);
lua_setglobal(FMaster.LuaState, PChar(FThreadName));
inherited;
end;
function luaResume(L : PLua_State; NArgs:Integer; out Res : Integer) : Boolean;
begin
Res := lua_resume(L, NArgs);
result := Res <> 0;
end;
function TLUAThread.Start(TableName : AnsiString; AMethodName : AnsiString; const ArgNames: array of AnsiString; var ErrorString : AnsiString) : Boolean;
var
i,
rres : Integer;
begin
FTableName := TableName;
FMethodName := AMethodName;
if TableName <> '' then
begin
lua_pushstring(L, PChar(TableName));
lua_gettable(L, LUA_GLOBALSINDEX);
plua_pushstring(L, PChar(AMethodName));
lua_rawget(L, -2);
end
else
lua_getglobal(L, PChar(AMethodName));
for i := 0 to Length(ArgNames)-1 do
lua_getglobal(L, PChar(ArgNames[i]));
if luaResume(L, Length(ArgNames), rres) then
begin
ErrorString := lua_tostring(L, -1);
result := false;
exit;
end
else
result := true;
end;
function TLUAThread.Resume(EllapsedTime : lua_Number; Args : array of Variant; var ErrorString : AnsiString) : Boolean;
var
rres,
i : Integer;
msg : AnsiString;
begin
lua_pushnumber(L, EllapsedTime);
for i := 0 to Length(Args)-1 do
plua_pushvariant(L, Args[i]);
if luaResume(L, Length(Args)+1, rres) then
begin
ErrorString := lua_tostring(L, -1);
msg := 'Error ('+IntToStr(rres)+'): '+ErrorString;
result := false;
raise exception.Create(msg);
end
else
result := true;
end;
{ TLUAThreadList }
function TLUAThreadList.GetCount: Integer;
begin
result := FThreads.Count;
end;
function TLUAThreadList.GetThread(index: integer): TLUAThread;
begin
result := TLUAThread(FThreads[index]);
end;
constructor TLUAThreadList.Create(LUAInstance: TLUA);
begin
FLUAInstance := LUAInstance;
FThreads := TList.Create;
end;
destructor TLUAThreadList.Destroy;
var
T : TLUAThread;
begin
while FThreads.Count > 0 do
begin
T := TLUAThread(FThreads[FThreads.Count-1]);
FThreads.Remove(T);
T.Free;
end;
FThreads.Free;
inherited;
end;
procedure TLUAThreadList.Process(EllapsedTime: lua_Number; Args : array of Variant;
var ErrorString: AnsiString);
var
i : Integer;
begin
i := 0;
while i < Count do
begin
if not TLUAThread(FThreads[I]).Resume(EllapsedTime, Args, ErrorString) then
Release(i)
else
inc(i);
end;
end;
function TLUAThreadList.SpinUp(TableName, AMethodName, ThreadName: AnsiString; var ErrorString : AnsiString) : Boolean;
var
T : TLUAThread;
begin
T := TLUAThread.Create(FLUAInstance, ThreadName);
FThreads.Add(T);
result := T.Start(TableName, AMethodName, [], ErrorString);
end;
function TLUAThreadList.IndexOf(ThreadName: AnsiString): Integer;
var
i : Integer;
begin
result := -1;
i := 0;
while (result = -1) and (i<FThreads.Count) do
begin
if CompareText(ThreadName, TLUAThread(FThreads[i]).ThreadName) = 0 then
result := i;
inc(i);
end;
end;
procedure TLUAThreadList.Release(ThreadIndex: Integer);
var
T : TLUAThread;
begin
if (ThreadIndex < Count) and (ThreadIndex > -1) then
begin
T := TLUAThread(FThreads[ThreadIndex]);
FThreads.Delete(ThreadIndex);
T.Free;
end;
end;
initialization
finalization
end.
|
namespace NSTableView;
interface
uses
AppKit,
Foundation;
type
[IBObject]
MainWindowController = public class(NSWindowController, INSTableViewDelegate,INSTableViewDataSource)
private
people : NSMutableArray;
protected
public
[IBOutlet] tableView : NSTableView;
[IBOutlet] messageLabel : NSTextField;
method init: id; override;
[IBAction] method addPerson(sender : id);
[IBAction] method removePerson(sender : id);
method updateMessageLabel();
//INSTableViewDataSource
method tableView(tblView : NSTableView) objectValueForTableColumn(tableColumn: NSTableColumn) row(row : NSInteger): id;
method tableView(tblView : NSTableView) setObjectValue(obj: id) forTableColumn(tableColumn : NSTableColumn) row(row: NSInteger);
method numberOfRowsInTableView(tblView : NSTableView): NSInteger;
//iNSTableViewDelegate
method tableViewSelectionDidChange(aNotification : NSNotification);
end;
implementation
method MainWindowController.init: id;
begin
self := inherited initWithWindowNibName('MainWindowController');
if assigned(self) then begin
self.people := new NSMutableArray();
end;
result := self;
end;
method MainWindowController.addPerson(sender: id);
begin
var person := new Person();
person.name := "New Person";
person.age := 21;
self.people.addObject(person);
self.tableView.reloadData();
self.updateMessageLabel();
end;
method MainWindowController.removePerson(sender: id);
begin
var row := self.tableView.selectedRow();
if (row > -1) and (row < self.people.count()) then begin
self.tableView.abortEditing();
self.people.removeObjectAtIndex(row);
self.tableView.reloadData();
self.updateMessageLabel();
end;
end;
method MainWindowController.updateMessageLabel();
begin
var row := self.tableView.selectedRow();
if (row > -1) and (row < self.people.count()) then begin
var person := self.people.objectAtIndex(row);
self.messageLabel.stringValue := person.name;
end else begin
self.messageLabel.stringValue := "";
end;
end;
method MainWindowController.tableView(tblView: NSTableView) objectValueForTableColumn(tableColumn: NSTableColumn) row(row: NSInteger): id;
begin
var person := self.people.objectAtIndex(row);
case tableColumn.identifier of
"name":
result := person.name;
"age":
result := person.age;
else
result := "Unknown";
end;
end;
method MainWindowController.tableView(tblView: NSTableView) setObjectValue(obj: id) forTableColumn(tableColumn: NSTableColumn) row(row: NSInteger);
begin
var person : Person := self.people.objectAtIndex(row);
case tableColumn.identifier of
"name":
person.name := obj;
"age":
person.age := obj.intValue;
end;
self.updateMessageLabel();
end;
method MainWindowController.numberOfRowsInTableView(tblView: NSTableView): NSInteger;
begin
result := self.people.count();
end;
method MainWindowController.tableViewSelectionDidChange(aNotification: NSNotification);
begin
self.updateMessageLabel();
end;
end.
|
unit uFrmMsgBox;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, uDefCom, uOtherIntf;
type
TfrmMsgBox = class(TForm)
pnlClient: TPanel;
pnlBottom: TPanel;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
FIcons: Pchar;
FMessages: string;
FCaptions: string;
FButtons: TMessageBoxButtons;
FMsgType: TMessageBoxType;
procedure SetButtons(const Value: TMessageBoxButtons);
procedure SetCaptions(const Value: string);
procedure SetMessages(const Value: string);
procedure SetMsgType(const Value: TMessageBoxType);
procedure IniAllComp;
public
{ Public declarations }
property Messages: string read FMessages write SetMessages;
property Captions: string read FCaptions write SetCaptions;
property MsgType: TMessageBoxType read FMsgType write SetMsgType default mbtInformation;
property Buttons: TMessageBoxButtons read FButtons write SetButtons;
end;
const
ButtonNames: array[TMessageBoxButton] of string = (
'btnSett', 'btnDraft', 'btnClose', 'btnYes', 'btnNo', 'btnOk', 'btnCancel');
BtnCaptions: array[TMessageBoxButton] of string = (
'保存单据(&S)', '存入草稿(&D)', '废弃退出(&X)', '是(&Y)', '否(&N)',
'确定(&O)', '取消(&C)');
ModalResults: array[TMessageBoxButton] of Integer = (
mrSett, mrDraft, mrClose, mrYes, mrNo, mrOk, mrCancel);
IconIDs: array[TMessageBoxType] of PChar =
(IDI_EXCLAMATION, IDI_HAND, IDI_ASTERISK, IDI_QUESTION, nil);
var
frmMsgBox: TfrmMsgBox;
implementation
uses Math, Buttons, StdCtrls;
{$R *.dfm}
{ TfrmMsgBox }
procedure TfrmMsgBox.IniAllComp;
var
I: Integer;
begin
for I := 0 to ComponentCount - 1 do
begin
if Components[I] is TPanel then
begin
TPanel(Components[I]).Color := clWhite;
end;
end;
end;
procedure TfrmMsgBox.FormCreate(Sender: TObject);
begin
IniAllComp();
end;
procedure TfrmMsgBox.SetButtons(const Value: TMessageBoxButtons);
var
ButtonWidths: array[TMessageBoxButton] of Integer;
B, DefaultBtn, CancelBtn: TMessageBoxButton;
TextRect: TRect;
X, BtnCount, BtnGroupWidth: Integer;
BtnWidth, BtnHeight, BtnSpace: Integer;
begin
FButtons := Value;
BtnCount := 0;
BtnWidth := 80; //默认BtnWidth
BtnHeight := 23; //默认BtnHeight
BtnSpace := 8; //默认BtnSpace
BtnGroupWidth := 0;
for B := Low(TMessageBoxButton) to High(TMessageBoxButton) do
begin
ButtonWidths[B] := 0;
if B in FButtons then
begin
Inc(BtnCount);
TextRect := Rect(0, 0, 0, 0);
Windows.DrawText(pnlBottom.Handle, PChar(BtnCaptions[B]), -1,
TextRect, DT_CALCRECT or DT_LEFT or DT_SINGLELINE or
DrawTextBiDiModeFlagsReadingOnly);
with TextRect do
ButtonWidths[B] := Right - Left + 16;
BtnWidth := Max(BtnWidth, ButtonWidths[B]);
end;
end;
if mbbSett in FButtons then
DefaultBtn := mbbSett
else if mbbOk in FButtons then
DefaultBtn := mbbOk
else if mbbYes in FButtons then
DefaultBtn := mbbYes;
if mbbCancel in FButtons then
CancelBtn := mbbCancel
else if mbbClose in FButtons then
CancelBtn := mbbClose
else if mbbNo in FButtons then
CancelBtn := mbbNo;
if BtnCount <> 0 then
BtnGroupWidth := BtnWidth * BtnCount + BtnSpace * (BtnCount - 1);
X := (ClientWidth - BtnGroupWidth) div 2;
for B := Low(TMessageBoxButton) to High(TMessageBoxButton) do
begin
if B in FButtons then
with TBitBtn.Create(Self) do
begin
Name := ButtonNames[B];
Parent := pnlBottom;
Caption := BtnCaptions[B];
ModalResult := ModalResults[B];
if B = DefaultBtn then
Default := True;
if B = CancelBtn then
Cancel := True;
SetBounds(X, (pnlBottom.ClientHeight - BtnHeight) div 2,
BtnWidth, BtnHeight);
Inc(X, BtnWidth + BtnSpace);
end;
end;
end;
procedure TfrmMsgBox.SetCaptions(const Value: string);
begin
if Value = EmptyStr then
FCaptions := '提示'
else
FCaptions := Value;
Caption := FCaptions;
end;
procedure TfrmMsgBox.SetMessages(const Value: string);
var
TextRect: TRect;
MsgHeight, MsgWidth: Integer;
begin
FMessages := Value;
with TMemo.Create(Self) do
begin
Name := 'Message';
Parent := pnlClient;
WordWrap := True;
Text := FMessages;
BorderStyle := bsNone;
Color := pnlClient.Color;
ReadOnly := True;
TextRect := Rect(0, 0, pnlClient.Width - 80, pnlClient.Height);
BiDiMode := pnlClient.BiDiMode;
Windows.DrawText(pnlClient.Handle, PChar(FMessages),
Length(FMessages),
TextRect, DT_EXPANDTABS or DT_CALCRECT or DT_WORDBREAK or
DrawTextBiDiModeFlagsReadingOnly);
with TextRect do
begin
MsgHeight := Bottom - Top;
MsgWidth := Right - Left;
end;
if MsgHeight > 30 then
Self.ClientHeight := Self.ClientHeight + MsgHeight - 30;
if MsgWidth < 100 then
Self.ClientWidth := Self.ClientWidth + MsgWidth - 260
else if MsgWidth < 200 then
Self.ClientWidth := Self.ClientWidth + MsgWidth - 260;
SetBounds(64, (pnlClient.ClientHeight - MsgHeight) div 2,
pnlClient.Width - 80, MsgHeight);
end;
end;
procedure TfrmMsgBox.SetMsgType(const Value: TMessageBoxType);
begin
FMsgType := Value;
FIcons := IconIDs[FMsgType];
if FIcons <> nil then
with TImage.Create(Self) do
begin
Name := 'Image';
Parent := pnlClient;
Picture.Icon.Handle := LoadIcon(0, FIcons);
SetBounds(16, 16, 32, 32);
end;
end;
end.
|
unit Main;
interface
uses
SysUtils, Classes, Controls, Forms,
Dialogs, StdCtrls, Grids, ExtCtrls, Menus, MPlayer,
Buttons, IniFiles, jpeg;
type
TfMain = class(TForm)
sField: TStringGrid;
pnlHorizontal1: TPanel;
pnlHorizontal2: TPanel;
pnlVertical1: TPanel;
pnlVertical2: TPanel;
btnNewGame: TButton;
btnAgain: TButton;
btnCheckSudoku: TButton;
btnHint: TButton;
btnGiveUp: TButton;
btnSave: TBitBtn;
btnLoad: TBitBtn;
MainMenu: TMainMenu;
N1: TMenuItem;
N2: TMenuItem;
N3: TMenuItem;
N4: TMenuItem;
N5: TMenuItem;
N6: TMenuItem;
N7: TMenuItem;
N8: TMenuItem;
N9: TMenuItem;
N10: TMenuItem;
Image: TImage;
mpSound: TMediaPlayer;
cbbDifficulty: TComboBox;
dlgSave: TSaveDialog;
dlgOpen: TOpenDialog;
procedure btnNewGameClick(Sender: TObject);
procedure btnAgainClick(Sender: TObject);
procedure btnCheckSudokuClick(Sender: TObject);
procedure btnHintClick(Sender: TObject);
procedure btnGiveUpClick(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
procedure btnLoadClick(Sender: TObject);
procedure N3Click(Sender: TObject);
procedure N4Click(Sender: TObject);
procedure N5Click(Sender: TObject);
procedure N6Click(Sender: TObject);
procedure N7Click(Sender: TObject);
procedure N9Click(Sender: TObject);
procedure N10Click(Sender: TObject);
procedure sFieldSelectCell(Sender: TObject; ACol, ARow: Integer;
var CanSelect: Boolean);
procedure FormCreate(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
public
Activated: string[12];
{ Public declarations }
end;
type Cell = record //Тип клітинки судоку
Tried: array[1..9] of Boolean;
Value: 0..9;
Filled: Boolean;
end;
Tsdk = record //Тип файла судоку
Primary: array[1..9, 1..9] of Cell;
Current: array[1..9, 1..9] of Cell;
Solved: array[1..9, 1..9] of string[3];
Hints: Byte;
GameDifficulty: Byte;
GameActive: Boolean;
end;
var
fMain: TfMain; //Головна форма
Field: array[1..9, 1..9] of Cell; //Масив клітинок ігрового поля
TempField: array[1..9, 1..9] of Cell; //Оригінальний варіант поточної гри
Difficulty: Byte; //Кількість прихованих клітинок
Solutions: Integer; //Кількість розв'язків
Hints: Byte; //Кількість використаних підказок
GameActive: Boolean; //Стан гри (триває/закінчена)
Checked: Boolean; //Стан автоматичної перевірки заповненого поля
SudokuGame: Tsdk; //Змінна для збереження і відкриття гри в файл
FileSDK: file of Tsdk; //Файлова змінна
FileName: string; //Назва файла
WasSaved: Boolean; //Чи була збережена гра
Activated: string[12]; //Чи було введено ключ активації
implementation
uses Numbers, AboutProgram, AboutGame, Authors, SaveGame;
{$R *.dfm}
//Очищує клітинку в масиві Field
procedure ResetCell(var c: Cell);
var i: 1..9;
begin
c.Value := 0;
for i := 1 to 9 do c.Tried[i] := False;
c.Filled := False;
end;
//Обчислює координати наступної клітинки в масиві Field
procedure NextCell(var r, c: Byte);
begin
if c < 9 then c := c + 1
else
begin
r := r + 1; ;
c := 1;
end;
end;
//Перевіряє, чи всі елементи масиву Field заповнені
function AllFilled: Boolean;
var
r, c: 1..9;
begin
AllFilled := False;
for r := 1 to 9 do
for c := 1 to 9 do
if Field[r, c].Filled = False then Exit;
AllFilled := True;
end;
//Перевірка, чи всі клітинки ігрового поля sField заповнені
function AllSolved: Boolean;
var
r, c: 1..9;
begin
AllSolved := False;
for r := 1 to 9 do
for c := 1 to 9 do
if (Field[r, c].Filled = False) and (Length(fMain.sField.Cells[r - 1, c - 1]) = 0) then Exit;
AllSolved := True;
end;
//Обчислює кількість спробуваних чисел даної клітинки за прохід під час генерації поля
function CountTried(c: Cell): Byte;
var
i, count: Byte;
begin
count := 0;
for i := 1 to 9 do
if c.Tried[i] = True then inc(Count);
CountTried := count;
end;
//Перевіряє, чи число Number з координатами Row, Column може перебувати в квадраті 3x3
function CheckCellBox(Number, Row, Column: byte): Boolean;
var
c, r: 1..9;
begin
CheckCellBox := False;
if (Column mod 3) = 0 then Column := Column - 2
else Column := (Column div 3) * 3 + 1;
if (Row mod 3) = 0 then Row := Row - 2
else Row := (Row div 3) * 3 + 1;
for r := Row to Row + 2 do
for c := Column to Column + 2 do
if (Field[r, c].Filled) and (Field[r, c].Value = Number) then Exit;
CheckCellBox := True;
end;
//Перевіряє, чи число Number з координатами Row, Column може перебувати в масиві Field, використовується під час генерації поля
function CheckNumberFill(Number, Row, Column: byte): Boolean;
var
i: 1..9;
begin
CheckNumberFill := False;
if CheckCellBox(Number, Row, Column) = False then Exit
else
begin
for i := 1 to 9 do
begin
if Field[Row, i].Value = Number then Exit;
end;
for i := 1 to 9 do
begin
if Field[i, Column].Value = Number then Exit;
end;
end;
CheckNumberFill := True;
end;
//Перевіряє, чи число Number з координатами Row, Column може перебувати в масиві Field, використовується під час перевірки введення числа
function CheckNumberSolve(Number, Row, Column: byte): Boolean;
var
i: 1..9;
begin
CheckNumberSolve := False;
if CheckCellBox(Number, Row, Column) = False then Exit
else
begin
for i := 1 to 9 do
begin
if (Field[Row, i].Filled) and (Field[Row, i].Value = Number) then Exit;
end;
for i := 1 to 9 do
begin
if (Field[i, Column].Filled) and (Field[i, Column].Value = Number) then Exit;
end;
end;
CheckNumberSolve := True;
end;
//Обраховує кількість доступних чисел для клітинки
function CountVariants(Row, Column: Byte): Byte;
var
i, count: Byte;
begin
count := 0;
for i := 1 to 9 do
if CheckNumberSolve(i, Row, Column) then inc(count);
CountVariants := count;
end;
//Знаходить вільну клітинку з найменшою кількість варіантів
procedure FindMinPoint(var r, c: Byte);
var
a, b, min: 1..9;
begin
min := 9;
for a := 1 to 9 do
for b := 1 to 9 do
if Field[a, b].Filled then Continue
else if CountVariants(a, b) < min then
begin
min := CountVariants(a, b);
r := a;
c := b;
end;
end;
//Неявно розв'язує гру і глобальній змінній Solutions присвоює кількість розв'язків
procedure Solve;
var
r, c, i, num: Byte;
begin
if AllFilled then
begin
inc(Solutions);
Exit;
end
else
begin
FindMinPoint(r, c);
for i := 1 to 9 do
if CheckNumberSolve(i, r, c) then
begin
num := Field[r, c].Value;
Field[r, c].Value := i;
Field[r, c].Filled := True;
Solve;
Field[r, c].Value := num;
Field[r, c].Filled := False;
end;
end;
end;
//Генерує заповнене ігрове поле
procedure Generate(Row, Column: Byte);
var
num, r, c: Byte;
begin
Randomize;
while Field[9, 9].Filled = False do
begin
r := Row;
c := Column;
if CountTried(Field[Row, Column]) < 9 then
begin
repeat
num := Random(9) + 1;
until Field[Row, Column].Tried[num] = False;
if CheckNumberFill(num, Row, Column) then
begin
Field[r, c].Value := num;
Field[r, c].Tried[num] := True;
Field[r, c].Filled := True;
NextCell(r, c);
if (r <= 9) and (c <= 9) then Generate(r, c);
end
else Field[r, c].Tried[num] := True;
end
else
begin
ResetCell(Field[r, c]);
Exit;
end;
end;
end;
//Приховує вказану в глобальній змінній Difficulty кількість клітинок таким чином, щоб гра мала єдиний розв'язок
procedure HideCells;
var
r, c, count: byte;
begin
Randomize;
count := 0;
while count < Difficulty do
begin
r := Random(9) + 1;
c := Random(9) + 1;
if Field[r, c].Filled = False then Continue
else
begin
Field[r, c].Filled := False;
Solve;
if Solutions = 1 then Inc(count)
else Field[r, c].Filled := True;
Solutions := 0;
end;
end;
end;
//Обчислює кількість помилок, допущених гравцем
function CountMistakes: Byte;
var
r, c, mistakes: Byte;
begin
mistakes := 0;
for r := 1 to 9 do
for c := 1 to 9 do
if (Field[r, c].Filled = False) and (' ' + IntToStr(Field[r, c].Value) <> fMain.sField.Cells[r - 1, c - 1]) then inc(mistakes);
CountMistakes := mistakes;
end;
//Генерує нову унікальну гру
procedure TfMain.btnNewGameClick(Sender: TObject);
var
r, c: 1..9;
begin
if WasSaved = False then
begin
fSavePrevGame.ShowModal;
if fSavePrevGame.SaveChoice = True then
if dlgSave.Execute = False then Exit;
end;
case cbbDifficulty.ItemIndex of
0: Difficulty := 36;
1: Difficulty := 45;
2: Difficulty := 52;
end;
GameActive := True;
Checked := False;
WasSaved := False;
sField.Enabled := True;
Solutions := 0;
Hints := 0;
btnHint.Enabled := True;
btnGiveUp.Enabled := True;
for r := 1 to 9 do
for c := 1 to 9 do
ResetCell(Field[r, c]);
Generate(1, 1);
HideCells;
for r := 1 to 9 do
for c := 1 to 9 do
begin
TempField[r, c] := Field[r, c];
if Field[r, c].Filled then
sField.Cells[r - 1, c - 1] := ' ' + IntToStr(Field[r, c].Value) + '.'
else sField.Cells[r - 1, c - 1] := '';
end;
end;
//Розпочинає поточну гру спочатку
procedure TfMain.btnAgainClick(Sender: TObject);
var
r, c: 1..9;
begin
for r := 1 to 9 do
for c := 1 to 9 do
begin
Field[r, c] := TempField[r, c];
if TempField[r, c].Filled then sField.Cells[r - 1, c - 1] := ' ' + IntToStr(TempField[r, c].Value) + '.'
else sField.Cells[r - 1, c - 1] := '';
end;
Hints := 0;
GameActive := True;
Checked := False;
btnHint.Enabled := True;
btnGiveUp.Enabled := True;
end;
//Виконує перевірку розв'язку
procedure TfMain.btnCheckSudokuClick(Sender: TObject);
begin
if AllSolved = False then
begin
ShowMessage('Заповніть, будь ласка, все поле!');
Exit;
end
else if CountMistakes = 0 then
begin
if Hints = 0 then ShowMessage('Судоку розв"язно правильно. Вітаємо!!!')
else if Hints = 81 then ShowMessage('Ви здалися!!!')
else ShowMessage('Судоку розв"язано правильно, але з допомогою підказок. Використано підказок: ' + IntToStr(Hints) + ' з ' + IntToStr(Difficulty));
GameActive := False;
btnHint.Enabled := False;
btnGiveUp.Enabled := False;
end
else ShowMessage('На жаль, судоку розв"язано неправильно. Допущено помилок: ' + IntToStr(CountMistakes) + '. Спробуйте ще!');
end;
//Відкриває клітинку з найменшою кількістю варіантів
procedure TfMain.btnHintClick(Sender: TObject);
var
r, c: Byte;
begin
if (GameActive = False) or (AllFilled) then Exit;
inc(Hints);
repeat
FindMinPoint(r, c);
if sField.Cells[r - 1, c - 1] = ' ' + IntToStr(Field[r, c].Value) then Field[r, c].Filled := True;
until sField.Cells[r - 1, c - 1] <> ' ' + IntToStr(Field[r, c].Value);
Field[r, c].Filled := True;
sField.Cells[r - 1, c - 1] := ' ' + IntToStr(Field[r, c].Value) + '!';
if (AllSolved) and ((Checked = False) or (CountMistakes = 0)) then
begin
btnCheckSudoku.Click;
Checked := True;
end;
end;
//Завершує поточну гру та показує правильний розв'язок
procedure TfMain.btnGiveUpClick(Sender: TObject);
var
r, c: 1..9;
begin
if (GameActive = False) or (AllFilled) then Exit;
for r := 1 to 9 do
for c := 1 to 9 do
begin
if Field[r, c].Filled = False then sField.Cells[r - 1, c - 1] := ' ' + IntToStr(Field[r, c].Value);
Field[r, c].Filled := True;
end;
Hints := 81;
btnHint.Enabled := False;
btnGiveUp.Enabled := False;
GameActive := False;
end;
//Викликає вікно вибору числа
procedure TfMain.sFieldSelectCell(Sender: TObject; ACol, ARow: Integer;
var CanSelect: Boolean);
begin
if GameActive = False then Exit;
if not Field[ACol + 1, Arow + 1].Filled then
begin
fNumbers.ShowModal;
if fNumbers.Num = 'X' then Exit
else if fNumbers.Num = '0' then sField.Cells[ACol, Arow] := ''
else sField.Cells[Acol, Arow] := ' ' + fNumbers.Num;
end;
if (AllSolved) and ((Checked = False) or (CountMistakes = 0)) then
begin
btnCheckSudoku.Click;
Checked := True;
end;
end;
//Зберігає гру в файл
procedure TfMain.N6Click(Sender: TObject);
var
r, c: 1..9;
begin
if dlgSave.Execute = False then Exit;
WasSaved := True;
for r := 1 to 9 do
for c := 1 to 9 do
begin
SudokuGame.Primary[r, c] := TempField[r, c];
SudokuGame.Current[r, c] := Field[r, c];
SudokuGame.Solved[r, c] := sField.Cells[r - 1, c - 1];
SudokuGame.Hints := Hints;
SudokuGame.GameDifficulty := Difficulty;
SudokuGame.GameActive := GameActive;
end;
begin
FileName := dlgSave.FileName;
if FileName = '' then FileName := 'Game';
if Copy(FileName, Length(FileName) - 3, 4) <> '.sdk' then FileName := FileName + '.sdk';
AssignFile(FileSDK, FileName);
Rewrite(FileSDK);
Write(FileSDK, SudokuGame);
CloseFile(FileSDK);
end;
end;
//Відкриває гру з файла
procedure TfMain.N7Click(Sender: TObject);
var
r, c: 1..9;
begin
if WasSaved = False then
begin
fSavePrevGame.ShowModal;
if fSavePrevGame.SaveChoice = True then N6.Click;
end;
if (dlgOpen.Execute = False) or (dlgOpen.FileName = '') then Exit;
begin
FileName := dlgOpen.FileName;
AssignFile(FileSDK, FileName);
Reset(FileSDK);
Read(FileSDK, SudokuGame);
CloseFile(FileSDK);
end;
for r := 1 to 9 do
for c := 1 to 9 do
begin
TempField[r, c] := SudokuGame.Primary[r, c];
Field[r, c] := SudokuGame.Current[r, c];
sField.Cells[r - 1, c - 1] := SudokuGame.Solved[r, c];
end;
Hints := SudokuGame.Hints;
Difficulty := SudokuGame.GameDifficulty;
GameActive := SudokuGame.GameActive;
case Difficulty of
36: cbbDifficulty.ItemIndex := 0;
45: cbbDifficulty.ItemIndex := 1;
54: cbbDifficulty.ItemIndex := 2;
end; ;
Checked := True;
WasSaved := True;
if GameActive then
begin
btnHint.Enabled := True;
btnGiveUp.Enabled := True;
end
else
begin
btnHint.Enabled := False;
btnGiveUp.Enabled := False;
end;
end;
//Виклик нової гри з меню
procedure TfMain.N5Click(Sender: TObject);
begin
btnNewGame.Click;
end;
//Оброблює плеєр при запуску
procedure TfMain.FormActivate(Sender: TObject);
begin
wassaved := True;
btnNewGame.Click;
WasSaved := False;
if FileExists('sound.wav') then mpSound.Open
else if FileExists('sound.mp3') then
begin
mpSound.FileName := 'sound.mp3';
mpSound.Open;
end
else mpSound.Visible := False;
end;
//Виклик завантаження з меню
procedure TfMain.btnLoadClick(Sender: TObject);
begin
N7.Click;
end;
//Виклик збереження з меню
procedure TfMain.btnSaveClick(Sender: TObject);
begin
N6.Click;
end;
//Виклик вікна "Про програму"
procedure TfMain.N10Click(Sender: TObject);
begin
fAboutProgram.ShowModal;
end;
//Виклик вікна "Про гру"
procedure TfMain.N3Click(Sender: TObject);
begin
fAboutGame.ShowModal;
end;
//Виклик вікна "Про авторів"
procedure TfMain.N4Click(Sender: TObject);
begin
fAuthors.ShowModal;
end;
//Закриття програми
procedure TfMain.N9Click(Sender: TObject);
begin
Close;
end;
//Збереження параметрів
procedure TfMain.FormDestroy(Sender: TObject);
var
ini: TIniFile;
begin
ini := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'options.ini');
ini.WriteInteger('Position', 'Top', fMain.Top);
ini.WriteInteger('Position', 'Left', fMain.Left);
ini.WriteInteger('Difficulty', 'Level', fMain.cbbDifficulty.ItemIndex);
ini.WriteString('Activation', 'Activated', Activated);
ini.Free;
end;
//Застосування збережених параметрів
procedure TfMain.FormCreate(Sender: TObject);
var
ini: TIniFile;
begin
ini := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'options.ini');
fMain.Top := ini.ReadInteger('Position', 'Top', 140);
fMain.Left := ini.ReadInteger('Position', 'Left', 391);
fMain.cbbDifficulty.ItemIndex := ini.ReadInteger('Difficulty', 'Level', 1);
Activated := ini.ReadString('Activation', 'Activated', 'No Password!');
ini.Free;
end;
//Пропозиція зберегти гру перед виходом
procedure TfMain.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if WasSaved = False then
begin
fSavePrevGame.ShowModal;
if fSavePrevGame.SaveChoice = True then N6.Click;
end;
end;
end.
|
unit OpenImg;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
System.IOUtils, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
FMX.Layouts, FMX.ListBox, FMX.Controls.Presentation, FMX.StdCtrls;
type
TFrmOpenImg = class(TForm)
LbxDateiList: TListBox;
StyleBook: TStyleBook;
procedure FormCreate(Sender: TObject);
procedure LbxDateiListItemClick(const Sender: TCustomListBox;
const Item: TListBoxItem);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private-Deklarationen }
public
sDateiName: String;
end;
var
FrmOpenImg: TFrmOpenImg;
implementation
{$R *.fmx}
procedure TFrmOpenImg.FormClose(Sender: TObject; var Action: TCloseAction);
begin
ModalResult := mrOk;
Action := TCloseAction.caFree;
end;
procedure TFrmOpenImg.FormCreate(Sender: TObject);
var
DirArraySize, i : Integer;
DirArray : TStringDynArray;
ListItem : TListBoxItem;
Size: TSizeF;
begin
LbxDateiList.BeginUpdate;
DirArray := TDirectory.GetFiles(TPath.GetDocumentsPath);
DirArraySize := Length(DirArray);
Size.Width := 32;
Size.Height := 32;
for i := 0 to DirArraySize-1 do
begin
ListItem := TListBoxItem.Create(LbxDateiList);
//ListItem.StyleLookup := 'listboxitemrightdetail';
ListItem.text := ExtractFileName(DirArray[i]);
if ExtractFileExt(DirArray[i]) = '.png' then
ListItem.ItemData.Bitmap.LoadFromFile(DirArray[i]);
ListItem.Parent := LbxDateiList;
end;
LbxDateiList.EndUpdate;
end;
procedure TFrmOpenImg.LbxDateiListItemClick(const Sender: TCustomListBox;
const Item: TListBoxItem);
begin
sDateiName := TPath.Combine(TPath.GetDocumentsPath, Item.Text);
Close;
end;
end.
|
unit ContaPagarDAO;
interface
uses
DBXCommon, SqlExpr, BaseDAO, ContaPagar, SysUtils;
type
TContaPagarDAO = class(TBaseDAO)
public
function List: TDBXReader;
function Insert(ContaPagar: TContaPagar): Boolean;
function Update(ContaPagar: TContaPagar): Boolean;
function Delete(ContaPagar: TContaPagar): Boolean;
function BaixarConta(ContaPagar: TContaPagar): Boolean;
function Relatorio(DataInicial, DataFinal: TDateTime; FornecedorCodigo: string; Situacao: Integer): TDBXReader;
end;
implementation
uses uSCPrincipal, StringUtils;
{ TClienteDAO }
function TContaPagarDAO.List: TDBXReader;
begin
PrepareCommand;
FComm.Text := 'SELECT C.ID, C.FORNECEDOR_CODIGO, F.NOME, C.VENCIMENTO, C.VALOR, C.OBSERVACOES, C.BAIXADA '+
'FROM CONTAS_PAGAR C '+
'INNER JOIN FORNECEDORES F ON F.CODIGO = C.FORNECEDOR_CODIGO '+
'WHERE C.BAIXADA = 0 '+
'ORDER BY C.VENCIMENTO, C.FORNECEDOR_CODIGO';
Result := FComm.ExecuteQuery;
end;
function TContaPagarDAO.Relatorio(DataInicial, DataFinal: TDateTime; FornecedorCodigo: string; Situacao: Integer): TDBXReader;
begin
PrepareCommand;
FComm.Text := 'SELECT C.ID, C.FORNECEDOR_CODIGO, F.NOME, C.VENCIMENTO, C.VALOR, C.OBSERVACOES, C.BAIXADA '+
'FROM CONTAS_PAGAR C '+
'INNER JOIN FORNECEDORES F ON F.CODIGO = C.FORNECEDOR_CODIGO '+
'WHERE C.ID <> 0 ';
if DataInicial <> 0 then
FComm.Text := FComm.Text + 'AND CONVERT(CHAR(8), C.VENCIMENTO, 112) >= '+FormatDateTime('yyyymmdd', DataInicial)+' ';
if DataFinal <> 0 then
FComm.Text := FComm.Text + 'AND CONVERT(CHAR(8), C.VENCIMENTO, 112) <= '+FormatDateTime('yyyymmdd', DataFinal)+' ';
if FornecedorCodigo <> '' then
FComm.Text := FComm.Text + 'AND C.FORNECEDOR_CODIGO = '''+FornecedorCodigo+''' ';
if Situacao = 1 then
FComm.Text := FComm.Text + 'AND C.BAIXADA = 0 ';
if Situacao = 2 then
FComm.Text := FComm.Text + 'AND C.BAIXADA = 1 ';
FComm.Text := FComm.Text + 'ORDER BY C.VENCIMENTO, C.FORNECEDOR_CODIGO';
Result := FComm.ExecuteQuery;
end;
function TContaPagarDAO.Insert(ContaPagar: TContaPagar): Boolean;
var
query: TSQLQuery;
begin
query := TSQLQuery.Create(nil);
try
query.SQLConnection := SCPrincipal.ConnTopCommerce;
//
query.SQL.Text := 'INSERT INTO CONTAS_PAGAR (FORNECEDOR_CODIGO, VENCIMENTO, VALOR, OBSERVACOES, BAIXADA) VALUES (:FORNECEDOR_CODIGO, :VENCIMENTO, :VALOR, :OBSERVACOES, :BAIXADA)';
//
query.ParamByName('FORNECEDOR_CODIGO').AsString := ContaPagar.Fornecedor.Codigo;
query.ParamByName('VENCIMENTO').AsDateTime := ContaPagar.Vencimento;
query.ParamByName('VALOR').AsCurrency := ContaPagar.Valor;
query.ParamByName('OBSERVACOES').AsString := ContaPagar.Observacoes;
query.ParamByName('BAIXADA').AsBoolean := ContaPagar.Baixada;
//
try
query.ExecSQL;
Result := True;
except
Result := False;
end;
finally
query.Free;
end;
end;
function TContaPagarDAO.Update(ContaPagar: TContaPagar): Boolean;
var
query: TSQLQuery;
begin
query := TSQLQuery.Create(nil);
try
query.SQLConnection := SCPrincipal.ConnTopCommerce;
//
query.SQL.Text := 'UPDATE CONTAS_PAGAR SET FORNECEDOR_CODIGO = :FORNECEDOR_CODIGO, VENCIMENTO = :VENCIMENTO, VALOR = :VALOR, OBSERVACOES = :OBSERVACOES, BAIXADA = :BAIXADA '+
'WHERE ID = :ID';
//
query.ParamByName('FORNECEDOR_CODIGO').AsString := ContaPagar.Fornecedor.Codigo;
query.ParamByName('VENCIMENTO').AsDateTime := ContaPagar.Vencimento;
query.ParamByName('VALOR').AsCurrency := ContaPagar.Valor;
query.ParamByName('OBSERVACOES').AsString := ContaPagar.Observacoes;
query.ParamByName('BAIXADA').AsBoolean := ContaPagar.Baixada;
query.ParamByName('ID').AsInteger := ContaPagar.Id;
//
try
query.ExecSQL;
Result := True;
except
Result := False;
end;
finally
query.Free;
end;
end;
function TContaPagarDAO.BaixarConta(ContaPagar: TContaPagar): Boolean;
var
query: TSQLQuery;
begin
query := TSQLQuery.Create(nil);
try
query.SQLConnection := SCPrincipal.ConnTopCommerce;
//
query.SQL.Text := 'UPDATE CONTAS_PAGAR SET BAIXADA = 1 WHERE ID = :ID';
//
query.ParamByName('ID').AsInteger := ContaPagar.Id;
//
try
query.ExecSQL;
Result := True;
except
Result := False;
end;
finally
query.Free;
end;
end;
function TContaPagarDAO.Delete(ContaPagar: TContaPagar): Boolean;
var
query: TSQLQuery;
begin
query := TSQLQuery.Create(nil);
try
query.SQLConnection := SCPrincipal.ConnTopCommerce;
//
query.SQL.Text := 'DELETE FROM CONTAS_PAGAR WHERE ID = :ID';
//
query.ParamByName('ID').AsInteger := ContaPagar.Id;
//
try
query.ExecSQL;
Result := True;
except
Result := False;
end;
finally
query.Free;
end;
end;
end.
|
unit Hash32Tests;
interface
{$IFDEF FPC}
{$WARNINGS OFF}
{$NOTES OFF}
{$ENDIF FPC}
uses
Classes,
SysUtils,
{$IFDEF FPC}
fpcunit,
testregistry,
{$ELSE}
TestFramework,
{$ENDIF FPC}
HashLibTestBase,
HlpHashFactory,
HlpIHash,
HlpIHashInfo,
HlpConverters;
// Hash32
type
TTestAP = class(THashLibAlgorithmTestCase)
private
FAP: IHash;
const
FExpectedHashOfEmptyData: String = 'AAAAAAAA';
FExpectedHashOfDefaultData: String = '7F14EFED';
FExpectedHashOfOnetoNine: String = 'C0E86BE5';
FExpectedHashOfabcde: String = '7F6A697A';
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestEmptyString;
procedure TestDefaultData;
procedure TestOnetoNine;
procedure TestBytesabcde;
procedure TestEmptyStream;
procedure TestIncrementalHash;
procedure TestHashCloneIsCorrect;
procedure TestHashCloneIsUnique;
end;
type
TTestBernstein = class(THashLibAlgorithmTestCase)
private
FBernstein: IHash;
const
FExpectedHashOfEmptyData: String = '00001505';
FExpectedHashOfDefaultData: String = 'C4635F48';
FExpectedHashOfOnetoNine: String = '35CDBB82';
FExpectedHashOfabcde: String = '0F11B894';
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestEmptyString;
procedure TestDefaultData;
procedure TestOnetoNine;
procedure TestBytesabcde;
procedure TestEmptyStream;
procedure TestIncrementalHash;
procedure TestHashCloneIsCorrect;
procedure TestHashCloneIsUnique;
end;
type
TTestBernstein1 = class(THashLibAlgorithmTestCase)
private
FBernstein1: IHash;
const
FExpectedHashOfEmptyData: String = '00001505';
FExpectedHashOfDefaultData: String = '2D122E48';
FExpectedHashOfOnetoNine: String = '3BABEA14';
FExpectedHashOfabcde: String = '0A1DEB04';
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestEmptyString;
procedure TestDefaultData;
procedure TestOnetoNine;
procedure TestBytesabcde;
procedure TestEmptyStream;
procedure TestIncrementalHash;
procedure TestHashCloneIsCorrect;
procedure TestHashCloneIsUnique;
end;
type
TTestBKDR = class(THashLibAlgorithmTestCase)
private
FBKDR: IHash;
const
FExpectedHashOfEmptyData: String = '00000000';
FExpectedHashOfDefaultData: String = '29E11B15';
FExpectedHashOfOnetoNine: String = 'DE43D6D5';
FExpectedHashOfabcde: String = 'B3EDEA13';
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestEmptyString;
procedure TestDefaultData;
procedure TestOnetoNine;
procedure TestBytesabcde;
procedure TestEmptyStream;
procedure TestIncrementalHash;
procedure TestHashCloneIsCorrect;
procedure TestHashCloneIsUnique;
end;
type
TTestDEK = class(THashLibAlgorithmTestCase)
private
FDEK: IHash;
const
FExpectedHashOfEmptyData: String = '00000000';
FExpectedHashOfDefaultData: String = '8E01E947';
FExpectedHashOfOnetoNine: String = 'AB4ACBA5';
FExpectedHashOfabcde: String = '0C2080E5';
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestEmptyString;
procedure TestDefaultData;
procedure TestOnetoNine;
procedure TestBytesabcde;
procedure TestEmptyStream;
procedure TestIncrementalHash;
procedure TestHashCloneIsCorrect;
procedure TestHashCloneIsUnique;
end;
type
TTestDJB = class(THashLibAlgorithmTestCase)
private
FDJB: IHash;
const
FExpectedHashOfEmptyData: String = '00001505';
FExpectedHashOfDefaultData: String = 'C4635F48';
FExpectedHashOfOnetoNine: String = '35CDBB82';
FExpectedHashOfabcde: String = '0F11B894';
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestEmptyString;
procedure TestDefaultData;
procedure TestOnetoNine;
procedure TestBytesabcde;
procedure TestEmptyStream;
procedure TestIncrementalHash;
procedure TestHashCloneIsCorrect;
procedure TestHashCloneIsUnique;
end;
type
TTestELF = class(THashLibAlgorithmTestCase)
private
FELF: IHash;
const
FExpectedHashOfEmptyData: String = '00000000';
FExpectedHashOfDefaultData: String = '01F5B2CC';
FExpectedHashOfOnetoNine: String = '0678AEE9';
FExpectedHashOfabcde: String = '006789A5';
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestEmptyString;
procedure TestDefaultData;
procedure TestOnetoNine;
procedure TestBytesabcde;
procedure TestEmptyStream;
procedure TestIncrementalHash;
procedure TestHashCloneIsCorrect;
procedure TestHashCloneIsUnique;
end;
type
TTestFNV = class(THashLibAlgorithmTestCase)
private
FFNV: IHash;
const
FExpectedHashOfEmptyData: String = '00000000';
FExpectedHashOfDefaultData: String = 'BE611EA3';
FExpectedHashOfOnetoNine: String = 'D8D70BF1';
FExpectedHashOfabcde: String = 'B2B39969';
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestEmptyString;
procedure TestDefaultData;
procedure TestOnetoNine;
procedure TestBytesabcde;
procedure TestEmptyStream;
procedure TestIncrementalHash;
procedure TestHashCloneIsCorrect;
procedure TestHashCloneIsUnique;
end;
type
TTestFNV1a = class(THashLibAlgorithmTestCase)
private
FFNV1a: IHash;
const
FExpectedHashOfEmptyData: String = '811C9DC5';
FExpectedHashOfDefaultData: String = '1892F1F8';
FExpectedHashOfOnetoNine: String = 'BB86B11C';
FExpectedHashOfabcde: String = '749BCF08';
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestEmptyString;
procedure TestDefaultData;
procedure TestOnetoNine;
procedure TestBytesabcde;
procedure TestEmptyStream;
procedure TestIncrementalHash;
procedure TestHashCloneIsCorrect;
procedure TestHashCloneIsUnique;
end;
type
TTestJenkins3 = class(THashLibAlgorithmTestCase)
private
FJenkins3: IHash;
const
FExpectedHashOfEmptyData: String = 'DEADBEEF';
FExpectedHashOfDefaultData: String = 'F0F69CEF';
FExpectedHashOfOnetoNine: String = '845D9A96';
FExpectedHashOfabcde: String = '026D72DE';
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestEmptyString;
procedure TestDefaultData;
procedure TestOnetoNine;
procedure TestBytesabcde;
procedure TestEmptyStream;
procedure TestIncrementalHash;
procedure TestHashCloneIsCorrect;
procedure TestHashCloneIsUnique;
end;
type
TTestJS = class(THashLibAlgorithmTestCase)
private
FJS: IHash;
const
FExpectedHashOfEmptyData: String = '4E67C6A7';
FExpectedHashOfDefaultData: String = '683AFCFE';
FExpectedHashOfOnetoNine: String = '90A4224B';
FExpectedHashOfabcde: String = '62E8C8B5';
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestEmptyString;
procedure TestDefaultData;
procedure TestOnetoNine;
procedure TestBytesabcde;
procedure TestEmptyStream;
procedure TestIncrementalHash;
procedure TestHashCloneIsCorrect;
procedure TestHashCloneIsUnique;
end;
type
TTestMurmur2 = class(THashLibAlgorithmTestCase)
private
FMurmur2: IHash;
const
FExpectedHashOfEmptyData: String = '00000000';
FExpectedHashOfDefaultData: String = '30512DE6';
FExpectedHashOfOnetoNine: String = 'DCCB0167';
FExpectedHashOfabcde: String = '5F09A8DE';
FExpectedHashOfDefaultDataWithMaxUInt32AsKey: String = 'B15D52F0';
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestEmptyString;
procedure TestDefaultData;
procedure TestOnetoNine;
procedure TestBytesabcde;
procedure TestEmptyStream;
procedure TestIncrementalHash;
procedure TestWithDifferentKey;
procedure TestHashCloneIsCorrect;
procedure TestHashCloneIsUnique;
end;
type
TTestMurmurHash3_x86_32 = class(THashLibAlgorithmTestCase)
private
FMurmurHash3_x86_32: IHash;
const
FExpectedHashOfEmptyData: String = '00000000';
FExpectedHashOfDefaultData: String = '3D97B9EB';
FExpectedHashOfRandomString: String = 'A8D02B9A';
FExpectedHashOfZerotoFour: String = '19D02170';
FExpectedHashOfEmptyDataWithOneAsKey: String = '514E28B7';
FExpectedHashOfDefaultDataWithMaxUInt32AsKey: String = 'B05606FE';
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestEmptyString;
procedure TestDefaultData;
procedure TestRandomString;
procedure TestZerotoFour;
procedure TestEmptyStream;
procedure TestIncrementalHash;
procedure TestAnotherChunkedDataIncrementalHash;
procedure TestIndexChunkedDataIncrementalHash;
procedure TestWithDifferentKeyMaxUInt32DefaultData;
procedure TestWithDifferentKeyOneEmptyString;
procedure TestHashCloneIsCorrect;
procedure TestHashCloneIsUnique;
end;
type
TTestOneAtTime = class(THashLibAlgorithmTestCase)
private
FOneAtTime: IHash;
const
FExpectedHashOfEmptyData: String = '00000000';
FExpectedHashOfDefaultData: String = '4E379A4F';
FExpectedHashOfOnetoNine: String = 'C66B58C5';
FExpectedHashOfabcde: String = 'B98559FC';
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestEmptyString;
procedure TestDefaultData;
procedure TestOnetoNine;
procedure TestBytesabcde;
procedure TestEmptyStream;
procedure TestIncrementalHash;
procedure TestHashCloneIsCorrect;
procedure TestHashCloneIsUnique;
end;
type
TTestPJW = class(THashLibAlgorithmTestCase)
private
FPJW: IHash;
const
FExpectedHashOfEmptyData: String = '00000000';
FExpectedHashOfDefaultData: String = '01F5B2CC';
FExpectedHashOfOnetoNine: String = '0678AEE9';
FExpectedHashOfabcde: String = '006789A5';
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestEmptyString;
procedure TestDefaultData;
procedure TestOnetoNine;
procedure TestBytesabcde;
procedure TestEmptyStream;
procedure TestIncrementalHash;
procedure TestHashCloneIsCorrect;
procedure TestHashCloneIsUnique;
end;
type
TTestRotating = class(THashLibAlgorithmTestCase)
private
FRotating: IHash;
const
FExpectedHashOfEmptyData: String = '00000000';
FExpectedHashOfDefaultData: String = '158009D3';
FExpectedHashOfOnetoNine: String = '1076548B';
FExpectedHashOfabcde: String = '00674525';
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestEmptyString;
procedure TestDefaultData;
procedure TestOnetoNine;
procedure TestBytesabcde;
procedure TestEmptyStream;
procedure TestIncrementalHash;
procedure TestHashCloneIsCorrect;
procedure TestHashCloneIsUnique;
end;
type
TTestRS = class(THashLibAlgorithmTestCase)
private
FRS: IHash;
const
FExpectedHashOfEmptyData: String = '00000000';
FExpectedHashOfDefaultData: String = '9EF98E63';
FExpectedHashOfOnetoNine: String = '704952E9';
FExpectedHashOfabcde: String = 'A4A13F5D';
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestEmptyString;
procedure TestDefaultData;
procedure TestOnetoNine;
procedure TestBytesabcde;
procedure TestEmptyStream;
procedure TestIncrementalHash;
procedure TestHashCloneIsCorrect;
procedure TestHashCloneIsUnique;
end;
type
TTestSDBM = class(THashLibAlgorithmTestCase)
private
FSDBM: IHash;
const
FExpectedHashOfEmptyData: String = '00000000';
FExpectedHashOfDefaultData: String = '3001A5C9';
FExpectedHashOfOnetoNine: String = '68A07035';
FExpectedHashOfabcde: String = 'BD500063';
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestEmptyString;
procedure TestDefaultData;
procedure TestOnetoNine;
procedure TestBytesabcde;
procedure TestEmptyStream;
procedure TestIncrementalHash;
procedure TestHashCloneIsCorrect;
procedure TestHashCloneIsUnique;
end;
type
TTestShiftAndXor = class(THashLibAlgorithmTestCase)
private
FShiftAndXor: IHash;
const
FExpectedHashOfEmptyData: String = '00000000';
FExpectedHashOfDefaultData: String = 'BD0A7DA4';
FExpectedHashOfOnetoNine: String = 'E164F745';
FExpectedHashOfabcde: String = '0731B823';
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestEmptyString;
procedure TestDefaultData;
procedure TestOnetoNine;
procedure TestBytesabcde;
procedure TestEmptyStream;
procedure TestIncrementalHash;
procedure TestHashCloneIsCorrect;
procedure TestHashCloneIsUnique;
end;
type
TTestSuperFast = class(THashLibAlgorithmTestCase)
private
FSuperFast: IHash;
const
FExpectedHashOfEmptyData: String = '00000000';
FExpectedHashOfDefaultData: String = 'F00EB3C0';
FExpectedHashOfOnetoNine: String = '9575A2E9';
FExpectedHashOfabcde: String = '51ED072E';
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestEmptyString;
procedure TestDefaultData;
procedure TestOnetoNine;
procedure TestBytesabcde;
procedure TestEmptyStream;
procedure TestIncrementalHash;
procedure TestHashCloneIsCorrect;
procedure TestHashCloneIsUnique;
end;
type
TTestXXHash32 = class(THashLibAlgorithmTestCase)
private
FXXHash32: IHash;
const
FExpectedHashOfEmptyData: String = '02CC5D05';
FExpectedHashOfDefaultData: String = '6A1C7A99';
FExpectedHashOfRandomString: String = 'CE8CF448';
FExpectedHashOfZerotoFour: String = '8AA3B71C';
FExpectedHashOfEmptyDataWithOneAsKey: String = '0B2CB792';
FExpectedHashOfDefaultDataWithMaxUInt32AsKey: String = '728C6772';
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestEmptyString;
procedure TestDefaultData;
procedure TestRandomString;
procedure TestZerotoFour;
procedure TestEmptyStream;
procedure TestIncrementalHash;
procedure TestAnotherChunkedDataIncrementalHash;
procedure TestWithDifferentKeyMaxUInt32DefaultData;
procedure TestWithDifferentKeyOneEmptyString;
procedure TestHashCloneIsCorrect;
procedure TestHashCloneIsUnique;
end;
implementation
// Hash32
{ TTestAP }
procedure TTestAP.SetUp;
begin
inherited;
FAP := THashFactory.THash32.CreateAP();
end;
procedure TTestAP.TearDown;
begin
FAP := Nil;
inherited;
end;
procedure TTestAP.TestBytesabcde;
var
LBuffer: TBytes;
begin
System.SetLength(LBuffer, System.SizeOf(FBytesabcde));
System.Move(FBytesabcde, Pointer(LBuffer)^, System.SizeOf(FBytesabcde));
FExpectedString := FExpectedHashOfabcde;
FActualString := FAP.ComputeBytes(LBuffer).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestAP.TestHashCloneIsCorrect;
var
Original, Copy: IHash;
MainData, ChunkOne, ChunkTwo: TBytes;
Count: Int32;
begin
MainData := TConverters.ConvertStringToBytes(FDefaultData, TEncoding.UTF8);
Count := System.Length(MainData) - 3;
ChunkOne := System.Copy(MainData, 0, Count);
ChunkTwo := System.Copy(MainData, Count, System.Length(MainData) - Count);
Original := FAP;
Original.Initialize;
Original.TransformBytes(ChunkOne);
// Make Copy Of Current State
Copy := Original.Clone();
Original.TransformBytes(ChunkTwo);
FExpectedString := Original.TransformFinal().ToString();
Copy.TransformBytes(ChunkTwo);
FActualString := Copy.TransformFinal().ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestAP.TestHashCloneIsUnique;
var
Original, Copy: IHash;
begin
Original := FAP;
Original.Initialize;
Original.BufferSize := (64 * 1024); // 64Kb
// Make Copy Of Current State
Copy := Original.Clone();
Copy.BufferSize := (128 * 1024); // 128Kb
CheckNotEquals(Original.BufferSize, Copy.BufferSize,
Format('Expected %d but got %d.', [Original.BufferSize, Copy.BufferSize]));
end;
procedure TTestAP.TestDefaultData;
begin
FExpectedString := FExpectedHashOfDefaultData;
FActualString := FAP.ComputeString(FDefaultData, TEncoding.UTF8).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestAP.TestEmptyStream;
var
stream: TStream;
begin
stream := TMemoryStream.Create;
try
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FAP.ComputeStream(stream).ToString();
CheckEquals(FExpectedString, FActualString,
Format('Expected %s but got %s.', [FExpectedString, FActualString]));
finally
stream.Free;
end;
end;
procedure TTestAP.TestEmptyString;
begin
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FAP.ComputeString(FEmptyData, TEncoding.UTF8).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestAP.TestIncrementalHash;
begin
FExpectedString := FExpectedHashOfDefaultData;
FHash := THashFactory.THash32.CreateAP();
FHash.Initialize();
FHash.TransformString(System.Copy(FDefaultData, 1, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 4, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 7, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 10, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 13, 2), TEncoding.UTF8);
FHashResult := FHash.TransformFinal();
FActualString := FHashResult.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestAP.TestOnetoNine;
begin
FExpectedString := FExpectedHashOfOnetoNine;
FActualString := FAP.ComputeString(FOnetoNine, TEncoding.UTF8).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
{ TTestBernstein }
procedure TTestBernstein.SetUp;
begin
inherited;
FBernstein := THashFactory.THash32.CreateBernstein();
end;
procedure TTestBernstein.TearDown;
begin
FBernstein := Nil;
inherited;
end;
procedure TTestBernstein.TestBytesabcde;
var
LBuffer: TBytes;
begin
System.SetLength(LBuffer, System.SizeOf(FBytesabcde));
System.Move(FBytesabcde, Pointer(LBuffer)^, System.SizeOf(FBytesabcde));
FExpectedString := FExpectedHashOfabcde;
FActualString := FBernstein.ComputeBytes(LBuffer).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestBernstein.TestHashCloneIsCorrect;
var
Original, Copy: IHash;
MainData, ChunkOne, ChunkTwo: TBytes;
Count: Int32;
begin
MainData := TConverters.ConvertStringToBytes(FDefaultData, TEncoding.UTF8);
Count := System.Length(MainData) - 3;
ChunkOne := System.Copy(MainData, 0, Count);
ChunkTwo := System.Copy(MainData, Count, System.Length(MainData) - Count);
Original := FBernstein;
Original.Initialize;
Original.TransformBytes(ChunkOne);
// Make Copy Of Current State
Copy := Original.Clone();
Original.TransformBytes(ChunkTwo);
FExpectedString := Original.TransformFinal().ToString();
Copy.TransformBytes(ChunkTwo);
FActualString := Copy.TransformFinal().ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestBernstein.TestHashCloneIsUnique;
var
Original, Copy: IHash;
begin
Original := FBernstein;
Original.Initialize;
Original.BufferSize := (64 * 1024); // 64Kb
// Make Copy Of Current State
Copy := Original.Clone();
Copy.BufferSize := (128 * 1024); // 128Kb
CheckNotEquals(Original.BufferSize, Copy.BufferSize,
Format('Expected %d but got %d.', [Original.BufferSize, Copy.BufferSize]));
end;
procedure TTestBernstein.TestDefaultData;
begin
FExpectedString := FExpectedHashOfDefaultData;
FActualString := FBernstein.ComputeString(FDefaultData, TEncoding.UTF8)
.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestBernstein.TestEmptyStream;
var
stream: TStream;
begin
stream := TMemoryStream.Create;
try
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FBernstein.ComputeStream(stream).ToString();
CheckEquals(FExpectedString, FActualString,
Format('Expected %s but got %s.', [FExpectedString, FActualString]));
finally
stream.Free;
end;
end;
procedure TTestBernstein.TestEmptyString;
begin
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FBernstein.ComputeString(FEmptyData, TEncoding.UTF8)
.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestBernstein.TestIncrementalHash;
begin
FExpectedString := FExpectedHashOfDefaultData;
FHash := THashFactory.THash32.CreateBernstein();
FHash.Initialize();
FHash.TransformString(System.Copy(FDefaultData, 1, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 4, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 7, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 10, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 13, 2), TEncoding.UTF8);
FHashResult := FHash.TransformFinal();
FActualString := FHashResult.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestBernstein.TestOnetoNine;
begin
FExpectedString := FExpectedHashOfOnetoNine;
FActualString := FBernstein.ComputeString(FOnetoNine, TEncoding.UTF8)
.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
{ TTestBernstein1 }
procedure TTestBernstein1.SetUp;
begin
inherited;
FBernstein1 := THashFactory.THash32.CreateBernstein1();
end;
procedure TTestBernstein1.TearDown;
begin
FBernstein1 := Nil;
inherited;
end;
procedure TTestBernstein1.TestBytesabcde;
var
LBuffer: TBytes;
begin
System.SetLength(LBuffer, System.SizeOf(FBytesabcde));
System.Move(FBytesabcde, Pointer(LBuffer)^, System.SizeOf(FBytesabcde));
FExpectedString := FExpectedHashOfabcde;
FActualString := FBernstein1.ComputeBytes(LBuffer).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestBernstein1.TestHashCloneIsCorrect;
var
Original, Copy: IHash;
MainData, ChunkOne, ChunkTwo: TBytes;
Count: Int32;
begin
MainData := TConverters.ConvertStringToBytes(FDefaultData, TEncoding.UTF8);
Count := System.Length(MainData) - 3;
ChunkOne := System.Copy(MainData, 0, Count);
ChunkTwo := System.Copy(MainData, Count, System.Length(MainData) - Count);
Original := FBernstein1;
Original.Initialize;
Original.TransformBytes(ChunkOne);
// Make Copy Of Current State
Copy := Original.Clone();
Original.TransformBytes(ChunkTwo);
FExpectedString := Original.TransformFinal().ToString();
Copy.TransformBytes(ChunkTwo);
FActualString := Copy.TransformFinal().ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestBernstein1.TestHashCloneIsUnique;
var
Original, Copy: IHash;
begin
Original := FBernstein1;
Original.Initialize;
Original.BufferSize := (64 * 1024); // 64Kb
// Make Copy Of Current State
Copy := Original.Clone();
Copy.BufferSize := (128 * 1024); // 128Kb
CheckNotEquals(Original.BufferSize, Copy.BufferSize,
Format('Expected %d but got %d.', [Original.BufferSize, Copy.BufferSize]));
end;
procedure TTestBernstein1.TestDefaultData;
begin
FExpectedString := FExpectedHashOfDefaultData;
FActualString := FBernstein1.ComputeString(FDefaultData, TEncoding.UTF8)
.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestBernstein1.TestEmptyStream;
var
stream: TStream;
begin
stream := TMemoryStream.Create;
try
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FBernstein1.ComputeStream(stream).ToString();
CheckEquals(FExpectedString, FActualString,
Format('Expected %s but got %s.', [FExpectedString, FActualString]));
finally
stream.Free;
end;
end;
procedure TTestBernstein1.TestEmptyString;
begin
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FBernstein1.ComputeString(FEmptyData, TEncoding.UTF8)
.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestBernstein1.TestIncrementalHash;
begin
FExpectedString := FExpectedHashOfDefaultData;
FHash := THashFactory.THash32.CreateBernstein1();
FHash.Initialize();
FHash.TransformString(System.Copy(FDefaultData, 1, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 4, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 7, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 10, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 13, 2), TEncoding.UTF8);
FHashResult := FHash.TransformFinal();
FActualString := FHashResult.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestBernstein1.TestOnetoNine;
begin
FExpectedString := FExpectedHashOfOnetoNine;
FActualString := FBernstein1.ComputeString(FOnetoNine, TEncoding.UTF8)
.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
{ TTestBKDR }
procedure TTestBKDR.SetUp;
begin
inherited;
FBKDR := THashFactory.THash32.CreateBKDR();
end;
procedure TTestBKDR.TearDown;
begin
FBKDR := Nil;
inherited;
end;
procedure TTestBKDR.TestBytesabcde;
var
LBuffer: TBytes;
begin
System.SetLength(LBuffer, System.SizeOf(FBytesabcde));
System.Move(FBytesabcde, Pointer(LBuffer)^, System.SizeOf(FBytesabcde));
FExpectedString := FExpectedHashOfabcde;
FActualString := FBKDR.ComputeBytes(LBuffer).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestBKDR.TestHashCloneIsCorrect;
var
Original, Copy: IHash;
MainData, ChunkOne, ChunkTwo: TBytes;
Count: Int32;
begin
MainData := TConverters.ConvertStringToBytes(FDefaultData, TEncoding.UTF8);
Count := System.Length(MainData) - 3;
ChunkOne := System.Copy(MainData, 0, Count);
ChunkTwo := System.Copy(MainData, Count, System.Length(MainData) - Count);
Original := FBKDR;
Original.Initialize;
Original.TransformBytes(ChunkOne);
// Make Copy Of Current State
Copy := Original.Clone();
Original.TransformBytes(ChunkTwo);
FExpectedString := Original.TransformFinal().ToString();
Copy.TransformBytes(ChunkTwo);
FActualString := Copy.TransformFinal().ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestBKDR.TestHashCloneIsUnique;
var
Original, Copy: IHash;
begin
Original := FBKDR;
Original.Initialize;
Original.BufferSize := (64 * 1024); // 64Kb
// Make Copy Of Current State
Copy := Original.Clone();
Copy.BufferSize := (128 * 1024); // 128Kb
CheckNotEquals(Original.BufferSize, Copy.BufferSize,
Format('Expected %d but got %d.', [Original.BufferSize, Copy.BufferSize]));
end;
procedure TTestBKDR.TestDefaultData;
begin
FExpectedString := FExpectedHashOfDefaultData;
FActualString := FBKDR.ComputeString(FDefaultData, TEncoding.UTF8).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestBKDR.TestEmptyStream;
var
stream: TStream;
begin
stream := TMemoryStream.Create;
try
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FBKDR.ComputeStream(stream).ToString();
CheckEquals(FExpectedString, FActualString,
Format('Expected %s but got %s.', [FExpectedString, FActualString]));
finally
stream.Free;
end;
end;
procedure TTestBKDR.TestEmptyString;
begin
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FBKDR.ComputeString(FEmptyData, TEncoding.UTF8).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestBKDR.TestIncrementalHash;
begin
FExpectedString := FExpectedHashOfDefaultData;
FHash := THashFactory.THash32.CreateBKDR();
FHash.Initialize();
FHash.TransformString(System.Copy(FDefaultData, 1, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 4, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 7, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 10, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 13, 2), TEncoding.UTF8);
FHashResult := FHash.TransformFinal();
FActualString := FHashResult.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestBKDR.TestOnetoNine;
begin
FExpectedString := FExpectedHashOfOnetoNine;
FActualString := FBKDR.ComputeString(FOnetoNine, TEncoding.UTF8).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
{ TTestDEK }
procedure TTestDEK.SetUp;
begin
inherited;
FDEK := THashFactory.THash32.CreateDEK();
end;
procedure TTestDEK.TearDown;
begin
FDEK := Nil;
inherited;
end;
procedure TTestDEK.TestBytesabcde;
var
LBuffer: TBytes;
begin
System.SetLength(LBuffer, System.SizeOf(FBytesabcde));
System.Move(FBytesabcde, Pointer(LBuffer)^, System.SizeOf(FBytesabcde));
FExpectedString := FExpectedHashOfabcde;
FActualString := FDEK.ComputeBytes(LBuffer).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestDEK.TestHashCloneIsCorrect;
var
Original, Copy: IHash;
MainData, ChunkOne, ChunkTwo: TBytes;
Count: Int32;
begin
MainData := TConverters.ConvertStringToBytes(FDefaultData, TEncoding.UTF8);
Count := System.Length(MainData) - 3;
ChunkOne := System.Copy(MainData, 0, Count);
ChunkTwo := System.Copy(MainData, Count, System.Length(MainData) - Count);
Original := FDEK;
Original.Initialize;
Original.TransformBytes(ChunkOne);
// Make Copy Of Current State
Copy := Original.Clone();
Original.TransformBytes(ChunkTwo);
FExpectedString := Original.TransformFinal().ToString();
Copy.TransformBytes(ChunkTwo);
FActualString := Copy.TransformFinal().ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestDEK.TestHashCloneIsUnique;
var
Original, Copy: IHash;
begin
Original := FDEK;
Original.Initialize;
Original.BufferSize := (64 * 1024); // 64Kb
// Make Copy Of Current State
Copy := Original.Clone();
Copy.BufferSize := (128 * 1024); // 128Kb
CheckNotEquals(Original.BufferSize, Copy.BufferSize,
Format('Expected %d but got %d.', [Original.BufferSize, Copy.BufferSize]));
end;
procedure TTestDEK.TestDefaultData;
begin
FExpectedString := FExpectedHashOfDefaultData;
FActualString := FDEK.ComputeString(FDefaultData, TEncoding.UTF8).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestDEK.TestEmptyStream;
var
stream: TStream;
begin
stream := TMemoryStream.Create;
try
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FDEK.ComputeStream(stream).ToString();
CheckEquals(FExpectedString, FActualString,
Format('Expected %s but got %s.', [FExpectedString, FActualString]));
finally
stream.Free;
end;
end;
procedure TTestDEK.TestEmptyString;
begin
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FDEK.ComputeString(FEmptyData, TEncoding.UTF8).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestDEK.TestIncrementalHash;
begin
FExpectedString := FExpectedHashOfDefaultData;
FHash := THashFactory.THash32.CreateDEK();
FHash.Initialize();
FHash.TransformString(System.Copy(FDefaultData, 1, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 4, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 7, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 10, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 13, 2), TEncoding.UTF8);
FHashResult := FHash.TransformFinal();
FActualString := FHashResult.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestDEK.TestOnetoNine;
begin
FExpectedString := FExpectedHashOfOnetoNine;
FActualString := FDEK.ComputeString(FOnetoNine, TEncoding.UTF8).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
{ TTestDJB }
procedure TTestDJB.SetUp;
begin
inherited;
FDJB := THashFactory.THash32.CreateDJB();
end;
procedure TTestDJB.TearDown;
begin
FDJB := Nil;
inherited;
end;
procedure TTestDJB.TestBytesabcde;
var
LBuffer: TBytes;
begin
System.SetLength(LBuffer, System.SizeOf(FBytesabcde));
System.Move(FBytesabcde, Pointer(LBuffer)^, System.SizeOf(FBytesabcde));
FExpectedString := FExpectedHashOfabcde;
FActualString := FDJB.ComputeBytes(LBuffer).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestDJB.TestHashCloneIsCorrect;
var
Original, Copy: IHash;
MainData, ChunkOne, ChunkTwo: TBytes;
Count: Int32;
begin
MainData := TConverters.ConvertStringToBytes(FDefaultData, TEncoding.UTF8);
Count := System.Length(MainData) - 3;
ChunkOne := System.Copy(MainData, 0, Count);
ChunkTwo := System.Copy(MainData, Count, System.Length(MainData) - Count);
Original := FDJB;
Original.Initialize;
Original.TransformBytes(ChunkOne);
// Make Copy Of Current State
Copy := Original.Clone();
Original.TransformBytes(ChunkTwo);
FExpectedString := Original.TransformFinal().ToString();
Copy.TransformBytes(ChunkTwo);
FActualString := Copy.TransformFinal().ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestDJB.TestHashCloneIsUnique;
var
Original, Copy: IHash;
begin
Original := FDJB;
Original.Initialize;
Original.BufferSize := (64 * 1024); // 64Kb
// Make Copy Of Current State
Copy := Original.Clone();
Copy.BufferSize := (128 * 1024); // 128Kb
CheckNotEquals(Original.BufferSize, Copy.BufferSize,
Format('Expected %d but got %d.', [Original.BufferSize, Copy.BufferSize]));
end;
procedure TTestDJB.TestDefaultData;
begin
FExpectedString := FExpectedHashOfDefaultData;
FActualString := FDJB.ComputeString(FDefaultData, TEncoding.UTF8).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestDJB.TestEmptyStream;
var
stream: TStream;
begin
stream := TMemoryStream.Create;
try
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FDJB.ComputeStream(stream).ToString();
CheckEquals(FExpectedString, FActualString,
Format('Expected %s but got %s.', [FExpectedString, FActualString]));
finally
stream.Free;
end;
end;
procedure TTestDJB.TestEmptyString;
begin
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FDJB.ComputeString(FEmptyData, TEncoding.UTF8).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestDJB.TestIncrementalHash;
begin
FExpectedString := FExpectedHashOfDefaultData;
FHash := THashFactory.THash32.CreateDJB();
FHash.Initialize();
FHash.TransformString(System.Copy(FDefaultData, 1, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 4, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 7, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 10, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 13, 2), TEncoding.UTF8);
FHashResult := FHash.TransformFinal();
FActualString := FHashResult.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestDJB.TestOnetoNine;
begin
FExpectedString := FExpectedHashOfOnetoNine;
FActualString := FDJB.ComputeString(FOnetoNine, TEncoding.UTF8).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
{ TTestELF }
procedure TTestELF.SetUp;
begin
inherited;
FELF := THashFactory.THash32.CreateELF();
end;
procedure TTestELF.TearDown;
begin
FELF := Nil;
inherited;
end;
procedure TTestELF.TestBytesabcde;
var
LBuffer: TBytes;
begin
System.SetLength(LBuffer, System.SizeOf(FBytesabcde));
System.Move(FBytesabcde, Pointer(LBuffer)^, System.SizeOf(FBytesabcde));
FExpectedString := FExpectedHashOfabcde;
FActualString := FELF.ComputeBytes(LBuffer).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestELF.TestHashCloneIsCorrect;
var
Original, Copy: IHash;
MainData, ChunkOne, ChunkTwo: TBytes;
Count: Int32;
begin
MainData := TConverters.ConvertStringToBytes(FDefaultData, TEncoding.UTF8);
Count := System.Length(MainData) - 3;
ChunkOne := System.Copy(MainData, 0, Count);
ChunkTwo := System.Copy(MainData, Count, System.Length(MainData) - Count);
Original := FELF;
Original.Initialize;
Original.TransformBytes(ChunkOne);
// Make Copy Of Current State
Copy := Original.Clone();
Original.TransformBytes(ChunkTwo);
FExpectedString := Original.TransformFinal().ToString();
Copy.TransformBytes(ChunkTwo);
FActualString := Copy.TransformFinal().ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestELF.TestHashCloneIsUnique;
var
Original, Copy: IHash;
begin
Original := FELF;
Original.Initialize;
Original.BufferSize := (64 * 1024); // 64Kb
// Make Copy Of Current State
Copy := Original.Clone();
Copy.BufferSize := (128 * 1024); // 128Kb
CheckNotEquals(Original.BufferSize, Copy.BufferSize,
Format('Expected %d but got %d.', [Original.BufferSize, Copy.BufferSize]));
end;
procedure TTestELF.TestDefaultData;
begin
FExpectedString := FExpectedHashOfDefaultData;
FActualString := FELF.ComputeString(FDefaultData, TEncoding.UTF8).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestELF.TestEmptyStream;
var
stream: TStream;
begin
stream := TMemoryStream.Create;
try
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FELF.ComputeStream(stream).ToString();
CheckEquals(FExpectedString, FActualString,
Format('Expected %s but got %s.', [FExpectedString, FActualString]));
finally
stream.Free;
end;
end;
procedure TTestELF.TestEmptyString;
begin
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FELF.ComputeString(FEmptyData, TEncoding.UTF8).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestELF.TestIncrementalHash;
begin
FExpectedString := FExpectedHashOfDefaultData;
FHash := THashFactory.THash32.CreateELF();
FHash.Initialize();
FHash.TransformString(System.Copy(FDefaultData, 1, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 4, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 7, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 10, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 13, 2), TEncoding.UTF8);
FHashResult := FHash.TransformFinal();
FActualString := FHashResult.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestELF.TestOnetoNine;
begin
FExpectedString := FExpectedHashOfOnetoNine;
FActualString := FELF.ComputeString(FOnetoNine, TEncoding.UTF8).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
{ TTestFNV }
procedure TTestFNV.SetUp;
begin
inherited;
FFNV := THashFactory.THash32.CreateFNV();
end;
procedure TTestFNV.TearDown;
begin
FFNV := Nil;
inherited;
end;
procedure TTestFNV.TestBytesabcde;
var
LBuffer: TBytes;
begin
System.SetLength(LBuffer, System.SizeOf(FBytesabcde));
System.Move(FBytesabcde, Pointer(LBuffer)^, System.SizeOf(FBytesabcde));
FExpectedString := FExpectedHashOfabcde;
FActualString := FFNV.ComputeBytes(LBuffer).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestFNV.TestHashCloneIsCorrect;
var
Original, Copy: IHash;
MainData, ChunkOne, ChunkTwo: TBytes;
Count: Int32;
begin
MainData := TConverters.ConvertStringToBytes(FDefaultData, TEncoding.UTF8);
Count := System.Length(MainData) - 3;
ChunkOne := System.Copy(MainData, 0, Count);
ChunkTwo := System.Copy(MainData, Count, System.Length(MainData) - Count);
Original := FFNV;
Original.Initialize;
Original.TransformBytes(ChunkOne);
// Make Copy Of Current State
Copy := Original.Clone();
Original.TransformBytes(ChunkTwo);
FExpectedString := Original.TransformFinal().ToString();
Copy.TransformBytes(ChunkTwo);
FActualString := Copy.TransformFinal().ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestFNV.TestHashCloneIsUnique;
var
Original, Copy: IHash;
begin
Original := FFNV;
Original.Initialize;
Original.BufferSize := (64 * 1024); // 64Kb
// Make Copy Of Current State
Copy := Original.Clone();
Copy.BufferSize := (128 * 1024); // 128Kb
CheckNotEquals(Original.BufferSize, Copy.BufferSize,
Format('Expected %d but got %d.', [Original.BufferSize, Copy.BufferSize]));
end;
procedure TTestFNV.TestDefaultData;
begin
FExpectedString := FExpectedHashOfDefaultData;
FActualString := FFNV.ComputeString(FDefaultData, TEncoding.UTF8).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestFNV.TestEmptyStream;
var
stream: TStream;
begin
stream := TMemoryStream.Create;
try
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FFNV.ComputeStream(stream).ToString();
CheckEquals(FExpectedString, FActualString,
Format('Expected %s but got %s.', [FExpectedString, FActualString]));
finally
stream.Free;
end;
end;
procedure TTestFNV.TestEmptyString;
begin
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FFNV.ComputeString(FEmptyData, TEncoding.UTF8).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestFNV.TestIncrementalHash;
begin
FExpectedString := FExpectedHashOfDefaultData;
FHash := THashFactory.THash32.CreateFNV();
FHash.Initialize();
FHash.TransformString(System.Copy(FDefaultData, 1, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 4, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 7, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 10, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 13, 2), TEncoding.UTF8);
FHashResult := FHash.TransformFinal();
FActualString := FHashResult.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestFNV.TestOnetoNine;
begin
FExpectedString := FExpectedHashOfOnetoNine;
FActualString := FFNV.ComputeString(FOnetoNine, TEncoding.UTF8).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
{ TTestFNV1a }
procedure TTestFNV1a.SetUp;
begin
inherited;
FFNV1a := THashFactory.THash32.CreateFNV1a();
end;
procedure TTestFNV1a.TearDown;
begin
FFNV1a := Nil;
inherited;
end;
procedure TTestFNV1a.TestBytesabcde;
var
LBuffer: TBytes;
begin
System.SetLength(LBuffer, System.SizeOf(FBytesabcde));
System.Move(FBytesabcde, Pointer(LBuffer)^, System.SizeOf(FBytesabcde));
FExpectedString := FExpectedHashOfabcde;
FActualString := FFNV1a.ComputeBytes(LBuffer).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestFNV1a.TestHashCloneIsCorrect;
var
Original, Copy: IHash;
MainData, ChunkOne, ChunkTwo: TBytes;
Count: Int32;
begin
MainData := TConverters.ConvertStringToBytes(FDefaultData, TEncoding.UTF8);
Count := System.Length(MainData) - 3;
ChunkOne := System.Copy(MainData, 0, Count);
ChunkTwo := System.Copy(MainData, Count, System.Length(MainData) - Count);
Original := FFNV1a;
Original.Initialize;
Original.TransformBytes(ChunkOne);
// Make Copy Of Current State
Copy := Original.Clone();
Original.TransformBytes(ChunkTwo);
FExpectedString := Original.TransformFinal().ToString();
Copy.TransformBytes(ChunkTwo);
FActualString := Copy.TransformFinal().ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestFNV1a.TestHashCloneIsUnique;
var
Original, Copy: IHash;
begin
Original := FFNV1a;
Original.Initialize;
Original.BufferSize := (64 * 1024); // 64Kb
// Make Copy Of Current State
Copy := Original.Clone();
Copy.BufferSize := (128 * 1024); // 128Kb
CheckNotEquals(Original.BufferSize, Copy.BufferSize,
Format('Expected %d but got %d.', [Original.BufferSize, Copy.BufferSize]));
end;
procedure TTestFNV1a.TestDefaultData;
begin
FExpectedString := FExpectedHashOfDefaultData;
FActualString := FFNV1a.ComputeString(FDefaultData, TEncoding.UTF8)
.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestFNV1a.TestEmptyStream;
var
stream: TStream;
begin
stream := TMemoryStream.Create;
try
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FFNV1a.ComputeStream(stream).ToString();
CheckEquals(FExpectedString, FActualString,
Format('Expected %s but got %s.', [FExpectedString, FActualString]));
finally
stream.Free;
end;
end;
procedure TTestFNV1a.TestEmptyString;
begin
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FFNV1a.ComputeString(FEmptyData, TEncoding.UTF8).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestFNV1a.TestIncrementalHash;
begin
FExpectedString := FExpectedHashOfDefaultData;
FHash := THashFactory.THash32.CreateFNV1a();
FHash.Initialize();
FHash.TransformString(System.Copy(FDefaultData, 1, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 4, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 7, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 10, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 13, 2), TEncoding.UTF8);
FHashResult := FHash.TransformFinal();
FActualString := FHashResult.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestFNV1a.TestOnetoNine;
begin
FExpectedString := FExpectedHashOfOnetoNine;
FActualString := FFNV1a.ComputeString(FOnetoNine, TEncoding.UTF8).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
{ TTestJenkins3 }
procedure TTestJenkins3.SetUp;
begin
inherited;
FJenkins3 := THashFactory.THash32.CreateJenkins3();
end;
procedure TTestJenkins3.TearDown;
begin
FJenkins3 := Nil;
inherited;
end;
procedure TTestJenkins3.TestBytesabcde;
var
LBuffer: TBytes;
begin
System.SetLength(LBuffer, System.SizeOf(FBytesabcde));
System.Move(FBytesabcde, Pointer(LBuffer)^, System.SizeOf(FBytesabcde));
FExpectedString := FExpectedHashOfabcde;
FActualString := FJenkins3.ComputeBytes(LBuffer).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestJenkins3.TestHashCloneIsCorrect;
var
Original, Copy: IHash;
MainData, ChunkOne, ChunkTwo: TBytes;
Count: Int32;
begin
MainData := TConverters.ConvertStringToBytes(FDefaultData, TEncoding.UTF8);
Count := System.Length(MainData) - 3;
ChunkOne := System.Copy(MainData, 0, Count);
ChunkTwo := System.Copy(MainData, Count, System.Length(MainData) - Count);
Original := FJenkins3;
Original.Initialize;
Original.TransformBytes(ChunkOne);
// Make Copy Of Current State
Copy := Original.Clone();
Original.TransformBytes(ChunkTwo);
FExpectedString := Original.TransformFinal().ToString();
Copy.TransformBytes(ChunkTwo);
FActualString := Copy.TransformFinal().ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestJenkins3.TestHashCloneIsUnique;
var
Original, Copy: IHash;
begin
Original := FJenkins3;
Original.Initialize;
Original.BufferSize := (64 * 1024); // 64Kb
// Make Copy Of Current State
Copy := Original.Clone();
Copy.BufferSize := (128 * 1024); // 128Kb
CheckNotEquals(Original.BufferSize, Copy.BufferSize,
Format('Expected %d but got %d.', [Original.BufferSize, Copy.BufferSize]));
end;
procedure TTestJenkins3.TestDefaultData;
begin
FExpectedString := FExpectedHashOfDefaultData;
FActualString := FJenkins3.ComputeString(FDefaultData, TEncoding.UTF8)
.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestJenkins3.TestEmptyStream;
var
stream: TStream;
begin
stream := TMemoryStream.Create;
try
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FJenkins3.ComputeStream(stream).ToString();
CheckEquals(FExpectedString, FActualString,
Format('Expected %s but got %s.', [FExpectedString, FActualString]));
finally
stream.Free;
end;
end;
procedure TTestJenkins3.TestEmptyString;
begin
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FJenkins3.ComputeString(FEmptyData, TEncoding.UTF8)
.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestJenkins3.TestIncrementalHash;
begin
FExpectedString := FExpectedHashOfDefaultData;
FHash := THashFactory.THash32.CreateJenkins3();
FHash.Initialize();
FHash.TransformString(System.Copy(FDefaultData, 1, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 4, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 7, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 10, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 13, 2), TEncoding.UTF8);
FHashResult := FHash.TransformFinal();
FActualString := FHashResult.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestJenkins3.TestOnetoNine;
begin
FExpectedString := FExpectedHashOfOnetoNine;
FActualString := FJenkins3.ComputeString(FOnetoNine, TEncoding.UTF8)
.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
{ TTestJS }
procedure TTestJS.SetUp;
begin
inherited;
FJS := THashFactory.THash32.CreateJS();
end;
procedure TTestJS.TearDown;
begin
FJS := Nil;
inherited;
end;
procedure TTestJS.TestBytesabcde;
var
LBuffer: TBytes;
begin
System.SetLength(LBuffer, System.SizeOf(FBytesabcde));
System.Move(FBytesabcde, Pointer(LBuffer)^, System.SizeOf(FBytesabcde));
FExpectedString := FExpectedHashOfabcde;
FActualString := FJS.ComputeBytes(LBuffer).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestJS.TestHashCloneIsCorrect;
var
Original, Copy: IHash;
MainData, ChunkOne, ChunkTwo: TBytes;
Count: Int32;
begin
MainData := TConverters.ConvertStringToBytes(FDefaultData, TEncoding.UTF8);
Count := System.Length(MainData) - 3;
ChunkOne := System.Copy(MainData, 0, Count);
ChunkTwo := System.Copy(MainData, Count, System.Length(MainData) - Count);
Original := FJS;
Original.Initialize;
Original.TransformBytes(ChunkOne);
// Make Copy Of Current State
Copy := Original.Clone();
Original.TransformBytes(ChunkTwo);
FExpectedString := Original.TransformFinal().ToString();
Copy.TransformBytes(ChunkTwo);
FActualString := Copy.TransformFinal().ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestJS.TestHashCloneIsUnique;
var
Original, Copy: IHash;
begin
Original := FJS;
Original.Initialize;
Original.BufferSize := (64 * 1024); // 64Kb
// Make Copy Of Current State
Copy := Original.Clone();
Copy.BufferSize := (128 * 1024); // 128Kb
CheckNotEquals(Original.BufferSize, Copy.BufferSize,
Format('Expected %d but got %d.', [Original.BufferSize, Copy.BufferSize]));
end;
procedure TTestJS.TestDefaultData;
begin
FExpectedString := FExpectedHashOfDefaultData;
FActualString := FJS.ComputeString(FDefaultData, TEncoding.UTF8).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestJS.TestEmptyStream;
var
stream: TStream;
begin
stream := TMemoryStream.Create;
try
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FJS.ComputeStream(stream).ToString();
CheckEquals(FExpectedString, FActualString,
Format('Expected %s but got %s.', [FExpectedString, FActualString]));
finally
stream.Free;
end;
end;
procedure TTestJS.TestEmptyString;
begin
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FJS.ComputeString(FEmptyData, TEncoding.UTF8).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestJS.TestIncrementalHash;
begin
FExpectedString := FExpectedHashOfDefaultData;
FHash := THashFactory.THash32.CreateJS();
FHash.Initialize();
FHash.TransformString(System.Copy(FDefaultData, 1, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 4, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 7, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 10, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 13, 2), TEncoding.UTF8);
FHashResult := FHash.TransformFinal();
FActualString := FHashResult.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestJS.TestOnetoNine;
begin
FExpectedString := FExpectedHashOfOnetoNine;
FActualString := FJS.ComputeString(FOnetoNine, TEncoding.UTF8).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
{ TTestMurmur2 }
procedure TTestMurmur2.SetUp;
begin
inherited;
FMurmur2 := THashFactory.THash32.CreateMurmur2();
end;
procedure TTestMurmur2.TearDown;
begin
FMurmur2 := Nil;
inherited;
end;
procedure TTestMurmur2.TestBytesabcde;
var
LBuffer: TBytes;
begin
System.SetLength(LBuffer, System.SizeOf(FBytesabcde));
System.Move(FBytesabcde, Pointer(LBuffer)^, System.SizeOf(FBytesabcde));
FExpectedString := FExpectedHashOfabcde;
FActualString := FMurmur2.ComputeBytes(LBuffer).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestMurmur2.TestHashCloneIsCorrect;
var
Original, Copy: IHash;
MainData, ChunkOne, ChunkTwo: TBytes;
Count: Int32;
begin
MainData := TConverters.ConvertStringToBytes(FDefaultData, TEncoding.UTF8);
Count := System.Length(MainData) - 3;
ChunkOne := System.Copy(MainData, 0, Count);
ChunkTwo := System.Copy(MainData, Count, System.Length(MainData) - Count);
Original := FMurmur2;
Original.Initialize;
Original.TransformBytes(ChunkOne);
// Make Copy Of Current State
Copy := Original.Clone();
Original.TransformBytes(ChunkTwo);
FExpectedString := Original.TransformFinal().ToString();
Copy.TransformBytes(ChunkTwo);
FActualString := Copy.TransformFinal().ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestMurmur2.TestHashCloneIsUnique;
var
Original, Copy: IHash;
begin
Original := FMurmur2;
Original.Initialize;
Original.BufferSize := (64 * 1024); // 64Kb
// Make Copy Of Current State
Copy := Original.Clone();
Copy.BufferSize := (128 * 1024); // 128Kb
CheckNotEquals(Original.BufferSize, Copy.BufferSize,
Format('Expected %d but got %d.', [Original.BufferSize, Copy.BufferSize]));
end;
procedure TTestMurmur2.TestDefaultData;
begin
FExpectedString := FExpectedHashOfDefaultData;
FActualString := FMurmur2.ComputeString(FDefaultData, TEncoding.UTF8)
.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestMurmur2.TestEmptyStream;
var
stream: TStream;
begin
stream := TMemoryStream.Create;
try
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FMurmur2.ComputeStream(stream).ToString();
CheckEquals(FExpectedString, FActualString,
Format('Expected %s but got %s.', [FExpectedString, FActualString]));
finally
stream.Free;
end;
end;
procedure TTestMurmur2.TestEmptyString;
begin
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FMurmur2.ComputeString(FEmptyData, TEncoding.UTF8)
.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestMurmur2.TestIncrementalHash;
begin
FExpectedString := FExpectedHashOfDefaultData;
FHash := THashFactory.THash32.CreateMurmur2();
FHash.Initialize();
FHash.TransformString(System.Copy(FDefaultData, 1, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 4, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 7, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 10, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 13, 2), TEncoding.UTF8);
FHashResult := FHash.TransformFinal();
FActualString := FHashResult.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestMurmur2.TestOnetoNine;
begin
FExpectedString := FExpectedHashOfOnetoNine;
FActualString := FMurmur2.ComputeString(FOnetoNine, TEncoding.UTF8)
.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestMurmur2.TestWithDifferentKey;
var
LIHashWithKey: IHashWithKey;
begin
FExpectedString := FExpectedHashOfDefaultDataWithMaxUInt32AsKey;
LIHashWithKey := (FMurmur2 as IHashWithKey);
LIHashWithKey.Key := TConverters.ReadUInt32AsBytesLE(System.High(UInt32));
FActualString := LIHashWithKey.ComputeString(FDefaultData, TEncoding.UTF8)
.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
{ TTestMurmurHash3_x86_32 }
procedure TTestMurmurHash3_x86_32.SetUp;
begin
inherited;
FMurmurHash3_x86_32 := THashFactory.THash32.CreateMurmurHash3_x86_32();
end;
procedure TTestMurmurHash3_x86_32.TearDown;
begin
FMurmurHash3_x86_32 := Nil;
inherited;
end;
procedure TTestMurmurHash3_x86_32.TestEmptyStream;
var
stream: TStream;
begin
stream := TMemoryStream.Create;
try
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FMurmurHash3_x86_32.ComputeStream(stream).ToString();
CheckEquals(FExpectedString, FActualString,
Format('Expected %s but got %s.', [FExpectedString, FActualString]));
finally
stream.Free;
end;
end;
procedure TTestMurmurHash3_x86_32.TestEmptyString;
begin
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FMurmurHash3_x86_32.ComputeString(FEmptyData, TEncoding.UTF8)
.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestMurmurHash3_x86_32.TestAnotherChunkedDataIncrementalHash;
var
x, size, i: Int32;
temp: string;
begin
for x := 0 to System.Pred(System.SizeOf(Fc_chunkSize)
div System.SizeOf(Int32)) do
begin
size := Fc_chunkSize[x];
FMurmurHash3_x86_32.Initialize();
i := size;
while i < System.Length(FChunkedData) do
begin
temp := System.Copy(FChunkedData, (i - size) + 1, size);
FMurmurHash3_x86_32.TransformString(temp, TEncoding.UTF8);
System.Inc(i, size);
end;
temp := System.Copy(FChunkedData, (i - size) + 1,
System.Length(FChunkedData) - ((i - size)));
FMurmurHash3_x86_32.TransformString(temp, TEncoding.UTF8);
FActualString := FMurmurHash3_x86_32.TransformFinal().ToString();
FExpectedString := THashFactory.THash32.CreateMurmurHash3_x86_32.
ComputeString(FChunkedData, TEncoding.UTF8).ToString();
CheckEquals(FExpectedString, FActualString,
Format('Expected %s but got %s.', [FExpectedString, FActualString]));
end;
end;
procedure TTestMurmurHash3_x86_32.TestHashCloneIsCorrect;
var
Original, Copy: IHash;
MainData, ChunkOne, ChunkTwo: TBytes;
Count: Int32;
begin
MainData := TConverters.ConvertStringToBytes(FDefaultData, TEncoding.UTF8);
Count := System.Length(MainData) - 3;
ChunkOne := System.Copy(MainData, 0, Count);
ChunkTwo := System.Copy(MainData, Count, System.Length(MainData) - Count);
Original := FMurmurHash3_x86_32;
Original.Initialize;
Original.TransformBytes(ChunkOne);
// Make Copy Of Current State
Copy := Original.Clone();
Original.TransformBytes(ChunkTwo);
FExpectedString := Original.TransformFinal().ToString();
Copy.TransformBytes(ChunkTwo);
FActualString := Copy.TransformFinal().ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestMurmurHash3_x86_32.TestHashCloneIsUnique;
var
Original, Copy: IHash;
begin
Original := FMurmurHash3_x86_32;
Original.Initialize;
Original.BufferSize := (64 * 1024); // 64Kb
// Make Copy Of Current State
Copy := Original.Clone();
Copy.BufferSize := (128 * 1024); // 128Kb
CheckNotEquals(Original.BufferSize, Copy.BufferSize,
Format('Expected %d but got %d.', [Original.BufferSize, Copy.BufferSize]));
end;
procedure TTestMurmurHash3_x86_32.TestDefaultData;
begin
FExpectedString := FExpectedHashOfDefaultData;
FActualString := FMurmurHash3_x86_32.ComputeString(FDefaultData,
TEncoding.UTF8).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestMurmurHash3_x86_32.TestIncrementalHash;
begin
FExpectedString := FExpectedHashOfDefaultData;
FHash := THashFactory.THash32.CreateMurmurHash3_x86_32();
FHash.Initialize();
FHash.TransformString(System.Copy(FDefaultData, 1, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 4, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 7, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 10, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 13, 2), TEncoding.UTF8);
FHashResult := FHash.TransformFinal();
FActualString := FHashResult.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestMurmurHash3_x86_32.TestIndexChunkedDataIncrementalHash;
var
Count, i: Int32;
ChunkedDataBytes, temp: TBytes;
begin
ChunkedDataBytes := TConverters.ConvertStringToBytes(FChunkedData,
TEncoding.UTF8);
for i := System.Low(ChunkedDataBytes) to System.High(ChunkedDataBytes) do
begin
Count := System.Length(ChunkedDataBytes) - i;
temp := System.Copy(ChunkedDataBytes, i, Count);
FMurmurHash3_x86_32.Initialize();
FMurmurHash3_x86_32.TransformBytes(ChunkedDataBytes, i, Count);
FActualString := FMurmurHash3_x86_32.TransformFinal().ToString();
FExpectedString := THashFactory.THash32.CreateMurmurHash3_x86_32.
ComputeBytes(temp).ToString();
CheckEquals(FExpectedString, FActualString,
Format('Expected %s but got %s.', [FExpectedString, FActualString]));
end;
end;
procedure TTestMurmurHash3_x86_32.TestRandomString;
begin
FExpectedString := FExpectedHashOfRandomString;
FActualString := FMurmurHash3_x86_32.ComputeString(FRandomStringRecord,
TEncoding.UTF8).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestMurmurHash3_x86_32.TestWithDifferentKeyMaxUInt32DefaultData;
var
LIHashWithKey: IHashWithKey;
begin
FExpectedString := FExpectedHashOfDefaultDataWithMaxUInt32AsKey;
LIHashWithKey := (FMurmurHash3_x86_32 as IHashWithKey);
LIHashWithKey.Key := TConverters.ReadUInt32AsBytesLE(System.High(UInt32));
FActualString := LIHashWithKey.ComputeString(FDefaultData, TEncoding.UTF8)
.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestMurmurHash3_x86_32.TestWithDifferentKeyOneEmptyString;
var
LIHashWithKey: IHashWithKey;
begin
FExpectedString := FExpectedHashOfEmptyDataWithOneAsKey;
LIHashWithKey := (FMurmurHash3_x86_32 as IHashWithKey);
LIHashWithKey.Key := TConverters.ReadUInt32AsBytesLE(UInt32(1));
FActualString := LIHashWithKey.ComputeString(FEmptyData, TEncoding.UTF8)
.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestMurmurHash3_x86_32.TestZerotoFour;
begin
FExpectedString := FExpectedHashOfZerotoFour;
FActualString := FMurmurHash3_x86_32.ComputeString(FZerotoFour,
TEncoding.UTF8).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
{ TTestOneAtTime }
procedure TTestOneAtTime.SetUp;
begin
inherited;
FOneAtTime := THashFactory.THash32.CreateOneAtTime();
end;
procedure TTestOneAtTime.TearDown;
begin
FOneAtTime := Nil;
inherited;
end;
procedure TTestOneAtTime.TestBytesabcde;
var
LBuffer: TBytes;
begin
System.SetLength(LBuffer, System.SizeOf(FBytesabcde));
System.Move(FBytesabcde, Pointer(LBuffer)^, System.SizeOf(FBytesabcde));
FExpectedString := FExpectedHashOfabcde;
FActualString := FOneAtTime.ComputeBytes(LBuffer).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestOneAtTime.TestHashCloneIsCorrect;
var
Original, Copy: IHash;
MainData, ChunkOne, ChunkTwo: TBytes;
Count: Int32;
begin
MainData := TConverters.ConvertStringToBytes(FDefaultData, TEncoding.UTF8);
Count := System.Length(MainData) - 3;
ChunkOne := System.Copy(MainData, 0, Count);
ChunkTwo := System.Copy(MainData, Count, System.Length(MainData) - Count);
Original := FOneAtTime;
Original.Initialize;
Original.TransformBytes(ChunkOne);
// Make Copy Of Current State
Copy := Original.Clone();
Original.TransformBytes(ChunkTwo);
FExpectedString := Original.TransformFinal().ToString();
Copy.TransformBytes(ChunkTwo);
FActualString := Copy.TransformFinal().ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestOneAtTime.TestHashCloneIsUnique;
var
Original, Copy: IHash;
begin
Original := FOneAtTime;
Original.Initialize;
Original.BufferSize := (64 * 1024); // 64Kb
// Make Copy Of Current State
Copy := Original.Clone();
Copy.BufferSize := (128 * 1024); // 128Kb
CheckNotEquals(Original.BufferSize, Copy.BufferSize,
Format('Expected %d but got %d.', [Original.BufferSize, Copy.BufferSize]));
end;
procedure TTestOneAtTime.TestDefaultData;
begin
FExpectedString := FExpectedHashOfDefaultData;
FActualString := FOneAtTime.ComputeString(FDefaultData, TEncoding.UTF8)
.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestOneAtTime.TestEmptyStream;
var
stream: TStream;
begin
stream := TMemoryStream.Create;
try
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FOneAtTime.ComputeStream(stream).ToString();
CheckEquals(FExpectedString, FActualString,
Format('Expected %s but got %s.', [FExpectedString, FActualString]));
finally
stream.Free;
end;
end;
procedure TTestOneAtTime.TestEmptyString;
begin
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FOneAtTime.ComputeString(FEmptyData, TEncoding.UTF8)
.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestOneAtTime.TestIncrementalHash;
begin
FExpectedString := FExpectedHashOfDefaultData;
FHash := THashFactory.THash32.CreateOneAtTime();
FHash.Initialize();
FHash.TransformString(System.Copy(FDefaultData, 1, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 4, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 7, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 10, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 13, 2), TEncoding.UTF8);
FHashResult := FHash.TransformFinal();
FActualString := FHashResult.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestOneAtTime.TestOnetoNine;
begin
FExpectedString := FExpectedHashOfOnetoNine;
FActualString := FOneAtTime.ComputeString(FOnetoNine, TEncoding.UTF8)
.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
{ TTestPJW }
procedure TTestPJW.SetUp;
begin
inherited;
FPJW := THashFactory.THash32.CreatePJW();
end;
procedure TTestPJW.TearDown;
begin
FPJW := Nil;
inherited;
end;
procedure TTestPJW.TestBytesabcde;
var
LBuffer: TBytes;
begin
System.SetLength(LBuffer, System.SizeOf(FBytesabcde));
System.Move(FBytesabcde, Pointer(LBuffer)^, System.SizeOf(FBytesabcde));
FExpectedString := FExpectedHashOfabcde;
FActualString := FPJW.ComputeBytes(LBuffer).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestPJW.TestHashCloneIsCorrect;
var
Original, Copy: IHash;
MainData, ChunkOne, ChunkTwo: TBytes;
Count: Int32;
begin
MainData := TConverters.ConvertStringToBytes(FDefaultData, TEncoding.UTF8);
Count := System.Length(MainData) - 3;
ChunkOne := System.Copy(MainData, 0, Count);
ChunkTwo := System.Copy(MainData, Count, System.Length(MainData) - Count);
Original := FPJW;
Original.Initialize;
Original.TransformBytes(ChunkOne);
// Make Copy Of Current State
Copy := Original.Clone();
Original.TransformBytes(ChunkTwo);
FExpectedString := Original.TransformFinal().ToString();
Copy.TransformBytes(ChunkTwo);
FActualString := Copy.TransformFinal().ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestPJW.TestHashCloneIsUnique;
var
Original, Copy: IHash;
begin
Original := FPJW;
Original.Initialize;
Original.BufferSize := (64 * 1024); // 64Kb
// Make Copy Of Current State
Copy := Original.Clone();
Copy.BufferSize := (128 * 1024); // 128Kb
CheckNotEquals(Original.BufferSize, Copy.BufferSize,
Format('Expected %d but got %d.', [Original.BufferSize, Copy.BufferSize]));
end;
procedure TTestPJW.TestDefaultData;
begin
FExpectedString := FExpectedHashOfDefaultData;
FActualString := FPJW.ComputeString(FDefaultData, TEncoding.UTF8).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestPJW.TestEmptyStream;
var
stream: TStream;
begin
stream := TMemoryStream.Create;
try
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FPJW.ComputeStream(stream).ToString();
CheckEquals(FExpectedString, FActualString,
Format('Expected %s but got %s.', [FExpectedString, FActualString]));
finally
stream.Free;
end;
end;
procedure TTestPJW.TestEmptyString;
begin
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FPJW.ComputeString(FEmptyData, TEncoding.UTF8).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestPJW.TestIncrementalHash;
begin
FExpectedString := FExpectedHashOfDefaultData;
FHash := THashFactory.THash32.CreatePJW();
FHash.Initialize();
FHash.TransformString(System.Copy(FDefaultData, 1, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 4, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 7, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 10, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 13, 2), TEncoding.UTF8);
FHashResult := FHash.TransformFinal();
FActualString := FHashResult.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestPJW.TestOnetoNine;
begin
FExpectedString := FExpectedHashOfOnetoNine;
FActualString := FPJW.ComputeString(FOnetoNine, TEncoding.UTF8).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
{ TTestRotating }
procedure TTestRotating.SetUp;
begin
inherited;
FRotating := THashFactory.THash32.CreateRotating();
end;
procedure TTestRotating.TearDown;
begin
FRotating := Nil;
inherited;
end;
procedure TTestRotating.TestBytesabcde;
var
LBuffer: TBytes;
begin
System.SetLength(LBuffer, System.SizeOf(FBytesabcde));
System.Move(FBytesabcde, Pointer(LBuffer)^, System.SizeOf(FBytesabcde));
FExpectedString := FExpectedHashOfabcde;
FActualString := FRotating.ComputeBytes(LBuffer).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestRotating.TestHashCloneIsCorrect;
var
Original, Copy: IHash;
MainData, ChunkOne, ChunkTwo: TBytes;
Count: Int32;
begin
MainData := TConverters.ConvertStringToBytes(FDefaultData, TEncoding.UTF8);
Count := System.Length(MainData) - 3;
ChunkOne := System.Copy(MainData, 0, Count);
ChunkTwo := System.Copy(MainData, Count, System.Length(MainData) - Count);
Original := FRotating;
Original.Initialize;
Original.TransformBytes(ChunkOne);
// Make Copy Of Current State
Copy := Original.Clone();
Original.TransformBytes(ChunkTwo);
FExpectedString := Original.TransformFinal().ToString();
Copy.TransformBytes(ChunkTwo);
FActualString := Copy.TransformFinal().ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestRotating.TestHashCloneIsUnique;
var
Original, Copy: IHash;
begin
Original := FRotating;
Original.Initialize;
Original.BufferSize := (64 * 1024); // 64Kb
// Make Copy Of Current State
Copy := Original.Clone();
Copy.BufferSize := (128 * 1024); // 128Kb
CheckNotEquals(Original.BufferSize, Copy.BufferSize,
Format('Expected %d but got %d.', [Original.BufferSize, Copy.BufferSize]));
end;
procedure TTestRotating.TestDefaultData;
begin
FExpectedString := FExpectedHashOfDefaultData;
FActualString := FRotating.ComputeString(FDefaultData, TEncoding.UTF8)
.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestRotating.TestEmptyStream;
var
stream: TStream;
begin
stream := TMemoryStream.Create;
try
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FRotating.ComputeStream(stream).ToString();
CheckEquals(FExpectedString, FActualString,
Format('Expected %s but got %s.', [FExpectedString, FActualString]));
finally
stream.Free;
end;
end;
procedure TTestRotating.TestEmptyString;
begin
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FRotating.ComputeString(FEmptyData, TEncoding.UTF8)
.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestRotating.TestIncrementalHash;
begin
FExpectedString := FExpectedHashOfDefaultData;
FHash := THashFactory.THash32.CreateRotating();
FHash.Initialize();
FHash.TransformString(System.Copy(FDefaultData, 1, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 4, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 7, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 10, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 13, 2), TEncoding.UTF8);
FHashResult := FHash.TransformFinal();
FActualString := FHashResult.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestRotating.TestOnetoNine;
begin
FExpectedString := FExpectedHashOfOnetoNine;
FActualString := FRotating.ComputeString(FOnetoNine, TEncoding.UTF8)
.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
{ TTestRS }
procedure TTestRS.SetUp;
begin
inherited;
FRS := THashFactory.THash32.CreateRS();
end;
procedure TTestRS.TearDown;
begin
FRS := Nil;
inherited;
end;
procedure TTestRS.TestBytesabcde;
var
LBuffer: TBytes;
begin
System.SetLength(LBuffer, System.SizeOf(FBytesabcde));
System.Move(FBytesabcde, Pointer(LBuffer)^, System.SizeOf(FBytesabcde));
FExpectedString := FExpectedHashOfabcde;
FActualString := FRS.ComputeBytes(LBuffer).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestRS.TestHashCloneIsCorrect;
var
Original, Copy: IHash;
MainData, ChunkOne, ChunkTwo: TBytes;
Count: Int32;
begin
MainData := TConverters.ConvertStringToBytes(FDefaultData, TEncoding.UTF8);
Count := System.Length(MainData) - 3;
ChunkOne := System.Copy(MainData, 0, Count);
ChunkTwo := System.Copy(MainData, Count, System.Length(MainData) - Count);
Original := FRS;
Original.Initialize;
Original.TransformBytes(ChunkOne);
// Make Copy Of Current State
Copy := Original.Clone();
Original.TransformBytes(ChunkTwo);
FExpectedString := Original.TransformFinal().ToString();
Copy.TransformBytes(ChunkTwo);
FActualString := Copy.TransformFinal().ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestRS.TestHashCloneIsUnique;
var
Original, Copy: IHash;
begin
Original := FRS;
Original.Initialize;
Original.BufferSize := (64 * 1024); // 64Kb
// Make Copy Of Current State
Copy := Original.Clone();
Copy.BufferSize := (128 * 1024); // 128Kb
CheckNotEquals(Original.BufferSize, Copy.BufferSize,
Format('Expected %d but got %d.', [Original.BufferSize, Copy.BufferSize]));
end;
procedure TTestRS.TestDefaultData;
begin
FExpectedString := FExpectedHashOfDefaultData;
FActualString := FRS.ComputeString(FDefaultData, TEncoding.UTF8).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestRS.TestEmptyStream;
var
stream: TStream;
begin
stream := TMemoryStream.Create;
try
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FRS.ComputeStream(stream).ToString();
CheckEquals(FExpectedString, FActualString,
Format('Expected %s but got %s.', [FExpectedString, FActualString]));
finally
stream.Free;
end;
end;
procedure TTestRS.TestEmptyString;
begin
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FRS.ComputeString(FEmptyData, TEncoding.UTF8).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestRS.TestIncrementalHash;
begin
FExpectedString := FExpectedHashOfDefaultData;
FHash := THashFactory.THash32.CreateRS();
FHash.Initialize();
FHash.TransformString(System.Copy(FDefaultData, 1, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 4, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 7, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 10, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 13, 2), TEncoding.UTF8);
FHashResult := FHash.TransformFinal();
FActualString := FHashResult.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestRS.TestOnetoNine;
begin
FExpectedString := FExpectedHashOfOnetoNine;
FActualString := FRS.ComputeString(FOnetoNine, TEncoding.UTF8).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
{ TTestSDBM }
procedure TTestSDBM.SetUp;
begin
inherited;
FSDBM := THashFactory.THash32.CreateSDBM();
end;
procedure TTestSDBM.TearDown;
begin
FSDBM := Nil;
inherited;
end;
procedure TTestSDBM.TestBytesabcde;
var
LBuffer: TBytes;
begin
System.SetLength(LBuffer, System.SizeOf(FBytesabcde));
System.Move(FBytesabcde, Pointer(LBuffer)^, System.SizeOf(FBytesabcde));
FExpectedString := FExpectedHashOfabcde;
FActualString := FSDBM.ComputeBytes(LBuffer).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestSDBM.TestHashCloneIsCorrect;
var
Original, Copy: IHash;
MainData, ChunkOne, ChunkTwo: TBytes;
Count: Int32;
begin
MainData := TConverters.ConvertStringToBytes(FDefaultData, TEncoding.UTF8);
Count := System.Length(MainData) - 3;
ChunkOne := System.Copy(MainData, 0, Count);
ChunkTwo := System.Copy(MainData, Count, System.Length(MainData) - Count);
Original := FSDBM;
Original.Initialize;
Original.TransformBytes(ChunkOne);
// Make Copy Of Current State
Copy := Original.Clone();
Original.TransformBytes(ChunkTwo);
FExpectedString := Original.TransformFinal().ToString();
Copy.TransformBytes(ChunkTwo);
FActualString := Copy.TransformFinal().ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestSDBM.TestHashCloneIsUnique;
var
Original, Copy: IHash;
begin
Original := FSDBM;
Original.Initialize;
Original.BufferSize := (64 * 1024); // 64Kb
// Make Copy Of Current State
Copy := Original.Clone();
Copy.BufferSize := (128 * 1024); // 128Kb
CheckNotEquals(Original.BufferSize, Copy.BufferSize,
Format('Expected %d but got %d.', [Original.BufferSize, Copy.BufferSize]));
end;
procedure TTestSDBM.TestDefaultData;
begin
FExpectedString := FExpectedHashOfDefaultData;
FActualString := FSDBM.ComputeString(FDefaultData, TEncoding.UTF8).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestSDBM.TestEmptyStream;
var
stream: TStream;
begin
stream := TMemoryStream.Create;
try
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FSDBM.ComputeStream(stream).ToString();
CheckEquals(FExpectedString, FActualString,
Format('Expected %s but got %s.', [FExpectedString, FActualString]));
finally
stream.Free;
end;
end;
procedure TTestSDBM.TestEmptyString;
begin
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FSDBM.ComputeString(FEmptyData, TEncoding.UTF8).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestSDBM.TestIncrementalHash;
begin
FExpectedString := FExpectedHashOfDefaultData;
FHash := THashFactory.THash32.CreateSDBM();
FHash.Initialize();
FHash.TransformString(System.Copy(FDefaultData, 1, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 4, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 7, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 10, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 13, 2), TEncoding.UTF8);
FHashResult := FHash.TransformFinal();
FActualString := FHashResult.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestSDBM.TestOnetoNine;
begin
FExpectedString := FExpectedHashOfOnetoNine;
FActualString := FSDBM.ComputeString(FOnetoNine, TEncoding.UTF8).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
{ TTestShiftAndXor }
procedure TTestShiftAndXor.SetUp;
begin
inherited;
FShiftAndXor := THashFactory.THash32.CreateShiftAndXor();
end;
procedure TTestShiftAndXor.TearDown;
begin
FShiftAndXor := Nil;
inherited;
end;
procedure TTestShiftAndXor.TestBytesabcde;
var
LBuffer: TBytes;
begin
System.SetLength(LBuffer, System.SizeOf(FBytesabcde));
System.Move(FBytesabcde, Pointer(LBuffer)^, System.SizeOf(FBytesabcde));
FExpectedString := FExpectedHashOfabcde;
FActualString := FShiftAndXor.ComputeBytes(LBuffer).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestShiftAndXor.TestHashCloneIsCorrect;
var
Original, Copy: IHash;
MainData, ChunkOne, ChunkTwo: TBytes;
Count: Int32;
begin
MainData := TConverters.ConvertStringToBytes(FDefaultData, TEncoding.UTF8);
Count := System.Length(MainData) - 3;
ChunkOne := System.Copy(MainData, 0, Count);
ChunkTwo := System.Copy(MainData, Count, System.Length(MainData) - Count);
Original := FShiftAndXor;
Original.Initialize;
Original.TransformBytes(ChunkOne);
// Make Copy Of Current State
Copy := Original.Clone();
Original.TransformBytes(ChunkTwo);
FExpectedString := Original.TransformFinal().ToString();
Copy.TransformBytes(ChunkTwo);
FActualString := Copy.TransformFinal().ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestShiftAndXor.TestHashCloneIsUnique;
var
Original, Copy: IHash;
begin
Original := FShiftAndXor;
Original.Initialize;
Original.BufferSize := (64 * 1024); // 64Kb
// Make Copy Of Current State
Copy := Original.Clone();
Copy.BufferSize := (128 * 1024); // 128Kb
CheckNotEquals(Original.BufferSize, Copy.BufferSize,
Format('Expected %d but got %d.', [Original.BufferSize, Copy.BufferSize]));
end;
procedure TTestShiftAndXor.TestDefaultData;
begin
FExpectedString := FExpectedHashOfDefaultData;
FActualString := FShiftAndXor.ComputeString(FDefaultData, TEncoding.UTF8)
.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestShiftAndXor.TestEmptyStream;
var
stream: TStream;
begin
stream := TMemoryStream.Create;
try
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FShiftAndXor.ComputeStream(stream).ToString();
CheckEquals(FExpectedString, FActualString,
Format('Expected %s but got %s.', [FExpectedString, FActualString]));
finally
stream.Free;
end;
end;
procedure TTestShiftAndXor.TestEmptyString;
begin
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FShiftAndXor.ComputeString(FEmptyData, TEncoding.UTF8)
.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestShiftAndXor.TestIncrementalHash;
begin
FExpectedString := FExpectedHashOfDefaultData;
FHash := THashFactory.THash32.CreateShiftAndXor();
FHash.Initialize();
FHash.TransformString(System.Copy(FDefaultData, 1, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 4, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 7, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 10, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 13, 2), TEncoding.UTF8);
FHashResult := FHash.TransformFinal();
FActualString := FHashResult.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestShiftAndXor.TestOnetoNine;
begin
FExpectedString := FExpectedHashOfOnetoNine;
FActualString := FShiftAndXor.ComputeString(FOnetoNine, TEncoding.UTF8)
.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
{ TTestSuperFast }
procedure TTestSuperFast.SetUp;
begin
inherited;
FSuperFast := THashFactory.THash32.CreateSuperFast();
end;
procedure TTestSuperFast.TearDown;
begin
FSuperFast := Nil;
inherited;
end;
procedure TTestSuperFast.TestBytesabcde;
var
LBuffer: TBytes;
begin
System.SetLength(LBuffer, System.SizeOf(FBytesabcde));
System.Move(FBytesabcde, Pointer(LBuffer)^, System.SizeOf(FBytesabcde));
FExpectedString := FExpectedHashOfabcde;
FActualString := FSuperFast.ComputeBytes(LBuffer).ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestSuperFast.TestHashCloneIsCorrect;
var
Original, Copy: IHash;
MainData, ChunkOne, ChunkTwo: TBytes;
Count: Int32;
begin
MainData := TConverters.ConvertStringToBytes(FDefaultData, TEncoding.UTF8);
Count := System.Length(MainData) - 3;
ChunkOne := System.Copy(MainData, 0, Count);
ChunkTwo := System.Copy(MainData, Count, System.Length(MainData) - Count);
Original := FSuperFast;
Original.Initialize;
Original.TransformBytes(ChunkOne);
// Make Copy Of Current State
Copy := Original.Clone();
Original.TransformBytes(ChunkTwo);
FExpectedString := Original.TransformFinal().ToString();
Copy.TransformBytes(ChunkTwo);
FActualString := Copy.TransformFinal().ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestSuperFast.TestHashCloneIsUnique;
var
Original, Copy: IHash;
begin
Original := FSuperFast;
Original.Initialize;
Original.BufferSize := (64 * 1024); // 64Kb
// Make Copy Of Current State
Copy := Original.Clone();
Copy.BufferSize := (128 * 1024); // 128Kb
CheckNotEquals(Original.BufferSize, Copy.BufferSize,
Format('Expected %d but got %d.', [Original.BufferSize, Copy.BufferSize]));
end;
procedure TTestSuperFast.TestDefaultData;
begin
FExpectedString := FExpectedHashOfDefaultData;
FActualString := FSuperFast.ComputeString(FDefaultData, TEncoding.UTF8)
.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestSuperFast.TestEmptyStream;
var
stream: TStream;
begin
stream := TMemoryStream.Create;
try
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FSuperFast.ComputeStream(stream).ToString();
CheckEquals(FExpectedString, FActualString,
Format('Expected %s but got %s.', [FExpectedString, FActualString]));
finally
stream.Free;
end;
end;
procedure TTestSuperFast.TestEmptyString;
begin
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FSuperFast.ComputeString(FEmptyData, TEncoding.UTF8)
.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestSuperFast.TestIncrementalHash;
begin
FExpectedString := FExpectedHashOfDefaultData;
FHash := THashFactory.THash32.CreateSuperFast();
FHash.Initialize();
FHash.TransformString(System.Copy(FDefaultData, 1, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 4, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 7, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 10, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 13, 2), TEncoding.UTF8);
FHashResult := FHash.TransformFinal();
FActualString := FHashResult.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestSuperFast.TestOnetoNine;
begin
FExpectedString := FExpectedHashOfOnetoNine;
FActualString := FSuperFast.ComputeString(FOnetoNine, TEncoding.UTF8)
.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
{ TTestXXHash32 }
procedure TTestXXHash32.SetUp;
begin
inherited;
FXXHash32 := THashFactory.THash32.CreateXXHash32();
end;
procedure TTestXXHash32.TearDown;
begin
FXXHash32 := Nil;
inherited;
end;
procedure TTestXXHash32.TestEmptyStream;
var
stream: TStream;
begin
stream := TMemoryStream.Create;
try
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FXXHash32.ComputeStream(stream).ToString();
CheckEquals(FExpectedString, FActualString,
Format('Expected %s but got %s.', [FExpectedString, FActualString]));
finally
stream.Free;
end;
end;
procedure TTestXXHash32.TestEmptyString;
begin
FExpectedString := FExpectedHashOfEmptyData;
FActualString := FXXHash32.ComputeString(FEmptyData, TEncoding.UTF8)
.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestXXHash32.TestAnotherChunkedDataIncrementalHash;
var
x, size, i: Int32;
temp: string;
begin
for x := 0 to System.Pred(System.SizeOf(Fc_chunkSize)
div System.SizeOf(Int32)) do
begin
size := Fc_chunkSize[x];
FXXHash32.Initialize();
i := size;
while i < System.Length(FChunkedData) do
begin
temp := System.Copy(FChunkedData, (i - size) + 1, size);
FXXHash32.TransformString(temp, TEncoding.UTF8);
System.Inc(i, size);
end;
temp := System.Copy(FChunkedData, (i - size) + 1,
System.Length(FChunkedData) - ((i - size)));
FXXHash32.TransformString(temp, TEncoding.UTF8);
FActualString := FXXHash32.TransformFinal().ToString();
FExpectedString := THashFactory.THash32.CreateXXHash32.ComputeString
(FChunkedData, TEncoding.UTF8).ToString();
CheckEquals(FExpectedString, FActualString,
Format('Expected %s but got %s.', [FExpectedString, FActualString]));
end;
end;
procedure TTestXXHash32.TestHashCloneIsCorrect;
var
Original, Copy: IHash;
MainData, ChunkOne, ChunkTwo: TBytes;
Count: Int32;
begin
MainData := TConverters.ConvertStringToBytes(FDefaultData, TEncoding.UTF8);
Count := System.Length(MainData) - 3;
ChunkOne := System.Copy(MainData, 0, Count);
ChunkTwo := System.Copy(MainData, Count, System.Length(MainData) - Count);
Original := FXXHash32;
Original.Initialize;
Original.TransformBytes(ChunkOne);
// Make Copy Of Current State
Copy := Original.Clone();
Original.TransformBytes(ChunkTwo);
FExpectedString := Original.TransformFinal().ToString();
Copy.TransformBytes(ChunkTwo);
FActualString := Copy.TransformFinal().ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestXXHash32.TestHashCloneIsUnique;
var
Original, Copy: IHash;
begin
Original := FXXHash32;
Original.Initialize;
Original.BufferSize := (64 * 1024); // 64Kb
// Make Copy Of Current State
Copy := Original.Clone();
Copy.BufferSize := (128 * 1024); // 128Kb
CheckNotEquals(Original.BufferSize, Copy.BufferSize,
Format('Expected %d but got %d.', [Original.BufferSize, Copy.BufferSize]));
end;
procedure TTestXXHash32.TestDefaultData;
begin
FExpectedString := FExpectedHashOfDefaultData;
FActualString := FXXHash32.ComputeString(FDefaultData, TEncoding.UTF8)
.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestXXHash32.TestIncrementalHash;
begin
FExpectedString := FExpectedHashOfDefaultData;
FHash := THashFactory.THash32.CreateXXHash32();
FHash.Initialize();
FHash.TransformString(System.Copy(FDefaultData, 1, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 4, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 7, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 10, 3), TEncoding.UTF8);
FHash.TransformString(System.Copy(FDefaultData, 13, 2), TEncoding.UTF8);
FHashResult := FHash.TransformFinal();
FActualString := FHashResult.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestXXHash32.TestRandomString;
begin
FExpectedString := FExpectedHashOfRandomString;
FActualString := FXXHash32.ComputeString(FRandomStringTobacco, TEncoding.UTF8)
.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestXXHash32.TestWithDifferentKeyMaxUInt32DefaultData;
var
LIHashWithKey: IHashWithKey;
begin
FExpectedString := FExpectedHashOfDefaultDataWithMaxUInt32AsKey;
LIHashWithKey := (FXXHash32 as IHashWithKey);
LIHashWithKey.Key := TConverters.ReadUInt32AsBytesLE(System.High(UInt32));
FActualString := LIHashWithKey.ComputeString(FDefaultData, TEncoding.UTF8)
.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestXXHash32.TestWithDifferentKeyOneEmptyString;
var
LIHashWithKey: IHashWithKey;
begin
FExpectedString := FExpectedHashOfEmptyDataWithOneAsKey;
LIHashWithKey := (FXXHash32 as IHashWithKey);
LIHashWithKey.Key := TConverters.ReadUInt32AsBytesLE(UInt32(1));
FActualString := LIHashWithKey.ComputeString(FEmptyData, TEncoding.UTF8)
.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
procedure TTestXXHash32.TestZerotoFour;
begin
FExpectedString := FExpectedHashOfZerotoFour;
FActualString := FXXHash32.ComputeString(FZerotoFour, TEncoding.UTF8)
.ToString();
CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.',
[FExpectedString, FActualString]));
end;
initialization
// Register any test cases with the test runner
{$IFDEF FPC}
// Hash32
RegisterTest(TTestAP);
RegisterTest(TTestBernstein);
RegisterTest(TTestBernstein1);
RegisterTest(TTestBKDR);
RegisterTest(TTestDEK);
RegisterTest(TTestDJB);
RegisterTest(TTestELF);
RegisterTest(TTestFNV);
RegisterTest(TTestFNV1a);
RegisterTest(TTestJenkins3);
RegisterTest(TTestJS);
RegisterTest(TTestMurmur2);
RegisterTest(TTestMurmurHash3_x86_32);
RegisterTest(TTestOneAtTime);
RegisterTest(TTestPJW);
RegisterTest(TTestRotating);
RegisterTest(TTestRS);
RegisterTest(TTestSDBM);
RegisterTest(TTestShiftAndXor);
RegisterTest(TTestSuperFast);
RegisterTest(TTestXXHash32);
{$ELSE}
// Hash32
RegisterTest(TTestAP.Suite);
RegisterTest(TTestBernstein.Suite);
RegisterTest(TTestBernstein1.Suite);
RegisterTest(TTestBKDR.Suite);
RegisterTest(TTestDEK.Suite);
RegisterTest(TTestDJB.Suite);
RegisterTest(TTestELF.Suite);
RegisterTest(TTestFNV.Suite);
RegisterTest(TTestFNV1a.Suite);
RegisterTest(TTestJenkins3.Suite);
RegisterTest(TTestJS.Suite);
RegisterTest(TTestMurmur2.Suite);
RegisterTest(TTestMurmurHash3_x86_32.Suite);
RegisterTest(TTestOneAtTime.Suite);
RegisterTest(TTestPJW.Suite);
RegisterTest(TTestRotating.Suite);
RegisterTest(TTestRS.Suite);
RegisterTest(TTestSDBM.Suite);
RegisterTest(TTestShiftAndXor.Suite);
RegisterTest(TTestSuperFast.Suite);
RegisterTest(TTestXXHash32.Suite);
{$ENDIF FPC}
end.
|
{################################################}
{# Program func #}
{# | | _ |V| _|\| _ __ _ _ #}
{# |__|_||<(/_ | |(_| |(/_|||(/_(/_ #}
{# 2015 #}
{################################################}
{# Ukázka použití funkcí v programu #}
{################################################}
program func;
uses crt;
Function sayHello() : Integer;
begin
writeln('hello');
sayHello := 0;
end;
Function average( x : Integer; y : Integer) : Real;
var
sum : Integer;
begin
sum := x + y;
average := sum / 2;
end;
Function test (var value: Integer) : Integer;
begin
writeln('2 - ',value);
value := value+1;
writeln('3 - ',value);
end;
Function test2 ( value : Integer) : Integer;
begin
writeln('2 - ',value);
value := value+1;
writeln('3 - ',value);
end;
Function swap (var x: Integer; var y: Integer): Integer;
begin
x := x + y;
y := x - y;
x := x - y;
end;
//globální var
var
myValue, a, b : Integer;
begin
sayHello;
myValue := 1;
writeln('1 - ',myValue);
test(myValue);
writeln('4 - ',myValue);
myValue := 1;
writeln('1 - ',myValue);
test2(myValue);
writeln('4 - ',myValue);
a := 1;
b := 3;
writeln( a, ' ', b);
swap( a, b);
writeln( a, ' ', b);
readln;
end.
|
//---------------------------------------------------------------------------
// This software is Copyright (c) 2012 Embarcadero Technologies, Inc.
// You may only use this software if you are an authorized licensee
// of Delphi, C++Builder or RAD Studio (Embarcadero Products).
// This software is considered a Redistributable as defined under
// the software license agreement that comes with the Embarcadero Products
// and is subject to that software license agreement.
//---------------------------------------------------------------------------
unit CaptureForm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.Objects, FMX.Media, FMX.StdCtrls,
FMX.Layouts, FMX.ListBox;
type
TForm240 = class(TForm)
Image1: TImage;
CaptureButton: TSpeedButton;
Layout1: TLayout;
SaveDialog1: TSaveDialog;
Ellipse1: TEllipse;
StopButton: TSpeedButton;
procedure FormCreate(Sender: TObject);
procedure CaptureButtonClick(Sender: TObject);
procedure StopButtonClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
VideoCamera: TVideoCaptureDevice;
procedure SampleBufferReady(Sender: TObject; const ATime: TMediaTime);
end;
var
Form240: TForm240;
implementation
{$R *.fmx}
procedure TForm240.FormCreate(Sender: TObject);
begin
VideoCamera := TCaptureDeviceManager.Current.DefaultVideoCaptureDevice;
if VideoCamera <> nil then
begin
Ellipse1.AnimateFloat('Opacity', 1, 1.0);
VideoCamera.OnSampleBufferReady := SampleBufferReady;
VideoCamera.StartCapture;
end
else
begin
CaptureButton.Enabled := False;
Caption := 'Video capture devices not available.';
end;
end;
procedure TForm240.FormDestroy(Sender: TObject);
begin
if VideoCamera <> nil then
VideoCamera.StopCapture;
end;
procedure TForm240.SampleBufferReady(Sender: TObject; const ATime: TMediaTime);
begin
VideoCamera.SampleBufferToBitmap(Image1.Bitmap, True);
end;
procedure TForm240.StopButtonClick(Sender: TObject);
begin
if VideoCamera <> nil then
begin
if VideoCamera.State = TCaptureDeviceState.Capturing then
begin
Ellipse1.AnimateFloat('Opacity', 0, 1.0);
StopButton.Text := 'Capture';
VideoCamera.StopCapture;
end
else
begin
Ellipse1.AnimateFloat('Opacity', 1, 1.0);
StopButton.Text := 'Stop';
VideoCamera.StartCapture
end;
end;
end;
procedure TForm240.CaptureButtonClick(Sender: TObject);
begin
if SaveDialog1.Execute then
Image1.Bitmap.SaveToFile(SaveDialog1.FileName);
end;
end.
|
unit EditBone.Dialog.ChangedFiles;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BCCommon.Dialog.Base, Vcl.StdCtrls, Vcl.ExtCtrls, sPanel, BCControl.Panel,
VirtualTrees, sSkinProvider;
type
PChangedFilesTreeData = ^TChangedFilesTreeData;
TChangedFilesTreeData = record
Index: Integer;
FileName: string;
Path: string;
end;
TChangedFilesDialog = class(TBCBaseDialog)
PanelButtons: TBCPanel;
ButtonFind: TButton;
ButtonCancel: TButton;
VirtualDrawTree: TVirtualDrawTree;
procedure VirtualDrawTreeDrawNode(Sender: TBaseVirtualTree; const PaintInfo: TVTPaintInfo);
procedure VirtualDrawTreeInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode;
var InitialStates: TVirtualNodeInitStates);
procedure VirtualDrawTreeGetNodeWidth(Sender: TBaseVirtualTree; HintCanvas: TCanvas; Node: PVirtualNode;
Column: TColumnIndex; var NodeWidth: Integer);
procedure VirtualDrawTreeFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode);
private
{ Private declarations }
procedure SetDrawTreeData(AFileNames: TStrings);
public
function Execute(AFileNames: TStrings): Boolean;
end;
implementation
{$R *.dfm}
uses
System.Math, System.Types;
function TChangedFilesDialog.Execute(AFileNames: TStrings): Boolean;
begin
VirtualDrawTree.NodeDataSize := SizeOf(TChangedFilesTreeData);
SetDrawTreeData(AFileNames);
Result := ShowModal = mrOk;
end;
procedure TChangedFilesDialog.SetDrawTreeData(AFileNames: TStrings);
var
LIndex: Integer;
LNode: PVirtualNode;
LData: PChangedFilesTreeData;
begin
VirtualDrawTree.BeginUpdate;
VirtualDrawTree.Clear;
VirtualDrawTree.DefaultNodeHeight := Max(Canvas.TextHeight('Tg'), 18);
for LIndex := 0 to AFileNames.Count - 1 do
begin
LNode := VirtualDrawTree.AddChild(nil);
LData := VirtualDrawTree.GetNodeData(LNode);
LData^.Index := Integer(AFileNames.Objects[LIndex]);
LData^.FileName := ExtractFileName(AFileNames[LIndex]);
LData^.Path := ExtractFilePath(AFileNames[LIndex]);
end;
LNode := VirtualDrawTree.GetFirst;
if Assigned(LNode) then
VirtualDrawTree.Selected[LNode] := True;
VirtualDrawTree.EndUpdate;
end;
procedure TChangedFilesDialog.VirtualDrawTreeDrawNode(Sender: TBaseVirtualTree; const PaintInfo: TVTPaintInfo);
var
LText: string;
LData: PChangedFilesTreeData;
LFormat: Cardinal;
LRect: TRect;
begin
with Sender as TVirtualDrawTree, PaintInfo do
begin
LData := Sender.GetNodeData(Node);
if not Assigned(LData) then
Exit;
if Assigned(SkinProvider.SkinData) and Assigned(SkinProvider.SkinData.SkinManager) then
Canvas.Font.Color := SkinProvider.SkinData.SkinManager.GetActiveEditFontColor
else
Canvas.Font.Color := clWindowText;
if vsSelected in PaintInfo.Node.States then
begin
if Assigned(SkinProvider.SkinData) and Assigned(SkinProvider.SkinData.SkinManager) then
Canvas.Font.Color := SkinProvider.SkinData.SkinManager.GetHighLightFontColor
else
Canvas.Font.Color := clHighlightText;
end;
SetBKMode(Canvas.Handle, TRANSPARENT);
if Column = 0 then
LText := LData^.FileName
else
LText := LData^.Path;
LRect := ContentRect;
if Length(LText) > 0 then
begin
LFormat := DT_TOP or DT_LEFT or DT_VCENTER or DT_SINGLELINE;
DrawText(Canvas.Handle, LText, Length(LText), LRect, LFormat)
end;
end;
end;
procedure TChangedFilesDialog.VirtualDrawTreeFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode);
var
LData: PChangedFilesTreeData;
begin
LData := VirtualDrawTree.GetNodeData(Node);
Finalize(LData^);
inherited;
end;
procedure TChangedFilesDialog.VirtualDrawTreeGetNodeWidth(Sender: TBaseVirtualTree; HintCanvas: TCanvas;
Node: PVirtualNode; Column: TColumnIndex; var NodeWidth: Integer);
var
LData: PChangedFilesTreeData;
LText: string;
begin
with Sender as TVirtualDrawTree do
begin
LData := Sender.GetNodeData(Node);
if Column = 0 then
LText := LData^.FileName
else
LText := LData^.Path;
if Assigned(LData) then
NodeWidth := Canvas.TextWidth(LText);
end;
end;
procedure TChangedFilesDialog.VirtualDrawTreeInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode;
var InitialStates: TVirtualNodeInitStates);
begin
with Sender do
begin
CheckType[Node] := ctCheckBox;
CheckState[Node] := csCheckedNormal;
end
end;
end. |
program poignore;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes, SysUtils, mpofiles, futils;
var
SourcePo, RemovePo, OutPo: TPoFile;
fname: string;
i, first: integer;
begin
writeln;
if (paramcount < 2) or (paramcount > 3) then begin
writeln('Removes from a source .po file all entries with a reference found in a remove .po file');
writeln;
writeln('usage:');
writeln(Format(' %s source[.po] remove[.po] [output[.po]]', [appName]));
end
else begin
OutPo := nil;
RemovePo := nil;
SourcePo := TPoFile.Create(ParamFilename(1));
RemovePo := TPoFile.Create(ParamFilename(2));
OutPo := TPoFile.Create('');
try
SourcePo.WriteStatistics('Source');
RemovePo.WriteStatistics('Remove');
if SourcePo.HasHeader then begin
OutPo.Insert(OutPo.count).Assign(SourcePo[0]);
first := 1
end
else
first := 0;
for i := first to SourcePo.count-1 do begin
if (RemovePo.IndexOfReference(SourcePo[i].Reference) < 0) then
OutPo.Insert(OutPo.count).Assign(SourcePo[i]);
end;
if paramcount > 2 then
fname := ParamFilename(3)
else
fname := SourcePo.filename;
if not SaveToBackup(fname) then
fname := UniqueFilename(fname);
OutPo.SaveToFile(fname);
OutPo.WriteStatistics('Output', fname);
finally
SourcePo.free;
RemovePo.free;
OutPo.free;
end;
end;
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ }
{ Copyright (c) 1996-2001 Borland Software Corporation }
{ }
{ Русификация: 1998-2001 Polaris Software }
{ http://polesoft.da.ru }
{*******************************************************}
unit ComStrs;
interface
resourcestring
{$IFNDEF VER100}
sTabFailClear = 'Не удалось очистить tab control';
sTabFailDelete = 'Не удалось удалить страницу (tab) с индексом %d';
sTabFailRetrieve = 'Не удалось восстановить страницу (tab) с индексом %d';
sTabFailGetObject = 'Не удалось получить объект с индексом %d';
sTabFailSet = 'Не удалось установить страницу (tab) "%s" с индексом %d';
sTabFailSetObject = 'Не удалось установить объект с индексом %d';
sTabMustBeMultiLine = 'MultiLine должно быть True, когда TabPosition равно tpLeft или tpRight';
{$ELSE}
sTabAccessError = 'Ошибка доступа к tab control';
{$ENDIF}
sInvalidLevel = 'Присваивание неверного уровня элемента';
sInvalidLevelEx = 'Неверный уровень (%d) для элемента "%s"';
sInvalidIndex = 'Неверный индекс';
sInsertError = 'Невозможно вставить элемент';
sInvalidOwner = 'Неверный владелец';
sUnableToCreateColumn = 'Невозможно создать новый столбец';
sUnableToCreateItem = 'Невозможно создать новый элемент';
sRichEditInsertError = 'Ошибка вставки строки в RichEdit';
sRichEditLoadFail = 'Сбой при Load Stream';
sRichEditSaveFail = 'Сбой при Save Stream';
sTooManyPanels = 'StatusBar не может иметь более 64 панелей';
sHKError = 'Ошибка назначения Hot-Key на %s. %s';
sHKInvalid = 'Неверный Hot-Key';
sHKInvalidWindow = 'Неверное или дочернее окно';
sHKAssigned = 'Hot-Key назначен на другое окно';
sUDAssociated = '%s уже связан с %s';
sPageIndexError = 'Неверное значение PageIndex (%d). PageIndex должен быть ' +
'между 0 и %d';
sInvalidComCtl32 = 'Этот компонент требует COMCTL32.DLL версии 4.70 или выше';
sDateTimeMax = 'Дата превысила максимум %s';
sDateTimeMin = 'Дата меньше, чем минимум %s';
sNeedAllowNone = 'Требуется режим ShowCheckbox для установки этой даты';
{$IFNDEF VER100}
sFailSetCalDateTime = 'Ошибка при установке даты или времени в календаре';
sFailSetCalMaxSelRange = 'Ошибка при установке максимального диапазона выбора';
sFailSetCalMinMaxRange = 'Ошибка при установке мин/макс диапазона календаря';
sCalRangeNeedsMultiSelect = 'Диапазон дат может использоваться только в режиме мультивыбора';
sFailsetCalSelRange = 'Ошибка при установке выбранного диапазона календаря';
{$ENDIF}
implementation
end.
|
unit htAjaxPanel;
interface
uses
Windows, SysUtils, Types, Classes, Controls, Graphics,
htInterfaces, htTag, htMarkup, htControls, htPanel;
type
IhtAjaxControl = interface
['{F5E67CB7-D1B1-44A7-A709-37F66146B2D2}']
procedure GenerateTag(inTag: ThtTag; inMarkup: ThtMarkup);
end;
//
ThtAjaxPanel = class(ThtCustomPanel, IhtAjaxControl)
public
procedure Generate(const inContainer: string;
inMarkup: ThtMarkup); override;
procedure GenerateTag(inTag: ThtTag; inMarkup: ThtMarkup);
published
property Align;
property Outline;
property Style;
property Transparent;
property Visible;
end;
function AlignToAjaxAlign(inAlign: TAlign): string;
procedure AjaxGenerateChildren(inOwner: TWinControl; inParent: ThtTag;
inMarkup: ThtMarkup);
implementation
uses
LrVclUtils, LrControlIterator, htPaint;
function AlignToAjaxAlign(inAlign: TAlign): string;
const
cAjaxAligns: array[TAlign] of string = ( '', 'top', 'bottom', 'left',
'right', 'client', 'custom' );
begin
Result := cAjaxAligns[inAlign];
end;
procedure AjaxGenerateCtrlTag(inParent: ThtTag;
inCtrl: TControl; inMarkup: ThtMarkup);
var
c: IhtAjaxControl;
begin
if LrIsAs(inCtrl, IhtAjaxControl, c) then
c.GenerateTag(inParent.Add, inMarkup);
end;
procedure AjaxGenerateChildren(inOwner: TWinControl; inParent: ThtTag;
inMarkup: ThtMarkup);
begin
with TLrCtrlIterator.Create(inOwner) do
try
while Next do
AjaxGenerateCtrlTag(inParent, Ctrl, inMarkup);
finally
Free;
end;
end;
procedure AjaxStylize(inControl: TControl; inStyleBase: string;
inMarkup: ThtMarkup);
var
s: string;
begin
case inControl.Align of
alLeft, alRight: s := Format(' width: %dpx;', [ inControl.ClientWidth ]);
alTop, alBottom: s := Format(' height: %dpx;', [ inControl.ClientHeight ]);
else s := '';
end;
s := inStyleBase + s;
if (s <> '') then
inMarkup.Styles.Add(Format('#%s { %s }', [ inControl.Name, s ]));
end;
{ ThtAjaxPanel }
procedure ThtAjaxPanel.Generate(const inContainer: string;
inMarkup: ThtMarkup);
var
tag: ThtTag;
begin
tag := ThtTag.Create;
try
GenerateTag(tag, inMarkup);
inMarkup.Add(tag.HTML);
finally
tag.Free;
end;
end;
procedure ThtAjaxPanel.GenerateTag(inTag: ThtTag; inMarkup: ThtMarkup);
var
s: string;
begin
inTag.Element := 'div';
inTag.Attributes['turboAlign'] := AlignToAjaxAlign(Align);
inTag.Attributes['id'] := Name;
s := Style.InlineAttribute;
case Align of
alLeft, alRight: s := s + Format(' width: %dpx;', [ ClientWidth ]);
alTop, alBottom: s := s + Format(' height: %dpx;', [ ClientHeight ]);
end;
if (s <> '') then
inMarkup.Styles.Add(Format('#%s { %s }', [ Name, s ]));
AjaxGenerateChildren(Self, inTag, inMarkup);
end;
end.
|
// Copyright (c) 2009, ConTEXT Project Ltd
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// 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.
// Neither the name of ConTEXT Project Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
// 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 fHTMLTidyProfile;
interface
{$I ConTEXT.inc}
{$IFDEF SUPPORTS_HTML_TIDY}
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, TidyLib, TidyGlobal, uHTMLTidy, ComCtrls, StdCtrls, TidyEnums,
uCommon;
type
TfmHTMLTidyProfile = class(TForm)
pcProfile: TPageControl;
pgMarkup: TTabSheet;
pgPrettyPrint: TTabSheet;
pgDiagnostics: TTabSheet;
pgEncoding: TTabSheet;
eAltText: TEdit;
eDoctype: TEdit;
eBlockTags: TEdit;
eEmptyTags: TEdit;
eInlineTags: TEdit;
ePreTags: TEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
cbBreakBeforeBR: TCheckBox;
cbDropEmptyParas: TCheckBox;
cbDropFontTags: TCheckBox;
cbDropPropAttrs: TCheckBox;
cbEncloseBlockText: TCheckBox;
cbEncloseBodyText: TCheckBox;
cbFixComments: TCheckBox;
cbFixUri: TCheckBox;
cbHideComments: TCheckBox;
cbHideEndTags: TCheckBox;
cbJoinClasses: TCheckBox;
cbJoinStyles: TCheckBox;
cbLogicalEmphasis: TCheckBox;
cbLowerLiterals: TCheckBox;
cbMakeBare: TCheckBox;
cbMakeClean: TCheckBox;
cbNcr: TCheckBox;
cbNumEntities: TCheckBox;
cbQuoteAmpersand: TCheckBox;
cbQuoteMarks: TCheckBox;
cbQuoteNbsp: TCheckBox;
cbReplaceColor: TCheckBox;
cbBodyOnly: TCheckBox;
cbUpperCaseAttrs: TCheckBox;
cbUpperCaseTags: TCheckBox;
cbWord2000: TCheckBox;
Label7: TLabel;
cbDuplicateAttrs: TComboBox;
pgXMLMarkup: TTabSheet;
cbXmlDecl: TCheckBox;
cbXmlPIs: TCheckBox;
cbXmlSpace: TCheckBox;
cbXmlTags: TCheckBox;
cbEscapeCdata: TCheckBox;
cbIndentCdata: TCheckBox;
Label8: TLabel;
Label9: TLabel;
Label10: TLabel;
Label11: TLabel;
eIndentSpaces: TEdit;
eTabSize: TEdit;
eWrapLen: TEdit;
cbIndentContent: TComboBox;
cbIndentAttributes: TCheckBox;
cbLiteralAttribs: TCheckBox;
cbShowMarkup: TCheckBox;
cbWrapAsp: TCheckBox;
cbWrapAttVals: TCheckBox;
cbWrapJste: TCheckBox;
cbWrapPhp: TCheckBox;
cbWrapScriptlets: TCheckBox;
cbWrapSection: TCheckBox;
cbFixBackslash: TCheckBox;
btnOK: TButton;
btnCancel: TButton;
cbAsciiChars: TCheckBox;
cbCharEncoding: TComboBox;
cbInCharEncoding: TComboBox;
cbOutCharEncoding: TComboBox;
Label12: TLabel;
Label13: TLabel;
Label14: TLabel;
labProfileName: TLabel;
eProfileName: TEdit;
procedure btnOKClick(Sender: TObject);
private
fProfile: TTidyConfiguration;
fProfileName: string;
fOriginalProfileName: string;
procedure CreateEnums;
procedure OptionsToForm;
procedure FormToOptions;
public
constructor Create(AOwner: TComponent; AProfile: TTidyConfiguration; ProfileName: string); reintroduce;
destructor Destroy; override;
property Profile: TTidyConfiguration read fProfile;
end;
{$ENDIF}
implementation
{$IFDEF SUPPORTS_HTML_TIDY}
{$R *.dfm}
////////////////////////////////////////////////////////////////////////////////////////////
// Functions
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TfmHTMLTidyProfile.CreateEnums;
var
EncodingID: TidyEncodingID;
DupAttrModes: TidyDupAttrModes;
TidyTriState: TTidyTriState;
begin
cbDuplicateAttrs.Items.Clear;
cbIndentContent.Items.Clear;
cbCharEncoding.Items.Clear;
for EncodingID:=Low(TidyEncodingID) to High(TidyEncodingID) do
cbCharEncoding.Items.AddObject(STR_TIDY_ENCODING_ID[EncodingID], pointer(EncodingID));
for TidyTriState:=Low(TTidyTriState) to High(TTidyTriState) do
cbIndentContent.Items.AddObject(STR_TIDY_TRISTATE[TidyTriState], pointer(TidyTriState));
for DupAttrModes:=Low(TidyDupAttrModes) to High(TidyDupAttrModes) do
cbDuplicateAttrs.Items.AddObject(STR_TIDY_DUP_ATTR_MODES[DupAttrModes], pointer(DupAttrModes));
cbInCharEncoding.Items.Assign(cbCharEncoding.Items);
cbOutCharEncoding.Items.Assign(cbCharEncoding.Items);
end;
//------------------------------------------------------------------------------------------
procedure TfmHTMLTidyProfile.OptionsToForm;
begin
with fProfile do begin
// markup properties
eAltText.Text:=AltText;
eDoctype.Text:=Doctype;
eBlockTags.Text:=BlockTags;
eEmptyTags.Text:=EmptyTags;
eInlineTags.Text:=InlineTags;
ePreTags.Text:=PreTags;
cbBreakBeforeBR.Checked:=BreakBeforeBR;
cbDropEmptyParas.Checked:=DropEmptyParas;
cbDropFontTags.Checked:=DropFontTags;
cbDropPropAttrs.Checked:=DropPropAttrs;
cbEncloseBlockText.Checked:=EncloseBlockText;
cbEncloseBodyText.Checked:=EncloseBodyText;
cbFixComments.Checked:=FixComments;
cbFixUri.Checked:=FixUri;
cbHideComments.Checked:=HideComments;
cbHideEndTags.Checked:=HideEndTags;
cbJoinClasses.Checked:=JoinClasses;
cbJoinStyles.Checked:=JoinStyles;
cbLogicalEmphasis.Checked:=LogicalEmphasis;
cbLowerLiterals.Checked:=LowerLiterals;
cbMakeBare.Checked:=MakeBare;
cbMakeClean.Checked:=MakeClean;
cbNcr.Checked:=Ncr;
cbNumEntities.Checked:=NumEntities;
cbQuoteAmpersand.Checked:=QuoteAmpersand;
cbQuoteMarks.Checked:=QuoteMarks;
cbQuoteNbsp.Checked:=QuoteNbsp;
cbReplaceColor.Checked:=ReplaceColor;
cbBodyOnly.Checked:=BodyOnly;
cbUpperCaseAttrs.Checked:=UpperCaseAttrs;
cbUpperCaseTags.Checked:=UpperCaseTags;
cbWord2000.Checked:=Word2000;
cbDuplicateAttrs.ItemIndex:=cbDuplicateAttrs.Items.IndexOfObject(pointer(DuplicateAttrs));
// xml markup properties
cbXmlDecl.Checked:=XmlDecl;
cbXmlPIs.Checked:=XmlPIs;
cbXmlSpace.Checked:=XmlSpace;
cbXmlTags.Checked:=XmlTags;
cbEscapeCdata.Checked:=EscapeCdata;
cbIndentCdata.Checked:=IndentCdata;
// pretty print
cbIndentContent.ItemIndex:=cbIndentContent.Items.IndexOfObject(pointer(IndentContent));
cbIndentAttributes.Checked:=IndentAttributes;
eIndentSpaces.Text:=IntToStr(IndentSpaces);
cbLiteralAttribs.Checked:=LiteralAttribs;
cbShowMarkup.Checked:=ShowMarkup;
eTabSize.Text:=IntToStr(TabSize);
eWrapLen.Text:=IntToStr(WrapLen);
cbWrapAsp.Checked:=WrapAsp;
cbWrapAttVals.Checked:=WrapAttVals;
cbWrapJste.Checked:=WrapJste;
cbWrapPhp.Checked:=WrapPhp;
cbWrapScriptlets.Checked:=WrapScriptlets;
cbWrapSection.Checked:=WrapSection;
cbFixBackslash.Checked:=FixBackslash;
// encoding
cbAsciiChars.Checked:=AsciiChars;
cbCharEncoding.ItemIndex:=cbCharEncoding.Items.IndexOfObject(pointer(CharEncoding));
cbInCharEncoding.ItemIndex:=cbInCharEncoding.Items.IndexOfObject(pointer(InCharEncoding));
cbOutCharEncoding.ItemIndex:=cbOutCharEncoding.Items.IndexOfObject(pointer(OutCharEncoding));
// OutputBom
end;
end;
//------------------------------------------------------------------------------------------
procedure TfmHTMLTidyProfile.FormToOptions;
begin
with fProfile do begin
// markup properties
AltText:=eAltText.Text;
Doctype:=eDoctype.Text;
BlockTags:=eBlockTags.Text;
EmptyTags:=eEmptyTags.Text;
InlineTags:=eInlineTags.Text;
PreTags:=ePreTags.Text;
BreakBeforeBR:=cbBreakBeforeBR.Checked;
DropEmptyParas:=cbDropEmptyParas.Checked;
DropFontTags:=cbDropFontTags.Checked;
DropPropAttrs:=cbDropPropAttrs.Checked;
EncloseBlockText:=cbEncloseBlockText.Checked;
EncloseBodyText:=cbEncloseBodyText.Checked;
FixComments:=cbFixComments.Checked;
FixUri:=cbFixUri.Checked;
HideComments:=cbHideComments.Checked;
HideEndTags:=cbHideEndTags.Checked;
JoinClasses:=cbJoinClasses.Checked;
JoinStyles:=cbJoinStyles.Checked;
LogicalEmphasis:=cbLogicalEmphasis.Checked;
LowerLiterals:=cbLowerLiterals.Checked;
MakeBare:=cbMakeBare.Checked;
MakeClean:=cbMakeClean.Checked;
Ncr:=cbNcr.Checked;
NumEntities:=cbNumEntities.Checked;
QuoteAmpersand:=cbQuoteAmpersand.Checked;
QuoteMarks:=cbQuoteMarks.Checked;
QuoteNbsp:=cbQuoteNbsp.Checked;
ReplaceColor:=cbReplaceColor.Checked;
BodyOnly:=cbBodyOnly.Checked;
UpperCaseAttrs:=cbUpperCaseAttrs.Checked;
UpperCaseTags:=cbUpperCaseTags.Checked;
Word2000:=cbWord2000.Checked;
DuplicateAttrs:=TidyDupAttrModes(cbDuplicateAttrs.ItemIndex);
// xml markup properties
XmlDecl:=cbXmlDecl.Checked;
XmlPIs:=cbXmlPIs.Checked;
XmlSpace:=cbXmlSpace.Checked;
XmlTags:=cbXmlTags.Checked;
EscapeCdata:=cbEscapeCdata.Checked;
IndentCdata:=cbIndentCdata.Checked;
// pretty print
IndentContent:=TTidyTriState(cbIndentContent.ItemIndex);
IndentAttributes:=cbIndentAttributes.Checked;
IndentSpaces:=StrToIntDef(eIndentSpaces.Text, 2);
LiteralAttribs:=cbLiteralAttribs.Checked;
ShowMarkup:=cbShowMarkup.Checked;
TabSize:=StrToIntDef(eTabSize.Text, 4);
WrapLen:=StrToIntDef(eWrapLen.Text, 68);
WrapAsp:=cbWrapAsp.Checked;
WrapAttVals:=cbWrapAttVals.Checked;
WrapJste:=cbWrapJste.Checked;
WrapPhp:=cbWrapPhp.Checked;
WrapScriptlets:=cbWrapScriptlets.Checked;
WrapSection:=cbWrapSection.Checked;
FixBackslash:=cbFixBackslash.Checked;
// encoding
AsciiChars:=cbAsciiChars.Checked;
CharEncoding:=TidyEncodingID(cbCharEncoding.ItemIndex);
InCharEncoding:=TidyEncodingID(cbInCharEncoding.ItemIndex);
OutCharEncoding:=TidyEncodingID(cbOutCharEncoding.ItemIndex);
// OutputBom
end;
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Buttons
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TfmHTMLTidyProfile.btnOKClick(Sender: TObject);
var
ProfileName: string;
FileName: string;
begin
FormToOptions;
ProfileName:=Trim(eProfileName.Text);
if (ProfileName<>fOriginalProfileName) then begin
end;
FileName:=MakeProfileFilename(ProfileName);
if not HTMLTidy.SaveToFile(FileName) then begin
DlgErrorSaveFile(FileName);
end;
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Constructor, destructor
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
constructor TfmHTMLTidyProfile.Create(AOwner: TComponent; AProfile: TTidyConfiguration; ProfileName: string);
begin
inherited Create(AOwner);
fProfile:=AProfile;
fOriginalProfileName:=ProfileName;
eProfileName.Text:=ProfileName;
pcProfile.ActivePageIndex:=0;
CreateEnums;
OptionsToForm;
end;
//------------------------------------------------------------------------------------------
destructor TfmHTMLTidyProfile.Destroy;
begin
inherited;
end;
//------------------------------------------------------------------------------------------
{$ENDIF}
end.
|
unit ibSHDatabaseAliasOptions;
interface
uses
Windows, SysUtils, Classes, Controls, Forms, Dialogs, Graphics,
SHDesignIntf, ibSHDesignIntf, ibSHConsts;
type
TibSHDDLOptions = class;
TibSHDMLOptions = class;
TibSHNavigatorOptions = class;
TibSHDatabaseAliasOptions = class(TSHInterfacedPersistent, IibSHDatabaseAliasOptions)
private
FNavigator: TibSHNavigatorOptions;
FDDL: TibSHDDLOptions;
FDML: TibSHDMLOptions;
function GetDDL: IibSHDDLOptions;
function GetDML: IibSHDMLOptions;
function GetNavigator: IibSHNavigatorOptions;
public
constructor Create;
destructor Destroy; override;
published
property Navigator: TibSHNavigatorOptions read FNavigator write FNavigator;
property DDL: TibSHDDLOptions read FDDL write FDDL;
property DML: TibSHDMLOptions read FDML write FDML;
end;
TibSHNavigatorOptions = class(TSHInterfacedPersistent, IibSHNavigatorOptions)
private
FFavoriteObjectNames: TStrings;
FFavoriteObjectColor: TColor;
FShowDomains: Boolean;
FShowTables: Boolean;
FShowViews: Boolean;
FShowProcedures: Boolean;
FShowTriggers: Boolean;
FShowGenerators: Boolean;
FShowExceptions: Boolean;
FShowFunctions: Boolean;
FShowFilters: Boolean;
FShowRoles: Boolean;
FShowIndices: Boolean;
function GetFavoriteObjectNames: TStrings;
procedure SetFavoriteObjectNames(Value: TStrings);
function GetFavoriteObjectColor: TColor;
procedure SetFavoriteObjectColor(Value: TColor);
function GetShowDomains: Boolean;
procedure SetShowDomains(Value: Boolean);
function GetShowTables: Boolean;
procedure SetShowTables(Value: Boolean);
function GetShowViews: Boolean;
procedure SetShowViews(Value: Boolean);
function GetShowProcedures: Boolean;
procedure SetShowProcedures(Value: Boolean);
function GetShowTriggers: Boolean;
procedure SetShowTriggers(Value: Boolean);
function GetShowGenerators: Boolean;
procedure SetShowGenerators(Value: Boolean);
function GetShowExceptions: Boolean;
procedure SetShowExceptions(Value: Boolean);
function GetShowFunctions: Boolean;
procedure SetShowFunctions(Value: Boolean);
function GetShowFilters: Boolean;
procedure SetShowFilters(Value: Boolean);
function GetShowRoles: Boolean;
procedure SetShowRoles(Value: Boolean);
function GetShowIndices: Boolean;
procedure SetShowIndices(Value: Boolean);
public
constructor Create;
destructor Destroy; override;
published
property FavoriteObjectNames: TStrings read GetFavoriteObjectNames write SetFavoriteObjectNames;
property FavoriteObjectColor: TColor read FFavoriteObjectColor write FFavoriteObjectColor;
property ShowDomains: Boolean read FShowDomains write FShowDomains;
property ShowTables: Boolean read FShowTables write FShowTables;
property ShowViews: Boolean read FShowViews write FShowViews;
property ShowProcedures: Boolean read FShowProcedures write FShowProcedures;
property ShowTriggers: Boolean read FShowTriggers write FShowTriggers;
property ShowGenerators: Boolean read FShowGenerators write FShowGenerators;
property ShowExceptions: Boolean read FShowExceptions write FShowExceptions;
property ShowFunctions: Boolean read FShowFunctions write FShowFunctions;
property ShowFilters: Boolean read FShowFilters write FShowFilters;
property ShowRoles: Boolean read FShowRoles write FShowRoles;
property ShowIndices: Boolean read FShowIndices write FShowIndices;
end;
TibSHDDLOptions = class(TSHInterfacedPersistent, IibSHDDLOptions)
private
FAutoCommit: Boolean;
FStartDomainForm: string;
FStartTableForm: string;
FStartIndexForm: string;
FStartViewForm: string;
FStartProcedureForm: string;
FStartTriggerForm: string;
FStartGeneratorForm: string;
FStartExceptionForm: string;
FStartFunctionForm: string;
FStartFilterForm: string;
FStartRoleForm: string;
function GetAutoCommit: Boolean;
procedure SetAutoCommit(Value: Boolean);
function GetStartDomainForm: string;
procedure SetStartDomainForm(Value: string);
function GetStartTableForm: string;
procedure SetStartTableForm(Value: string);
function GetStartIndexForm: string;
procedure SetStartIndexForm(Value: string);
function GetStartViewForm: string;
procedure SetStartViewForm(Value: string);
function GetStartProcedureForm: string;
procedure SetStartProcedureForm(Value: string);
function GetStartTriggerForm: string;
procedure SetStartTriggerForm(Value: string);
function GetStartGeneratorForm: string;
procedure SetStartGeneratorForm(Value: string);
function GetStartExceptionForm: string;
procedure SetStartExceptionForm(Value: string);
function GetStartFunctionForm: string;
procedure SetStartFunctionForm(Value: string);
function GetStartFilterForm: string;
procedure SetStartFilterForm(Value: string);
function GetStartRoleForm: string;
procedure SetStartRoleForm(Value: string);
protected
property StartDomainForm: string read GetStartDomainForm write SetStartDomainForm;
property StartTableForm: string read GetStartTableForm write SetStartTableForm;
property StartIndexForm: string read GetStartIndexForm write SetStartIndexForm;
property StartViewForm: string read GetStartViewForm write SetStartViewForm;
property StartProcedureForm: string read GetStartProcedureForm write SetStartProcedureForm;
property StartTriggerForm: string read GetStartTriggerForm write SetStartTriggerForm;
property StartGeneratorForm: string read GetStartGeneratorForm write SetStartGeneratorForm;
property StartExceptionForm: string read GetStartExceptionForm write SetStartExceptionForm;
property StartFunctionForm: string read GetStartFunctionForm write SetStartFunctionForm;
property StartFilterForm: string read GetStartFilterForm write SetStartFilterForm;
property StartRoleForm: string read GetStartRoleForm write SetStartRoleForm;
published
property AutoCommit: Boolean read FAutoCommit write FAutoCommit;
end;
TibSHDMLOptions = class(TSHInterfacedPersistent, IibSHDMLOptions)
private
FAutoCommit: Boolean;
FShowDB_KEY: Boolean;
FUseDB_KEY: Boolean;
FConfirmEndTransaction: string;
FDefaultTransactionAction: string;
FIsolationLevel: string;
FTransactionParams: TStringList;
function GetAutoCommit: Boolean;
procedure SetAutoCommit(Value: Boolean);
function GetShowDB_KEY: Boolean;
procedure SetShowDB_KEY(Value: Boolean);
function GetUseDB_KEY: Boolean;
procedure SetUseDB_KEY(Value: Boolean);
function GetConfirmEndTransaction: string;
procedure SetConfirmEndTransaction(Value: string);
function GetDefaultTransactionAction: string;
procedure SetDefaultTransactionAction(Value: string);
function GetIsolationLevel: string;
procedure SetIsolationLevel(Value: string);
function GetTransactionParams: TStrings;
procedure SetTransactionParams(Value: TStrings);
public
constructor Create;
destructor Destroy; override;
published
property AutoCommit: Boolean read GetAutoCommit write SetAutoCommit;
property ShowDB_KEY: Boolean read FShowDB_KEY write FShowDB_KEY;
property UseDB_KEY: Boolean read FUseDB_KEY write FUseDB_KEY;
property ConfirmEndTransaction: string read FConfirmEndTransaction write FConfirmEndTransaction;
property DefaultTransactionAction: string read FDefaultTransactionAction write FDefaultTransactionAction;
property IsolationLevel: string read GetIsolationLevel write SetIsolationLevel;
property TransactionParams: TStrings read GetTransactionParams write SetTransactionParams;
end;
TibSHDatabaseAliasOptionsInt = class(TSHInterfacedPersistent, IibSHDatabaseAliasOptionsInt)
private
FFilterList: TStrings;
FFilterIndex: Integer;
FDMLHistoryActive: Boolean;
FDMLHistoryMaxCount: Integer;
FDMLHistorySelect: Boolean;
FDMLHistoryInsert: Boolean;
FDMLHistoryUpdate: Boolean;
FDMLHistoryDelete: Boolean;
FDMLHistoryExecute: Boolean;
FDMLHistoryCrash: Boolean;
FDDLHistoryActive: Boolean;
function GetFilterList: TStrings;
procedure SetFilterList(Value: TStrings);
function GetFilterIndex: Integer;
procedure SetFilterIndex(Value: Integer);
function GetDMLHistoryActive: Boolean;
procedure SetDMLHistoryActive(const Value: Boolean);
function GetDMLHistoryMaxCount: Integer;
procedure SetDMLHistoryMaxCount(const Value: Integer);
function GetDMLHistorySelect: Boolean;
procedure SetDMLHistorySelect(const Value: Boolean);
function GetDMLHistoryInsert: Boolean;
procedure SetDMLHistoryInsert(const Value: Boolean);
function GetDMLHistoryUpdate: Boolean;
procedure SetDMLHistoryUpdate(const Value: Boolean);
function GetDMLHistoryDelete: Boolean;
procedure SetDMLHistoryDelete(const Value: Boolean);
function GetDMLHistoryExecute: Boolean;
procedure SetDMLHistoryExecute(const Value: Boolean);
function GetDMLHistoryCrash: Boolean;
procedure SetDMLHistoryCrash(const Value: Boolean);
function GetDDLHistoryActive: Boolean;
procedure SetDDLHistoryActive(const Value: Boolean);
public
constructor Create;
destructor Destroy; override;
published
property FilterList: TStrings read GetFilterList write SetFilterList;
property FilterIndex: Integer read GetFilterIndex write SetFilterIndex;
property DMLHistoryActive: Boolean read GetDMLHistoryActive
write SetDMLHistoryActive default True;
property DMLHistoryMaxCount: Integer read GetDMLHistoryMaxCount
write SetDMLHistoryMaxCount default 0;
property DMLHistorySelect: Boolean read GetDMLHistorySelect
write SetDMLHistorySelect default True;
property DMLHistoryInsert: Boolean read GetDMLHistoryInsert
write SetDMLHistoryInsert default True;
property DMLHistoryUpdate: Boolean read GetDMLHistoryUpdate
write SetDMLHistoryUpdate default True;
property DMLHistoryDelete: Boolean read GetDMLHistoryDelete
write SetDMLHistoryDelete default True;
property DMLHistoryExecute: Boolean read GetDMLHistoryExecute
write SetDMLHistoryExecute default True;
property DMLHistoryCrash: Boolean read GetDMLHistoryCrash
write SetDMLHistoryCrash default False;
property DDLHistoryActive: Boolean read GetDDLHistoryActive
write SetDDLHistoryActive;
end;
implementation
{ TibSHDatabaseAliasOptions }
constructor TibSHDatabaseAliasOptions.Create;
begin
inherited Create;
FNavigator := TibSHNavigatorOptions.Create;
FDDL := TibSHDDLOptions.Create;
FDML := TibSHDMLOptions.Create;
Navigator.FavoriteObjectColor := clBlue;
Navigator.ShowDomains := True;
Navigator.ShowTables := True;
Navigator.ShowViews := True;
Navigator.ShowProcedures := True;
Navigator.ShowTriggers := True;
Navigator.ShowGenerators := True;
Navigator.ShowExceptions := True;
Navigator.ShowFunctions := True;
Navigator.ShowFilters := True;
Navigator.ShowRoles := True;
Navigator.ShowIndices := True;
DDL.AutoCommit := True;
DDL.StartDomainForm := SCallSourceDDL;
DDL.StartTableForm := SCallSourceDDL;
DDL.StartIndexForm := SCallSourceDDL;
DDL.StartViewForm := SCallSourceDDL;
DDL.StartProcedureForm := SCallSourceDDL;
DDL.StartTriggerForm := SCallSourceDDL;
DDL.StartGeneratorForm := SCallSourceDDL;
DDL.StartExceptionForm := SCallSourceDDL;
DDL.StartFunctionForm := SCallSourceDDL;
DDL.StartFilterForm := SCallSourceDDL;
DDL.StartRoleForm := SCallSourceDDL;
DML.AutoCommit := False;
DML.ShowDB_KEY := False;
DML.UseDB_KEY := True;
DML.ConfirmEndTransaction := ConfirmEndTransactions[0];
DML.DefaultTransactionAction := DefaultTransactionActions[0];
DML.IsolationLevel := IsolationLevels[1];
DML.TransactionParams.Text := TransactionParamsCustomDefault;
end;
destructor TibSHDatabaseAliasOptions.Destroy;
begin
FNavigator.Free;
FDDL.Free;
FDML.Free;
inherited Destroy;
end;
function TibSHDatabaseAliasOptions.GetDDL: IibSHDDLOptions;
begin
Supports(FDDL, IibSHDDLOptions, Result);
end;
function TibSHDatabaseAliasOptions.GetDML: IibSHDMLOptions;
begin
Supports(FDML, IibSHDMLOptions, Result);
end;
function TibSHDatabaseAliasOptions.GetNavigator: IibSHNavigatorOptions;
begin
Supports(FNavigator, IibSHNavigatorOptions, Result);
end;
{ TibSHNavigatorOptions }
constructor TibSHNavigatorOptions.Create;
begin
inherited Create;
FFavoriteObjectNames := TStringList.Create;
end;
destructor TibSHNavigatorOptions.Destroy;
begin
FFavoriteObjectNames.Free;
inherited Destroy;
end;
function TibSHNavigatorOptions.GetFavoriteObjectNames: TStrings;
begin
Result := FFavoriteObjectNames;
end;
procedure TibSHNavigatorOptions.SetFavoriteObjectNames(Value: TStrings);
begin
TStringList(FFavoriteObjectNames).Sorted := False;
FFavoriteObjectNames.Assign(Value);
TStringList(FFavoriteObjectNames).Sorted := True;
end;
function TibSHNavigatorOptions.GetFavoriteObjectColor: TColor;
begin
Result := FavoriteObjectColor;
end;
procedure TibSHNavigatorOptions.SetFavoriteObjectColor(Value: TColor);
begin
FavoriteObjectColor := Value;
end;
function TibSHNavigatorOptions.GetShowDomains: Boolean;
begin
Result := ShowDomains;
end;
procedure TibSHNavigatorOptions.SetShowDomains(Value: Boolean);
begin
ShowDomains := Value;
end;
function TibSHNavigatorOptions.GetShowTables: Boolean;
begin
Result := ShowTables;
end;
procedure TibSHNavigatorOptions.SetShowTables(Value: Boolean);
begin
ShowTables := Value;
end;
function TibSHNavigatorOptions.GetShowViews: Boolean;
begin
Result := ShowViews;
end;
procedure TibSHNavigatorOptions.SetShowViews(Value: Boolean);
begin
ShowViews := Value;
end;
function TibSHNavigatorOptions.GetShowProcedures: Boolean;
begin
Result := ShowProcedures;
end;
procedure TibSHNavigatorOptions.SetShowProcedures(Value: Boolean);
begin
ShowProcedures := Value;
end;
function TibSHNavigatorOptions.GetShowTriggers: Boolean;
begin
Result := ShowTriggers;
end;
procedure TibSHNavigatorOptions.SetShowTriggers(Value: Boolean);
begin
ShowTriggers := Value;
end;
function TibSHNavigatorOptions.GetShowGenerators: Boolean;
begin
Result := ShowGenerators;
end;
procedure TibSHNavigatorOptions.SetShowGenerators(Value: Boolean);
begin
ShowGenerators := Value;
end;
function TibSHNavigatorOptions.GetShowExceptions: Boolean;
begin
Result := ShowExceptions;
end;
procedure TibSHNavigatorOptions.SetShowExceptions(Value: Boolean);
begin
ShowExceptions := Value;
end;
function TibSHNavigatorOptions.GetShowFunctions: Boolean;
begin
Result := ShowFunctions;
end;
procedure TibSHNavigatorOptions.SetShowFunctions(Value: Boolean);
begin
ShowFunctions := Value;
end;
function TibSHNavigatorOptions.GetShowFilters: Boolean;
begin
Result := ShowFilters;
end;
procedure TibSHNavigatorOptions.SetShowFilters(Value: Boolean);
begin
ShowFilters := Value;
end;
function TibSHNavigatorOptions.GetShowRoles: Boolean;
begin
Result := ShowRoles;
end;
procedure TibSHNavigatorOptions.SetShowRoles(Value: Boolean);
begin
ShowRoles := Value;
end;
function TibSHNavigatorOptions.GetShowIndices: Boolean;
begin
Result := ShowIndices;
end;
procedure TibSHNavigatorOptions.SetShowIndices(Value: Boolean);
begin
ShowIndices := Value;
end;
{ TibSHDDLOptions }
function TibSHDDLOptions.GetAutoCommit: Boolean;
begin
Result := AutoCommit;
end;
procedure TibSHDDLOptions.SetAutoCommit(Value: Boolean);
begin
AutoCommit := Value;
end;
function TibSHDDLOptions.GetStartDomainForm: string;
begin
Result := FStartDomainForm;
end;
procedure TibSHDDLOptions.SetStartDomainForm(Value: string);
begin
FStartDomainForm := Value;
end;
function TibSHDDLOptions.GetStartTableForm: string;
begin
Result := FStartTableForm;
end;
procedure TibSHDDLOptions.SetStartTableForm(Value: string);
begin
FStartTableForm := Value;
end;
function TibSHDDLOptions.GetStartIndexForm: string;
begin
Result := FStartIndexForm;
end;
procedure TibSHDDLOptions.SetStartIndexForm(Value: string);
begin
FStartIndexForm := Value;
end;
function TibSHDDLOptions.GetStartViewForm: string;
begin
Result := FStartViewForm;
end;
procedure TibSHDDLOptions.SetStartViewForm(Value: string);
begin
FStartViewForm := Value;
end;
function TibSHDDLOptions.GetStartProcedureForm: string;
begin
Result := FStartProcedureForm;
end;
procedure TibSHDDLOptions.SetStartProcedureForm(Value: string);
begin
FStartProcedureForm := Value;
end;
function TibSHDDLOptions.GetStartTriggerForm: string;
begin
Result := FStartTriggerForm;
end;
procedure TibSHDDLOptions.SetStartTriggerForm(Value: string);
begin
FStartTriggerForm := Value;
end;
function TibSHDDLOptions.GetStartGeneratorForm: string;
begin
Result := FStartGeneratorForm;
end;
procedure TibSHDDLOptions.SetStartGeneratorForm(Value: string);
begin
FStartGeneratorForm := Value;
end;
function TibSHDDLOptions.GetStartExceptionForm: string;
begin
Result := FStartExceptionForm;
end;
procedure TibSHDDLOptions.SetStartExceptionForm(Value: string);
begin
FStartExceptionForm := Value;
end;
function TibSHDDLOptions.GetStartFunctionForm: string;
begin
Result := FStartFunctionForm;
end;
procedure TibSHDDLOptions.SetStartFunctionForm(Value: string);
begin
FStartFunctionForm := Value;
end;
function TibSHDDLOptions.GetStartFilterForm: string;
begin
Result := FStartFilterForm;
end;
procedure TibSHDDLOptions.SetStartFilterForm(Value: string);
begin
FStartFilterForm := Value;
end;
function TibSHDDLOptions.GetStartRoleForm: string;
begin
Result := FStartRoleForm;
end;
procedure TibSHDDLOptions.SetStartRoleForm(Value: string);
begin
FStartRoleForm := Value;
end;
{ TibSHDMLOptions }
function TibSHDMLOptions.GetAutoCommit: Boolean;
begin
Result := FAutoCommit;
end;
procedure TibSHDMLOptions.SetAutoCommit(Value: Boolean);
begin
FAutoCommit := Value;
end;
function TibSHDMLOptions.GetShowDB_KEY: Boolean;
begin
Result := ShowDB_KEY;
end;
procedure TibSHDMLOptions.SetShowDB_KEY(Value: Boolean);
begin
ShowDB_KEY := Value;
end;
function TibSHDMLOptions.GetUseDB_KEY: Boolean;
begin
Result := UseDB_KEY;
end;
procedure TibSHDMLOptions.SetUseDB_KEY(Value: Boolean);
begin
UseDB_KEY := Value;
end;
function TibSHDMLOptions.GetConfirmEndTransaction: string;
begin
Result := ConfirmEndTransaction;
end;
procedure TibSHDMLOptions.SetConfirmEndTransaction(Value: string);
begin
ConfirmEndTransaction := Value;
end;
function TibSHDMLOptions.GetDefaultTransactionAction: string;
begin
Result := DefaultTransactionAction;
end;
procedure TibSHDMLOptions.SetDefaultTransactionAction(Value: string);
begin
DefaultTransactionAction := Value;
end;
function TibSHDMLOptions.GetIsolationLevel: string;
begin
Result := FIsolationLevel;
end;
procedure TibSHDMLOptions.SetIsolationLevel(Value: string);
begin
FIsolationLevel := Value;
end;
function TibSHDMLOptions.GetTransactionParams: TStrings;
begin
Result := FTransactionParams;
end;
procedure TibSHDMLOptions.SetTransactionParams(Value: TStrings);
begin
FTransactionParams.Assign(Value);
end;
constructor TibSHDMLOptions.Create;
begin
inherited Create;
FTransactionParams := TStringList.Create;
end;
destructor TibSHDMLOptions.Destroy;
begin
FTransactionParams.Free;
inherited;
end;
{ TibSHDatabaseAliasOptionsInt }
constructor TibSHDatabaseAliasOptionsInt.Create;
begin
inherited Create;
FFilterList := TStringList.Create;
FFilterIndex := -1;
FDMLHistoryActive := True;
FDMLHistoryMaxCount := 0;
FDMLHistorySelect := True;
FDMLHistoryInsert := True;
FDMLHistoryUpdate := True;
FDMLHistoryDelete := True;
FDMLHistoryExecute := True;
FDDLHistoryActive := True;
end;
destructor TibSHDatabaseAliasOptionsInt.Destroy;
begin
FFilterList.Free;
inherited Destroy;
end;
function TibSHDatabaseAliasOptionsInt.GetFilterList: TStrings;
begin
Result := FFilterList;
end;
procedure TibSHDatabaseAliasOptionsInt.SetFilterList(Value: TStrings);
begin
FFilterList.Assign(Value);
end;
function TibSHDatabaseAliasOptionsInt.GetFilterIndex: Integer;
begin
Result := FFilterIndex;
end;
procedure TibSHDatabaseAliasOptionsInt.SetFilterIndex(Value: Integer);
begin
FFilterIndex := Value;
end;
function TibSHDatabaseAliasOptionsInt.GetDMLHistoryActive: Boolean;
begin
Result := FDMLHistoryActive;
end;
procedure TibSHDatabaseAliasOptionsInt.SetDMLHistoryActive(
const Value: Boolean);
begin
FDMLHistoryActive := Value;
end;
function TibSHDatabaseAliasOptionsInt.GetDMLHistoryMaxCount: Integer;
begin
Result := FDMLHistoryMaxCount;
end;
procedure TibSHDatabaseAliasOptionsInt.SetDMLHistoryMaxCount(
const Value: Integer);
begin
FDMLHistoryMaxCount := Value;
end;
function TibSHDatabaseAliasOptionsInt.GetDMLHistorySelect: Boolean;
begin
Result := FDMLHistorySelect;
end;
procedure TibSHDatabaseAliasOptionsInt.SetDMLHistorySelect(
const Value: Boolean);
begin
FDMLHistorySelect := Value;
end;
function TibSHDatabaseAliasOptionsInt.GetDMLHistoryInsert: Boolean;
begin
Result := FDMLHistoryInsert;
end;
procedure TibSHDatabaseAliasOptionsInt.SetDMLHistoryInsert(
const Value: Boolean);
begin
FDMLHistoryInsert := Value;
end;
function TibSHDatabaseAliasOptionsInt.GetDMLHistoryUpdate: Boolean;
begin
Result := FDMLHistoryUpdate;
end;
procedure TibSHDatabaseAliasOptionsInt.SetDMLHistoryUpdate(
const Value: Boolean);
begin
FDMLHistoryUpdate := Value;
end;
function TibSHDatabaseAliasOptionsInt.GetDMLHistoryDelete: Boolean;
begin
Result := FDMLHistoryDelete;
end;
procedure TibSHDatabaseAliasOptionsInt.SetDMLHistoryDelete(
const Value: Boolean);
begin
FDMLHistoryDelete := Value;
end;
function TibSHDatabaseAliasOptionsInt.GetDMLHistoryExecute: Boolean;
begin
Result := FDMLHistoryExecute;
end;
procedure TibSHDatabaseAliasOptionsInt.SetDMLHistoryExecute(
const Value: Boolean);
begin
FDMLHistoryExecute := Value;
end;
function TibSHDatabaseAliasOptionsInt.GetDMLHistoryCrash: Boolean;
begin
Result := FDMLHistoryCrash;
end;
procedure TibSHDatabaseAliasOptionsInt.SetDMLHistoryCrash(
const Value: Boolean);
begin
FDMLHistoryCrash := Value;
end;
function TibSHDatabaseAliasOptionsInt.GetDDLHistoryActive: Boolean;
begin
Result := FDDLHistoryActive;
end;
procedure TibSHDatabaseAliasOptionsInt.SetDDLHistoryActive(
const Value: Boolean);
begin
FDDLHistoryActive := Value;
end;
end.
|
unit ModflowSUB_Writer;
interface
uses
Classes, CustomModflowWriterUnit, ModflowPackageSelectionUnit, UnitList,
IntListUnit, PhastModelUnit, SysUtils;
type
TMaterialZone = record
VerticalK: double;
ElasticSpecificStorage: double;
InelasticSpecificStorage: double;
class operator Equal(Var1: TMaterialZone; Var2: TMaterialZone): boolean;
class operator NotEqual(Var1: TMaterialZone; Var2: TMaterialZone): boolean;
function ID: Integer;
end;
TMaterialZoneIdItem = class(TIDItem)
private
FMaterialZoneValues: TMaterialZone;
FZoneNumber: integer;
FNextSameID: TMaterialZoneIdItem;
procedure SetMaterialZoneValues(const Value: TMaterialZone);
procedure AssignID;
public
Constructor Create;
Destructor Destroy; override;
property MaterialZoneValues: TMaterialZone read FMaterialZoneValues
write SetMaterialZoneValues;
property ZoneNumber: integer read FZoneNumber write FZoneNumber;
property NextSameID: TMaterialZoneIdItem read FNextSameID write FNextSameID;
end;
TMaterialZoneList = class(TObject)
private
FMaterialZones: TList;
FIdList: TIDList;
function GetItem(Index: integer): TMaterialZoneIdItem;
public
Constructor Create;
Destructor Destroy; override;
function AddRecord(MaterialZone: TMaterialZone): TMaterialZoneIdItem;
function Count: integer;
property Items[Index: integer]: TMaterialZoneIdItem read GetItem; default;
end;
TModflowSUB_Writer = class(TCustomSubWriter)
private
// model layer assignments for each system of no-delay interbeds
FLN: TIntegerList;
// model layer assignments for each system of delay interbeds
FLDN: TIntegerList;
// specifying the factor n-equiv - Delay beds
FRNB_List: TList;
// preconsolidation head - No-Delay beds
FHC_List: TList;
// elastic skeletal storage coefficient - No-Delay beds
FSfe_List: TList;
// inelastic skeletal storage coefficient - No-Delay beds
FSfv_List: TList;
// fcstarting compaction - No-Delay beds
FCom_List: TList;
// material zones - Delay beds
FDP_List: TMaterialZoneList;
FDelayVK_List: TList;
FDelayElasticSpecificStorage_List: TList;
FDelayInElasticSpecificStorage_List: TList;
// starting head - Delay beds
FDstart_List: TList;
// starting preconsolidation head - Delay beds
FDHC_List: TList;
// starting compaction - Delay beds
FDCOM_List: TList;
// equivalent thickness - Delay beds
FDZ_List: TList;
// material zone numbers - Delay beds
FNZ_List: TList;
FSubPackage: TSubPackageSelection;
FNameOfFile: string;
procedure RetrieveArrays;
procedure EvaluateMaterialZones;
procedure Evaluate;
procedure WriteDataSet1;
procedure WriteDataSet2;
procedure WriteDataSet3;
procedure WriteDataSet4;
procedure WriteDataSets5to8;
procedure WriteDataSet9;
procedure WriteDataSets10to14;
procedure WriteDataSet15;
procedure WriteDataSet16;
protected
function Package: TModflowPackageSelection; override;
class function Extension: string; override;
public
procedure WriteFile(const AFileName: string);
Constructor Create(Model: TCustomModel; EvaluationType: TEvaluationType); override;
Destructor Destroy; override;
end;
implementation
uses
Contnrs, LayerStructureUnit, ModflowSubsidenceDefUnit, DataSetUnit,
GoPhastTypes, RbwParser, ModflowUnitNumbers, frmProgressUnit,
frmErrorsAndWarningsUnit, Forms, JclMath;
resourcestring
StrSubsidenceNotSuppo = 'Subsidence not supported with MODFLOW-LGR';
StrRestartFileNamesI = 'Restart File names identical for SUB package';
StrTheRestartFileSav = 'The restart file saved by the Subsidence package' +
' has the same name as the restart file read by Subsidence package to ' +
'define the starting head and starting preconsolidation head. You need ' +
'to change the name of the file read by the Subsidence package in the ' +
'"Model|Packages and Programs" dialog box.';
StrModelMuseDoesNotC = 'ModelMuse does not currently support the use of th' +
'e Subsidence package in MODFLOW-LGR.';
StrWritingSUBPackage = 'Writing SUB Package input.';
// StrWritingDataSet1 = ' Writing Data Set 1.';
// StrWritingDataSet2 = ' Writing Data Set 2.';
// StrWritingDataSet3 = ' Writing Data Set 3.';
// StrWritingDataSet4 = ' Writing Data Set 4.';
// StrWritingDataSets5to8 = ' Writing Data Sets 5 to 8.';
// StrWritingDataSet9 = ' Writing Data Set 9.';
StrWritingDataSets10to14 = ' Writing Data Sets 10 to 14.';
// StrWritingDataSet15 = ' Writing Data Set 15.';
// StrWritingDataSet16 = ' Writing Data Set 16.';
function TMaterialZone.ID: Integer;
var
ByteArray: array of Byte;
begin
SetLength(ByteArray, SizeOf(TMaterialZone));
Move(self, ByteArray[0], SizeOf(TMaterialZone));
result := Integer(CRC32(ByteArray, SizeOf(TMaterialZone)));
end;
class operator TMaterialZone.NotEqual(Var1, Var2: TMaterialZone): boolean;
begin
result := (Var1.VerticalK <> Var2.VerticalK)
or (Var1.ElasticSpecificStorage <> Var2.ElasticSpecificStorage)
or (Var1.InelasticSpecificStorage <> Var2.InelasticSpecificStorage)
end;
{ TMaterialZone }
class operator TMaterialZone.Equal(Var1, Var2: TMaterialZone): boolean;
begin
result := (Var1.VerticalK = Var2.VerticalK)
and (Var1.ElasticSpecificStorage = Var2.ElasticSpecificStorage)
and (Var1.InelasticSpecificStorage = Var2.InelasticSpecificStorage)
end;
{ TModflowSUB_Writer }
constructor TModflowSUB_Writer.Create(Model: TCustomModel; EvaluationType: TEvaluationType);
begin
inherited;
FLN := TIntegerList.Create;
FLDN := TIntegerList.Create;
FRNB_List := TList.Create;
FHC_List := TList.Create;
FSfe_List := TList.Create;
FSfv_List := TList.Create;
FCom_List := TList.Create;
FDP_List := TMaterialZoneList.Create;
FDelayVK_List := TList.Create;
FDelayElasticSpecificStorage_List := TList.Create;
FDelayInElasticSpecificStorage_List := TList.Create;
FDstart_List := TList.Create;
FDHC_List := TList.Create;
FDCOM_List := TList.Create;
FDZ_List := TList.Create;
FNZ_List := TObjectList.Create;
end;
destructor TModflowSUB_Writer.Destroy;
begin
FNZ_List.Free;
FDZ_List.Free;
FDCOM_List.Free;
FDHC_List.Free;
FDstart_List.Free;
FDelayInElasticSpecificStorage_List.Free;
FDelayElasticSpecificStorage_List.Free;
FDelayVK_List.Free;
FDP_List.Free;
FCom_List.Free;
FSfv_List.Free;
FSfe_List.Free;
FHC_List.Free;
FRNB_List.Free;
FLDN.Free;
FLN.Free;
inherited;
end;
procedure TModflowSUB_Writer.Evaluate;
begin
RetrieveArrays;
EvaluateMaterialZones;
end;
procedure TModflowSUB_Writer.EvaluateMaterialZones;
var
DataArrayIndex: Integer;
VK_Array: TDataArray;
ElasticSSArray: TDataArray;
InElasticSSArray: TDataArray;
RowIndex: Integer;
ColIndex: Integer;
MaterialZoneRecord: TMaterialZone;
MaterialZoneObject: TMaterialZoneIdItem;
MaterialZoneArray: TDataArray;
begin
FNZ_List.Capacity := FDelayVK_List.Count;
for DataArrayIndex := 0 to FDelayVK_List.Count - 1 do
begin
VK_Array := FDelayVK_List[DataArrayIndex];
ElasticSSArray := FDelayElasticSpecificStorage_List[DataArrayIndex];
InElasticSSArray := FDelayInElasticSpecificStorage_List[DataArrayIndex];
VK_Array.Initialize;
ElasticSSArray.Initialize;
InElasticSSArray.Initialize;
MaterialZoneArray := TDataArray.Create(Model);
FNZ_List.Add(MaterialZoneArray);
MaterialZoneArray.Orientation := dsoTop;
MaterialZoneArray.DataType := rdtInteger;
MaterialZoneArray.EvaluatedAt := eaBlocks;
MaterialZoneArray.UpdateDimensions(1, VK_Array.RowCount, VK_Array.ColumnCount, True);
for RowIndex := 0 to VK_Array.RowCount - 1 do
begin
for ColIndex := 0 to VK_Array.ColumnCount - 1 do
begin
MaterialZoneRecord.VerticalK := VK_Array.RealData[0,RowIndex,ColIndex];
MaterialZoneRecord.ElasticSpecificStorage := ElasticSSArray.RealData[0,RowIndex,ColIndex];
MaterialZoneRecord.InelasticSpecificStorage := InElasticSSArray.RealData[0,RowIndex,ColIndex];
MaterialZoneObject := FDP_List.AddRecord(MaterialZoneRecord);
MaterialZoneArray.IntegerData[0,RowIndex,ColIndex] := MaterialZoneObject.ZoneNumber;
end;
end;
MaterialZoneArray.UpToDate := True;
end;
end;
class function TModflowSUB_Writer.Extension: string;
begin
result := '.sub';
end;
function TModflowSUB_Writer.Package: TModflowPackageSelection;
begin
result := Model.ModflowPackages.SubPackage;
end;
procedure TModflowSUB_Writer.RetrieveArrays;
var
GroupIndex: Integer;
Layers: TLayerStructure;
Group: TLayerGroup;
SubsidenceIndex: Integer;
NoDelayItem: TSubNoDelayBedLayerItem;
PreconsolidationHeadDataArray: TDataArray;
ElasticSkeletalStorageCoefficientDataArray: TDataArray;
InelasticSkeletalStorageCoefficientDataArray: TDataArray;
InitialCompactionDataArray: TDataArray;
MFLayer_Group: Integer;
LayerIndex: Integer;
DelayItem: TSubDelayBedLayerItem;
EquivNumberDataArray: TDataArray;
VerticalHydraulicConductivityDataArray: TDataArray;
ElasticSpecificStorageDataArray: TDataArray;
InelasticSpecificStorageDataArray: TDataArray;
InterbedStartingHeadDataArray: TDataArray;
InterbedPreconsolidationHeadDataArray: TDataArray;
InterbedStartingCompactionDataArray: TDataArray;
InterbedEquivalentThicknessDataArray: TDataArray;
begin
Layers := Model.LayerStructure;
MFLayer_Group := 0;
for GroupIndex := 1 to Layers.Count - 1 do
begin
Group := Layers.LayerGroups[GroupIndex];
if Group.RunTimeSimulated then
begin
for SubsidenceIndex := 0 to Group.SubNoDelayBedLayers.Count - 1 do
begin
NoDelayItem := Group.SubNoDelayBedLayers[SubsidenceIndex];
PreconsolidationHeadDataArray := Model.DataArrayManager.GetDataSetByName(
NoDelayItem.PreconsolidationHeadDataArrayName);
Assert(PreconsolidationHeadDataArray <> nil);
ElasticSkeletalStorageCoefficientDataArray := Model.DataArrayManager.GetDataSetByName(
NoDelayItem.ElasticSkeletalStorageCoefficientDataArrayName);
Assert(ElasticSkeletalStorageCoefficientDataArray <> nil);
InelasticSkeletalStorageCoefficientDataArray := Model.DataArrayManager.GetDataSetByName(
NoDelayItem.InelasticSkeletalStorageCoefficientDataArrayName);
Assert(InelasticSkeletalStorageCoefficientDataArray <> nil);
InitialCompactionDataArray := Model.DataArrayManager.GetDataSetByName(
NoDelayItem.InitialCompactionDataArrayName);
Assert(InitialCompactionDataArray <> nil);
if Group.LayerCount = 1 then
begin
FLN.Add(MFLayer_Group+1);
FHC_List.Add(PreconsolidationHeadDataArray);
FSfe_List.Add(ElasticSkeletalStorageCoefficientDataArray);
FSfv_List.Add(InelasticSkeletalStorageCoefficientDataArray);
FCom_List.Add(InitialCompactionDataArray);
end
else
begin
if NoDelayItem.UseInAllLayers then
begin
for LayerIndex := 1 to Group.LayerCount do
begin
FLN.Add(MFLayer_Group+LayerIndex);
FHC_List.Add(PreconsolidationHeadDataArray);
FSfe_List.Add(ElasticSkeletalStorageCoefficientDataArray);
FSfv_List.Add(InelasticSkeletalStorageCoefficientDataArray);
FCom_List.Add(InitialCompactionDataArray);
end;
end
else
begin
for LayerIndex := 1 to Group.LayerCount do
begin
if NoDelayItem.UsedLayers.GetItemByLayerNumber(LayerIndex) <> nil then
begin
FLN.Add(MFLayer_Group+LayerIndex);
FHC_List.Add(PreconsolidationHeadDataArray);
FSfe_List.Add(ElasticSkeletalStorageCoefficientDataArray);
FSfv_List.Add(InelasticSkeletalStorageCoefficientDataArray);
FCom_List.Add(InitialCompactionDataArray);
end;
end;
end;
end;
end;
for SubsidenceIndex := 0 to Group.SubDelayBedLayers.Count - 1 do
begin
DelayItem := Group.SubDelayBedLayers[SubsidenceIndex];
EquivNumberDataArray := Model.DataArrayManager.GetDataSetByName(
DelayItem.EquivNumberDataArrayName);
Assert(EquivNumberDataArray <> nil);
VerticalHydraulicConductivityDataArray := Model.DataArrayManager.GetDataSetByName(
DelayItem.VerticalHydraulicConductivityDataArrayName);
Assert(VerticalHydraulicConductivityDataArray <> nil);
ElasticSpecificStorageDataArray := Model.DataArrayManager.GetDataSetByName(
DelayItem.ElasticSpecificStorageDataArrayName);
Assert(ElasticSpecificStorageDataArray <> nil);
InelasticSpecificStorageDataArray := Model.DataArrayManager.GetDataSetByName(
DelayItem.InelasticSpecificStorageDataArrayName);
Assert(InelasticSpecificStorageDataArray <> nil);
InterbedStartingHeadDataArray := Model.DataArrayManager.GetDataSetByName(
DelayItem.InterbedStartingHeadDataArrayName);
if FSubPackage.ReadDelayRestartFileName = '' then
begin
Assert(InterbedStartingHeadDataArray <> nil);
end;
InterbedPreconsolidationHeadDataArray := Model.DataArrayManager.GetDataSetByName(
DelayItem.InterbedPreconsolidationHeadDataArrayName);
if FSubPackage.ReadDelayRestartFileName = '' then
begin
Assert(InterbedPreconsolidationHeadDataArray <> nil);
end;
InterbedStartingCompactionDataArray := Model.DataArrayManager.GetDataSetByName(
DelayItem.InterbedStartingCompactionDataArrayName);
Assert(InterbedStartingCompactionDataArray <> nil);
InterbedEquivalentThicknessDataArray := Model.DataArrayManager.GetDataSetByName(
DelayItem.InterbedEquivalentThicknessDataArrayName);
Assert(InterbedEquivalentThicknessDataArray <> nil);
if Group.LayerCount = 1 then
begin
FLDN.Add(MFLayer_Group+1);
FRNB_List.Add(EquivNumberDataArray);
FDelayVK_List.Add(VerticalHydraulicConductivityDataArray);
FDelayElasticSpecificStorage_List.Add(ElasticSpecificStorageDataArray);
FDelayInElasticSpecificStorage_List.Add(InelasticSpecificStorageDataArray);
FDstart_List.Add(InterbedStartingHeadDataArray);
FDHC_List.Add(InterbedPreconsolidationHeadDataArray);
FDCOM_List.Add(InterbedStartingCompactionDataArray);
FDZ_List.Add(InterbedEquivalentThicknessDataArray);
end
else
begin
if DelayItem.UseInAllLayers then
begin
for LayerIndex := 1 to Group.LayerCount do
begin
FLDN.Add(MFLayer_Group+LayerIndex);
FRNB_List.Add(EquivNumberDataArray);
FDelayVK_List.Add(VerticalHydraulicConductivityDataArray);
FDelayElasticSpecificStorage_List.Add(ElasticSpecificStorageDataArray);
FDelayInElasticSpecificStorage_List.Add(InelasticSpecificStorageDataArray);
FDstart_List.Add(InterbedStartingHeadDataArray);
FDHC_List.Add(InterbedPreconsolidationHeadDataArray);
FDCOM_List.Add(InterbedStartingCompactionDataArray);
FDZ_List.Add(InterbedEquivalentThicknessDataArray);
end;
end
else
begin
for LayerIndex := 1 to Group.LayerCount do
begin
if DelayItem.UsedLayers.GetItemByLayerNumber(LayerIndex) <> nil then
begin
FLDN.Add(MFLayer_Group+LayerIndex);
FRNB_List.Add(EquivNumberDataArray);
FDelayVK_List.Add(VerticalHydraulicConductivityDataArray);
FDelayElasticSpecificStorage_List.Add(ElasticSpecificStorageDataArray);
FDelayInElasticSpecificStorage_List.Add(InelasticSpecificStorageDataArray);
FDstart_List.Add(InterbedStartingHeadDataArray);
FDHC_List.Add(InterbedPreconsolidationHeadDataArray);
FDCOM_List.Add(InterbedStartingCompactionDataArray);
FDZ_List.Add(InterbedEquivalentThicknessDataArray);
end;
end;
end;
end;
end;
Inc(MFLayer_Group,Group.LayerCount);
end;
end;
Assert(FLN.Count = FHC_List.Count);
Assert(FLN.Count = FSfe_List.Count);
Assert(FLN.Count = FSfv_List.Count);
Assert(FLN.Count = FCom_List.Count);
Assert(FLDN.Count = FRNB_List.Count);
Assert(FLDN.Count = FDelayVK_List.Count);
Assert(FLDN.Count = FDelayElasticSpecificStorage_List.Count);
Assert(FLDN.Count = FDelayInElasticSpecificStorage_List.Count);
Assert(FLDN.Count = FDstart_List.Count);
Assert(FLDN.Count = FDCOM_List.Count);
Assert(FLDN.Count = FDZ_List.Count);
end;
procedure TModflowSUB_Writer.WriteDataSet1;
var
ISUBCB: Integer;
ISUBOC: Integer;
NNDB: Integer;
NDB: Integer;
NMZ: integer;
NN: integer;
AC1: Double;
AC2: Double;
ITMIN: Integer;
IDSAVE: Integer;
SaveRestartFileName: string;
IDREST: Integer;
ReadRestartFileName: string;
begin
GetFlowUnitNumber(ISUBCB);
ISUBOC := FSubPackage.PrintChoices.Count;
NNDB := Model.LayerStructure.NoDelayCount;
NDB := Model.LayerStructure.DelayCount;
NMZ := FDP_List.Count;
NN := FSubPackage.NumberOfNodes;
AC1 := FSubPackage.AccelerationParameter1;
AC2 := FSubPackage.AccelerationParameter2;
ITMIN := FSubPackage.MinIterations;
SaveRestartFileName := '';
if FSubPackage.SaveDelayRestart then
begin
IDSAVE := Model.UnitNumbers.UnitNumber(StrSUBSaveRestart);
SaveRestartFileName := ExtractFileName(ChangeFileExt(FNameOfFile, '.rst'));
WriteToNameFile(StrDATABINARY, IDSAVE,
SaveRestartFileName, foOutput, Model);
end
else
begin
IDSAVE := 0;
end;
if FSubPackage.ReadDelayRestartFileName = '' then
begin
IDREST := 0;
end
else
begin
IDREST := Model.UnitNumbers.UnitNumber(StrSUBReadRestart);
ReadRestartFileName := ExtractRelativePath(FNameOfFile,
FSubPackage.ReadDelayRestartFileName);
if SaveRestartFileName = ReadRestartFileName then
begin
frmErrorsAndWarnings.AddError(Model, StrRestartFileNamesI,
StrTheRestartFileSav);
end;
WriteToNameFile(StrDATABINARY, IDREST,
ReadRestartFileName, foInputAlreadyExists, Model, True);
end;
WriteInteger(ISUBCB);
WriteInteger(ISUBOC);
WriteInteger(NNDB);
WriteInteger(NDB);
WriteInteger(NMZ);
WriteInteger(NN);
WriteFloat(AC1);
WriteFloat(AC2);
WriteInteger(ITMIN);
WriteInteger(IDSAVE);
WriteInteger(IDREST);
WriteString(' # ISUBCB ISUBOC NNDB NDB NMZ NN AC1 AC2 ITMIN IDSAVE IDREST');
NewLine;
end;
procedure TModflowSUB_Writer.WriteDataSet15;
var
Ifm1: Integer;
Iun1: Integer;
AFileName: string;
Ifm2: Integer;
Iun2: Integer;
Ifm3: Integer;
Iun3: Integer;
Ifm4: Integer;
Iun4: Integer;
Ifm5: Integer;
Iun5: Integer;
Ifm6: Integer;
Iun6: Integer;
Index: Integer;
PrintChoice: TSubPrintItem;
Save1: Boolean;
Save2: Boolean;
Save3: Boolean;
Save4: Boolean;
Save5: Boolean;
Save6: Boolean;
SubFileName: string;
function GetCombinedUnitNumber: integer;
begin
result := Model.UnitNumbers.UnitNumber(StrSubSUB_Out);
if SubFileName = '' then
begin
SubFileName := ExtractFileName(ChangeFileExt(FNameOfFile, StrSubOut));
WriteToNameFile(StrDATABINARY, result,
SubFileName, foOutput, Model);
end;
end;
begin
if FSubPackage.PrintChoices.Count > 0 then
begin
Save1 := False;
Save2 := False;
Save3 := False;
Save4 := False;
Save5 := False;
Save6 := False;
for Index := 0 to FSubPackage.PrintChoices.Count - 1 do
begin
PrintChoice := FSubPackage.PrintChoices[Index];
Save1 := Save1 or PrintChoice.SaveSubsidence;
Save2 := Save2 or PrintChoice.SaveCompactionByModelLayer;
Save3 := Save3 or PrintChoice.SaveCompactionByInterbedSystem;
Save4 := Save4 or PrintChoice.SaveVerticalDisplacement;
Save5 := Save5 or PrintChoice.SaveCriticalHeadNoDelay;
Save6 := Save6 or PrintChoice.SaveCriticalHeadDelay;
if Save1 and Save2 and Save3 and Save4 and Save5 and Save6 then
begin
break;
end;
end;
Ifm1 := FSubPackage.PrintFormats.SubsidenceFormat+1;
SubFileName := '';
Iun1 := 0;
if Save1 then
begin
case FSubPackage.BinaryOutputChoice of
sbocSingleFile:
begin
Iun1 := GetCombinedUnitNumber;
end;
sbocMultipleFiles:
begin
Iun1 := Model.UnitNumbers.UnitNumber(StrSubSUB_Out);
AFileName := ExtractFileName(ChangeFileExt(FNameOfFile, StrSubSubOut));
WriteToNameFile(StrDATABINARY, Iun1,
AFileName, foOutput, Model);
end
else Assert(False);
end;
end;
Ifm2 := FSubPackage.PrintFormats.CompactionByModelLayerFormat+1;
Iun2 := 0;
if Save2 then
begin
case FSubPackage.BinaryOutputChoice of
sbocSingleFile:
begin
Iun2 := GetCombinedUnitNumber;
end;
sbocMultipleFiles:
begin
Iun2 := Model.UnitNumbers.UnitNumber(StrSubCOM_ML_Out);
AFileName := ExtractFileName(ChangeFileExt(FNameOfFile, StrSubComMlOut));
WriteToNameFile(StrDATABINARY, Iun2,
AFileName, foOutput, Model);
end
else Assert(False);
end;
end;
Ifm3 := FSubPackage.PrintFormats.CompactionByInterbedSystemFormat+1;
Iun3 := 0;
if Save3 then
begin
case FSubPackage.BinaryOutputChoice of
sbocSingleFile:
begin
Iun3 := GetCombinedUnitNumber;
end;
sbocMultipleFiles:
begin
Iun3 := Model.UnitNumbers.UnitNumber(StrSubCOM_IS_Out);
AFileName := ExtractFileName(ChangeFileExt(FNameOfFile, StrSubComIsOut));
WriteToNameFile(StrDATABINARY, Iun3,
AFileName, foOutput, Model);
end
else Assert(False);
end;
end;
Ifm4 := FSubPackage.PrintFormats.VerticalDisplacementFormat+1;
Iun4 := 0;
if Save4 then
begin
case FSubPackage.BinaryOutputChoice of
sbocSingleFile:
begin
Iun4 := GetCombinedUnitNumber;
end;
sbocMultipleFiles:
begin
Iun4 := Model.UnitNumbers.UnitNumber(StrSub_VD_Out);
AFileName := ExtractFileName(ChangeFileExt(FNameOfFile, StrSubVdOut));
WriteToNameFile(StrDATABINARY, Iun4,
AFileName, foOutput, Model);
end
else Assert(False);
end;
end;
Ifm5 := FSubPackage.PrintFormats.NoDelayPreconsolidationHeadFormat+1;
Iun5 := 0;
if Save5 then
begin
case FSubPackage.BinaryOutputChoice of
sbocSingleFile:
begin
Iun5 := GetCombinedUnitNumber;
end;
sbocMultipleFiles:
begin
Iun5 := Model.UnitNumbers.UnitNumber(StrSub_NDPCH_Out);
AFileName := ExtractFileName(ChangeFileExt(FNameOfFile, StrSubNdCritHeadOut));
WriteToNameFile(StrDATABINARY, Iun5,
AFileName, foOutput, Model);
end
else Assert(False);
end;
end;
Ifm6 := FSubPackage.PrintFormats.DelayPreconsolidationHeadFormat+1;
Iun6 := 0;
if Save6 then
begin
case FSubPackage.BinaryOutputChoice of
sbocSingleFile:
begin
Iun6 := GetCombinedUnitNumber;
end;
sbocMultipleFiles:
begin
Iun6 := Model.UnitNumbers.UnitNumber(StrSub_DPCH_Out);
AFileName := ExtractFileName(ChangeFileExt(FNameOfFile, StrSubDCritHeadOut));
WriteToNameFile(StrDATABINARY, Iun6,
AFileName, foOutput, Model);
end
else Assert(False);
end;
end;
WriteInteger(Ifm1);
WriteInteger(Iun1);
WriteInteger(Ifm2);
WriteInteger(Iun2);
WriteInteger(Ifm3);
WriteInteger(Iun3);
WriteInteger(Ifm4);
WriteInteger(Iun4);
WriteInteger(Ifm5);
WriteInteger(Iun5);
WriteInteger(Ifm6);
WriteInteger(Iun6);
WriteString(' # Ifm1 Iun1 Ifm2 Iun2 Ifm3 Iun3 Ifm4 Iun4 Ifm5 Iun5 Ifm6 Iun6');
NewLine;
end;
end;
procedure TModflowSUB_Writer.WriteDataSet16;
var
PrintChoice: TSubPrintItem;
ISP1, ISP2, ITS1, ITS2: integer;
PrintChoiceIndex: Integer;
Ifl1: Integer;
Ifl2: Integer;
Ifl3: Integer;
Ifl4: Integer;
Ifl5: Integer;
Ifl6: Integer;
Ifl7: Integer;
Ifl8: Integer;
Ifl9: Integer;
Ifl10: Integer;
Ifl11: Integer;
Ifl12: Integer;
Ifl13: Integer;
begin
FSubPackage.PrintChoices.ReportErrors;
for PrintChoiceIndex := 0 to FSubPackage.PrintChoices.Count -1 do
begin
PrintChoice := FSubPackage.PrintChoices[PrintChoiceIndex];
if PrintChoice.StartTime <= PrintChoice.EndTime then
begin
GetStartAndEndTimeSteps(ITS2, ISP2, ITS1, ISP1, PrintChoice);
Ifl1 := Ord(PrintChoice.PrintSubsidence);
Ifl2 := Ord(PrintChoice.SaveSubsidence);
Ifl3 := Ord(PrintChoice.PrintCompactionByModelLayer);
Ifl4 := Ord(PrintChoice.SaveCompactionByModelLayer);
Ifl5 := Ord(PrintChoice.PrintCompactionByInterbedSystem);
Ifl6 := Ord(PrintChoice.SaveCompactionByInterbedSystem);
Ifl7 := Ord(PrintChoice.PrintVerticalDisplacement);
Ifl8 := Ord(PrintChoice.SaveVerticalDisplacement);
Ifl9 := Ord(PrintChoice.PrintCriticalHeadNoDelay);
Ifl10 := Ord(PrintChoice.SaveCriticalHeadNoDelay);
Ifl11 := Ord(PrintChoice.PrintCriticalHeadDelay);
Ifl12 := Ord(PrintChoice.SaveCriticalHeadDelay);
Ifl13 := Ord(PrintChoice.PrintDelayBudgets);
WriteInteger(ISP1);
WriteInteger(ISP2);
WriteInteger(ITS1);
WriteInteger(ITS2);
WriteInteger(Ifl1);
WriteInteger(Ifl2);
WriteInteger(Ifl3);
WriteInteger(Ifl4);
WriteInteger(Ifl5);
WriteInteger(Ifl6);
WriteInteger(Ifl7);
WriteInteger(Ifl8);
WriteInteger(Ifl9);
WriteInteger(Ifl10);
WriteInteger(Ifl11);
WriteInteger(Ifl12);
WriteInteger(Ifl13);
WriteString(' # ISP1 ISP2 ITS1 ITS2 Ifl1 Ifl2 Ifl3 Ifl4 Ifl5 Ifl6 Ifl7 Ifl8 Ifl9 Ifl10 Ifl11 Ifl12 Ifl13');
NewLine;
end;
end;
end;
procedure TModflowSUB_Writer.WriteDataSet2;
var
Index: Integer;
begin
if FLN.Count = 0 then
begin
Exit;
end;
for Index := 0 to FLN.Count - 1 do
begin
WriteInteger(FLN[Index]);
end;
WriteString(' # LN');
NewLine;
end;
procedure TModflowSUB_Writer.WriteDataSet3;
var
Index: Integer;
begin
if FLDN.Count = 0 then
begin
Exit;
end;
for Index := 0 to FLDN.Count - 1 do
begin
WriteInteger(FLDN[Index]);
end;
WriteString(' # LDN');
NewLine;
end;
procedure TModflowSUB_Writer.WriteDataSet4;
var
Index: Integer;
DataArray: TDataArray;
begin
for Index := 0 to FRNB_List.Count - 1 do
begin
DataArray := FRNB_List[Index];
WriteArray(DataArray, 0, 'RNB', StrNoValueAssigned, 'RNB');
Model.DataArrayManager.AddDataSetToCache(DataArray);
end;
Model.DataArrayManager.CacheDataArrays;
end;
procedure TModflowSUB_Writer.WriteDataSet9;
var
MaterialZone: TMaterialZoneIdItem;
Index: Integer;
begin
if FDP_List.Count = 0 then
begin
Exit;
end;
for Index := 0 to FDP_List.Count - 1 do
begin
MaterialZone := FDP_List[Index];
WriteFloat(MaterialZone.FMaterialZoneValues.VerticalK);
WriteFloat(MaterialZone.FMaterialZoneValues.ElasticSpecificStorage);
WriteFloat(MaterialZone.FMaterialZoneValues.InelasticSpecificStorage);
WriteString(' # DP');
NewLine;
end;
end;
procedure TModflowSUB_Writer.WriteDataSets10to14;
var
Index: Integer;
DataArray: TDataArray;
begin
for Index := 0 to FDstart_List.Count - 1 do
begin
if FSubPackage.ReadDelayRestartFileName = '' then
begin
DataArray := FDstart_List[Index];
WriteArray(DataArray, 0, 'Dstart', StrNoValueAssigned, 'Dstart');
Model.DataArrayManager.AddDataSetToCache(DataArray);
DataArray := FDHC_List[Index];
WriteArray(DataArray, 0, 'DHC', StrNoValueAssigned, 'DHC');
Model.DataArrayManager.AddDataSetToCache(DataArray);
end;
DataArray := FDCOM_List[Index];
WriteArray(DataArray, 0, 'DCOM', StrNoValueAssigned, 'DCOM');
Model.DataArrayManager.AddDataSetToCache(DataArray);
DataArray := FDZ_List[Index];
WriteArray(DataArray, 0, 'DZ', StrNoValueAssigned, 'DZ');
Model.DataArrayManager.AddDataSetToCache(DataArray);
DataArray := FNZ_List[Index];
WriteArray(DataArray, 0, 'NZ', StrNoValueAssigned, 'NZ');
// This one isn't cached because it is temporary
end;
Model.DataArrayManager.CacheDataArrays;
end;
procedure TModflowSUB_Writer.WriteDataSets5to8;
var
Index: Integer;
DataArray: TDataArray;
begin
for Index := 0 to FHC_List.Count - 1 do
begin
DataArray := FHC_List[Index];
WriteArray(DataArray, 0, 'HC', StrNoValueAssigned, 'HC');
Model.DataArrayManager.AddDataSetToCache(DataArray);
DataArray := FSfe_List[Index];
WriteArray(DataArray, 0, 'Sfe', StrNoValueAssigned, 'Sfe');
Model.DataArrayManager.AddDataSetToCache(DataArray);
DataArray := FSfv_List[Index];
WriteArray(DataArray, 0, 'Sfv', StrNoValueAssigned, 'Sfv');
Model.DataArrayManager.AddDataSetToCache(DataArray);
DataArray := FCom_List[Index];
WriteArray(DataArray, 0, 'Com', StrNoValueAssigned, 'Com');
Model.DataArrayManager.AddDataSetToCache(DataArray);
end;
Model.DataArrayManager.CacheDataArrays;
end;
procedure TModflowSUB_Writer.WriteFile(const AFileName: string);
begin
FSubPackage := Package as TSubPackageSelection;
if not FSubPackage.IsSelected then
begin
Exit
end;
if Model.PackageGeneratedExternally(StrSUB) then
begin
Exit;
end;
frmErrorsAndWarnings.BeginUpdate;
try
frmErrorsAndWarnings.RemoveErrorGroup(Model, StrSubsidenceNotSuppo);
frmErrorsAndWarnings.RemoveErrorGroup(Model, StrRestartFileNamesI);
if Model is TChildModel then
begin
frmErrorsAndWarnings.AddError(Model, StrSubsidenceNotSuppo,
StrModelMuseDoesNotC);
end;
FNameOfFile := FileName(AFileName);
WriteToNameFile(StrSUB, Model.UnitNumbers.UnitNumber(StrSUB),
FNameOfFile, foInput, Model);
Evaluate;
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
OpenFile(FNameOfFile);
try
frmProgressMM.AddMessage(StrWritingSUBPackage);
WriteDataSet0;
frmProgressMM.AddMessage(StrWritingDataSet1);
WriteDataSet1;
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
frmProgressMM.AddMessage(StrWritingDataSet2);
WriteDataSet2;
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
frmProgressMM.AddMessage(StrWritingDataSet3);
WriteDataSet3;
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
frmProgressMM.AddMessage(StrWritingDataSet4);
WriteDataSet4;
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
frmProgressMM.AddMessage(StrWritingDataSets5to8);
WriteDataSets5to8;
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
frmProgressMM.AddMessage(StrWritingDataSet9);
WriteDataSet9;
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
frmProgressMM.AddMessage(StrWritingDataSets10to14);
WriteDataSets10to14;
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
frmProgressMM.AddMessage(StrWritingDataSet15);
WriteDataSet15;
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
frmProgressMM.AddMessage(StrWritingDataSet16);
WriteDataSet16;
Application.ProcessMessages;
if not frmProgressMM.ShouldContinue then
begin
Exit;
end;
finally
CloseFile;
end;
finally
frmErrorsAndWarnings.EndUpdate;
end;
end;
{ TMaterialZoneIdItem }
procedure TMaterialZoneIdItem.AssignID;
begin
ID := MaterialZoneValues.ID;
end;
constructor TMaterialZoneIdItem.Create;
begin
FNextSameID := nil;
end;
destructor TMaterialZoneIdItem.Destroy;
begin
NextSameID.Free;
inherited;
end;
procedure TMaterialZoneIdItem.SetMaterialZoneValues(const Value: TMaterialZone);
begin
FMaterialZoneValues := Value;
AssignID;
end;
{ TMaterialZoneList }
function TMaterialZoneList.AddRecord(
MaterialZone: TMaterialZone): TMaterialZoneIdItem;
var
LastResult: TMaterialZoneIdItem;
begin
result := FIdList.ByID[MaterialZone.ID] as TMaterialZoneIdItem;
if result = nil then
begin
result := TMaterialZoneIdItem.Create;
result.MaterialZoneValues := MaterialZone;
result.ZoneNumber := FMaterialZones.Add(result)+1;
FIdList.Add(result);
end
else
begin
LastResult := nil;
while Assigned(result) and (result.MaterialZoneValues <> MaterialZone) do
begin
LastResult := result;
result := result.NextSameID;
end;
if result = nil then
begin
result := TMaterialZoneIdItem.Create;
result.MaterialZoneValues := MaterialZone;
result.ZoneNumber := FMaterialZones.Add(result)+1;
LastResult.NextSameID := result;
end;
end;
end;
function TMaterialZoneList.Count: integer;
begin
result := FMaterialZones.Count;
end;
constructor TMaterialZoneList.Create;
begin
FMaterialZones:= TList.Create;
FIdList := TIDList.Create;
end;
destructor TMaterialZoneList.Destroy;
begin
FIdList.Free;
FMaterialZones.Free;
inherited;
end;
function TMaterialZoneList.GetItem(Index: integer): TMaterialZoneIdItem;
begin
result := FMaterialZones[Index];
end;
end.
|
unit M_smledt;
interface
uses WinTypes, WinProcs, Classes, Graphics, Forms, Controls, Buttons,
StdCtrls, ExtCtrls, FileCtrl, SysUtils, Dialogs;
type
TSmallTextEditor = class(TForm)
Memo: TMemo;
SpeedBar: TPanel;
SpeedButtonCOmmit: TSpeedButton;
SpeedButtonRollback: TSpeedButton;
SpeedButtonFont: TSpeedButton;
FontDialog1: TFontDialog;
SBHelp: TSpeedButton;
procedure FormActivate(Sender: TObject);
procedure SpeedButtonCOmmitClick(Sender: TObject);
procedure SpeedButtonRollbackClick(Sender: TObject);
procedure SpeedButtonFontClick(Sender: TObject);
procedure FormKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure SBHelpClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
TheFile : TFileName;
end;
var
SmallTextEditor: TSmallTextEditor;
implementation
{$R *.DFM}
procedure TSmallTextEditor.FormActivate(Sender: TObject);
begin
SmallTextEditor.Caption := 'WDFUSE Small Textfile Editor - ' + TheFile;
Memo.Lines.LoadFromFile(TheFile);
end;
procedure TSmallTextEditor.SpeedButtonCOmmitClick(Sender: TObject);
begin
Memo.Lines.SaveToFile(TheFile);
SmallTextEditor.Close;
end;
procedure TSmallTextEditor.SpeedButtonRollbackClick(Sender: TObject);
begin
SmallTextEditor.Close;
end;
procedure TSmallTextEditor.SpeedButtonFontClick(Sender: TObject);
begin
with FontDialog1 do
begin
Font := Memo.Font;
if Execute then
begin
Memo.Font := Font;
end;
end;
end;
procedure TSmallTextEditor.FormKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Shift = [] then
Case Key of
VK_F1 : Application.HelpJump('wdfuse_help_otherfiles');
VK_F2 : SpeedButtonCommitClick(NIL);
VK_ESCAPE : SpeedButtonRollbackClick(NIL);
end;
end;
procedure TSmallTextEditor.SBHelpClick(Sender: TObject);
begin
Application.HelpJump('wdfuse_help_otherfiles');
end;
end.
|
{ NAME: Jordan Millett
CLASS: Comp Sci 1
DATE: 9/15/2016
PURPOSE: This program will add two numbers from the user
and display the answer.
}
Program calculat;
uses
crt;
var
num1,num2,sum1,sum2,sum3,sum4,mystery:integer;
quot:real;
txtcolor:string;
begin {main}
Writeln('Green');
Writeln('Blue');
Writeln('Red');
Writeln('Yellow');
Write('What color do you want you text? ');
readln(txtcolor);
if txtcolor = 'Green' then
textcolor(green);
if txtcolor = 'Yellow' then
textcolor(yellow);
if txtcolor = 'yellow' then
textcolor(yellow);
if txtcolor = 'Blue' then
textcolor(blue);
if txtcolor = 'Red' then
textcolor(red);
if txtcolor = 'green' then
textcolor(green);
if txtcolor = 'blue' then
textcolor(blue);
if txtcolor = 'red' then
textcolor(red);
clrscr;
Write('Enter the first number : ');
readln(num1);
Write('Enter the second number : ');
readln(num2);
mystery:=num1 mod num2;
sum1:=num1 + num2;
sum2:=num1 - num2;
sum3:=num1 div num2;
quot:=num1 div num2;
sum4:=num1 * num2;
if num1 = 9 then
if num2 = 10 then
sum1:=21;
writeln(num1,' + ',num2,' = ',sum1);
writeln(num1,' - ',num2,' = ',sum2);
writeln(num1,' / ',num2,' = ',sum3);
writeln(num1,' / ',num2,' = ',quot);
writeln(num1,' * ',num2,' = ',sum4);
writeln(num1,' % ',num2,' = ',mystery);
readkey;
{Mod divides two numbers and returns only the remainder that is a whole number.}
{type some really cool code here}
end. {main}
|
//=============================================================================
// sgUtils.pas
//=============================================================================
//
// The Utils unit contains general utility routins that may be useful for games.
//
// Change History:
//
// Version 3:
// - 2010-12-15: Andrew : Created to take general functionality from Core
//=============================================================================
/// SwinGame's Utils contain a number of helper routines that can be useful in
/// general game development.
///
/// @module Utils
/// @static
unit sgUtils;
//=============================================================================
interface
uses sgTypes;
//=============================================================================
//----------------------------------------------------------------------------
// Library Version
//----------------------------------------------------------------------------
/// Retrieves a string representing the version of SwinGame that is executing.
/// This can be used to check that the version supports the features required
/// for your game.
///
/// @lib
function SwinGameVersion(): String;
//----------------------------------------------------------------------------
// Exception Notification/Message
//----------------------------------------------------------------------------
/// This function can be used to retrieve a message containing the details of
/// the last error that occurred in SwinGame.
///
/// @lib
function ExceptionMessage(): String;
/// This function tells you if an error occurred with the last operation in
/// SwinGame.
///
/// @lib
function ExceptionOccured(): Boolean;
//----------------------------------------------------------------------------
// Random
//----------------------------------------------------------------------------
/// Generates a random number between 0 and 1.
///
/// @lib
function Rnd() : Single; overload;
/// Generates a random integer up to (but not including) ubound. Effectively,
/// the ubound value specifies the number of random values to create.
///
/// @lib RndUpto
function Rnd(ubound: Longint): Longint; overload;
//----------------------------------------------------------------------------
// Delay / Framerate
//----------------------------------------------------------------------------
/// Returns the average framerate for the last 10 frames as an integer.
///
/// @returns The current average framerate
///
/// @lib
function GetFramerate(): Longint;
/// Gets the number of milliseconds that have passed. This can be used to
/// determine timing operations, such as updating the game elements.
///
/// @returns The number of milliseconds passed
///
/// @lib
function GetTicks(): Longword;
/// Puts the process to sleep for a specified number of
/// milliseconds. This can be used to add delays into your
/// game.
///
/// @param time - The number of milliseconds to sleep
///
/// Side Effects
/// - Delay before returning
///
/// @lib
procedure Delay(time: Longword);
/// Returns the calculated framerate averages, highest, and lowest values along with
/// the suggested rendering color.
///
/// @lib
/// @sn calculateFramerateAvg:%s high:%s low:%s color:%s
procedure CalculateFramerate(out average, highest, lowest: String; out textColor: Color);
//=============================================================================
implementation
uses
SysUtils, Math, Classes, //System
sgShared, sgTrace, sgInputBackend, //SwinGame shared library code
sgResources, sgGeometry, sgImages, sgGraphics, sgDriverTimer, sgInput, sgWindowManager; //SwinGame
//=============================================================================
type
// Details required for the Frames per second calculations.
FPSData = record
values: Array [0..59] of Single;
pos: Longint;
max, min, avg: Single;
ready: Boolean;
end;
var
_fpsData: FPSData;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//Used to initialise the Frame Per Second data structure.
procedure _InitFPSData();
var
i: Longint;
begin
{$IFDEF TRACE}
TraceEnter('sgUtils', '_InitFPSData');
{$ENDIF}
// clear the array of values
for i := Low(_fpsData.values) to High(_fpsData.values) do
_fpsData.values[i] := 0;
// zero the current insert position, and the loop count
_fpsData.pos := 0;
//_fpsData.loops := 0;
// set the moving range and average to sensitble defaults
_fpsData.max := 0;
_fpsData.min := 0;
_fpsData.avg := 0;
_fpsData.ready := false;
{$IFDEF TRACE}
TraceExit('sgUtils', '_InitFPSData');
{$ENDIF}
end;
//----------------------------------------------------------------------------
// Library Version
//----------------------------------------------------------------------------
function SwinGameVersion(): String;
begin
{$IFDEF TRACE}
TraceEnter('sgUtils', 'SwinGameVersion');
{$ENDIF}
result := DLL_VERSION;
{$IFDEF TRACE}
TraceExit('sgUtils', 'SwinGameVersion');
{$ENDIF}
end;
//----------------------------------------------------------------------------
// Exception Notification/Message
//----------------------------------------------------------------------------
function ExceptionMessage(): String;
begin
{$IFDEF TRACE}
TraceEnter('sgUtils', 'ExceptionMessage');
{$ENDIF}
result := ErrorMessage;
{$IFDEF TRACE}
TraceExit('sgUtils', 'ExceptionMessage', result);
{$ENDIF}
end;
function ExceptionOccured(): Boolean;
begin
{$IFDEF TRACE}
TraceEnter('sgUtils', 'ExceptionOccured');
{$ENDIF}
result := HasException;
{$IFDEF TRACE}
TraceExit('sgUtils', 'ExceptionOccured : ' + BoolToStr(result, true));
{$ENDIF}
end;
//----------------------------------------------------------------------------
// Delay / Framerate
//----------------------------------------------------------------------------
procedure Delay(time: Longword);
var
t: Longword;
begin
{$IFDEF TRACE}
TraceEnter('sgUtils', 'Delay');
{$ENDIF}
if time > 0 then
begin
if time < 50 then TimerDriver.Delay(time)
else
begin
for t := 1 to time div 50 do
begin
ProcessEvents();
if WindowCloseRequested() then exit;
TimerDriver.Delay(50);
end;
t := time mod 50;
if t > 0 then TimerDriver.Delay(t);
end;
end;
{$IFDEF TRACE}
TraceExit('sgUtils', 'Delay');
{$ENDIF}
end;
function GetTicks(): Longword;
begin
{$IFDEF TRACE}
TraceEnter('sgUtils', 'GetTicks');
{$ENDIF}
result := TimerDriver.GetTicks();
{$IFDEF TRACE}
TraceExit('sgUtils', 'GetTicks');
{$ENDIF}
end;
function GetFramerate(): Longint;
begin
{$IFDEF TRACE}
TraceEnter('sgUtils', 'GetFramerate');
{$ENDIF}
if _fpsData.avg = 0 then
result := 60
else
result := RoundInt(1000 / _fpsData.avg);
{$IFDEF TRACE}
TraceExit('sgUtils', 'GetFramerate');
{$ENDIF}
end;
procedure CalculateFramerate(out average, highest, lowest: String; out textColor: Color);
var
avg, hi, lo: Single;
begin
{$IFDEF TRACE}
TraceEnter('sgUtils', 'CalculateFramerate');
{$ENDIF}
if not _fpsData.ready then
begin
textColor := ColorBlue;
average :='??.?';
highest :='??.?';
lowest :='??.?';
{$IFDEF TRACE}
TraceExit('sgUtils', 'CalculateFramerate');
{$ENDIF}
exit;
end;
if _fpsData.avg = 0 then
avg := 9999
else
avg := (1000 / _fpsData.avg);
lo := (1000 / _fpsData.max);
hi := (1000 / _fpsData.min);
Str(avg:4:1, average);
Str(hi:4:1, highest);
Str(lo:4:1, lowest);
if avg < 10 then
textColor := ColorRed
else if avg < 50 then
textColor := ColorYellow
else
textColor := ColorGreen;
{$IFDEF TRACE}
TraceExit('sgUtils', 'CalculateFramerate');
{$ENDIF}
end;
procedure _UpdateFPSDataProc(delta: Longword);
function RunningAverage(var values: Array of Single; newValue: Longword; var pos: Longint): Single;
var
i: Longint;
sum: Double;
begin
{$IFDEF TRACE}
TraceEnter('sgUtils', '_UpdateFPSData');
{$ENDIF}
// insert the newValue as the position specified
values[pos] := newValue;
// calculate the sum for the average
sum := 0;
for i := Low(values) to High(values) do
sum := sum + values[i];
result := Single(sum / Length(values));
//Inc position index, and wrap-around to start if needed
pos := pos + 1;
if pos > High(values) then
begin
pos := Low(values);
if not _fpsData.ready then
begin
_fpsData.max := _fpsData.avg;
_fpsData.min := _fpsData.avg;
_fpsData.ready := True;
end;
end;
end;
begin
_fpsData.avg := RunningAverage(_fpsData.values, delta, _fpsData.pos);
if _fpsData.avg = 0.0 then _fpsData.avg := 0.01;
//Adjust the min/maxes
if _fpsData.ready then
begin
if _fpsData.avg > _fpsData.max then _fpsData.max := _fpsData.avg
else if _fpsData.avg < _fpsData.min then _fpsData.min := _fpsData.avg;
end;
{$IFDEF TRACE}
TraceExit('sgUtils', '_UpdateFPSData');
{$ENDIF}
end;
//----------------------------------------------------------------------------
// Random
//----------------------------------------------------------------------------
function Rnd() : Single; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgUtils', 'Rnd');
{$ENDIF}
result := Single(System.Random());
{$IFDEF TRACE}
TraceExit('sgUtils', 'Rnd');
{$ENDIF}
end;
function Rnd(ubound: Longint): Longint; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgUtils', 'Rnd');
{$ENDIF}
result := System.Random(ubound);
{$IFDEF TRACE}
TraceExit('sgUtils', 'Rnd');
{$ENDIF}
end;
//=============================================================================
initialization
begin
{$IFDEF TRACE}
TraceEnter('sgUtils', 'initialization');
{$ENDIF}
InitialiseSwinGame();
_InitFPSData();
_UpdateFPSData := @_UpdateFPSDataProc;
{$IFDEF TRACE}
TraceExit('sgUtils', 'initialization');
{$ENDIF}
end;
end.
|
unit uErrors;
interface
uses
System.SysUtils,
Dmitry.Utils.System
{$IFDEF PHOTODB}
,uTranslate
{$ENDIF}
;
const
CRYPT_RESULT_UNDEFINED = 0;
CRYPT_RESULT_OK = 1;
CRYPT_RESULT_FAILED_CRYPT = 2;
CRYPT_RESULT_FAILED_CRYPT_FILE = 3;
CRYPT_RESULT_FAILED_CRYPT_DB = 4;
CRYPT_RESULT_PASS_INCORRECT = 5;
CRYPT_RESULT_PASS_DIFFERENT = 6;
CRYPT_RESULT_ALREADY_CRYPT = 7;
CRYPT_RESULT_ALREADY_DECRYPTED = 8;
CRYPT_RESULT_ERROR_READING_FILE = 9;
CRYPT_RESULT_ERROR_WRITING_FILE = 10;
CRYPT_RESULT_FAILED_GENERAL_ERROR = 11;
CRYPT_RESULT_UNSUPORTED_VERSION = 12;
function DBErrorToString(ErrorCode: Integer): string;
implementation
function DBErrorToString(ErrorCode: Integer): string;
begin
{$IFnDEF PHOTODB}
Result := 'Error code is ' + IntToStr(ErrorCode);
{$ENDIF}
{$IFDEF PHOTODB}
case ErrorCode of
CRYPT_RESULT_UNDEFINED:
Result := TA('Result is undefined!', 'Errors');
CRYPT_RESULT_OK:
Result := TA('No errors', 'Errors');
CRYPT_RESULT_FAILED_CRYPT:
Result := TA('Failed to encrypt object!', 'Errors');
CRYPT_RESULT_FAILED_CRYPT_FILE:
Result := TA('Failed to encrypt file!', 'Errors');
CRYPT_RESULT_FAILED_CRYPT_DB:
Result := TA('Failed to encrypt collection item!', 'Errors');
CRYPT_RESULT_PASS_INCORRECT:
Result := TA('Password is incorrect!', 'Errors');
CRYPT_RESULT_PASS_DIFFERENT:
Result := TA('Passwords are different!', 'Errors');
CRYPT_RESULT_ALREADY_CRYPT:
Result := TA('Object is already encrypted!', 'Errors');
CRYPT_RESULT_ALREADY_DECRYPTED:
Result := TA('Object is already decrypted!', 'Errors');
CRYPT_RESULT_ERROR_READING_FILE:
Result := TA('Error reading from file!', 'Errors');
CRYPT_RESULT_ERROR_WRITING_FILE:
Result := TA('Error writing to file!', 'Errors');
CRYPT_RESULT_UNSUPORTED_VERSION:
Result := TA('Unsupported version of file!', 'Errors');
else
Result := FormatEx(TA('Error code is: {0}' , 'Errors'), [ErrorCode]);
end;
{$ENDIF}
end;
end.
|
unit uIMultiplier;
{$I ..\Include\IntXLib.inc}
interface
uses
uIntX,
uIntXLibTypes;
type
/// <summary>
/// Multiplier class interface.
/// </summary>
IIMultiplier = interface(IInterface)
['{9259DC7D-71A5-433A-A756-FD239C6F562F}']
/// <summary>
/// Multiplies two big integers.
/// </summary>
/// <param name="int1">First big integer.</param>
/// <param name="int2">Second big integer.</param>
/// <returns>Resulting big integer.</returns>
function Multiply(int1: TIntX; int2: TIntX): TIntX; overload;
/// <summary>
/// Multiplies two big integers represented by their digits.
/// </summary>
/// <param name="digits1">First big integer digits.</param>
/// <param name="length1">First big integer real length.</param>
/// <param name="digits2">Second big integer digits.</param>
/// <param name="length2">Second big integer real length.</param>
/// <param name="digitsRes">Where to put resulting big integer.</param>
/// <returns>Resulting big integer real length.</returns>
function Multiply(digits1: TIntXLibUInt32Array; length1: UInt32;
digits2: TIntXLibUInt32Array; length2: UInt32;
digitsRes: TIntXLibUInt32Array): UInt32; overload;
/// <summary>
/// Multiplies two big integers using pointers.
/// </summary>
/// <param name="digitsPtr1">First big integer digits.</param>
/// <param name="length1">First big integer length.</param>
/// <param name="digitsPtr2">Second big integer digits.</param>
/// <param name="length2">Second big integer length.</param>
/// <param name="digitsResPtr">Resulting big integer digits.</param>
/// <returns>Resulting big integer length.</returns>
function Multiply(digitsPtr1: PCardinal; length1: UInt32;
digitsPtr2: PCardinal; length2: UInt32; digitsResPtr: PCardinal)
: UInt32; overload;
end;
implementation
end.
|
unit uFrmPrincipal;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls,
uContinente, uPais, uMundo, uEnumContinente;
type
TFrmPrincipal = class(TForm)
Panel1: TPanel;
btnInserirContinente: TButton;
edtDimensao: TLabeledEdit;
edtPopulacao: TLabeledEdit;
edtNomePais: TLabeledEdit;
btnExibir: TButton;
btnInserirPais: TButton;
cmbContinente: TComboBox;
Label1: TLabel;
Memo1: TMemo;
procedure btnInserirContinenteClick(Sender: TObject);
procedure btnExibirClick(Sender: TObject);
procedure btnInserirPaisClick(Sender: TObject);
private
{ Private declarations }
oContinente : TContinente;
oMundo : TMundo;
procedure AdicionarPais;
procedure AdicionarContinente;
public
{ Public declarations }
end;
var
FrmPrincipal: TFrmPrincipal;
implementation
{$R *.dfm}
procedure TFrmPrincipal.AdicionarPais;
var
oPais : TPais;
begin
oPais := TPais.Create;
oPais.NomePais := edtNomePais.Text;
oPais.Populacao := StrToInt(edtPopulacao.Text);
oPais.Dimensao := StrToFloat(edtDimensao.Text);
oContinente.Adicionar(oPais);
end;
procedure TFrmPrincipal.btnInserirContinenteClick(Sender: TObject);
begin
AdicionarContinente;
end;
procedure TFrmPrincipal.btnInserirPaisClick(Sender: TObject);
begin
AdicionarPais;
end;
procedure TFrmPrincipal.btnExibirClick(Sender: TObject);
begin
Memo1.Lines.Add(oMundo.ToString);
end;
procedure TFrmPrincipal.AdicionarContinente;
begin
oMundo := TMundo.Create;
oContinente := TContinente.Create;
oContinente.Nome := tContinentes(cmbContinente.ItemIndex);
oMundo.AdicionarContinente(oContinente);
end;
end.
|
unit uDBBaseTypes;
interface
uses
Vcl.Menus;
type
TStringFunction = function: string;
TIntegerFunction = function: Integer;
TBooleanFunction = function: Boolean;
TPAnsiCharFunction = function: PAnsiChar;
TDllRegisterServer = function: HResult; stdcall;
//array types
type
TArMenuItem = array of TMenuItem;
TArInteger = array of Integer;
TArStrings = array of String;
TArBoolean = array of Boolean;
TArDateTime = array of TDateTime;
TArTime = array of TDateTime;
TArInteger64 = array of int64;
TArCardinal = array of Cardinal;
type
TBuffer = array of Char;
type
TProgressCallBackInfo = record
MaxValue : Int64;
Position : Int64;
Information : String;
Terminate : Boolean;
end;
TCallBackProgressEvent = procedure(Sender: TObject; var Info: TProgressCallBackInfo) of object;
type
TSimpleCallBackProgressRef = reference to procedure(Sender: TObject; Total, Value: Int64);
implementation
end.
|
unit MT5.Protocol;
interface
uses
MT5.Utils;
type
TMTHeaderProtocol = class
private
{ private declarations }
var
FSizeBody: Integer;
FFlag: Integer;
FNumberPacket: Integer;
protected
{ protected declarations }
public
{ public declarations }
const
HEADER_LENGTH = 9;
constructor Create(ASizeBody, ANumberPacket, AFlag: Integer);
property SizeBody: Integer read FSizeBody;
property NumberPacket: Integer read FNumberPacket;
property Flag: Integer read FFlag;
class function GetHeader(AHeaderData: TArray<Byte>): TMTHeaderProtocol;
end;
TMTProtocolConsts = class
const
WEB_CMD_AUTH_START = 'AUTH_START'; // begin of authorization on server
WEB_CMD_AUTH_ANSWER = 'AUTH_ANSWER'; // end of authorization on server
// --- config
WEB_CMD_COMMON_GET = 'COMMON_GET'; // get config
// --- time
WEB_CMD_TIME_SERVER = 'TIME_SERVER'; // get time of server
WEB_CMD_TIME_GET = 'TIME_GET'; // get config of times
// --- api
WEB_PREFIX_WEBAPI = 'MT5WEBAPI%04x%04x'; // format of package for api
WEB_PACKET_FORMAT = '%04x%04x'; // format of packages second or more request
WEB_API_WORD = 'WebAPI';
// ---
WEB_PARAM_VERSION = 'VERSION'; // version of authorization
WEB_PARAM_RETCODE = 'RETCODE'; // code answer
WEB_PARAM_LOGIN = 'LOGIN'; // login
WEB_PARAM_TYPE = 'TYPE'; // type of connection, type of data, type of operation
WEB_PARAM_AGENT = 'AGENT'; // agent name
WEB_PARAM_SRV_RAND = 'SRV_RAND'; // server random string
WEB_PARAM_SRV_RAND_ANSWER = 'SRV_RAND_ANSWER'; // answer on server random string
WEB_PARAM_CLI_RAND = 'CLI_RAND'; // client's random string
WEB_PARAM_CLI_RAND_ANSWER = 'CLI_RAND_ANSWER'; // answer to clients random string
WEB_PARAM_TIME = 'TIME'; // time param
WEB_PARAM_TOTAL = 'TOTAL'; // total
WEB_PARAM_INDEX = 'INDEX'; // index
WEB_PARAM_GROUP = 'GROUP'; // group
WEB_PARAM_SYMBOL = 'SYMBOL'; // symbol
WEB_PARAM_NAME = 'NAME'; // name
WEB_PARAM_COMPANY = 'COMPANY'; // company
WEB_PARAM_LANGUAGE = 'LANGUAGE'; // language (LANGID)
WEB_PARAM_COUNTRY = 'COUNTRY'; // country
WEB_PARAM_CITY = 'CITY'; // city
WEB_PARAM_STATE = 'STATE'; // state
WEB_PARAM_ZIPCODE = 'ZIPCODE'; // zipcode
WEB_PARAM_ADDRESS = 'ADDRESS'; // address
WEB_PARAM_PHONE = 'PHONE'; // phone
WEB_PARAM_EMAIL = 'EMAIL'; // email
WEB_PARAM_ID = 'ID'; // id
WEB_PARAM_STATUS = 'STATUS'; // status
WEB_PARAM_COMMENT = 'COMMENT'; // comment
WEB_PARAM_COLOR = 'COLOR'; // color
WEB_PARAM_PASS_MAIN = 'PASS_MAIN'; // main password
WEB_PARAM_PASS_INVESTOR = 'PASS_INVESTOR'; // invest paswword
WEB_PARAM_PASS_API = 'PASS_API'; // API password
WEB_PARAM_PASS_PHONE = 'PASS_PHONE'; // phone password
WEB_PARAM_LEVERAGE = 'LEVERAGE'; // leverage
WEB_PARAM_RIGHTS = 'RIGHTS'; // rights
WEB_PARAM_BALANCE = 'BALANCE'; // balance
WEB_PARAM_PASSWORD = 'PASSWORD'; // password
WEB_PARAM_TICKET = 'TICKET'; // ticket
WEB_PARAM_OFFSET = 'OFFSET'; // offset for page requests
WEB_PARAM_FROM = 'FROM'; // from time
WEB_PARAM_TO = 'TO'; // to time
WEB_PARAM_TRANS_ID = 'TRANS_ID'; // trans id
WEB_PARAM_SUBJECT = 'SUBJECT'; // subject
WEB_PARAM_CATEGORY = 'CATEGORY'; // category
WEB_PARAM_PRIORITY = 'PRIORITY'; // priority
WEB_PARAM_BODYTEXT = 'BODY_TEXT'; // big text
WEB_PARAM_CHECK_MARGIN = 'CHECK_MARGIN'; // check margin
// --- crypt
WEB_PARAM_CRYPT_METHOD = 'CRYPT_METHOD'; // method of crypt
WEB_PARAM_CRYPT_RAND = 'CRYPT_RAND'; // random string for crypt
// --- group
WEB_CMD_GROUP_TOTAL = 'GROUP_TOTAL'; // get count groups
WEB_CMD_GROUP_NEXT = 'GROUP_NEXT'; // get next group
WEB_CMD_GROUP_GET = 'GROUP_GET'; // get info about group
WEB_CMD_GROUP_ADD = 'GROUP_ADD'; // group add
WEB_CMD_GROUP_DELETE = 'GROUP_DELETE'; // group delete
// --- symbols
WEB_CMD_SYMBOL_TOTAL = 'SYMBOL_TOTAL'; // get count symbols
WEB_CMD_SYMBOL_NEXT = 'SYMBOL_NEXT'; // get next symbol
WEB_CMD_SYMBOL_GET = 'SYMBOL_GET'; // get info about symbol
WEB_CMD_SYMBOL_GET_GROUP = 'SYMBOL_GET_GROUP'; // get info about symbol group
WEB_CMD_SYMBOL_ADD = 'SYMBOL_ADD'; // symbol add
WEB_CMD_SYMBOL_DELETE = 'SYMBOL_DELETE'; // symbol delete
// --- user
WEB_CMD_USER_ADD = 'USER_ADD'; // add new user
WEB_CMD_USER_UPDATE = 'USER_UPDATE'; // update user
WEB_CMD_USER_DELETE = 'USER_DELETE'; // delete user
WEB_CMD_USER_GET = 'USER_GET'; // get user information
WEB_CMD_USER_PASS_CHECK = 'USER_PASS_CHECK'; // user check
WEB_CMD_USER_PASS_CHANGE = 'USER_PASS_CHANGE'; // password change
WEB_CMD_USER_ACCOUNT_GET = 'USER_ACCOUNT_GET'; // account info get
WEB_CMD_USER_USER_LOGINS = 'USER_LOGINS'; // users logins get
// --- password type
WEB_VAL_USER_PASS_MAIN = 'MAIN';
WEB_VAL_USER_PASS_INVESTOR = 'INVESTOR';
WEB_VAL_USER_PASS_API = 'API';
// --- crypts
WEB_VAL_CRYPT_NONE = 'NONE';
WEB_VAL_CRYPT_AES256OFB = 'AES256OFB';
// --- trade command
WEB_CMD_USER_DEPOSIT_CHANGE = 'USER_DEPOSIT_CHANGE'; // deposit change
// --- work with order
WEB_CMD_ORDER_GET = 'ORDER_GET'; // get order
WEB_CMD_ORDER_GET_TOTAL = 'ORDER_GET_TOTAL'; // get count orders
WEB_CMD_ORDER_GET_PAGE = 'ORDER_GET_PAGE'; // get order from history
// --- work with position
WEB_CMD_POSITION_GET = 'POSITION_GET'; // get position
WEB_CMD_POSITION_GET_TOTAL = 'POSITION_GET_TOTAL'; // get count positions
WEB_CMD_POSITION_GET_PAGE = 'POSITION_GET_PAGE'; // get positions
// --- work with deal
WEB_CMD_DEAL_GET = 'DEAL_GET'; // get deal
WEB_CMD_DEAL_GET_TOTAL = 'DEAL_GET_TOTAL'; // get count deals
WEB_CMD_DEAL_GET_PAGE = 'DEAL_GET_PAGE'; // get list of deals
// --- work with history
WEB_CMD_HISTORY_GET = 'HISTORY_GET'; // get history
WEB_CMD_HISTORY_GET_TOTAL = 'HISTORY_GET_TOTAL'; // get count of history order
WEB_CMD_HISTORY_GET_PAGE = 'HISTORY_GET_PAGE'; // get list of history
// --- work with ticks
WEB_CMD_TICK_LAST = 'TICK_LAST'; // get tick
WEB_CMD_TICK_LAST_GROUP = 'TICK_LAST_GROUP'; // get tick by group name
WEB_CMD_TICK_STAT = 'TICK_STAT'; // tick stat
// --- mail
WEB_CMD_MAIL_SEND = 'MAIL_SEND';
// --- news
WEB_CMD_NEWS_SEND = 'NEWS_SEND';
// --- ping
WEB_CMD_PING = 'PING';
// --- trade
WEB_CMD_TRADE_BALANCE = 'TRADE_BALANCE';
// --- server restart
WEB_CMD_SERVER_RESTART = 'SERVER_RESTART';
end;
implementation
uses
System.SysUtils, System.Classes;
{ TMTHeaderProtocol }
constructor TMTHeaderProtocol.Create(ASizeBody, ANumberPacket, AFlag: Integer);
begin
FSizeBody := ASizeBody;
FFlag := AFlag;
FNumberPacket := ANumberPacket;
end;
class function TMTHeaderProtocol.GetHeader(AHeaderData: TArray<Byte>): TMTHeaderProtocol;
var
LSizeBody: Integer;
LNumberPacket: Integer;
LFlag: Integer;
LMTHeaderProtocol: TMTHeaderProtocol;
begin
Result := nil;
if (Length(AHeaderData) < HEADER_LENGTH) then
Exit(nil);
try
LSizeBody := TMTUtils.HexToInt((TMTUtils.BytesToStr(Copy(AHeaderData, 0, 4))));
LNumberPacket := TMTUtils.HexToInt((TMTUtils.BytesToStr(Copy(AHeaderData, 4, 4)))); // TMTUtils.HexToInt(TEncoding.ASCII.GetString(AHeaderData, 4, 4));
LFlag := TMTUtils.HexToInt((TMTUtils.BytesToStr(Copy(AHeaderData, 8, 1)))); // Ord(TEncoding.ASCII.GetString(AHeaderData, 8, 1).Chars[0]);
LMTHeaderProtocol := TMTHeaderProtocol.Create(LSizeBody, LNumberPacket, LFlag);
Result := LMTHeaderProtocol;
except
end;
end;
end.
|
{-----------------------------------------------------------------------------
Miguel A. Risco Castillo TuESelector v0.3
http://ue.accesus.com/uecontrols
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/MPL-1.1.html
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for
the specific language governing rights and limitations under the License.
-----------------------------------------------------------------------------}
unit uESelector;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, ExtCtrls,
LCLIntf, LCLType, LCLProc, Types,
BGRABitmap, BGRABitmapTypes, uEKnob;
type
{ TCustomuESelector }
TCustomuESelector = class(TCustomuEKnob)
private
FIndex: Integer;
FItems: TStringList;
procedure SetIndex(const AValue: Integer);
procedure SetItems(const AValue: TStringList);
protected
procedure ItemsChanged(Sender:TObject); virtual;
procedure DefaultPicture; override;
procedure ForcePosition(const AValue: Real); override;
property Index: Integer read FIndex write SetIndex;
property Items: TStringList read FItems write SetItems;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure DrawScales(LBitmap:TBGRABitmap); override;
end;
TuESelector = class(TCustomuESelector)
published
property MaxAngle;
property MinAngle;
property Picture;
property Index;
property Items;
property LTicksSize;
property LTicksColor;
property TicksMargin;
property ShowValues;
property ValuesMargin;
property ValuesFont;
property Transparent;
property OnChange;
property OnPaint;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
//
property Align;
property Anchors;
property BorderSpacing;
property Color;
property Constraints;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property ParentColor;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property Visible;
property OnChangeBounds;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseWheel;
property OnMouseWheelDown;
property OnMouseWheelUp;
property OnClick;
property OnConstrainedResize;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnResize;
property OnStartDock;
property OnStartDrag;
end;
procedure Register;
implementation
procedure TCustomuESelector.SetIndex(const AValue: Integer);
begin
if FIndex=AValue then exit;
FIndex:=AValue;
ForcePosition(AValue);
end;
procedure TCustomuESelector.SetItems(const AValue: TStringList);
begin
if FItems.Equals(AValue) then exit;
if AValue.Count>2 then FItems.Assign(AValue);
end;
procedure TCustomuESelector.DefaultPicture;
const ks=34;
var
TempBitmap: TBitmap;
c:real;
begin
c:=(ks-1)/2;
TempBitmap := TBitmap.Create;
Bitmap.SetSize(ks,ks);
Bitmap.Fill(BGRAPixelTransparent);
Bitmap.FillEllipseAntialias(c,c,c,c,BGRABlack);
Bitmap.GradientFill(0,0,ks,ks,
BGRA(128,128,128,255),BGRA(0,0,0,0),
gtRadial,PointF(c,c),PointF(0,c),
dmDrawWithTransparency);
Bitmap.FillRectAntialias(c-5,0,c+5,ks,BGRABlack);
Bitmap.DrawLineAntialias(c,c+5,c,ks-5,BGRAWhite,2);
try
TempBitmap.PixelFormat:=pf32bit;
TempBitmap.SetSize(ks,ks);
With TempBitmap
do begin
Transparent:=true;
TransparentColor:=clLime;
Canvas.Brush.Color:=clLime;
Canvas.FillRect(Canvas.ClipRect);
end;
Bitmap.Draw(TempBitmap.Canvas,0,0,true);
Picture.Assign(TempBitmap);
Picture.Graphic.Transparent:=true;
finally
TempBitmap.Free;
end;
end;
procedure TCustomuESelector.ItemsChanged(Sender: TObject);
begin
FLTicks:=FItems.Count;
FMax:=FItems.Count-1;
ForcePosition(FIndex);
UpdateScales;
invalidate;
end;
constructor TCustomuESelector.Create(AOwner: TComponent);
begin
FItems:=TStringList.Create;
FItems.Add('S1=10');
FItems.Add('S2=20');
FItems.Add('S3=30');
FItems.Add('S4=40');
FItems.Add('S5=50');
FItems.Add('S6=60');
FItems.Add('S7=70');
inherited Create(AOwner);
FMax:=6;
FMin:=0;
FValuesMargin:=10;
FLTicksSize:=5;
FIndex:=0;
FItems.OnChange := @ItemsChanged;
end;
destructor TCustomuESelector.Destroy;
begin
FItems.OnChange:=nil;
FreeAndNil(FItems);
inherited Destroy;
end;
procedure TCustomuESelector.DrawScales(LBitmap: TBGRABitmap);
var i:integer;
x1,y1,x2,y2,lpos:real;
xc,yc,langle:real;
sn,cn:real;
lc,vc:TBGRAPixel;
ts:TSize;
la:string;
begin
xc:=LBitmap.Width/2-1;
yc:=LBitmap.Height/2-1;
lc:=ColorToBGRA(ColorToRGB(FLTicksColor));
vc:=ColorToBGRA(ColorToRGB(FValuesFont.Color));
LBitmap.FontHeight:=abs(FValuesFont.Height);
LBitmap.FontStyle:=FValuesFont.Style;
LBitmap.FontName:=FValuesFont.Name;
LBitmap.FontOrientation:=FValuesFont.Orientation;
if FItems.Count>0 then For i:=0 to FItems.Count-1 do
begin
lpos:=(i/(FItems.Count-1))*(FMax-FMin)+FMin;
langle:=PosToAngle(lpos)*PI/1800 +PI/2;
sn:=sin(langle);
cn:=cos(langle);
x1:=xc+FTicksMargin*cn;
y1:=yc+FTicksMargin*sn;
x2:=xc+(FTicksMargin+FLTicksSize)*cn;
y2:=yc+(FTicksMargin+FLTicksSize)*sn;
if FLTicksSize>0 then LBitmap.DrawLineAntialias(x1,y1,x2,y2,lc, 1);
if FShowValues then
begin
la:=FItems.Names[i];
if la='' then la:=FItems.ValueFromIndex[i];
ts:=LBitmap.TextSize(la);
x2:=xc+(FTicksMargin+FLTicksSize+FValuesMargin+ts.cx/8)*cn;
y2:=yc+(FTicksMargin+FLTicksSize+FValuesMargin)*sn-ts.cy/2;
LBitmap.TextOut(round(x2), round(y2), la, vc, taCenter);
end;
end;
end;
procedure TCustomuESelector.ForcePosition(const AValue: Real);
var lastindex:integer;
begin
if AValue<FMin then FPosition:=FMin
else if AValue>FMax then FPosition:=FMax
else FPosition:=AValue;
lastindex:=FIndex;
FIndex:=round(FPosition);
Angle:=PostoAngle(FIndex)/10;
if FIndex<>lastindex then DoOnChange;
end;
procedure Register;
begin
{$I ueselector_icon.lrs}
RegisterComponents('uEControls', [TuESelector]);
end;
end.
|
unit Passw;
{ Скомпонован и дописан 13.10.2004
Предоставляет две функции типа Boolean:
- IsPasswordValid проверяет является ли аргумент p_Password валидным паролем
типа p_Type с параметрами p_Options.
- TestPassword высвечивает окошко для ввода пароля и проверяет его на валидность
в соответствии с типом p_Type и параметрами p_Options
ВНИМАНИЕ РАЗРАБОТЧИКАМ!!!
При появлении нового типа пароля поступить нужно следующим образом:
1. Добавить в тип TOilPasswordType константу, которая соответствует новому типу
2. Добавить в функцию IsPasswordValid часть, которая проверяет новый тип пароля.
Если эта часть занимает много строк, вынести в отдельную функцию, которую не
вписывать в интерфейсную часть.
3. В функцию TestPassword изменений вносить не нужно.
Заранее спасибо за следование этим правилам.
(Ю.Должиков)
}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, StdCtrls, Buttons, uCrypt, uCommonForm,uOilQuery,Ora, uOilStoredProc;
type
TPasswForm = class(TCommonForm)
Panel1: TPanel;
btnOk: TBitBtn;
btnCancel: TBitBtn;
Panel2: TPanel;
Image1: TImage;
edit1: TEdit;
procedure FormShow(Sender: TObject);
procedure edit1KeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
public
{ Public declarations }
end;
var
PasswForm: TPasswForm;
function IsPasswordValid(
p_Password: string;
p_Type: TOilPasswordType;
p_Options: string=''): Boolean;
function TestPassword(
p_Type: TOilPasswordType;
p_Options: string=''): Boolean;
implementation
{$R *.DFM}
uses Main,ExFunc,uDbFunc;
//==============================================================================
// Функция проверяет пароль на валидность
//------------------------------------------------------------------------------
function IsPasswordValid(
p_Password: string;
p_Type: TOilPasswordType;
p_Options: string=''): Boolean;
var
s: string;
Last_run_date: TDateTime;
begin
Last_run_date := StrToDateTime(ReadOilVar('Last_run_date'));
case p_Type of
pwtOrg,pwtWagon: result:=p_Password=GetPassword(p_Type,[Trunc(Last_run_date), INST]);
pwtPart:
result:=p_Password=GetSqlValue(
'select password from adm_users where login = ''admin''');
pwtTestLaunch :
begin
s :=GetPassword(
pwtTestLaunch,
[Main.CheckupStatus.ErrBlock, Main.INST, Last_run_date, p_Options]
);
Result := s =p_password;
end;
end;
end;
//==============================================================================
function TestPassword(
p_Type: TOilPasswordType;
p_Options: string=''): Boolean;
var
F: TPasswForm;
begin
Application.CreateForm(TPasswForm,F);
result := false;
repeat
F.ShowModal;
if F.ModalResult=mrOk then begin
result:=IsPasswordValid(F.edit1.Text,p_Type,p_Options);
if not result then showmessage(TranslateText('Неверный пароль!'));
end;
until result or (F.ModalResult=mrCancel);
F.Free;
end;
//==============================================================================
procedure TPasswForm.FormShow(Sender: TObject);
begin
Edit1.SetFocus;
end;
//==============================================================================
procedure TPasswForm.edit1KeyPress(Sender: TObject; var Key: Char);
begin
if Key=#13 then btnOk.Click;
end;
end.
|
unit IntXZeroandOneTest;
interface
uses
DUnitX.TestFramework,
uIntX;
type
[TestFixture]
TTIntXZeroandOneTest = class(TObject)
public
[Test]
procedure IsCustomTIntXZeroEqualToZero();
[Test]
procedure IsCustomTIntXZeroEqualToNegativeZero();
[Test]
procedure IsCustomTIntXZeroEqualToNegativeZero2();
[Test]
procedure IsCustomTIntXOneEqualToOne();
end;
implementation
[Test]
procedure TTIntXZeroandOneTest.IsCustomTIntXZeroEqualToZero();
var
int1: TIntX;
begin
int1 := TIntX.Create(0);
Assert.IsTrue(int1 = TIntX.Zero);
Assert.IsTrue(int1 = 0);
end;
[Test]
procedure TTIntXZeroandOneTest.IsCustomTIntXZeroEqualToNegativeZero();
var
int1: TIntX;
begin
int1 := TIntX.Create(-0);
Assert.IsTrue(int1 = TIntX.Zero);
Assert.IsTrue(int1 = 0);
end;
[Test]
procedure TTIntXZeroandOneTest.IsCustomTIntXZeroEqualToNegativeZero2();
var
int1: TIntX;
begin
int1 := TIntX.Create('-0');
Assert.IsTrue(int1 = TIntX.Zero);
Assert.IsTrue(int1 = 0);
end;
[Test]
procedure TTIntXZeroandOneTest.IsCustomTIntXOneEqualToOne();
var
int1: TIntX;
begin
int1 := TIntX.Create(1);
Assert.IsTrue(int1 = TIntX.One);
Assert.IsTrue(int1 = 1);
end;
initialization
TDUnitX.RegisterTestFixture(TTIntXZeroandOneTest);
end.
|
unit OpenSSL.DSAUtilsTests;
interface
uses
TestFramework, OpenSSL.Api_11, OpenSSL.DSAUtils, System.SysUtils, System.Classes,
OpenSSL.Core;
type
TDSAUtilTest = class(TTestCase)
strict private
FDSAUtil: TDSAUtil;
private
function LoadBufferFromFile(const AFile: string): TBytes;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestSignVerifyBuffer;
procedure TestSignVerifyFile;
end;
implementation
{ TDSAUtilTest }
function TDSAUtilTest.LoadBufferFromFile(const AFile: string): TBytes;
begin
with TFileStream.Create(AFile, fmOpenRead or fmShareDenyWrite) do
try
SetLength(Result, Size);
Position := 0;
ReadBuffer(Pointer(Result)^, Size);
finally
Free;
end;
end;
procedure TDSAUtilTest.SetUp;
begin
inherited;
FDSAUtil := TDSAUtil.Create;
end;
procedure TDSAUtilTest.TearDown;
begin
inherited;
FreeAndNil(FDSAUtil);
end;
procedure TDSAUtilTest.TestSignVerifyBuffer;
var
B, D, S: TBytes;
F: string;
begin
F := GetModuleName(HInstance);
D := LoadBufferFromFile(F);
B := LoadBufferFromFile('..\TestData\dsa_priv.pem');
FDSAUtil.PrivateKey.LoadFromBuffer(B);
S := FDSAUtil.PrivateSign(D);
B := LoadBufferFromFile('..\TestData\dsa_pub.pem');
FDSAUtil.PublicKey.LoadFromBuffer(B);
FDSAUtil.PublicVerify(D, S);
end;
procedure TDSAUtilTest.TestSignVerifyFile;
var
F, S: string;
begin
F := GetModuleName(HInstance);
S := F + '.sig';
FDSAUtil.PrivateKey.LoadFromFile('..\TestData\dsa_priv.pem');
FDSAUtil.PrivateSign(F, S);
FDSAUtil.PublicKey.LoadFromFile('..\TestData\dsa_pub.pem');
FDSAUtil.PublicVerify(F, S);
end;
initialization
// Register any test cases with the test runner
RegisterTest(TDSAUtilTest.Suite);
end.
|
unit WORKAR; {Protsedura Workaround, u yakiy pryvedenyy alhorytm z neobkhidnymy metodamy obkhoda}
interface
uses GLOBAL; {Opysannya dostupnoyi informatsiyi dlya yinshykh moduliv}
procedure WORKAR1711(var A: arr); {Alhorytm "vstavka – obmin" z vykorystannyam dodatkovoho masyvu}
procedure WORKAR1712(var A: arr); {Alhorytm "vstavka-obmin" z vykorystannyam elementiv "uyavnoho" vektora}
procedure WORKAR1713(var A: arr); {Alhorytm "vstavka-obmin", zdiysnyuyuchy obkhid bezposeredn'o po elementakh zadanoho masyvu}
procedure SortVector(var C: vector); {Alhorytm "vstavka – obmin" sortuvannya vektora}
implementation
procedure WORKAR1711(var a: arr);{Alhorytm "vstavka – obmin" z vykorystannyam dodatkovoho masyvu}
var ii, k, j, i, B:integer; {ii: koordynata odnovymirnoho masyvu; k,i,j: koordynaty 3-vymirnoho masyvu; B-dodatkova komirka}
Z:vector; {Dodatkovyy odnovymirnyy masyv}
begin
for k:=1 to p do {Lichyl'nyky prokhodu po koordynatam 3-vymirnoho masyvu}
begin
ii:=1;
for i := 1 to m do
for j := 1 to n do
begin
Z[ii] := a[k, i, j]; {Perepysuvannya elementiv dvovymirnoho masyvu do odnovymirnoho}
inc(ii);{Pislya kozhnoho prokhodu lichyl'nyka, kordynata odnovymirnoho masyvu ii zbil'shuyet'sya na 1}
end;
for i:=2 to (n*m) do {Prokhid po odnovymirnomu masyvu}
begin
j:=i;
while (j>1) and (Z[j]<Z[j-1]) do {Pochynayet'sya robota bezposeredn'o hibrydnoho alhorytmu "vstavka – obmin"}
begin
B:=Z[j]; {Zmina elementiv mistsyamy}
Z[j]:=Z[j-1];
Z[j-1]:=B;
j:=j-1;
end;
end;
ii := 1;
for i := 1 to m do {Lichyl'nyky prokhodu po koordynatam 2-vymirnoho masyvu}
for j := 1 to n do
begin
a[k, i, j]:= Z[ii]; {Perepysuvannya elementiv odnovymirnoho masyvu do dvovymirnoho}
inc(ii); {Pislya kozhnoho prokhodu lichyl'nyka, kordynata odnovymirnoho masyvu ii zbil'shuyet'sya na 1}
end;
end;
end;
procedure WORKAR1712(var a: arr); {Alhorytm "vstavka-obmin" z vykorystannyam elementiv "uyavnoho" vektora}
var k,j, i, B:integer; {k,i,j: koordynaty 3-vymirnoho masyvu; B-dodatkova komirka pam"yati}
begin
for k:=1 to p do {Lichyl'nyky prokhodu po pererizam 3-vymirnoho masyvu}
for i:=2 to (n*m) do {Lichyl'nyky prokhodu po uyavnomu vektoru}
begin
j:=i;
while (j>1) and (A[k,((j-1) div n)+1,((j-1) mod n)+1]<A[k,((j-2) div n)+1,((j-2) mod n)+1]) do {Formula perevedennya}
begin
B:=A[k,((j-1) div n)+1,((j-1) mod n)+1]; {Zmina elementiv mistsyamy}
A[k,((j-1) div n)+1,((j-1) mod n)+1]:=A[k,((j-2) div n)+1,((j-2) mod n)+1];
A[k,((j-2) div n)+1,((j-2) mod n)+1]:=B;
j:=j-1;
end;
end;
end;
procedure WORKAR1713(var a: arr); {Alhorytm "vstavka-obmin", zdiysnyuyuchy obkhid bezposeredn'o po elementakh zadanoho masyvu}
var
i, j, k, Z, H, f,g, B: integer; {k,i,j: koordynaty masyvu; B-dodatkova komirka pam"yati; Z, H, f, g: dodatkovi zminni}
begin
for k:=1 to p do {Lichyl'nyk prokhodu po pererizam 3-vymirnoho masyvu}
for i:=1 to m do {Lichyl'nyky prokhodu po koordynatam pererizu}
for j:=1 to n do
begin
Z:=i; H:=j; {Kopiyuvannya koordynat elementa, dlya mozhlyvosti yikh zminy}
if H<>1 then {perevirka na pershist' elementa u ryadku}
begin
f:=Z; g:=H-1; {Vidbuvayet'sya perekhid elementiv koordynat g,f na susidniy element zliva}
end
else
begin
f:=Z-1; g:=n;{Vidbuvayet'sya perekhid koordynat g,f na ostanniy element poperedn'oho ryadka}
end;
while (H>=1) and (f>=1) and (A[k,Z,H]<A[k,f,g]) do {Perevirka za umovoyu alhorytmu; H,f- perevirka vykhodu za ramky }
begin
B:=A[k,Z,H]; {Zmina elementiv mistsyamy}
A[k,Z,H]:=A[k,f,g];
A[k,f,g]:=B;
dec(H); dec(g); {Zmen'shennya koordynat, vidpovidayuchykh za prokhid po stovptsyam elementa}
if H=1 then {Perevirka na pershchist' koordynaty elementu}
begin
g:=n; f:=Z-1; {Vidbuvayet'sya perekhid dodatkovykh koordynat g,f na ostanniy element poperedn'oho ryadka}
end
else
if H=0 then {Perevirka na zakin'chennya ryadka}
begin
H:=n; Z:=Z-1; {Dodatkovi koordynaty H,Z perekhodyat' na ostanniy element poperedn'oho ryadka}
end;
end;
end;
end;
procedure SortVector(var C:vector); {Alhorytm "vstavka – obmin" sortuvannya vektora}
var i,j,k,B: integer; {i,j: koordynaty prokhodu po vektoru; B-dodatkova komirka pam"yati;}
begin
for i:=2 to (m*n) do {Lichyl'nyk prokhodu po vektoru}
begin
j:=i;
while (j>1) and (C[j]<C[j-1]) do {Pochynayet'sya robota bezposeredn'o hibrydnoho alhorytmu "vstavka – obmin"}
begin
B:=C[j]; {Zmina elementiv mistsyamy}
C[j]:=C[j-1];
C[j-1]:=B;
j:=j-1; {Zmishchennya koordynaty vlivo}
end;
end;
end;
end. |
unit ConnectPage;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, ADSchemaUnit, ADSchemaTypes, ErrorPage;
type
TConnectForm = class(TForm)
EditHost: TEdit;
EditUsername: TEdit;
EditPassword: TEdit;
LabelHost: TLabel;
LabelUsername: TLabel;
LabelPassword: TLabel;
ConnectBtn: TButton;
ErrorLabel: TLabel;
GroupBox1: TGroupBox;
GroupBox2: TGroupBox;
procedure ConnectBtnClick(Sender: TObject);
procedure ErrorLabelClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
schema : ADSchema;
status : ADSchemaStatus;
procedure pvShowErrorDialog(errorNumb: integer; errorMsg: string);
public
{ Public declarations }
property GetSchema : ADSchema
read schema;
end;
var
ConnectForm: TConnectForm;
implementation
{$R *.dfm}
//Error handling
procedure TConnectForm.pvShowErrorDialog(errorNumb: integer; errorMsg: string);
var
errorForm : TErrorForm;
begin
errorForm := TErrorForm.Create(Application);
errorForm.SetErrorInfo(errorNumb, errorMsg);
try
errorForm.ShowModal;
finally
errorForm.Free;
end;
end;
procedure TConnectForm.ConnectBtnClick(Sender: TObject);
var
hostName, userName, password : string;
portNumber : integer;
entry : ADEntry;
begin
hostName := EditHost.Text;
userName := EditUsername.Text;
password := EditPassword.Text;
portNumber := 389;
schema := ADSchema.Create(hostName, userName, password, portNumber, status);
if (status.StatusType <> SuccessStatus) then
begin
ErrorLabel.Visible := true
end
else
begin
status.Free;
status := nil;
//check is user in schema admin group
entry := schema.GetEntry('account', ClassEntry, ['cn'], status);
if status.StatusType <> SuccessStatus then
ErrorLabel.Visible := true
else ModalResult := mrOk;
end;
end;
procedure TConnectForm.ErrorLabelClick(Sender: TObject);
begin
pvShowErrorDialog(status.StatusNumb, status.StatusMsg);
end;
procedure TConnectForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if status <> nil then
begin
status.free;
status := nil;
end;
end;
end.
|
(* Hashing - Chaining 15.03.2017*)
PROGRAM hash;
uses
Crt;
CONST
size = 31;
TYPE
NodePtr = ^Node;
Node = RECORD
key: STRING;
(* data: AnyType*)
next: NodePtr;
END; (*Record*)
ListPtr = NodePtr;
HashTable = ARRAY[0..size-1] OF ListPtr;
VAR
ht : HashTable;
procedure InitHashTable;
var
h: Integer;
begin
for h := 0 to size-1 do begin
ht[h] := Nil;
end;
end; (*InitHashTable*)
function NewNode(key: String; next: NodePtr) : NodePtr;
var
n: NodePtr;
begin
New(n);
n^.key := key;
n^.next := next;
(* n^.data := data; *)
NewNode := n;
end; (*NewNode*)
(* returns the hashcode of a key *)
function HashCode(key: String): Integer;
begin
HashCode := Ord(key[1]) MOD size;
end; (*HashCode*)
(* returns the hashcode of a key *)
function HashCode2(key: String): Integer;
begin
HashCode2 := (Ord(key[1]) + Length(key)) MOD size;
end; (*HashCode2*)
(* compiler hashcode.. *)
function HashCode3(key: String): Integer;
begin
if Length(key) = 1 then
HashCode3 := (Ord(key[1]) * 7 + 1) * 17 MOD size
else
HashCode3 := (Ord(key[1]) * 7 + Ord(key[2]) + Length(key)) * 17 MOD size
end; (*HashCode3*)
(* returns the hashcode of a key *)
function HashCode4(key: String): Integer;
var
hc, i : Integer;
begin
hc := 0;
for i := 1 to Length(key) do begin
{Q-}
{R-}
hc := 31 * hc + Ord(key[i]);
{R+}
{Q+}
end; (* for *)
HashCode4 := Abs(hc) MOD size;
end; (*HashCode4*)
(* Lookup combines search and prepend *)
function Lookup(key: String) : NodePtr;
var
i: Integer;
n: NodePtr;
begin
i := HashCode4(key);
WriteLn('Hashwert= ', i);
n := ht[i];
while (n <> Nil) AND (n^.key <> key) do begin
n := n^.next;
end;
if n = nil then begin
n := NewNode(key, ht[i]);
ht[i] := n;
end; (*if*)
Lookup := n;
end; (* Lookup *)
procedure WriteHashTable;
var
h : Integer;
n: NodePtr;
begin
for h:= 0 to size-1 do begin
if ht[h] <> nil then begin
Write(h, ': ');
n := ht[h];
while n <> nil do begin
Write(n^.key, ' ');
n := n^.next;
end; (* while *)
WriteLn;
end; (* if *)
end; (* for *)
end; (* WriteHashTable *)
var
n: NodePtr;
BEGIN
Write('Auer '); n := Lookup('Auer');
Write('Bach '); n := Lookup('Bach');
Write('Bieger '); n := Lookup('Bieger');
Write('Rieger '); n := Lookup('Rieger');
Write('Brunmueller '); n := Lookup('Brunmueller');
Write('Eieger '); n := Lookup('Eieger');
Write('Sauer '); n := Lookup('Sauer');
WriteLn;
WriteHashTable;
END. (* Hash *) |
unit uHttpTransfer;
interface
uses
Transfer, IdComponent, System.Classes, IdHTTP, System.SysUtils, IdURI;
type
THTTPTransfer = class(TTransfer)
private
FidHttp: TIdHttp;
protected
function GetOnStatus: TIdStatusEvent; override;
procedure SetOnStatus(Value: TIdStatusEvent); override;
procedure SetURI(Value: TIdURI); override;
public
constructor Create;
destructor Destroy; override;
procedure Abort; override;
procedure ClearProxySeting; override;
procedure Connect; override;
procedure Get(FileName: String); overload; override;
procedure Get(Stream: TStream); overload; override;
procedure SetProxy(ProxyObj: TPersistent); overload; override;
procedure SetProxy(ProxyInfo: TProxySeting); overload; override;
end;
implementation
uses
System.IOUtils;
constructor THTTPTransfer.Create;
begin
inherited;
FidHttp := TIdHTTP.Create(nil);
// TODO -cMM: THTTPTransfer.Create default body inserted
end;
destructor THTTPTransfer.Destroy;
begin
if Assigned(fIdHttp) then
begin
fIdHttp.Disconnect;
FreeAndNil(fIdHttp);
end;
inherited Destroy;
// TODO -cMM: THTTPTransfer.Destroy default body inserted
end;
procedure THTTPTransfer.Abort;
begin
FidHttp.Disconnect;
end;
procedure THTTPTransfer.ClearProxySeting;
begin
FidHttp.ProxyParams.Clear;
end;
procedure THTTPTransfer.Connect;
begin
FidHttp.Connect;
inherited;
end;
procedure THTTPTransfer.Get(FileName: String);
var
temp: Int64;
FileStream: TFileStream;
memstream: TMemoryStream;
begin
// try
if not DirectoryExists(ExtractFilePath(FileName)) then
TDirectory.CreateDirectory(ExtractFilePath(FileName));
if Tfile.Exists(FileName) then
FileStream := TFileStream.Create(FileName, fmOpenReadWrite)
else
FileStream := TFileStream.Create(FileName, fmCreate);
FileStream.Seek(0, soEnd);
memstream := TMemoryStream.Create;
try
FIdHTTP.Request.Range := '';
FidHttp.HandleRedirects := true;
FidHttp.Head(Self.URI.URLEncode(Self.URL));
temp := FIdHTTP.Response.ContentLength;
// if temp > 10240 then
// begin
// end
// else
// begin
// FIdHTTP.OnWorkBegin := nil;
// FIdHTTP.OnWork := nil;
// FIdHTTP.OnWorkEnd := nil;
// end;
if FileStream.Position - FIdHTTP.Response.ContentLength < 0 then
begin
FIdHTTP.OnWorkBegin := Self.WorkStart;
FIdHTTP.OnWork := Self.Work;
FIdHTTP.OnWorkEnd := Self.WorkEnd;
FidHttp.ConnectTimeout := 3000;
FidHttp.ReadTimeout := 3000;
FIdHttp.Request.Range := Format('%d-%d', [FileStream.Position, FIdHTTP.Response.ContentLength]);
//FIdHTTP.Get(Self.URI.URLEncode(Self.URL), FileStream);
try
FIdHTTP.Get(Self.URI.URLEncode(Self.URL), memstream);
except
if (FidHttp.ResponseCode >= 200) and (FidHttp.ResponseCode < 300) then
FIdHTTP.Get(Self.URI.URLEncode(Self.URL), memstream)
else
raise;
end;
memstream.SaveToStream(FileStream);
end
else
OnTransferEnd(nil);
finally
FreeAndNil(FileStream);
FreeAndNil(memstream);
end;
Sleep(100);
// except
// raise;
// end;
end;
procedure THTTPTransfer.Get(Stream: TStream);
begin
try
FidHttp.Get(Self.URI.URI, Stream);
except
raise;
end;
end;
function THTTPTransfer.GetOnStatus: TIdStatusEvent;
begin
Result := FidHttp.OnStatus;
end;
procedure THTTPTransfer.SetOnStatus(Value: TIdStatusEvent);
begin
FidHttp.OnStatus := Value;
end;
procedure THTTPTransfer.SetProxy(ProxyObj: TPersistent);
begin
inherited;
FidHttp.ProxyParams.Assign(ProxyObj);
end;
procedure THTTPTransfer.SetProxy(ProxyInfo: TProxySeting);
begin
FidHttp.ProxyParams.ProxyServer := proxyInfo.ProxyServer;
FidHttp.ProxyParams.ProxyPort := ProxyInfo.ProxyPort;
FidHttp.ProxyParams.ProxyUsername := ProxyInfo.ProxyUser;
FidHttp.ProxyParams.ProxyPassword := ProxyInfo.ProxyPass;
end;
procedure THTTPTransfer.SetURI(Value: TIdURI);
begin
// TODO -cMM: THTTPTransfer.SetURI default body inserted
//if Assigned(FURI) then FURI.Free;
inherited;
Self.URL := Value.URI;
self.Host := URI.Host;
if trim(URI.Username) = '' then
self.User := 'Anonymous'
else
self.User := URI.Username;
self.Password := URI.Password;
if trim(URI.Path) = '' then
Self.CurrentDir := '/'
else
self.CurrentDir := URI.Path;
self.FileName := URI.Document;
if (URI.Port = '') then
self.Port := 80
else
self.Port := StrToInt(URI.Port);
end;
end.
|
unit GlobalFunctionsUnit;
interface
Uses
ConfigurationUnit,
MailWatchDogUnit,
SysUtils,Classes, Windows ;
Var
Configured : Boolean;
ApplicationPath : String;
Configs : TConfiguration;
MailWatchDog : TMailWatchDog;
Mutex : THandle;
Const
DirWatchDogSleepTime = 10 * 1000;
InboxWatchDogSleepTime = 1 * 1000;
BufferSize = 1024;
function GetNodeFromXml(_Node:String; Const _Xml:String):String;
function AddXmlStyle(_Node:String; _Content:String):String;
Procedure Logging(_LogFileName:String; _Text: String);
Procedure Configure();
implementation
function GetNodeFromXml(_Node:String; Const _Xml:String):String;
Var
Pos1:Integer;
Pos2:Integer;
Begin
Result := '';
Pos1 := Pos('<'+_Node+'>',_Xml) + Length(_Node) + 2;
Pos2 := Pos('</'+_Node+'>',_Xml);
if (Pos1 > 0) And (Pos2 > 0) then
Begin
Result := Copy(_Xml,Pos1,Pos2-Pos1);
End;
End;
function AddXmlStyle(_Node:String; _Content:String):String;
Begin
Result := Format('<%s>'+sLineBreak+'%s'+sLineBreak+'</%s>',[_Node,_Content,_Node]);
End;
Procedure Logging(_LogFileName:String; _Text: String);
Var
LogFile:TextFile;
begin
Try
AssignFile(LogFile,ApplicationPath + _LogFileName);
if Not FileExists(ApplicationPath + _LogFileName) Then
Rewrite(LogFile)
else
Append(LogFile);
Write(LogFile,sLineBreak + '----------------------------' +
sLineBreak + DateTimeToStr(Now) + ': ' +
sLineBreak + _Text + sLineBreak);
System.Close(LogFile);
Except
End;
end;
Procedure Configure();
Begin
Configured := True;
MailWatchDog := TMailWatchDog.Create();
if Not MailWatchDog.Configured then
Begin
Configured := False;
MailWatchDog.Free;
MailWatchDog := nil;
End;
End;
Initialization
Begin
Mutex := CreateMutex(nil, False, 'tilda');
if Mutex = 0 then
RaiseLastOSError;
ApplicationPath := ExtractFilePath(ParamStr(0));
Configured := False;
Configs := TConfiguration.Create;
End;
end.
|
{
Clever Internet Suite Version 6.2
Copyright (C) 1999 - 2006 Clever Components
www.CleverComponents.com
}
unit clXmlUtils;
interface
{$I clVer.inc}
uses
Classes{$IFDEF DELPHI6}, Variants, msxml {$ELSE}, msxml_tlb{$ENDIF};
procedure StringsToXML(AStrings: TStrings; ANode: IXMLDOMNode);
procedure XMLToStrings(AStrings: TStrings; ANode: IXMLDOMNode);
procedure SaveXMLToFile(const AFileName: string; ADomDoc: IXMLDOMDocument);
procedure SaveXMLToStrings(AList: TStrings; ADomDoc: IXMLDOMDocument);
procedure AddCDataNodeName(const AName: string);
function GetAttributeValue(const ANode: IXMLDOMNode; const AName: string): string;
procedure SetAttributeValue(const ANode: IXMLDOMNode; const AName, AValue: string);
function GetNodeByName(const ARoot: IXMLDomNode; const AName, ANameSpace: string): IXMLDomNode;
function GetNodeValueByName(const ARoot: IXMLDomNode; const AName, ANameSpace: string): string;
implementation
uses
SysUtils;
const
CDataXMLFormat = '<xsl:output indent="yes" method="xml" encoding="UTF-8" cdata-section-elements="%s"/>';
XMLFormat = '<?xml version="1.0" encoding="UTF-8"?>' +
'<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">' +
' <xsl:output indent="yes" method="xml" encoding="UTF-8"/> %s ' +
' <xsl:template match="/ | @* | node()">' +
' <xsl:copy>' +
' <xsl:apply-templates select="@* | node()"/>' +
' </xsl:copy>' +
' </xsl:template>' +
'</xsl:stylesheet>';
var
CDataNodeNames: TStrings = nil;
procedure AddCDataNodeName(const AName: string);
begin
if (CDataNodeNames = nil) then
begin
CDataNodeNames := TStringList.Create();
end;
if (CDataNodeNames.IndexOf(AName) < 0) then
begin
CDataNodeNames.Add(AName);
end;
end;
function GetXMLFormat: string;
var
i: Integer;
begin
Result := '';
if (CDataNodeNames <> nil) then
begin
for i := 0 to CDataNodeNames.Count - 1 do
begin
Result := Result + #32 + Format(CDataXMLFormat, [CDataNodeNames[i]]);
end;
end;
Result := Format(XMLFormat, [Result]);
end;
procedure SaveXMLToFile(const AFileName: string; ADomDoc: IXMLDOMDocument);
var
b: Boolean;
TransDoc, ResDoc: IXMLDOMDocument;
begin
TransDoc := CoDOMDocument.Create();
ResDoc := CoDOMDocument.Create();
TransDoc.loadXML(GetXMLFormat());
try
ADomDoc.transformNodeToObject(TransDoc, ResDoc);
b := (ResDoc.xml <> '');
except
b := False;
end;
if b then
begin
ResDoc.save(AFileName);
end else
begin
ADomDoc.save(AFileName);
end;
end;
procedure SaveXMLToStrings(AList: TStrings; ADomDoc: IXMLDOMDocument);
var
b: Boolean;
TransDoc, ResDoc: IXMLDOMDocument;
begin
TransDoc := CoDOMDocument.Create();
ResDoc := CoDOMDocument.Create();
TransDoc.loadXML(GetXMLFormat());
try
ADomDoc.transformNodeToObject(TransDoc, ResDoc);
b := (ResDoc.xml <> '');
except
b := False;
end;
if b then
begin
AList.Text := string(ResDoc.xml);
end else
begin
AList.Text := string(ADomDoc.xml);
end;
end;
procedure StringsToXML(AStrings: TStrings; ANode: IXMLDOMNode);
var
ChildNode: IXMLDOMNode;
begin
ChildNode := ANode.ownerDocument.createCDATASection(AStrings.Text);
ANode.appendChild(ChildNode);
end;
procedure XMLToStrings(AStrings: TStrings; ANode: IXMLDOMNode);
begin
AStrings.Text := ANode.text;
end;
function GetAttributeValue(const ANode: IXMLDOMNode; const AName: string): string;
begin
Result := VarToStr((ANode as IXMLDOMElement).getAttribute(WideString(AName)));
end;
procedure SetAttributeValue(const ANode: IXMLDOMNode; const AName, AValue: string);
begin
if (AValue <> '') then
begin
(ANode as IXMLDOMElement).setAttribute(WideString(AName), AValue);
end else
begin
(ANode as IXMLDOMElement).removeAttribute(WideString(AName));
end;
end;
function GetNodeByName(const ARoot: IXMLDomNode; const AName, ANameSpace: string): IXMLDomNode;
var
list: IXMLDomNodeList;
begin
list := ARoot.childNodes;
Result := list.nextNode;
while (Result <> nil) do
begin
if (Result.baseName = AName) and (Result.namespaceURI = ANameSpace) then Exit;
Result := list.nextNode;
end;
Result := nil;
end;
function GetNodeValueByName(const ARoot: IXMLDomNode; const AName, ANameSpace: string): string;
var
node: IXMLDomNode;
begin
node := GetNodeByName(ARoot, AName, ANameSpace);
if (node <> nil) then
begin
Result := Trim(string(node.text));
end else
begin
Result := '';
end;
end;
initialization
finalization
CDataNodeNames.Free();
end. |
unit uDatabaseDirectoriesUpdater;
interface
uses
Winapi.Windows,
Winapi.ActiveX,
Generics.Defaults,
Generics.Collections,
System.SyncObjs,
System.SysUtils,
System.Classes,
System.DateUtils,
System.Math,
Vcl.Forms,
Vcl.Imaging.Jpeg,
Data.DB,
Xml.Xmldom,
Dmitry.CRC32,
Dmitry.Utils.System,
Dmitry.Utils.Files,
UnitINI,
UnitDBDeclare,
uConstants,
uRuntime,
uMemory,
uGUIDUtils,
uInterfaces,
uAssociations,
uDBAdapter,
uDBForm,
uDBThread,
wfsU,
uGOM,
uDBTypes,
uDBConnection,
uDBClasses,
uDBUtils,
uMediaInfo,
uDBContext,
uDBEntities,
uDBManager,
uLogger,
uCounters,
uSettings,
uFormInterfaces,
uConfiguration,
uDBUpdateUtils,
uShellUtils,
uTranslate,
uLockedFileNotifications,
uShellIntegration,
uCDMappingTypes,
uCollectionEvents,
uCollectionUtils;
type
TDatabaseTask = class(TObject)
protected
FDBContext: IDBContext;
FFileName: string;
public
function IsPrepaired: Boolean; virtual;
function SelfTest: Boolean; virtual;
constructor Create(DBContext: IDBContext; FileName: string);
property DBContext: IDBContext read FDBContext;
property FileName: string read FFileName;
end;
TUpdateTask = class(TDatabaseTask)
private
FID: Integer;
public
constructor Create(DBContext: IDBContext; ID: Integer; FileName: string); overload;
procedure Execute;
property ID: Integer read FID;
end;
TRemoveTask = class(TDatabaseTask)
private
FID: Integer;
public
function SelfTest: Boolean; override;
function IsPrepaired: Boolean; override;
constructor Create(DBContext: IDBContext; ID: Integer; FileName: string); overload;
procedure Execute;
property ID: Integer read FID;
end;
TRemoveDirectoryTask = class(TDatabaseTask)
public
function SelfTest: Boolean; override;
function IsPrepaired: Boolean; override;
constructor Create(DBContext: IDBContext; DirectoryName: string); overload;
procedure Execute;
end;
TAddTask = class(TDatabaseTask)
private
FData: TMediaItem;
procedure NotifyAboutFileProcessing(Info: TMediaItem; Res: TMediaInfo);
public
constructor Create(DBContext: IDBContext; Data: TMediaItem); overload;
constructor Create(DBContext: IDBContext; FileName: string); overload;
destructor Destroy; override;
procedure Execute(Items: TArray<TAddTask>);
property Data: TMediaItem read FData;
end;
TUpdateAttributeTask = class(TDatabaseTask)
private
FData: TMediaItem;
FAttr: Integer;
public
constructor Create(DBContext: IDBContext; Data: TMediaItem; Attr: Integer); overload;
destructor Destroy; override;
procedure Execute();
property Data: TMediaItem read FData;
end;
TDatabaseDirectoriesUpdater = class(TDBThread)
private
FQuery: TDataSet;
FThreadID: TGUID;
FSkipExtensions: string;
FAddRawFiles: Boolean;
FDBContext: IDBContext;
FRescanDirectory: string;
function IsDirectoryChangedOnDrive(Directory: string; ItemSizes: TList<Int64>; ItemsToAdd: TList<string>; ItemsToUpdate: TList<TUpdateTask>): Boolean;
procedure AddItemsToDatabase(Items: TList<string>);
procedure UpdateItemsInDatabase(Items: TList<TUpdateTask>);
function UpdateDatabaseItems: Boolean;
function SearchForMissedItems: Boolean;
function SearchForDeletedItems: Boolean;
function GetIsValidThread: Boolean;
function CanAddFileAutomatically(FileName: string): Boolean;
property IsValidThread: Boolean read GetIsValidThread;
protected
procedure Execute; override;
public
constructor Create(DBContext: IDBContext; RescanDirectory: string = '');
destructor Destroy; override;
end;
IUserDirectoriesWatcher = interface
['{ED4EF3E3-43A6-4D86-A40D-52AA1DFAD299}']
procedure Execute(Context: IDBContext);
procedure StartWatch;
procedure StopWatch;
procedure Restart;
procedure SuppressEvent(FileName: string; Action: Integer);
procedure ResumeEvent(FileName: string; Action: Integer);
end;
type
TSuppressInfo = record
FileName: string;
Action: Integer;
end;
TUserDirectoriesWatcher = class(TInterfacedObject, IUserDirectoriesWatcher, IDirectoryWatcher)
private
FWatchers: TList<TWachDirectoryClass>;
FState: TGUID;
FDBContext: IDBContext;
FSuppressInfos: TList<TSuppressInfo>;
procedure StartWatch;
procedure StopWatch;
function IsEventSupressed(FileName: string; Action: Integer): Boolean;
public
constructor Create;
destructor Destroy; override;
procedure Execute(Context: IDBContext);
procedure Restart;
procedure SuppressEvent(FileName: string; Action: Integer);
procedure ResumeEvent(FileName: string; Action: Integer);
procedure CheckDirectoryMoveRename(Info: TInfoCallback);
procedure DirectoryChanged(Sender: TObject; SID: TGUID; pInfos: TInfoCallBackDirectoryChangedArray; WatchType: TDirectoryWatchType);
procedure TerminateWatcher(Sender: TObject; SID: TGUID; Folder: string);
end;
TDatabaseTaskPriority = (dtpNormal, dtpHigh, dtpHighAndSkipFilters);
TUpdaterStorage = class(TObject)
private
FSync: TCriticalSection;
FTotalItemsCount: Integer;
FEstimateRemainingTime: TTime;
FTasks: TList<TDatabaseTask>;
FErrorFileList: TStringList;
FContext: IDBContext;
FCurrentUpdaterState: string;
function GetEstimateRemainingTime: TTime;
function GetActiveItemsCount: Integer;
procedure SetCurrentUpdaterState(const Value: string);
function GetCurrentUpdaterState: string;
function IsDuplicateTask(Task: TDatabaseTask): Boolean;
public
constructor Create(Context: IDBContext);
destructor Destroy; override;
procedure SaveStorage;
procedure RestoreStorage(Context: IDBContext);
function Take<T: TDatabaseTask>(Count: Integer): TArray<T>;
function TakeOne<T: TDatabaseTask>: T;
procedure Add(Task: TDatabaseTask; Priority: TDatabaseTaskPriority);
procedure AddRange(Tasks: TList<TDatabaseTask>; Priority: TDatabaseTaskPriority);
procedure AddFile(Info: TMediaItem; Priority: TDatabaseTaskPriority); overload;
procedure AddFile(FileName: string; Priority: TDatabaseTaskPriority); overload;
procedure AddDirectory(DirectoryPath: string);
function HasFile(FileName: string): Boolean;
procedure CleanUpDatabase(NewContext: IDBContext);
procedure AddFileWithErrors(FileName: string);
procedure RemoveFileWithErrors(FileName: string);
procedure RemoveFilesWithErrors(Files: TList<string>; FileSizes: TList<Int64>);
procedure MarkItemAsDeleted(Item: TMediaItem);
procedure MarkItemAsExisted(Item: TMediaItem);
procedure UpdateRemainingTime(Conter: TSpeedEstimateCounter);
property EstimateRemainingTime: TTime read GetEstimateRemainingTime;
property TotalItemsCount: Integer read FTotalItemsCount;
property ActiveItemsCount: Integer read GetActiveItemsCount;
property CurrentUpdaterState: string read GetCurrentUpdaterState write SetCurrentUpdaterState;
end;
TDatabaseUpdater = class(TDBThread)
private
FSpeedCounter: TSpeedEstimateCounter;
protected
procedure Execute; override;
public
constructor Create;
destructor Destroy; override;
end;
function UpdaterStorage: TUpdaterStorage;
procedure RecheckDirectoryOnDrive(DirectoryPath: string);
procedure RecheckUserDirectories;
procedure ClearUpdaterCache(Context: IDBContext);
implementation
const
cAddImagesAtOneStep = 4;
var
DirectoriesScanID: TGUID = '{00000000-0000-0000-0000-000000000000}';
FUpdaterStorage: TUpdaterStorage = nil;
FStorageLock: TCriticalSection = nil;
procedure RecheckUserDirectories;
begin
if UserDirectoryUpdaterCount = 0 then
begin
TThread.Synchronize(nil,
procedure
begin
TDatabaseDirectoriesUpdater.Create(DBManager.DBContext);
end
);
end;
end;
function UpdaterStorage: TUpdaterStorage;
begin
FStorageLock.Enter;
try
if FUpdaterStorage = nil then
begin
FUpdaterStorage := TUpdaterStorage.Create(DBManager.DBContext);
FUpdaterStorage.RestoreStorage(DBManager.DBContext);
end;
Result := FUpdaterStorage;
finally
FStorageLock.Leave;
end;
end;
function DatabaseFolderPersistaseFileName(CollectionPath: string): string;
begin
Result := GetAppDataDirectory + FolderCacheDirectory + ExtractFileName(CollectionPath) + IntToStr(StringCRC(CollectionPath)) + '.cache';
end;
function DatabaseErrorsPersistaseFileName(CollectionPath: string): string;
begin
Result := GetAppDataDirectory + FolderCacheDirectory + ExtractFileName(CollectionPath) + IntToStr(StringCRC(CollectionPath)) + '.errors.cache';
end;
procedure StopCurrentUpdater;
begin
DirectoriesScanID := GetGUID;
end;
procedure ClearUpdaterCache(Context: IDBContext);
begin
StopCurrentUpdater;
DeleteFile(DatabaseFolderPersistaseFileName(Context.CollectionFileName));
DeleteFile(DatabaseErrorsPersistaseFileName(Context.CollectionFileName));
AppSettings.WriteDateTime(GetCollectionRootKey(Context.CollectionFileName), 'CheckForDeletedItems', 0);
UpdaterStorage.CleanUpDatabase(nil);
end;
procedure LoadDirectoriesState(FileName: string; DirectoryCache: TDictionary<string, Int64>);
var
I: Integer;
Doc: IDOMDocument;
DocumentElement: IDOMElement;
DirectoriesList: IDOMNodeList;
DirectoryNode: IDOMNode;
PathNode, SizeNode: IDOMNode;
begin
Doc := GetDOM.createDocument('', '', nil);
try
(Doc as IDOMPersist).load(FileName);
DocumentElement := Doc.documentElement;
if DocumentElement <> nil then
begin
DirectoriesList := DocumentElement.childNodes;
if DirectoriesList <> nil then
begin
for I := 0 to DirectoriesList.length - 1 do
begin
DirectoryNode := DirectoriesList.item[I];
PathNode := DirectoryNode.attributes.getNamedItem('Path');
SizeNode := DirectoryNode.attributes.getNamedItem('Size');
if (PathNode <> nil) and (SizeNode <> nil) then
DirectoryCache.AddOrSetValue(PathNode.nodeValue, StrToInt64Def(SizeNode.nodeValue, 0));
end;
end;
end;
except
on e: Exception do
EventLog(e);
end;
end;
procedure SaveDirectoriesState(FileName: string; DirectoryCache: TDictionary<string, Int64>);
var
Doc: IDOMDocument;
DocumentElement: IDOMElement;
DirectoryNode: IDOMNode;
Pair: TPair<string, Int64>;
procedure AddProperty(Name: string; Value: string);
var
Attr: IDOMAttr;
begin
Attr := Doc.createAttribute(Name);
Attr.value := Value;
DirectoryNode.attributes.setNamedItem(Attr);
end;
begin
Doc := GetDOM.createDocument('', '', nil);
try
DocumentElement := Doc.createElement('directories');
Doc.documentElement := DocumentElement;
DirectoryNode := DocumentElement;
for Pair in DirectoryCache do
begin
DirectoryNode := Doc.createElement('directory');
AddProperty('Path', Pair.Key);
AddProperty('Size', IntToStr(Pair.Value));
Doc.documentElement.appendChild(DirectoryNode);
end;
CreateDirA(ExtractFileDir(FileName));
(Doc as IDOMPersist).save(FileName);
except
on e: Exception do
EventLog(e);
end;
end;
procedure RecheckDirectoryOnDrive(DirectoryPath: string);
var
Context: IDBContext;
begin
Context := DBManager.DBContext;
if IsFileInCollectionDirectories(Context.CollectionFileName, DirectoryPath, True) then
TDatabaseDirectoriesUpdater.Create(DBManager.DBContext, DirectoryPath);
end;
function CheckIfCanAddFileAutomatically(FileName: string; AddRawFiles: Boolean; SkipExtensions: string): Boolean;
var
Ext: string;
begin
if not AddRawFiles and IsRAWImageFile(FileName) then
Exit(False);
if SkipExtensions <> '' then
begin
Ext := AnsiLowerCase(ExtractFileExt(FileName));
if SkipExtensions.IndexOf(AnsiLowerCase(Ext)) > 0 then
Exit(False);
end;
Exit(True);
end;
{ TDatabaseDirectoriesUpdater }
function TDatabaseDirectoriesUpdater.CanAddFileAutomatically(FileName: string): Boolean;
begin
Result := CheckIfCanAddFileAutomatically(FileName, FAddRawFiles, FSkipExtensions);
end;
constructor TDatabaseDirectoriesUpdater.Create(DBContext: IDBContext; RescanDirectory: string = '');
begin
inherited Create(nil, False);
FDBContext := DBContext;
FThreadID := GetGUID;
DirectoriesScanID := FThreadID;
FRescanDirectory := RescanDirectory;
FSkipExtensions := AnsiLowerCase(AppSettings.ReadString('Updater', 'SkipExtensions'));
FAddRawFiles := AppSettings.ReadBool('Updater', 'AddRawFiles', False);
FQuery := DBContext.CreateQuery(dbilRead);
end;
destructor TDatabaseDirectoriesUpdater.Destroy;
begin
FreeDS(FQuery);
inherited;
end;
function TDatabaseDirectoriesUpdater.UpdateDatabaseItems: Boolean;
var
SettingsRepository: ISettingsRepository;
Settings: TSettings;
MediaItem: TMediaItem;
SC: TSelectCommand;
begin
SettingsRepository := FDBContext.Settings;
Result := False;
Settings := SettingsRepository.Get;
SC := FDBContext.CreateSelect(ImageTable);
try
SC.AddParameter(TAllParameter.Create());
SC.TopRecords := 50;
SC.AddWhereParameter(TIntegerParameter.Create('PreviewSize', Settings.ThSize, paNotEquals));
SC.AddWhereParameter(TIntegerParameter.Create('Attr', Db_attr_deleted, paNotEquals));
SC.AddWhereParameter(TDateTimeParameter.Create('DateUpdated', IncDay(Now, -14), paLessThan));
SC.OrderBy('DateUpdated');
SC.OrderByDescending('DateToAdd');
SC.Execute;
while not SC.DS.EOF do
begin
if DBTerminating or not IsValidThread then
Exit(False);
Result := True;
MediaItem := TMediaItem.CreateFromDS(SC.DS);
try
try
if not UpdateImageRecordEx(FDBContext, nil, MediaItem, Settings) then
MarkRecordAsUpdated(FDBContext, MediaItem.ID);
except
on e: Exception do
begin
EventLog(e);
MarkRecordAsUpdated(FDBContext, MediaItem.ID);
end;
end;
finally
F(MediaItem);
end;
SC.DS.Next;
end;
finally
F(Settings);
F(SC);
end;
end;
function TDatabaseDirectoriesUpdater.SearchForDeletedItems: Boolean;
var
SC: TSelectCommand;
IDs: TList<Integer>;
begin
Result := False;
SC := FDBContext.CreateSelect(ImageTable);
try
SC.AddParameter(TIntegerParameter.Create('ID'));
SC.AddParameter(TStringParameter.Create('Attr'));
SC.TopRecords := 100;
SC.AddWhereParameter(TIntegerParameter.Create('Attr', Db_attr_deleted, paEquals));
SC.AddWhereParameter(TDateTimeParameter.Create('DateUpdated', Now - 1, paLessThan));
SC.OrderBy('ID');
SC.Execute;
IDs := TList<Integer>.Create;
try
while not SC.DS.EOF do
begin
if DBTerminating or not IsValidThread then
Exit(False);
IDs.Add(SC.DS.FindField('ID').AsInteger);
Result := True;
SC.DS.Next;
end;
if IDs.Count > 0 then
FDBContext.Media.DeleteFromCollectionEx(IDs);
finally
F(IDs);
end;
finally
F(SC);
end;
end;
function TDatabaseDirectoriesUpdater.SearchForMissedItems: Boolean;
var
SettingsRepository: ISettingsRepository;
SC: TSelectCommand;
FileName: string;
ID, BaseID, Attr: Integer;
FE: Boolean;
begin
SettingsRepository := FDBContext.Settings;
Result := False;
BaseID := AppSettings.ReadInteger(GetCollectionRootKey(FDBContext.CollectionFileName), 'DeletedCheckPosition', 0);
SC := FDBContext.CreateSelect(ImageTable);
try
SC.AddParameter(TIntegerParameter.Create('ID'));
SC.AddParameter(TStringParameter.Create('FFileName'));
SC.AddParameter(TStringParameter.Create('Attr'));
SC.TopRecords := 500;
SC.AddWhereParameter(TIntegerParameter.Create('ID', BaseID, paGrateThan));
SC.OrderBy('ID');
SC.Execute;
while not SC.DS.EOF do
begin
if DBTerminating or not IsValidThread then
Exit(False);
ID := SC.DS.FindField('ID').AsInteger;
FileName := SC.DS.FindField('FFileName').AsString;
Attr := SC.DS.FindField('Attr').AsInteger;
FE := not StaticPath(FileName) or FileExistsSafe(FileName);
if FE and (Attr in [Db_attr_missed, Db_attr_deleted]) then
FDBContext.Media.SetAttribute(ID, Db_attr_norm);
if not FE and not (Attr in [Db_attr_missed, Db_attr_deleted]) then
FDBContext.Media.SetAttribute(ID, Db_attr_missed);
Result := True;
SC.DS.Next;
end;
if not Result then
AppSettings.WriteInteger(GetCollectionRootKey(FDBContext.CollectionFileName), 'DeletedCheckPosition', 0)
else
AppSettings.WriteInteger(GetCollectionRootKey(FDBContext.CollectionFileName), 'DeletedCheckPosition', SC.DS.FindField('ID').AsInteger);
finally
F(SC);
end;
end;
procedure TDatabaseDirectoriesUpdater.Execute;
var
FolderList: TList<TDatabaseDirectory>;
DD: TDatabaseDirectory;
Directories: TQueue<string>;
ItemsToAdd: TList<string>;
ItemsToUpdate: TList<TUpdateTask>;
ItemSizes: TList<Int64>;
TotalDirectorySize: Int64;
Found: Integer;
OldMode: Cardinal;
SearchRec: TSearchRec;
ScanInformationFileName,
FileName, Dir, DirectoryPath: string;
SavedDirectoriesStructure: TDictionary<string, Int64>;
IsRescanMode: Boolean;
procedure NotifyTask(Task: string);
begin
TThread.Synchronize(nil,
procedure
begin
UpdaterStorage.CurrentUpdaterState := Task;
end
);
end;
begin
inherited;
FreeOnTerminate := True;
Priority := tpLower;
try
Inc(UserDirectoryUpdaterCount);
CoInitializeEx(nil, COM_MODE);
try
IsRescanMode := FRescanDirectory <> '';
if not IsRescanMode then
while UpdateDatabaseItems do
NotifyTask(TA('Updating collection items', 'System'));
if not IsRescanMode then
while SearchForDeletedItems do
NotifyTask(TA('Searching for deleted items', 'System'));
if Now - AppSettings.ReadDateTime(GetCollectionRootKey(FDBContext.CollectionFileName), 'CheckForDeletedItems', 0) > 7 then
begin
if not IsRescanMode then
while SearchForMissedItems do
NotifyTask(TA('Searching for missed items', 'System'));
if not DBTerminating and IsValidThread then
AppSettings.WriteDateTime(GetCollectionRootKey(FDBContext.CollectionFileName), 'CheckForDeletedItems', Now);
end;
Directories := TQueue<string>.Create;
ItemsToAdd := TList<string>.Create;
ItemsToUpdate := TList<TUpdateTask>.Create;
ItemSizes := TList<Int64>.Create;
SavedDirectoriesStructure := TDictionary<string, Int64>.Create;
OldMode := SetErrorMode(SEM_FAILCRITICALERRORS);
try
if not IsRescanMode then
begin
ScanInformationFileName := DatabaseFolderPersistaseFileName(FDBContext.CollectionFileName);
LoadDirectoriesState(ScanInformationFileName, SavedDirectoriesStructure);
//list of directories to scan
FolderList := TList<TDatabaseDirectory>.Create;
try
ReadDatabaseSyncDirectories(FolderList, FDBContext.CollectionFileName);
for DD in FolderList do
Directories.Enqueue(DD.Path);
finally
FreeList(FolderList);
end;
end else
Directories.Enqueue(FRescanDirectory);
while Directories.Count > 0 do
begin
if DBTerminating or not IsValidThread then
Break;
Dir := Directories.Dequeue;
NotifyTask(FormatEx(TA('Scaning items on hard drive ({0})', 'System'), [Dir]));
Dir := IncludeTrailingBackslash(Dir);
TotalDirectorySize := 0;
ItemSizes.Clear;
ItemsToAdd.Clear;
FreeList(ItemsToUpdate, False);
Found := FindFirst(Dir + '*.*', faDirectory, SearchRec);
try
while Found = 0 do
begin
if (SearchRec.Name <> '.') and (SearchRec.Name <> '..') and (faHidden and SearchRec.Attr = 0) then
begin
if (faDirectory and SearchRec.Attr = 0) and IsGraphicFile(SearchRec.Name) and CanAddFileAutomatically(SearchRec.Name) then
begin
FileName := Dir + SearchRec.Name;
Inc(TotalDirectorySize, SearchRec.Size);
ItemsToAdd.Add(FileName);
ItemSizes.Add(SearchRec.Size);
end;
if faDirectory and SearchRec.Attr <> 0 then
Directories.Enqueue(Dir + SearchRec.Name);
end;
Found := System.SysUtils.FindNext(SearchRec);
end;
finally
FindClose(SearchRec);
end;
DirectoryPath := AnsiLowerCase(Dir);
if not IsRescanMode then
begin
if SavedDirectoriesStructure.ContainsKey(DirectoryPath) then
begin
//directory is unchanged
if TotalDirectorySize = SavedDirectoriesStructure[DirectoryPath] then
Continue;
end;
end;
if not IsRescanMode then
UpdaterStorage.RemoveFilesWithErrors(ItemsToAdd, ItemSizes);
if (ItemsToAdd.Count > 0) and IsDirectoryChangedOnDrive(Dir, ItemSizes, ItemsToAdd, ItemsToUpdate) and IsValidThread then
begin
if ItemsToAdd.Count > 0 then
AddItemsToDatabase(ItemsToAdd);
if ItemsToUpdate.Count > 0 then
UpdateItemsInDatabase(ItemsToUpdate);
end else
SavedDirectoriesStructure.AddOrSetValue(DirectoryPath, TotalDirectorySize);
end;
if not IsRescanMode and (IsValidThread or DBTerminating) then
SaveDirectoriesState(ScanInformationFileName, SavedDirectoriesStructure);
finally
SetErrorMode(OldMode);
F(ItemSizes);
F(ItemsToAdd);
FreeList(ItemsToUpdate);
F(SavedDirectoriesStructure);
F(Directories);
end;
finally
CoUninitialize;
Dec(UserDirectoryUpdaterCount);
end;
except
on e: Exception do
begin
EventLog(e);
MessageBoxDB(0, e.Message, TA('Error'), TD_BUTTON_OK, TD_ICON_ERROR);
end;
end;
end;
function TDatabaseDirectoriesUpdater.GetIsValidThread: Boolean;
begin
Result := FThreadID = DirectoriesScanID;
end;
function TDatabaseDirectoriesUpdater.IsDirectoryChangedOnDrive(
Directory: string; ItemSizes: TList<Int64>; ItemsToAdd: TList<string>; ItemsToUpdate: TList<TUpdateTask>): Boolean;
var
I, J: Integer;
DA: TImageTableAdapter;
FileName: string;
begin
if ItemsToAdd.Count = 0 then
Exit(False);
SetSQL(FQuery, 'Select ID, FileSize, Name FROM $DB$ WHERE FolderCRC = ' + IntToStr(GetPathCRC(Directory, False)));
if TryOpenCDS(FQuery) then
begin
if not FQuery.IsEmpty then
begin
FQuery.First;
DA := TImageTableAdapter.Create(FQuery);
try
for I := 1 to FQuery.RecordCount do
begin
FileName := AnsiLowerCase(Directory + DA.Name);
for J := ItemsToAdd.Count - 1 downto 0 do
if(AnsiLowerCase(ItemsToAdd[J]) = FileName) then
begin
if (ItemSizes[J] <> DA.FileSize) then
ItemsToUpdate.Add(TUpdateTask.Create(FDBContext, Da.ID, ItemsToAdd[J]));
ItemsToAdd.Delete(J);
ItemSizes.Delete(J);
end;
FQuery.Next;
end;
finally
F(DA);
end;
end;
Exit((ItemsToAdd.Count > 0) or (ItemsToUpdate.Count > 0));
end else
Exit(True);
end;
procedure TDatabaseDirectoriesUpdater.UpdateItemsInDatabase(Items: TList<TUpdateTask>);
begin
UpdaterStorage.AddRange(TList<TDatabaseTask>(Items), dtpHigh);
Items.Clear;
end;
procedure TDatabaseDirectoriesUpdater.AddItemsToDatabase(Items: TList<string>);
var
FileName: string;
AddTasks: TList<TAddTask>;
begin
AddTasks := TList<TAddTask>.Create;
try
for FileName in Items do
AddTasks.Add(TAddTask.Create(FDBContext, FileName));
UpdaterStorage.AddRange(TList<TDatabaseTask>(AddTasks), dtpHigh);
finally
F(AddTasks);
end;
end;
{ TUserDirectoriesWatcher }
constructor TUserDirectoriesWatcher.Create;
begin
FWatchers := TList<TWachDirectoryClass>.Create;
FSuppressInfos := TList<TSuppressInfo>.Create;
GOM.AddObj(Self);
end;
destructor TUserDirectoriesWatcher.Destroy;
begin
StopWatch;
FreeList(FWatchers);
F(FSuppressInfos);
GOM.RemoveObj(Self);
inherited;
end;
procedure TUserDirectoriesWatcher.Execute(Context: IDBContext);
begin
inherited;
StopWatch;
FDBContext := Context;
StartWatch;
TDatabaseDirectoriesUpdater.Create(FDBContext);
end;
procedure TUserDirectoriesWatcher.Restart;
begin
StopWatch;
StartWatch;
end;
procedure TUserDirectoriesWatcher.StartWatch;
var
Watch: TWachDirectoryClass;
FolderList: TList<TDatabaseDirectory>;
DD: TDatabaseDirectory;
begin
FState := GetGUID;
//list of directories to watch
FolderList := TList<TDatabaseDirectory>.Create;
try
ReadDatabaseSyncDirectories(FolderList, FDBContext.CollectionFileName);
for DD in FolderList do
begin
Watch := TWachDirectoryClass.Create;
FWatchers.Add(Watch);
Watch.Start(DD.Path, Self, Self, FState, True, dwtFiles);
Watch := TWachDirectoryClass.Create;
FWatchers.Add(Watch);
Watch.Start(DD.Path, Self, Self, FState, True, dwtDirectories);
end;
finally
FreeList(FolderList);
end;
end;
procedure TUserDirectoriesWatcher.StopWatch;
var
I: Integer;
begin
for I := 0 to FWatchers.Count - 1 do
FWatchers[I].StopWatch;
FreeList(FWatchers, False);
end;
function TUserDirectoriesWatcher.IsEventSupressed(FileName: string; Action: Integer): Boolean;
var
SI: TSuppressInfo;
begin
FileName := AnsiLowerCase(FileName);
for SI in FSuppressInfos do
if (SI.FileName = FileName) and (SI.Action = Action) then
Exit(True);
Exit(False);
end;
procedure TUserDirectoriesWatcher.SuppressEvent(FileName: string; Action: Integer);
var
SI: TSuppressInfo;
begin
if IsEventSupressed(FileName, Action) then
Exit;
SI.FileName := AnsiLowerCase(FileName);
SI.Action := Action;
FSuppressInfos.Add(SI);
end;
procedure TUserDirectoriesWatcher.ResumeEvent(FileName: string; Action: Integer);
var
I: Integer;
begin
FileName := AnsiLowerCase(FileName);
for I := 0 to FSuppressInfos.Count - 1 do
if (FSuppressInfos[I].FileName = FileName) and (FSuppressInfos[I].Action = Action) then
begin
FSuppressInfos.Delete(I);
Exit;
end;
end;
procedure TUserDirectoriesWatcher.CheckDirectoryMoveRename(Info: TInfoCallback);
begin
if IsEventSupressed(Info.NewFileName, Info.Action) then
begin
ResumeEvent(Info.NewFileName, Info.Action);
Exit;
end;
case Info.Action of
FILE_ACTION_REMOVED:
UpdaterStorage.Add(TRemoveDirectoryTask.Create(FDBContext, Info.NewFileName), dtpHigh);
FILE_ACTION_RENAMED_NEW_NAME:
//not implemented (program explorer handles this situation)
end;
end;
procedure TUserDirectoriesWatcher.DirectoryChanged(Sender: TObject; SID: TGUID;
pInfos: TInfoCallBackDirectoryChangedArray; WatchType: TDirectoryWatchType);
var
Info: TInfoCallback;
IsFileExists: Boolean;
FileName, SkipExtensions: string;
AddRawFiles: Boolean;
begin
if FState <> SID then
Exit;
for Info in pInfos do
begin
if not IsGraphicFile(Info.NewFileName) then
begin
if (WatchType = dwtDirectories) then
CheckDirectoryMoveRename(Info);
Continue;
end;
IsFileExists := True;
if (Info.NewFileName <> '') and TLockFiles.Instance.IsFileLocked(Info.NewFileName) then
IsFileExists := False;
if (Info.OldFileName <> '') and TLockFiles.Instance.IsFileLocked(Info.OldFileName) then
IsFileExists := False;
FileName := Info.NewFileName;
SkipExtensions := AnsiLowerCase(AppSettings.ReadString('Updater', 'SkipExtensions'));
AddRawFiles := AppSettings.ReadBool('Updater', 'AddRawFiles', False);
if not CheckIfCanAddFileAutomatically(FileName, AddRawFiles, SkipExtensions) then
Exit;
case Info.Action of
FILE_ACTION_ADDED:
if IsFileExists then
UpdaterStorage.Add(TAddTask.Create(FDBContext, FileName), dtpHigh);
FILE_ACTION_REMOVED:
UpdaterStorage.Add(TRemoveTask.Create(FDBContext, FileName), dtpHigh);
FILE_ACTION_RENAMED_NEW_NAME:
Break;
FILE_ACTION_MODIFIED:
if IsFileExists then
UpdaterStorage.Add(TUpdateTask.Create(FDBContext, 0, FileName), dtpHigh);
end;
end;
end;
procedure TUserDirectoriesWatcher.TerminateWatcher(Sender: TObject; SID: TGUID;
Folder: string);
begin
//do nothing for now
end;
{ TDatabaseTask }
constructor TDatabaseTask.Create(DBContext: IDBContext; FileName: string);
begin
FDBContext := DBContext;
FFileName := FileName;
end;
function TDatabaseTask.IsPrepaired: Boolean;
var
hFile: THandle;
begin
Result := False;
//don't allow to write to file and try to open file
hFile := CreateFile(PChar(FFileName), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
try
Result := (hFile <> INVALID_HANDLE_VALUE) and (hFile <> 0);
finally
if Result then
CloseHandle(hFile);
end;
end;
function TDatabaseTask.SelfTest: Boolean;
begin
Result := FileExistsSafe(FileName);
end;
{ TUpdateTask }
constructor TUpdateTask.Create(DBContext: IDBContext; ID: Integer; FileName: string);
begin
inherited Create(DBContext, FileName);
FFileName := FileName;
FID := ID;
end;
procedure TUpdateTask.Execute;
var
MediaRepository: IMediaRepository;
begin
MediaRepository := FDBContext.Media;
try
if FID = 0 then
FID := MediaRepository.GetIdByFileName(FFileName);
if not UpdateImageRecord(FDBContext, nil, FFileName, ID) then
UpdaterStorage.AddFileWithErrors(FFileName);
except
on e: Exception do
EventLog(e);
end;
end;
{ TRemoveTask }
constructor TRemoveTask.Create(DBContext: IDBContext; ID: Integer;
FileName: string);
begin
inherited Create(DBContext, FileName);
FFileName := FileName;
FID := ID;
end;
procedure TRemoveTask.Execute;
var
MediaRepository: IMediaRepository;
begin
MediaRepository := FDBContext.Media;
try
if FID = 0 then
FID := MediaRepository.GetIdByFileName(FFileName);
if FID > 0 then
MediaRepository.DeleteFromCollection(FFileName, ID);
except
on e: Exception do
EventLog(e);
end;
end;
function TRemoveTask.IsPrepaired: Boolean;
begin
Result := True;
end;
function TRemoveTask.SelfTest: Boolean;
begin
Result := True;
end;
{ TRemoveDirectoryTask }
constructor TRemoveDirectoryTask.Create(DBContext: IDBContext;
DirectoryName: string);
begin
inherited Create(DBContext, DirectoryName);
FFileName := DirectoryName;
end;
procedure TRemoveDirectoryTask.Execute;
var
MediaRepository: IMediaRepository;
begin
MediaRepository := FDBContext.Media;
try
MediaRepository.DeleteDirectoryFromCollection(FFileName);
except
on e: Exception do
EventLog(e);
end;
end;
function TRemoveDirectoryTask.IsPrepaired: Boolean;
begin
Result := True;
end;
function TRemoveDirectoryTask.SelfTest: Boolean;
begin
Result := True;
end;
{ TMaskAsDeletedTask }
constructor TUpdateAttributeTask.Create(DBContext: IDBContext; Data: TMediaItem;
Attr: Integer);
begin
inherited Create(DBContext, Data.FileName);
FData := Data.Copy
end;
destructor TUpdateAttributeTask.Destroy;
begin
F(FData);
inherited;
end;
procedure TUpdateAttributeTask.Execute;
begin
FDBContext.Media.SetAttribute(FData.ID, FAttr);
end;
{ TAddTask }
constructor TAddTask.Create(DBContext: IDBContext; Data: TMediaItem);
begin
if Data = nil then
raise Exception.Create('Can''t create task for null task!');
inherited Create(DBContext, Data.FileName);
FData := Data.Copy;
end;
constructor TAddTask.Create(DBContext: IDBContext; FileName: string);
begin
inherited Create(DBContext, FileName);
FData := TMediaItem.CreateFromFile(FileName);
FData.Include := True;
end;
destructor TAddTask.Destroy;
begin
F(FData);
inherited;
end;
procedure TAddTask.Execute(Items: TArray<TAddTask>);
var
I: Integer;
ResArray: TMediaInfoArray;
Infos: TMediaItemCollection;
Info: TMediaItem;
Res: TMediaInfo;
NotifyAboutFile: Boolean;
MediaRepository: IMediaRepository;
begin
MediaRepository := FDBContext.Media;
try
Infos := TMediaItemCollection.Create;
try
for I := 0 to Length(Items) - 1 do
Infos.Add(Items[I].Data.Copy);
ResArray := GetImageIDWEx(FDBContext, Infos, False);
try
for I := 0 to Length(ResArray) - 1 do
begin
Res := ResArray[I];
Info := Infos[I];
if Res.Jpeg = nil then
begin
//failed to load image
UpdaterStorage.AddFileWithErrors(Info.FileName);
Continue;
end;
//decode jpeg in background for fasten drawing in GUI
Res.Jpeg.DIBNeeded;
UpdaterStorage.RemoveFileWithErrors(Info.FileName);
//new file in collection
if Res.Count = 0 then
begin
if TDatabaseUpdateManager.AddFile(FDBContext, Info, Res) then
begin
TThread.Synchronize(nil,
procedure
begin
NotifyAboutFileProcessing(Info, Res);
end
);
end else
UpdaterStorage.AddFileWithErrors(Info.FileName);
Continue;
end;
NotifyAboutFile := True;
try
if Res.Count = 1 then
begin
//moved file
if (StaticPath(Res.FileNames[0]) and not FileExists(Res.FileNames[0])) or (Res.Attr[0] in [Db_attr_missed, Db_attr_deleted]) then
begin
TDatabaseUpdateManager.MergeWithExistedInfo(FDBContext, Res.IDs[0], Info, True);
Continue;
end;
//the same file was deleted
if (AnsiLowerCase(Res.FileNames[0]) = AnsiLowerCase(Info.FileName)) and (Res.Attr[0] in [Db_attr_missed, Db_attr_deleted]) then
begin
MediaRepository.SetAttribute(Info.ID, Db_attr_norm);
Continue;
end;
//the same file, skip
if AnsiLowerCase(Res.FileNames[0]) = AnsiLowerCase(Info.FileName) then
begin
MediaRepository.SetFileNameById(Res.IDs[0], Info.FileName);
Continue;
end;
end;
//add file as duplicate
if not TDatabaseUpdateManager.AddFileAsDuplicate(FDBContext, Info, Res) then
begin
UpdaterStorage.AddFileWithErrors(Info.FileName);
NotifyAboutFile := False;
end;
finally
if NotifyAboutFile then
begin
TThread.Synchronize(nil,
procedure
begin
NotifyAboutFileProcessing(Info, Res);
end
);
end;
end;
end;
finally
for I := 0 to Length(ResArray) - 1 do
if ResArray[I].Jpeg <> nil then
begin
ResArray[I].Jpeg.Free;
ResArray[I].Jpeg := nil;
end;
end;
finally
F(Infos);
end;
except
on e: Exception do
begin
EventLog(e);
raise;
end;
end;
end;
procedure TAddTask.NotifyAboutFileProcessing(Info: TMediaItem; Res: TMediaInfo);
var
EventInfo: TEventValues;
begin
Info.SaveToEvent(EventInfo);
EventInfo.NewName := Info.FileName;
EventInfo.JPEGImage := Res.Jpeg;
CollectionEvents.DoIDEvent(Application.MainForm as TDBForm, Info.ID, [EventID_FileProcessed, EventID_Param_Name], EventInfo);
end;
{ TUpdaterStorage }
procedure TUpdaterStorage.AddDirectory(DirectoryPath: string);
var
FolderList: TList<TDatabaseDirectory>;
DD: TDatabaseDirectory;
begin
if IsFileInCollectionDirectories(FContext.CollectionFileName, DirectoryPath, True) then
Exit;
FolderList := TList<TDatabaseDirectory>.Create;
try
ReadDatabaseSyncDirectories(FolderList, FContext.CollectionFileName);
DirectoryPath := ExcludeTrailingPathDelimiter(DirectoryPath);
DD := TDatabaseDirectory.Create(DirectoryPath, ExtractFileName(DirectoryPath), 0);
FolderList.Add(DD);
SaveDatabaseSyncDirectories(FolderList, FContext.CollectionFileName);
finally
FreeList(FolderList);
end;
RecheckUserDirectories;
end;
procedure TUpdaterStorage.AddFile(Info: TMediaItem; Priority: TDatabaseTaskPriority);
var
SkipExtensions: string;
AddRawFiles: Boolean;
begin
if Info = nil then
Exit;
if Priority <> dtpHighAndSkipFilters then
begin
SkipExtensions := AnsiLowerCase(AppSettings.ReadString('Updater', 'SkipExtensions'));
AddRawFiles := AppSettings.ReadBool('Updater', 'AddRawFiles', False);
if not CheckIfCanAddFileAutomatically(Info.FileName, AddRawFiles, SkipExtensions) then
Exit;
end;
Add(TAddTask.Create(FContext, Info), Priority);
end;
procedure TUpdaterStorage.AddFile(FileName: string; Priority: TDatabaseTaskPriority);
var
Info: TMediaItem;
begin
Info := TMediaItem.CreateFromFile(FileName);
try
Info.Include := True;
AddFile(Info, Priority);
finally
F(Info);
end;
end;
procedure TUpdaterStorage.AddFileWithErrors(FileName: string);
begin
FSync.Enter;
try
FileName := AnsiLowerCase(FileName);
if FErrorFileList.IndexOf(FileName) = -1 then
FErrorFileList.Add(AnsiLowerCase(FileName));
finally
FSync.Leave;
end;
end;
procedure TUpdaterStorage.RemoveFilesWithErrors(Files: TList<string>; FileSizes: TList<Int64>);
var
I: Integer;
begin
FSync.Enter;
try
for I := Files.Count - 1 downto 0 do
if FErrorFileList.IndexOf(AnsiLowerCase(Files[I])) > -1 then
begin
Files.Delete(I);
FileSizes.Delete(I);
end;
finally
FSync.Leave;
end;
end;
procedure TUpdaterStorage.RemoveFileWithErrors(FileName: string);
var
Index: Integer;
begin
FSync.Enter;
try
FileName := AnsiLowerCase(FileName);
if FErrorFileList.Find(FileName, Index) then
FErrorFileList.Delete(Index);
finally
FSync.Leave;
end;
end;
procedure TUpdaterStorage.Add(Task: TDatabaseTask; Priority: TDatabaseTaskPriority);
begin
FSync.Enter;
try
if IsDuplicateTask(Task) then
begin
Task.Free;
Exit;
end;
if Priority = dtpNormal then
FTasks.Add(Task);
if Priority in [dtpHigh, dtpHighAndSkipFilters] then
FTasks.Insert(0, Task);
Inc(FTotalItemsCount);
finally
FSync.Leave;
end;
end;
procedure TUpdaterStorage.AddRange(Tasks: TList<TDatabaseTask>; Priority: TDatabaseTaskPriority);
var
I: Integer;
begin
FSync.Enter;
try
for I := Tasks.Count - 1 downto 0 do
if IsDuplicateTask(Tasks[I]) then
begin
Tasks[I].Free;
Tasks.Delete(I);
Continue;
end;
if Priority = dtpNormal then
FTasks.AddRange(Tasks.ToArray());
if Priority in [dtpHigh, dtpHighAndSkipFilters] then
FTasks.InsertRange(0, Tasks.ToArray());
Inc(FTotalItemsCount, Tasks.Count);
finally
FSync.Leave;
end;
end;
procedure TUpdaterStorage.CleanUpDatabase(NewContext: IDBContext);
var
I: Integer;
begin
FSync.Enter;
try
for I := FTasks.Count - 1 downto 0 do
if FTasks[I].FDBContext <> NewContext then
begin
FTasks[I].Free;
FTasks.Delete(I);
Dec(FTotalItemsCount);
end;
FErrorFileList.Clear;
finally
FSync.Leave;
end;
end;
constructor TUpdaterStorage.Create(Context: IDBContext);
begin
FContext := Context;
FSync := TCriticalSection.Create;
FTasks := TList<TDatabaseTask>.Create;
TDatabaseUpdater.Create;
FEstimateRemainingTime := 0;
FTotalItemsCount := 0;
FErrorFileList := TStringList.Create;
end;
destructor TUpdaterStorage.Destroy;
begin
SaveStorage;
F(FSync);
FreeList(FTasks);
F(FErrorFileList);
FContext := nil;
inherited;
end;
function TUpdaterStorage.GetActiveItemsCount: Integer;
begin
FSync.Enter;
try
Result := FTasks.Count;
finally
FSync.Leave;
end;
end;
procedure TUpdaterStorage.SetCurrentUpdaterState(const Value: string);
begin
FSync.Enter;
try
FCurrentUpdaterState := Value;
finally
FSync.Leave;
end;
end;
function TUpdaterStorage.GetCurrentUpdaterState: string;
begin
FSync.Enter;
try
Result := FCurrentUpdaterState;
finally
FSync.Leave;
end;
end;
function TUpdaterStorage.GetEstimateRemainingTime: TTime;
begin
FSync.Enter;
try
Result := FEstimateRemainingTime;
finally
FSync.Leave;
end;
end;
function TUpdaterStorage.HasFile(FileName: string): Boolean;
var
I: Integer;
begin
Result := False;
FSync.Enter;
try
FileName := AnsiLowerCase(FileName);
for I := 0 to FTasks.Count - 1 do
if AnsiLowerCase(FTasks[I].FileName) = FileName then
Exit(True);
finally
FSync.Leave;
end;
end;
function TUpdaterStorage.IsDuplicateTask(Task: TDatabaseTask): Boolean;
var
I: Integer;
FileName: string;
begin
Result := False;
FileName := AnsiLowerCase(Task.FileName);
FSync.Enter;
try
for I := 0 to FTasks.Count - 1 do
if (AnsiLowerCase(FTasks[I].FileName) = FileName) and (Task.ClassName = FTasks[I].ClassName) then
Exit(True);
finally
FSync.Leave;
end;
end;
procedure TUpdaterStorage.MarkItemAsDeleted(Item: TMediaItem);
begin
FSync.Enter;
try
FTasks.Add(TUpdateAttributeTask.Create(FContext, Item.Copy, Db_attr_missed));
finally
FSync.Leave;
end;
end;
procedure TUpdaterStorage.MarkItemAsExisted(Item: TMediaItem);
begin
FSync.Enter;
try
FTasks.Add(TUpdateAttributeTask.Create(FContext, Item.Copy, Db_attr_norm));
finally
FSync.Leave;
end;
end;
procedure TUpdaterStorage.UpdateRemainingTime(Conter: TSpeedEstimateCounter);
begin
FSync.Enter;
try
FEstimateRemainingTime := Conter.GetTimeRemaining(100 * FTasks.Count);
finally
FSync.Leave;
end;
end;
procedure TUpdaterStorage.RestoreStorage(Context: IDBContext);
var
ErrorsFileName: string;
begin
FSync.Enter;
try
FContext := Context;
ErrorsFileName := DatabaseErrorsPersistaseFileName(Context.CollectionFileName);
try
FErrorFileList.LoadFromFile(ErrorsFileName);
except
on e: Exception do
EventLog(e);
end;
FErrorFileList.Sort;
finally
FSync.Leave;
end;
end;
procedure TUpdaterStorage.SaveStorage;
var
ErrorsFileName: string;
begin
FSync.Enter;
try
ErrorsFileName := DatabaseErrorsPersistaseFileName(FContext.CollectionFileName);
FErrorFileList.SaveToFile(ErrorsFileName);
FErrorFileList.Clear;
finally
FSync.Leave;
end;
end;
function TUpdaterStorage.Take<T>(Count: Integer): TArray<T>;
var
IsLoadingList: Boolean;
I, Index: Integer;
PI: PInteger;
FItems: TList<T>;
FItemsNotReady: TList<T>;
Task: TDatabaseTask;
begin
FItems := TList<T>.Create;
FItemsNotReady := TList<T>.Create;
try
Index := 0;
IsLoadingList := True;
while IsLoadingList do
begin
IsLoadingList := False;
FSync.Enter;
try
for I := Index to FTasks.Count - 1 do
begin
if I >= FTasks.Count then
Break;
Inc(Index);
if (FTasks[I] is T) then
begin
FItems.Add(FTasks[I]);
FTasks.Delete(I);
IsLoadingList := True;
if FItems.Count = Count then
begin
IsLoadingList := False;
Break;
end;
end;
if I = FTasks.Count - 1 then
IsLoadingList := False;
end;
finally
FSync.Leave;
end;
for I := FItems.Count - 1 downto 0 do
begin
Task := FItems[I];
if not Task.IsPrepaired then
begin
FItemsNotReady.Add(Task);
FItems.Remove(Task);
Continue;
end;
if not Task.SelfTest then
begin
Task.Free;
FItems.Delete(I);
Continue;
end;
end;
FSync.Enter;
try
for I := 0 to FItemsNotReady.Count - 1 do
FTasks.Insert(0, FItemsNotReady[I]);
FItemsNotReady.Clear;
finally
FSync.Leave;
end;
end;
Result := FItems.ToArray();
finally
F(FItems);
F(FItemsNotReady);
end;
end;
function TUpdaterStorage.TakeOne<T>: T;
var
Tasks: TArray<T>;
begin
Tasks := Take<T>(1);
if Length(Tasks) = 0 then
Exit(nil);
Exit(Tasks[0]);
end;
{ TDatabaseUpdater }
constructor TDatabaseUpdater.Create;
begin
inherited Create(nil, False);
FSpeedCounter := TSpeedEstimateCounter.Create(60 * 1000); //60 sec is estimate period
end;
destructor TDatabaseUpdater.Destroy;
begin
F(FSpeedCounter);
inherited;
end;
procedure TDatabaseUpdater.Execute;
var
Task: TDatabaseTask;
AddTasks: TArray<TAddTask>;
UpdateTask: TUpdateTask;
RemoveTask: TRemoveTask;
RemoveDirectoryTask: TRemoveDirectoryTask;
UpdateAttributeTask: TUpdateAttributeTask;
IdleCycle: Boolean;
procedure NotifyTask(Task: string);
begin
TThread.Synchronize(nil,
procedure
begin
UpdaterStorage.CurrentUpdaterState := Task;
end
);
end;
begin
inherited;
FreeOnTerminate := True;
Priority := tpLowest;
//task will work in background
while True do
begin
if DBTerminating then
Break;
IdleCycle := True;
try
AddTasks := UpdaterStorage.Take<TAddTask>(cAddImagesAtOneStep);
try
if Length(AddTasks) > 0 then
begin
IdleCycle := False;
AddTasks[0].Execute(AddTasks);
FSpeedCounter.AddSpeedInterval(100 * Length(AddTasks));
UpdaterStorage.UpdateRemainingTime(FSpeedCounter);
NotifyTask(FormatEx(TA('Adding file "{0}"', 'System'), [AddTasks[0].FileName]));
end;
finally
for Task in AddTasks do
Task.Free;
end;
if DBTerminating then
Break;
UpdateTask := UpdaterStorage.TakeOne<TUpdateTask>();
try
if UpdateTask <> nil then
begin
IdleCycle := False;
UpdateTask.Execute;
FSpeedCounter.AddSpeedInterval(100 * 1);
NotifyTask(FormatEx(TA('Updating item "{0}"', 'System'), [UpdateTask.FileName]));
end;
finally
F(UpdateTask);
end;
if DBTerminating then
Break;
RemoveTask := UpdaterStorage.TakeOne<TRemoveTask>();
try
if RemoveTask <> nil then
begin
IdleCycle := False;
RemoveTask.Execute;
FSpeedCounter.AddSpeedInterval(100 * 1);
NotifyTask(FormatEx(TA('Deleting file "{0}"', 'System'), [RemoveTask.FileName]));
end;
finally
F(RemoveTask);
end;
RemoveDirectoryTask := UpdaterStorage.TakeOne<TRemoveDirectoryTask>();
try
if RemoveDirectoryTask <> nil then
begin
IdleCycle := False;
RemoveDirectoryTask.Execute;
FSpeedCounter.AddSpeedInterval(100 * 1);
NotifyTask(FormatEx(TA('Deleting directory "{0}"', 'System'), [RemoveDirectoryTask.FileName]));
end;
finally
F(RemoveDirectoryTask);
end;
UpdateAttributeTask := UpdaterStorage.TakeOne<TUpdateAttributeTask>();
try
if UpdateAttributeTask <> nil then
begin
IdleCycle := False;
UpdateAttributeTask.Execute;
FSpeedCounter.AddSpeedInterval(100 * 1);
NotifyTask(FormatEx(TA('Updating attributes for "{0}"', 'System'), [UpdateAttributeTask.FileName]));
end;
finally
F(UpdateAttributeTask);
end;
except
on e: Exception do
EventLog(e);
end;
if IdleCycle then
Sleep(100);
end;
end;
initialization
FStorageLock := TCriticalSection.Create;
finalization
F(FUpdaterStorage);
F(FStorageLock);
end.
|
unit TestUHistoricoController;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, DB, DBXJSON, ConexaoBD, Generics.Collections, UController, Classes,
SysUtils, DBClient, UHistoricoVO, UHistoricoController, DBXCommon, SQLExpr;
type
// Test methods for class THistoricoController
TestTHistoricoController = class(TTestCase)
strict private
FHistoricoController: THistoricoController;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestConsultarPorId;
procedure TestConsultaPorIdNaoEncontrado;
end;
implementation
procedure TestTHistoricoController.SetUp;
begin
FHistoricoController := THistoricoController.Create;
end;
procedure TestTHistoricoController.TearDown;
begin
FHistoricoController.Free;
FHistoricoController := nil;
end;
procedure TestTHistoricoController.TestConsultaPorIdNaoEncontrado;
var
ReturnValue: THistoricoVO;
begin
ReturnValue := FHistoricoController.ConsultarPorId(1000);
if ReturnValue <> nil then
check(false,'Pesquisado com sucesso!')
else
check(true,'Não encontrado!');
end;
procedure TestTHistoricoController.TestConsultarPorId;
var
ReturnValue: THistoricoVO;
begin
ReturnValue := FHistoricoController.ConsultarPorId(1);
if ReturnValue <> nil then
check(true,'Pesquisado com sucesso!')
else
check(false,'Não encontrado!');
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTHistoricoController.Suite);
end.
|
unit UDPClient;
interface
uses
UDPSocketUtils, PacketBuffer,
IdBaseComponent, IdComponent, IdUDPBase, IdUDPServer, IdSocketHandle,
Windows, SysUtils, Classes, ExtCtrls;
type
TUDPClient = class (TComponent)
private
FPacketData : TPacketData;
FPacketBuffer : TPacketBuffer;
FIdUDPClient: TIdUDPServer;
FTimer : TTimer;
procedure on_Timer(Sender:TObject);
procedure on_PRead(Sender: TObject; AData: TStream; ABinding: TIdSocketHandle);
private
FHost: string;
FPort: integer;
function GetDataInBuffer: integer;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Send(AData:pointer; ASize:integer); overload;
procedure SendText(AText:string);
published
property Host : string read FHost write FHost;
property Port : integer read FPort write FPort;
property DataInBuffer : integer read GetDataInBuffer;
end;
implementation
{ TUDPClient }
constructor TUDPClient.Create(AOwner: TComponent);
begin
inherited;
FPacketData := TPacketData.Create;
FPacketBuffer := TPacketBuffer.Create;
FIdUDPClient := TIdUDPServer.Create(Self);
FIdUDPClient.ThreadedEvent := true;
FIdUDPClient.OnUDPRead := on_PRead;
FTimer := TTimer.Create(Self);
FTimer.Interval := 5;
FTimer.OnTimer := on_Timer;
FTimer.Enabled := true;
end;
destructor TUDPClient.Destroy;
begin
FTimer.OnTimer := nil;
FreeAndNil(FTimer);
FreeAndNil(FIdUDPClient);
FreeAndNil(FPacketBuffer);
FreeAndNil(FPacketData);
inherited;
end;
function TUDPClient.GetDataInBuffer: integer;
begin
Result := FPacketBuffer.Count;
end;
procedure TUDPClient.on_PRead(Sender: TObject; AData: TStream;
ABinding: TIdSocketHandle);
begin
end;
procedure TUDPClient.on_Timer(Sender: TObject);
begin
FTimer.Enabled := false;
try
if FPacketBuffer.Count = 0 then Exit;
if FPacketData.IsEmpty then begin
FPacketData.LoadFromPacketBuffer(FPacketBuffer);
if FPacketData.IsEmpty then Exit;
end;
FIdUDPClient.SendBuffer(Host, Port, FPacketData.Data^, FPacketData.Size);
finally
FTimer.Enabled := true;
end;
end;
procedure TUDPClient.Send(AData: pointer; ASize: integer);
begin
FPacketBuffer.Add(AData, ASize);
end;
procedure TUDPClient.SendText(AText: string);
var
Data : pointer;
Size : integer;
ssData : TStringStream;
begin
ssData := TStringStream.Create(AText);
try
ssData.Position := 0;
Size := ssData.Size;
if Size <= 0 then Exit;
GetMem(Data, Size);
try
ssData.Read(Data^, Size);
FPacketBuffer.Add(Data, Size);
finally
FreeMem(Data);
end;
finally
ssData.Free;
end;
end;
end.
|
unit sdBasic;
{Basic code for double precision special functions}
interface
{$i std.inc}
{$ifdef BIT16}
{$N+}
{$endif}
uses DAMath;
(*************************************************************************
DESCRIPTION : Basic code for double precision special functions:
Definitions, constants, etc.
REQUIREMENTS : BP7, D1-D7/D9-D10/D12/D17-D18, FPC, VP, WDOSX
EXTERNAL DATA : ---
MEMORY USAGE : ---
DISPLAY MODE : ---
REMARK : ---
REFERENCES : Index in damath_info.txt/references
Version Date Author Modification
------- -------- ------- ------------------------------------------
1.00.00 05.02.13 W.Ehrhardt sdBasic: Initial BP7 version from AMath.sfbasic
1.00.01 05.02.13 we sdBasic: sfd_bernoulli
1.00.02 05.02.13 we sdMisc: sfd_agm, sfd_agm2
1.00.03 06.02.13 we sdEllInt: THexDblW constants for sfd_nome
1.00.04 06.02.13 we sdEllInt: adjusted some constants for double precision
1.00.05 06.02.13 we sdEllInt: changed test 0<x to x<-eps_d in sfd_ellint_?
1.00.06 06.02.13 we sdEllInt: changed test abs(t-Pi_2)
1.00.07 07.02.13 we sdMisc: sfd_LambertW, sfd_LambertW1
1.00.08 07.02.13 we sdEllInt: adjusted Carlson eps constants
1.00.09 07.02.13 we sdEllInt: sfd_EllipticPiC/CPi always with cel
1.00.10 07.02.13 we sdBasic: sfd_bernoulli with bx16 (halved iteration count)
1.00.11 07.02.13 we sdGamma: stirf, sfd_gaminv_small, sfd_gamma_medium
1.00.12 08.02.13 we sdGamma: sfd_lngcorr, sfd_gstar, lngamma_small, lanczos
1.00.13 08.02.13 we sdbasic: BoFHex as THexDblW
1.00.14 08.02.13 we sdGamma: sfd_fac, sfd_dfac, sfd_binomial, sfd_psi, sfd_poch1
1.00.15 08.02.13 we sdZeta: sfd_dilog, sfd_etaint, sfd_zetaint
1.00.16 09.02.13 we sdZeta: zetap with 53-bit logic from [19]
1.00.17 09.02.13 we sdZeta: etam1pos
1.00.18 09.02.13 we sdGamma: sfd_trigamma/tetragamma/pentagamma/polygamma
1.00.19 09.02.13 we sdZeta: sfd_cl2
1.00.20 10.02.13 we sdMisc: sfd_debye
1.00.21 10.02.13 we sdPoly: adjusted tol in lq_hf
1.00.22 10.02.13 we sdGamma: sfd_lngamma uses FacTab
1.00.23 10.02.13 we sdMisc: sfd_ri
1.00.24 10.02.13 we sdExpInt: sfd_ei
1.00.25 10.02.13 we sdExpInt: modified sfd_eiex to compute exp(x) if expx < 0
1.00.26 10.02.13 we sdExpInt: en_series avoids FPC nonsense
1.00.27 10.02.13 we sdExpInt: sfd_ssi, auxfg
1.00.28 11.02.13 we sdGamma: igam_aux, sfd_igprefix
1.00.29 11.02.13 we sdErf: erf_small, sfd_erfc_iusc, sfd_erfi
1.00.30 11.02.13 we sdErf: sfd_fresnel
1.00.31 12.02.13 we sdSDist: sfd_normstd_cdf, sfd_normstd_pdf
1.00.32 12.02.13 we sdZeta: sfd_fdm05, sfd_fdp05
1.00.33 12.02.13 we sdBessel: Constant IvMaxX in sfd_iv
1.00.34 12.02.13 we sdBessel: sfd_i0
1.00.35 12.02.13 we sdBessel: sfd_j0, sfd_y0, bess_m0p0
1.00.36 13.02.13 we sdBessel: sfd_j1, sfd_y1, bess_m1p1
1.00.37 13.02.13 we sdBessel: sfd_in
1.00.38 13.02.13 we sdBessel: fix two near overflow cases in bessel_jy
1.00.39 14.02.13 we sdBessel: Airy functions
1.00.40 14.02.13 we sdBessel: Kelvin functions
1.00.41 14.02.13 we sdBessel: Struve functions
1.00.42 15.02.13 we sdGamma: improved sfd_git
1.00.43 16.02.13 we sdZeta: improved sfd_zetah
1.00.44 20.02.13 we SpecFunD: SpecFunD_Version
1.00.45 01.03.13 we (some) Reduced some Chebyshev degrees
1.00.46 02.02.13 we sdBessel: Fixed value of IvMaxX in sfd_iv
1.01.00 15.03.13 we sdEllInt: Remaining Jacobi elliptic functions
1.01.01 25.03.13 we sdEllInt: Remaining inverse Jacobi elliptic functions
1.01.02 28.03.13 we sdZeta: sfd_zetah for s<0
1.01.03 28.03.13 we sdZeta: sfd_trilog
1.01.04 30.03.13 we sdZeta: sfd_zetah for a near 1 and s<0
1.01.05 30.03.13 we sdGamma: improved sfd_binomial
1.02.00 07.04.13 we sdSDist: Improved sfd_chi2_pdf for very small x
1.02.01 11.04.13 we sdZeta: sfd_fdp15
1.02.02 13.04.13 we sdSDist: k changed to longint in sfd_poisson_pmf
1.02.03 14.04.13 we sdSDist: sfd_rayleigh_pdf/cdf/inv
1.02.04 18.04.13 we sdGamma: improved sfd_beta
1.02.05 18.04.13 we sdGamma: ibeta_series with parameter normalised
1.02.06 18.04.13 we sdGamma: sfd_nnbeta
1.02.07 19.04.13 we sdSDist: sfd_maxwell_pdf/cdf/inv
1.02.08 20.04.13 we sdSDist: sfd_evt1_pdf/cdf/inv
1.02.09 20.04.13 we sdSDist: sfd_maxwell_cdf/inv with lower igamma functions
1.02.10 21.04.13 we sdGamma: lanczos_gm05 = lanczos_g - 0.5 in implementation
1.02.11 27.04.13 we sdGamma: polygam_negx for n=11,12
1.02.12 01.05.13 we SpecFunD: FresnelC/FresnelS
1.03.00 09.05.13 we sdBessel: Airy/Scorer functions sfd_airy_gi/hi
1.03.01 11.05.13 we sdGamma: improved sfd_polygamma for large order: e.g. (3001, 871)
1.03.02 13.05.13 we sdPoly: Change limits to 2e16 in p0ph,p1mh,p1ph
1.03.03 27.05.13 we sdHyperG: New Hypergeometric functions unit
1.03.04 27.05.13 we sdGamma: sfd_nnbeta for a<=0 or b<=0
1.03.05 31.05.13 we sdHyperG: AMath changes for sfd_chu
1.04.00 15.06.13 we sdBessel: Fix typo in h1v_large
1.04.01 15.06.13 we sdBessel: sfd_bess_kv2
1.04.02 15.06.13 we sdHyperG: Temme's chu and uabx from AMath
1.04.03 16.06.13 we sdHyperG: Whittaker functions sfd_whitm/sfd _whitw
1.04.04 28.06.13 we sdBessel: Check overflow / return INF in bessel_jy
1.04.05 28.06.13 we sdHyperG: sfd_0f1
1.04.06 01.07.13 we sdHyperG: sfd_0f1r
1.05.00 28.07.13 we sdHyperG: MAXIT=64 in h1f1_tricomi
1.05.01 28.07.13 we sdGamma: sfd_git for x<0
1.05.02 15.08.13 we sdSDist: Removed code fragment for y>1 in sfd_beta_inv
1.05.03 15.08.13 we sdSDist: Check a,b > 0 in sfd_beta_cdf
1.05.04 15.08.13 we sdSDist: sfd_kumaraswamy_pdf/cdf/inv
1.05.05 16.08.13 we sdZeta: sfd_zeta for small s
1.05.06 16.08.13 we sdZeta: sfd_polylog with sfd_zetaint
1.05.07 15.08.13 we sdErf: sfd_erf_z, sfd_erf_p, sfd_erf_q
1.05.08 18.08.13 we sdsDist: normal/normstd_pdf/cdf with erf_z and erf_p
1.06.00 07.09.13 we sdZeta: Improved sfd_zetah/hurwitz_formula
1.06.01 12.09.13 we sdZeta: Bernoulli polynomials sfd_bernpoly
1.06.02 18.09.13 we sdPoly: sfd_chebyshev_v/w
1.06.03 24.09.13 we sdMisc: sfd_cosint, sfd_sinint
1.06.04 25.09.13 we sdGamma: sfd_batemang
1.06.05 25.09.13 we (some) use const one_d to avoid FPC nonsense
1.06.06 26.09.13 we sdMisc: Fixed quasi-periodic code for sfd_cos/sinint
1.06.07 28.09.13 we sdEllInt: special_reduce_modpi, used in sfd_ellint_1/2/3 and sfd_hlambda
1.07.00 19.10.13 we sdsDist: sfd_moyal_pdf/cdf/inv
1.07.01 23.10.13 we sdEllInt: sfd_EllipticKim, sfd_EllipticECim
1.07.02 04.11.13 we sdSDist: improved sfd_t_pdf for small x^2/nu
1.08.00 26.12.13 we sdZeta: sfd_fdp25
1.09.00 24.03.14 we sdHyperG: chu_luke only with $ifdef in dchu
1.09.01 28.03.14 we sdBessel: sfd_yn with LnPi from DAMath
1.09.02 28.03.14 we sdHyperG: InfOrNan tests in sfd_1f1
1.10.00 18.04.14 we sdGamma: polygam_negx (larger n for x<0}
1.10.01 02.05.14 we sdZeta: sfd_harmonic
1.10.02 03.05.14 we sdZeta: sfd_harmonic2
1.10.03 04.05.14 we sdSDist: sfd_zipf_pmf/cdf
1.11.00 24.05.14 we sdMisc: sfd_ali functional inverse of sfc_li
1.11.01 29.05.14 we sdZeta: Removed redundancy in sfc_harmonic2
1.11.02 29.05.14 we sdZeta: polylogneg with array of single
1.11.03 30.05.14 we SpecFunD: Fix zipf_pmf/cdf function type
1.11.04 31.05.14 we sdZeta: Lobachevski sfd_llci, sfd_llsi; improved harm2core
1.11.05 04.06.14 we sdMisc: sfd_fpoly/sfd_lpoly
1.11.06 05.06.14 we sdSDist: sfd_levy_pdf/cdf/inv
1.12.00 16.06.14 we Incomplete/inverse functions moved to sdGamma2
1.12.01 16.06.14 we sdGamma: const lanczos_gm05: double
1.12.02 16.06.14 we sdGamma2: sfd_ibeta_inv (code from sdSDist)
1.12.03 16.06.14 we sdZeta: Fermi/Dirac, Lobachewsky, harmonic functions moved to sdZeta2
1.12.04 22.06.14 we sdGamma2: sfd_ilng (inverse of lngamma)
1.12.05 25.06.14 we sdGamma2: sfd_ipsi (inverse of psi)
1.12.06 03.07.14 we SpecFunD: ibeta_inv
1.12.07 13.07.14 we sdHyperG: sfc_pcfd,sfc_pcfu,sfc_pcfhh
1.13.00 30.07.14 we sdBasic: moebius[1..83]
1.13.01 30.07.14 we sdZeta: Improved and expanded primezeta sfd_pz
1.13.02 06.08.14 we sdGamma: First check IsNaND(x) in sfd_lngammas
1.13.03 06.08.14 we sdGamma: improved sfd_gdr_pos for small x
1.13.04 11.08.14 we sdBessel: Iv := PosInf_v if Kv,Kv1=0 in bessel_ik or if x >= IvMaxXH in sfc_iv
1.13.05 11.08.14 we sdGamma: special case x=x+y in sfd_beta
1.13.06 11.08.14 we sdHyperG: fix: sfc_pcfd,sfc_pcfu,sfc_pcfhh use double
1.13.07 17.08.14 we sdMisc: Catalan function sfd_catf
1.13.08 19.08.14 we sdHyperG: sfc_pcfv
1.13.09 20.08.14 we sdGamma: sfd_gamma_delta_ratio returns 1 if x=x+d
1.14.00 01.09.14 we sdHyperG: sfd_chu for x<0
1.14.01 04.09.14 we sdHyperG: fix h1f1_tricomi (division by t=0)
1.14.02 07.09.14 we sdSDist: sfd_logistic_inv uses logit function
1.14.03 06.10.14 we sdSDist: sfd_logistic_cdf uses logistic function
1.15.00 26.10.14 we sdHyperG: No Kummer transformation in 1F1 if b=0,-1,-2,...
1.15.01 29.10.14 we sdHyperG: 1F1 = 1 + a/b*(exp(x)-1) for very small a,b
1.15.02 07.11.14 we sdBasic: Small Bernoulli numbers B2nHex moved to DAMath
1.16.00 15.12.14 we sdGamma: small changes in sfc_batemang
1.16.01 16.12.14 we sdGamma2: Check IsNanOrInf in sfd_ilng
1.16.02 23.12.14 we sdSDist: sfd_invgamma_pdf/cdf/inv
1.16.03 26.12.14 we sdSDist: logarithmic (series) distribution
1.16.04 03.01.15 we sdSDist: sfd_wald_cdf/pdf/inv
1.16.05 05.01.15 we sdSDist: Error if k<1 in sfc_ls_cdf/pmf
1.16.06 05.01.15 we sdHyperG: Special case b=1 in gen_0f1
1.16.07 09.01.15 we sdMisc: Euler numbers sfd_euler
1.17.00 25.01.15 we sdExpInt: sfd_ali from sdMisc
1.17.01 25.01.15 we sdExpInt: sfd_ei_inv
1.17.02 28.03.15 we sdEllInt: sfd_cel_d, sfd_ellint_d
1.17.03 01.05.15 we sdExpInt: fix sfd_ei_inv for x Nan
1.18.00 18.05.15 we sdZeta: Improved sfd_etam1 (adjusted Borwein constants)
1.18.01 18.05.15 we sdZeta: sfd_polylogr and sfd_lerch for s >= -1
1.18.02 25.05.15 we sdZeta: sfd_lerch(1,s,a) for s<>1 and special case z=0
1.18.03 04.06.15 we sdBasic: remove CSInitD
1.18.04 04.06.15 we sdMisc: sfd_kepler
1.18.05 10.06.15 we sdBessel: new IJ_series replaces Jv_series
1.18.06 10.06.15 we sdBessel: rewrite of sfc_in: use IJ_series and CF1_I
1.18.07 10.06.15 we sdBessel: improved bess_m0p0/bess_m1p1 with rem_2pi_sym and Kahan summation
1.18.08 10.06.15 we sdBessel: sfd_struve_l/h, sfd_struve_l0/1 use sfd_struve_l
1.18.09 14.06.15 we sdBessel: sfd_struve_h/l with real nu >= 0
1.18.10 19.06.15 we sdBessel: scaled Airy functions sfd_airy_ais, sfd_airy_bis
1.18.11 22.06.15 we sdEllInt: avoid overflow in sfd_ell_rf, better arg checks in Carlson functions
1.18.12 22.06.15 we sdEllInt: Carlson sfd_ell_rg
1.18.13 26.06.15 we sdZeta2: Fix: Type double in sfd_fdp25 and harm2core
1.18.14 26.06.15 we sdHyperG: Fix: double variables in chu_negx
1.19.00 08.07.15 we sdBessel: special cases Yv(+- 1/2, x)
1.19.01 08.07.15 we sdBessel: sfd_struve_h/l for v < 0
1.19.02 08.07.15 we (most): removed NOBASM/BASM conditional defines
1.19.03 09.07.15 we sdBessel: fix sfd_struve_h/l(v,0) for v<=-1
1.19.04 19.07.15 we sdZeta: eta near s=1
1.19.05 19.07.15 we sdEllint: sfd_el1(x, kc) = arctan(x) for kc^2=1
1.19.06 01.08.15 we sdHyperG: Avoid some overflows in h2f1_sum, improved h2f1_trans
1.20.00 25.08.15 we (most): Use THREE & SIXX to avoid 'optimization'
1.20.01 25.08.15 we sdZeta: sfd_bernpoly: avoid integer overflow and FPC optimization error
1.20.02 26.08.15 we sdBessel: Sqrt2 in kelvin functions (anti-'optimizing')
1.21.00 26.09.15 we sdEllInt: lemniscate functions sin_lemn, cos_lemn
1.21.01 29.09.15 we sdHyperG: sfd_pcfv(a,x) for a < 0
1.21.02 11.10.15 we sdGamma: polygamma for x<0 uses Euler series for Pi*cot(Pi*x)
***************************************************************************)
(*-------------------------------------------------------------------------
(C) Copyright 2009-2015 Wolfgang Ehrhardt
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.
----------------------------------------------------------------------------*)
(*-------------------------------------------------------------------------
This Pascal code uses material and ideas from open source and public
domain libraries, see the file '3rdparty.ama' for the licenses.
---------------------------------------------------------------------------*)
const
SD_BaseVersion = '1.21.02';
const
RTE_NoConvergence: integer = 234; {RTE for no convergence, set negative}
{to continue (with inaccurate result)}
RTE_ArgumentRange: integer = 235; {RTE for argument(s) out of range, set}
{negative to continue with NAN result.}
{Tested if $R+ option is enabled}
procedure sincosPix2(x: double; var s,c: double);
{-Return s=sin(Pi/2*x^2), c=cos(Pi/2*x^2); (s,c)=(0,1) for abs(x) >= 2^53}
function sfd_bernoulli(n: integer): double;
{-Return the nth Bernoulli number, 0 if n<0 or odd n >= 3}
{#Z+}
{---------------------------------------------------------------------------}
{Moebius function æ(n) for small arguments}
const
n_moeb = 83;
moebius: array[1..n_moeb] of shortint = (
1, -1, -1, 0, -1, 1, -1, 0, 0, 1,
-1, 0, -1, 1, 1, 0, -1, 0, -1, 0,
1, 1, -1, 0, 0, 1, 0, 0, -1, -1,
-1, 0, 1, 1, 1, 0, -1, 1, 1, 0,
-1, -1, -1, 0, 0, 1, -1, 0, 0, 0,
1, 0, -1, 0, 1, 0, 1, 1, -1, 0,
-1, 1, 0, 0, 1, -1, -1, 0, 1, -1,
-1, 0, -1, 1, 0, 0, 1, -1, -1, 0,
0, 1, -1);
{---------------------------------------------------------------------------}
{Bernoulli numbers. The B(2n), n = 0..MaxB2nSmall are in DAMath}
const
MaxBernoulli = 259;
const
NBoF = 20;
BoFHex: array[0..NBoF] of THexDblW = ({Bernoulli(2k+2)/(2k+2)! }
($5555,$5555,$5555,$3FB5), {+8.3333333333333333336E-2}
($6C17,$16C1,$C16C,$BF56), {-1.3888888888888888888E-3}
($1567,$BC01,$566A,$3F01), {+3.3068783068783068783E-5}
($EF0B,$9334,$BD77,$BEAB), {-8.2671957671957671957E-7}
($0EBE,$2BF7,$6A8F,$3E56), {+2.0876756987868098980E-8}
($267F,$D644,$2805,$BE02), {-5.2841901386874931847E-10}
($9162,$C4E0,$6DB2,$3DAD), {+1.3382536530684678833E-11}
($955C,$1F79,$DA4E,$BD57), {-3.3896802963225828668E-13}
($2E9E,$1D65,$5587,$3D03), {+8.5860620562778445639E-15}
($ACF1,$68CA,$57D9,$BCAF), {-2.1748686985580618731E-16}
($376F,$F09C,$67E1,$3C59), {+5.5090028283602295151E-18}
($2B5C,$033A,$97D9,$BC04), {-1.3954464685812523341E-19}
($AD06,$D7C6,$B132,$3BB0), {+3.5347070396294674718E-21}
($1C16,$D59F,$0F72,$BB5B), {-8.9535174270375468504E-23}
($A26D,$A4CC,$EF2D,$3B05), {+2.2679524523376830603E-24}
($E38B,$F96D,$C77D,$BAB1), {-5.7447906688722024451E-26}
($1B62,$DE52,$D299,$3A5C), {+1.4551724756148649018E-27}
($74A7,$6565,$5CDE,$BA07), {-3.6859949406653101781E-29}
($4ADF,$DB3B,$EFE8,$39B2), {+9.3367342570950446721E-31}
($61FF,$9047,$B322,$B95E), {-2.3650224157006299346E-32}
($8464,$F932,$E25F,$3908)); {+5.9906717624821343044E-34}
{#Z-}
{$ifdef debug}
type
sfd_debug_str = string[255];
const
NDCTR = 8;
var
sfd_diagctr: array[0..NDCTR-1] of longint; {General counters for diagnostics}
sfd_debug_output: boolean; {Really doing the outputs if true}
procedure sfd_dump_diagctr;
{-writeln diagnostic counters}
procedure sfd_write_debug_str(const msg: sfd_debug_str);
{-Writeln or Outputdebugstr of msg}
{$endif}
implementation
{$ifdef Debug}
{$ifdef WIN32or64}
{$ifndef VirtualPascal}
{$define USE_OutputDebugString}
{$endif}
{$endif}
{$ifdef USE_OutputDebugString}
{$ifdef UNIT_SCOPE}
uses winapi.windows;
{$else}
uses windows;
{$endif}
{$endif}
{$endif}
{---------------------------------------------------------------------------}
procedure sincosPix2(x: double; var s,c: double);
{-Return s=sin(Pi/2*x^2), c=cos(Pi/2*x^2); (s,c)=(0,1) for abs(x) >= 2^53}
var
n,f,g: double;
begin
{Note that this routine is very sensible to argument changes! }
{Demo of sincosPix2 sensibility to argument changes }
{Computing sin(Pi/2*x^2) with sincosPix2 and MPArith for x=10000.1}
{mp_float default bit precision = 240, decimal precision = 72.2 }
{Machine eps for double = 2.22044604925E-0016 }
{d = x(double) = +10000.100000000000364 }
{x - d = -3.6379788070917129517E-13 }
{rel. diff = -3.6379424276674362773E-17 }
{a = sincosPix2 = 1.57073287395724723E-0002 }
{b = sin(Pi/2*x^2) = +1.5707317311820675753E-2 }
{c = sin(Pi/2*d^2) = +1.5707328739572472151E-2 }
{(c - b) = +1.1427751796397653663E-8 }
{(c - b)/b = +7.2754319337507758102E-7 }
{(c - a) = -1.2497147346576779516E-19 }
{(c - a)/b = -7.9562582829926944803E-18 }
if THexDblW(x)[3] and $7FF0 >= $4340 then begin
{abs(x) >= 2^53}
s := 0.0;
c := 1.0;
end
else begin
{c, s depend on frac(x) and int(x) mod 4. This code is based on }
{W. Van Snyder: Remark on algorithm 723: Fresnel integrals, 1993.}
{http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.101.7180}
{Fortran source from http://netlib.org/toms/723}
f := abs(x);
n := int(f);
f := f - n;
g := 2.0*frac(f*int(0.5*n));
if frac(0.5*n)=0.0 then sincosPi(0.5*f*f + g, s, c)
else begin
sincosPi((0.5*f*f + f) + g, c, s);
c := -c;
end;
end;
end;
{---------------------------------------------------------------------------}
function sfd_bernoulli(n: integer): double;
{-Return the nth Bernoulli number, 0 if n<0 or odd n >= 3}
var
bn,p4: double;
m: integer;
const
bx16: array[0..8] of THexDblw = ( {Bernoulli(16*n+128)}
($C7AA,$9397,$49D6,$D78B), {-5.2500923086774131347E+113}
($DC82,$055D,$312B,$DBFC), {-1.2806926804084747554E+135}
($F740,$CDB0,$7C97,$E095), {-1.8437723552033869952E+157}
($C6C9,$5F0A,$3B07,$E554), {-1.3116736213556958091E+180}
($6528,$135D,$5994,$EA34), {-3.9876744968232205368E+203}
($ED60,$24DA,$6069,$EF33), {-4.5902296220617917542E+227}
($3B1F,$D638,$879E,$F44F), {-1.8059559586909309354E+252}
($2A28,$6304,$1403,$F984), {-2.2244891682179835734E+277}
($3856,$7CD9,$8C92,$FED2)); {-7.9502125045885251673E+302}
begin
if odd(n) or (n<0) then begin
if n=1 then sfd_bernoulli := -0.5
else sfd_bernoulli := 0.0;
end
else begin
m := n div 2;
if m<=MaxB2nSmall then sfd_bernoulli := double(B2nHex[m])
else if n>MaxBernoulli then sfd_bernoulli := PosInf_d
else begin
{When n is even, B(2n) = -2*(-1)^n*m!/(2Pi)^m*zeta(m) with m=2n. For }
{large m (e.g. m>63) zeta(m) is very close to 1 and we can derive the}
{asymptotic recursion formula B(m+1) = -m*(m+1)/(2Pi)^2 * B(m). The }
{avg. iteration count is <2, the max.rel. error < 1.9*eps_d for n=100}
m := (n - 120) div 16;
bn := double(bx16[m]);
m := 16*m + 128;
p4 := 4.0*PiSqr;
if n>m then begin
while n>m do begin
inc(m,2);
bn := bn/p4*m*(1-m);
end;
end
else begin
while m>n do begin
bn := bn/m/(1-m)*p4;
dec(m,2);
end;
end;
sfd_bernoulli := bn;
end;
end;
end;
{$ifdef debug}
{$ifdef USE_OutputDebugString}
{---------------------------------------------------------------------------}
procedure sfd_write_debug_str(const msg: sfd_debug_str);
{-Writeln or Outputdebugstr of msg}
var
ax: ansistring;
begin
if sfd_debug_output then begin
if IsConsole then writeln(msg)
else begin
ax := msg;
OutputDebugString(pchar({$ifdef D12Plus}string{$endif}(ax)));
end;
end;
end;
{$else}
{---------------------------------------------------------------------------}
procedure sfd_write_debug_str(const msg: sfd_debug_str);
{-Writeln or Outputdebugstr of msg}
begin
if sfd_debug_output then writeln(msg);
end;
{$endif}
{---------------------------------------------------------------------------}
procedure sfd_dump_diagctr;
{-writeln diagnostic counters}
var
k: integer;
begin
write('Diag ctr:');
for k:=0 to NDCTR-1 do write(k:3,':',sfd_diagctr[k]);
writeln;
end;
begin
sfd_debug_output := false;
fillchar(sfd_diagctr, sizeof(sfd_diagctr),0);
{$endif}
end.
|
{: Projected Textures example.<p>
Controls:
Left Mouse Button: Rotate
Right Mouse Button: Adjust Distance
'S': Change styles
The TGLProjectedTextures object can be used to simulate
projected lights or other special effects. To use it, add
it to the scene and set all objects that should receive
the projected textures as children. Then, add a number
of TGLTextureEmitter and load the texture that should
be projected into it. Add this emitter to the "emitters"
list of the projtex and that's it.
There are two styles of projection: original and inverse.
On the original method (developed by Tom Nuyens of
www.delphi3d.net) the scene is rendered and the textures
are projected into it. This is useful to simulate all
kinds of special effects from bullet holes, to shadow
maps (using tmBlend texture mode).
On the inverse method, first all emitters are rendered,
creating an "illumination mask". Then the scene is blended
to this mask, so that only lit pixels are drawn. This can
be used to create a projected-texture only illumination system.
}
unit Unit1;
interface
uses
SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
GLCadencer, GLScene, GLLCLViewer, glTexture, tga, GLObjects,
GLVectorGeometry, ExtCtrls, glProjectedTextures,
GLHUDObjects, GLCrossPlatform, GLMaterial, GLCoordinates, GLBaseClasses;
type
TForm1 = class(TForm)
viewer: TGLSceneViewer;
scene: TGLScene;
GLCadencer1: TGLCadencer;
camera: TGLCamera;
GLPlane1: TGLPlane;
GLPlane2: TGLPlane;
GLPlane3: TGLPlane;
scenery: TGLDummyCube;
GLSphere1: TGLSphere;
matLib: TGLMaterialLibrary;
Timer1: TTimer;
Light: TGLDummyCube;
GLLightSource1: TGLLightSource;
GLCube1: TGLCube;
GLCube2: TGLCube;
light2: TGLDummyCube;
GLSphere2: TGLSphere;
GLSphere3: TGLSphere;
ProjLight: TGLProjectedTextures;
emitter1: TGLTextureEmitter;
emitter2: TGLTextureEmitter;
procedure GLCadencer1Progress(Sender: TObject;
const deltaTime, newTime: double);
procedure FormCreate(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure viewerMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: integer);
procedure viewerMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: integer);
procedure viewerMouseMove(Sender: TObject; Shift: TShiftState; X, Y: integer);
procedure FormKeyDown(Sender: TObject; var Key: word; Shift: TShiftState);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
ang: single;
mx, my, mk: integer;
implementation
{$R *.lfm}
uses GLUtils, LCLType;
procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: double);
begin
ang := ang + deltatime * 20;
Light.Position.Y := sin(degToRad(ang));
light.position.x := cos(degToRad(ang));
light2.pitch(deltatime * 20);
viewer.invalidate;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
SetGLSceneMediaDir();
matLib.Materials[0].Material.Texture.Image.LoadFromFile('projector.tga');
matLib.Materials[1].Material.Texture.Image.LoadFromFile('flare1.bmp');
emitter1.Material.MaterialLibrary := matLib;
emitter1.Material.LibMaterialName := 'spot';
emitter2.Material.MaterialLibrary := matLib;
emitter2.Material.LibMaterialName := 'spot2';
emitter2.FOVy := 40;
GLPlane1.Material.Texture.Image.LoadFromFile('cm_front.jpg');
GLPlane2.Material.Texture.Image.LoadFromFile('cm_left.jpg');
GLPlane3.Material.Texture.Image.LoadFromFile('cm_bottom.jpg');
projLight.Emitters.AddEmitter(emitter1);
projLight.Emitters.AddEmitter(emitter2);
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
form1.Caption := format('%f', [viewer.framespersecond]);
viewer.resetperformancemonitor;
end;
procedure TForm1.viewerMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: integer);
begin
mk := 1;
mx := x;
my := y;
end;
procedure TForm1.viewerMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: integer);
begin
mk := 0;
end;
procedure TForm1.viewerMouseMove(Sender: TObject; Shift: TShiftState; X, Y: integer);
begin
if mk = 1 then
begin
if shift = [ssLeft] then
camera.MoveAroundTarget(y - my, x - mx)
else if shift = [ssRight] then
camera.AdjustDistanceToTarget(1.0 + (y - my) / 100);
end;
mx := x;
my := y;
end;
procedure TForm1.FormKeyDown(Sender: TObject; var Key: word; Shift: TShiftState);
begin
if key = VK_ADD then
emitter1.FOVy := emitter1.FOVy + 5
else if key = VK_SUBTRACT then
emitter1.FOVy := emitter1.FOVy - 5;
if chr(Key) = 'S' then
if ProjLight.style = ptsOriginal then
ProjLight.style := ptsInverse
else
ProjLight.style := ptsOriginal;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.