text stringlengths 14 6.51M |
|---|
// GLScriptBase
{: An abstract scripting interface for GLScene<p>
This unit provides the base methods for compiling and executing scripts as
well as calling scripted functions. No scripting APIs are implemented here,
only abstracted functions.<p>
<b>History : </b><font size=-1><ul>
<li>04/11/2004 - SG - Creation
</ul></font>
}
unit GLScriptBase;
interface
uses
Classes, XCollection;
type
TGLScriptState = ( ssUncompiled, // The script has yet to be compiled.
ssCompileErrors, // Errors occurred while compiling.
ssCompiled, // The script has been compiled and is
// ready to be executed/started.
ssRunningErrors, // Errors occured while the script was
// running.
ssRunning ); // The script is currently active and
// is running without error.
// TGLScriptBase
//
{: The base script class that defines the abstract functions and properties.
Don't use this class directly, use the script classes descended from this
base class. }
TGLScriptBase = class(TXCollectionItem)
private
{ Private Declarations }
FText : TStringList;
FDescription : String;
FErrors : TStringList; // not persistent
protected
{ Protected Declarations }
procedure WriteToFiler(writer : TWriter); override;
procedure ReadFromFiler(reader : TReader); override;
function GetState : TGLScriptState; virtual; abstract;
procedure SetText(const Value : TStringList);
procedure Notification(AComponent: TComponent; Operation: TOperation); virtual;
public
{ Public Declarations }
constructor Create(aOwner : TXCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure Compile; virtual; abstract;
procedure Start; virtual; abstract;
procedure Stop; virtual; abstract;
procedure Execute; virtual; abstract;
procedure Invalidate; virtual; abstract;
function Call(aName : String;
aParams : array of Variant) : Variant; virtual; abstract;
property Errors : TStringList read FErrors;
property State : TGLScriptState read GetState;
published
{ Published Declarations }
property Text : TStringList read FText write SetText;
property Description : String read FDescription write FDescription;
end;
// TGLScripts
//
{: XCollection descendant for storing and handling scripts. }
TGLScripts = class(TXCollection)
private
{ Private Declarations }
protected
{ Protected Declarations }
function GetItems(index : Integer) : TGLScriptBase;
public
{ Public Declarations }
procedure Assign(Source: TPersistent); override;
class function ItemsClass : TXCollectionItemClass; override;
function CanAdd(aClass : TXCollectionItemClass) : Boolean; override;
property Items[index : Integer] : TGLScriptBase read GetItems; default;
end;
// TGLScriptLibrary
//
{: Encapsulation of the scripts XCollection to help with script handling at
design-time. Links the scripts to Delphi's persistence model. }
TGLScriptLibrary = class (TComponent)
private
{ Private Declarations }
FScripts : TGLScripts;
protected
{ Protected Declarations }
procedure DefineProperties(Filer : TFiler); override;
procedure WriteScriptsData(Stream : TStream);
procedure ReadScriptsData(Stream : TStream);
procedure Loaded; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
{ Public Declarations }
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
published
{ Published Declarations }
property Scripts : TGLScripts read FScripts;
end;
implementation
// ---------------
// --------------- TGLScriptBase ---------------
// ---------------
// Create
//
constructor TGLScriptBase.Create(aOwner: TXCollection);
begin
inherited;
FText:=TStringList.Create;
FErrors:=TStringList.Create;
end;
// Destroy
//
destructor TGLScriptBase.Destroy;
begin
FText.Free;
FErrors.Free;
inherited;
end;
// Assign
//
procedure TGLScriptBase.Assign(Source: TPersistent);
begin
inherited;
if Source is TGLScriptBase then begin
Text.Assign(TGLScriptBase(Source).Text);
Description:=TGLScriptBase(Source).Description;
end;
end;
// ReadFromFiler
//
procedure TGLScriptBase.ReadFromFiler(reader: TReader);
var
archiveVersion : Integer;
begin
inherited;
archiveVersion:=reader.ReadInteger;
Assert(archiveVersion = 0);
with reader do begin
FText.Text:=ReadString;
FDescription:=ReadString;
end;
end;
// WriteToFiler
//
procedure TGLScriptBase.WriteToFiler(writer: TWriter);
begin
inherited;
writer.WriteInteger(0);
with writer do begin
WriteString(FText.Text);
WriteString(FDescription);
end;
end;
// SetText
//
procedure TGLScriptBase.SetText(const Value : TStringList);
begin
Text.Assign(Value);
end;
// Notification
//
procedure TGLScriptBase.Notification(AComponent: TComponent; Operation: TOperation);
begin
// Virtual
end;
// ---------------
// --------------- TGLScripts ---------------
// ---------------
// Assign
//
procedure TGLScripts.Assign(Source: TPersistent);
begin
inherited;
// Nothing yet
end;
// GetItems
//
function TGLScripts.GetItems(index: Integer): TGLScriptBase;
begin
Result:=TGLScriptBase(inherited GetItems(index));
end;
// ItemsClass
//
class function TGLScripts.ItemsClass: TXCollectionItemClass;
begin
Result:=TGLScriptBase;
end;
// CanAdd
//
function TGLScripts.CanAdd(aClass: TXCollectionItemClass): Boolean;
begin
Result:=aClass.InheritsFrom(TGLScriptBase);
end;
// ---------------
// --------------- TGLScriptLibrary ---------------
// ---------------
// Create
//
constructor TGLScriptLibrary.Create(AOwner : TComponent);
begin
inherited;
FScripts:=TGLScripts.Create(Self);
end;
// Destroy
//
destructor TGLScriptLibrary.Destroy;
begin
FScripts.Free;
inherited;
end;
// DefineProperties
//
procedure TGLScriptLibrary.DefineProperties(Filer : TFiler);
begin
inherited;
Filer.DefineBinaryProperty('ScriptsData',
ReadScriptsData, WriteScriptsData, (Scripts.Count>0));
end;
// WriteScriptsData
//
procedure TGLScriptLibrary.WriteScriptsData(Stream : TStream);
var
writer : TWriter;
begin
writer:=TWriter.Create(stream, 16384);
try
Scripts.WriteToFiler(writer);
finally
writer.Free;
end;
end;
// ReadScriptsData
//
procedure TGLScriptLibrary.ReadScriptsData(Stream : TStream);
var
reader : TReader;
begin
reader:=TReader.Create(stream, 16384);
try
Scripts.ReadFromFiler(reader);
finally
reader.Free;
end;
end;
// Loaded
//
procedure TGLScriptLibrary.Loaded;
begin
inherited;
Scripts.Loaded;
end;
// Notification
//
procedure TGLScriptLibrary.Notification(AComponent: TComponent; Operation: TOperation);
var
i : Integer;
begin
if Assigned(Scripts) then
for i:=0 to Scripts.Count-1 do
Scripts[i].Notification(AComponent, Operation);
inherited;
end;
initialization
RegisterClasses([TGLScriptLibrary, TGLScripts, TGLScriptBase]);
end.
|
unit UProduto;
interface
uses UGenerico, UMarca, UCategoria, UUnidade, UNcm;
type Produto = class(Generico)
protected
umaMarca : Marca;
umaCategoria : Categoria;
unidade : string[4];
umNcm : Ncm;
cst : string[4];
quantidade : Real;
icms : Real;
ipi : Real;
precoCompra : Double;
precoVenda : Real;
icmsAnterior : Real;
ipiAnterior : Real;
precoCompraAnt : Real;
observacao : string[255];
public
Constructor CrieObjeto;
Destructor Destrua_Se;
Procedure setUmaMarca (vUmaMarca : Marca);
Procedure setUmaCategoria (vUmaCategoria : Categoria);
Procedure setUnidade (vUnidade : String);
Procedure setUmNcm (vNcm : Ncm);
Procedure setCst (vCst : String);
Procedure setQuantidade (vQuantidade : Real);
Procedure setICMS (vICMS : Real);
Procedure setIPI (vIPI : Real);
Procedure setPrecoCompra (vPrecoCompra : Double);
Procedure setPrecoVenda (vPrecoVenda : Real);
Procedure setICMSAnterior (vICMSAnterior : Real);
Procedure setIPIAnterior (vIPIAnterior : Real);
Procedure setPrecoCompraAnt (vPrecoCompraAnt : Real);
Procedure setObservacao (vObservacao : String);
Function getUmaMarca : Marca;
Function getUmaCategoria : Categoria;
Function getUnidade : String;
Function getUmNcm : Ncm;
Function getCst : String;
Function getQuantidade : Real;
Function getICMS : Real;
Function getIPI : Real;
Function getPrecoCompra : Double;
Function getPrecoVenda : Real;
Function getICMSAnterior : Real;
Function getIPIAnterior : Real;
Function getPrecoCompraAnt : Real;
Function getObservacao : String;
end;
implementation
{ Produto }
constructor Produto.CrieObjeto;
begin
inherited;
umaMarca := Marca.CrieObjeto;
umaCategoria := Categoria.CrieObjeto;
unidade := '';
umNcm := Ncm.CrieObjeto;
cst := '';
quantidade := 0;
icms := 0;
ipi := 0;
precoCompra := 0;
precoVenda := 0;
icmsAnterior := 0;
ipiAnterior := 0;
precoCompraAnt := 0;
observacao := '';
end;
destructor Produto.Destrua_Se;
begin
end;
function Produto.getCst: String;
begin
Result := cst;
end;
function Produto.getICMS: Real;
begin
Result := ICMS;
end;
function Produto.getICMSAnterior: Real;
begin
Result := icmsAnterior;
end;
function Produto.getIPI: Real;
begin
Result := IPI;
end;
function Produto.getIPIAnterior: Real;
begin
Result := ipiAnterior;
end;
function Produto.getObservacao: String;
begin
Result := Observacao;
end;
function Produto.getPrecoCompra: Double;
begin
Result:= precoCompra;
end;
function Produto.getPrecoCompraAnt: Real;
begin
Result := precoCompraAnt;
end;
function Produto.getPrecoVenda: Real;
begin
Result := precoVenda;
end;
function Produto.getQuantidade: Real;
begin
Result := Quantidade;
end;
function Produto.getUmaCategoria: Categoria;
begin
Result := umaCategoria;
end;
function Produto.getUmaMarca: Marca;
begin
Result := umaMarca;
end;
function Produto.getUmNcm: Ncm;
begin
Result := umNcm;
end;
function Produto.getUnidade: String;
begin
Result := unidade;
end;
procedure Produto.setCst(vCst: String);
begin
cst := vCst;
end;
procedure Produto.setICMS(vICMS: Real);
begin
ICMS := vICMS
end;
procedure Produto.setICMSAnterior(vICMSAnterior: Real);
begin
icmsAnterior := vICMSAnterior;
end;
procedure Produto.setIPI(vIPI: Real);
begin
IPI := vIPI;
end;
procedure Produto.setIPIAnterior(vIPIAnterior: Real);
begin
ipiAnterior := vIPIAnterior;
end;
procedure Produto.setObservacao(vObservacao: String);
begin
Observacao := vObservacao;
end;
procedure Produto.setPrecoCompra(vPrecoCompra: Double);
begin
PrecoCompra := vPrecoCompra;
end;
procedure Produto.setPrecoCompraAnt(vPrecoCompraAnt: Real);
begin
precoCompraAnt := vPrecoCompraAnt;
end;
procedure Produto.setPrecoVenda(vPrecoVenda: Real);
begin
PrecoVenda := vPrecoVenda;
end;
procedure Produto.setQuantidade(vQuantidade: Real);
begin
Quantidade := vQuantidade;
end;
procedure Produto.setUmaCategoria(vUmaCategoria: Categoria);
begin
umaCategoria := vUmaCategoria;
end;
procedure Produto.setUmaMarca(vUmaMarca: Marca);
begin
umaMarca := vUmaMarca;
end;
procedure Produto.setUmNcm(vNcm: Ncm);
begin
umNcm := vNcm;
end;
procedure Produto.setUnidade(vUnidade: String);
begin
unidade := vUnidade;
end;
end.
|
unit uFileOperaHandler;
interface
uses
SimpleMsgPack, SysUtils, Windows, Classes, Math, uCRCTools,
uZipTools;
type
TFileOperaHandler = class(TObject)
private
class function getBasePath():String;
class procedure forceDirectoryOfFile(pvFile:String);
class function extractServerFileName(pvDataObject: TSimpleMsgPack):String;
class procedure pathWithoutBackslash(var vPath: String);
private
class function BigFileSize(const AFileName: string): Int64;
class procedure writeFileINfo(pvINfo: TSimpleMsgPack; const AFileName: string);
/// <summary>TFileOperaHandler.FileRename
/// </summary>
/// <returns> Boolean
/// </returns>
/// <param name="pvSrcFile"> 完整文件名 </param>
/// <param name="pvNewFileName"> 不带路径文件名 </param>
class function FileRename(pvSrcFile:String; pvNewFileName:string): Boolean;
class procedure downFileData(pvDataObject:TSimpleMsgPack);
class procedure uploadFileData(pvDataObject:TSimpleMsgPack);
/// <summary>
/// 复制一个文件
/// {
/// "catalog":"doc",
/// "fileName":"dev\a.doc", //源文件
/// "newFile":"dev\b.doc" //新文件
/// }
/// </summary>
class procedure executeCopyAFile(pvDataObject:TSimpleMsgPack);
//获取文件信息
class procedure readFileINfo(pvDataObject:TSimpleMsgPack);
//删除文件
class procedure FileDelete(pvDataObject:TSimpleMsgPack);
public
class procedure Execute(pvDataObject: TSimpleMsgPack);
end;
implementation
uses
utils.safeLogger;
{ TFTPWrapper_ProgressBar }
class function TFileOperaHandler.BigFileSize(const AFileName: string): Int64;
var
sr: TSearchRec;
begin
try
if SysUtils.FindFirst(AFileName, faAnyFile, sr) = 0 then
result := Int64(sr.FindData.nFileSizeHigh) shl Int64(32) + Int64(sr.FindData.nFileSizeLow)
else
result := -1;
finally
SysUtils.FindClose(sr);
end;
end;
class procedure TFileOperaHandler.Execute(pvDataObject: TSimpleMsgPack);
var
lvCMDIndex:Integer;
begin
lvCMDIndex := pvDataObject.ForcePathObject('cmd.index').AsInteger;
case lvCMDIndex of
1: // 下载文件
begin
downFileData(pvDataObject);
end;
2: //上传文件
begin
uploadFileData(pvDataObject);
// 删除文件数据
pvDataObject.DeleteObject('data');
end;
3: //读取文件信息
begin
readFileINfo(pvDataObject);
end;
4: //删除
begin
FileDelete(pvDataObject);
end;
5: // copy一个文件
begin
executeCopyAFile(pvDataObject);
end;
end;
end;
class function TFileOperaHandler.extractServerFileName(pvDataObject: TSimpleMsgPack): String;
var
lvPath, lvTempStr:String;
begin
Result := pvDataObject.S['fileName'];
if pvDataObject.S['catalog'] <> '' then
begin
lvTempStr := pvDataObject.S['catalog'];
pathWithoutBackslash(lvPath);
Result := lvTempStr + '\' + Result;
end;
lvPath := getBasePath;
pathWithoutBackslash(lvPath);
Result := lvPath + '\' + Result;
end;
class procedure TFileOperaHandler.FileDelete(pvDataObject: TSimpleMsgPack);
var
lvFileName:String;
begin
lvFileName:= extractServerFileName(pvDataObject);
if not FileExists(lvFileName) then
raise Exception.CreateFmt('(%s)文件不存在!', [pvDataObject.S['fileName']]);
if not SysUtils.DeleteFile(lvFileName) then
begin
RaiseLastOSError;
end;
// if FileExists(lvFileName) then
// begin
//
// end;
end;
class function TFileOperaHandler.FileRename(pvSrcFile:String;
pvNewFileName:string): Boolean;
var
lvNewFile:String;
begin
lvNewFile := ExtractFilePath(pvSrcFile) + ExtractFileName(pvNewFileName);
Result := MoveFile(pchar(pvSrcFile), pchar(lvNewFile));
end;
class procedure TFileOperaHandler.forceDirectoryOfFile(pvFile: String);
var
lvPath:String;
begin
lvPath := ExtractFilePath(pvFile);
pathWithoutBackslash(lvPath);
ForceDirectories(lvPath);
end;
class function TFileOperaHandler.getBasePath: String;
begin
Result := ExtractFilePath(ParamStr(0)) + 'files\';
end;
class procedure TFileOperaHandler.pathWithoutBackslash(var vPath: String);
var
lvLen:Integer;
begin
while True do
begin
lvLen := Length(vPath);
if lvLen = 0 then Break;
if vPath[lvLen] in ['/', '\'] then Delete(vPath, lvLen, 1) else
begin
Break;
end;
end;
end;
class procedure TFileOperaHandler.readFileINfo(pvDataObject: TSimpleMsgPack);
const
SEC_SIZE = 1024 * 4;
var
lvFileName:String;
lvINfo:TSimpleMsgPack;
begin
lvFileName := extractServerFileName(pvDataObject);
pvDataObject.DeleteObject('info');
if not FileExists(lvFileName) then
begin
pvDataObject.I['info.exists'] := -1; //不存在
exit;
end else
begin
lvINfo := pvDataObject.ForcePathObject('info');
writeFileINfo(lvINfo, lvFileName);
end;
end;
class procedure TFileOperaHandler.executeCopyAFile(pvDataObject:TSimpleMsgPack);
var
lvFileName, lvNewFile:String;
lvPath, lvTempStr:String;
begin
lvFileName := pvDataObject.S['fileName'];
lvNewFile := pvDataObject.S['newFile'];
if pvDataObject.S['catalog'] <> '' then
begin
lvTempStr := pvDataObject.S['catalog'];
pathWithoutBackslash(lvPath);
lvFileName := lvTempStr + '\' + lvFileName;
lvNewFile := lvTempStr + '\' + lvNewFile;
end;
lvPath := getBasePath;
pathWithoutBackslash(lvPath);
lvFileName := lvPath + '\' + lvFileName;
lvNewFile := lvPath + '\' + lvNewFile;
if not FileExists(lvFileName) then raise Exception.CreateFmt('(%s)文件不存在!', [pvDataObject.S['fileName']]);
if not Windows.CopyFile(PChar(lvFileName),
PChar(lvNewFile), False) then
begin
RaiseLastOSError;
end;
end;
class procedure TFileOperaHandler.downFileData(pvDataObject:TSimpleMsgPack);
const
SEC_SIZE = 1024 * 1024; //50K
var
lvFileStream:TFileStream;
lvFileName:String;
lvSize:Cardinal;
begin
lvFileName:= extractServerFileName(pvDataObject);
if not FileExists(lvFileName) then raise Exception.CreateFmt('(%s)文件不存在!', [pvDataObject.S['fileName']]);
lvFileStream := TFileStream.Create(lvFileName, fmOpenRead or fmShareDenyWrite);
try
lvFileStream.Position := pvDataObject.I['start'];
pvDataObject.Clear();
pvDataObject.I['fileSize'] := lvFileStream.Size;
lvSize := Min(SEC_SIZE, lvFileStream.Size-lvFileStream.Position);
sfLogger.logMessage('size:%d/%d', [lvSize, lvFileStream.Position], 'debug_output');
// 文件数据
pvDataObject.ForcePathObject('data').LoadBinaryFromStream(lvFileStream, lvSize);
pvDataObject.I['blockSize'] := lvSize;
finally
lvFileStream.Free;
end;
end;
class procedure TFileOperaHandler.uploadFileData(pvDataObject:TSimpleMsgPack);
var
lvFileStream:TFileStream;
lvFileName, lvRealFileName:String;
begin
lvFileName:= extractServerFileName(pvDataObject);
// 第一次传输
if pvDataObject.I['start'] = 0 then
begin
// 删除原有文件
if FileExists(lvFileName) then SysUtils.DeleteFile(lvFileName);
end;
lvRealFileName := lvFileName;
forceDirectoryOfFile(lvRealFileName);
lvFileName := lvFileName + '.temp';
if pvDataObject.I['start'] = 0 then
begin // 第一传送 删除临时文件
if FileExists(lvFileName) then SysUtils.DeleteFile(lvFileName);
end;
if FileExists(lvFileName) then
begin
lvFileStream := TFileStream.Create(lvFileName, fmOpenReadWrite);
end else
begin
lvFileStream := TFileStream.Create(lvFileName, fmCreate);
end;
try
lvFileStream.Position := pvDataObject.I['start'];
pvDataObject.ForcePathObject('data').SaveBinaryToStream(lvFileStream);
finally
lvFileStream.Free;
end;
if pvDataObject.B['eof'] then
begin
FileRename(lvFileName, lvRealFileName);
end;
end;
class procedure TFileOperaHandler.writeFileINfo(pvINfo: TSimpleMsgPack; const
AFileName: string);
var
lvFileStream:TFileStream;
begin
if FileExists(AFileName) then
begin
lvFileStream := TFileStream.Create(AFileName, fmOpenRead);
try
pvINfo.I['size'] := lvFileStream.Size;
if pvINfo.B['cmd.checksum'] then
begin // 获取checksum值
pvINfo.I['checksum'] := TZipTools.verifyStream(lvFileStream, 0);
end;
finally
lvFileStream.Free;
end;
end;
end;
end.
|
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+}
{$M 16384,0,0}
{
by Behdad Esfahbod
Algorithmic Problems Book
April '2000
Problem 120 O(N3) Floyd Alg.
}
program
BestPath;
const
MaxN = 100;
var
N, M : Integer;
G : array [1 .. MaxN, 1 .. MaxN] of Longint;
P : array [1 .. MaxN, 1 .. MaxN] of Byte;
I, J, K, L : Integer;
procedure ReadInput;
begin
FillChar(G, SizeOf(G), 1);
Assign(Input, 'input.txt');
Reset(Input);
Readln(N, M);
for I := 1 to M do
begin
Readln(J, K, L);
G[J, K] := L;
end;
Close(Input);
end;
procedure WritePath (I, J : Integer);
begin
if P[I, J] <> 0 then
begin
WritePath(I, P[I, J]);
Write(P[I, J], ' ');
WritePath(P[I, J], J);
end;
end;
procedure WriteOutput;
begin
Assign(Output, 'output.txt');
Rewrite(Output);
if G[1, 2] > 1000000 then
Writeln('No Solution')
else
begin
Writeln(G[1, 2]);
Write(1, ' ');
WritePath(1, 2);
Writeln(2);
end;
Close(Output);
end;
procedure Floyd;
begin
for K := 1 to N do
for I := 1 to N do
for J := 1 to N do
if (G[I, J] > G[I, K]) and (G[I, J] > G[K, J]) then
begin
G[I, J] := G[I, K];
if G[I, J] < G[K, J] then
G[I, J] := G[K, J];
P[I, J] := K;
end;
end;
begin
ReadInput;
Floyd;
WriteOutput;
end.
|
// ===============================================================================
// | THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF |
// | ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO |
// | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A |
// | PARTICULAR PURPOSE. |
// | Copyright (c)2010 ADMINSYSTEM SOFTWARE LIMITED |
// |
// | Project: It demonstrates how to use EASendMailObj to send email with synchronous mode
// |
// | Author: Ivan Lui ( ivan@emailarchitect.net )
// ===============================================================================
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, EASendMailObjLib_TLB, StdCtrls;
type
TForm1 = class(TForm)
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
textFrom: TEdit;
textTo: TEdit;
textCc: TEdit;
textSubject: TEdit;
Label5: TLabel;
GroupBox1: TGroupBox;
Label6: TLabel;
textServer: TEdit;
chkAuth: TCheckBox;
Label7: TLabel;
Label8: TLabel;
textUser: TEdit;
textPassword: TEdit;
chkSSL: TCheckBox;
chkSign: TCheckBox;
chkEncrypt: TCheckBox;
Label9: TLabel;
lstCharset: TComboBox;
Label10: TLabel;
textAttachment: TEdit;
btnAdd: TButton;
btnClear: TButton;
textBody: TMemo;
btnSend: TButton;
lstProtocol: TComboBox;
procedure FormCreate(Sender: TObject);
procedure InitCharset();
procedure btnSendClick(Sender: TObject);
procedure chkAuthClick(Sender: TObject);
function ChAnsiToWide(const StrA: AnsiString): WideString;
procedure btnAddClick(Sender: TObject);
procedure DirectSend(oSmtp: TMail);
procedure btnClearClick(Sender: TObject);
procedure FormResize(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
const
CRYPT_MACHINE_KEYSET = 32;
CRYPT_USER_KEYSET = 4096;
CERT_SYSTEM_STORE_CURRENT_USER = 65536;
CERT_SYSTEM_STORE_LOCAL_MACHINE = 131072;
var
Form1: TForm1;
m_arAttachments : TStringList;
m_arCharset: array[0..27,0..1] of WideString;
implementation
{$R *.dfm}
procedure TForm1.InitCharset();
var
i, index: integer;
begin
index := 0;
m_arCharset[index, 0] := 'Arabic(Windows)';
m_arCharset[index, 1] := 'windows-1256';
index := index + 1;
m_arCharset[index, 0] := 'Baltic(ISO)';
m_arCharset[index, 1] := 'iso-8859-4';
index := index + 1;
m_arCharset[index, 0] := 'Baltic(Windows)';
m_arCharset[index, 1] := 'windows-1257';
index := index + 1;
m_arCharset[index, 0] := 'Central Euporean(ISO)';
m_arCharset[index, 1] := 'iso-8859-2';
index := index + 1;
m_arCharset[index, 0] := 'Central Euporean(Windows)';
m_arCharset[index, 1] := 'windows-1250';
index := index + 1;
m_arCharset[index, 0] := 'Chinese Simplified(GB18030)';
m_arCharset[index, 1] := 'GB18030';
index := index + 1;
m_arCharset[index, 0] := 'Chinese Simplified(GB2312)';
m_arCharset[index, 1] := 'gb2312';
index := index + 1;
m_arCharset[index, 0] := 'Chinese Simplified(HZ)';
m_arCharset[index, 1] := 'hz-gb-2312';
index := index + 1;
m_arCharset[index, 0] := 'Chinese Traditional(Big5)';
m_arCharset[index, 1] := 'big5';
index := index + 1;
m_arCharset[index, 0] := 'Cyrillic(ISO)';
m_arCharset[index, 1] := 'iso-8859-5';
index := index + 1;
m_arCharset[index, 0] := 'Cyrillic(KOI8-R)';
m_arCharset[index, 1] := 'koi8-r';
index := index + 1;
m_arCharset[index, 0] := 'Cyrillic(KOI8-U)';
m_arCharset[index, 1] := 'koi8-u';
index := index + 1;
m_arCharset[index, 0] := 'Cyrillic(Windows)';
m_arCharset[index, 1] := 'windows-1251';
index := index + 1;
m_arCharset[index, 0] := 'Greek(ISO)';
m_arCharset[index, 1] := 'iso-8859-7';
index := index + 1;
m_arCharset[index, 0] := 'Greek(Windows)';
m_arCharset[index, 1] := 'windows-1253';
index := index + 1;
m_arCharset[index, 0] := 'Hebrew(Windows)';
m_arCharset[index, 1] := 'windows-1255';
index := index + 1;
m_arCharset[index, 0] := 'Japanese(JIS)';
m_arCharset[index, 1] := 'iso-2022-jp';
index := index + 1;
m_arCharset[index, 0] := 'Korean';
m_arCharset[index, 1] := 'ks_c_5601-1987';
index := index + 1;
m_arCharset[index, 0] := 'Korean(EUC)';
m_arCharset[index, 1] := 'euc-kr';
index := index + 1;
m_arCharset[index, 0] := 'Latin 9(ISO)';
m_arCharset[index, 1] := 'iso-8859-15';
index := index + 1;
m_arCharset[index, 0] := 'Thai(Windows)';
m_arCharset[index, 1] := 'windows-874';
index := index + 1;
m_arCharset[index, 0] := 'Turkish(ISO)';
m_arCharset[index, 1] := 'iso-8859-9';
index := index + 1;
m_arCharset[index, 0] := 'Turkish(Windows)';
m_arCharset[index, 1] := 'windows-1254';
index := index + 1;
m_arCharset[index, 0] := 'Unicode(UTF-7)';
m_arCharset[index, 1] := 'utf-7';
index := index + 1;
m_arCharset[index, 0] := 'Unicode(UTF-8)';
m_arCharset[index, 1] := 'utf-8';
index := index + 1;
m_arCharset[index, 0] := 'Vietnames(Windows)';
m_arCharset[index, 1] := 'windows-1258';
index := index + 1;
m_arCharset[index, 0] := 'Western European(ISO)';
m_arCharset[index, 1] := 'iso-8859-1';
index := index + 1;
m_arCharset[index, 0] := 'Western European(Windows)';
m_arCharset[index, 1] := 'windows-1252';
for i:= 0 to 27 do
begin
lstCharset.AddItem(m_arCharset[i,0], nil);
end;
// Set default encoding to utf-8, it supports all languages.
lstCharset.ItemIndex := 24;
lstProtocol.AddItem('SMTP Protocol - Recommended', nil);
lstProtocol.AddItem('Exchange Web Service - 2007/2010', nil);
lstProtocol.AddItem('Exchange WebDav - 2000/2003', nil);
lstProtocol.ItemIndex := 0;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
textSubject.Text := 'delphi email test';
textBody.Text := 'This sample demonstrates how to send simple email.'
+ #13#10 + #13#10
+ 'If no sever address was specified, the email will be delivered to the recipient''s server directly,'
+ 'However, if you don''t have a static IP address, '
+ 'many anti-spam filters will mark it as a junk-email.'
+ #13#10;
m_arAttachments := TStringList.Create();
InitCharset();
end;
procedure TForm1.btnSendClick(Sender: TObject);
var
oSmtp: TMail;
i: integer;
Rcpts: OleVariant;
RcptBound: integer;
RcptAddr: WideString;
oEncryptCert: TCertificate;
begin
if trim(textFrom.Text) = '' then
begin
ShowMessage( 'Plese input From email address!' );
textFrom.SetFocus();
exit;
end;
if(trim(textTo.Text) = '' ) and
(trim(textCc.Text) = '' ) then
begin
ShowMessage( 'Please input To or Cc email addresses, please use comma(,) to separate multiple addresses!');
textTo.SetFocus();
exit;
end;
if chkAuth.Checked and ((trim(textUser.Text)='') or
(trim(textPassword.Text)='')) then
begin
ShowMessage( 'Please input User, Password for SMTP authentication!' );
textUser.SetFocus();
exit;
end;
btnSend.Enabled := false;
// Create TMail Object
oSmtp := TMail.Create(Application);
oSmtp.LicenseCode := 'TryIt';
oSmtp.Charset := m_arCharset[lstCharset.ItemIndex, 1];
oSmtp.FromAddr := ChAnsiToWide(trim(textFrom.Text));
// Add recipient's
oSmtp.AddRecipientEx(ChAnsiToWide(trim(textTo.Text)), 0 );
oSmtp.AddRecipientEx(ChAnsiToWide(trim(textCc.Text)), 0 );
// Set subject
oSmtp.Subject := ChAnsiToWide(textSubject.Text);
// Using HTML FORMAT to send mail
// oSmtp.BodyFormat := 1;
// Set body
oSmtp.BodyText := ChAnsiToWide(textBody.Text);
// Add attachments
for i:= 0 to m_arAttachments.Count - 1 do
begin
oSmtp.AddAttachment(ChAnsiToWide(m_arAttachments[i]));
end;
// Add digital signature
if chkSign.Checked then
begin
if not oSmtp.SignerCert.FindSubject( oSmtp.FromAddr,
CERT_SYSTEM_STORE_CURRENT_USER, 'my' ) then
begin
ShowMessage( 'Not cert found for signing: ' + oSmtp.SignerCert.GetLastError());
btnSend.Enabled := true;
exit;
end;
if not oSmtp.SignerCert.HasCertificate Then
begin
ShowMessage( 'Signer certificate has no private key, ' +
'this certificate can not be used to sign email');
btnSend.Enabled := true;
exit;
end;
end;
// get all to, cc, bcc email address to an array
Rcpts := oSmtp.Recipients;
RcptBound := VarArrayHighBound( Rcpts, 1 );
// search encrypting cert for every recipient.
if chkEncrypt.Checked then
for i := 0 to RcptBound do
begin
RcptAddr := VarArrayGet( Rcpts, i );
oEncryptCert := TCertificate.Create(Application);
if not oEncryptCert.FindSubject(RcptAddr,
CERT_SYSTEM_STORE_CURRENT_USER, 'AddressBook' ) then
if not oEncryptCert.FindSubject(RcptAddr,
CERT_SYSTEM_STORE_CURRENT_USER, 'my' ) then
begin
ShowMessage( 'Failed to find cert for ' + RcptAddr + ': ' + oEncryptCert.GetLastError());
btnSend.Enabled := true;
exit;
end;
oSmtp.RecipientsCerts.Add(oEncryptCert.DefaultInterface);
end;
oSmtp.ServerAddr := trim(textServer.Text);
oSmtp.Protocol := lstProtocol.ItemIndex;
if oSmtp.ServerAddr <> '' then
begin
if chkAuth.Checked then
begin
oSmtp.UserName := trim(textUser.Text);
oSmtp.Password := trim(textPassword.Text);
end;
if chkSSL.Checked then
begin
oSmtp.SSL_init();
// If SSL port is 465, please add the following codes
// oSmtp.ServerPort := 465;
// oSmtp.SSL_starttls := 0;
end;
end;
if (RcptBound > 0) and (oSmtp.ServerAddr = '') then
begin
// To send email without specified smtp server, we have to send the emails one by one
// to multiple recipients. That is because every recipient has different smtp server.
DirectSend( oSmtp );
btnSend.Enabled := true;
exit;
end;
if oSmtp.SendMail() = 0 then
ShowMessage( 'Message delivered' )
else
ShowMessage( oSmtp.GetLastErrDescription());
btnSend.Enabled := true;
end;
procedure TForm1.DirectSend(oSmtp: TMail);
var
Rcpts: OleVariant;
i, RcptBound: integer;
RcptAddr: WideString;
begin
Rcpts := oSmtp.Recipients;
RcptBound := VarArrayHighBound( Rcpts, 1 );
for i := 0 to RcptBound do
begin
RcptAddr := VarArrayGet( Rcpts, i );
oSmtp.ClearRecipient();
oSmtp.AddRecipientEx( RcptAddr, 0 );
ShowMessage( 'Start to send email to ' + RcptAddr );
if oSmtp.SendMail() = 0 then
ShowMessage( 'Message delivered to ' + RcptAddr + ' successfully!')
else
ShowMessage( 'Failed to deliver to ' + RcptAddr + ': ' + oSmtp.GetLastErrDescription());
end;
end;
procedure TForm1.chkAuthClick(Sender: TObject);
begin
textUser.Enabled := chkAuth.Checked;
textPassword.Enabled := chkAuth.Checked;
if( chkAuth.Checked ) then
begin
textUser.Color := clWindow;
textPassword.Color := clWindow;
end
else
begin
textUser.Color := cl3DLight;
textPassword.Color := cl3DLight;
end;
end;
// before delphi doesn't support unicode very well in VCL, so
// we have to convert the ansistring to unicode by current default codepage.
function TForm1.ChAnsiToWide(const StrA: AnsiString): WideString;
var
nLen: integer;
begin
Result := StrA;
if Result <> '' then
begin
// convert ansi string to widestring (unicode) by current system codepage
nLen := MultiByteToWideChar(GetACP(), 1, PAnsiChar(@StrA[1]), -1, nil, 0);
SetLength(Result, nLen - 1);
if nLen > 1 then
MultiByteToWideChar(GetACP(), 1, PAnsiChar(@StrA[1]), -1, PWideChar(@Result[1]), nLen - 1);
end;
end;
procedure TForm1.btnAddClick(Sender: TObject);
var
pFileDlg : TOpenDialog;
fileName : string;
index: integer;
begin
pFileDlg := TOpenDialog.Create(Form1);
if pFileDlg.Execute() then
begin
fileName := pFileDlg.FileName;
m_arAttachments.Add( fileName );
while true do
begin
index := Pos( '\', fileName );
if index <= 0 then
break;
fileName := Copy( fileName, index+1, Length(fileName)- index );
end;
textAttachment.Text := textAttachment.Text + fileName + ';';
end;
pFileDlg.Destroy();
end;
procedure TForm1.btnClearClick(Sender: TObject);
begin
m_arAttachments.Clear();
textAttachment.Text := '';
end;
procedure TForm1.FormResize(Sender: TObject);
begin
if Form1.Width < 671 then
Form1.Width := 671;
if Form1.Height < 445 then
Form1.Height := 445;
textBody.Width := Form1.Width - 30;
textBody.Height := Form1.Height - 300;
btnSend.Top := textBody.Top + textBody.Height + 5;
btnSend.Left := Form1.Width - 20 - btnSend.Width;
GroupBox1.Left := Form1.Width - GroupBox1.Width - 20;
textFrom.Width := Form1.Width - GroupBox1.Width - 110;
textSubject.Width := textFrom.Width;
textTo.Width := textFrom.Width;
textCc.Width := textFrom.Width;
end;
end.
|
unit u_xpl_message;
{==============================================================================
UnitName = uxplmessage
UnitDesc = xPL Message management object and function
UnitCopyright = GPL by Clinique / xPL Project
==============================================================================
0.95 : Name and Description fields added
0.98 : Removed user interface function to u_xpl_message_gui to enable console apps
Introduced usage of u_xpl_udp_socket_client
0.99 : Modified due to schema move from Body to Header
1.00 : Added system variable handling
Ripped off fSocket and sending capabilities from TxPLMessage object, moved
to dedicated TxPLSender object
1.01 : Added Strings property
}
{$ifdef fpc}
{$mode objfpc}{$H+}
{$endif}
interface
uses u_xpl_custom_message,
u_xml_plugins;
type // TxPLMessage ===========================================================
TxPLMessage = class(TxPLCustomMessage)
private
fMsgName : string;
public
function ProcessedxPL : string;
function ElementByName(const aItem : string) : string;
procedure ReadFromJSON (const aCom : TCommandType);
published
property MsgName : string read fMsgName write fMsgName;
end;
implementation // =============================================================
Uses Classes
, SysUtils
, u_xpl_common
, u_xpl_processor
;
// TxPLMessage ================================================================
function TxPLMessage.ElementByName(const aItem: string): string;
begin
if aItem = 'Schema' then result := Schema.RawxPL;
if aItem = 'Source' then result := Source.RawxPL;
if aItem = 'Target' then result := Target.RawxPL;
if aItem = 'Type' then result := MsgTypeAsStr;
if aItem = 'Body' then result := Body.RawxPL;
if aItem = 'TimeStamp' then result := DateTimeToStr(TimeStamp);
end;
function TxPLMessage.ProcessedxPL: string;
begin
with TxPLProcessor.Create do begin
Result := Transform(Source,RawxPL);
Free;
end;
end;
procedure TxPLMessage.ReadFromJSON(const aCom: TCommandType);
var item : TCollectionItem;
begin
ResetValues;
MsgName := aCom.name;
MsgTypeAsStr := K_MSG_TYPE_HEAD + aCom.msg_type;
Target.IsGeneric := true;
source.RawxPL := TCommandsType(aCom.Collection).DV + '.instance' ;
Schema.RawxPL := aCom.msg_schema;
for item in aCom.Elements do
Body.AddKeyValuePairs([TElementType(item).Name],[TElementType(item).default_]);
end;
end.
|
unit CommonUtils;
interface
uses
SysUtils, Classes, StdCtrls;
function ValidateRoomName(RoomName: string) : boolean;
function ValidateNickName(NickName: string) : boolean;
function IsWrongIP(ip: string): boolean;
function ValidateHost(host: string) : boolean;
function ValidatePort(port: string) : boolean;
function ValidateAge(age: string) : boolean;
procedure AlphabeticSort(var Strings: TStrings); overload;
procedure AlphabeticSort(var ListBox: TListBox); overload;
implementation
function ValidateNickName(NickName: string) : boolean;
var
i: integer;
begin
Result := True;
if (Length(NickName) > 0) AND (Length(NickName) <= 32) then
begin
for i := 1 to Length(NickName) do
begin
if (not (NickName[i] in ['A'..'z']))
AND (not (NickName[i] in ['1'..'9']))
AND (NickName[i] <> '_') AND (NickName[i] <> '-') then
begin
Result := False;
exit;
end;
end;
end
else
Result := False;
end;
function ValidateRoomName(RoomName: string) : boolean;
var
i: integer;
begin
Result := True;
if (Length(RoomName) > 0) AND (Length(RoomName) <= 32) then
begin
if RoomName[1] <> '#' then
Result := False
else
for i := 2 to Length(RoomName) do
begin
if (not (RoomName[i] in ['A'..'z']))
AND (not (RoomName[i] in ['1'..'9']))
AND (RoomName[i] <> '_') AND (RoomName[i] <> '-') then
begin
Result := False;
exit;
end;
end;
end
else
Result := False;
end;
function IsWrongIP(ip: string): boolean;
var z, i: integer;
st: array[1..3] of byte;
const ziff = ['0'..'9'];
begin
st[1] := 0;
st[2] := 0;
st[3] := 0;
z := 0;
Result := False;
for i := 1 to length(ip) do if ip[i] in ziff then
else
begin
if ip[i] = '.' then
begin
inc(z);
if z < 4 then st[z] := i
else
begin
IsWrongIP:= True;
exit;
end;
end
else
begin
IsWrongIP:= True;
exit;
end;
end;
if (z <> 3) or (st[1] < 2) or (st[3] = length(ip)) or (st[1] + 2 > st[2]) or
(st[2] + 2 > st[3]) or (st[1] > 4) or (st[2] > st[1] + 4) or (st[3] > st[2] + 4) then
begin
IsWrongIP:= True;
exit;
end;
z := StrToInt(copy(ip, 1, st[1] - 1));
if (z > 255) or (ip[1] = '0') then
begin
IsWrongIP:= True;
exit;
end;
z := StrToInt(copy(ip, st[1] + 1, st[2] - st[1] - 1));
if (z > 255) or ((z <> 0) and (ip[st[1] + 1] = '0')) then
begin
IsWrongIP:= True;
exit;
end;
z := StrToInt(copy(ip, st[2] + 1, st[3] - st[2] - 1));
if (z > 255) or ((z <> 0) and (ip[st[2] + 1] = '0')) then
begin
IsWrongIP:= True;
exit;
end;
z := StrToInt(copy(ip, st[3] + 1, length(ip) - st[3]));
if (z > 255) or ((z <> 0) and (ip[st[3] + 1] = '0')) then
begin
IsWrongIP:= True;
exit;
end;
end;
function ValidateHost(host: string) : boolean;
begin
if Length(host) > 0 then
Result := True
else
Result := False;
end;
function ValidatePort(port: string) : boolean;
var
PortInt: integer;
begin
try
PortInt := StrToInt(port);
if (PortInt >= 0) AND (PortInt <= 65535) then
Result := True
else
Result := False;
except
Result := False;
end;
end;
function ValidateAge(age: string) : boolean;
var
AgeInt: integer;
begin
if age = '' then
begin
Result := True;
exit
end;
try
AgeInt := StrToInt(age);
if (AgeInt > 0) AND (AgeInt <= 100) then
Result := True
else
Result := False;
except
Result := False;
end;
end;
procedure AlphabeticSort(var Strings: TStrings);
var
i, x: Integer;
begin
for i := 0 to (Strings.Count - 1) do
for x := 0 to (Strings.Count - 1) do
if (Strings[x] < Strings[i]) and (x > i) then
begin
Strings.Insert(i, Strings[x]);
Strings.Delete(x + 1);
end;
end;
procedure AlphabeticSort(var ListBox: TListBox);
var
i, x: Integer;
begin
for i := 0 to (ListBox.Items.Count - 1) do
for x := 0 to (ListBox.Items.Count - 1) do
if (ListBox.Items[x] < ListBox.Items[i]) and (x > i) then
begin
ListBox.Items.Insert(i, ListBox.Items[x]);
ListBox.Items.Delete(x + 1);
end;
end;
end.
|
{
Initial author: VCC
- 2017.05.05 -
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.
}
unit SHA256CalcMainForm;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, DCPsha256, Forms, Controls, Graphics, Dialogs,
StdCtrls, ComCtrls, ExtCtrls;
type
TProcessHashThread = class(TThread)
private
FFileSize: Int64;
FFilePosition: Int64;
FFilename: TFilename;
FHash: string;
protected
procedure Execute; override;
end;
{ TfrmSHA256CalcMain }
TfrmSHA256CalcMain = class(TForm)
btnLoadFile: TButton;
btnStop: TButton;
chkDisplayAsLowerCase: TCheckBox;
edtCredits: TEdit;
lbeHash: TLabeledEdit;
lbeFile: TLabeledEdit;
OpenDialog1: TOpenDialog;
prbShaProcessing: TProgressBar;
tmrStartup: TTimer;
tmrUpdateProgressBar: TTimer;
procedure btnLoadFileClick(Sender: TObject);
procedure btnStopClick(Sender: TObject);
procedure chkDisplayAsLowerCaseChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure tmrStartupTimer(Sender: TObject);
procedure tmrUpdateProgressBarTimer(Sender: TObject);
procedure ThreadTerminated(Sender: TObject);
private
{ private declarations }
FProcessHashThread: TProcessHashThread;
public
{ public declarations }
end;
var
frmSHA256CalcMain: TfrmSHA256CalcMain;
implementation
{$R *.lfm}
procedure TProcessHashThread.Execute;
var
Sha256: TDCP_sha256;
AFileStream: TFileStream;
ADigest: array[0..31] of Byte;
i: Integer;
begin
try
Sha256 := TDCP_sha256.Create(nil);
try
AFileStream := TFileStream.Create(FFileName, fmOpenRead);
try
Sha256.Burn;
Sha256.Init;
FFileSize := AFileStream.Size;
AFileStream.Position := 0;
repeat
Sha256.UpdateStream(AFileStream, 8192);
FFilePosition := AFileStream.Position;
until (AFileStream.Position >= AFileStream.Size) or Terminated;
Sha256.Final(ADigest);
finally
AFileStream.Free;
end;
FHash := '';
if not Terminated then //Leave an empty hash if manually terminated
for i := 0 to 31 do
FHash := FHash + IntToHex(ADigest[i], 2);
finally
Sha256.Free;
end;
except
end;
end;
{ TfrmSHA256CalcMain }
procedure TfrmSHA256CalcMain.btnLoadFileClick(Sender: TObject);
begin
if Sender = tmrStartup then
OpenDialog1.FileName := ParamStr(1)
else
if not OpenDialog1.Execute then
Exit;
if FProcessHashThread <> nil then
Exit;
lbeFile.Text := OpenDialog1.FileName;
FProcessHashThread := TProcessHashThread.Create(True);
FProcessHashThread.FreeOnTerminate := True;
FProcessHashThread.OnTerminate := @ThreadTerminated;
FProcessHashThread.FFilename := OpenDialog1.FileName;
btnLoadFile.Enabled := False;
lbeHash.Text := '';
prbShaProcessing.Visible := True;
btnStop.Visible := True;
tmrUpdateProgressBar.Enabled := True;
FProcessHashThread.Start;
end;
procedure TfrmSHA256CalcMain.btnStopClick(Sender: TObject);
begin
try
FProcessHashThread.Terminate;
except
end;
end;
procedure TfrmSHA256CalcMain.chkDisplayAsLowerCaseChange(Sender: TObject);
begin
if not chkDisplayAsLowerCase.Checked then
lbeHash.Text := UpperCase(lbeHash.Text)
else
lbeHash.Text := LowerCase(lbeHash.Text);
end;
procedure TfrmSHA256CalcMain.FormCreate(Sender: TObject);
begin
FProcessHashThread := nil;
tmrStartup.Enabled := True;
end;
procedure TfrmSHA256CalcMain.tmrStartupTimer(Sender: TObject);
begin
tmrStartup.Enabled := False;
if ParamCount > 0 then
if FileExists(ParamStr(1)) then
btnLoadFileClick(tmrStartup);
end;
procedure TfrmSHA256CalcMain.ThreadTerminated(Sender: TObject);
begin
tmrUpdateProgressBar.Enabled := False;
btnLoadFile.Enabled := True;
if chkDisplayAsLowerCase.Checked then
lbeHash.Text := LowerCase(FProcessHashThread.FHash)
else
lbeHash.Text := FProcessHashThread.FHash;
prbShaProcessing.Visible := False;
btnStop.Visible := False;
btnStop.Repaint;
if FProcessHashThread <> nil then
FProcessHashThread := nil;
end;
procedure TfrmSHA256CalcMain.tmrUpdateProgressBarTimer(Sender: TObject);
begin
if FProcessHashThread = nil then
Exit;
prbShaProcessing.Max := FProcessHashThread.FFileSize;
prbShaProcessing.Position := FProcessHashThread.FFilePosition;
prbShaProcessing.Repaint;
end;
end.
|
(******************************************************************************)
(* TdfsExtListView component demo. *)
(* This demo illustrates the following features of the TdfsExtListView *)
(* component: *)
(* + Automatic column sorting of string, date/time and numeric values *)
(* toggling between ascending and descending order with no code. *)
(* + Automatic saving and restoring of the column widths and the column *)
(* ordering between sessions. *)
(* + Ability to set and clear all of the extended styles at run-time so you *)
(* can see their effects. *)
(* + Ability to set the hover time before lvxTrackSelect kicks in and *)
(* autoselects the item. *)
(* + Shows how to use the CheckComCtlVersion method to ensure a specific *)
(* version of COMCTL32.DLL is installed. *)
(* + Shows usage of OnMarqueeBegin event to inhibit drag selection of items. *)
(* + Shows how to use GetSubItemAt method to find specific text at X,Y pos. *)
(* + Shows how to change column order in code. *)
(* + Shows how to set subitem images (SubItem_ImageIndex property). Enable *)
(* lvxSubitemImages in ExtendedStyles. *)
(******************************************************************************)
//{$I DFS.INC}
unit Main;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
{$IFDEF DFS_COMPILER_4_UP}
ImgList,
{$ENDIF}
StdCtrls, ExtCtrls, ExtListView, Spin, ComCtrls, CommCtrl, EnhListView;
type
TForm1 = class(TForm)
Bevel1: TBevel;
ComboBox1: TComboBox;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
IconSpacingX: TSpinEdit;
IconSpacingY: TSpinEdit;
ScrollBox1: TScrollBox;
GridLines: TCheckBox;
SubItemImages: TCheckBox;
CheckBoxes: TCheckBox;
TrackSelect: TCheckBox;
HeaderDragDrop: TCheckBox;
FullRowSelect: TCheckBox;
OneClickActivate: TCheckBox;
TwoClickActivate: TCheckBox;
StatusBar: TStatusBar;
Button1: TButton;
Label6: TLabel;
cbxNoDrag: TCheckBox;
ExtListView: TdfsExtListView;
ImageList1: TImageList;
FlatScrollBar: TCheckBox;
UnderlineHot: TCheckBox;
UnderlineCold: TCheckBox;
Label5: TLabel;
HoverTime: TSpinEdit;
RequireCOMCTL: TCheckBox;
ccMajorHi: TEdit;
Label7: TLabel;
ccMajorLo: TEdit;
Label8: TLabel;
ccMinorHi: TEdit;
Label9: TLabel;
ccMinorLo: TEdit;
Button3: TButton;
procedure FormCreate(Sender: TObject);
procedure GridLinesClick(Sender: TObject);
procedure SubItemImagesClick(Sender: TObject);
procedure CheckBoxesClick(Sender: TObject);
procedure TrackSelectClick(Sender: TObject);
procedure HeaderDragDropClick(Sender: TObject);
procedure FullRowSelectClick(Sender: TObject);
procedure OneClickActivateClick(Sender: TObject);
procedure TwoClickActivateClick(Sender: TObject);
procedure ComboBox1Change(Sender: TObject);
procedure IconSpacingChange(Sender: TObject);
procedure ExtListViewMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure Button1Click(Sender: TObject);
procedure ExtListViewMarqueeBegin(Sender: TObject; var CanBegin: Boolean);
procedure FlatScrollBarClick(Sender: TObject);
procedure UnderlineHotClick(Sender: TObject);
procedure UnderlineColdClick(Sender: TObject);
procedure HoverTimeChange(Sender: TObject);
procedure RequireCOMCTLClick(Sender: TObject);
procedure ccValueChange(Sender: TObject);
private
procedure CheckComCtlVersion;
public
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.FormCreate(Sender: TObject);
var
x, y: integer;
begin
ComboBox1.ItemIndex := 2;
// Stick some date/time values in column #2.
ExtListView.Items[0].SubItems[0] := DateTimeToStr(Now);
ExtListView.Items[1].SubItems[0] := DateTimeToStr(Now+2);
ExtListView.Items[2].SubItems[0] := DateTimeToStr(Now+0.0001);
ExtListView.Items[3].SubItems[0] := DateTimeToStr(Now-190.002);
// Give everyone some subitem images
for x := 0 to 3 do
for y := 0 to 2 do
// Item #x, subitem #y, image index #y+1
ExtListView.SubItem_ImageIndex[x, y] := y+1;
end;
procedure TForm1.GridLinesClick(Sender: TObject);
begin
with ExtListView do
if (Sender as TCheckBox).Checked then
ExtendedStyles := ExtendedStyles + [lvxGridLines]
else
ExtendedStyles := ExtendedStyles - [lvxGridLines];
end;
procedure TForm1.SubItemImagesClick(Sender: TObject);
begin
with ExtListView do
if (Sender as TCheckBox).Checked then
ExtendedStyles := ExtendedStyles + [lvxSubItemImages]
else
ExtendedStyles := ExtendedStyles - [lvxSubItemImages];
end;
procedure TForm1.CheckBoxesClick(Sender: TObject);
begin
with ExtListView do
if (Sender as TCheckBox).Checked then
ExtendedStyles := ExtendedStyles + [lvxCheckBoxes]
else
ExtendedStyles := ExtendedStyles - [lvxCheckBoxes];
end;
procedure TForm1.TrackSelectClick(Sender: TObject);
begin
with ExtListView do
if (Sender as TCheckBox).Checked then
ExtendedStyles := ExtendedStyles + [lvxTrackSelect]
else
ExtendedStyles := ExtendedStyles - [lvxTrackSelect];
end;
procedure TForm1.HeaderDragDropClick(Sender: TObject);
begin
with ExtListView do
if (Sender as TCheckBox).Checked then
ExtendedStyles := ExtendedStyles + [lvxHeaderDragDrop]
else
ExtendedStyles := ExtendedStyles - [lvxHeaderDragDrop];
end;
procedure TForm1.FullRowSelectClick(Sender: TObject);
begin
with ExtListView do
if (Sender as TCheckBox).Checked then
ExtendedStyles := ExtendedStyles + [lvxFullRowSelect]
else
ExtendedStyles := ExtendedStyles - [lvxFullRowSelect];
end;
procedure TForm1.OneClickActivateClick(Sender: TObject);
begin
with ExtListView do
if (Sender as TCheckBox).Checked then
ExtendedStyles := ExtendedStyles + [lvxOneClickActivate]
else
ExtendedStyles := ExtendedStyles - [lvxOneClickActivate];
end;
procedure TForm1.TwoClickActivateClick(Sender: TObject);
begin
with ExtListView do
if (Sender as TCheckBox).Checked then
ExtendedStyles := ExtendedStyles + [lvxTwoClickActivate]
else
ExtendedStyles := ExtendedStyles - [lvxTwoClickActivate];
end;
procedure TForm1.ComboBox1Change(Sender: TObject);
begin
case ComboBox1.ItemIndex of
0: ExtListView.ViewStyle := vsIcon;
1: ExtListView.ViewStyle := vsList;
2: ExtListView.ViewStyle := vsReport;
3: ExtListView.ViewStyle := vsSmallIcon;
end;
end;
procedure TForm1.IconSpacingChange(Sender: TObject);
var
X, Y: integer;
begin
try
X := IconSpacingX.Value;
Y := IconSpacingY.Value;
with ExtListView do begin
SetIconSpacing(X, Y);
if ViewStyle = vsIcon then begin
SendMessage(Handle, WM_SETREDRAW, 0, 0);
try
ViewStyle := vsSmallIcon;
ViewStyle := vsIcon;
finally
SendMessage(Handle, WM_SETREDRAW, 1, 0);
end;
end;
end;
except
// conversion error, ignore it.
end;
end;
procedure TForm1.ExtListViewMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
var
SubItemText: string;
begin
SubItemText := ExtListView.GetSubItemAt(X, Y);
if SubItemText <> '' then
SubItemText := 'SubItem = ' + SubItemText;
StatusBar.SimpleText := SubItemText;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
Columns: array[0..3] of integer;
Tmp: integer;
begin
if ExtListView.GetColumnOrder(4, Columns) then
begin
Tmp := Columns[0];
Columns[0] := Columns[3];
Columns[3] := Tmp;
Tmp := Columns[1];
Columns[1] := Columns[2];
Columns[2] := Tmp;
ExtListView.SetColumnOrder(4, Columns);
end;
end;
procedure TForm1.ExtListViewMarqueeBegin(Sender: TObject; var CanBegin: Boolean);
begin
CanBegin := not cbxNoDrag.Checked;
end;
procedure TForm1.FlatScrollBarClick(Sender: TObject);
begin
with ExtListView do
if (Sender as TCheckBox).Checked then
ExtendedStyles := ExtendedStyles + [lvxFlatScrollBar]
else
ExtendedStyles := ExtendedStyles - [lvxFlatScrollBar];
end;
procedure TForm1.UnderlineHotClick(Sender: TObject);
begin
with ExtListView do
if (Sender as TCheckBox).Checked then
ExtendedStyles := ExtendedStyles + [lvxUnderlineHot]
else
ExtendedStyles := ExtendedStyles - [lvxUnderlineHot];
end;
procedure TForm1.UnderlineColdClick(Sender: TObject);
begin
with ExtListView do
if (Sender as TCheckBox).Checked then
ExtendedStyles := ExtendedStyles + [lvxUnderlineCold]
else
ExtendedStyles := ExtendedStyles - [lvxUnderlineCold];
end;
procedure TForm1.HoverTimeChange(Sender: TObject);
begin
ExtListView.HoverTime := HoverTime.Value;
end;
procedure TForm1.RequireCOMCTLClick(Sender: TObject);
begin
if RequireCOMCTL.Checked then
begin
ccMajorHi.Enabled := TRUE;
ccMajorLo.Enabled := TRUE;
ccMinorHi.Enabled := TRUE;
ccMinorLo.Enabled := TRUE;
CheckComCtlVersion;
end else begin
ccMajorHi.Enabled := FALSE;
ccMajorLo.Enabled := FALSE;
ccMinorHi.Enabled := FALSE;
ccMinorLo.Enabled := FALSE;
end;
end;
procedure TForm1.CheckComCtlVersion;
begin
if not ExtListView.CheckComCtlVersion(StrToIntDef(ccMajorHi.Text, 4),
StrToIntDef(ccMajorLo.Text, 7), StrToIntDef(ccMinorHi.Text, 0),
StrToIntDef(ccMinorLo.Text, 0)) then
MessageDlg('The version of COMCTL32.DLL installed on this machine is too' +
' old.', mtWarning, [mbOk], 0);
end;
procedure TForm1.ccValueChange(Sender: TObject);
begin
CheckComCtlVersion;
end;
end.
|
PROGRAM ASK3;
VAR
let, small, cap: CHAR;
num_let, small_let, cap_let: INTEGER;
BEGIN
WRITE ('Enter a letter : ');
READ (let);
num_let := ord (let);
If ( (num_let>=65) and (num_let<=90) ) then
BEGIN
cap_let := ord(num_let+32);
small:= chr (cap_let);
WRITELN ('The small letter is : ', small);
END;
If ( (num_let>=97) and (num_let<=122) ) then
BEGIN
small_let := ord(num_let-32);
cap := chr (small_let);
WRITELN ('The cap letter is : ', cap);
END;
END. |
unit mainunit;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, TAGraph, TASeries, TASources, TAChartListbox,
TADbSource, Forms, Controls, Graphics, Dialogs, StdCtrls, ComCtrls, ExtCtrls,
ZConnection, httpsend, RegExpr, DA1Class, QueryExecutor;
type
{ TFormMain }
TFormMain = class(TForm)
btnDownload: TButton;
ChartPie: TChart;
ChartPiePieSeries1: TPieSeries;
chartSource: TListChartSource;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
lbQueue: TLabel;
lbTotal: TLabel;
lbpr: TLabel;
lbjk: TLabel;
lvThread: TListView;
mError: TMemo;
PageControl1: TPageControl;
Panel1: TPanel;
sbMain: TStatusBar;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
TabSheet3: TTabSheet;
tmMon: TTimer;
procedure btnDownloadClick(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure tmMonTimer(Sender: TObject);
private
FDA1: TDA1;
procedure EvOnExecQuery(Sender: TObject ; SQL: string);
procedure EvOnQueryError(Sender: TObject ; SQL: string);
{ private declarations }
public
{ public declarations }
end;
var
FormMain: TFormMain;
const
URL_DA1 = 'http://pilpres2014.kpu.go.id/da1.php';
implementation
uses udm;
{$R *.lfm}
{ TFormMain }
procedure TFormMain.FormShow(Sender: TObject);
begin
end;
procedure TFormMain.tmMonTimer(Sender: TObject);
var
i: integer;
sPr,sJk: string;
begin
lvThread.Items.BeginUpdate;
lvThread.Items.Clear;
for i:= 0 to FDA1.ThreadList.Count - 1 do
begin
if FDA1.ThreadList[i] <> nil then
begin
if Trim(TDA1Executor(FDA1.ThreadList[i]).Name) = '' then Continue;
with lvThread.Items.Add do
begin
Caption:=TDA1Executor(FDA1.ThreadList[i]).Name;
SubItems.Add('Running');
end;
end;
end;
lvThread.Items.EndUpdate;
with dm.qView do
begin
Close;
sql.Text:='select * from vw_realcount';
Open;
sPr:=(Format('0|%f|?|Prabowo - Hatta (%f%s)',[FieldByName('prabowopr').AsFloat,FieldByName('prabowopr').AsFloat,'%']));
sJk:=(Format('0|%f|?|Jokowi - JK (%f%s)',[FieldByName('jokowipr').AsFloat,FieldByName('jokowipr').AsFloat,'%']));
if (FieldByName('prabowopr').AsFloat < 1) and (FieldByName('jokowipr').AsFloat < 1) then exit;
chartSource.DataPoints.Clear;
chartSource.DataPoints.Add(sPr);
chartSource.DataPoints.Add(sJk);
lbpr.Caption:= FormatFloat('#,##0',FieldByName('prabowo').AsFloat);
lbjk.Caption:= FormatFloat('#,##0',FieldByName('jokowi').AsFloat);
lbTotal.Caption:=FormatFloat('#,##0',FieldByName('prabowo').AsFloat + FieldByName('jokowi').AsFloat);
end;
lbQueue.Caption:= FormatFloat('#,##0',_QueryExecutor.SQLQueue);;
end;
procedure TFormMain.EvOnExecQuery(Sender: TObject; SQL: string);
begin
sbMain.SimpleText:=Format('SQL : %s',[SQL]);
end;
procedure TFormMain.EvOnQueryError(Sender: TObject; SQL: string);
begin
mError.Lines.Add(SQL);
end;
procedure TFormMain.btnDownloadClick(Sender: TObject);
var
s: string;
begin
FDA1 := TDA1.Create;
try
FDA1.ID:='';
FDA1.IDParent:='0';
FDA1.ImportData;
tmMon.Enabled:=True;
finally
end;
btnDownload.Enabled:=False;
end;
procedure TFormMain.Button2Click(Sender: TObject);
begin
end;
procedure TFormMain.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
FreeAndNil(dm);
end;
procedure TFormMain.FormCreate(Sender: TObject);
begin
dm := Tdm.Create(Self);
_QueryExecutor := TQueryList.Create;
_QueryExecutor.OnExecQuery:=@EvOnExecQuery;
_QueryExecutor.OnQueryError:=@EvOnQueryError;
end;
end.
|
{********************************************}
{ TeeChart Pro Charting Library }
{ Copyright (c) 1995-2004 by David Berneda }
{ All Rights Reserved }
{********************************************}
unit TeeDBSourceEditor;
{$I TeeDefs.inc}
interface
uses
{$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
SysUtils, Classes, DB,
{$IFDEF CLR}
Variants,
{$ENDIF}
{$IFDEF CLX}
Qt, QGraphics, QControls, QForms, QDialogs, QStdCtrls, QExtCtrls,
{$IFNDEF TEELITE}
QDBCtrls,
{$ENDIF}
{$ELSE}
Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls,
{$IFNDEF TEELITE}
DBCtrls,
{$ENDIF}
{$ENDIF}
Chart, TeEngine, TeeDBEdit, TeeSelectList, TeCanvas;
type
TDBChartSourceEditor = class(TBaseDBChartEditor)
procedure BApplyClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure CBSourcesChange(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
{$IFNDEF TEELITE}
INavig : TDBNavigator;
{$ENDIF}
ISources : TSelectListForm;
Procedure FillFields;
Function DataSource:TDataSource;
procedure OnChangeSources(Sender: TObject);
protected
Function IsValid(AComponent:TComponent):Boolean; override;
public
{ Public declarations }
end;
TSingleRecordSeriesSource=class(TTeeSeriesDBSource)
public
class Function Description:String; override;
class Function Editor:TComponentClass; override;
class Function HasSeries(ASeries:TChartSeries):Boolean; override;
end;
implementation
{$IFNDEF CLX}
{$R *.DFM}
{$ELSE}
{$R *.xfm}
{$ENDIF}
Uses
DBChart, TeeProcs, TeeConst, TeePenDlg;
Function TDBChartSourceEditor.IsValid(AComponent:TComponent):Boolean;
begin
result:=AComponent is TDataSource;
end;
procedure TDBChartSourceEditor.BApplyClick(Sender: TObject);
var tmpSt : String;
t : Integer;
begin
inherited;
TheSeries.DataSource:=nil;
With ISources.ToList do
if Items.Count>0 then
begin
tmpSt:=Items[0];
for t:=1 to Items.Count-1 do
tmpSt:=tmpSt+';'+Items[t];
end
else tmpSt:='';
TheSeries.MandatoryValueList.ValueSource:=tmpSt;
TheSeries.DataSource:=DataSource;
{$IFNDEF TEELITE}
INavig.DataSource:=DataSource;
{$ENDIF}
BApply.Enabled:=False;
end;
Function TDBChartSourceEditor.DataSource:TDataSource;
begin
With CBSources do
if ItemIndex=-1 then result:=nil
else result:=TDataSource(Items.Objects[CBSources.ItemIndex]);
end;
procedure TDBChartSourceEditor.OnChangeSources(Sender: TObject);
begin
BApply.Enabled:=True;
end;
procedure TDBChartSourceEditor.FormShow(Sender: TObject);
begin
inherited;
LLabel.Caption:=TeeMsg_AskDataSource;
ISources:=TSelectListForm.Create(Self);
ISources.Align:=alClient;
ISources.OnChange:=OnChangeSources;
AddFormTo(ISources,Self,Tag);
{$IFNDEF TEELITE}
INavig:=TDBNavigator.Create(Self);
With INavig do
begin
VisibleButtons:=[nbFirst, nbPrior, nbNext, nbLast, nbRefresh];
Flat:=True;
Parent:=ISources;
Align:=alBottom;
end;
{$ENDIF}
FillFields;
end;
procedure TDBChartSourceEditor.CBSourcesChange(Sender: TObject);
begin
inherited;
FillFields;
TheSeries.XLabelsSource:='';
end;
Procedure TDBChartSourceEditor.FillFields;
Procedure AddField(Const tmpSt:String; tmpType:TFieldType);
begin
Case TeeFieldType(tmpType) of
tftNumber,
tftDateTime: ISources.FromList.Items.Add(tmpSt);
end;
end;
Procedure AddAggregateFields;
var t : Integer;
begin
With DataSource.DataSet do
for t:=0 to AggFields.Count-1 do
AddField(AggFields[t].FieldName,ftFloat);
end;
var tmpSt : String;
tmpField : String;
t : Integer;
begin
ISources.FromList.Clear;
ISources.ToList.Clear;
{$IFNDEF TEELITE}
INavig.DataSource:=DataSource;
{$ENDIF}
if (DataSource<>nil) and (DataSource.DataSet<>nil) then
begin
With DataSource.DataSet do
if FieldCount>0 then
begin
for t:=0 to FieldCount-1 do
AddField(Fields[t].FieldName,Fields[t].DataType);
AddAggregateFields;
end
else
begin
FieldDefs.Update;
for t:=0 to FieldDefs.Count-1 do
AddField(FieldDefs[t].Name,FieldDefs[t].DataType);
AddAggregateFields;
end;
tmpSt:=TheSeries.MandatoryValueList.ValueSource;
for t:=1 to TeeNumFields(tmpSt) do
begin
tmpField:=TeeExtractField(tmpSt,t);
With ISources.FromList.Items do
if IndexOf(tmpField)<>-1 then
begin
ISources.ToList.Items.Add(tmpField);
Delete(IndexOf(tmpField));
end;
end;
end;
ISources.EnableButtons;
end;
procedure TDBChartSourceEditor.FormDestroy(Sender: TObject);
begin
{$IFNDEF TEELITE}
INavig.Free;
{$ENDIF}
inherited;
end;
{ TSingleRecordSeriesSource }
class function TSingleRecordSeriesSource.Description: String;
begin
result:=TeeMsg_SingleRecord;
end;
class function TSingleRecordSeriesSource.Editor: TComponentClass;
begin
result:=TDBChartSourceEditor;
end;
class function TSingleRecordSeriesSource.HasSeries(
ASeries: TChartSeries): Boolean;
begin
result:=ASeries.DataSource is TDataSource;
end;
initialization
TeeSources.Add({$IFDEF CLR}TObject{$ENDIF}(TSingleRecordSeriesSource));
finalization
TeeSources.Remove({$IFDEF CLR}TObject{$ENDIF}(TSingleRecordSeriesSource));
end.
|
Program sorting_insertions;
Uses CRT;
Const INF = 1000;
Type PItem = ^TItem;
TItem = Record
next: PItem;
data: Integer;
End;
Procedure Push(Var top: PItem; x: Integer);
Var p: PItem;
Begin
New(p);
p^.data := x;
p^.next := top;
top := p;
End;
Procedure LinkSwap(Var p1, p2, p3, p4: PItem);
// this procedure swaps 2 middle elements from 4 in linked list
Begin
p2^.next := p4;
p1^.next := p3;
p3^.next := p2;
End;
Procedure Sort(Var top:PItem);
Var swapped: Boolean;
// we need 3 runners
// to swap r2 and r3, we also need to change r1 pointer to r3
// and also r2 next shoul point to r4
// r1 -> r2 -> r3 -> r4
r1, r2, r3, r4: PItem;
i: integer;
Begin
Repeat
swapped := false;
r1 := top;
r2 := r1^.next;
r3 := r2^.next;
r4 := r3^.next;
i := 0;
While (r3^.data <> INF) Do
Begin
If (r2^.data > r3^.data) Then
Begin
LinkSwap(r1, r2, r3, r4);
swapped := true;
End;
r1 := r1^.next;
r2 := r2^.next;
r3 := r3^.next;
If (r3^.data <> INF) Then // if r3 points to INF then r4 nowhere to look
r4 := r4^.next;
i := i + 1;
End;
Inc(i);
Until (Not swapped);
End;
Procedure Insert(Var top: PItem; x: Integer);
Var p, r: PItem;
Begin
New(p);
p^.data := x;
r := top;
While (x > r^.next^.data) Do
Begin
r := r^.next;
End;
p^.next := r^.next;
r^.next := p;
End;
Procedure Pop(Var top: PItem);
Var p: PItem;
Begin
If top^.data <> -INF Then
Begin
p := top;
top := top^.next;
Dispose(p);
End;
End;
Procedure Print(top: PItem);
// Print list without -INF and +INF
Var r: PItem;
Begin
r := top^.next;
// skip first element as it always will be -INF
While (r^.data <> INF) Do
Begin
write(r^.data:3);
r := r^.next;
End;
writeln;
End;
Procedure TestInsertionSort;
Var s: PItem;
i: Integer;
Begin
// init first two elements, to avoid heomoroids later
Push(s, INF);
Push(s, -INF);
// inserting random test data
For i := 0 To 20 Do
Begin
Insert(s, Random(100));
End;
// numbers should be printed in ascending order
writeln('=== Insertion sort: ');
Print(s);
writeln;
End;
Procedure TestSwapSort;
Var s: PItem;
i: Integer;
Begin
// put only +INF
// remember that in "stack" we are pushing numbers from "end"
Push(s, INF);
// inserting random test data between -INF and INF
For i := 0 To 10 Do
Begin
Push(s, Random(100));
End;
// should be PUT AFTER our numbers, so it is last element
Push(s, -INF);
// numbers should be printed in ascending order
writeln('=== Swap sort: ');
writeln(' list before sorting: ');
write(' ');
Print(s);
Sort(s);
writeln(' list after sorting: ');
write(' ');
Print(s);
writeln;
End;
Begin
Randomize;
// ClrScr;
TestInsertionSort;
TestSwapSort
End.
|
unit NtUtils.Svc.SingleTaskSvc;
interface
uses
NtUtils.Svc;
type
TSvcxPayload = procedure(ScvParams: TArray<String>);
// Starts service control dispatcher.
function SvcxMain(ServiceName: String; Payload: TSvcxPayload): Boolean;
implementation
uses
Winapi.Svc, Winapi.WinError, Winapi.WinBase, System.SysUtils;
var
SvcxName: String;
SvcxPayload: TSvcxPayload = nil;
SvcxStatusHandle: THandle;
SvcxStatus: TServiceStatus = (
ServiceType: SERVICE_WIN32_OWN_PROCESS;
CurrentState: ServiceRunning;
ControlsAccepted: 0;
Win32ExitCode: 0;
ServiceSpecificExitCode: 0;
CheckPoint: 0;
WaitHint: 5000
);
function SvcxHandlerEx(Control: TServiceControl; EventType: Cardinal;
EventData: Pointer; Context: Pointer): Cardinal; stdcall;
begin
if Control = ServiceControlInterrogate then
Result := ERROR_SUCCESS
else
Result := ERROR_CALL_NOT_IMPLEMENTED;
end;
procedure SvcxServiceMain(dwNumServicesArgs: Integer;
lpServiceArgVectors: PServiceArgsW) stdcall;
var
i: Integer;
Parameters: TArray<String>;
begin
// Register service control handler
SvcxStatusHandle := RegisterServiceCtrlHandlerExW(PWideChar(SvcxName),
SvcxHandlerEx, nil);
// Report running status
SetServiceStatus(SvcxStatusHandle, SvcxStatus);
// Prepare passed parameters
SetLength(Parameters, dwNumServicesArgs);
for i := 0 to High(Parameters) do
Parameters[i] := String(lpServiceArgVectors{$R-}[i]{$R+});
{$IFDEF DEBUG}
OutputDebugStringW(PWideChar(ParamStr(0)));
OutputDebugStringW('Service parameters: ');
for i := 0 to dwNumServicesArgs - 1 do
OutputDebugStringW(lpServiceArgVectors{$R-}[i]{$R+});
{$ENDIF}
// Call the payload
try
if Assigned(SvcxPayload) then
SvcxPayload(Parameters);
except
on E: Exception do
OutputDebugStringW(PWideChar(E.ClassName + ': ' + E.Message));
end;
// Report that we have finished
SvcxStatus.CurrentState := ServiceStopped;
SetServiceStatus(SvcxStatusHandle, SvcxStatus);
end;
function SvcxMain(ServiceName: String; Payload: TSvcxPayload): Boolean;
var
ServiceTable: array [0 .. 1] of TServiceTableEntryW;
begin
SvcxName := ServiceName;
SvcxPayload := Payload;
ServiceTable[0].ServiceName := PWideChar(SvcxName);
ServiceTable[0].ServiceProc := SvcxServiceMain;
ServiceTable[1].ServiceName := nil;
ServiceTable[1].ServiceProc := nil;
Result := StartServiceCtrlDispatcherW(PServiceTableEntryW(@ServiceTable));
end;
end.
|
unit dvariant_1;
interface
type
Variant = packed record
private
VType: UInt16;
VData1: Int32;
VData2: Int32;
VData3: Int32;
VType4: Int16;
constructor Init;
destructor Final;
operator Implicit(const Value: Int32): Variant; overload;
operator Implicit(const Value: String): Variant; overload;
operator Implicit(const Value: Variant): Int32; overload;
operator Implicit(const Value: Variant): String; overload;
end;
const sVariants = 'Variants';
function VarIsNull(const V: Variant): Boolean; external sVariants;
function VarIsEmpty(const V: Variant): Boolean; external sVariants;
implementation
procedure _VarFromInt(var Dst: Variant; const Src: Int32); external sVariants;
procedure _VarFromUStr(var Dst: Variant; const Src: String); external sVariants;
procedure _VarToInt(const Src: Variant; var Dst: Int32); external sVariants;
procedure _VarToUStr(const Src: Variant; var Dst: String); external sVariants;
procedure _VarClear(const Src: Variant); external sVariants;
constructor Variant.Init;
begin
VType := 0;
end;
constructor Variant.Final;
begin
_VarClear(Self);
end;
operator Variant.Implicit(const Value: Int32): Variant; overload;
begin
_VarFromInt(Result, Value);
end;
operator Variant.Implicit(const Value: String): Variant; overload;
begin
_VarFromUStr(Result, Value);
end;
operator Variant.Implicit(const Value: Variant): Int32; overload;
begin
_VarToInt(Value, Result);
end;
operator Variant.Implicit(const Value: Variant): String; overload;
begin
_VarToUStr(Value, Result);
end;
var
VSize: Int32;
B: Boolean;
V: Variant;
I: Int32;
S: string;
procedure Test;
begin
VSize := SizeOf(Variant);
Assert(VSize = 16);
Assert(VarIsNull(V) = false);
Assert(VarIsEmpty(V) = true);
V := 5;
I := V;
Assert(I = 5);
// V := 'delphi variant';
// S := V;
// Assert(S = 'delphi variant');
// Assert(not VarIsNull(V));
end;
initialization
Test();
finalization
end. |
unit fcsp256;
(*************************************************************************
DESCRIPTION : File crypt/authenticate unit using Serpent 256
REQUIREMENTS : TP5-7, D1-D7/D9-D10, FPC, VP
EXTERNAL DATA : ---
MEMORY USAGE : ---
DISPLAY MODE : ---
REFERENCES : ---
REMARK :
Version Date Author Modification
------- -------- ------- ------------------------------------------
0.10 10.03.16 G.Tani Based on W.Ehrhardt fcaes256 0.16 modified to use Serpent 256
**************************************************************************)
(*-------------------------------------------------------------------------
(C) Copyright 2003-2008 Wolfgang Ehrhardt, Giorgio Tani
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.
----------------------------------------------------------------------------*)
{$i STD.INC}
interface
uses
BTypes,
{$ifdef USEDLL}
{$ifdef VirtualPascal}
CH_INTV, SP_INTV;
{$else}
CH_INTF, SP_INTF;
{$endif}
{$else}
Hash, HMAC, Whirl512, KDF, SP_base, SP_CTR, SP_EAX;
{$endif}
const
C_FCS_Sig = $FC;
KeyIterations : word = 1000; {Iterations in KeyDeriv}
type
TFCS256Salt = array[0..2] of longint; {96 Bit salt}
TFCS256Hdr = packed record {same header format used in Fcrypt}
{a plus key size bit in Flag for 256 bit keys (bit 2)}
FCSsig: byte; {Sig $FC}
Flags : byte; {High $A0; Bit2: 0=128bit (as in Fcrypta)}
{1=256bit; Bit1: compression; Bit0: 1=EAX, 0=HMAC-CTR}
Salt : TFCS256Salt;
PW_Ver: word;
end;
TFCS256_AuthBlock = array[0..15] of byte;
type
TFCS_HMAC256_Context = record
SP_ctx : TSPContext; {crypt context}
hmac_ctx : THMAC_Context; {auth context}
end;
function FCS_EAX256_init(var cx: TSP_EAXContext; pPW: pointer; pLen: word; var hdr: TFCS256Hdr): integer;
{-Initialize crypt context using password pointer pPW and hdr.salt}
function FCS_EAX256_initS(var cx: TSP_EAXContext; sPW: Str255; var hdr: TFCS256Hdr): integer;
{-Initialize crypt context using password string sPW and hdr.salt}
function FCS_EAX256_encrypt(var cx: TSP_EAXContext; var data; dLen: word): integer;
{-encyrypt a block of data in place and update EAX}
function FCS_EAX256_decrypt(var cx: TSP_EAXContext; var data; dLen: word): integer;
{-decyrypt a block of data in place and update EAX}
procedure FCS_EAX256_final(var cx: TSP_EAXContext; var auth: TFCS256_AuthBlock);
{-return final EAX tag}
function FCS_HMAC256_init(var cx: TFCS_HMAC256_Context; pPW: pointer; pLen: word; var hdr: TFCS256Hdr): integer;
{-Initialize crypt context using password pointer pPW and hdr.salt}
function FCS_HMAC256_initS(var cx: TFCS_HMAC256_Context; sPW: Str255; var hdr: TFCS256Hdr): integer;
{-Initialize crypt context using password string sPW and hdr.salt}
function FCS_HMAC256_encrypt(var cx: TFCS_HMAC256_Context; var data; dLen: word): integer;
{-encyrypt a block of data in place and update HMAC}
function FCS_HMAC256_decrypt(var cx: TFCS_HMAC256_Context; var data; dLen: word): integer;
{-decyrypt a block of data in place and update HMAC}
procedure FCS_HMAC256_final(var cx: TFCS_HMAC256_Context; var auth: TFCS256_AuthBlock);
{-return final HMAC-Whirlpool-128 digest}
implementation
type
TX256Key = packed record {eXtended key for PBKDF}
ak: packed array[0..31] of byte; {SP 256 bit key }
hk: packed array[0..31] of byte; {HMAC key / EAX nonce }
pv: word; {password verifier }
end;
{---------------------------------------------------------------------------}
function FCS_HMAC256_init(var cx: TFCS_HMAC256_Context; pPW: pointer; pLen: word; var hdr: TFCS256Hdr): integer;
{-Initialize crypt context using password pointer pPW and hdr.salt}
var
XKey: TX256Key;
CTR : TSPBlock;
pwph: PHashDesc;
Err : integer;
begin
{CTR=0, random/uniqness from hdr.salt}
fillchar(CTR, sizeof(CTR), 0);
{derive the SP, HMAC keys and pw verifier}
pwph := FindHash_by_ID(_Whirlpool);
Err := pbkdf2(pwph, pPW, pLen, @hdr.salt, sizeof(TFCS256Salt), KeyIterations, XKey, sizeof(XKey));
{init SP CTR mode with ak}
if Err=0 then Err := SP_CTR_Init(XKey.ak, 8*sizeof(XKey.ak), CTR, cx.SP_ctx);
{exit if any error}
FCS_HMAC256_init := Err;
if Err<>0 then exit;
{initialise HMAC with hk, here pwph is valid}
hmac_init(cx.hmac_ctx, pwph, @XKey.hk, sizeof(XKey.hk));
{return pw verifier}
hdr.PW_Ver := XKey.pv;
hdr.FCSSig := C_FCS_Sig;
hdr.Flags := $A4;
{burn XKey}
fillchar(XKey, sizeof(XKey),0);
end;
{---------------------------------------------------------------------------}
function FCS_HMAC256_initS(var cx: TFCS_HMAC256_Context; sPW: Str255; var hdr: TFCS256Hdr): integer;
{-Initialize crypt context using password string sPW and hdr.salt}
begin
FCS_HMAC256_initS := FCS_HMAC256_init(cx, @sPW[1], length(sPW), hdr);
end;
{---------------------------------------------------------------------------}
function FCS_HMAC256_encrypt(var cx: TFCS_HMAC256_Context; var data; dLen: word): integer;
{-encyrypt a block of data in place and update HMAC}
begin
FCS_HMAC256_encrypt := SP_CTR_Encrypt(@data, @data, dLen, cx.SP_ctx);
hmac_update(cx.hmac_ctx, @data, dLen);
end;
{---------------------------------------------------------------------------}
function FCS_HMAC256_decrypt(var cx: TFCS_HMAC256_Context; var data; dLen: word): integer;
{-decyrypt a block of data in place and update HMAC}
begin
hmac_update(cx.hmac_ctx, @data, dLen);
FCS_HMAC256_decrypt := SP_CTR_Encrypt(@data, @data, dLen, cx.SP_ctx);
end;
{---------------------------------------------------------------------------}
procedure FCS_HMAC256_final(var cx: TFCS_HMAC256_Context; var auth: TFCS256_AuthBlock);
{-return final HMAC-Whirlpool-128 digest}
var
mac: THashDigest;
begin
hmac_final(cx.hmac_ctx,mac);
move(mac, auth, sizeof(auth));
end;
{---------------------------------------------------------------------------}
function FCS_EAX256_init(var cx: TSP_EAXContext; pPW: pointer; pLen: word; var hdr: TFCS256Hdr): integer;
{-Initialize crypt context using password pointer pPW and hdr.salt}
var
XKey: TX256Key;
Err : integer;
begin
{derive the EAX key / nonce and pw verifier}
Err := pbkdf2(FindHash_by_ID(_Whirlpool), pPW, pLen, @hdr.salt, sizeof(TFCS256Salt), KeyIterations, XKey, sizeof(XKey));
{init SP EAX mode with ak/hk}
if Err=0 then Err := SP_EAX_Init(XKey.ak, 8*sizeof(XKey.ak), xkey.hk, sizeof(XKey.hk), cx);;
{exit if any error}
FCS_EAX256_init := Err;
if Err<>0 then exit;
{return pw verifier}
hdr.PW_Ver := XKey.pv;
hdr.FCSSig := C_FCS_Sig;
hdr.Flags := $A5;
{burn XKey}
fillchar(XKey, sizeof(XKey),0);
end;
{---------------------------------------------------------------------------}
function FCS_EAX256_initS(var cx: TSP_EAXContext; sPW: Str255; var hdr: TFCS256Hdr): integer;
{-Initialize crypt context using password string sPW and hdr.salt}
begin
FCS_EAX256_initS := FCS_EAX256_init(cx, @sPW[1], length(sPW), hdr);
end;
{---------------------------------------------------------------------------}
function FCS_EAX256_encrypt(var cx: TSP_EAXContext; var data; dLen: word): integer;
{-encyrypt a block of data in place and update EAX}
begin
FCS_EAX256_encrypt := SP_EAX_Encrypt(@data, @data, dLen, cx);
end;
{---------------------------------------------------------------------------}
function FCS_EAX256_decrypt(var cx: TSP_EAXContext; var data; dLen: word): integer;
{-decyrypt a block of data in place and update EAX}
begin
FCS_EAX256_decrypt := SP_EAX_decrypt(@data, @data, dLen, cx);
end;
{---------------------------------------------------------------------------}
procedure FCS_EAX256_final(var cx: TSP_EAXContext; var auth: TFCS256_AuthBlock);
{-return final EAX tag}
begin
SP_EAX_Final(TSPBlock(auth), cx);
end;
end.
|
unit Mobs;
interface
uses
Classes,
Vcl.Graphics,
Vcl.Imaging.PNGImage;
type
TMobInfo = record
Force: Integer;
X: Integer;
Y: Integer;
Id: Integer;
Level: Integer;
Exp: Integer;
Name: string;
Life: Integer;
MaxLife: Integer;
MinDam: Integer;
MaxDam: Integer;
Radius: Integer;
Strength: Integer;
Dexterity: Integer;
Intellect: Integer;
Perception: Integer;
Protection: Integer;
Reach: Integer;
SP: Integer;
LP: Integer;
end;
type
TPlayer = class(TObject)
private
FIdx: Integer;
FIsDefeat: Boolean;
public
constructor Create;
destructor Destroy; override;
property Idx: Integer read FIdx write FIdx;
property IsDefeat: Boolean read FIsDefeat write FIsDefeat;
function MaxExp(const Level: Integer): Integer;
procedure Render(Canvas: TCanvas);
procedure Defeat;
procedure FindIdx;
procedure Save;
procedure Load;
end;
type
TMobs = class(TObject)
private
FForce: TStringList;
FCoord: TStringList;
FID: TStringList;
FLevel: TStringList;
FName: TStringList;
FLife: TStringList;
FDam: TStringList;
FRad: TStringList;
FAt1: TStringList;
FAt2: TStringList;
FReach: TStringList;
FPoint: TStringList;
FPlayer: TPlayer;
FIsLook: Boolean;
FLX: Byte;
FLY: Byte;
procedure Miss(Atk: TMobInfo);
procedure Defeat(DefId: Integer; Def: TMobInfo);
function Look(DX, DY: Integer): Boolean;
public
MobLB: TBitmap;
Lifebar: TPNGImage;
Frame: TPNGImage;
constructor Create;
destructor Destroy; override;
procedure Clear;
procedure ChLook;
procedure LoadFromMap(const N: Integer);
procedure Add(const Force, X, Y, Id, Level, Exp: Integer; N: string; L, MaxL, MinD, MaxD, R, Str, Dex, Int, Per, Prot, Reach, SP,
LP: Integer); overload;
procedure Add(const P: TMobInfo); overload;
function BarWidth(CX, MX, GS: Integer): Integer;
function Count: Integer;
function Get(I: Integer): TMobInfo;
function Del(I: Integer): Boolean;
function IndexOf(const X, Y: Integer): Integer;
procedure ModLife(const Index, Value: Integer);
procedure ModExp(const Index, Value: Integer);
procedure Move(const AtkId, DX, DY: Integer); overload;
procedure Move(const DX, DY: Integer); overload;
procedure Attack(const NX, NY, AtkId, DefId: Integer; Atk, Def: TMobInfo);
procedure MoveToPosition(const I, DX, DY: Integer);
procedure SetPosition(const I, X, Y: Integer);
function GetDist(FromX, FromY, ToX, ToY: Single): Word;
procedure Render(Canvas: TCanvas);
property Player: TPlayer read FPlayer write FPlayer;
property IsLook: Boolean read FIsLook write FIsLook;
property LX: Byte read FLX write FLX;
property LY: Byte read FLY write FLY;
end;
implementation
uses
SysUtils,
Math,
Dialogs,
WorldMap,
Mods,
TiledMap,
PathFind,
MsgLog,
Utils;
const
F = '%d=%d';
{ TMobs }
function IsTilePassable(X, Y: Integer): Boolean; stdcall;
begin
with Map.GetCurrentMap do
begin
Result := TiledObject[FMap[lrTiles][X][Y]].Passable;
if (FMap[lrObjects][X][Y] >= 0) then
Result := Result and TiledObject[FMap[lrObjects][X][Y]].Passable;
end;
end;
function TMobs.BarWidth(CX, MX, GS: Integer): Integer;
var
I: Integer;
begin
if (CX = MX) and (CX = 0) then
begin
Result := 0;
Exit;
end;
if (MX <= 0) then
MX := 1;
I := (CX * GS) div MX;
if I <= 0 then
I := 0;
if (CX >= MX) then
I := GS;
Result := I;
end;
procedure TMobs.Add(const Force, X, Y, Id, Level, Exp: Integer; N: string; L, MaxL, MinD, MaxD, R, Str, Dex, Int, Per, Prot, Reach, SP, LP: Integer);
begin
FForce.Append(Force.ToString);
FCoord.Append(Format(F, [X, Y]));
FID.Append(Id.ToString);
FLevel.Append(Format(F, [Level, Exp]));
FName.Append(N);
FLife.Append(Format(F, [L, MaxL]));
FDam.Append(Format(F, [MinD, MaxD]));
FRad.Append(R.ToString);
FAt1.Append(Format(F, [Str, Dex]));
FAt2.Append(Format(F, [Int, Per]));
FReach.Append(Format(F, [Prot, Reach]));
FPoint.Append(Format(F, [SP, LP]));
end;
procedure TMobs.Add(const P: TMobInfo);
begin
Self.Add(P.Force, P.X, P.Y, P.Id, P.Level, P.Exp, P.Name, P.Life, P.MaxLife, P.MinDam, P.MaxDam, P.Radius, P.Strength, P.Dexterity, P.Intellect,
P.Perception, P.Protection, P.Reach, P.SP, P.LP);
end;
procedure TMobs.Attack(const NX, NY, AtkId, DefId: Integer; Atk, Def: TMobInfo);
var
Dam: Integer;
begin
if (Math.RandomRange(0, Atk.Dexterity + 1) >= Math.RandomRange(0, Def.Dexterity + 1)) then
begin
Dam := Math.RandomRange(Atk.MinDam, Atk.MaxDam + 1);
Dam := EnsureRange(Dam - Def.Protection, 1, 255);
if (Math.RandomRange(0, Atk.Level + 1) > Math.RandomRange(0, 100)) then
begin
Dam := Dam + Atk.Strength;
ModLife(DefId, -Dam);
Log.Add(Format('%s: крит %d HP', [Def.Name, -Dam]));
end
else
begin
ModLife(DefId, -Dam);
Log.Add(Format('%s: %d HP', [Def.Name, -Dam]));
end;
end
else
Miss(Atk);
if Get(DefId).Life = 0 then
Defeat(DefId, Def);
end;
procedure TMobs.ChLook;
var
Plr: TMobInfo;
begin
if Player.IsDefeat then
Exit;
IsLook := not IsLook;
if IsLook then
begin
Plr := Get(Player.Idx);
LX := Plr.X;
LY := Plr.Y;
end;
Log.Turn;
end;
procedure TMobs.Clear;
begin
FForce.Clear;
FCoord.Clear;
FID.Clear;
FLevel.Clear;
FName.Clear;
FLife.Clear;
FDam.Clear;
FRad.Clear;
FAt1.Clear;
FAt2.Clear;
FReach.Clear;
FPoint.Clear;
end;
function TMobs.Count: Integer;
begin
Result := FID.Count;
end;
constructor TMobs.Create;
begin
FIsLook := False;
Player := TPlayer.Create;
MobLB := TBitmap.Create;
Lifebar := TPNGImage.Create;
Lifebar.LoadFromFile(GMods.GetPath('images', 'lifebar.png'));
Frame := TPNGImage.Create;
Frame.LoadFromFile(GMods.GetPath('images', 'frame.png'));
FForce := TStringList.Create;
FCoord := TStringList.Create;
FID := TStringList.Create;
FLevel := TStringList.Create;
FName := TStringList.Create;
FLife := TStringList.Create;
FDam := TStringList.Create;
FRad := TStringList.Create;
FAt1 := TStringList.Create;
FAt2 := TStringList.Create;
FReach := TStringList.Create;
FPoint := TStringList.Create;
end;
procedure TMobs.Defeat(DefId: Integer; Def: TMobInfo);
var
I, Exp: Integer;
begin
begin
Exp := Def.Exp;
Log.Add(Format('%s убит', [Def.Name]));
Del(DefId);
// Map.GetCurrentMap.FMap[lrMonsters][NX][NY] := -1;
Player.Idx := -1;
for I := 0 to Count - 1 do
if FForce[I] = '1' then
begin
Player.Idx := I;
Break;
end;
if Player.Idx = -1 then
Player.Defeat
else
ModExp(Player.Idx, Exp);
end;
end;
function TMobs.Del(I: Integer): Boolean;
begin
FForce.Delete(I);
FCoord.Delete(I);
FID.Delete(I);
FLevel.Delete(I);
FName.Delete(I);
FLife.Delete(I);
FDam.Delete(I);
FRad.Delete(I);
FAt1.Delete(I);
FAt2.Delete(I);
FReach.Delete(I);
FPoint.Delete(I);
Result := True;
end;
destructor TMobs.Destroy;
begin
FreeAndNil(FPlayer);
FreeAndNil(MobLB);
FreeAndNil(Lifebar);
FreeAndNil(Frame);
FreeAndNil(FForce);
FreeAndNil(FCoord);
FreeAndNil(FID);
FreeAndNil(FLevel);
FreeAndNil(FName);
FreeAndNil(FLife);
FreeAndNil(FDam);
FreeAndNil(FRad);
FreeAndNil(FAt1);
FreeAndNil(FAt2);
FreeAndNil(FReach);
FreeAndNil(FPoint);
inherited;
end;
function TMobs.Get(I: Integer): TMobInfo;
begin
Result.Force := FForce[I].ToInteger;
Result.X := FCoord.KeyNames[I].ToInteger;
Result.Y := FCoord.ValueFromIndex[I].ToInteger;
Result.Id := FID[I].ToInteger;
Result.Level := FLevel.KeyNames[I].ToInteger;
Result.Exp := FLevel.ValueFromIndex[I].ToInteger;
Result.Name := FName[I];
Result.Life := FLife.KeyNames[I].ToInteger;
Result.MaxLife := FLife.ValueFromIndex[I].ToInteger;
Result.MinDam := FDam.KeyNames[I].ToInteger;
Result.MaxDam := FDam.ValueFromIndex[I].ToInteger;
Result.Radius := FRad[I].ToInteger;
Result.Strength := FAt1.KeyNames[I].ToInteger;
Result.Dexterity := FAt1.ValueFromIndex[I].ToInteger;
Result.Intellect := FAt2.KeyNames[I].ToInteger;
Result.Perception := FAt2.ValueFromIndex[I].ToInteger;
Result.Protection := FReach.KeyNames[I].ToInteger;
Result.Reach := FReach.ValueFromIndex[I].ToInteger;
Result.SP := FPoint.KeyNames[I].ToInteger;
Result.LP := FPoint.ValueFromIndex[I].ToInteger;
end;
function TMobs.GetDist(FromX, FromY, ToX, ToY: Single): Word;
begin
Result := Round(SQRT(SQR(ToX - FromX) + SQR(ToY - FromY)));
end;
function TMobs.IndexOf(const X, Y: Integer): Integer;
begin
Result := FCoord.IndexOf(Format(F, [X, Y]));
end;
procedure TMobs.LoadFromMap(const N: Integer);
var
I, J, F, X, Y: Integer;
begin
J := 0;
for Y := 0 to Map.GetMap(N).Height - 1 do
for X := 0 to Map.GetMap(N).Width - 1 do
begin
F := 0;
I := Map.GetMap(N).FMap[lrMonsters][X][Y];
if I >= 0 then
begin
with Map.GetMap(N).TiledObject[I] do
begin
if LowerCase(Name) = 'player' then
begin
Player.Idx := J;
F := 1;
end;
Add(F, X, Y, I, Level, Exp, Name, Life, Life, MinDam, MaxDam, Radius, Strength, Dexterity, Intellect, Perception, Protection, Reach, 0, 0);
Inc(J);
end;
end;
end;
end;
procedure TMobs.ModExp(const Index, Value: Integer);
var
SP, LP, Level, Exp, MaxExp: Integer;
begin
Level := FLevel.KeyNames[Index].ToInteger;
Exp := FLevel.ValueFromIndex[Index].ToInteger;
SP := FPoint.KeyNames[Index].ToInteger;
LP := FPoint.ValueFromIndex[Index].ToInteger;
Exp := Exp + Value;
Log.Add(Format('Опыт: +%d.', [Value]));
MaxExp := Player.MaxExp(Level);
if Exp > MaxExp then
begin
Log.Add('Новый уровень!');
Level := Level + 1;
SP := SP + 3;
LP := LP + 1;
end;
FLevel[Index] := Format(F, [Level, Exp]);
FPoint[Index] := Format(F, [SP, LP]);
end;
procedure TMobs.ModLife(const Index, Value: Integer);
var
CurLife, MaxLife: Integer;
begin
CurLife := FLife.KeyNames[Index].ToInteger + Value;
MaxLife := FLife.ValueFromIndex[Index].ToInteger;
CurLife := Math.EnsureRange(CurLife, 0, MaxLife);
FLife[Index] := Format(F, [CurLife, MaxLife]);
end;
procedure TMobs.Move(const DX, DY: Integer);
var
I, NX, NY: Integer;
Plr, Enm: TMobInfo;
begin
if Player.IsDefeat then
Exit;
Log.Turn;
Move(Player.Idx, DX, DY);
for I := Count - 1 downto 0 do
begin
if Player.Idx = -1 then
Exit;
if Get(I).Force = 0 then
begin
Plr := Get(Player.Idx);
Enm := Get(I);
NX := 0;
NY := 0;
if (GetDist(Enm.X, Enm.Y, Plr.X, Plr.Y) > Enm.Radius) or not IsPathFind(Map.GetCurrentMap.Width, Map.GetCurrentMap.Height, Enm.X, Enm.Y, Plr.X,
Plr.Y, @IsTilePassable, NX, NY) then
Continue;
MoveToPosition(I, NX, NY);
end
else
begin
end;
end;
end;
procedure TMobs.MoveToPosition(const I, DX, DY: Integer);
var
M: TMobInfo;
NX, NY: Integer;
begin
NX := 0;
NY := 0;
M := Get(I);
if DX < M.X then
NX := -1;
if DX > M.X then
NX := 1;
if DY < M.Y then
NY := -1;
if DY > M.Y then
NY := 1;
Move(I, NX, NY);
end;
procedure TMobs.Render(Canvas: TCanvas);
var
I, X, Y: Integer;
M: TMobInfo;
begin
for I := 0 to Map.GetCurrentMapMobs.Count - 1 do
begin
M := Map.GetCurrentMapMobs.Get(I);
Map.GetCurrentMapMobs.MobLB.Assign(Map.GetCurrentMapMobs.Lifebar);
Map.GetCurrentMapMobs.MobLB.Width := Map.GetCurrentMapMobs.BarWidth(M.Life, M.MaxLife, 30);
X := M.X * Map.GetCurrentMap.TileSize;
Y := M.Y * Map.GetCurrentMap.TileSize;
Canvas.Draw(X + 1, Y, Map.GetCurrentMapMobs.MobLB);
Canvas.Draw(X, Y, Map.GetCurrentMap.TiledObject[M.Id].Image);
end;
if IsLook then
begin
Canvas.Draw(LX * Map.GetCurrentMap.TileSize, LY * Map.GetCurrentMap.TileSize, Map.GetCurrentMapMobs.Frame);
end;
end;
function TMobs.Look(DX, DY: Integer): Boolean;
var
S: string;
begin
Result := False;
if IsLook then
begin
FLX := EnsureRange(FLX + DX, 0, Map.GetCurrentMap.Width - 1);
FLY := EnsureRange(FLY + DY, 0, Map.GetCurrentMap.Height - 1);
S := '';
with Map.GetCurrentMap do
begin
S := TiledObject[FMap[lrTiles][FLX][FLY]].Name;
if (FMap[lrObjects][FLX][FLY] >= 0) then
S := S + '/' + TiledObject[FMap[lrObjects][FLX][FLY]].Name;
end;
Log.Turn;
Log.Add(S);
Result := True;
end;
end;
procedure TMobs.Miss(Atk: TMobInfo);
begin
Log.Add(Format('%s промахивается.', [Atk.Name]));
end;
procedure TMobs.Move(const AtkId, DX, DY: Integer);
var
NX, NY, DefId, I, Dam: Integer;
Atk, Def: TMobInfo;
ObjType, ItemType: string;
begin
if Look(DX, DY) or (Player.Idx = -1) then
Exit;
Atk := Get(AtkId);
if Atk.Life <= 0 then
Exit;
NX := Atk.X + DX;
NY := Atk.Y + DY;
if (NX < 0) and Map.Go(drMapLeft) then
begin
Log.Add(Map.GetCurrentMap.Name);
Map.GetCurrentMapMobs.SetPosition(Map.GetCurrentMapMobs.Player.Idx, Map.GetCurrentMap.Width - 1, NY);
Exit;
end;
if (NX > Map.GetCurrentMap.Width - 1) and Map.Go(drMapRight) then
begin
Log.Add(Map.GetCurrentMap.Name);
Map.GetCurrentMapMobs.SetPosition(Map.GetCurrentMapMobs.Player.Idx, 0, NY);
Exit;
end;
if (NY < 0) and Map.Go(drMapUp) then
begin
Log.Add(Map.GetCurrentMap.Name);
Map.GetCurrentMapMobs.SetPosition(Map.GetCurrentMapMobs.Player.Idx, NX, Map.GetCurrentMap.Height - 1);
Exit;
end;
if (NY > Map.GetCurrentMap.Height - 1) and Map.Go(drMapDown) then
begin
Log.Add(Map.GetCurrentMap.Name);
Map.GetCurrentMapMobs.SetPosition(Map.GetCurrentMapMobs.Player.Idx, NX, 0);
Exit;
end;
if (NX < 0) or (NX > Map.GetCurrentMap.Width - 1) then
Exit;
if (NY < 0) or (NY > Map.GetCurrentMap.Height - 1) then
Exit;
ObjType := Map.GetCurrentMap.GetTileType(lrObjects, NX, NY);
ItemType := Map.GetCurrentMap.GetTileType(lrItems, NX, NY);
if not IsTilePassable(NX, NY) then
Exit;
if (ObjType = 'closed_door') or (ObjType = 'hidden_door') or (ObjType = 'closed_chest') or (ObjType = 'trapped_chest') then
begin
Inc(Map.GetCurrentMap.FMap[lrObjects][NX][NY]);
if (ObjType = 'closed_chest') then
begin
Map.GetCurrentMap.FMap[lrItems][NX][NY] := RandomRange(Map.GetCurrentMap.Firstgid[lrItems], Map.GetCurrentMap.Firstgid[lrMonsters]) - 1;
end;
Exit;
end;
if (ItemType <> '') then
begin
Log.Add('Ваша добыча: ' + ItemType);
Map.GetCurrentMap.FMap[lrItems][NX][NY] := -1;
Exit;
end;
DefId := Self.IndexOf(NX, NY);
if DefId >= 0 then
begin
Def := Get(DefId);
if Atk.Force <> Def.Force then
begin
Self.Attack(NX, NY, AtkId, DefId, Atk, Def);
end;
Exit;
end;
SetPosition(AtkId, NX, NY);
end;
procedure TMobs.SetPosition(const I, X, Y: Integer);
begin
FCoord[I] := Format(F, [X, Y]);
end;
{ TPlayer }
constructor TPlayer.Create;
begin
Idx := -1;
IsDefeat := False;
end;
procedure TPlayer.Defeat;
begin
IsDefeat := True;
ShowMessage('DEFEAT!!!');
end;
destructor TPlayer.Destroy;
begin
inherited;
end;
procedure TPlayer.FindIdx;
var
I: Integer;
P: TMobInfo;
begin
Idx := -1;
for I := 0 to Map.GetCurrentMapMobs.Count - 1 do
begin
P := Map.GetCurrentMapMobs.Get(I);
if P.Force = 1 then
begin
Idx := I;
Break;
end;
end;
end;
procedure TPlayer.Render(Canvas: TCanvas);
var
S: string;
M: TMobInfo;
begin
if Map.GetCurrentMapMobs.Player.IsDefeat then
Exit;
M := Map.GetCurrentMapMobs.Get(Idx);
S := Format('%s HP:%d/%d Dam:%d-%d P:%d Lev:%d Exp:%d/%d SP/LP:%d/%d STR/DEX/INT/PER: %d/%d/%d/%d',
[M.Name, M.Life, M.MaxLife, M.MinDam, M.MaxDam, M.Protection, M.Level, M.Exp, MaxExp(M.Level), M.SP, M.LP, M.Strength, M.Dexterity, M.Intellect,
M.Perception]);
Canvas.TextOut(0, Map.GetCurrentMap.TileSize * (Map.GetCurrentMap.Height + 4), S);
end;
procedure TPlayer.Load;
var
Path: string;
SL: TStringList;
M: TMobInfo;
Level, Exp, MaxLife, MinDam, MaxDam, Str, Dex, Int, Per, Prot, SP, LP: Integer;
begin
if IsDefeat then
Exit;
Path := GetPath('saves') + 'player.sav';
if not FileExists(Path) then
Exit;
SL := TStringList.Create;
try
SL.LoadFromFile(Path, TEncoding.UTF8);
Level := StrToInt(SL[0]);
Exp := StrToInt(SL[1]);
MaxLife := StrToInt(SL[2]);
MinDam := StrToInt(SL[3]);
MaxDam := StrToInt(SL[4]);
Str := StrToInt(SL[5]);
Dex := StrToInt(SL[6]);
Int := StrToInt(SL[7]);
Per := StrToInt(SL[8]);
Prot := StrToInt(SL[9]);
SP := StrToInt(SL[10]);
LP := StrToInt(SL[11]);
M := Map.GetCurrentMapMobs.Get(Idx);
Map.GetCurrentMapMobs.Del(Idx);
M.Level := Level;
M.Exp := Exp;
M.Life := MaxLife;
M.MaxLife := MaxLife;
M.MinDam := MinDam;
M.MaxDam := MaxDam;
M.Strength := Str;
M.Dexterity := Dex;
M.Intellect := Int;
M.Perception := Per;
M.Protection := Prot;
M.SP := SP;
M.LP := LP;
Map.GetCurrentMapMobs.Add(M);
Map.GetCurrentMapMobs.Player.FindIdx;
finally
FreeAndNil(SL);
end;
end;
function TPlayer.MaxExp(const Level: Integer): Integer;
var
I: Integer;
begin
Result := 10;
for I := 1 to Level do
Result := Result + ((Level * 10) + Round(Result * 0.33));
end;
procedure TPlayer.Save;
var
P: TMobInfo;
Path: string;
SL: TStringList;
begin
if IsDefeat then
Exit;
Path := GetPath('saves') + 'player.sav';
SL := TStringList.Create;
P := Map.GetCurrentMapMobs.Get(Idx);
try
SL.Append(IntToStr(P.Level));
SL.Append(IntToStr(P.Exp));
SL.Append(IntToStr(P.MaxLife));
SL.Append(IntToStr(P.MinDam));
SL.Append(IntToStr(P.MaxDam));
SL.Append(IntToStr(P.Strength));
SL.Append(IntToStr(P.Dexterity));
SL.Append(IntToStr(P.Intellect));
SL.Append(IntToStr(P.Perception));
SL.Append(IntToStr(P.Protection));
SL.Append(IntToStr(P.SP));
SL.Append(IntToStr(P.LP));
SL.SaveToFile(Path, TEncoding.UTF8);
finally
FreeAndNil(SL);
end;
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLVerletHairClasses<p>
Creates a single strand of hair using verlet classes. Can be used to simulate
ropes, fur or hair.<p>
<b>History : </b><font size=-1><ul>
<li>29/05/08 - DaStr - Added $I GLScene.inc
<li>06/03/04 - MF - Creation
</ul>
}
unit GLVerletHairClasses;
interface
{$I GLScene.inc}
uses
System.Classes, System.SysUtils,
GLVerletTypes, GLVectorTypes, GLVectorLists, GLVectorGeometry;
type
TVHStiffness = (vhsFull, vhsSkip1Node, vhsSkip2Node, vhsSkip3Node,
vhsSkip4Node, vhsSkip5Node, vhsSkip6Node, vhsSkip7Node, vhsSkip8Node,
vhsSkip9Node);
TVHStiffnessSet = set of TVHStiffness;
TVerletHair = class
private
FNodeList: TVerletNodeList;
FLinkCount: integer;
FRootDepth: single;
FVerletWorld: TVerletWorld;
FHairLength: single;
FData: pointer;
FStiffness: TVHStiffnessSet;
FStiffnessList : TList;
function GetAnchor: TVerletNode;
function GetRoot: TVerletNode;
function GetLinkLength: single;
procedure AddStickStiffness(const ANodeSkip : integer);
procedure SetStiffness(const Value: TVHStiffnessSet);
public
procedure BuildHair(const AAnchorPosition, AHairDirection: TAffineVector);
procedure BuildStiffness;
procedure ClearStiffness;
procedure Clear;
constructor Create(const AVerletWorld : TVerletWorld;
const ARootDepth, AHairLength : single; ALinkCount : integer;
const AAnchorPosition, AHairDirection : TAffineVector;
const AStiffness : TVHStiffnessSet);
destructor Destroy; override;
property NodeList : TVerletNodeList read FNodeList;
property VerletWorld : TVerletWorld read FVerletWorld;
property RootDepth : single read FRootDepth;
property LinkLength : single read GetLinkLength;
property LinkCount : integer read FLinkCount;
property HairLength : single read FHairLength;
property Stiffness : TVHStiffnessSet read FStiffness write SetStiffness;
property Data : pointer read FData write FData;
{: Anchor should be nailed down to give the hair stability }
property Anchor : TVerletNode read GetAnchor;
{: Root should be nailed down to give the hair stability }
property Root : TVerletNode read GetRoot;
end;
implementation
{ TVerletHair }
procedure TVerletHair.AddStickStiffness(const ANodeSkip: integer);
var
i : integer;
begin
for i := 0 to NodeList.Count-(1+ANodeSkip*2) do
FStiffnessList.Add(VerletWorld.CreateStick(NodeList[i], NodeList[i+2*ANodeSkip]));
end;
procedure TVerletHair.BuildHair(const AAnchorPosition, AHairDirection: TAffineVector);
var
i : integer;
Position : TAffineVector;
Node, PrevNode : TVerletNode;
Direction : TAffineVector;
begin
Clear;
Direction := VectorNormalize(AHairDirection);
// Fix the root of the hair
Position := VectorAdd(AAnchorPosition, VectorScale(Direction, -FRootDepth));
Node := VerletWorld.CreateOwnedNode(Position);
NodeList.Add(Node);
Node.NailedDown := true;
PrevNode := Node;
// Now add the links in the hair
for i := 0 to FLinkCount-1 do
begin
Position := VectorAdd(AAnchorPosition, VectorScale(Direction, HairLength * (i/LinkCount)));
Node := VerletWorld.CreateOwnedNode(Position);
NodeList.Add(Node);
// first one is the anchor
if i=0 then
Node.NailedDown := true
else
// Create the hair link
VerletWorld.CreateStick(PrevNode, Node);
PrevNode := Node;
end;
// Now we must stiffen the hair with either sticks or springs
BuildStiffness;
end;
procedure TVerletHair.BuildStiffness;
var
i : integer;
begin
ClearStiffness;
if vhsFull in FStiffness then
begin
for i := 1 to 100 do
AddStickStiffness(i);
exit;
end;
if vhsSkip1Node in FStiffness then AddStickStiffness(1);
if vhsSkip2Node in FStiffness then AddStickStiffness(2);
if vhsSkip3Node in FStiffness then AddStickStiffness(3);
if vhsSkip4Node in FStiffness then AddStickStiffness(4);
if vhsSkip5Node in FStiffness then AddStickStiffness(5);
if vhsSkip6Node in FStiffness then AddStickStiffness(6);
if vhsSkip7Node in FStiffness then AddStickStiffness(7);
if vhsSkip8Node in FStiffness then AddStickStiffness(8);
if vhsSkip9Node in FStiffness then AddStickStiffness(9);
end;
procedure TVerletHair.Clear;
var
i : integer;
begin
ClearStiffness;
for i := FNodeList.Count-1 downto 0 do
FNodeList[i].Free;
FNodeList.Clear;
FStiffnessList.Clear;
end;
procedure TVerletHair.ClearStiffness;
var
i : integer;
begin
for i := 0 to FStiffnessList.Count-1 do
TVerletConstraint(FStiffnessList[i]).Free;
FStiffnessList.Clear;
end;
constructor TVerletHair.Create(const AVerletWorld : TVerletWorld;
const ARootDepth, AHairLength : single; ALinkCount : integer;
const AAnchorPosition, AHairDirection : TAffineVector;
const AStiffness : TVHStiffnessSet);
begin
FVerletWorld := AVerletWorld;
FRootDepth := ARootDepth;
FLinkCount := ALinkCount;
FHairLength := AHairLength;
FNodeList := TVerletNodeList.Create;
FStiffness := AStiffness;
FStiffnessList := TList.Create;
BuildHair(AAnchorPosition, AHairDirection);
end;
destructor TVerletHair.Destroy;
begin
Clear;
FreeAndNil(FNodeList);
FreeAndNil(FStiffnessList);
inherited;
end;
function TVerletHair.GetAnchor: TVerletNode;
begin
result := NodeList[1];
end;
function TVerletHair.GetLinkLength: single;
begin
if LinkCount>0 then
result := HairLength / LinkCount
else
result := 0;
end;
function TVerletHair.GetRoot: TVerletNode;
begin
result := NodeList[0];
end;
procedure TVerletHair.SetStiffness(const Value: TVHStiffnessSet);
begin
FStiffness := Value;
BuildStiffness;
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ }
{ Copyright(c) 2015-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit System.Win.ShareContract;
interface
{$SCOPEDENUMS ON}
uses
System.Sysutils, System.Win.WinRT, System.Classes, System.Generics.Collections, Winapi.Windows,
WinAPI.WinRT, WinAPI.Foundation.Types, WinAPI.ApplicationModel.DataTransfer, WinAPI.Storage, WinAPI.Storage.Streams;
{$HPPEMIT 'using namespace Winapi::Applicationmodel::Datatransfer;'}
type
/// <summary>Exception class for ShareContract specific exceptions</summary>
EShareContractException = class(Exception);
/// <summary>Signature for an event fired when a target application has been chosen</summary>
TApplicationChosenEvent = procedure(const Sender: TObject; const AManager: IDataTransferManager;
const Args: ITargetApplicationChosenEventArgs) of object;
/// <summary>Signature for an event fired when requiring data for an ongoing transference</summary>
TTransferDataEvent = procedure(const Sender: TObject; const ARequest: IDataProviderRequest) of object;
/// <summary>Signature for a procedure to be executed when processing the application message queue is is needed</summary>
TProcessMessagesProc = procedure of object;
/// <summary>Class that encapsulate and provides access to the sharing contract</summary>
TShareContract = class
private type
TDataTransferEventHandler = class(TInspectableObject,
TypedEventHandler_2__IDataTransferManager__IDataRequestedEventArgs_Delegate_Base,
TypedEventHandler_2__IDataTransferManager__IDataRequestedEventArgs)
private
[Weak] FOwner: TShareContract;
procedure Invoke(sender: IDataTransferManager; args: IDataRequestedEventArgs); safecall;
public
constructor Create(const AOwner: TShareContract);
destructor Destroy; override;
end;
TAppChosenEventHandler = class(TInspectableObject,
TypedEventHandler_2__IDataTransferManager__ITargetApplicationChosenEventArgs_Delegate_Base,
TypedEventHandler_2__IDataTransferManager__ITargetApplicationChosenEventArgs)
private
[Weak] FOwner: TShareContract;
procedure Invoke(sender: IDataTransferManager; args: ITargetApplicationChosenEventArgs); safecall;
public
constructor Create(const AOwner: TShareContract);
end;
TDataProviderHandler = class(TInspectableObject, DataProviderHandler)
private
[Weak] FOwner: TShareContract;
procedure Invoke(request: IDataProviderRequest); safecall;
public
constructor Create(const AOwner: TShareContract);
end;
TCompletedHandler = class(TInspectableObject,
AsyncOperationCompletedHandler_1__IStorageFile_Delegate_Base,
AsyncOperationCompletedHandler_1__IStorageFile)
private
FStatus: AsyncStatus;
function GetAsyncStatus: AsyncStatus;
public
procedure Invoke(asyncInfo: IAsyncOperation_1__IStorageFile; aasyncStatus: AsyncStatus); safecall;
property Status: AsyncStatus read GetAsyncStatus;
end;
private
class var
FProcessMessages: TProcessMessagesProc;
class var
FBasePath: string;
private
FOnTransferImage: TTransferDataEvent;
FOnAppChosen: TApplicationChosenEvent;
FPackageName: string;
FContentSourceWebLink: string;
FContentSourceApplicationLink: string;
FImageFile: string;
FIconFile: string;
FWebAddress: string;
FApplicationName: string;
FDescription: string;
FDataTitle: string;
FDataText: string;
FLogoFile: string;
FRtfText: string;
FHTML: string;
FFileList: TStrings;
procedure DoTransferImage(const ARequest: IDataProviderRequest);
procedure DoAppChosen(sender: IDataTransferManager; args: ITargetApplicationChosenEventArgs);
class procedure SetProcessMessages(const Value: TProcessMessagesProc); static;
protected
/// <summary>Window Handle needed to share data</summary>
FWindowHandle: THandle;
/// <summary>Interface to access to the SharingContract</summary>
FTransferManager: IDataTransferManager;
/// <summary>Event Registration token needed to unregister the DataRequestedHandler</summary>
FSharingRequested: EventRegistrationToken;
/// <summary>Event Registration token needed to unregister the AppChosenHandler</summary>
FTargetAppRequested: EventRegistrationToken;
/// <summary>EventHandler to manage DataRequest events</summary>
FDataRequestedHandlerIntf: TypedEventHandler_2__IDataTransferManager__IDataRequestedEventArgs;
/// <summary>EventHandler to manage AppChosen events</summary>
FAppChosenHandlerIntf: TypedEventHandler_2__IDataTransferManager__ITargetApplicationChosenEventArgs;
/// <summary>EventHandler to manage Image Transfer events</summary>
FImageDataProvider: DataProviderHandler;
private
class procedure ProcessMessages;
public
constructor Create(AWinHandle: HWND);
destructor Destroy; override;
/// <summary>User invoked procedure to start sharing data with other applications</summary>
procedure InitSharing;
/// <summary>Property that holds a reference to the Application's ProcessMessages procedure</summary>
class property OnProcessMessages: TProcessMessagesProc read FProcessMessages write SetProcessMessages;
/// <summary>Commom path to be used with properties that hold a file name</summary>
class property BasePath: string read FBasePath write FBasePath;
/// <summary>Function that converts a FileName to a IRandomAccessStreamReference. Opens and loads the specified file.</summary>
class function FileNameToStream(const AFileName: string): IRandomAccessStreamReference; static;
public
/// <summary>Application Name to be shared with the target application</summary>
property ApplicationName: string read FApplicationName write FApplicationName;
/// <summary>ContentSourceWebLink to be shared with the target application</summary>
property ContentSourceWebLink: string read FContentSourceWebLink write FContentSourceWebLink;
/// <summary>ContentSourceApplicationLink to be shared with the target application</summary>
property ContentSourceApplicationLink: string read FContentSourceApplicationLink write FContentSourceApplicationLink;
/// <summary>DataText to be shared with the target application</summary>
property DataText: string read FDataText write FDataText;
/// <summary>DataTitle to be shared with the target application</summary>
property DataTitle: string read FDataTitle write FDataTitle;
/// <summary>Description to be shared with the target application</summary>
property Description: string read FDescription write FDescription;
/// <summary>IconFile to be shared with the target application</summary>
property IconFile: string read FIconFile write FIconFile;
/// <summary>ImageFile to be shared with the target application</summary>
property ImageFile: string read FImageFile write FImageFile;
/// <summary>LogoFile to be shared with the target application</summary>
property LogoFile: string read FLogoFile write FLogoFile;
/// <summary>Package Name to be shared with the target application</summary>
property PackageName: string read FPackageName write FPackageName;
/// <summary>Web address to be shared with the target application</summary>
property WebAddress: string read FWebAddress write FWebAddress;
/// <summary>RtfText to be shared with the target application</summary>
property RtfText: string read FRtfText write FRtfText;
/// <summary>HTML to be shared with the target application</summary>
property HTML: string read FHTML write FHTML;
/// <summary>FileList to be shared with the target application</summary>
property FileList: TStrings read FFileList write FFileList;
// Events...
/// <summary>Event invoked when sharing an Image</summary>
property OnTransferImage: TTransferDataEvent read FOnTransferImage write FOnTransferImage;
/// <summary>Event invoked when user selects a target application that is going to receive the shared information</summary>
property OnAppChosen: TApplicationChosenEvent read FOnAppChosen write FOnAppChosen;
/// <summary>Event invoked when system requests for data to be shared</summary>
property OnDataRequest : TypedEventHandler_2__IDataTransferManager__IDataRequestedEventArgs read FDataRequestedHandlerIntf write FDataRequestedHandlerIntf;
end;
TIterableStorageItems = class(TInspectableObject, IIterable_1__IStorageItem)
private
FItems: TList<IStorageItem>;
public
constructor Create;
function First: IIterator_1__IStorageItem; safecall;
procedure Add(AItem: IStorageItem);
end;
TIteratorStorageItems = class(TInspectableObject, IIterator_1__IStorageItem)
private
FList: TList<IStorageItem>;
FIndex: Integer;
public
constructor Create(AItems: TList<IStorageItem>);
function GetMany(itemsSize: Cardinal; items: PIStorageItem)
: Cardinal; safecall;
function MoveNext: Boolean; safecall;
function get_Current: IStorageItem; safecall;
function get_HasCurrent: Boolean; safecall;
end;
TOperationCompleted = class(TInterfacedObject,
AsyncOperationCompletedHandler_1__IStorageFile,
AsyncOperationCompletedHandler_1__IStorageFile_Delegate_Base)
private
FResult: IStorageFile;
procedure SetResult(const Value: IStorageFile);
public
constructor Create;
procedure Invoke(AAsyncInfo: IAsyncOperation_1__IStorageFile;
aasyncStatus: AsyncStatus); safecall;
property Result: IStorageFile read FResult write SetResult;
end;
implementation
uses
WinAPI.CommonTypes, WinAPI.Foundation, WinAPI.Foundation.Collections,
System.IOUtils, System.RTLConsts;
{ TShareContract }
constructor TShareContract.Create(AWinHandle: HWND);
begin
inherited Create;
FFileList := TStringList.Create;
if not Assigned(FProcessMessages) then
raise EShareContractException.Create(SShareContractNotInitialized);
FWindowHandle := AWinHandle;
if TOSVersion.Check(10) then
begin
FTransferManager := TDataTransferManager.Interop.GetForWindow(FWindowHandle, TWinRTImportHelper.GetUIID<IDataTransferManager>);
// Set Handler???
FDataRequestedHandlerIntf := TDataTransferEventHandler.Create(Self);
FSharingRequested := FTransferManager.add_DataRequested(FDataRequestedHandlerIntf);
FAppChosenHandlerIntf := TAppChosenEventHandler.Create(Self);
FTargetAppRequested := FTransferManager.add_TargetApplicationChosen(FAppChosenHandlerIntf);
FImageDataProvider := TDataProviderHandler.Create(Self);
end;
end;
destructor TShareContract.Destroy;
begin
if FTransferManager <> nil then
begin
FTransferManager.remove_DataRequested(FSharingRequested);
FTransferManager.remove_TargetApplicationChosen(FTargetAppRequested);
end;
FFileList.Free;
inherited;
end;
procedure TShareContract.DoAppChosen(sender: IDataTransferManager; args: ITargetApplicationChosenEventArgs);
begin
if Assigned(FOnAppChosen) then
FOnAppChosen(Self, sender, args);
end;
procedure TShareContract.DoTransferImage(const ARequest: IDataProviderRequest);
begin
if Assigned(FOnTransferImage) then
FOnTransferImage(Self, ARequest)
else
ARequest.SetData(FileNameToStream(ImageFile));
end;
class function TShareContract.FileNameToStream(const AFileName: string): IRandomAccessStreamReference;
var
LFileName: TWindowsString;
LFileAsync: IAsyncOperation_1__IStorageFile;
LCompHandler: AsyncOperationCompletedHandler_1__IStorageFile;
begin
Result := nil;
LFileName := TWindowsString.Create(TPath.Combine(FBasePath, AFileName));
LFileAsync := TStorageFile.Statics.GetFileFromPathAsync(LFileName);
LCompHandler := TShareContract.TCompletedHandler.Create;
LFileAsync.Completed := LCompHandler;
if TShareContract.TCompletedHandler(LCompHandler).Status = AsyncStatus.Completed then
Result := TRandomAccessStreamReference.Statics.CreateFromFile(LFileAsync.GetResults);
end;
procedure TShareContract.InitSharing;
begin
if TOsVersion.Check(10) then
TDataTransferManager.Interop.ShowShareUIForWindow(FWindowHandle)
else
raise EShareContractException.CreateFmt(SShareContractNotSupported, [TOSVersion.ToString]);
end;
class procedure TShareContract.ProcessMessages;
begin
if Assigned(FProcessMessages) then
FProcessMessages;
end;
class procedure TShareContract.SetProcessMessages(const Value: TProcessMessagesProc);
begin
FProcessMessages := Value;
end;
{ TShareContract.TDataTransferEventHandler }
constructor TShareContract.TDataTransferEventHandler.Create(const AOwner: TShareContract);
begin
inherited Create;
FOwner := AOwner;
end;
destructor TShareContract.TDataTransferEventHandler.Destroy;
begin
inherited;
end;
procedure TShareContract.TDataTransferEventHandler.Invoke(sender: IDataTransferManager;
args: IDataRequestedEventArgs);
var
LRequest: IDataRequest;
LDataPackage: IDataPackage;
LProperties: IDataPackagePropertySet;
LProperties2: IDataPackagePropertySet2;
LURI: IUriRuntimeClass;
LWebURI: IUriRuntimeClass;
LWebAppURI: IUriRuntimeClass;
LWindowsString: TWindowsString;
LTmpWinStr: TWindowsString;
LMyElem: String;
LIterableStorageItems: TIterableStorageItems;
LAsynOp: IAsyncOperation_1__IStorageFile;
LStorageFile: IStorageFile;
LOut: IAsyncInfo;
LErr: Cardinal;
begin
LRequest := args.get_Request;
LDataPackage := LRequest.get_Data;
LProperties := LDataPackage.get_Properties;
if FOwner.DataTitle <> '' then
begin
LWindowsString := TWindowsString.Create(FOwner.DataTitle);
LProperties.Title := LWindowsString;
end;
if FOwner.ApplicationName <> '' then
begin
LWindowsString := TWindowsString.Create(FOwner.ApplicationName);
LProperties.ApplicationName := LWindowsString;
end;
if FOwner.Description <> '' then
begin
LWindowsString := TWindowsString.Create(FOwner.Description);
LProperties.Description := LWindowsString;
end;
if FOwner.ImageFile <> '' then
begin
LProperties.Thumbnail := FileNameToStream(FOwner.ImageFile);
end;
if FOwner.DataText <> '' then
begin
LWindowsString := TWindowsString.Create(FOwner.DataText);
LDataPackage.SetText(LWindowsString);
end;
if FOwner.RtfText <> '' then
begin
LDataPackage.Properties.FileTypes.Append(TStandardDataFormats.Statics.Rtf);
LWindowsString := TWindowsString.Create(FOwner.RtfText);
LDataPackage.SetRtf(LWindowsString);
end;
if FOwner.HTML <> '' then
begin
LDataPackage.Properties.FileTypes.Append(TStandardDataFormats.Statics.Html);
LWindowsString := TWindowsString.Create(FOwner.HTML);
LDataPackage.SetHtmlFormat(THtmlFormatHelper.Statics.CreateHtmlFormat(LWindowsString));
end;
if FOwner.WebAddress <> '' then
begin
LWindowsString := TWindowsString.Create(FOwner.WebAddress);
LURI := TUri.Factory.CreateUri(LWindowsString);
LDataPackage.SetUri(LURI);
end;
LProperties2 := LDataPackage.get_Properties as IDataPackagePropertySet2;
if FOwner.ContentSourceApplicationLink <> '' then
begin
LWindowsString := TWindowsString.Create(FOwner.ContentSourceApplicationLink);
LWebAppURI := TUri.Factory.CreateUri(LWindowsString);
LProperties2.ContentSourceApplicationLink := LWebAppURI;
end;
if FOwner.ContentSourceWebLink <> '' then
begin
LWindowsString := TWindowsString.Create(FOwner.ContentSourceWebLink);
LWebURI := TUri.Factory.CreateUri(LWindowsString);
LProperties2.ContentSourceWebLink := LWebURI;
end;
if FOwner.PackageName <> '' then
begin
LWindowsString := TWindowsString.Create(FOwner.PackageName);
LProperties2.PackageFamilyName := LWindowsString;
end;
if FOwner.LogoFile <> '' then
LProperties2.Square30x30Logo := FileNameToStream(FOwner.LogoFile);
if FOwner.FFileList.Count > 0 then
begin
LIterableStorageItems := TIterableStorageItems.Create;
for LMyElem in FOwner.FFileList do
begin
if LMyElem <> '' then
begin
LTmpWinStr := TWindowsString.Create(LMyElem);
LAsynOp := TStorageFile.GetFileFromPathAsync(LTmpWinStr);
if not Supports(LAsynOp, IAsyncInfo, LOut) then
raise Exception.Create('Interface not supports IAsyncInfo');
while not(LOut.Status in [AsyncStatus.Completed, AsyncStatus.Canceled,
AsyncStatus.Error]) do
begin
Sleep(100);
FOwner.OnProcessMessages;
end;
LErr := HResultCode(LOut.ErrorCode);
if LErr <> ERROR_SUCCESS then
// FIX {how to retrieve the error description?}
raise Exception.Create(SysErrorMessage(LErr));
LStorageFile := LAsynOp.GetResults;
LIterableStorageItems.Add(LStorageFile as IStorageItem);
end;
end;
LRequest.Data.SetStorageItems(LIterableStorageItems);
end;
end;
{ TShareContractComponent.TAppChosenEventHandler }
constructor TShareContract.TAppChosenEventHandler.Create(const AOwner: TShareContract);
begin
FOwner := AOwner;
end;
procedure TShareContract.TAppChosenEventHandler.Invoke(sender: IDataTransferManager; args: ITargetApplicationChosenEventArgs);
begin
FOwner.DoAppChosen(sender, args);
end;
{ TShareContract.TDataProviderHandler }
constructor TShareContract.TDataProviderHandler.Create(const AOwner: TShareContract);
begin
FOwner := AOwner;
end;
procedure TShareContract.TDataProviderHandler.Invoke(request: IDataProviderRequest);
begin
FOwner.DoTransferImage(request);
end;
{ TShareContract.TCompletedHandler }
function TShareContract.TCompletedHandler.GetAsyncStatus: AsyncStatus;
begin
while FStatus = AsyncStatus.Started do
TShareContract.ProcessMessages;
Result := FStatus;
end;
procedure TShareContract.TCompletedHandler.Invoke(asyncInfo: IAsyncOperation_1__IStorageFile;
aasyncStatus: AsyncStatus);
begin
FStatus := aasyncstatus;
end;
{ TIterableStorageFiles }
procedure TIterableStorageItems.Add(AItem: IStorageItem);
begin
FItems.Add(AItem);
end;
constructor TIterableStorageItems.Create;
begin
inherited;
FItems := TList<IStorageItem>.Create;
end;
function TIterableStorageItems.First: IIterator_1__IStorageItem;
begin
Result := TIteratorStorageItems.Create(FItems);
end;
{ TIteratorStorageItems }
constructor TIteratorStorageItems.Create(AItems: TList<IStorageItem>);
begin
inherited Create;
FList := AItems;
FIndex := 0;
end;
function TIteratorStorageItems.GetMany(itemsSize: Cardinal;
items: PIStorageItem): Cardinal;
begin
raise Exception.Create('Not Implemented');
Result:=FList.Count;
end;
function TIteratorStorageItems.get_Current: IStorageItem;
begin
Result := FList[FIndex];
end;
function TIteratorStorageItems.get_HasCurrent: Boolean;
begin
Result := ((FIndex > -1) and (FIndex < FList.Count))
end;
function TIteratorStorageItems.MoveNext: Boolean;
begin
if (FIndex < (FList.Count - 1)) then
begin
inc(FIndex);
Result := True;
end
else
begin
Result := False;
end;
end;
{ TOperationCompleted }
constructor TOperationCompleted.Create;
begin
end;
procedure TOperationCompleted.Invoke(AAsyncInfo
: IAsyncOperation_1__IStorageFile; aasyncStatus: AsyncStatus);
begin
if (aasyncStatus = AsyncStatus.Completed) then
begin
SetResult(AAsyncInfo.GetResults);
end;
end;
procedure TOperationCompleted.SetResult(const Value: IStorageFile);
begin
FResult := Value;
end;
end.
|
{-----------------------------------------------------------------------------
The contents of this file are subject to the GNU General Public 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.gnu.org/copyleft/gpl.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.
The Initial Developer of the Original Code is Michael Elsdörfer.
All Rights Reserved.
$Id$
You may retrieve the latest version of this file at the Corporeal
Website, located at http://www.elsdoerfer.info/corporeal
Known Issues:
-----------------------------------------------------------------------------}
unit Core;
interface
uses
Windows,
VersionInfo;
const
AppShortName = 'Corporeal';
AppWebsiteUrl = 'http://www.elsdoerfer.info/corporeal';
function AppnameWithVersion: string;
function AppVersion: string;
var
// This will store our custom windows message we use to tell an already
// existing instance to activate itself once a second is started up.
// It is registered with windows in the init section of this unit.
WM_INSTANCE_LIMIT_MESSAGE: DWORD;
// Commonly used strings
resourcestring
XMLFilter = 'XML Files (*.xml)';
AllFilesFilter = 'All Files (*.*)';
CorporealFilter = 'Corporeal Store Files (*.corporeal;*.patronus)';
TogglePasswordCharHint = 'Toggle Hide/Show Passwords';
implementation
function AppVersion: string;
begin
Result := MakeVersionString(vsfFull);
end;
function AppnameWithVersion: string;
begin
Result := AppShortname+' '+MakeVersionString(vsfShort);
end;
initialization
// Use guid as identifier
WM_INSTANCE_LIMIT_MESSAGE :=
RegisterWindowMessage('{18C01079-A5B4-490C-B9A1-791438C2B6A6}');
end.
|
unit ImplItfCppOrdine;
{ *---------------------------------------------------------------
Unit con le implementazioni delle interfaccie
@Author: Roberto Carrer
@Date: 28/04/2019
----------------------------------------------------------------* }
interface
uses ItfCppOrdine, classes;
type
{ *---------------------------------------------------------------
Implementazione interfaccia per la riga ordine
@Author: Roberto Carrer
@Date: 28/04/2019
----------------------------------------------------------------* }
TImplCppRiga = class(TObject, ICppRiga)
public
function GetCodice: PWideChar; stdcall;
function GetDescrizione: PWideChar; stdcall;
function GetQta(): Integer; stdcall;
protected
// Property per i test
m_cod: AnsiString;
m_des: AnsiString;
m_qta: Integer;
m_refCount: Integer;
constructor Create(const codice: AnsiString; const descrizione: AnsiString);
function generaQta(): Integer;
function QueryInterface(const IID: TGUID; out Obj): HRESULT; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
end;
{ *---------------------------------------------------------------
Implementazione interfaccia con i dati di testata ordine e relative righe
@Author: Roberto Carrer
@Date: 28/04/2019
----------------------------------------------------------------* }
TImplCppOrdine = class(TObject, ICppOrdine)
public
m_cppRiga: TImplCppRiga;
function GetNumeroOrdine: Integer; stdcall;
function GetRiga(const index: Integer): { ICppRiga } Pointer; stdcall;
function ContaRighe(): Integer; stdcall;
constructor Create();
destructor Destroy(); override;
protected
// Property private di mockup per i test
m_numeroOrdine: Integer;
m_lstRighe: TList;
m_refCount: Integer;
procedure creaDatiMockup();
function QueryInterface(const IID: TGUID; out Obj): HRESULT; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
end;
implementation
{ TImplCppOrdine }
function TImplCppOrdine.ContaRighe: Integer;
begin
result := m_lstRighe.Count;
end;
procedure TImplCppOrdine.creaDatiMockup;
var
rg: TImplCppRiga;
begin
// Preparo un numero ordine finto
m_numeroOrdine := 20190428;
// Creo delle righe fittizzie
rg := TImplCppRiga.Create('Art01', 'Articolo riga 1');
m_lstRighe.Add(rg);
rg := TImplCppRiga.Create('Art02', 'Articolo riga21');
m_lstRighe.Add(rg);
rg := TImplCppRiga.Create('Art03', 'Articolo riga 3');
m_lstRighe.Add(rg);
end;
constructor TImplCppOrdine.Create();
begin
inherited;
m_cppRiga := nil;
m_lstRighe := TList.Create();
// Solo per i test
creaDatiMockup();
end;
destructor TImplCppOrdine.Destroy;
var
kk: Integer;
begin
for kk := 0 to m_lstRighe.Count - 1 do
begin
TImplCppRiga(m_lstRighe.Items[kk]).free;
end;
m_lstRighe.Clear;
end;
function TImplCppOrdine.GetNumeroOrdine: Integer;
begin
result := m_numeroOrdine;
end;
function TImplCppOrdine.GetRiga(const index: Integer): { ICppRiga } Pointer;
var
rg: TImplCppRiga;
begin
result := nil;
if index <= m_lstRighe.Count then
begin
// ritorno la struttura cercata
rg := m_lstRighe.Items[index];
result := Pointer(ICppRiga(rg));
end;
end;
function TImplCppOrdine.QueryInterface(const IID: TGUID; out Obj): HRESULT;
begin
Pointer(Obj) := self;
result := S_OK;
end;
function TImplCppOrdine._AddRef: Integer;
begin
inc(m_refCount);
result := m_refCount;
end;
function TImplCppOrdine._Release: Integer;
begin
dec(m_refCount);
if (m_refCount = 0) then
begin
free;
result := 0;
end
else
result := m_refCount;
end;
{ TImplCppRiga }
constructor TImplCppRiga.Create(const codice, descrizione: AnsiString);
begin
m_cod := codice;
m_des := descrizione;
m_qta := generaQta();
end;
function TImplCppRiga.generaQta: Integer;
begin
result := Random(5);
if result = 0 then
result := 1;
end;
function TImplCppRiga.GetCodice: PWideChar;
var
buff: array [0 .. 32] of WideChar;
begin
StringToWideChar(string(m_cod), buff, sizeof(buff));
result := buff;
end;
function TImplCppRiga.GetDescrizione: PWideChar;
var
buff: array [0 .. 512] of WideChar;
begin
StringToWideChar(string(m_des), buff, sizeof(buff));
result := buff;
end;
function TImplCppRiga.GetQta: Integer;
begin
result := m_qta;
end;
function TImplCppRiga.QueryInterface(const IID: TGUID; out Obj): HRESULT;
begin
Pointer(Obj) := self;
result := S_OK;
end;
function TImplCppRiga._AddRef: Integer;
begin
inc(m_refCount);
result := m_refCount;
end;
function TImplCppRiga._Release: Integer;
begin
dec(m_refCount);
if (m_refCount = 0) then
begin
free;
result := 0;
end
else
result := m_refCount;
end;
end.
|
unit AM.Gestion.PhotoMobileVCL;
///
/// /// version de test
/// ////
///
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, IPPeerClient, IPPeerServer,
Vcl.StdCtrls, Vcl.ExtCtrls, System.Tether.Manager,
System.Tether.AppProfile, System.JSON,
Vcl.ExtDlgs, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, Data.DB, FireDAC.Stan.StorageXML,
FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.Bind.Grid, System.Rtti, System.Bindings.Outputs, Vcl.Bind.Editors, Data.Bind.EngExt, Vcl.Bind.DBEngExt, Data.Bind.Controls, Vcl.Buttons,
Vcl.Bind.Navigator, Data.Bind.Components, Data.Bind.Grid, Vcl.Grids, Data.Bind.DBScope, Vcl.DBGrids;
type
TfrmPhoto = class(TForm)
MediaReceiverManager: TTetheringManager;
MediaReceiverProfile: TTetheringAppProfile;
Button1: TButton;
Image1: TImage;
Button2: TButton;
Label1: TLabel;
Memo1: TMemo;
logMemo: TMemo;
Button3: TButton;
FDMemTblClients: TFDMemTable;
FDStanStorageXMLLink1: TFDStanStorageXMLLink;
FDMemTblClientsNom: TStringField;
FDMemTblClientsAdresse: TStringField;
FDMemTblClientsVille: TStringField;
FDMemTblClientsLongitude: TFloatField;
FDMemTblClientsLatitude: TFloatField;
FDMemTblClientsTelephone: TStringField;
FDMemTblClientsDescription: TStringField;
BindSourceDB1: TBindSourceDB;
BindingsList1: TBindingsList;
BindNavigator1: TBindNavigator;
DBGrid1: TDBGrid;
DataSource1: TDataSource;
TetheringAppProfile1: TTetheringAppProfile;
CheckBox1: TCheckBox;
procedure MediaReceiverManagerRequestManagerPassword(const Sender: TObject; const ARemoteIdentifier: string; var Password: string);
procedure MediaReceiverProfileResourceReceived(const Sender: TObject; const AResource: TRemoteResource);
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure MediaReceiverManagerEndAutoConnect(Sender: TObject);
procedure MediaReceiverManagerPairedFromLocal(const Sender: TObject; const [Ref] AManagerInfo: TTetheringManagerInfo);
procedure MediaReceiverManagerPairedToRemote(const Sender: TObject; const [Ref] AManagerInfo: TTetheringManagerInfo);
procedure MediaReceiverManagerRemoteManagerShutdown(const Sender: TObject; const AManagerIdentifier: string);
procedure Button3Click(Sender: TObject);
procedure FDMemTblClientsAfterPost(DataSet: TDataSet);
private
{ Private declarations }
Fstm: TSTream;
FLicense: String;
procedure UpdateProjetsObjects;
public
{ Public declarations }
end;
var
frmPhoto: TfrmPhoto;
implementation
{$R *.dfm}
uses
Vcl.imaging.jpeg, IdCoder, IdCoderMIME, REST.JSON, MsgObjU, System.NetEncoding, UtilsU,
ClientsU
;
resourcestring
StrAtelierMathieuPassword = 'AtelierMathieu';
procedure TfrmPhoto.Button1Click(Sender: TObject);
//var
// ms: TMemoryStream;
begin
Fstm.Size := 0;
Image1.Picture.graphic.SaveToStream(Fstm);
Fstm.Position := 0;
modalResult := mrOk;
// ms := TMemoryStream.Create;
// image1.Picture.Graphic.SaveToStream(ms);
//
// ms.SaveToFile('P:\img.jpg');
// ms.Free;
end;
procedure TfrmPhoto.Button3Click(Sender: TObject);
begin
UpdateProjetsObjects;
// sl := TStringList.Create;
// ListBox1.Clear;
// i := System.SysUtils.FindFirst('C:\DataGL\Projets\AM\PhotosMobile\Run\Dossiers\*', faDirectory, sf);
// while i = 0 do
// begin
// if ((sf.Attr and faDirectory) = faDirectory) and not sametext(sf.Name, '.') and not sametext(sf.Name, '..') then
// begin
// sl.Add(sf.Name);
// ListBox1.Items.Add(sf.Name) ;
// end;
//
// i := System.SysUtils.FindNext(sf);
// end;
// System.SysUtils.findclose(sf);
//
//
// for I := 0 to MediaReceiverProfile.Resources.Count -1 do
// begin
// if sametext(MediaReceiverProfile.Resources.Items[i].Name, 'ProjectList') then
// begin
// MediaReceiverProfile.Resources.Delete(i);
// res := MediaReceiverProfile.Resources.Add;
// res.ResType := TRemoteResourceType.Data;
// res.Name := 'ProjectList';
// sl.Delimiter := #9;
//
// res.Value.Create(sl.DelimitedText );
// break;
// end;
// end;
//
// sl.Free;
//
end;
procedure TfrmPhoto.FDMemTblClientsAfterPost(DataSet: TDataSet);
begin
FDMemTblClients.SaveToFile('..\..\..\..\data\Clients.xml');
UpdateProjetsObjects;
end;
procedure TfrmPhoto.FormCreate(Sender: TObject);
const
LICENSE_KEYS: Array [0 .. 2] of String = ('{F13D701D-00F8-47CB-904B-09386A98E08F}', '{945221F4-1F3F-49DD-A9AC-CA9118995F14}', '{72BBAAA5-07B8-4ABE-9BCF-2006A4543503}');
var
res : TLocalResource;
begin
Randomize; // Otherwise we'll get the same number generated every time
// Select a random License String from our Array of License Keys
FLicense := LICENSE_KEYS[Random(2)];
//
// Log what License has been chosen
logMemo.Lines.Add(Format('Local License: %s', [FLicense]));
// Update our shared Resource in the Tethering Profile with the License key
MediaReceiverProfile.Resources.FindByName('License').Value := FLicense;
// Log the unique LOCAL identifier so we can distinguish between instances
// Essentially, this is a unique GUID generated when our application is executed
logMemo.Lines.Add('Local Identifier: ' + MediaReceiverManager.Identifier);
// Now let's look for Remote Mangers with which to pair...
logMemo.Lines.Add('Scanning for Remote Managers with which to pair...');
MediaReceiverManager.DiscoverManagers;
res := MediaReceiverProfile.Resources.Add;
res.ResType := TRemoteResourceType.Data;
res.Name := 'ProjectList';
// res.Value.Create();
// Assert(res.Value.DataType = TResourceType.String, '');
try
FDMemTblClients.LoadFromFile('..\..\..\..\data\Clients.xml');
except
FDMemTblClients.CreateDataSet;
end;
end;
procedure TfrmPhoto.MediaReceiverManagerEndAutoConnect(Sender: TObject);
begin
logMemo.Lines.Add(Format('AutoConnect Complete, Found %d Remote Managers', [MediaReceiverManager.RemoteManagers.Count]));
end;
procedure TfrmPhoto.MediaReceiverManagerPairedFromLocal(const Sender: TObject; const [Ref] AManagerInfo: TTetheringManagerInfo);
begin
// Log that we've paired to a Remote Manager and provide details
logMemo.Lines.Add(Format('A Remote Manager %s has paired with us' + #13#10 + #9 + 'Manager Name: %s' + #13#10 + #9 + 'Manager Text: %s' + #13#10 + #9 + 'Connection String: %s',
[AManagerInfo.ManagerIdentifier, AManagerInfo.ManagerName, AManagerInfo.ManagerText, AManagerInfo.ConnectionString]));
end;
procedure TfrmPhoto.MediaReceiverManagerPairedToRemote(const Sender: TObject; const [Ref] AManagerInfo: TTetheringManagerInfo);
begin
// Log that we've paired to a Remote Manager and provide details
logMemo.Lines.Add(Format('We have paired with a Remote Manager %s' + #13#10 + #9 + 'Manager Name: %s' + #13#10 + #9 + 'Manager Text: %s' + #13#10 + #9 + 'Connection String: %s',
[AManagerInfo.ManagerIdentifier, AManagerInfo.ManagerName, AManagerInfo.ManagerText, AManagerInfo.ConnectionString]));
end;
procedure TfrmPhoto.MediaReceiverManagerRemoteManagerShutdown(const Sender: TObject; const AManagerIdentifier: string);
begin
logMemo.Lines.Add('Connectioin lost :' + AManagerIdentifier);
end;
procedure TfrmPhoto.MediaReceiverManagerRequestManagerPassword(const Sender: TObject; const ARemoteIdentifier: string; var Password: string);
begin
Password := StrAtelierMathieuPassword;
end;
procedure BitmapFromBase64(Base64: string; Bitmap: Vcl.Graphics.TBitmap);
var
Stream: TBytesStream;
Bytes: TBytes;
Encoding: TBase64Encoding;
img: TWICImage;
begin
Stream := TBytesStream.Create;
try
Encoding := TBase64Encoding.Create(0);
try
Bytes := Encoding.DecodeStringToBytes(Base64);
Stream.WriteData(Bytes, Length(Bytes));
Stream.Position := 0;
img := TWICImage.Create;
img.LoadFromStream(Stream);
// img.ImageFormat := TWICImageFormat.wifJpeg;
img.ImageFormat := TWICImageFormat.wifBmp;
Bitmap.Assign(img);
// Image1.Picture.Assign(img);
img.Free;
// Bitmap.LoadFromStream(Stream);
finally
Encoding.Free;
end;
finally
Stream.Free;
end;
end;
procedure TfrmPhoto.MediaReceiverProfileResourceReceived(const Sender: TObject; const AResource: TRemoteResource);
var
// img: TWICImage;
JsonObject: TJSONObject;
sstream: TStringStream;
// sl: tstringlist;
// comp: Tcomponent;
msg: TMsgObj;
jsonMD5: TJSONValue;
jsonLeData: TJSONObject;
begin
sstream := TStringStream.Create();
sstream.LoadFromStream(AResource.Value.AsStream);
// JsonObject := TJSONObject.Create;
// JsonObject := TJSONObject.ParseJSONValue( TEncoding.ASCII.GetBytes(sstream.DataString), 0) as TJSONObject;
JsonObject := TJSONObject.ParseJSONValue(sstream.Bytes, 0, sstream.Size) as TJSONObject;
jsonMD5 := JsonObject.Get('MD5').JsonValue;
jsonLeData := JsonObject.Get('dataObjet').JsonValue as TJSONObject;
if jsonMD5.Value = CalcMd5(jsonLeData.ToString) then
begin
msg := TJSON.JsonToObject<TMsgObj>(jsonLeData);
// msg:= TJSON.JsonToObject<TMsgObj>(sstream.DataString);
BitmapFromBase64(msg.ImgstR, Image1.Picture.Bitmap);
Memo1.Text := msg.note;
Label1.Caption := Format('%d x %d', [Image1.Picture.Width, Image1.Picture.Height]);
end;
end;
procedure TfrmPhoto.UpdateProjetsObjects;
var
clone: TFDMemTable;
unClient: TClient;
SL : TStringList;
begin
logMemo.Lines.Add('Updating Projets Objects Data');
clone := TFDMemTable.Create(Self);
try
clone.CloneCursor(FDMemTblClients);
clone.First;
SL := TStringList.Create;
try
while not Clone.Eof do
begin
unClient := TClient.Create(clone.FieldByName('Nom').AsString);
try
unClient.Adresse := clone.FieldByName('Adresse').AsString;
unClient.Ville := clone.FieldByName('Ville').AsString;
unClient.Long := clone.FieldByName('Longitude').AsFloat;
unClient.Lati := clone.FieldByName('Latitude').AsFloat;
unClient.Telephone := clone.FieldByName('Telephone').AsString;
unClient.Description := clone.FieldByName('Description').AsString;
SL.Add(TJson.ObjectToJsonString(unClient));
finally
unClient.Free;
end;
Clone.Next;
end;
SL.Delimiter := Data_Delimiter;
MediaReceiverProfile.Resources.FindByName('ProjectList').Value := SL.DelimitedText;
logMemo.Lines.Add(SL.DelimitedText);
finally
SL.Free;
end;
finally
clone.Free;
end;
end;
end.
|
{$F-,A+,O+,G+,R-,S+,I+,Q-,V-,B-,X+,T-,P-,D-,L-,N-,E+}
unit Config10;
interface
procedure cfgArchiverEditor;
implementation
uses Dos,
Global, Strings, Config, Output, Input, Files, Misc, bbsInit, Archive,
Logs;
procedure cfgArchiverEditor;
var curArch, Z : Byte; Arch : tArchiverRec; B : Boolean; X : Byte;
optView : array[1..2] of String;
begin
curArch := 1;
optView[1] := 'None';
optView[2] := 'ZIP';
logWrite('*Archive edit.');
archLoadArch(Arch,curArch);
cfgOver := False;
cfgDraw := True;
repeat
cfgInit(bbsTitle+' Archiver Editor');
cfgCol := 25;
cfgItem('--Current archiver #',2,St(curArch),'');
cfgItem('A Active archiver',3,b2st(Arch.Active),
'Is this archiver currently active or disabled?');
cfgItem('B File extension',3,Arch.Extension,
'3 character file extension that signifies use of this archiver');
cfgItem('C Archive signature',20,Arch.fileSig,
'First bytes of archive file (for ID). Use ^xxx for weird chars (xxx = Ascii)');
cfgItem('D Compress command',40,Arch.cmdZip,
'Archive command to compress/add file(s) to an archive');
cfgItem('E Decompress command',40,Arch.cmdUnzip,
'Archive command to decompress an archive to a specific directory');
cfgItem('F Test command',40,Arch.cmdTest,
'Archive command to perform an integrity check on the archive file');
cfgItem('G Comment command',40,Arch.cmdComment,
'Archive command to add file comments to the archive, if possible');
cfgItem('H Delete command',40,Arch.cmdDelete,
'Archive command to delete file(s) from the archive');
cfgItem('I List character',1,Arch.listChar,
'Character used to specify a batch list of files for an operation');
cfgItem('J Internal viewer',5,cfgOption(optView,Arch.Viewer),
'Internal archiver viewer');
cfgItem('K Success errorlevel',3,St(Arch.okErrLevel),
'Errorlevel that indicates that archive command was successful');
cfgItem('L Check errorlevel',3,B2St(Arch.CheckEL),
'Check the errorlevel for success code, or ignore it?');
cfgItem('[ Previous archiver',0,'','');
cfgItem('] Next archiver',0,'','');
cfgBar;
cfgDrawAllItems;
cfgPromptCommand;
case cfgKey of
'A' : begin
cfgReadBoolean(Arch.Active);
cfgSetItem(B2St(Arch.Active));
end;
'B' : begin
cfgReadInfo(Arch.Extension,inUpper,chFilename,'',False);
Arch.Extension := cfgRead;
cfgSetItem(Arch.Extension);
end;
'C' : begin
cfgReadInfo(Arch.fileSig,inNormal,chNormal,'',False);
if cfgRead = '' then Arch.fileSig := '' else
if mArchSig(cfgRead) <> '' then Arch.fileSig := cfgRead;
cfgSetItem(Arch.fileSig);
end;
'D' : begin
cfgReadInfo(Arch.cmdZip,inNormal,chNormal,'',False);
Arch.cmdZip := cfgRead;
cfgSetItem(Arch.cmdZip);
end;
'E' : begin
cfgReadInfo(Arch.cmdUnzip,inNormal,chNormal,'',False);
Arch.cmdUnzip := cfgRead;
cfgSetItem(Arch.cmdUnzip);
end;
'F' : begin
cfgReadInfo(Arch.cmdTest,inNormal,chNormal,'',False);
Arch.cmdTest := cfgRead;
cfgSetItem(Arch.cmdTest);
end;
'G' : begin
cfgReadInfo(Arch.cmdComment,inNormal,chNormal,'',False);
Arch.cmdComment := cfgRead;
cfgSetItem(Arch.cmdComment);
end;
'H' : begin
cfgReadInfo(Arch.cmdDelete,inNormal,chNormal,'',False);
Arch.cmdDelete := cfgRead;
cfgSetItem(Arch.cmdDelete);
end;
'I' : begin
cfgReadInfo(Arch.listChar,inNormal,chNormal,'',False);
Arch.listChar := cfgRead[1];
cfgSetItem(Arch.listChar);
end;
'J' : begin
cfgReadOption(optView,2,Arch.Viewer);
cfgSetItem(cfgOption(optView,Arch.Viewer));
end;
'K' : begin
cfgReadInfo(St(Arch.okErrLevel),inUpper,chNumeric,'',False);
Arch.okErrLevel := mClip(StrToInt(cfgRead),0,255);
cfgSetItem(St(Arch.okErrLevel));
end;
{ Viewer }
'L' : begin
cfgReadBoolean(Arch.CheckEL);
cfgSetItem(B2St(Arch.CheckEL));
end;
'[' : begin
archSaveArch(Arch,curArch);
Dec(curArch,1);
if curArch < 1 then curArch := maxArchiver;
archLoadArch(Arch,curArch);
cfgDraw := True;
cfgOver := True;
end;
']' : begin
archSaveArch(Arch,curArch);
Inc(curArch,1);
if curArch > maxArchiver then curArch := 1;
archLoadArch(Arch,curArch);
cfgDraw := True;
cfgOver := True;
end;
end;
until (HangUp) or (cfgDone);
archSaveArch(Arch,curArch);
cfgDone := False;
end;
end. |
{####################################################################################################################
TINJECT - Componente de comunicação (Não Oficial)
www.tinject.com.br
Novembro de 2019
####################################################################################################################
Owner.....: Daniel Oliveira Rodrigues - Dor_poa@hotmail.com - +55 51 9.9155-9228
Developer.: Joathan Theiller - jtheiller@hotmail.com -
Mike W. Lustosa - mikelustosa@gmail.com - +55 81 9.9630-2385
Robson André de Morais - robinhodemorais@gmail.com
####################################################################################################################
Obs:
- Código aberto a comunidade Delphi, desde que mantenha os dados dos autores e mantendo sempre o nome do IDEALIZADOR
Mike W. Lustosa;
- Colocar na evolução as Modificação juntamente com as informaçoes do colaborador: Data, Nova Versao, Autor;
- Mantenha sempre a versao mais atual acima das demais;
- Todo Commit ao repositório deverá ser declarado as mudança na UNIT e ainda o Incremento da Versão de
compilação (último digito);
####################################################################################################################
Evolução do Código
####################################################################################################################
Autor........:
Email........:
Data.........:
Identificador:
Modificação..:
####################################################################################################################
}
unit uTInject.AdjustNumber;
interface
uses
System.Classes, uTInject.Classes, System.MaskUtils, uTInject.Diversos;
{$M+}{$TYPEINFO ON}
type
TInjectAdjusteNumber = class(TPersistent)
private
FLastAdjustDt: TDateTime;
FLastAdjuste: String;
FLastDDI: String;
FLastDDD: String;
FLastNumber: String;
FAutoAdjust: Boolean;
FDDIDefault: Integer;
FLengthDDI: integer;
FLengthDDD: Integer;
FLengthPhone: Integer;
FLastNumberFormat: String;
FLastType: TTypeNumber;
FAllowOneDigit: Boolean;
Owner: TComponent;
Procedure SetPhone(Const Pnumero:String);
public
constructor Create(AOwner: TComponent);
Function FormatIn(PNum:String): String;
Function FormatOut(PNum:String): String;
property LastType : TTypeNumber Read FLastType;
property LastAdjuste : String Read FLastAdjuste;
property LastDDI : String Read FLastDDI;
property LastDDD : String Read FLastDDD;
property LastNumber : String Read FLastNumber;
property LastNumberFormat: String Read FLastNumberFormat;
property LastAdjustDt: TDateTime Read FLastAdjustDt;
published
property AutoAdjust : Boolean read FAutoAdjust write FAutoAdjust default True;
property LengthDDI : Integer read FLengthDDI write FLengthDDI default 2;
property LengthDDD : Integer read FLengthDDD write FLengthDDD default 2;
property LengthPhone: Integer read FLengthPhone write FLengthPhone default 9;
property AllowOneDigitMore: Boolean read FAllowOneDigit write FAllowOneDigit default True;
property DDIDefault : Integer read FDDIDefault write FDDIDefault Default 2;
end;
implementation
uses
System.SysUtils, uTInject.Constant;
{ TAdjustNumber }
function TInjectAdjusteNumber.FormatIn(PNum: String): String;
var
LClearNum: String;
LInc:Integer;
begin
if FAllowOneDigit then
LInc := 1 else
LInc := 0;
Result := Pnum;
try
if not AutoAdjust then
Exit;
//Garante valores LIMPOS (sem mascaras, letras, etc) apenas NUMEROS
Result := PNum;
LClearNum := TrazApenasNumeros(pnum);
if Length(LClearNum) < (LengthDDD + LengthPhone + LInc) then
Begin
if Length(LClearNum) < (LengthDDD + LengthPhone) then
Begin
Result := '';
Exit;
End;
End;
//Testa se é um grupo ou Lista Transmissao
if Length(LClearNum) <= (LengthDDI + LengthDDD + LengthPhone + 1 + LInc) Then //14 then
begin
if (Length(LClearNum) <= (LengthDDD + LengthPhone+ LInc)) or (Length(PNum) <= (LengthDDD + LengthPhone+ LInc)) then
begin
if Copy(LClearNum, 0, LengthDDI) <> DDIDefault.ToString then
LClearNum := DDIDefault.ToString + LClearNum;
Result := LClearNum + CardContact;
end;
end;
finally
if Result = '' then
raise Exception.Create(MSG_ExceptPhoneNumberError);
SetPhone(Result);
end;
end;
function TInjectAdjusteNumber.FormatOut(PNum: String): String;
var
LDDi, LDDD, Lresto, LMask : String;
begin
LDDi := Copy(PNum, 0, FLengthDDI);
LDDD := Copy(PNum, FLengthDDI + 1, FLengthDDD);
Lresto := Copy(PNum, FLengthDDI + FLengthDDD + 1); // + 1, LengthPhone);
if Length(Lresto) <= 8 then
LMask := '0000\-0000;0;' else
LMask := '0\.0000\-0000;0;';
Result := '+' + LDDi + ' (' + LDDD + ') ' + FormatMaskText(LMask, Lresto );
end;
procedure TInjectAdjusteNumber.SetPhone(const Pnumero: String);
begin
FLastType := TypUndefined;
FLastDDI := '';
FLastDDD := '';
FLastNumber := '';
FLastNumberFormat := '';
FLastAdjustDt := Now;
FLastAdjuste := Pnumero;
FLastNumberFormat := Pnumero;
if pos(CardGroup, Pnumero) > 0 then
begin
FLastType := TypGroup;
end else
Begin
if Length(Pnumero) = (LengthDDI + LengthDDD + LengthPhone + Length(CardContact)) then
Begin
FLastType := TypContact;
end;
end;
if FLastType = TypContact then
Begin
FLastDDI := Copy(Pnumero, 0, LengthDDI);
FLastDDD := Copy(Pnumero, LengthDDI+1, LengthDDD);
FLastNumber := Copy(Pnumero, LengthDDI+LengthDDD+1, LengthPhone);
FLastNumberFormat := FormatOut(FLastNumber);
End;
end;
constructor TInjectAdjusteNumber.Create(AOwner: TComponent);
begin
Owner := Aowner;
FLastAdjuste := '';
FLastDDI := '';
FLastDDD := '';
FLastNumber := '';
FAllowOneDigit := true;
FAutoAdjust := True;
FDDIDefault := 55;
FLengthDDI := 2;
FLengthDDD := 2;
FLengthPhone := 8;
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{ : GLSceneForm<p>
<b>History : </b><font size=-1><ul>
<li>05/04/11 - Yar - Added property FullScreenVideoMode (thanks to ltyrosine)
<li>08/12/10 - Yar - Added code for Lazarus (thanks Rustam Asmandiarov aka Predator)
<li>23/08/10 - Yar - Creation
</ul></font>
}
unit GLSceneForm;
interface
{$I GLScene.inc}
uses
Winapi.Windows,
Winapi.Messages,
System.Classes,
VCL.Controls,
VCL.Forms,
GLScene,
GLContext,
GLCrossPlatform,
GLScreen,
GLViewer;
const
lcl_major = 0;
lcl_minor = 0;
lcl_release = 0;
type
TGLSceneForm = class;
// TGLFullScreenResolution
//
{: Defines how GLSceneForm will handle fullscreen request
fcWindowMaximize: Use current resolution (just maximize form and hide OS bars)
fcNearestResolution: Change to nearest valid resolution from current window size
fcManualResolution: Use FFullScreenVideoMode settings }
TGLFullScreenResolution = (
fcUseCurrent,
fcNearestResolution,
fcManualResolution);
// TGLFullScreenVideoMode
//
{: Screen mode settings }
TGLFullScreenVideoMode = class(TPersistent)
private
FOwner: TGLSceneForm;
FEnabled: Boolean;
FAltTabSupportEnable: Boolean;
FWidth: Integer;
FHeight: Integer;
FColorDepth: Integer;
FFrequency: Integer;
FResolutionMode: TGLFullScreenResolution;
procedure SetEnabled(aValue: Boolean);
procedure SetAltTabSupportEnable(aValue: Boolean);
public
constructor Create(AOwner: TGLSceneForm);
published
property Enabled: Boolean read FEnabled write SetEnabled default False;
property AltTabSupportEnable: Boolean read FAltTabSupportEnable
write SetAltTabSupportEnable default False;
property ResolutionMode: TGLFullScreenResolution read FResolutionMode
write FResolutionMode default fcUseCurrent;
property Width: Integer read FWidth write FWidth;
property Height: Integer read FHeight write FHeight;
property ColorDepth: Integer read FColorDepth write FColorDepth;
property Frequency: Integer read FFrequency write FFrequency;
end;
{ TGLSceneForm }
TGLSceneForm = class(TForm)
private
{ Private Declarations }
FBuffer: TGLSceneBuffer;
FVSync: TVSyncMode;
FOwnDC: HDC;
FFullScreenVideoMode: TGLFullScreenVideoMode;
procedure SetBeforeRender(const val: TNotifyEvent);
function GetBeforeRender: TNotifyEvent;
procedure SetPostRender(const val: TNotifyEvent);
function GetPostRender: TNotifyEvent;
procedure SetAfterRender(const val: TNotifyEvent);
function GetAfterRender: TNotifyEvent;
procedure SetCamera(const val: TGLCamera);
function GetCamera: TGLCamera;
procedure SetBuffer(const val: TGLSceneBuffer);
function GetFieldOfView: single;
procedure SetFieldOfView(const Value: single);
function GetIsRenderingContextAvailable: Boolean;
procedure WMEraseBkgnd(var Message: TWMEraseBkgnd); message WM_ERASEBKGND;
procedure WMPaint(var Message: TWMPaint); message WM_PAINT;
procedure WMSize(var Message: TWMSize); message WM_SIZE;
procedure WMDestroy(var Message: TWMDestroy); message WM_DESTROY;
procedure LastFocus(var Mess: TMessage); message WM_ACTIVATE;
procedure SetFullScreenVideoMode(AValue: TGLFullScreenVideoMode);
procedure StartupFS;
procedure ShutdownFS;
protected
{ Protected Declarations }
procedure Notification(AComponent: TComponent; Operation: TOperation);
override;
procedure CreateWnd; override;
procedure Loaded; override;
procedure DoBeforeRender(Sender: TObject); dynamic;
procedure DoBufferChange(Sender: TObject); virtual;
procedure DoBufferStructuralChange(Sender: TObject); dynamic;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure DestroyWnd; override;
property IsRenderingContextAvailable: Boolean read
GetIsRenderingContextAvailable;
property RenderDC: HDC read FOwnDC;
published
{ Published Declarations }
{ : Camera from which the scene is rendered. }
property Camera: TGLCamera read GetCamera write SetCamera;
{ : Specifies if the refresh should be synchronized with the VSync signal.<p>
If the underlying OpenGL ICD does not support the WGL_EXT_swap_control
extension, this property is ignored. }
property VSync: TVSyncMode read FVSync write FVSync default vsmNoSync;
{ : Triggered before the scene's objects get rendered.<p>
You may use this event to execute your own OpenGL rendering. }
property BeforeRender: TNotifyEvent read GetBeforeRender write
SetBeforeRender;
{ : Triggered just after all the scene's objects have been rendered.<p>
The OpenGL context is still active in this event, and you may use it
to execute your own OpenGL rendering.<p> }
property PostRender: TNotifyEvent read GetPostRender write SetPostRender;
{ : Called after rendering.<p>
You cannot issue OpenGL calls in this event, if you want to do your own
OpenGL stuff, use the PostRender event. }
property AfterRender: TNotifyEvent read GetAfterRender write SetAfterRender;
{ : Access to buffer properties. }
property Buffer: TGLSceneBuffer read FBuffer write SetBuffer;
{ : Returns or sets the field of view for the viewer, in degrees.<p>
This value depends on the camera and the width and height of the scene.
The value isn't persisted, if the width/height or camera.focallength is
changed, FieldOfView is changed also. }
property FieldOfView: single read GetFieldOfView write SetFieldOfView;
property FullScreenVideoMode: TGLFullScreenVideoMode read
FFullScreenVideoMode
write SetFullScreenVideoMode;
end;
implementation
constructor TGLSceneForm.Create(AOwner: TComponent);
begin
FBuffer := TGLSceneBuffer.Create(Self);
FVSync := vsmNoSync;
FBuffer.ViewerBeforeRender := DoBeforeRender;
FBuffer.OnChange := DoBufferChange;
FBuffer.OnStructuralChange := DoBufferStructuralChange;
FFullScreenVideoMode := TGLFullScreenVideoMode.Create(Self);
inherited Create(AOwner);
end;
destructor TGLSceneForm.Destroy;
begin
FBuffer.Free;
FBuffer := nil;
FFullScreenVideoMode.Destroy;
inherited Destroy;
end;
// Notification
//
procedure TGLSceneForm.Notification(AComponent: TComponent; Operation:
TOperation);
begin
if (Operation = opRemove) and (FBuffer <> nil) then
begin
if (AComponent = FBuffer.Camera) then
FBuffer.Camera := nil;
end;
inherited;
end;
// CreateWnd
//
procedure TGLSceneForm.CreateWnd;
begin
inherited CreateWnd;
// initialize and activate the OpenGL rendering context
// need to do this only once per window creation as we have a private DC
FBuffer.Resize(0, 0, Self.Width, Self.Height);
FOwnDC := GetDC(Handle);
FBuffer.CreateRC(FOwnDC, false);
end;
// DestroyWnd
//
procedure TGLSceneForm.DestroyWnd;
begin
if Assigned(FBuffer) then
begin
FBuffer.DestroyRC;
if FOwnDC <> 0 then
begin
ReleaseDC(Handle, FOwnDC);
FOwnDC := 0;
end;
end;
inherited;
end;
// Loaded
//
procedure TGLSceneForm.Loaded;
begin
inherited Loaded;
// initiate window creation
HandleNeeded;
if not (csDesigning in ComponentState) then
begin
if FFullScreenVideoMode.FEnabled then
StartupFS;
end;
end;
// WMEraseBkgnd
//
procedure TGLSceneForm.WMEraseBkgnd(var Message: TWMEraseBkgnd);
begin
if GetIsRenderingContextAvailable then
Message.Result := 1
else
inherited;
end;
// WMSize
//
procedure TGLSceneForm.WMSize(var Message: TWMSize);
begin
inherited;
if Assigned(FBuffer) then
FBuffer.Resize(0, 0, Message.Width, Message.Height);
end;
// WMPaint
//
procedure TGLSceneForm.WMPaint(var Message: TWMPaint);
var
PS: TPaintStruct;
begin
BeginPaint(Handle, PS);
try
if GetIsRenderingContextAvailable and (Width > 0) and (Height > 0) then
FBuffer.Render;
finally
EndPaint(Handle, PS);
Message.Result := 0;
end;
end;
// WMDestroy
//
procedure TGLSceneForm.WMDestroy(var Message: TWMDestroy);
begin
if Assigned(FBuffer) then
begin
FBuffer.DestroyRC;
if FOwnDC <> 0 then
begin
ReleaseDC(Handle, FOwnDC);
FOwnDC := 0;
end;
end;
inherited;
end;
// LastFocus
//
procedure TGLSceneForm.LastFocus(var Mess: TMessage);
begin
if not (csDesigning in ComponentState)
and FFullScreenVideoMode.FEnabled
and FFullScreenVideoMode.FAltTabSupportEnable then
begin
if Mess.wParam = WA_INACTIVE then
begin
ShutdownFS;
end
else
begin
StartupFS;
end;
end;
inherited;
end;
procedure TGLFullScreenVideoMode.SetEnabled(aValue: Boolean);
begin
if FEnabled <> aValue then
begin
FEnabled := aValue;
if not ((csDesigning in FOwner.ComponentState)
or (csLoading in FOwner.ComponentState)) then
begin
if FEnabled then
FOwner.StartupFS
else
FOwner.ShutdownFS;
end;
end;
end;
constructor TGLFullScreenVideoMode.Create(AOwner: TGLSceneForm);
begin
inherited Create;
FOwner := AOwner;
FEnabled := False;
FAltTabSupportEnable := False;
ReadVideoModes;
{$IFDEF MSWINDOWS}
FWidth := vVideoModes[0].Width;
FHeight := vVideoModes[0].Height;
FColorDepth := vVideoModes[0].ColorDepth;
FFrequency := vVideoModes[0].MaxFrequency;
{$ENDIF}
{$IFDEF GLS_X11_SUPPORT}
FWidth := vVideoModes[0].vdisplay;
FHeight := vVideoModes[0].hdisplay;
FColorDepth := 32;
FFrequency := 0;
{$ENDIF}
{$IFDEF DARWIN}
FWidth := 1280;
FHeight := 1024;
FColorDepth := 32;
FFrequency := 0;
{$Message Hint 'Fullscreen mode not yet implemented for Darwin OSes' }
{$ENDIF}
if FFrequency = 0 then
FFrequency := 50;
FResolutionMode := fcUseCurrent;
end;
procedure TGLFullScreenVideoMode.SetAltTabSupportEnable(aValue: Boolean);
begin
if FAltTabSupportEnable <> aValue then
FAltTabSupportEnable := aValue;
end;
procedure TGLSceneForm.StartupFS;
begin
case FFullScreenVideoMode.FResolutionMode of
fcNearestResolution:
begin
SetFullscreenMode(GetIndexFromResolution(ClientWidth, ClientHeight,
{$IFDEF MSWINDOWS}
vVideoModes[0].ColorDepth));
{$ELSE}
32));
{$ENDIF}
end;
fcManualResolution:
begin
SetFullscreenMode(GetIndexFromResolution(FFullScreenVideoMode.Width , FFullScreenVideoMode.Height, FFullScreenVideoMode.ColorDepth), FFullScreenVideoMode.Frequency);
end;
end;
Left := 0;
Top := 0;
BorderStyle := bsNone;
FormStyle := fsStayOnTop;
BringToFront;
WindowState := wsMaximized;
Application.MainFormOnTaskBar := True;
end;
procedure TGLSceneForm.ShutdownFS;
begin
RestoreDefaultMode;
SendToBack;
WindowState := wsNormal;
BorderStyle := bsSingle;
FormStyle := fsNormal;
Left := (Screen.Width div 2) - (Width div 2);
Top := (Screen.Height div 2) - (Height div 2);
end;
// DoBeforeRender
//
procedure TGLSceneForm.DoBeforeRender(Sender: TObject);
begin
SetupVSync(VSync);
end;
// DoBufferChange
//
procedure TGLSceneForm.DoBufferChange(Sender: TObject);
begin
if (not Buffer.Rendering) and (not Buffer.Freezed) then
Invalidate;
end;
// DoBufferStructuralChange
//
procedure TGLSceneForm.DoBufferStructuralChange(Sender: TObject);
begin
RecreateWnd;
end;
procedure TGLSceneForm.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
inherited;
if csDesignInteractive in ControlStyle then
FBuffer.NotifyMouseMove(Shift, X, Y);
end;
// SetBeforeRender
//
procedure TGLSceneForm.SetBeforeRender(const val: TNotifyEvent);
begin
FBuffer.BeforeRender := val;
end;
// GetBeforeRender
//
function TGLSceneForm.GetBeforeRender: TNotifyEvent;
begin
Result := FBuffer.BeforeRender;
end;
// SetPostRender
//
procedure TGLSceneForm.SetPostRender(const val: TNotifyEvent);
begin
FBuffer.PostRender := val;
end;
// GetPostRender
//
function TGLSceneForm.GetPostRender: TNotifyEvent;
begin
Result := FBuffer.PostRender;
end;
// SetAfterRender
//
procedure TGLSceneForm.SetAfterRender(const val: TNotifyEvent);
begin
FBuffer.AfterRender := val;
end;
// GetAfterRender
//
function TGLSceneForm.GetAfterRender: TNotifyEvent;
begin
Result := FBuffer.AfterRender;
end;
// SetCamera
//
procedure TGLSceneForm.SetCamera(const val: TGLCamera);
begin
FBuffer.Camera := val;
end;
// GetCamera
//
function TGLSceneForm.GetCamera: TGLCamera;
begin
Result := FBuffer.Camera;
end;
// SetBuffer
//
procedure TGLSceneForm.SetBuffer(const val: TGLSceneBuffer);
begin
FBuffer.Assign(val);
end;
// GetFieldOfView
//
function TGLSceneForm.GetFieldOfView: single;
begin
if not Assigned(Camera) then
Result := 0
else if Width < Height then
Result := Camera.GetFieldOfView(Width)
else
Result := Camera.GetFieldOfView(Height);
end;
// SetFieldOfView
//
procedure TGLSceneForm.SetFieldOfView(const Value: single);
begin
if Assigned(Camera) then
begin
if Width < Height then
Camera.SetFieldOfView(Value, Width)
else
Camera.SetFieldOfView(Value, Height);
end;
end;
procedure TGLSceneForm.SetFullScreenVideoMode(AValue: TGLFullScreenVideoMode);
begin
end;
// GetIsRenderingContextAvailable
//
function TGLSceneForm.GetIsRenderingContextAvailable: Boolean;
begin
Result := FBuffer.RCInstantiated and FBuffer.RenderingContext.IsValid;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
RegisterClass(TGLSceneForm);
end.
|
unit rTIU;
interface
uses SysUtils, Classes, ORNet, ORFn, rCore, uCore, uConst, TRPCB, uTIU, Dialogs, UITypes;
type
TPatchInstalled = record
PatchInstalled: boolean;
PatchChecked: boolean;
end;
{ Progress Note Titles }
function DfltNoteTitle: Integer;
function DfltNoteTitleName: string;
procedure ResetNoteTitles;
function IsConsultTitle(TitleIEN: Integer): Boolean;
function IsPRFTitle(TitleIEN: Integer): Boolean;
function IsClinProcTitle(TitleIEN: Integer): Boolean;
procedure ListNoteTitlesShort(Dest: TStrings);
procedure LoadBoilerPlate(Dest: TStrings; Title: Integer);
function PrintNameForTitle(TitleIEN: Integer): string;
function SubSetOfNoteTitles(aResults: TStrings; const StartFrom: string; Direction: Integer; IDNotesOnly: boolean): Integer;
{ TIU Preferences }
procedure ResetTIUPreferences;
function AskCosignerForNotes: Boolean;
function AskCosignerForDocument(ADocument: Integer; AnAuthor: Int64; ADate: TFMDateTime): Boolean;
function AskCosignerForTitle(ATitle: integer; AnAuthor: Int64; ADate: TFMDateTime): Boolean;
function AskSubjectForNotes: Boolean;
function CanCosign(ATitle, ADocType: integer; AUser: Int64; ADate: TFMDateTime): Boolean;
function CanChangeCosigner(IEN: integer): boolean;
procedure DefaultCosigner(var IEN: Int64; var Name: string);
function ReturnMaxNotes: Integer;
function SortNotesAscending: Boolean;
function GetCurrentTIUContext: TTIUContext;
procedure SaveCurrentTIUContext(AContext: TTIUContext) ;
function TIUSiteParams: string;
function DfltTIULocation: Integer;
function DfltTIULocationName: string;
{ Data Retrieval }
procedure ActOnDocument(var AuthSts: TActionRec; IEN: Integer; const ActionName: string);
function AuthorSignedDocument(IEN: Integer): boolean;
function CosignDocument(IEN: Integer): Boolean;
//function CPTRequiredForNote(IEN: Integer): Boolean;
procedure ListNotes(Dest: TStrings; Context: Integer; Early, Late: TFMDateTime;
Person: int64; OccLim: Integer; SortAscending: Boolean);
procedure ListNotesForTree(Dest: TStrings; Context: Integer; Early, Late: TFMDateTime;
Person: int64; OccLim: Integer; SortAscending: Boolean);
procedure ListConsultRequests(Dest: TStrings);
procedure ListDCSumm(Dest: TStrings);
procedure LoadDetailText(Dest: TStrings; IEN: Integer); //**KCM**
procedure LoadDocumentText(Dest: TStrings; IEN: Integer);
procedure GetNoteForEdit(var EditRec: TEditNoteRec; IEN: Integer);
procedure GetNoteEditTextOnly(ResultList: TStrings; IEN: Integer);
function VisitStrForNote(IEN: Integer): string;
function GetCurrentSigners(IEN: integer): TStrings;
function TitleForNote(IEN: Int64): Integer;
function GetConsultIENforNote(NoteIEN: integer): Integer;
function GetPackageRefForNote(NoteIEN: integer): string;
procedure LockDocument(IEN: Int64; var AnErrMsg: string);
procedure UnlockDocument(IEN: Int64);
function LastSaveClean(IEN: Int64): Boolean;
function NoteHasText(NoteIEN: integer): boolean;
function GetTIUListItem(IEN: Int64): string;
{ Data Storage }
//procedure ClearCPTRequired(IEN: Integer);
procedure DeleteDocument(var DeleteSts: TActionRec; IEN: Integer; const Reason: string);
function AncillaryPackageMessages(IEN: Integer; const Action: string): string;
function JustifyDocumentDelete(IEN: Integer): Boolean;
procedure SignDocument(var SignSts: TActionRec; IEN: Integer; const ESCode: string);
procedure PutNewNote(var CreatedDoc: TCreatedDoc; const NoteRec: TNoteRec);
procedure PutAddendum(var CreatedDoc: TCreatedDoc; const NoteRec: TNoteRec; AddendumTo: Integer);
procedure PutEditedNote(var UpdatedDoc: TCreatedDoc; const NoteRec: TNoteRec; NoteIEN: Integer);
procedure PutTextOnly(var ErrMsg: string; NoteText: TStrings; NoteIEN: Int64);
procedure SetText(var ErrMsg: string; NoteText: TStrings; NoteIEN: Int64; Suppress: Integer);
procedure InitParams(NoteIEN: Int64; Suppress: Integer);
procedure UpdateAdditionalSigners(IEN: integer; Signers: TStrings);
procedure ChangeCosigner(IEN: integer; Cosigner: int64);
{ Printing }
function AllowPrintOfNote(ANote: Integer): string;
function AllowChartPrintForNote(ANote: Integer): Boolean;
procedure PrintNoteToDevice(ANote: Integer; const ADevice: string; ChartCopy: Boolean;
var ErrMsg: string);
function GetFormattedNote(ANote: Integer; ChartCopy: Boolean): TStrings;
// Interdisciplinary Notes
function IDNotesInstalled: boolean;
function CanTitleBeIDChild(Title: integer; var WhyNot: string): boolean;
function CanReceiveAttachment(DocID: string; var WhyNot: string): boolean;
function CanBeAttached(DocID: string; var WhyNot: string): boolean;
function DetachEntryFromParent(DocID: string; var WhyNot: string): boolean;
function AttachEntryToParent(DocID, ParentDocID: string; var WhyNot: string): boolean;
function OneNotePerVisit(NoteEIN: Integer; DFN: String;VisitStr: String): boolean;
//User Classes
function SubSetOfUserClasses(const StartFrom: string; Direction: Integer): TStrings;
function UserDivClassInfo(User: Int64): TStrings;
function UserInactive(EIN: String): boolean;
//Miscellaneous
function TIUPatch175Installed: boolean;
const
CLS_PROGRESS_NOTES = 3;
implementation
uses rMisc;
var
uTIUSiteParams: string;
uTIUSiteParamsLoaded: boolean = FALSE;
uNoteTitles: TNoteTitles;
uTIUPrefs: TTIUPrefs;
uPatch175Installed: TPatchInstalled;
{ Progress Note Titles -------------------------------------------------------------------- }
procedure LoadNoteTitles;
{ private - called one time to set up the uNoteTitles object }
const
CLASS_PROGRESS_NOTES = 3;
var
x: string;
begin
if uNoteTitles <> nil then Exit;
CallV('TIU PERSONAL TITLE LIST', [User.DUZ, CLS_PROGRESS_NOTES]);
RPCBrokerV.Results.Insert(0, '~SHORT LIST'); // insert so can call ExtractItems
uNoteTitles := TNoteTitles.Create;
ExtractItems(uNoteTitles.ShortList, RPCBrokerV.Results, 'SHORT LIST');
x := ExtractDefault(RPCBrokerV.Results, 'SHORT LIST');
uNoteTitles.DfltTitle := StrToIntDef(Piece(x, U, 1), 0);
uNoteTitles.DfltTitleName := Piece(x, U, 2);
end;
procedure ResetNoteTitles;
begin
if uNoteTitles <> nil then
begin
uNoteTitles.Free;
uNoteTitles := nil;
LoadNoteTitles;
end;
end;
function DfltNoteTitle: Integer;
{ returns the IEN of the user defined default progress note title (if any) }
begin
if uNoteTitles = nil then LoadNoteTitles;
Result := uNoteTitles.DfltTitle;
end;
function DfltNoteTitleName: string;
{ returns the name of the user defined default progress note title (if any) }
begin
if uNoteTitles = nil then LoadNoteTitles;
Result := uNoteTitles.DfltTitleName;
end;
function IsConsultTitle(TitleIEN: Integer): Boolean;
begin
Result := False;
if TitleIEN <= 0 then Exit;
Result := sCallV('TIU IS THIS A CONSULT?', [TitleIEN]) = '1';
end;
function IsPRFTitle(TitleIEN: Integer): Boolean;
begin
Result := False;
if TitleIEN <= 0 then Exit;
Result := sCallV('TIU ISPRF', [TitleIEN]) = '1';
end;
function IsClinProcTitle(TitleIEN: Integer): Boolean;
begin
Result := False;
if TitleIEN <= 0 then Exit;
Result := sCallV('TIU IS THIS A CLINPROC?', [TitleIEN]) = '1';
end;
procedure ListNoteTitlesShort(Dest: TStrings);
{ returns the user defined list (short list) of progress note titles }
begin
if uNoteTitles = nil then LoadNoteTitles;
Dest.AddStrings(uNoteTitles.Shortlist);
//FastAddStrings(uNoteTitles.ShortList, Dest); // backed out from v27.27 - CQ #14619 - RV
if uNoteTitles.ShortList.Count > 0 then
begin
Dest.Add('0^________________________________________________________________________');
Dest.Add('0^ ');
end;
end;
procedure LoadBoilerPlate(Dest: TStrings; Title: Integer);
{ returns the boilerplate text (if any) for a given progress note title }
begin
CallV('TIU LOAD BOILERPLATE TEXT', [Title, Patient.DFN, Encounter.VisitStr]);
FastAssign(RPCBrokerV.Results, Dest);
end;
function PrintNameForTitle(TitleIEN: Integer): string;
begin
Result := sCallV('TIU GET PRINT NAME', [TitleIEN]);
end;
function SubSetOfNoteTitles(aResults: TStrings; const StartFrom: string; Direction: Integer; IDNotesOnly: boolean): Integer;
{ returns a pointer to a list of progress note titles (for use in a long list box) -
The return value is a pointer to RPCBrokerV.Results, so the data must be used BEFORE
the next broker call! }
begin
if IDNotesOnly then
CallVistA('TIU LONG LIST OF TITLES', [CLS_PROGRESS_NOTES, StartFrom, Direction, IDNotesOnly], aResults)
else
CallVistA('TIU LONG LIST OF TITLES', [CLS_PROGRESS_NOTES, StartFrom, Direction], aResults);
//MixedCaseList(RPCBrokerV.Results);
Result := aResults.Count;
end;
{ TIU Preferences ------------------------------------------------------------------------- }
procedure LoadTIUPrefs;
{ private - creates TIUPrefs object for reference throughout the session }
var
x: string;
begin
uTIUPrefs := TTIUPrefs.Create;
with uTIUPrefs do
begin
x := sCallV('TIU GET PERSONAL PREFERENCES', [User.DUZ]);
DfltLoc := StrToIntDef(Piece(x, U, 2), 0);
DfltLocName := ExternalName(DfltLoc, FN_HOSPITAL_LOCATION);
SortAscending := Piece(x, U, 4) = 'A';
SortBy := Piece(x, U, 3);
AskNoteSubject := Piece(x, U, 8) = '1';
DfltCosigner := StrToInt64Def(Piece(x, U, 9), 0);
DfltCosignerName := ExternalName(DfltCosigner, FN_NEW_PERSON);
MaxNotes := StrToIntDef(Piece(x, U, 10), 0);
x := sCallV('TIU REQUIRES COSIGNATURE', [TYP_PROGRESS_NOTE, 0, User.DUZ]);
AskCosigner := Piece(x, U, 1) = '1';
end;
end;
procedure ResetTIUPreferences;
begin
if uTIUPrefs <> nil then
begin
uTIUPrefs.Free;
uTIUPrefs := nil;
LoadTIUPrefs;
end;
end;
function AskCosignerForDocument(ADocument: Integer; AnAuthor: Int64; ADate: TFMDateTime): Boolean;
begin
if TIUPatch175Installed then
Result := Piece(sCallV('TIU REQUIRES COSIGNATURE', [0, ADocument, AnAuthor, ADate]), U, 1) = '1'
else
Result := Piece(sCallV('TIU REQUIRES COSIGNATURE', [0, ADocument, AnAuthor]), U, 1) = '1';
end;
function AskCosignerForTitle(ATitle: integer; AnAuthor: Int64; ADate: TFMDateTime): Boolean;
{ returns TRUE if a cosignature is required for a document title and author }
begin
if TIUPatch175Installed then
Result := Piece(sCallV('TIU REQUIRES COSIGNATURE', [ATitle, 0, AnAuthor, ADate]), U, 1) = '1'
else
Result := Piece(sCallV('TIU REQUIRES COSIGNATURE', [ATitle, 0, AnAuthor]), U, 1) = '1';
end;
function AskCosignerForNotes: Boolean;
{ returns true if cosigner should be asked when creating a new progress note }
begin
if uTIUPrefs = nil then LoadTIUPrefs;
Result := uTIUPrefs.AskCosigner;
end;
function AskSubjectForNotes: Boolean;
{ returns true if subject should be asked when creating a new progress note }
begin
if uTIUPrefs = nil then LoadTIUPrefs;
Result := uTIUPrefs.AskNoteSubject;
end;
function CanCosign(ATitle, ADocType: integer; AUser: Int64; ADate: TFMDateTime): Boolean;
begin
if ATitle > 0 then ADocType := 0;
if TIUPatch175Installed and (ADocType = 0) then
Result := Piece(sCallV('TIU REQUIRES COSIGNATURE', [ATitle, ADocType, AUser, ADate]), U, 1) <> '1'
else
Result := Piece(sCallV('TIU REQUIRES COSIGNATURE', [ATitle, ADocType, AUser]), U, 1) <> '1';
end;
procedure DefaultCosigner(var IEN: Int64; var Name: string);
{ returns the IEN (from the New Person file) and Name of this user's default cosigner }
begin
if uTIUPrefs = nil then LoadTIUPrefs;
IEN := uTIUPrefs.DfltCosigner;
Name := uTIUPrefs.DfltCosignerName;
end;
function ReturnMaxNotes: Integer;
begin
if uTIUPrefs = nil then LoadTIUPrefs;
Result := uTIUPrefs.MaxNotes;
if Result = 0 then Result := 100;
end;
function SortNotesAscending: Boolean;
{ returns true if progress notes should be sorted from oldest to newest (chronological) }
begin
if uTIUPrefs = nil then LoadTIUPrefs;
Result := uTIUPrefs.SortAscending;
end;
function DfltTIULocation: Integer;
{ returns the IEN of the user defined default progress note title (if any) }
begin
if uTIUPrefs = nil then LoadTIUPrefs;
Result := uTIUPrefs.DfltLoc;
end;
function DfltTIULocationName: string;
{ returns the name of the user defined default progress note title (if any) }
begin
if uTIUPrefs = nil then LoadTIUPrefs;
Result := uTIUPrefs.DfltLocName;
end;
{ Data Retrieval --------------------------------------------------------------------------- }
procedure ActOnDocument(var AuthSts: TActionRec; IEN: Integer; const ActionName: string);
var
x: string;
begin
if not (IEN > 0) then
begin
AuthSts.Success := True;
AuthSts.Reason := '';
Exit;
end;
x := sCallV('TIU AUTHORIZATION', [IEN, ActionName]);
AuthSts.Success := Piece(x, U, 1) = '1';
AuthSts.Reason := Piece(x, U, 2);
end;
function AuthorSignedDocument(IEN: Integer): boolean;
begin
Result := SCallV('TIU HAS AUTHOR SIGNED?', [IEN, User.DUZ]) = '1';
end;
function CosignDocument(IEN: Integer): Boolean;
var
x: string;
begin
x := sCallV('TIU WHICH SIGNATURE ACTION', [IEN]);
Result := x = 'COSIGNATURE';
end;
(*function CPTRequiredForNote(IEN: Integer): Boolean;
begin
If IEN > 0 then
Result := sCallV('ORWPCE CPTREQD', [IEN]) = '1'
else
Result := False;
end;*)
procedure ListConsultRequests(Dest: TStrings);
{ lists outstanding consult requests for a patient: IEN^Request D/T^Service^Procedure }
begin
CallV('GMRC LIST CONSULT REQUESTS', [Patient.DFN]);
//MixedCaseList(RPCBrokerV.Results);
{ remove first returned string, it is just a count }
if RPCBrokerV.Results.Count > 0 then RPCBrokerV.Results.Delete(0);
SetListFMDateTime('mmm dd,yy hh:nn', TStringList(RPCBrokerV.Results), U, 2);
FastAssign(RPCBrokerV.Results, Dest);
end;
procedure ListNotes(Dest: TStrings; Context: Integer; Early, Late: TFMDateTime;
Person: int64; OccLim: Integer; SortAscending: Boolean);
{ retrieves existing progress notes for a patient according to the parameters passed in
Pieces: IEN^Title^FMDateOfNote^Patient^Author^Location^Status^Visit
Return: IEN^ExDateOfNote^Title, Location, Author^ImageCount^Visit }
var
i: Integer;
x: string;
SortSeq: Char;
begin
if SortAscending then SortSeq := 'A' else SortSeq := 'D';
//if OccLim = 0 then OccLim := MaxNotesReturned;
CallV('TIU DOCUMENTS BY CONTEXT',
[3, Context, Patient.DFN, Early, Late, Person, OccLim, SortSeq]);
with RPCBrokerV do
begin
for i := 0 to Results.Count - 1 do
begin
x := Results[i];
x := Piece(x, U, 1) + U + FormatFMDateTime('mmm dd,yy', MakeFMDateTime(Piece(x, U, 3))) +
U + Piece(x, U, 2) + ', ' + Piece(x, U, 6) + ', ' + Piece(Piece(x, U, 5), ';', 2) +
U + Piece(x, U, 11) + U + Piece(x, U, 8) + U + Piece(x, U, 3);
Results[i] := x;
end; {for}
FastAssign(RPCBrokerV.Results, Dest);
end; {with}
end;
procedure ListNotesForTree(Dest: TStrings; Context: Integer; Early, Late: TFMDateTime;
Person: int64; OccLim: Integer; SortAscending: Boolean);
{ retrieves existing progress notes for a patient according to the parameters passed in
Pieces: IEN^Title^FMDateOfNote^Patient^Author^Location^Status^Visit
Return: IEN^ExDateOfNote^Title, Location, Author^ImageCount^Visit }
var
SortSeq: Char;
const
SHOW_ADDENDA = True;
begin
if SortAscending then SortSeq := 'A' else SortSeq := 'D';
if Context > 0 then
begin
CallV('TIU DOCUMENTS BY CONTEXT', [3, Context, Patient.DFN, Early, Late, Person, OccLim, SortSeq, SHOW_ADDENDA]);
FastAssign(RPCBrokerV.Results, Dest);
end;
end;
procedure ListDCSumm(Dest: TStrings);
{ returns the list of discharge summaries for a patient - see ListNotes for pieces }
var
i: Integer;
x: string;
begin
CallV('TIU SUMMARIES', [Patient.DFN]);
with RPCBrokerV do
begin
SortByPiece(TStringList(Results), U, 3); // sort on date/time of summary
for i := 0 to Results.Count - 1 do
begin
x := Results[i];
x := Piece(x, U, 1) + U + FormatFMDateTime('mmm dd,yy', MakeFMDateTime(Piece(x, U, 3)))
+ U + Piece(x, U, 2) + ', ' + Piece(x, U, 6) + ', ' + Piece(Piece(x, U, 5), ';', 2);
Results[i] := x;
end; {for}
FastAssign(RPCBrokerV.Results, Dest);
end; {with}
end;
procedure LoadDocumentText(Dest: TStrings; IEN: Integer);
{ returns the text of a document (progress note, discharge summary, etc.) }
begin
CallV('TIU GET RECORD TEXT', [IEN]);
FastAssign(RPCBrokerV.Results, Dest);
end;
procedure LoadDetailText(Dest: TStrings; IEN: Integer); //**KCM**
begin
CallV('TIU DETAILED DISPLAY', [IEN]);
FastAssign(RPCBrokerV.Results, Dest);
end;
procedure GetNoteForEdit(var EditRec: TEditNoteRec; IEN: Integer);
{ retrieves internal/external values for progress note fields & loads them into EditRec
Fields: Title:.01, RefDate:1301, Author:1204, Cosigner:1208, Subject:1701, Location:1205 }
var
i, TxtIndx: Integer;
//x: string;
function FindDT(const FieldID: string): TFMDateTime;
var
i: Integer;
begin
Result := 0;
with RPCBrokerV do for i := 0 to Results.Count - 1 do
if Piece(Results[i], U, 1) = FieldID then
begin
Result := MakeFMDateTime(Piece(Results[i], U, 2));
Break;
end;
end;
function FindExt(const FieldID: string): string;
var
i: Integer;
begin
Result := '';
with RPCBrokerV do for i := 0 to Results.Count - 1 do
if Piece(Results[i], U, 1) = FieldID then
begin
Result := Piece(Results[i], U, 3);
Break;
end;
end;
function FindInt(const FieldID: string): Integer;
var
i: Integer;
begin
Result := 0;
with RPCBrokerV do for i := 0 to Results.Count - 1 do
if Piece(Results[i], U, 1) = FieldID then
begin
Result := StrToIntDef(Piece(Results[i], U, 2), 0);
Break;
end;
end;
function FindInt64(const FieldID: string): Int64;
var
i: Integer;
begin
Result := 0;
with RPCBrokerV do for i := 0 to Results.Count - 1 do
if Piece(Results[i], U, 1) = FieldID then
begin
Result := StrToInt64Def(Piece(Results[i], U, 2), 0);
Break;
end;
end;
function FindVal(const FieldID: string): string;
var
i: Integer;
begin
Result := '';
with RPCBrokerV do for i := 0 to Results.Count - 1 do
if Piece(Results[i], U, 1) = FieldID then
begin
Result := Piece(Results[i], U, 2);
Break;
end;
end;
begin
CallV('TIU LOAD RECORD FOR EDIT', [IEN, '.01;.06;.07;1301;1204;1208;1701;1205;1405;2101;70201;70202']);
FillChar(EditRec, SizeOf(EditRec), 0);
with EditRec do
begin
Title := FindInt('.01');
TitleName := FindExt('.01');
DateTime := FindDT('1301');
Author := FindInt64('1204');
AuthorName := FindExt('1204');
Cosigner := FindInt64('1208');
CosignerName := FindExt('1208');
Subject := FindExt('1701');
Location := FindInt('1205');
LocationName := FindExt('1205');
IDParent := FindInt('2101');
ClinProcSummCode := FindInt('70201');
ClinProcDateTime := FindDT('70202');
VisitDate := FindDT('.07');
PkgRef := FindVal('1405');
PkgIEN := StrToIntDef(Piece(PkgRef, ';', 1), 0);
PkgPtr := Piece(PkgRef, ';', 2);
if Title = TYP_ADDENDUM then Addend := FindInt('.06');
with RPCBrokerV do
begin
// -------------------- v19.1 (RV) LOST NOTES?----------------------------
//Lines := Results; 'Lines' is being overwritten by subsequent Broker calls
if not Assigned(Lines) then Lines := TStringList.Create;
//load the text if present
TxtIndx := Results.IndexOf('$TXT');
if TxtIndx > 0 then
begin
for i := TxtIndx + 1 to Results.Count - 1 do
Lines.Add(Results[i]);
end;
// -----------------------------------------------------------------------
end;
end;
end;
procedure GetNoteEditTextOnly(ResultList: TStrings; IEN: Integer);
var
RtnLst: TStringList;
begin
RtnLst := TStringList.Create;
try
CallVistA('TIU LOAD RECORD TEXT', [IEN], RtnLst);
if RtnLst.Count > 0 then
begin
if RtnLst[0] = '$TXT' then
begin
//Remove the indicator
RtnLst.Delete(0);
//assign the remaining
ResultList.Assign(RtnLst);
end;
end;
finally
RtnLst.Free;
end;
end;
function VisitStrForNote(IEN: Integer): string;
begin
Result := sCallV('ORWPCE NOTEVSTR', [IEN]);
end;
function TitleForNote(IEN: Int64): Integer;
begin
Result := StrToIntDef(sCallV('TIU GET DOCUMENT TITLE', [IEN]), 3);
// with RPCBrokerV do
// begin
// ClearParameters := True;
// RemoteProcedure := 'XWB GET VARIABLE VALUE';
// Param[0].PType := reference;
// Param[0].Value := '$G(^TIU(8925,' + IntToStr(IEN) + ',0))';
// CallBroker;
// Result := StrToIntDef(Piece(Results[0], U, 1), 3);
// end;
end;
function GetPackageRefForNote(NoteIEN: integer): string;
begin
Result := sCallV('TIU GET REQUEST', [NoteIEN]);
end;
function GetConsultIENforNote(NoteIEN: integer): Integer;
var
x: string;
begin
x := sCallV('TIU GET REQUEST', [NoteIEN]);
if Piece(x, ';', 2) <> PKG_CONSULTS then
Result := -1
else
Result := StrTOIntDef(Piece(x, ';', 1), -1);
end;
procedure LockDocument(IEN: Int64; var AnErrMsg: string);
var
x: string;
begin
x := sCallV('TIU LOCK RECORD', [IEN]);
if CharAt(x, 1) = '0' then AnErrMsg := '' else AnErrMsg := Piece(x, U, 2);
end;
procedure UnlockDocument(IEN: Int64);
begin
CallV('TIU UNLOCK RECORD', [IEN]);
end;
function LastSaveClean(IEN: Int64): Boolean;
begin
Result := sCallV('TIU WAS THIS SAVED?', [IEN]) = '1';
end;
function GetTIUListItem(IEN: Int64): string;
begin
Result := sCallV('ORWTIU GET LISTBOX ITEM', [IEN]);
end;
{ Data Updates ----------------------------------------------------------------------------- }
(*procedure ClearCPTRequired(IEN: Integer);
{ sets CREDIT STOP CODE ON COMPLETION to NO when no more need to get encounter information }
begin
with RPCBrokerV do
begin
ClearParameters := True;
RemoteProcedure := 'TIU UPDATE RECORD';
Param[0].PType := literal;
Param[0].Value := IntToStr(IEN);
Param[1].PType := list;
with Param[1] do Mult['.11'] := '0'; // **** block removed in v19.1 {RV} ****
CallBroker;
end;
end;*)
procedure DeleteDocument(var DeleteSts: TActionRec; IEN: Integer; const Reason: string);
{ delete a TIU document given the internal entry number, return reason if unable to delete }
var
Return: TStrings;
begin
Return := TStringList.Create;
CallVistA('TIU DELETE RECORD', [IEN, Reason], Return);
if (Return.Count > 0) then
begin
DeleteSts.Success := Piece(Return.Strings[0], U, 1) = '0';
DeleteSts.Reason := Piece(Return.Strings[0], U, 2);
end
else
begin
DeleteSts.Success := False;
DeleteSts.Reason := 'The server did not return a status.';
end;
Return.Destroy;
end;
function AncillaryPackageMessages(IEN: Integer; const Action: string): string;
var
Return: TStrings;
Line: integer;
begin
Return := TStringList.Create;
CallVistA('TIU ANCILLARY PACKAGE MESSAGE', [IEN, Action], Return);
Result := '';
if (Return.Count > 0) then
begin
for Line := 0 to Return.Count - 1 do
begin
if (Piece(Return.Strings[Line], U, 1) = '~NPKG') then
begin
Result := Result + CRLF + CRLF + Piece(Return.Strings[Line], U, 2);
end
else
begin
Result := Result + ' ' + Return.Strings[Line];
end;
end;
end;
Return.Destroy;
end;
function JustifyDocumentDelete(IEN: Integer): Boolean;
begin
Result := sCallV('TIU JUSTIFY DELETE?', [IEN]) = '1';
end;
procedure SignDocument(var SignSts: TActionRec; IEN: Integer; const ESCode: string);
{ update signed status of a TIU document, return reason if signature is not accepted }
var
x: string;
begin
(* with RPCBrokerV do // temp - to insure sign doesn't go interactive
begin
ClearParameters := True;
RemoteProcedure := 'TIU UPDATE RECORD';
Param[0].PType := literal;
Param[0].Value := IntToStr(IEN);
Param[1].PType := list;
with Param[1] do Mult['.11'] := '0'; // **** block removed in v19.1 {RV} ****
CallBroker;
end; // temp - end*)
x := sCallV('TIU SIGN RECORD', [IEN, ESCode]);
SignSts.Success := Piece(x, U, 1) = '0';
SignSts.Reason := Piece(x, U, 2);
end;
procedure PutNewNote(var CreatedDoc: TCreatedDoc; const NoteRec: TNoteRec);
{ create a new progress note with the data in NoteRec and return its internal entry number
load broker directly since there isn't a good way to set up mutilple subscript arrays }
(*var
i: Integer;*)
var
ErrMsg: string;
begin
LockBroker;
try
with RPCBrokerV do
begin
ClearParameters := True;
RemoteProcedure := 'TIU CREATE RECORD';
Param[0].PType := literal;
Param[0].Value := Patient.DFN; //*DFN*
Param[1].PType := literal;
Param[1].Value := IntToStr(NoteRec.Title);
Param[2].PType := literal;
Param[2].Value := ''; //FloatToStr(Encounter.DateTime);
Param[3].PType := literal;
Param[3].Value := ''; //IntToStr(Encounter.Location);
Param[4].PType := literal;
Param[4].Value := '';
Param[5].PType := list;
with Param[5] do
begin
//Mult['.11'] := BOOLCHAR[NoteRec.NeedCPT]; // **** removed in v19.1 {RV} ****
Mult['1202'] := IntToStr(NoteRec.Author);
Mult['1301'] := FloatToStr(NoteRec.DateTime);
Mult['1205'] := IntToStr(Encounter.Location);
if NoteRec.Cosigner > 0 then Mult['1208'] := IntToStr(NoteRec.Cosigner);
if NoteRec.PkgRef <> '' then Mult['1405'] := NoteRec.PkgRef;
Mult['1701'] := FilteredString(Copy(NoteRec.Subject, 1, 80));
if NoteRec.IDParent > 0 then Mult['2101'] := IntToStr(NoteRec.IDParent);
(* if NoteRec.Lines <> nil then
for i := 0 to NoteRec.Lines.Count - 1 do
Mult['"TEXT",' + IntToStr(i+1) + ',0'] := FilteredString(NoteRec.Lines[i]);*)
end;
Param[6].PType := literal;
Param[6].Value := Encounter.VisitStr;
Param[7].PType := literal;
Param[7].Value := '1'; // suppress commit logic
CallBroker;
CreatedDoc.IEN := StrToIntDef(Piece(Results[0], U, 1), 0);
CreatedDoc.ErrorText := Piece(Results[0], U, 2);
end;
finally
UnlockBroker;
end;
if ( NoteRec.Lines <> nil ) and ( CreatedDoc.IEN <> 0 ) then
begin
SetText(ErrMsg, NoteRec.Lines, CreatedDoc.IEN, 1);
if ErrMsg <> '' then
begin
CreatedDoc.IEN := 0;
CreatedDoc.ErrorText := ErrMsg;
end;
end;
end;
procedure PutAddendum(var CreatedDoc: TCreatedDoc; const NoteRec: TNoteRec; AddendumTo: Integer);
{ create a new addendum for note identified in AddendumTo, returns IEN of new document
load broker directly since there isn't a good way to set up mutilple subscript arrays }
(*var
i: Integer;*)
var
ErrMsg: string;
begin
LockBroker;
try
with RPCBrokerV do
begin
ClearParameters := True;
RemoteProcedure := 'TIU CREATE ADDENDUM RECORD';
Param[0].PType := literal;
Param[0].Value := IntToStr(AddendumTo);
Param[1].PType := list;
with Param[1] do
begin
Mult['1202'] := IntToStr(NoteRec.Author);
Mult['1301'] := FloatToStr(NoteRec.DateTime);
if NoteRec.Cosigner > 0 then Mult['1208'] := IntToStr(NoteRec.Cosigner);
(* if NoteRec.Lines <> nil then
for i := 0 to NoteRec.Lines.Count - 1 do
Mult['"TEXT",' + IntToStr(i+1) + ',0'] := FilteredString(NoteRec.Lines[i]);*)
end;
Param[2].PType := literal;
Param[2].Value := '1'; // suppress commit logic
CallBroker;
CreatedDoc.IEN := StrToIntDef(Piece(Results[0], U, 1), 0);
CreatedDoc.ErrorText := Piece(Results[0], U, 2);
end;
finally
UnlockBroker;
end;
if ( NoteRec.Lines <> nil ) and ( CreatedDoc.IEN <> 0 ) then
begin
SetText(ErrMsg, NoteRec.Lines, CreatedDoc.IEN, 1);
if ErrMsg <> '' then
begin
CreatedDoc.IEN := 0;
CreatedDoc.ErrorText := ErrMsg;
end;
end;
end;
procedure PutEditedNote(var UpdatedDoc: TCreatedDoc; const NoteRec: TNoteRec; NoteIEN: Integer);
{ update the fields and content of the note identified in NoteIEN, returns 1 if successful
load broker directly since there isn't a good way to set up mutilple subscript arrays }
(*var
i: Integer;*)
var
ErrMsg: string;
begin
// First, file field data
LockBroker;
try
with RPCBrokerV do
begin
ClearParameters := True;
RemoteProcedure := 'TIU UPDATE RECORD';
Param[0].PType := literal;
Param[0].Value := IntToStr(NoteIEN);
Param[1].PType := list;
with Param[1] do
begin
if NoteRec.Addend = 0 then
begin
Mult['.01'] := IntToStr(NoteRec.Title);
//Mult['.11'] := BOOLCHAR[NoteRec.NeedCPT]; // **** removed in v19.1 {RV} ****
end;
Mult['1202'] := IntToStr(NoteRec.Author);
if NoteRec.Cosigner > 0 then Mult['1208'] := IntToStr(NoteRec.Cosigner);
if NoteRec.PkgRef <> '' then Mult['1405'] := NoteRec.PkgRef;
Mult['1301'] := FloatToStr(NoteRec.DateTime);
Mult['1701'] := FilteredString(Copy(NoteRec.Subject, 1, 80));
if NoteRec.ClinProcSummCode > 0 then Mult['70201'] := IntToStr(NoteRec.ClinProcSummCode);
if NoteRec.ClinProcDateTime > 0 then Mult['70202'] := FloatToStr(NoteRec.ClinProcDateTime);
(* for i := 0 to NoteRec.Lines.Count - 1 do
Mult['"TEXT",' + IntToStr(i+1) + ',0'] := FilteredString(NoteRec.Lines[i]);*)
end;
CallBroker;
UpdatedDoc.IEN := StrToIntDef(Piece(Results[0], U, 1), 0);
UpdatedDoc.ErrorText := Piece(Results[0], U, 2);
end;
finally
UnlockBroker;
end;
if UpdatedDoc.IEN <= 0 then //v22.12 - RV
//if UpdatedDoc.ErrorText <> '' then //v22.5 - RV
begin
UpdatedDoc.ErrorText := UpdatedDoc.ErrorText + #13#10 + #13#10 + 'Document #: ' + IntToStr(NoteIEN);
exit;
end;
// next, if no error, file document body
SetText(ErrMsg, NoteRec.Lines, NoteIEN, 0);
if ErrMsg <> '' then
begin
UpdatedDoc.IEN := 0;
UpdatedDoc.ErrorText := ErrMsg;
end;
end;
procedure PutTextOnly(var ErrMsg: string; NoteText: TStrings; NoteIEN: Int64);
var
i: Integer;
begin
LockBroker;
try
with RPCBrokerV do
begin
ClearParameters := True;
RemoteProcedure := 'TIU UPDATE RECORD';
Param[0].PType := literal;
Param[0].Value := IntToStr(NoteIEN);
Param[1].PType := list;
for i := 0 to Pred(NoteText.Count) do
Param[1].Mult['"TEXT",' + IntToStr(Succ(i)) + ',0'] := FilteredString(NoteText[i]);
Param[2].PType := literal;
Param[2].Value :='1'; // suppress commit code
CallBroker;
if Piece(Results[0], U, 1) = '0' then ErrMsg := Piece(Results[0], U, 2) else ErrMsg := '';
end;
finally
UnlockBroker;
end;
end;
procedure SetText(var ErrMsg: string; NoteText: TStrings; NoteIEN: Int64; Suppress: Integer);
const
DOCUMENT_PAGE_SIZE = 300;
TX_SERVER_ERROR = 'An error occurred on the server.' ;
var
i, j, page, pages: Integer;
begin
// Compute pages, initialize Params
pages := ( NoteText.Count div DOCUMENT_PAGE_SIZE );
if (NoteText.Count mod DOCUMENT_PAGE_SIZE) > 0 then pages := pages + 1;
page := 1;
LockBroker;
try
InitParams( NoteIEN, Suppress );
// Loop through NoteRec.Lines
for i := 0 to NoteText.Count - 1 do
begin
j := i + 1;
//Add each successive line to Param[1].Mult...
RPCBrokerV.Param[1].Mult['"TEXT",' + IntToStr(j) + ',0'] := FilteredString(NoteText[i]);
// When current page is filled, call broker, increment page, itialize params,
// and continue...
if ( j mod DOCUMENT_PAGE_SIZE ) = 0 then
begin
RPCBrokerV.Param[1].Mult['"HDR"'] := IntToStr(page) + U + IntToStr(pages);
CallBroker;
if RPCBrokerV.Results.Count > 0 then
ErrMsg := Piece(RPCBrokerV.Results[0], U, 4)
else
ErrMsg := TX_SERVER_ERROR;
if ErrMsg <> '' then Exit;
page := page + 1;
InitParams( NoteIEN, Suppress );
end; // if
end; // for
// finally, file any remaining partial page
if ( NoteText.Count mod DOCUMENT_PAGE_SIZE ) <> 0 then
begin
RPCBrokerV.Param[1].Mult['"HDR"'] := IntToStr(page) + U + IntToStr(pages);
CallBroker;
if RPCBrokerV.Results.Count > 0 then
ErrMsg := Piece(RPCBrokerV.Results[0], U, 4)
else
ErrMsg := TX_SERVER_ERROR;
end;
finally
UnlockBroker;
end;
end;
procedure InitParams( NoteIEN: Int64; Suppress: Integer );
begin
with RPCBrokerV do
begin
ClearParameters := True;
RemoteProcedure := 'TIU SET DOCUMENT TEXT';
Param[0].PType := literal;
Param[0].Value := IntToStr(NoteIEN);
Param[1].PType := list;
Param[2].PType := literal;
Param[2].Value := IntToStr(Suppress);
end;
end;
{ Printing --------------------------------------------------------------------------------- }
function AllowPrintOfNote(ANote: Integer): string;
{ returns
0 message Can't print at all (fails bus rules)
1 Can print work copy only
2 Can print work or chart copy (Param=1 or user is MAS)
}
begin
CallVistA('TIU CAN PRINT WORK/CHART COPY', [ANote], Result); // sCallV('TIU CAN PRINT WORK/CHART COPY', [ANote]);
end;
function AllowChartPrintForNote(ANote: Integer): Boolean;
{ returns true if a progress note may be printed outside of MAS }
begin
Result := (Piece(sCallV('TIU GET DOCUMENT PARAMETERS', [ANote]), U, 9) = '1')
or (sCallV('TIU AUTHORIZATION', [ANote , 'PRINT RECORD']) = '1');
// or (sCallV('TIU USER IS MEMBER OF CLASS', [User.DUZ, 'MEDICAL INFORMATION SECTION']) = '1');
// (V16? - RV) New TIU RPC required, per discussion on NOIS MAR-0900-21265
end;
procedure PrintNoteToDevice(ANote: Integer; const ADevice: string; ChartCopy: Boolean;
var ErrMsg: string);
{ prints a progress note on the selected device }
begin
ErrMsg := sCallV('TIU PRINT RECORD', [ANote, ADevice, ChartCopy]);
if Piece(ErrMsg, U, 1) = '0' then ErrMsg := '' else ErrMsg := Piece(ErrMsg, U, 2);
end;
function GetFormattedNote(ANote: Integer; ChartCopy: Boolean): TStrings;
begin
CallV('ORWTIU WINPRINT NOTE',[ANote, ChartCopy]);
Result := RPCBrokerV.Results;
end;
function GetCurrentSigners(IEN: integer): TStrings;
begin
CallV('TIU GET ADDITIONAL SIGNERS', [IEN]);
MixedCaseList(RPCBrokerV.Results);
Result := RPCBrokerV.Results ;
end;
procedure UpdateAdditionalSigners(IEN: integer; Signers: TStrings);
begin
CallV('TIU UPDATE ADDITIONAL SIGNERS', [IEN, Signers]);
end;
function CanChangeCosigner(IEN: integer): boolean;
begin
Result := Piece(sCallV('TIU CAN CHANGE COSIGNER?', [IEN]), U, 1) = '1';
end;
procedure ChangeCosigner(IEN: integer; Cosigner: int64);
begin
LockBroker;
try
with RPCBrokerV do
begin
ClearParameters := True;
RemoteProcedure := 'TIU UPDATE RECORD';
Param[0].PType := literal;
Param[0].Value := IntToStr(IEN);
Param[1].PType := list;
with Param[1] do
if Cosigner > 0 then
Mult['1208'] := IntToStr(Cosigner)
else
Mult['1208'] := '@';
CallBroker;
end;
finally
UnlockBroker;
end;
end;
// Determine if given note title is allowed more than once per visit. 12/2002-GRE
function OneNotePerVisit(NoteEIN: Integer; DFN: String; VisitStr: String):boolean;
var x: string;
begin
x := sCallV('TIU ONE VISIT NOTE?', [IntToStr(NoteEIN),DFN,VisitStr]);
if StrToInt(x) > 0 then
Result := True //Only one per visit
else
Result := False;
end;
function GetCurrentTIUContext: TTIUContext;
var
x: string;
AContext: TTIUContext;
begin
x := sCallV('ORWTIU GET TIU CONTEXT', [User.DUZ]) ;
with AContext do
begin
Changed := True;
BeginDate := Piece(x, ';', 1);
FMBeginDate := StrToFMDateTime(BeginDate);
EndDate := Piece(x, ';', 2);
FMEndDate := StrToFMDateTime(EndDate);
Status := Piece(x, ';', 3);
if (StrToIntDef(Status, 0) < 1) or (StrToIntDef(Status, 0) > 5) then Status := '1';
Author := StrToInt64Def(Piece(x, ';', 4), 0);
MaxDocs := StrToIntDef(Piece(x, ';', 5), 0);
ShowSubject := StrToIntDef(Piece(x, ';', 6), 0) > 0; //TIU PREFERENCE??
SortBy := Piece(x, ';', 7); //TIU PREFERENCE??
ListAscending := StrToIntDef(Piece(x, ';', 8), 0) > 0;
TreeAscending := StrToIntDef(Piece(x, ';', 9), 0) > 0; //TIU PREFERENCE??
GroupBy := Piece(x, ';', 10);
SearchField := Piece(x, ';', 11);
KeyWord := Piece(x, ';', 12);
Filtered := (Keyword <> '');
end;
Result := AContext;
end;
procedure SaveCurrentTIUContext(AContext: TTIUContext) ;
var
x: string;
begin
with AContext do
begin
SetPiece(x, ';', 1, BeginDate);
SetPiece(x, ';', 2, EndDate);
SetPiece(x, ';', 3, Status);
if Author > 0 then
SetPiece(x, ';', 4, IntToStr(Author))
else
SetPiece(x, ';', 4, '');
SetPiece(x, ';', 5, IntToStr(MaxDocs));
SetPiece(x, ';', 6, BOOLCHAR[ShowSubject]); //TIU PREFERENCE??
SetPiece(x, ';', 7, SortBy); //TIU PREFERENCE??
SetPiece(x, ';', 8, BOOLCHAR[ListAscending]);
SetPiece(x, ';', 9, BOOLCHAR[TreeAscending]); //TIU PREFERENCE??
SetPiece(x, ';', 10, GroupBy);
SetPiece(x, ';', 11, SearchField);
SetPiece(x, ';', 12, KeyWord);
end;
CallV('ORWTIU SAVE TIU CONTEXT', [x]);
end;
function TIUSiteParams: string;
begin
if(not uTIUSiteParamsLoaded) then
begin
uTIUSiteParams := sCallV('TIU GET SITE PARAMETERS', []) ;
uTIUSiteParamsLoaded := TRUE;
end;
Result := uTIUSiteParams;
end;
// ===================Interdisciplinary Notes RPCs =====================
function IDNotesInstalled: boolean;
begin
Result := True; // old patch check no longer called
end;
function CanTitleBeIDChild(Title: integer; var WhyNot: string): boolean;
var
x: string;
begin
Result := False;
x := sCallV('ORWTIU CANLINK', [Title]);
if Piece(x, U, 1) = '1' then
Result := True
else if Piece(x, U, 1) = '0' then
begin
Result := False;
WhyNot := Piece(x, U, 2);
end;
end;
function CanBeAttached(DocID: string; var WhyNot: string): boolean;
var
x: string;
const
TX_NO_ATTACH = 'This note appears to be an interdisciplinary parent. Please drag the child note you wish to ' + CRLF +
'attach instead of attempting to drag the parent, or check with IRM or your' + CRLF +
'clinical coordinator.';
begin
Result := False;
if StrToIntDef(DocID, 0) = 0 then exit;
x := sCallV('TIU ID CAN ATTACH', [DocID]);
if Piece(x, U, 1) = '1' then
Result := True
else if Piece(x, U, 1) = '0' then
begin
Result := False;
WhyNot := Piece(x, U, 2);
end
else if Piece(x, U, 1) = '-1' then
begin
Result := False;
WhyNot := TX_NO_ATTACH;
end;
end;
function CanReceiveAttachment(DocID: string; var WhyNot: string): boolean;
var
x: string;
begin
x := sCallV('TIU ID CAN RECEIVE', [DocID]);
if Piece(x, U, 1) = '1' then
Result := True
else
begin
Result := False;
WhyNot := Piece(x, U, 2);
end;
end;
function AttachEntryToParent(DocID, ParentDocID: string; var WhyNot: string): boolean;
var
x: string;
begin
x := sCallV('TIU ID ATTACH ENTRY', [DocID, ParentDocID]);
if StrToIntDef(Piece(x, U, 1), 0) > 0 then
Result := True
else
begin
Result := False;
WhyNot := Piece(x, U, 2);
end;
end;
function DetachEntryFromParent(DocID: string; var WhyNot: string): boolean;
var
x: string;
begin
x := sCallV('TIU ID DETACH ENTRY', [DocID]);
if StrToIntDef(Piece(x, U, 1), 0) > 0 then
Result := True
else
begin
Result := False;
WhyNot := Piece(x, U, 2);
end;
end;
function SubSetOfUserClasses(const StartFrom: string; Direction: Integer): TStrings;
begin
CallV('TIU USER CLASS LONG LIST', [StartFrom, Direction]);
Result := RPCBrokerV.Results;
end;
function UserDivClassInfo(User: Int64): TStrings;
begin
CallV('TIU DIV AND CLASS INFO', [User]);
Result := RPCBrokerV.Results;
end;
function UserInactive(EIN: String): boolean;
var x: string;
begin
x:= sCallv('TIU USER INACTIVE?', [EIN]) ;
if (StrToInt(x) > 0) then
Result := True
else
Result := False;
end;
function TIUPatch175Installed: boolean;
begin
with uPatch175Installed do
if not PatchChecked then
begin
PatchInstalled := ServerHasPatch('TIU*1.0*175');
PatchChecked := True;
end;
Result := uPatch175Installed.PatchInstalled;
end;
function NoteHasText(NoteIEN: integer): boolean;
begin
Result := (StrToIntDef(sCallV('ORWTIU CHKTXT', [NoteIEN]), 0) > 0);
end;
initialization
// nothing for now
finalization
if uNoteTitles <> nil then uNoteTitles.Free;
if uTIUPrefs <> nil then uTIUPrefs.Free;
end.
|
unit u_xml_plugins;
{$ifdef fpc}
{$mode objfpc}{$H+}
{$endif}
interface
uses Classes
, SysUtils
, superobject
, u_xpl_common
, u_xpl_header
;
type TChoiceType = class(TCollectionItem)
public
value : string;
label_ : String ;
procedure Set_O(o : ISuperObject);
end;
TChoicesType = class(TCollection)
public
Constructor Create(const so : ISuperObject);
function Get_Items(Index : integer) : TChoiceType;
property Items[Index : integer] : TChoiceType read Get_Items; default;
end;
{ TElementType }
TElementType = class(TCollectionItem)
fChoices : TChoicesType;
private
fSO : ISuperObject;
function GetChoices: TChoicesType;
public
name : string;
label_ : String ;
control_type : String;
min_val : integer;
max_val : integer;
regexp : String ;
default_ : String ;
conditional_visibility : String;
property Choices : TChoicesType read GetChoices;
procedure Set_O(o : ISuperObject);
destructor Destroy; override;
end;
{ TElementsType }
TElementsType = class(TCollection)
public
Constructor Create(const so : ISuperObject);
function Get_Items(Index : integer) : TElementType;
property Items[Index : integer] : TElementType read Get_Items; default;
end;
{ TPluginType }
{ TCommandType }
TCommandType = class(TCollectionItem)
fElements : TElementsType;
private
fSO : ISuperObject;
function GetElements: TElementsType;
function GetMsgType: TxPLMessageType;
public
msg_type : string;
name : string;
description : string;
msg_schema : string;
procedure Set_O(o : ISuperObject);
destructor Destroy; override;
property Elements : TElementsType read GetElements;
published
property MsgType : TxPLMessageType read GetMsgType;
end;
{ TConfigItemType }
TConfigItemType = class(TCollectionItem)
public
name : string;
description : string;
format : string;
procedure Set_O(o : ISuperObject);
end;
TTriggersType = class(TCollection)
public
Constructor Create(const so : ISuperObject);
function Get_Items(Index : integer) : TCommandType;
property Items[Index : integer] : TCommandType read Get_Items; default;
end;
{ TCommandsType }
TCommandsType = class(TCollection)
private
fDV : string;
public
constructor Create(const so: ISuperObject; const aDV : string);
function Get_Items(Index : integer) : TCommandType;
property Items[Index : integer] : TCommandType read Get_Items; default;
property DV : string read fDV; // gives back vendor-device string
end;
{ TConfigItemsType }
TConfigItemsType = class(TCollection)
public
Constructor Create(const so : ISuperObject);
function Get_Items(Index : integer) : TConfigItemType;
property Items[Index : integer] : TConfigItemType read Get_Items; default;
end;
{ TDeviceType }
TDeviceType = class(TCollectionItem)
private
fSO : iSuperObject;
fCommands : TCommandsType;
fConfigItems : TConfigItemsType;
fTriggers : TTriggersType;
function GetCommands: TCommandsType;
function GetConfigItems: TConfigItemsType;
function GetTriggers: TTriggersType;
function Get_Device: string;
function Get_Vendor: string;
public
id_ : string;
Version : string;
Description : string;
info_url : string;
platform_ : string;
beta_version : string;
download_url : string;
type_ : string;
procedure Set_O(o : ISuperObject);
destructor Destroy; override;
published
property Device : string read Get_Device;
property Vendor : string read Get_Vendor;
property Commands : TCommandsType read GetCommands;
property Triggers : TTriggersType read GetTriggers;
property ConfigItems : TConfigItemsType read GetConfigItems;
end;
{ TDevicesType }
TDevicesType = class(TCollection)
public
Constructor Create(const so : ISuperObject);
function Get_Items(Index : integer) : TDeviceType;
property Items[Index : integer] : TDeviceType read Get_Items; default;
end;
TPluginType = class(TCollectionItem)
private
fSO : ISuperObject;
fVendor : string;
fFileName : string;
fPresent : boolean;
fDevices : TDevicesType;
function GetDevices: TDevicesType;
procedure Set_Vendor(const AValue: string);
public
Name : string;
Type_ : string;
Description : string;
URL : string;
Info_URL : string;
Plugin_URL : string;
Version : string;
function Update : boolean;
destructor Destroy; override;
published
property Vendor : string read fVendor write Set_Vendor;
property Present: boolean read fPresent;
property FileName : string read fFileName;
property Devices : TDevicesType read GetDevices;
end;
TLocationType = class(TCollectionItem)
public
Url : string;
end;
TLocationsType = class(TCollection)
public
Constructor Create(const so : ISuperObject);
function Get_Items(Index : integer) : TLocationType;
property Items[Index : integer] : TLocationType read Get_Items; default;
end;
TPluginsType = class(TCollection)
protected
fPluginDir : string;
public
Constructor Create(const so : ISuperObject; const aPluginDir : string);
function Get_Items(Index : integer) : TPluginType;
property Items[Index : integer] : TPluginType read Get_Items; default;
end;
TSchemaType = class(TCollectionItem)
public
name : string;
end;
// TSchemaCollection ====================================================
TSchemaCollection = class(TCollection)
protected
fPluginDir : string;
public
Constructor Create(const so : ISuperObject; const aPluginDir : string);
function Get_Items(Index : integer) : TSchemaType;
property Items[Index : integer] : TSchemaType read Get_Items; default;
end;
implementation //==============================================================
uses StrUtils
, typInfo
, uxPLConst
, u_downloader_Indy
, superxmlparser
, u_xPL_Application
;
{ TElementsType }
constructor TElementsType.Create(const so: ISuperObject);
var arr : TSuperArray;
i : integer;
o : isuperobject;
begin
inherited Create(TElementType);
o := so['element'];
if not assigned(o) then exit;
if o.IsType(stArray) then begin
arr := o.AsArray;
for i := 0 to arr.Length-1 do with TElementType(Add) do Set_O(arr[i]);
end else
if o.IsType(stObject) then with TElementType(Add) do Set_O(o);
end;
function TElementsType.Get_Items(Index: integer): TElementType;
begin
Result := TElementType(inherited Items[index]);
end;
constructor TChoicesType.Create(const so: ISuperObject);
var arr : TSuperArray;
i : integer;
o : isuperobject;
begin
inherited Create(TChoiceType);
o := so['option'];
if not assigned(o) then exit;
if o.IsType(stArray) then begin
arr := o.AsArray;
for i := 0 to arr.Length-1 do with TChoiceType(Add) do Set_O(arr[i]);
end else
if o.IsType(stObject) then with TChoiceType(Add) do Set_O(o);
end;
function TChoicesType.Get_Items(Index: integer): TChoiceType;
begin
Result := TChoiceType(inherited Items[index]);
end;
procedure TChoiceType.Set_O(o: ISuperObject);
begin
value := AnsiString(o['value'].AsString);
if Assigned(o['label']) then label_ := AnsiString(o['label'].AsString);
end;
{ TElementType }
function TElementType.GetChoices: TChoicesType;
begin
if Assigned(fSO['choices']) and (not Assigned(fChoices))
then fChoices := TChoicesType.Create(fSO['choices']);
Result := fChoices;
end;
procedure TElementType.Set_O(o: ISuperObject);
begin
fSO := o;
fChoices := nil;
name := AnsiString(fSO['name'].AsString);
if Assigned(fSO['default']) then default_ := AnsiString(fSO['default'].AsString);
end;
destructor TElementType.Destroy;
begin
if Assigned(fChoices)
then fChoices.Free;
inherited Destroy;
end;
{ TCommandType }
function TCommandType.GetElements: TElementsType;
begin
if not Assigned(fElements)
then fElements := TElementsType.Create(fSO);
Result := fElements;
end;
function TCommandType.GetMsgType: TxPLMessageType;
begin
result := TxPLMessageType(GetEnumValue(TypeInfo(TxPLMessageType), msg_type));
end;
procedure TCommandType.Set_O(o: ISuperObject);
var b : ISuperObject;
begin
fSO := o;
fElements := nil;
name := AnsiString(o['name'].AsString);
b := fSO['msg_type']; if assigned(b) then msg_type := AnsiString(b.AsString);
b := fSO['description']; if assigned(b) then description := AnsiString(b.AsString);
b := fSO['msg_schema']; if assigned(b) then msg_schema := AnsiString(b.AsString);
end;
destructor TCommandType.Destroy;
begin
if Assigned(fElements)
then fElements.Free;
inherited Destroy;
end;
procedure TConfigItemType.Set_O(o: ISuperObject);
var b : ISuperObject;
begin
name := AnsiString(o['name'].AsString);
b := o['format']; if assigned(b) then format := AnsiString(b.AsString);
b := o['description']; if assigned(b) then description := AnsiString(b.AsString);
end;
{ TCommandsType }
constructor TCommandsType.Create(const so: ISuperObject; const aDV : string);
var arr : TSuperArray;
i : integer;
o : isuperobject;
begin
inherited Create(TCommandType);
fDV := aDV;
o := so['command'];
if not assigned(o) then exit;
if o.IsType(stArray) then begin
arr := o.AsArray;
for i := 0 to arr.Length-1 do with TCommandType(Add) do Set_O(arr[i]);
end else
if o.IsType(stObject) then with TCommandType(Add) do Set_O(o);
end;
function TCommandsType.Get_Items(Index: integer): TCommandType;
begin
Result := TCommandType(inherited Items[index]);
end;
constructor TTriggersType.Create(const so: ISuperObject);
var arr : TSuperArray;
i : integer;
o : isuperobject;
begin
inherited Create(TCommandType);
o := so['trigger'];
if not assigned(o) then exit;
if o.IsType(stArray) then begin
arr := o.AsArray;
for i := 0 to arr.Length-1 do with TCommandType(Add) do Set_O(arr[i]);
end else
if o.IsType(stObject) then with TCommandType(Add) do Set_O(o);
end;
function TTriggersType.Get_Items(Index: integer): TCommandType;
begin
Result := TCommandType(inherited Items[index]);
end;
{ TConfigItemsType }
constructor TConfigItemsType.Create(const so: ISuperObject);
var arr : TSuperArray;
i : integer;
o : isuperobject;
begin
inherited Create(TCommandType);
o := so['configItem'];
if not assigned(o) then exit;
if o.IsType(stArray) then begin
arr := o.AsArray;
for i := 0 to arr.Length-1 do with TConfigItemType(Add) do Set_O(arr[i]);
end else
if o.IsType(stObject) then with TConfigItemType(Add) do Set_O(o);
end;
function TConfigItemsType.Get_Items(Index: integer): TConfigItemType;
begin
Result := TConfigItemType(inherited Items[index]);
end;
{ TDeviceType }
function TDeviceType.Get_Device: string;
begin
Result := AnsiRightStr(Id_,Length(Id_)-AnsiPos('-',Id_));
end;
function TDeviceType.GetCommands: TCommandsType;
begin
if not Assigned(fCommands) then
fCommands := TCommandsType.Create(fSO,ID_);
Result := fCommands;
end;
function TDeviceType.GetConfigItems: TConfigItemsType;
begin
if not Assigned(fConfigItems) then
fConfigItems := TConfigItemsType.Create(fSO);
Result := fConfigItems;
end;
function TDeviceType.GetTriggers: TTriggersType;
begin
if not Assigned(fTriggers) then
fTriggers := TTriggersType.Create(fSO);
Result := fTriggers;
end;
function TDeviceType.Get_Vendor: string;
begin
Result := AnsiLeftStr(Id_,Pred(AnsiPos('-',Id_)));
end;
procedure TDeviceType.Set_O(o: ISuperObject);
var b : ISuperObject;
begin
fSO := o;
fCommands := nil;
fConfigItems := nil;
fTriggers := nil;
id_ := AnsiString(fSO['id'].AsString);
b := fSO['version']; if assigned(b) then Version := AnsiString(b.AsString);
b := fSO['description']; if assigned(b) then Description := AnsiString(b.AsString);
b := fSO['info_url']; if assigned(b) then Info_URL := AnsiString(b.AsString);
b := fSO['platform']; if assigned(b) then platform_ := AnsiString(b.AsString);
b := fSO['beta_version']; if assigned(b) then beta_version := AnsiString(b.AsString);
b := fSO['download_url']; if assigned(b) then download_url :=AnsiString( b.AsString);
b := fSO['type']; if assigned(b) then type_ := AnsiString(b.AsString);
end;
destructor TDeviceType.Destroy;
begin
if Assigned(fCommands)
then fCommands.Free;
if Assigned(fConfigItems)
then fConfigItems.Free;
if Assigned(fTriggers)
then fTriggers.Free;
inherited Destroy;
end;
{ TDevicesType }
constructor TDevicesType.Create(const so: ISuperObject);
var arr : TSuperArray;
i : integer;
o : isuperobject;
begin
inherited Create(TDeviceType);
o := so['device'];
if assigned(o) then
if o.IsType(stArray) then begin
arr := SO['device'].AsArray;
for i:=0 to arr.Length-1 do
with TDeviceType(Add) do Set_O(arr[i]);
end
else with TDeviceType(Add) do Set_O(o);
end;
function TDevicesType.Get_Items(Index: integer): TDeviceType;
begin
Result := TDeviceType(inherited Items[index]);
end;
{ TPluginType }
procedure TPluginType.Set_Vendor(const AValue: string);
var o : ISuperObject;
s : string;
begin
if AnsiCompareText(fVendor,AValue) <> 0 then begin
fVendor := AnsiLowerCase(AValue);
fFileName := TPluginsType(Collection).fPluginDir +
AnsiRightStr( URL,length(Url)-LastDelimiter('/',URL)
) + K_FEXT_XML;
fPresent := Fileexists(fFileName);
if fPresent then begin
fSO := XMLParseFile(fFileName,true);
if Assigned(so) then begin // The file may be present but not XML valid
s := AnsiString(so.AsJSon);
if length(s)>0 then begin
o := fSO['version'];
if assigned(o) then Version := AnsiString(o.AsString);
o := fSO['info_url'];
if assigned(o) then Info_URL := AnsiString(o.AsString);
o := fSO['plugin_url'];
if assigned(o) then Plugin_URL := AnsiString(o.AsString);
end;
end;
end;
end;
end;
function TPluginType.GetDevices: TDevicesType;
begin
if not Assigned(fDevices) then
fDevices := TDevicesType.Create(fSO);
result := fDevices;
end;
function TPluginType.Update: boolean;
var aUrl : string;
begin
aUrl := Url;
if not AnsiEndsStr(K_FEXT_XML, aUrl) then aUrl := aUrl + K_FEXT_XML;
Result := HTTPDownload(aUrl, FileName, xPLApplication.Settings.ProxyServer);
end;
destructor TPluginType.Destroy;
begin
if Assigned(fDevices)
then fDevices.Free;
inherited Destroy;
end;
// TPluginsType ===============================================================
constructor TPluginsType.Create(const so : ISuperObject; const aPluginDir : string);
var i : integer;
arr : TSuperArray;
begin
inherited Create(TPluginType);
fPluginDir := aPluginDir;
arr := so['plugin'].AsArray;
for i := 0 to arr.Length-1 do
with TPluginType(Add) do begin
name := AnsiString(arr[i]['name'].AsString);
type_ := AnsiString(arr[i]['type'].AsString);
description := AnsiString(arr[i]['description'].AsString);
url := AnsiString(arr[i]['url'].AsString);
vendor := AnsiLeftStr(Name,Pred(AnsiPos(' ',Name)));
end;
end;
function TPluginsType.Get_Items(Index : integer) : TPluginType;
begin
Result := TPluginType(inherited Items[index]);
end;
// TSchemaCollection ==========================================================
constructor TSchemaCollection.Create(const so : ISuperObject; const aPluginDir : string);
var i : integer;
arr : TSuperArray;
begin
inherited Create(TSchemaType);
fPluginDir := aPluginDir;
arr := so['xplSchema'].AsArray;
for i := 0 to arr.Length-1 do
with TSchemaType(Add) do
name := AnsiString(arr[i]['name'].AsString);
end;
function TSchemaCollection.Get_Items(Index: integer): TSchemaType;
begin
Result := TSchemaType(inherited Items[index]);
end;
// TLocationsType =============================================================
constructor TLocationsType.Create(const so : ISuperObject);
var i : integer;
arr : TSuperArray;
begin
inherited Create(TLocationType);
arr := SO['locations']['location'].AsArray;
for i:=0 to arr.Length-1 do
with TLocationType(Add) do
Url := AnsiString(arr[i]['url'].AsString);
end;
function TLocationsType.Get_Items(Index : integer) : TLocationType;
begin
Result := TLocationType(inherited Items[index]);
end;
end.
|
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$HPPEMIT LINKUNIT}
unit Data.DbxMSSQL;
interface
uses
Data.DBXDynalink,
Data.DBXDynalinkNative,
Data.DBXCommon, Data.DbxMSSQLReadOnlyMetaData, Data.DbxMSSQLMetaData;
type
TDBXMSSQLProperties = class(TDBXProperties)
strict private
const StrOSAuthentication = 'OS Authentication';
const StrPrepareSQL = 'Prepare SQL';
const StrMSSQLTransIsolation = 'MSSQL TransIsolation';
function GetBlobSize: Integer;
function GetMSSQLTransIsolation: string;
function GetOSAuthentication: Boolean;
function GetPrepareSql: Boolean;
function GetSchemaOverride: string;
function GetDatabase: string;
procedure SetDatabase(const Value: string);
procedure SetBlobSize(const Value: Integer);
procedure SetMSSQLTransIsolation(const Value: string);
procedure SetOSAuthentication(const Value: Boolean);
procedure SetPrepareSql(const Value: Boolean);
procedure SetSchemaOverride(const Value: string);
function GetHostName: string;
function GetPassword: string;
function GetUserName: string;
procedure SetHostName(const Value: string);
procedure SetPassword(const Value: string);
procedure SetUserName(const Value: string);
public
constructor Create(DBXContext: TDBXContext); override;
published
property HostName: string read GetHostName write SetHostName;
property UserName: string read GetUserName write SetUserName;
property Password: string read GetPassword write SetPassword;
property SchemaOverride: string read GetSchemaOverride write SetSchemaOverride;
property BlobSize: Integer read GetBlobSize write SetBlobSize;
property MSSQLTransIsolation: string read GetMSSQLTransIsolation write SetMSSQLTransIsolation;
property OSAuthentication: Boolean read GetOSAuthentication write SetOSAuthentication;
property PrepareSQL: Boolean read GetPrepareSql write SetPrepareSql;
property Database: string read GetDatabase write SetDatabase;
end;
TDBXMSSQLDriver = class(TDBXDynalinkDriverNative)
public
constructor Create(DBXDriverDef: TDBXDriverDef); override;
end;
implementation
uses
Data.DBXCommonResStrs, Data.DBXPlatform, System.SysUtils;
const
sDriverName = 'MSSQL';
sAltDriverName = 'MSSQL9';
{ TDBXMSSQLDriver }
constructor TDBXMSSQLDriver.Create(DBXDriverDef: TDBXDriverDef);
var
Props: TDBXMSSQLProperties;
I, Index: Integer;
begin
Props := TDBXMSSQLProperties.Create(DBXDriverDef.FDBXContext);
if DBXDriverDef.FDriverProperties <> nil then
begin
for I := 0 to DBXDriverDef.FDriverProperties.Count - 1 do
begin
Index := Props.Properties.IndexOfName(DBXDriverDef.FDriverProperties.Properties.Names[I]);
if Index > -1 then
Props.Properties.Strings[Index] := DBXDriverDef.FDriverProperties.Properties.Strings[I];
end;
Props.AddUniqueProperties(DBXDriverDef.FDriverProperties.Properties);
DBXDriverDef.FDriverProperties.AddUniqueProperties(Props.Properties);
end;
inherited Create(DBXDriverDef, TDBXDynalinkDriverLoader, Props);
rcs;
end;
{ TDBXMSSQLProperties }
constructor TDBXMSSQLProperties.Create(DBXContext: TDBXContext);
begin
inherited Create(DBXContext);
Values[TDBXPropertyNames.SchemaOverride] := '%.dbo';
Values[TDBXPropertyNames.DriverUnit] := 'Data.DBXMsSQL';
Values[TDBXPropertyNames.DriverPackageLoader] := 'TDBXDynalinkDriverLoader,DBXMSSQLDriver' + PackageVersion + '.bpl';
Values[TDBXPropertyNames.DriverAssemblyLoader] := 'Borland.Data.TDBXDynalinkDriverLoader,Borland.Data.DbxCommonDriver,Version=' + AssemblyVersion + ',Culture=neutral,PublicKeyToken=' + TDBXPlatform.GetPublicKeyToken;
Values[TDBXPropertyNames.MetaDataPackageLoader] := 'TDBXMsSqlMetaDataCommandFactory,DbxMSSQLDriver' + PackageVersion + '.bpl';
Values[TDBXPropertyNames.MetaDataAssemblyLoader] := 'Borland.Data.TDBXMsSqlMetaDataCommandFactory,Borland.Data.DbxMSSQLDriver,Version=' + AssemblyVersion + ',Culture=neutral,PublicKeyToken=' + TDBXPlatform.GetPublicKeyToken;
Values[TDBXPropertyNames.GetDriverFunc] := 'getSQLDriverMSSQL';
Values[TDBXPropertyNames.LibraryName] := 'dbxmss.dll';
Values[TDBXPropertyNames.VendorLib] := 'sqlncli10.dll';
Values[TDBXPropertyNames.VendorLibWin64] := 'sqlncli10.dll';
Values[TDBXPropertyNames.HostName] := 'ServerName';
Values[TDBXPropertyNames.Database] := 'Database Name';
// Values[TDBXPropertyNames.UserName] := 'user';
// Values[TDBXPropertyNames.Password] := 'password';
Values[TDBXPropertyNames.MaxBlobSize] := '-1';
Values[TDBXPropertyNames.ErrorResourceFile] := '';
Values[TDBXDynalinkPropertyNames.LocaleCode] := '0000';
Values[TDBXPropertyNames.IsolationLevel] := 'ReadCommitted';
Values['OSAuthentication'] := 'False';
Values['PrepareSQL'] := 'True';
end;
function TDBXMSSQLProperties.GetBlobSize: Integer;
begin
Result := StrToIntDef(Values[TDBXPropertyNames.MaxBlobSize], -1);
end;
function TDBXMSSQLProperties.GetDatabase: string;
begin
Result := Values[TDBXPropertyNames.Database];
end;
function TDBXMSSQLProperties.GetHostName: string;
begin
Result := Values[TDBXPropertyNames.HostName];
end;
function TDBXMSSQLProperties.GetMSSQLTransIsolation: string;
begin
Result := Values[StrMSSQLTransIsolation];
end;
function TDBXMSSQLProperties.GetOSAuthentication: Boolean;
begin
Result := StrToBoolDef(Values[StrOSAuthentication], False);
end;
function TDBXMSSQLProperties.GetPassword: string;
begin
Result := Values[TDBXPropertyNames.Password];
end;
function TDBXMSSQLProperties.GetPrepareSql: Boolean;
begin
Result := StrToBoolDef(Values[StrPrepareSQL], False);
end;
function TDBXMSSQLProperties.GetSchemaOverride: string;
begin
Result := Values[TDBXPropertyNames.SchemaOverride];
end;
function TDBXMSSQLProperties.GetUserName: string;
begin
Result := Values[TDBXPropertyNames.UserName];
end;
procedure TDBXMSSQLProperties.SetBlobSize(const Value: Integer);
begin
Values[TDBXPropertyNames.MaxBlobSize] := IntToStr(Value);
end;
procedure TDBXMSSQLProperties.SetDatabase(const Value: string);
begin
Values[TDBXPropertyNames.Database] := Value;
end;
procedure TDBXMSSQLProperties.SetHostName(const Value: string);
begin
Values[TDBXPropertyNames.HostName] := Value;
end;
procedure TDBXMSSQLProperties.SetMSSQLTransIsolation(const Value: string);
begin
Values[StrMSSQLTransIsolation] := Value;
end;
procedure TDBXMSSQLProperties.SetOSAuthentication(const Value: Boolean);
begin
Values[StrOSAuthentication] := BoolToStr(Value, True);
end;
procedure TDBXMSSQLProperties.SetPassword(const Value: string);
begin
Values[TDBXPropertyNames.Password] := Value;
end;
procedure TDBXMSSQLProperties.SetPrepareSql(const Value: Boolean);
begin
Values[StrPrepareSql] := BoolToStr(Value, True);
end;
procedure TDBXMSSQLProperties.SetSchemaOverride(const Value: string);
begin
Values[TDBXPropertyNames.SchemaOverride] := Value;
end;
procedure TDBXMSSQLProperties.SetUserName(const Value: string);
begin
Values[TDBXPropertyNames.UserName] := Value;
end;
initialization
TDBXDriverRegistry.RegisterDriverClass(sDriverName, TDBXMSSQLDriver);
TDBXDriverRegistry.RegisterDriverClass(sAltDriverName, TDBXMSSQLDriver);
finalization
TDBXDriverRegistry.UnloadDriver(sDriverName);
TDBXDriverRegistry.UnloadDriver(sAltDriverName);
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2014-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit System.Tether.Consts;
interface
resourcestring
SProfileAlreadyRegistered = 'Profile "%s" is already registered';
SProfileNotRegistered = 'Profile "%s" is not registered';
SProtocolNotRegistered = 'Protocol "%s" is not registered';
SProfileWithoutAdapters = 'Profile "%s" without registered adapters';
SProfileWithoutProtocols = 'Profile "%s" without registered protocols';
SProfileWithoutProtocolAdapters = 'Profile "%s" without registered protocol-adapters';
SCanNotSetStorage = 'Can not set storage path. Manager already started.';
SCannotSetAllowedAdapters = 'Cannot change AllowedAdapters, Manager already started.';
SManagerUDPCreation = 'Error Opening UDP Server';
SManagerNetworkCreation = 'Error Opening Network Server';
SManagerBluetoothCreation = 'Error Opening Bluetooth Server';
SProtocolCreation = 'Error Opening %s Server';
SInvalidBluetoothTargetFormat = 'Invalid Bluetooth Target format "%s", expected Device$GUID';
SInvalidNetworkTargetFormat = 'Invalid Network Target format "%s", expected IP$Port';
SNoConnections = 'No available connections to %s';
SCanNotGetConnection = 'Can''t get a connection to profile %s';
SCanNotConnect = 'Can''t connect to profile %s';
SNoProfile = 'Can''t find profile %s';
SProfileNotConnected = 'Profile %s is not connected';
SCanNotSendFile = 'Can''t send file %s';
SNoResourceList = 'Can''t find resource list for profile %s';
SRemoteResNotFound = 'Remote resource not found';
SNoProfileFor = 'Can''t find profile for resource %s';
SNoProfileForAction = 'Can''t find profile for action %s';
SNoProfileCommand = 'AppProfile Command not Handled: "%s"';
SNoManager = 'Manager property not assigned';
SNoResourceValue = 'No resource value';
SLocalAction = 'Action %d';
SCustomLocalAction = 'Custom Local Item %d';
SLocalResource = 'Resource %d';
SCanNotSendResource = 'Can''t send resource %s';
SNoProtocolAndAdapter = 'You need to add a protocol and an adapter connecting to %s';
SDisabledManager = 'Manager %s is disabled';
// Common constants for tethering
const
TetheringSeparator = '|';
TetheringCommandSeparator = '~';
TetheringBlockSeparator: Char = #10; // LF
TetheringConnectionSeparator = '$';
implementation
end.
|
{$INCLUDE ..\cDefines.inc}
unit cSysComponents;
interface
uses
{ Delphi }
Classes,
Graphics,
StdCtrls,
{ Fundamentals }
cLog;
{ }
{ TfndMemoLog }
{ }
type
TfndMemoLogGetLogColorEvent = procedure (Sender: TObject; LogClass: TLogClass;
LogMsg: String; var Color: TColor) of object;
TfndMemoLog = class(TLog)
protected
FLogToMemo : TCustomMemo;
FMaxMemoLines : Integer;
FOnGetLogColor : TfndMemoLogGetLogColorEvent;
procedure Init; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
procedure TriggerLogMsg(const Sender: TObject; const LogClass: TLogClass;
const LogMsg: String); override;
published
property OnLog;
property OnEditMessage;
property OnLogFile;
property OnGetLogColor: TfndMemoLogGetLogColorEvent read FOnGetLogColor write FOnGetLogColor;
property LogFileName;
property LogOptions;
property LogTo;
property LogToMemo: TCustomMemo read FLogToMemo write FLogToMemo;
property MaxMemoLines: Integer read FMaxMemoLines write FMaxMemoLines default 1024;
end;
{ }
{ Component Register }
{ }
procedure Register;
implementation
uses
{ Delphi }
Messages,
ComCtrls,
{ Fundamentals }
cUtils,
cWindows,
cThreads;
{ }
{ TfndMemoLog }
{ }
procedure TfndMemoLog.Init;
begin
inherited Init;
FMaxMemoLines := 1024;
end;
procedure TfndMemoLog.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if Operation = opRemove then
if AComponent = FLogToMemo then
FLogToMemo := nil;
end;
procedure TfndMemoLog.TriggerLogMsg(const Sender: TObject;
const LogClass: TLogClass; const LogMsg: String);
var Col : TColor;
R : TCustomRichEdit;
L : Integer;
begin
inherited TriggerLogMsg(Sender, LogClass, LogMsg);
if Assigned(FLogToMemo) then
try
// Log to memo
if FLogToMemo is TCustomRichEdit then
begin
Col := clBlack;
if Assigned(FOnGetLogColor) then
FOnGetLogColor(Sender, LogClass, LogMsg, Col);
R := TCustomRichEdit(FLogToMemo);
L := Length(R.Text);
R.SelStart := L;
R.SelAttributes.Color := Col;
R.SelText := iif(L > 0, #13#10, '') + LogMsg;
end else
begin
L := Length(FLogToMemo.Text);
FLogToMemo.SelStart := L;
FLogToMemo.SelText := iif(L > 0, #13#10, '') + LogMsg;
end;
// Delete lines
if FMaxMemoLines > 0 then
While FLogToMemo.Lines.Count > FMaxMemoLines do
FLogToMemo.Lines.Delete(0);
// Scroll to bottom
FLogToMemo.Perform(EM_LineScroll, 0, FLogToMemo.Lines.Count - 1);
except
if not (loIgnoreLogFailure in FLogOptions) then
raise;
end;
end;
{ }
{ Component Register }
{ }
procedure Register;
begin
RegisterComponents('Fundamentals', [TfndWindowHandle, TfndTimerHandle,
TfndLog, TfndMemoLog, TfndThread]);
end;
end.
|
unit Hash_RipeMD;
{$I TinyDB.INC}
interface
uses Classes, HashBase, Hash_MD;
type
THash_RipeMD128 = class(THash_MD4) {RACE Integrity Primitives Evaluation Message Digest}
protected
class function TestVector: Pointer; override;
procedure Transform(Buffer: PIntArray); override;
end;
THash_RipeMD160 = class(THash_MD4)
protected
class function TestVector: Pointer; override;
procedure Transform(Buffer: PIntArray); override;
public
{DigestKey-Size 160 bit}
class function DigestKeySize: Integer; override;
end;
THash_RipeMD256 = class(THash_MD4)
protected
class function TestVector: Pointer; override;
procedure Transform(Buffer: PIntArray); override;
public
{DigestKey-Size 256 bit}
class function DigestKeySize: Integer; override;
procedure Init; override;
end;
THash_RipeMD320 = class(THash_MD4)
protected
class function TestVector: Pointer; override;
procedure Transform(Buffer: PIntArray); override;
public
{DigestKey-Size 320 bit}
class function DigestKeySize: Integer; override;
end;
implementation
uses SysUtils;
class function THash_RipeMD128.TestVector: Pointer;
asm
MOV EAX,OFFSET @Vector
RET
@Vector: DB 0CFh,0A0h,032h,0CFh,0D0h,08Fh,087h,03Ah
DB 078h,0DFh,013h,0E7h,0EBh,0CDh,098h,00Fh
end;
procedure THash_RipeMD128.Transform(Buffer: PIntArray);
var
A1, B1, C1, D1: LongWord;
A2, B2, C2, D2: LongWord;
begin
A1 := FDigest[0];
B1 := FDigest[1];
C1 := FDigest[2];
D1 := FDigest[3];
A2 := A1;
B2 := B1;
C2 := C1;
D2 := D1;
Inc(A1, B1 xor C1 xor D1 + Buffer[ 0]); A1 := A1 shl 11 or A1 shr 21;
Inc(D1, A1 xor B1 xor C1 + Buffer[ 1]); D1 := D1 shl 14 or D1 shr 18;
Inc(C1, D1 xor A1 xor B1 + Buffer[ 2]); C1 := C1 shl 15 or C1 shr 17;
Inc(B1, C1 xor D1 xor A1 + Buffer[ 3]); B1 := B1 shl 12 or B1 shr 20;
Inc(A1, B1 xor C1 xor D1 + Buffer[ 4]); A1 := A1 shl 5 or A1 shr 27;
Inc(D1, A1 xor B1 xor C1 + Buffer[ 5]); D1 := D1 shl 8 or D1 shr 24;
Inc(C1, D1 xor A1 xor B1 + Buffer[ 6]); C1 := C1 shl 7 or C1 shr 25;
Inc(B1, C1 xor D1 xor A1 + Buffer[ 7]); B1 := B1 shl 9 or B1 shr 23;
Inc(A1, B1 xor C1 xor D1 + Buffer[ 8]); A1 := A1 shl 11 or A1 shr 21;
Inc(D1, A1 xor B1 xor C1 + Buffer[ 9]); D1 := D1 shl 13 or D1 shr 19;
Inc(C1, D1 xor A1 xor B1 + Buffer[10]); C1 := C1 shl 14 or C1 shr 18;
Inc(B1, C1 xor D1 xor A1 + Buffer[11]); B1 := B1 shl 15 or B1 shr 17;
Inc(A1, B1 xor C1 xor D1 + Buffer[12]); A1 := A1 shl 6 or A1 shr 26;
Inc(D1, A1 xor B1 xor C1 + Buffer[13]); D1 := D1 shl 7 or D1 shr 25;
Inc(C1, D1 xor A1 xor B1 + Buffer[14]); C1 := C1 shl 9 or C1 shr 23;
Inc(B1, C1 xor D1 xor A1 + Buffer[15]); B1 := B1 shl 8 or B1 shr 24;
Inc(A1, B1 and C1 or not B1 and D1 + Buffer[ 7] + $5A827999); A1 := A1 shl 7 or A1 shr 25;
Inc(D1, A1 and B1 or not A1 and C1 + Buffer[ 4] + $5A827999); D1 := D1 shl 6 or D1 shr 26;
Inc(C1, D1 and A1 or not D1 and B1 + Buffer[13] + $5A827999); C1 := C1 shl 8 or C1 shr 24;
Inc(B1, C1 and D1 or not C1 and A1 + Buffer[ 1] + $5A827999); B1 := B1 shl 13 or B1 shr 19;
Inc(A1, B1 and C1 or not B1 and D1 + Buffer[10] + $5A827999); A1 := A1 shl 11 or A1 shr 21;
Inc(D1, A1 and B1 or not A1 and C1 + Buffer[ 6] + $5A827999); D1 := D1 shl 9 or D1 shr 23;
Inc(C1, D1 and A1 or not D1 and B1 + Buffer[15] + $5A827999); C1 := C1 shl 7 or C1 shr 25;
Inc(B1, C1 and D1 or not C1 and A1 + Buffer[ 3] + $5A827999); B1 := B1 shl 15 or B1 shr 17;
Inc(A1, B1 and C1 or not B1 and D1 + Buffer[12] + $5A827999); A1 := A1 shl 7 or A1 shr 25;
Inc(D1, A1 and B1 or not A1 and C1 + Buffer[ 0] + $5A827999); D1 := D1 shl 12 or D1 shr 20;
Inc(C1, D1 and A1 or not D1 and B1 + Buffer[ 9] + $5A827999); C1 := C1 shl 15 or C1 shr 17;
Inc(B1, C1 and D1 or not C1 and A1 + Buffer[ 5] + $5A827999); B1 := B1 shl 9 or B1 shr 23;
Inc(A1, B1 and C1 or not B1 and D1 + Buffer[ 2] + $5A827999); A1 := A1 shl 11 or A1 shr 21;
Inc(D1, A1 and B1 or not A1 and C1 + Buffer[14] + $5A827999); D1 := D1 shl 7 or D1 shr 25;
Inc(C1, D1 and A1 or not D1 and B1 + Buffer[11] + $5A827999); C1 := C1 shl 13 or C1 shr 19;
Inc(B1, C1 and D1 or not C1 and A1 + Buffer[ 8] + $5A827999); B1 := B1 shl 12 or B1 shr 20;
Inc(A1, (B1 or not C1) xor D1 + Buffer[ 3] + $6ED9EBA1); A1 := A1 shl 11 or A1 shr 21;
Inc(D1, (A1 or not B1) xor C1 + Buffer[10] + $6ED9EBA1); D1 := D1 shl 13 or D1 shr 19;
Inc(C1, (D1 or not A1) xor B1 + Buffer[14] + $6ED9EBA1); C1 := C1 shl 6 or C1 shr 26;
Inc(B1, (C1 or not D1) xor A1 + Buffer[ 4] + $6ED9EBA1); B1 := B1 shl 7 or B1 shr 25;
Inc(A1, (B1 or not C1) xor D1 + Buffer[ 9] + $6ED9EBA1); A1 := A1 shl 14 or A1 shr 18;
Inc(D1, (A1 or not B1) xor C1 + Buffer[15] + $6ED9EBA1); D1 := D1 shl 9 or D1 shr 23;
Inc(C1, (D1 or not A1) xor B1 + Buffer[ 8] + $6ED9EBA1); C1 := C1 shl 13 or C1 shr 19;
Inc(B1, (C1 or not D1) xor A1 + Buffer[ 1] + $6ED9EBA1); B1 := B1 shl 15 or B1 shr 17;
Inc(A1, (B1 or not C1) xor D1 + Buffer[ 2] + $6ED9EBA1); A1 := A1 shl 14 or A1 shr 18;
Inc(D1, (A1 or not B1) xor C1 + Buffer[ 7] + $6ED9EBA1); D1 := D1 shl 8 or D1 shr 24;
Inc(C1, (D1 or not A1) xor B1 + Buffer[ 0] + $6ED9EBA1); C1 := C1 shl 13 or C1 shr 19;
Inc(B1, (C1 or not D1) xor A1 + Buffer[ 6] + $6ED9EBA1); B1 := B1 shl 6 or B1 shr 26;
Inc(A1, (B1 or not C1) xor D1 + Buffer[13] + $6ED9EBA1); A1 := A1 shl 5 or A1 shr 27;
Inc(D1, (A1 or not B1) xor C1 + Buffer[11] + $6ED9EBA1); D1 := D1 shl 12 or D1 shr 20;
Inc(C1, (D1 or not A1) xor B1 + Buffer[ 5] + $6ED9EBA1); C1 := C1 shl 7 or C1 shr 25;
Inc(B1, (C1 or not D1) xor A1 + Buffer[12] + $6ED9EBA1); B1 := B1 shl 5 or B1 shr 27;
Inc(A1, B1 and D1 or C1 and not D1 + Buffer[ 1] + $8F1BBCDC); A1 := A1 shl 11 or A1 shr 21;
Inc(D1, A1 and C1 or B1 and not C1 + Buffer[ 9] + $8F1BBCDC); D1 := D1 shl 12 or D1 shr 20;
Inc(C1, D1 and B1 or A1 and not B1 + Buffer[11] + $8F1BBCDC); C1 := C1 shl 14 or C1 shr 18;
Inc(B1, C1 and A1 or D1 and not A1 + Buffer[10] + $8F1BBCDC); B1 := B1 shl 15 or B1 shr 17;
Inc(A1, B1 and D1 or C1 and not D1 + Buffer[ 0] + $8F1BBCDC); A1 := A1 shl 14 or A1 shr 18;
Inc(D1, A1 and C1 or B1 and not C1 + Buffer[ 8] + $8F1BBCDC); D1 := D1 shl 15 or D1 shr 17;
Inc(C1, D1 and B1 or A1 and not B1 + Buffer[12] + $8F1BBCDC); C1 := C1 shl 9 or C1 shr 23;
Inc(B1, C1 and A1 or D1 and not A1 + Buffer[ 4] + $8F1BBCDC); B1 := B1 shl 8 or B1 shr 24;
Inc(A1, B1 and D1 or C1 and not D1 + Buffer[13] + $8F1BBCDC); A1 := A1 shl 9 or A1 shr 23;
Inc(D1, A1 and C1 or B1 and not C1 + Buffer[ 3] + $8F1BBCDC); D1 := D1 shl 14 or D1 shr 18;
Inc(C1, D1 and B1 or A1 and not B1 + Buffer[ 7] + $8F1BBCDC); C1 := C1 shl 5 or C1 shr 27;
Inc(B1, C1 and A1 or D1 and not A1 + Buffer[15] + $8F1BBCDC); B1 := B1 shl 6 or B1 shr 26;
Inc(A1, B1 and D1 or C1 and not D1 + Buffer[14] + $8F1BBCDC); A1 := A1 shl 8 or A1 shr 24;
Inc(D1, A1 and C1 or B1 and not C1 + Buffer[ 5] + $8F1BBCDC); D1 := D1 shl 6 or D1 shr 26;
Inc(C1, D1 and B1 or A1 and not B1 + Buffer[ 6] + $8F1BBCDC); C1 := C1 shl 5 or C1 shr 27;
Inc(B1, C1 and A1 or D1 and not A1 + Buffer[ 2] + $8F1BBCDC); B1 := B1 shl 12 or B1 shr 20;
Inc(A2, B2 and D2 or C2 and not D2 + Buffer[ 5] + $50A28BE6); A2 := A2 shl 8 or A2 shr 24;
Inc(D2, A2 and C2 or B2 and not C2 + Buffer[14] + $50A28BE6); D2 := D2 shl 9 or D2 shr 23;
Inc(C2, D2 and B2 or A2 and not B2 + Buffer[ 7] + $50A28BE6); C2 := C2 shl 9 or C2 shr 23;
Inc(B2, C2 and A2 or D2 and not A2 + Buffer[ 0] + $50A28BE6); B2 := B2 shl 11 or B2 shr 21;
Inc(A2, B2 and D2 or C2 and not D2 + Buffer[ 9] + $50A28BE6); A2 := A2 shl 13 or A2 shr 19;
Inc(D2, A2 and C2 or B2 and not C2 + Buffer[ 2] + $50A28BE6); D2 := D2 shl 15 or D2 shr 17;
Inc(C2, D2 and B2 or A2 and not B2 + Buffer[11] + $50A28BE6); C2 := C2 shl 15 or C2 shr 17;
Inc(B2, C2 and A2 or D2 and not A2 + Buffer[ 4] + $50A28BE6); B2 := B2 shl 5 or B2 shr 27;
Inc(A2, B2 and D2 or C2 and not D2 + Buffer[13] + $50A28BE6); A2 := A2 shl 7 or A2 shr 25;
Inc(D2, A2 and C2 or B2 and not C2 + Buffer[ 6] + $50A28BE6); D2 := D2 shl 7 or D2 shr 25;
Inc(C2, D2 and B2 or A2 and not B2 + Buffer[15] + $50A28BE6); C2 := C2 shl 8 or C2 shr 24;
Inc(B2, C2 and A2 or D2 and not A2 + Buffer[ 8] + $50A28BE6); B2 := B2 shl 11 or B2 shr 21;
Inc(A2, B2 and D2 or C2 and not D2 + Buffer[ 1] + $50A28BE6); A2 := A2 shl 14 or A2 shr 18;
Inc(D2, A2 and C2 or B2 and not C2 + Buffer[10] + $50A28BE6); D2 := D2 shl 14 or D2 shr 18;
Inc(C2, D2 and B2 or A2 and not B2 + Buffer[ 3] + $50A28BE6); C2 := C2 shl 12 or C2 shr 20;
Inc(B2, C2 and A2 or D2 and not A2 + Buffer[12] + $50A28BE6); B2 := B2 shl 6 or B2 shr 26;
Inc(A2, (B2 or not C2) xor D2 + Buffer[ 6] + $5C4DD124); A2 := A2 shl 9 or A2 shr 23;
Inc(D2, (A2 or not B2) xor C2 + Buffer[11] + $5C4DD124); D2 := D2 shl 13 or D2 shr 19;
Inc(C2, (D2 or not A2) xor B2 + Buffer[ 3] + $5C4DD124); C2 := C2 shl 15 or C2 shr 17;
Inc(B2, (C2 or not D2) xor A2 + Buffer[ 7] + $5C4DD124); B2 := B2 shl 7 or B2 shr 25;
Inc(A2, (B2 or not C2) xor D2 + Buffer[ 0] + $5C4DD124); A2 := A2 shl 12 or A2 shr 20;
Inc(D2, (A2 or not B2) xor C2 + Buffer[13] + $5C4DD124); D2 := D2 shl 8 or D2 shr 24;
Inc(C2, (D2 or not A2) xor B2 + Buffer[ 5] + $5C4DD124); C2 := C2 shl 9 or C2 shr 23;
Inc(B2, (C2 or not D2) xor A2 + Buffer[10] + $5C4DD124); B2 := B2 shl 11 or B2 shr 21;
Inc(A2, (B2 or not C2) xor D2 + Buffer[14] + $5C4DD124); A2 := A2 shl 7 or A2 shr 25;
Inc(D2, (A2 or not B2) xor C2 + Buffer[15] + $5C4DD124); D2 := D2 shl 7 or D2 shr 25;
Inc(C2, (D2 or not A2) xor B2 + Buffer[ 8] + $5C4DD124); C2 := C2 shl 12 or C2 shr 20;
Inc(B2, (C2 or not D2) xor A2 + Buffer[12] + $5C4DD124); B2 := B2 shl 7 or B2 shr 25;
Inc(A2, (B2 or not C2) xor D2 + Buffer[ 4] + $5C4DD124); A2 := A2 shl 6 or A2 shr 26;
Inc(D2, (A2 or not B2) xor C2 + Buffer[ 9] + $5C4DD124); D2 := D2 shl 15 or D2 shr 17;
Inc(C2, (D2 or not A2) xor B2 + Buffer[ 1] + $5C4DD124); C2 := C2 shl 13 or C2 shr 19;
Inc(B2, (C2 or not D2) xor A2 + Buffer[ 2] + $5C4DD124); B2 := B2 shl 11 or B2 shr 21;
Inc(A2, B2 and C2 or not B2 and D2 + Buffer[15] + $6D703EF3); A2 := A2 shl 9 or A2 shr 23;
Inc(D2, A2 and B2 or not A2 and C2 + Buffer[ 5] + $6D703EF3); D2 := D2 shl 7 or D2 shr 25;
Inc(C2, D2 and A2 or not D2 and B2 + Buffer[ 1] + $6D703EF3); C2 := C2 shl 15 or C2 shr 17;
Inc(B2, C2 and D2 or not C2 and A2 + Buffer[ 3] + $6D703EF3); B2 := B2 shl 11 or B2 shr 21;
Inc(A2, B2 and C2 or not B2 and D2 + Buffer[ 7] + $6D703EF3); A2 := A2 shl 8 or A2 shr 24;
Inc(D2, A2 and B2 or not A2 and C2 + Buffer[14] + $6D703EF3); D2 := D2 shl 6 or D2 shr 26;
Inc(C2, D2 and A2 or not D2 and B2 + Buffer[ 6] + $6D703EF3); C2 := C2 shl 6 or C2 shr 26;
Inc(B2, C2 and D2 or not C2 and A2 + Buffer[ 9] + $6D703EF3); B2 := B2 shl 14 or B2 shr 18;
Inc(A2, B2 and C2 or not B2 and D2 + Buffer[11] + $6D703EF3); A2 := A2 shl 12 or A2 shr 20;
Inc(D2, A2 and B2 or not A2 and C2 + Buffer[ 8] + $6D703EF3); D2 := D2 shl 13 or D2 shr 19;
Inc(C2, D2 and A2 or not D2 and B2 + Buffer[12] + $6D703EF3); C2 := C2 shl 5 or C2 shr 27;
Inc(B2, C2 and D2 or not C2 and A2 + Buffer[ 2] + $6D703EF3); B2 := B2 shl 14 or B2 shr 18;
Inc(A2, B2 and C2 or not B2 and D2 + Buffer[10] + $6D703EF3); A2 := A2 shl 13 or A2 shr 19;
Inc(D2, A2 and B2 or not A2 and C2 + Buffer[ 0] + $6D703EF3); D2 := D2 shl 13 or D2 shr 19;
Inc(C2, D2 and A2 or not D2 and B2 + Buffer[ 4] + $6D703EF3); C2 := C2 shl 7 or C2 shr 25;
Inc(B2, C2 and D2 or not C2 and A2 + Buffer[13] + $6D703EF3); B2 := B2 shl 5 or B2 shr 27;
Inc(A2, B2 xor C2 xor D2 + Buffer[ 8]); A2 := A2 shl 15 or A2 shr 17;
Inc(D2, A2 xor B2 xor C2 + Buffer[ 6]); D2 := D2 shl 5 or D2 shr 27;
Inc(C2, D2 xor A2 xor B2 + Buffer[ 4]); C2 := C2 shl 8 or C2 shr 24;
Inc(B2, C2 xor D2 xor A2 + Buffer[ 1]); B2 := B2 shl 11 or B2 shr 21;
Inc(A2, B2 xor C2 xor D2 + Buffer[ 3]); A2 := A2 shl 14 or A2 shr 18;
Inc(D2, A2 xor B2 xor C2 + Buffer[11]); D2 := D2 shl 14 or D2 shr 18;
Inc(C2, D2 xor A2 xor B2 + Buffer[15]); C2 := C2 shl 6 or C2 shr 26;
Inc(B2, C2 xor D2 xor A2 + Buffer[ 0]); B2 := B2 shl 14 or B2 shr 18;
Inc(A2, B2 xor C2 xor D2 + Buffer[ 5]); A2 := A2 shl 6 or A2 shr 26;
Inc(D2, A2 xor B2 xor C2 + Buffer[12]); D2 := D2 shl 9 or D2 shr 23;
Inc(C2, D2 xor A2 xor B2 + Buffer[ 2]); C2 := C2 shl 12 or C2 shr 20;
Inc(B2, C2 xor D2 xor A2 + Buffer[13]); B2 := B2 shl 9 or B2 shr 23;
Inc(A2, B2 xor C2 xor D2 + Buffer[ 9]); A2 := A2 shl 12 or A2 shr 20;
Inc(D2, A2 xor B2 xor C2 + Buffer[ 7]); D2 := D2 shl 5 or D2 shr 27;
Inc(C2, D2 xor A2 xor B2 + Buffer[10]); C2 := C2 shl 15 or C2 shr 17;
Inc(B2, C2 xor D2 xor A2 + Buffer[14]); B2 := B2 shl 8 or B2 shr 24;
Inc(D2, C1 + FDigest[1]);
FDigest[1] := FDigest[2] + D1 + A2;
FDigest[2] := FDigest[3] + A1 + B2;
FDigest[3] := FDIgest[0] + B1 + C2;
FDigest[0] := D2;
end;
class function THash_RipeMD160.TestVector: Pointer;
asm
MOV EAX,OFFSET @Vector
RET
@Vector: DB 019h,054h,0DEh,0BCh,01Bh,055h,035h,030h
DB 008h,01Dh,09Bh,080h,070h,0A0h,0F2h,04Ah
DB 09Dh,0F7h,034h,004h
end;
procedure THash_RipeMD160.Transform(Buffer: PIntArray);
var
A1, B1, C1, D1, E1: LongWord;
A, B, C, D, E: LongWord;
begin
A := FDigest[0];
B := FDigest[1];
C := FDigest[2];
D := FDigest[3];
E := FDigest[4];
Inc(A, Buffer[ 0] + (B xor C xor D)); A := A shl 11 or A shr 21 + E; C := C shl 10 or C shr 22;
Inc(E, Buffer[ 1] + (A xor B xor C)); E := E shl 14 or E shr 18 + D; B := B shl 10 or B shr 22;
Inc(D, Buffer[ 2] + (E xor A xor B)); D := D shl 15 or D shr 17 + C; A := A shl 10 or A shr 22;
Inc(C, Buffer[ 3] + (D xor E xor A)); C := C shl 12 or C shr 20 + B; E := E shl 10 or E shr 22;
Inc(B, Buffer[ 4] + (C xor D xor E)); B := B shl 5 or B shr 27 + A; D := D shl 10 or D shr 22;
Inc(A, Buffer[ 5] + (B xor C xor D)); A := A shl 8 or A shr 24 + E; C := C shl 10 or C shr 22;
Inc(E, Buffer[ 6] + (A xor B xor C)); E := E shl 7 or E shr 25 + D; B := B shl 10 or B shr 22;
Inc(D, Buffer[ 7] + (E xor A xor B)); D := D shl 9 or D shr 23 + C; A := A shl 10 or A shr 22;
Inc(C, Buffer[ 8] + (D xor E xor A)); C := C shl 11 or C shr 21 + B; E := E shl 10 or E shr 22;
Inc(B, Buffer[ 9] + (C xor D xor E)); B := B shl 13 or B shr 19 + A; D := D shl 10 or D shr 22;
Inc(A, Buffer[10] + (B xor C xor D)); A := A shl 14 or A shr 18 + E; C := C shl 10 or C shr 22;
Inc(E, Buffer[11] + (A xor B xor C)); E := E shl 15 or E shr 17 + D; B := B shl 10 or B shr 22;
Inc(D, Buffer[12] + (E xor A xor B)); D := D shl 6 or D shr 26 + C; A := A shl 10 or A shr 22;
Inc(C, Buffer[13] + (D xor E xor A)); C := C shl 7 or C shr 25 + B; E := E shl 10 or E shr 22;
Inc(B, Buffer[14] + (C xor D xor E)); B := B shl 9 or B shr 23 + A; D := D shl 10 or D shr 22;
Inc(A, Buffer[15] + (B xor C xor D)); A := A shl 8 or A shr 24 + E; C := C shl 10 or C shr 22;
Inc(E, Buffer[ 7] + $5A827999 + ((A and B) or (not A and C))); E := E shl 7 or E shr 25 + D; B := B shl 10 or B shr 22;
Inc(D, Buffer[ 4] + $5A827999 + ((E and A) or (not E and B))); D := D shl 6 or D shr 26 + C; A := A shl 10 or A shr 22;
Inc(C, Buffer[13] + $5A827999 + ((D and E) or (not D and A))); C := C shl 8 or C shr 24 + B; E := E shl 10 or E shr 22;
Inc(B, Buffer[ 1] + $5A827999 + ((C and D) or (not C and E))); B := B shl 13 or B shr 19 + A; D := D shl 10 or D shr 22;
Inc(A, Buffer[10] + $5A827999 + ((B and C) or (not B and D))); A := A shl 11 or A shr 21 + E; C := C shl 10 or C shr 22;
Inc(E, Buffer[ 6] + $5A827999 + ((A and B) or (not A and C))); E := E shl 9 or E shr 23 + D; B := B shl 10 or B shr 22;
Inc(D, Buffer[15] + $5A827999 + ((E and A) or (not E and B))); D := D shl 7 or D shr 25 + C; A := A shl 10 or A shr 22;
Inc(C, Buffer[ 3] + $5A827999 + ((D and E) or (not D and A))); C := C shl 15 or C shr 17 + B; E := E shl 10 or E shr 22;
Inc(B, Buffer[12] + $5A827999 + ((C and D) or (not C and E))); B := B shl 7 or B shr 25 + A; D := D shl 10 or D shr 22;
Inc(A, Buffer[ 0] + $5A827999 + ((B and C) or (not B and D))); A := A shl 12 or A shr 20 + E; C := C shl 10 or C shr 22;
Inc(E, Buffer[ 9] + $5A827999 + ((A and B) or (not A and C))); E := E shl 15 or E shr 17 + D; B := B shl 10 or B shr 22;
Inc(D, Buffer[ 5] + $5A827999 + ((E and A) or (not E and B))); D := D shl 9 or D shr 23 + C; A := A shl 10 or A shr 22;
Inc(C, Buffer[ 2] + $5A827999 + ((D and E) or (not D and A))); C := C shl 11 or C shr 21 + B; E := E shl 10 or E shr 22;
Inc(B, Buffer[14] + $5A827999 + ((C and D) or (not C and E))); B := B shl 7 or B shr 25 + A; D := D shl 10 or D shr 22;
Inc(A, Buffer[11] + $5A827999 + ((B and C) or (not B and D))); A := A shl 13 or A shr 19 + E; C := C shl 10 or C shr 22;
Inc(E, Buffer[ 8] + $5A827999 + ((A and B) or (not A and C))); E := E shl 12 or E shr 20 + D; B := B shl 10 or B shr 22;
Inc(D, Buffer[ 3] + $6ED9EBA1 + ((E or not A) xor B)); D := D shl 11 or D shr 21 + C; A := A shl 10 or A shr 22;
Inc(C, Buffer[10] + $6ED9EBA1 + ((D or not E) xor A)); C := C shl 13 or C shr 19 + B; E := E shl 10 or E shr 22;
Inc(B, Buffer[14] + $6ED9EBA1 + ((C or not D) xor E)); B := B shl 6 or B shr 26 + A; D := D shl 10 or D shr 22;
Inc(A, Buffer[ 4] + $6ED9EBA1 + ((B or not C) xor D)); A := A shl 7 or A shr 25 + E; C := C shl 10 or C shr 22;
Inc(E, Buffer[ 9] + $6ED9EBA1 + ((A or not B) xor C)); E := E shl 14 or E shr 18 + D; B := B shl 10 or B shr 22;
Inc(D, Buffer[15] + $6ED9EBA1 + ((E or not A) xor B)); D := D shl 9 or D shr 23 + C; A := A shl 10 or A shr 22;
Inc(C, Buffer[ 8] + $6ED9EBA1 + ((D or not E) xor A)); C := C shl 13 or C shr 19 + B; E := E shl 10 or E shr 22;
Inc(B, Buffer[ 1] + $6ED9EBA1 + ((C or not D) xor E)); B := B shl 15 or B shr 17 + A; D := D shl 10 or D shr 22;
Inc(A, Buffer[ 2] + $6ED9EBA1 + ((B or not C) xor D)); A := A shl 14 or A shr 18 + E; C := C shl 10 or C shr 22;
Inc(E, Buffer[ 7] + $6ED9EBA1 + ((A or not B) xor C)); E := E shl 8 or E shr 24 + D; B := B shl 10 or B shr 22;
Inc(D, Buffer[ 0] + $6ED9EBA1 + ((E or not A) xor B)); D := D shl 13 or D shr 19 + C; A := A shl 10 or A shr 22;
Inc(C, Buffer[ 6] + $6ED9EBA1 + ((D or not E) xor A)); C := C shl 6 or C shr 26 + B; E := E shl 10 or E shr 22;
Inc(B, Buffer[13] + $6ED9EBA1 + ((C or not D) xor E)); B := B shl 5 or B shr 27 + A; D := D shl 10 or D shr 22;
Inc(A, Buffer[11] + $6ED9EBA1 + ((B or not C) xor D)); A := A shl 12 or A shr 20 + E; C := C shl 10 or C shr 22;
Inc(E, Buffer[ 5] + $6ED9EBA1 + ((A or not B) xor C)); E := E shl 7 or E shr 25 + D; B := B shl 10 or B shr 22;
Inc(D, Buffer[12] + $6ED9EBA1 + ((E or not A) xor B)); D := D shl 5 or D shr 27 + C; A := A shl 10 or A shr 22;
Inc(C, Buffer[ 1] + $8F1BBCDC + ((D and A) or (E and not A))); C := C shl 11 or C shr 21 + B; E := E shl 10 or E shr 22;
Inc(B, Buffer[ 9] + $8F1BBCDC + ((C and E) or (D and not E))); B := B shl 12 or B shr 20 + A; D := D shl 10 or D shr 22;
Inc(A, Buffer[11] + $8F1BBCDC + ((B and D) or (C and not D))); A := A shl 14 or A shr 18 + E; C := C shl 10 or C shr 22;
Inc(E, Buffer[10] + $8F1BBCDC + ((A and C) or (B and not C))); E := E shl 15 or E shr 17 + D; B := B shl 10 or B shr 22;
Inc(D, Buffer[ 0] + $8F1BBCDC + ((E and B) or (A and not B))); D := D shl 14 or D shr 18 + C; A := A shl 10 or A shr 22;
Inc(C, Buffer[ 8] + $8F1BBCDC + ((D and A) or (E and not A))); C := C shl 15 or C shr 17 + B; E := E shl 10 or E shr 22;
Inc(B, Buffer[12] + $8F1BBCDC + ((C and E) or (D and not E))); B := B shl 9 or B shr 23 + A; D := D shl 10 or D shr 22;
Inc(A, Buffer[ 4] + $8F1BBCDC + ((B and D) or (C and not D))); A := A shl 8 or A shr 24 + E; C := C shl 10 or C shr 22;
Inc(E, Buffer[13] + $8F1BBCDC + ((A and C) or (B and not C))); E := E shl 9 or E shr 23 + D; B := B shl 10 or B shr 22;
Inc(D, Buffer[ 3] + $8F1BBCDC + ((E and B) or (A and not B))); D := D shl 14 or D shr 18 + C; A := A shl 10 or A shr 22;
Inc(C, Buffer[ 7] + $8F1BBCDC + ((D and A) or (E and not A))); C := C shl 5 or C shr 27 + B; E := E shl 10 or E shr 22;
Inc(B, Buffer[15] + $8F1BBCDC + ((C and E) or (D and not E))); B := B shl 6 or B shr 26 + A; D := D shl 10 or D shr 22;
Inc(A, Buffer[14] + $8F1BBCDC + ((B and D) or (C and not D))); A := A shl 8 or A shr 24 + E; C := C shl 10 or C shr 22;
Inc(E, Buffer[ 5] + $8F1BBCDC + ((A and C) or (B and not C))); E := E shl 6 or E shr 26 + D; B := B shl 10 or B shr 22;
Inc(D, Buffer[ 6] + $8F1BBCDC + ((E and B) or (A and not B))); D := D shl 5 or D shr 27 + C; A := A shl 10 or A shr 22;
Inc(C, Buffer[ 2] + $8F1BBCDC + ((D and A) or (E and not A))); C := C shl 12 or C shr 20 + B; E := E shl 10 or E shr 22;
Inc(B, Buffer[ 4] + $A953FD4E + (C xor (D or not E))); B := B shl 9 or B shr 23 + A; D := D shl 10 or D shr 22;
Inc(A, Buffer[ 0] + $A953FD4E + (B xor (C or not D))); A := A shl 15 or A shr 17 + E; C := C shl 10 or C shr 22;
Inc(E, Buffer[ 5] + $A953FD4E + (A xor (B or not C))); E := E shl 5 or E shr 27 + D; B := B shl 10 or B shr 22;
Inc(D, Buffer[ 9] + $A953FD4E + (E xor (A or not B))); D := D shl 11 or D shr 21 + C; A := A shl 10 or A shr 22;
Inc(C, Buffer[ 7] + $A953FD4E + (D xor (E or not A))); C := C shl 6 or C shr 26 + B; E := E shl 10 or E shr 22;
Inc(B, Buffer[12] + $A953FD4E + (C xor (D or not E))); B := B shl 8 or B shr 24 + A; D := D shl 10 or D shr 22;
Inc(A, Buffer[ 2] + $A953FD4E + (B xor (C or not D))); A := A shl 13 or A shr 19 + E; C := C shl 10 or C shr 22;
Inc(E, Buffer[10] + $A953FD4E + (A xor (B or not C))); E := E shl 12 or E shr 20 + D; B := B shl 10 or B shr 22;
Inc(D, Buffer[14] + $A953FD4E + (E xor (A or not B))); D := D shl 5 or D shr 27 + C; A := A shl 10 or A shr 22;
Inc(C, Buffer[ 1] + $A953FD4E + (D xor (E or not A))); C := C shl 12 or C shr 20 + B; E := E shl 10 or E shr 22;
Inc(B, Buffer[ 3] + $A953FD4E + (C xor (D or not E))); B := B shl 13 or B shr 19 + A; D := D shl 10 or D shr 22;
Inc(A, Buffer[ 8] + $A953FD4E + (B xor (C or not D))); A := A shl 14 or A shr 18 + E; C := C shl 10 or C shr 22;
Inc(E, Buffer[11] + $A953FD4E + (A xor (B or not C))); E := E shl 11 or E shr 21 + D; B := B shl 10 or B shr 22;
Inc(D, Buffer[ 6] + $A953FD4E + (E xor (A or not B))); D := D shl 8 or D shr 24 + C; A := A shl 10 or A shr 22;
Inc(C, Buffer[15] + $A953FD4E + (D xor (E or not A))); C := C shl 5 or C shr 27 + B; E := E shl 10 or E shr 22;
Inc(B, Buffer[13] + $A953FD4E + (C xor (D or not E))); B := B shl 6 or B shr 26 + A; D := D shl 10 or D shr 22;
A1 := A;
B1 := B;
C1 := C;
D1 := D;
E1 := E;
A := FDigest[0];
B := FDigest[1];
C := FDigest[2];
D := FDigest[3];
E := FDigest[4];
Inc(A, Buffer[ 5] + $50A28BE6 + (B xor (C or not D))); A := A shl 8 or A shr 24 + E; C := C shl 10 or C shr 22;
Inc(E, Buffer[14] + $50A28BE6 + (A xor (B or not C))); E := E shl 9 or E shr 23 + D; B := B shl 10 or B shr 22;
Inc(D, Buffer[ 7] + $50A28BE6 + (E xor (A or not B))); D := D shl 9 or D shr 23 + C; A := A shl 10 or A shr 22;
Inc(C, Buffer[ 0] + $50A28BE6 + (D xor (E or not A))); C := C shl 11 or C shr 21 + B; E := E shl 10 or E shr 22;
Inc(B, Buffer[ 9] + $50A28BE6 + (C xor (D or not E))); B := B shl 13 or B shr 19 + A; D := D shl 10 or D shr 22;
Inc(A, Buffer[ 2] + $50A28BE6 + (B xor (C or not D))); A := A shl 15 or A shr 17 + E; C := C shl 10 or C shr 22;
Inc(E, Buffer[11] + $50A28BE6 + (A xor (B or not C))); E := E shl 15 or E shr 17 + D; B := B shl 10 or B shr 22;
Inc(D, Buffer[ 4] + $50A28BE6 + (E xor (A or not B))); D := D shl 5 or D shr 27 + C; A := A shl 10 or A shr 22;
Inc(C, Buffer[13] + $50A28BE6 + (D xor (E or not A))); C := C shl 7 or C shr 25 + B; E := E shl 10 or E shr 22;
Inc(B, Buffer[ 6] + $50A28BE6 + (C xor (D or not E))); B := B shl 7 or B shr 25 + A; D := D shl 10 or D shr 22;
Inc(A, Buffer[15] + $50A28BE6 + (B xor (C or not D))); A := A shl 8 or A shr 24 + E; C := C shl 10 or C shr 22;
Inc(E, Buffer[ 8] + $50A28BE6 + (A xor (B or not C))); E := E shl 11 or E shr 21 + D; B := B shl 10 or B shr 22;
Inc(D, Buffer[ 1] + $50A28BE6 + (E xor (A or not B))); D := D shl 14 or D shr 18 + C; A := A shl 10 or A shr 22;
Inc(C, Buffer[10] + $50A28BE6 + (D xor (E or not A))); C := C shl 14 or C shr 18 + B; E := E shl 10 or E shr 22;
Inc(B, Buffer[ 3] + $50A28BE6 + (C xor (D or not E))); B := B shl 12 or B shr 20 + A; D := D shl 10 or D shr 22;
Inc(A, Buffer[12] + $50A28BE6 + (B xor (C or not D))); A := A shl 6 or A shr 26 + E; C := C shl 10 or C shr 22;
Inc(E, Buffer[ 6] + $5C4DD124 + ((A and C) or (B and not C))); E := E shl 9 or E shr 23 + D; B := B shl 10 or B shr 22;
Inc(D, Buffer[11] + $5C4DD124 + ((E and B) or (A and not B))); D := D shl 13 or D shr 19 + C; A := A shl 10 or A shr 22;
Inc(C, Buffer[ 3] + $5C4DD124 + ((D and A) or (E and not A))); C := C shl 15 or C shr 17 + B; E := E shl 10 or E shr 22;
Inc(B, Buffer[ 7] + $5C4DD124 + ((C and E) or (D and not E))); B := B shl 7 or B shr 25 + A; D := D shl 10 or D shr 22;
Inc(A, Buffer[ 0] + $5C4DD124 + ((B and D) or (C and not D))); A := A shl 12 or A shr 20 + E; C := C shl 10 or C shr 22;
Inc(E, Buffer[13] + $5C4DD124 + ((A and C) or (B and not C))); E := E shl 8 or E shr 24 + D; B := B shl 10 or B shr 22;
Inc(D, Buffer[ 5] + $5C4DD124 + ((E and B) or (A and not B))); D := D shl 9 or D shr 23 + C; A := A shl 10 or A shr 22;
Inc(C, Buffer[10] + $5C4DD124 + ((D and A) or (E and not A))); C := C shl 11 or C shr 21 + B; E := E shl 10 or E shr 22;
Inc(B, Buffer[14] + $5C4DD124 + ((C and E) or (D and not E))); B := B shl 7 or B shr 25 + A; D := D shl 10 or D shr 22;
Inc(A, Buffer[15] + $5C4DD124 + ((B and D) or (C and not D))); A := A shl 7 or A shr 25 + E; C := C shl 10 or C shr 22;
Inc(E, Buffer[ 8] + $5C4DD124 + ((A and C) or (B and not C))); E := E shl 12 or E shr 20 + D; B := B shl 10 or B shr 22;
Inc(D, Buffer[12] + $5C4DD124 + ((E and B) or (A and not B))); D := D shl 7 or D shr 25 + C; A := A shl 10 or A shr 22;
Inc(C, Buffer[ 4] + $5C4DD124 + ((D and A) or (E and not A))); C := C shl 6 or C shr 26 + B; E := E shl 10 or E shr 22;
Inc(B, Buffer[ 9] + $5C4DD124 + ((C and E) or (D and not E))); B := B shl 15 or B shr 17 + A; D := D shl 10 or D shr 22;
Inc(A, Buffer[ 1] + $5C4DD124 + ((B and D) or (C and not D))); A := A shl 13 or A shr 19 + E; C := C shl 10 or C shr 22;
Inc(E, Buffer[ 2] + $5C4DD124 + ((A and C) or (B and not C))); E := E shl 11 or E shr 21 + D; B := B shl 10 or B shr 22;
Inc(D, Buffer[15] + $6D703EF3 + ((E or not A) xor B)); D := D shl 9 or D shr 23 + C; A := A shl 10 or A shr 22;
Inc(C, Buffer[ 5] + $6D703EF3 + ((D or not E) xor A)); C := C shl 7 or C shr 25 + B; E := E shl 10 or E shr 22;
Inc(B, Buffer[ 1] + $6D703EF3 + ((C or not D) xor E)); B := B shl 15 or B shr 17 + A; D := D shl 10 or D shr 22;
Inc(A, Buffer[ 3] + $6D703EF3 + ((B or not C) xor D)); A := A shl 11 or A shr 21 + E; C := C shl 10 or C shr 22;
Inc(E, Buffer[ 7] + $6D703EF3 + ((A or not B) xor C)); E := E shl 8 or E shr 24 + D; B := B shl 10 or B shr 22;
Inc(D, Buffer[14] + $6D703EF3 + ((E or not A) xor B)); D := D shl 6 or D shr 26 + C; A := A shl 10 or A shr 22;
Inc(C, Buffer[ 6] + $6D703EF3 + ((D or not E) xor A)); C := C shl 6 or C shr 26 + B; E := E shl 10 or E shr 22;
Inc(B, Buffer[ 9] + $6D703EF3 + ((C or not D) xor E)); B := B shl 14 or B shr 18 + A; D := D shl 10 or D shr 22;
Inc(A, Buffer[11] + $6D703EF3 + ((B or not C) xor D)); A := A shl 12 or A shr 20 + E; C := C shl 10 or C shr 22;
Inc(E, Buffer[ 8] + $6D703EF3 + ((A or not B) xor C)); E := E shl 13 or E shr 19 + D; B := B shl 10 or B shr 22;
Inc(D, Buffer[12] + $6D703EF3 + ((E or not A) xor B)); D := D shl 5 or D shr 27 + C; A := A shl 10 or A shr 22;
Inc(C, Buffer[ 2] + $6D703EF3 + ((D or not E) xor A)); C := C shl 14 or C shr 18 + B; E := E shl 10 or E shr 22;
Inc(B, Buffer[10] + $6D703EF3 + ((C or not D) xor E)); B := B shl 13 or B shr 19 + A; D := D shl 10 or D shr 22;
Inc(A, Buffer[ 0] + $6D703EF3 + ((B or not C) xor D)); A := A shl 13 or A shr 19 + E; C := C shl 10 or C shr 22;
Inc(E, Buffer[ 4] + $6D703EF3 + ((A or not B) xor C)); E := E shl 7 or E shr 25 + D; B := B shl 10 or B shr 22;
Inc(D, Buffer[13] + $6D703EF3 + ((E or not A) xor B)); D := D shl 5 or D shr 27 + C; A := A shl 10 or A shr 22;
Inc(C, Buffer[ 8] + $7A6D76E9 + ((D and E) or (not D and A))); C := C shl 15 or C shr 17 + B; E := E shl 10 or E shr 22;
Inc(B, Buffer[ 6] + $7A6D76E9 + ((C and D) or (not C and E))); B := B shl 5 or B shr 27 + A; D := D shl 10 or D shr 22;
Inc(A, Buffer[ 4] + $7A6D76E9 + ((B and C) or (not B and D))); A := A shl 8 or A shr 24 + E; C := C shl 10 or C shr 22;
Inc(E, Buffer[ 1] + $7A6D76E9 + ((A and B) or (not A and C))); E := E shl 11 or E shr 21 + D; B := B shl 10 or B shr 22;
Inc(D, Buffer[ 3] + $7A6D76E9 + ((E and A) or (not E and B))); D := D shl 14 or D shr 18 + C; A := A shl 10 or A shr 22;
Inc(C, Buffer[11] + $7A6D76E9 + ((D and E) or (not D and A))); C := C shl 14 or C shr 18 + B; E := E shl 10 or E shr 22;
Inc(B, Buffer[15] + $7A6D76E9 + ((C and D) or (not C and E))); B := B shl 6 or B shr 26 + A; D := D shl 10 or D shr 22;
Inc(A, Buffer[ 0] + $7A6D76E9 + ((B and C) or (not B and D))); A := A shl 14 or A shr 18 + E; C := C shl 10 or C shr 22;
Inc(E, Buffer[ 5] + $7A6D76E9 + ((A and B) or (not A and C))); E := E shl 6 or E shr 26 + D; B := B shl 10 or B shr 22;
Inc(D, Buffer[12] + $7A6D76E9 + ((E and A) or (not E and B))); D := D shl 9 or D shr 23 + C; A := A shl 10 or A shr 22;
Inc(C, Buffer[ 2] + $7A6D76E9 + ((D and E) or (not D and A))); C := C shl 12 or C shr 20 + B; E := E shl 10 or E shr 22;
Inc(B, Buffer[13] + $7A6D76E9 + ((C and D) or (not C and E))); B := B shl 9 or B shr 23 + A; D := D shl 10 or D shr 22;
Inc(A, Buffer[ 9] + $7A6D76E9 + ((B and C) or (not B and D))); A := A shl 12 or A shr 20 + E; C := C shl 10 or C shr 22;
Inc(E, Buffer[ 7] + $7A6D76E9 + ((A and B) or (not A and C))); E := E shl 5 or E shr 27 + D; B := B shl 10 or B shr 22;
Inc(D, Buffer[10] + $7A6D76E9 + ((E and A) or (not E and B))); D := D shl 15 or D shr 17 + C; A := A shl 10 or A shr 22;
Inc(C, Buffer[14] + $7A6D76E9 + ((D and E) or (not D and A))); C := C shl 8 or C shr 24 + B; E := E shl 10 or E shr 22;
Inc(B, Buffer[12] + (C xor D xor E)); B := B shl 8 or B shr 24 + A; D := D shl 10 or D shr 22;
Inc(A, Buffer[15] + (B xor C xor D)); A := A shl 5 or A shr 27 + E; C := C shl 10 or C shr 22;
Inc(E, Buffer[10] + (A xor B xor C)); E := E shl 12 or E shr 20 + D; B := B shl 10 or B shr 22;
Inc(D, Buffer[ 4] + (E xor A xor B)); D := D shl 9 or D shr 23 + C; A := A shl 10 or A shr 22;
Inc(C, Buffer[ 1] + (D xor E xor A)); C := C shl 12 or C shr 20 + B; E := E shl 10 or E shr 22;
Inc(B, Buffer[ 5] + (C xor D xor E)); B := B shl 5 or B shr 27 + A; D := D shl 10 or D shr 22;
Inc(A, Buffer[ 8] + (B xor C xor D)); A := A shl 14 or A shr 18 + E; C := C shl 10 or C shr 22;
Inc(E, Buffer[ 7] + (A xor B xor C)); E := E shl 6 or E shr 26 + D; B := B shl 10 or B shr 22;
Inc(D, Buffer[ 6] + (E xor A xor B)); D := D shl 8 or D shr 24 + C; A := A shl 10 or A shr 22;
Inc(C, Buffer[ 2] + (D xor E xor A)); C := C shl 13 or C shr 19 + B; E := E shl 10 or E shr 22;
Inc(B, Buffer[13] + (C xor D xor E)); B := B shl 6 or B shr 26 + A; D := D shl 10 or D shr 22;
Inc(A, Buffer[14] + (B xor C xor D)); A := A shl 5 or A shr 27 + E; C := C shl 10 or C shr 22;
Inc(E, Buffer[ 0] + (A xor B xor C)); E := E shl 15 or E shr 17 + D; B := B shl 10 or B shr 22;
Inc(D, Buffer[ 3] + (E xor A xor B)); D := D shl 13 or D shr 19 + C; A := A shl 10 or A shr 22;
Inc(C, Buffer[ 9] + (D xor E xor A)); C := C shl 11 or C shr 21 + B; E := E shl 10 or E shr 22;
Inc(B, Buffer[11] + (C xor D xor E)); B := B shl 11 or B shr 21 + A; D := D shl 10 or D shr 22;
Inc(D, C1 + FDigest[1]);
FDigest[1] := FDigest[2] + D1 + E;
FDigest[2] := FDigest[3] + E1 + A;
FDigest[3] := FDigest[4] + A1 + B;
FDigest[4] := FDigest[0] + B1 + C;
FDigest[0] := D;
end;
class function THash_RipeMD160.DigestKeySize: Integer;
begin
Result := 20;
end;
class function THash_RipeMD256.TestVector: Pointer;
asm
MOV EAX,OFFSET @Vector
RET
@Vector: DB 0C3h,0B1h,0D7h,0ACh,0A8h,09Ah,047h,07Ah
DB 038h,0D3h,06Dh,039h,0EFh,000h,0FBh,045h
DB 0FCh,04Eh,0C3h,01Ah,071h,021h,0DBh,09Eh
DB 01Ch,076h,0C5h,0DEh,099h,088h,018h,0C2h
end;
procedure THash_RipeMD256.Transform(Buffer: PIntArray);
var
A1, B1, C1, D1: LongWord;
A2, B2, C2, D2: LongWord;
T: LongWord;
begin
A1 := FDigest[0];
B1 := FDigest[1];
C1 := FDigest[2];
D1 := FDigest[3];
A2 := FDigest[4];
B2 := FDigest[5];
C2 := FDigest[6];
D2 := FDigest[7];
Inc(A1, B1 xor C1 xor D1 + Buffer[ 0]); A1 := A1 shl 11 or A1 shr 21;
Inc(D1, A1 xor B1 xor C1 + Buffer[ 1]); D1 := D1 shl 14 or D1 shr 18;
Inc(C1, D1 xor A1 xor B1 + Buffer[ 2]); C1 := C1 shl 15 or C1 shr 17;
Inc(B1, C1 xor D1 xor A1 + Buffer[ 3]); B1 := B1 shl 12 or B1 shr 20;
Inc(A1, B1 xor C1 xor D1 + Buffer[ 4]); A1 := A1 shl 5 or A1 shr 27;
Inc(D1, A1 xor B1 xor C1 + Buffer[ 5]); D1 := D1 shl 8 or D1 shr 24;
Inc(C1, D1 xor A1 xor B1 + Buffer[ 6]); C1 := C1 shl 7 or C1 shr 25;
Inc(B1, C1 xor D1 xor A1 + Buffer[ 7]); B1 := B1 shl 9 or B1 shr 23;
Inc(A1, B1 xor C1 xor D1 + Buffer[ 8]); A1 := A1 shl 11 or A1 shr 21;
Inc(D1, A1 xor B1 xor C1 + Buffer[ 9]); D1 := D1 shl 13 or D1 shr 19;
Inc(C1, D1 xor A1 xor B1 + Buffer[10]); C1 := C1 shl 14 or C1 shr 18;
Inc(B1, C1 xor D1 xor A1 + Buffer[11]); B1 := B1 shl 15 or B1 shr 17;
Inc(A1, B1 xor C1 xor D1 + Buffer[12]); A1 := A1 shl 6 or A1 shr 26;
Inc(D1, A1 xor B1 xor C1 + Buffer[13]); D1 := D1 shl 7 or D1 shr 25;
Inc(C1, D1 xor A1 xor B1 + Buffer[14]); C1 := C1 shl 9 or C1 shr 23;
Inc(B1, C1 xor D1 xor A1 + Buffer[15]); B1 := B1 shl 8 or B1 shr 24;
Inc(A2, B2 and D2 or C2 and not D2 + Buffer[ 5] + $50A28BE6); A2 := A2 shl 8 or A2 shr 24;
Inc(D2, A2 and C2 or B2 and not C2 + Buffer[14] + $50A28BE6); D2 := D2 shl 9 or D2 shr 23;
Inc(C2, D2 and B2 or A2 and not B2 + Buffer[ 7] + $50A28BE6); C2 := C2 shl 9 or C2 shr 23;
Inc(B2, C2 and A2 or D2 and not A2 + Buffer[ 0] + $50A28BE6); B2 := B2 shl 11 or B2 shr 21;
Inc(A2, B2 and D2 or C2 and not D2 + Buffer[ 9] + $50A28BE6); A2 := A2 shl 13 or A2 shr 19;
Inc(D2, A2 and C2 or B2 and not C2 + Buffer[ 2] + $50A28BE6); D2 := D2 shl 15 or D2 shr 17;
Inc(C2, D2 and B2 or A2 and not B2 + Buffer[11] + $50A28BE6); C2 := C2 shl 15 or C2 shr 17;
Inc(B2, C2 and A2 or D2 and not A2 + Buffer[ 4] + $50A28BE6); B2 := B2 shl 5 or B2 shr 27;
Inc(A2, B2 and D2 or C2 and not D2 + Buffer[13] + $50A28BE6); A2 := A2 shl 7 or A2 shr 25;
Inc(D2, A2 and C2 or B2 and not C2 + Buffer[ 6] + $50A28BE6); D2 := D2 shl 7 or D2 shr 25;
Inc(C2, D2 and B2 or A2 and not B2 + Buffer[15] + $50A28BE6); C2 := C2 shl 8 or C2 shr 24;
Inc(B2, C2 and A2 or D2 and not A2 + Buffer[ 8] + $50A28BE6); B2 := B2 shl 11 or B2 shr 21;
Inc(A2, B2 and D2 or C2 and not D2 + Buffer[ 1] + $50A28BE6); A2 := A2 shl 14 or A2 shr 18;
Inc(D2, A2 and C2 or B2 and not C2 + Buffer[10] + $50A28BE6); D2 := D2 shl 14 or D2 shr 18;
Inc(C2, D2 and B2 or A2 and not B2 + Buffer[ 3] + $50A28BE6); C2 := C2 shl 12 or C2 shr 20;
Inc(B2, C2 and A2 or D2 and not A2 + Buffer[12] + $50A28BE6); B2 := B2 shl 6 or B2 shr 26;
T := A1; A1 := A2; A2 := T;
Inc(A1, B1 and C1 or not B1 and D1 + Buffer[ 7] + $5A827999); A1 := A1 shl 7 or A1 shr 25;
Inc(D1, A1 and B1 or not A1 and C1 + Buffer[ 4] + $5A827999); D1 := D1 shl 6 or D1 shr 26;
Inc(C1, D1 and A1 or not D1 and B1 + Buffer[13] + $5A827999); C1 := C1 shl 8 or C1 shr 24;
Inc(B1, C1 and D1 or not C1 and A1 + Buffer[ 1] + $5A827999); B1 := B1 shl 13 or B1 shr 19;
Inc(A1, B1 and C1 or not B1 and D1 + Buffer[10] + $5A827999); A1 := A1 shl 11 or A1 shr 21;
Inc(D1, A1 and B1 or not A1 and C1 + Buffer[ 6] + $5A827999); D1 := D1 shl 9 or D1 shr 23;
Inc(C1, D1 and A1 or not D1 and B1 + Buffer[15] + $5A827999); C1 := C1 shl 7 or C1 shr 25;
Inc(B1, C1 and D1 or not C1 and A1 + Buffer[ 3] + $5A827999); B1 := B1 shl 15 or B1 shr 17;
Inc(A1, B1 and C1 or not B1 and D1 + Buffer[12] + $5A827999); A1 := A1 shl 7 or A1 shr 25;
Inc(D1, A1 and B1 or not A1 and C1 + Buffer[ 0] + $5A827999); D1 := D1 shl 12 or D1 shr 20;
Inc(C1, D1 and A1 or not D1 and B1 + Buffer[ 9] + $5A827999); C1 := C1 shl 15 or C1 shr 17;
Inc(B1, C1 and D1 or not C1 and A1 + Buffer[ 5] + $5A827999); B1 := B1 shl 9 or B1 shr 23;
Inc(A1, B1 and C1 or not B1 and D1 + Buffer[ 2] + $5A827999); A1 := A1 shl 11 or A1 shr 21;
Inc(D1, A1 and B1 or not A1 and C1 + Buffer[14] + $5A827999); D1 := D1 shl 7 or D1 shr 25;
Inc(C1, D1 and A1 or not D1 and B1 + Buffer[11] + $5A827999); C1 := C1 shl 13 or C1 shr 19;
Inc(B1, C1 and D1 or not C1 and A1 + Buffer[ 8] + $5A827999); B1 := B1 shl 12 or B1 shr 20;
Inc(A2, (B2 or not C2) xor D2 + Buffer[ 6] + $5C4DD124); A2 := A2 shl 9 or A2 shr 23;
Inc(D2, (A2 or not B2) xor C2 + Buffer[11] + $5C4DD124); D2 := D2 shl 13 or D2 shr 19;
Inc(C2, (D2 or not A2) xor B2 + Buffer[ 3] + $5C4DD124); C2 := C2 shl 15 or C2 shr 17;
Inc(B2, (C2 or not D2) xor A2 + Buffer[ 7] + $5C4DD124); B2 := B2 shl 7 or B2 shr 25;
Inc(A2, (B2 or not C2) xor D2 + Buffer[ 0] + $5C4DD124); A2 := A2 shl 12 or A2 shr 20;
Inc(D2, (A2 or not B2) xor C2 + Buffer[13] + $5C4DD124); D2 := D2 shl 8 or D2 shr 24;
Inc(C2, (D2 or not A2) xor B2 + Buffer[ 5] + $5C4DD124); C2 := C2 shl 9 or C2 shr 23;
Inc(B2, (C2 or not D2) xor A2 + Buffer[10] + $5C4DD124); B2 := B2 shl 11 or B2 shr 21;
Inc(A2, (B2 or not C2) xor D2 + Buffer[14] + $5C4DD124); A2 := A2 shl 7 or A2 shr 25;
Inc(D2, (A2 or not B2) xor C2 + Buffer[15] + $5C4DD124); D2 := D2 shl 7 or D2 shr 25;
Inc(C2, (D2 or not A2) xor B2 + Buffer[ 8] + $5C4DD124); C2 := C2 shl 12 or C2 shr 20;
Inc(B2, (C2 or not D2) xor A2 + Buffer[12] + $5C4DD124); B2 := B2 shl 7 or B2 shr 25;
Inc(A2, (B2 or not C2) xor D2 + Buffer[ 4] + $5C4DD124); A2 := A2 shl 6 or A2 shr 26;
Inc(D2, (A2 or not B2) xor C2 + Buffer[ 9] + $5C4DD124); D2 := D2 shl 15 or D2 shr 17;
Inc(C2, (D2 or not A2) xor B2 + Buffer[ 1] + $5C4DD124); C2 := C2 shl 13 or C2 shr 19;
Inc(B2, (C2 or not D2) xor A2 + Buffer[ 2] + $5C4DD124); B2 := B2 shl 11 or B2 shr 21;
T := B1; B1 := B2; B2 := T;
Inc(A1, (B1 or not C1) xor D1 + Buffer[ 3] + $6ED9EBA1); A1 := A1 shl 11 or A1 shr 21;
Inc(D1, (A1 or not B1) xor C1 + Buffer[10] + $6ED9EBA1); D1 := D1 shl 13 or D1 shr 19;
Inc(C1, (D1 or not A1) xor B1 + Buffer[14] + $6ED9EBA1); C1 := C1 shl 6 or C1 shr 26;
Inc(B1, (C1 or not D1) xor A1 + Buffer[ 4] + $6ED9EBA1); B1 := B1 shl 7 or B1 shr 25;
Inc(A1, (B1 or not C1) xor D1 + Buffer[ 9] + $6ED9EBA1); A1 := A1 shl 14 or A1 shr 18;
Inc(D1, (A1 or not B1) xor C1 + Buffer[15] + $6ED9EBA1); D1 := D1 shl 9 or D1 shr 23;
Inc(C1, (D1 or not A1) xor B1 + Buffer[ 8] + $6ED9EBA1); C1 := C1 shl 13 or C1 shr 19;
Inc(B1, (C1 or not D1) xor A1 + Buffer[ 1] + $6ED9EBA1); B1 := B1 shl 15 or B1 shr 17;
Inc(A1, (B1 or not C1) xor D1 + Buffer[ 2] + $6ED9EBA1); A1 := A1 shl 14 or A1 shr 18;
Inc(D1, (A1 or not B1) xor C1 + Buffer[ 7] + $6ED9EBA1); D1 := D1 shl 8 or D1 shr 24;
Inc(C1, (D1 or not A1) xor B1 + Buffer[ 0] + $6ED9EBA1); C1 := C1 shl 13 or C1 shr 19;
Inc(B1, (C1 or not D1) xor A1 + Buffer[ 6] + $6ED9EBA1); B1 := B1 shl 6 or B1 shr 26;
Inc(A1, (B1 or not C1) xor D1 + Buffer[13] + $6ED9EBA1); A1 := A1 shl 5 or A1 shr 27;
Inc(D1, (A1 or not B1) xor C1 + Buffer[11] + $6ED9EBA1); D1 := D1 shl 12 or D1 shr 20;
Inc(C1, (D1 or not A1) xor B1 + Buffer[ 5] + $6ED9EBA1); C1 := C1 shl 7 or C1 shr 25;
Inc(B1, (C1 or not D1) xor A1 + Buffer[12] + $6ED9EBA1); B1 := B1 shl 5 or B1 shr 27;
Inc(A2, B2 and C2 or not B2 and D2 + Buffer[15] + $6D703EF3); A2 := A2 shl 9 or A2 shr 23;
Inc(D2, A2 and B2 or not A2 and C2 + Buffer[ 5] + $6D703EF3); D2 := D2 shl 7 or D2 shr 25;
Inc(C2, D2 and A2 or not D2 and B2 + Buffer[ 1] + $6D703EF3); C2 := C2 shl 15 or C2 shr 17;
Inc(B2, C2 and D2 or not C2 and A2 + Buffer[ 3] + $6D703EF3); B2 := B2 shl 11 or B2 shr 21;
Inc(A2, B2 and C2 or not B2 and D2 + Buffer[ 7] + $6D703EF3); A2 := A2 shl 8 or A2 shr 24;
Inc(D2, A2 and B2 or not A2 and C2 + Buffer[14] + $6D703EF3); D2 := D2 shl 6 or D2 shr 26;
Inc(C2, D2 and A2 or not D2 and B2 + Buffer[ 6] + $6D703EF3); C2 := C2 shl 6 or C2 shr 26;
Inc(B2, C2 and D2 or not C2 and A2 + Buffer[ 9] + $6D703EF3); B2 := B2 shl 14 or B2 shr 18;
Inc(A2, B2 and C2 or not B2 and D2 + Buffer[11] + $6D703EF3); A2 := A2 shl 12 or A2 shr 20;
Inc(D2, A2 and B2 or not A2 and C2 + Buffer[ 8] + $6D703EF3); D2 := D2 shl 13 or D2 shr 19;
Inc(C2, D2 and A2 or not D2 and B2 + Buffer[12] + $6D703EF3); C2 := C2 shl 5 or C2 shr 27;
Inc(B2, C2 and D2 or not C2 and A2 + Buffer[ 2] + $6D703EF3); B2 := B2 shl 14 or B2 shr 18;
Inc(A2, B2 and C2 or not B2 and D2 + Buffer[10] + $6D703EF3); A2 := A2 shl 13 or A2 shr 19;
Inc(D2, A2 and B2 or not A2 and C2 + Buffer[ 0] + $6D703EF3); D2 := D2 shl 13 or D2 shr 19;
Inc(C2, D2 and A2 or not D2 and B2 + Buffer[ 4] + $6D703EF3); C2 := C2 shl 7 or C2 shr 25;
Inc(B2, C2 and D2 or not C2 and A2 + Buffer[13] + $6D703EF3); B2 := B2 shl 5 or B2 shr 27;
T := C1; C1 := C2; C2 := T;
Inc(A1, B1 and D1 or C1 and not D1 + Buffer[ 1] + $8F1BBCDC); A1 := A1 shl 11 or A1 shr 21;
Inc(D1, A1 and C1 or B1 and not C1 + Buffer[ 9] + $8F1BBCDC); D1 := D1 shl 12 or D1 shr 20;
Inc(C1, D1 and B1 or A1 and not B1 + Buffer[11] + $8F1BBCDC); C1 := C1 shl 14 or C1 shr 18;
Inc(B1, C1 and A1 or D1 and not A1 + Buffer[10] + $8F1BBCDC); B1 := B1 shl 15 or B1 shr 17;
Inc(A1, B1 and D1 or C1 and not D1 + Buffer[ 0] + $8F1BBCDC); A1 := A1 shl 14 or A1 shr 18;
Inc(D1, A1 and C1 or B1 and not C1 + Buffer[ 8] + $8F1BBCDC); D1 := D1 shl 15 or D1 shr 17;
Inc(C1, D1 and B1 or A1 and not B1 + Buffer[12] + $8F1BBCDC); C1 := C1 shl 9 or C1 shr 23;
Inc(B1, C1 and A1 or D1 and not A1 + Buffer[ 4] + $8F1BBCDC); B1 := B1 shl 8 or B1 shr 24;
Inc(A1, B1 and D1 or C1 and not D1 + Buffer[13] + $8F1BBCDC); A1 := A1 shl 9 or A1 shr 23;
Inc(D1, A1 and C1 or B1 and not C1 + Buffer[ 3] + $8F1BBCDC); D1 := D1 shl 14 or D1 shr 18;
Inc(C1, D1 and B1 or A1 and not B1 + Buffer[ 7] + $8F1BBCDC); C1 := C1 shl 5 or C1 shr 27;
Inc(B1, C1 and A1 or D1 and not A1 + Buffer[15] + $8F1BBCDC); B1 := B1 shl 6 or B1 shr 26;
Inc(A1, B1 and D1 or C1 and not D1 + Buffer[14] + $8F1BBCDC); A1 := A1 shl 8 or A1 shr 24;
Inc(D1, A1 and C1 or B1 and not C1 + Buffer[ 5] + $8F1BBCDC); D1 := D1 shl 6 or D1 shr 26;
Inc(C1, D1 and B1 or A1 and not B1 + Buffer[ 6] + $8F1BBCDC); C1 := C1 shl 5 or C1 shr 27;
Inc(B1, C1 and A1 or D1 and not A1 + Buffer[ 2] + $8F1BBCDC); B1 := B1 shl 12 or B1 shr 20;
Inc(A2, B2 xor C2 xor D2 + Buffer[ 8]); A2 := A2 shl 15 or A2 shr 17;
Inc(D2, A2 xor B2 xor C2 + Buffer[ 6]); D2 := D2 shl 5 or D2 shr 27;
Inc(C2, D2 xor A2 xor B2 + Buffer[ 4]); C2 := C2 shl 8 or C2 shr 24;
Inc(B2, C2 xor D2 xor A2 + Buffer[ 1]); B2 := B2 shl 11 or B2 shr 21;
Inc(A2, B2 xor C2 xor D2 + Buffer[ 3]); A2 := A2 shl 14 or A2 shr 18;
Inc(D2, A2 xor B2 xor C2 + Buffer[11]); D2 := D2 shl 14 or D2 shr 18;
Inc(C2, D2 xor A2 xor B2 + Buffer[15]); C2 := C2 shl 6 or C2 shr 26;
Inc(B2, C2 xor D2 xor A2 + Buffer[ 0]); B2 := B2 shl 14 or B2 shr 18;
Inc(A2, B2 xor C2 xor D2 + Buffer[ 5]); A2 := A2 shl 6 or A2 shr 26;
Inc(D2, A2 xor B2 xor C2 + Buffer[12]); D2 := D2 shl 9 or D2 shr 23;
Inc(C2, D2 xor A2 xor B2 + Buffer[ 2]); C2 := C2 shl 12 or C2 shr 20;
Inc(B2, C2 xor D2 xor A2 + Buffer[13]); B2 := B2 shl 9 or B2 shr 23;
Inc(A2, B2 xor C2 xor D2 + Buffer[ 9]); A2 := A2 shl 12 or A2 shr 20;
Inc(D2, A2 xor B2 xor C2 + Buffer[ 7]); D2 := D2 shl 5 or D2 shr 27;
Inc(C2, D2 xor A2 xor B2 + Buffer[10]); C2 := C2 shl 15 or C2 shr 17;
Inc(B2, C2 xor D2 xor A2 + Buffer[14]); B2 := B2 shl 8 or B2 shr 24;
T := D1; D1 := D2; D2 := T;
Inc(FDigest[0], A1);
Inc(FDigest[1], B1);
Inc(FDigest[2], C1);
Inc(FDigest[3], D1);
Inc(FDigest[4], A2);
Inc(FDigest[5], B2);
Inc(FDigest[6], C2);
Inc(FDigest[7], D2);
end;
class function THash_RipeMD256.DigestKeySize: Integer;
begin
Result := 32;
end;
procedure THash_RipeMD256.Init;
begin
inherited Init;
FDigest[4] := $76543210;
FDigest[5] := $FEDCBA98;
FDigest[6] := $89ABCDEF;
FDigest[7] := $01234567;
end;
class function THash_RipeMD320.TestVector: Pointer;
asm
MOV EAX,OFFSET @Vector
RET
@Vector: DB 0B7h,0BDh,02Ch,075h,0B7h,013h,050h,091h
DB 0E4h,067h,009h,046h,0F1h,041h,05Ah,048h
DB 045h,0DFh,08Eh,007h,0BAh,067h,04Eh,0A9h
DB 0FDh,066h,0EDh,001h,0D9h,06Fh,023h,020h
DB 0B5h,011h,012h,0C5h,0A7h,041h,0A6h,05Ch
end;
procedure THash_RipeMD320.Transform(Buffer: PIntArray);
var
A1, B1, C1, D1, E1: LongWord;
A2, B2, C2, D2, E2: LongWord;
T: LongWord;
begin
A1 := FDigest[0];
B1 := FDigest[1];
C1 := FDigest[2];
D1 := FDigest[3];
E1 := FDigest[4];
A2 := FDigest[5];
B2 := FDigest[6];
C2 := FDigest[7];
D2 := FDigest[8];
E2 := FDigest[9];
Inc(A1, Buffer[ 0] + (B1 xor C1 xor D1)); A1 := A1 shl 11 or A1 shr 21 + E1; C1 := C1 shl 10 or C1 shr 22;
Inc(E1, Buffer[ 1] + (A1 xor B1 xor C1)); E1 := E1 shl 14 or E1 shr 18 + D1; B1 := B1 shl 10 or B1 shr 22;
Inc(D1, Buffer[ 2] + (E1 xor A1 xor B1)); D1 := D1 shl 15 or D1 shr 17 + C1; A1 := A1 shl 10 or A1 shr 22;
Inc(C1, Buffer[ 3] + (D1 xor E1 xor A1)); C1 := C1 shl 12 or C1 shr 20 + B1; E1 := E1 shl 10 or E1 shr 22;
Inc(B1, Buffer[ 4] + (C1 xor D1 xor E1)); B1 := B1 shl 5 or B1 shr 27 + A1; D1 := D1 shl 10 or D1 shr 22;
Inc(A1, Buffer[ 5] + (B1 xor C1 xor D1)); A1 := A1 shl 8 or A1 shr 24 + E1; C1 := C1 shl 10 or C1 shr 22;
Inc(E1, Buffer[ 6] + (A1 xor B1 xor C1)); E1 := E1 shl 7 or E1 shr 25 + D1; B1 := B1 shl 10 or B1 shr 22;
Inc(D1, Buffer[ 7] + (E1 xor A1 xor B1)); D1 := D1 shl 9 or D1 shr 23 + C1; A1 := A1 shl 10 or A1 shr 22;
Inc(C1, Buffer[ 8] + (D1 xor E1 xor A1)); C1 := C1 shl 11 or C1 shr 21 + B1; E1 := E1 shl 10 or E1 shr 22;
Inc(B1, Buffer[ 9] + (C1 xor D1 xor E1)); B1 := B1 shl 13 or B1 shr 19 + A1; D1 := D1 shl 10 or D1 shr 22;
Inc(A1, Buffer[10] + (B1 xor C1 xor D1)); A1 := A1 shl 14 or A1 shr 18 + E1; C1 := C1 shl 10 or C1 shr 22;
Inc(E1, Buffer[11] + (A1 xor B1 xor C1)); E1 := E1 shl 15 or E1 shr 17 + D1; B1 := B1 shl 10 or B1 shr 22;
Inc(D1, Buffer[12] + (E1 xor A1 xor B1)); D1 := D1 shl 6 or D1 shr 26 + C1; A1 := A1 shl 10 or A1 shr 22;
Inc(C1, Buffer[13] + (D1 xor E1 xor A1)); C1 := C1 shl 7 or C1 shr 25 + B1; E1 := E1 shl 10 or E1 shr 22;
Inc(B1, Buffer[14] + (C1 xor D1 xor E1)); B1 := B1 shl 9 or B1 shr 23 + A1; D1 := D1 shl 10 or D1 shr 22;
Inc(A1, Buffer[15] + (B1 xor C1 xor D1)); A1 := A1 shl 8 or A1 shr 24 + E1; C1 := C1 shl 10 or C1 shr 22;
Inc(A2, Buffer[ 5] + $50A28BE6 + (B2 xor (C2 or not D2))); A2 := A2 shl 8 or A2 shr 24 + E2; C2 := C2 shl 10 or C2 shr 22;
Inc(E2, Buffer[14] + $50A28BE6 + (A2 xor (B2 or not C2))); E2 := E2 shl 9 or E2 shr 23 + D2; B2 := B2 shl 10 or B2 shr 22;
Inc(D2, Buffer[ 7] + $50A28BE6 + (E2 xor (A2 or not B2))); D2 := D2 shl 9 or D2 shr 23 + C2; A2 := A2 shl 10 or A2 shr 22;
Inc(C2, Buffer[ 0] + $50A28BE6 + (D2 xor (E2 or not A2))); C2 := C2 shl 11 or C2 shr 21 + B2; E2 := E2 shl 10 or E2 shr 22;
Inc(B2, Buffer[ 9] + $50A28BE6 + (C2 xor (D2 or not E2))); B2 := B2 shl 13 or B2 shr 19 + A2; D2 := D2 shl 10 or D2 shr 22;
Inc(A2, Buffer[ 2] + $50A28BE6 + (B2 xor (C2 or not D2))); A2 := A2 shl 15 or A2 shr 17 + E2; C2 := C2 shl 10 or C2 shr 22;
Inc(E2, Buffer[11] + $50A28BE6 + (A2 xor (B2 or not C2))); E2 := E2 shl 15 or E2 shr 17 + D2; B2 := B2 shl 10 or B2 shr 22;
Inc(D2, Buffer[ 4] + $50A28BE6 + (E2 xor (A2 or not B2))); D2 := D2 shl 5 or D2 shr 27 + C2; A2 := A2 shl 10 or A2 shr 22;
Inc(C2, Buffer[13] + $50A28BE6 + (D2 xor (E2 or not A2))); C2 := C2 shl 7 or C2 shr 25 + B2; E2 := E2 shl 10 or E2 shr 22;
Inc(B2, Buffer[ 6] + $50A28BE6 + (C2 xor (D2 or not E2))); B2 := B2 shl 7 or B2 shr 25 + A2; D2 := D2 shl 10 or D2 shr 22;
Inc(A2, Buffer[15] + $50A28BE6 + (B2 xor (C2 or not D2))); A2 := A2 shl 8 or A2 shr 24 + E2; C2 := C2 shl 10 or C2 shr 22;
Inc(E2, Buffer[ 8] + $50A28BE6 + (A2 xor (B2 or not C2))); E2 := E2 shl 11 or E2 shr 21 + D2; B2 := B2 shl 10 or B2 shr 22;
Inc(D2, Buffer[ 1] + $50A28BE6 + (E2 xor (A2 or not B2))); D2 := D2 shl 14 or D2 shr 18 + C2; A2 := A2 shl 10 or A2 shr 22;
Inc(C2, Buffer[10] + $50A28BE6 + (D2 xor (E2 or not A2))); C2 := C2 shl 14 or C2 shr 18 + B2; E2 := E2 shl 10 or E2 shr 22;
Inc(B2, Buffer[ 3] + $50A28BE6 + (C2 xor (D2 or not E2))); B2 := B2 shl 12 or B2 shr 20 + A2; D2 := D2 shl 10 or D2 shr 22;
Inc(A2, Buffer[12] + $50A28BE6 + (B2 xor (C2 or not D2))); A2 := A2 shl 6 or A2 shr 26 + E2; C2 := C2 shl 10 or C2 shr 22;
T := A1; A1 := A2; A2 := T;
Inc(E1, Buffer[ 7] + $5A827999 + ((A1 and B1) or (not A1 and C1))); E1 := E1 shl 7 or E1 shr 25 + D1; B1 := B1 shl 10 or B1 shr 22;
Inc(D1, Buffer[ 4] + $5A827999 + ((E1 and A1) or (not E1 and B1))); D1 := D1 shl 6 or D1 shr 26 + C1; A1 := A1 shl 10 or A1 shr 22;
Inc(C1, Buffer[13] + $5A827999 + ((D1 and E1) or (not D1 and A1))); C1 := C1 shl 8 or C1 shr 24 + B1; E1 := E1 shl 10 or E1 shr 22;
Inc(B1, Buffer[ 1] + $5A827999 + ((C1 and D1) or (not C1 and E1))); B1 := B1 shl 13 or B1 shr 19 + A1; D1 := D1 shl 10 or D1 shr 22;
Inc(A1, Buffer[10] + $5A827999 + ((B1 and C1) or (not B1 and D1))); A1 := A1 shl 11 or A1 shr 21 + E1; C1 := C1 shl 10 or C1 shr 22;
Inc(E1, Buffer[ 6] + $5A827999 + ((A1 and B1) or (not A1 and C1))); E1 := E1 shl 9 or E1 shr 23 + D1; B1 := B1 shl 10 or B1 shr 22;
Inc(D1, Buffer[15] + $5A827999 + ((E1 and A1) or (not E1 and B1))); D1 := D1 shl 7 or D1 shr 25 + C1; A1 := A1 shl 10 or A1 shr 22;
Inc(C1, Buffer[ 3] + $5A827999 + ((D1 and E1) or (not D1 and A1))); C1 := C1 shl 15 or C1 shr 17 + B1; E1 := E1 shl 10 or E1 shr 22;
Inc(B1, Buffer[12] + $5A827999 + ((C1 and D1) or (not C1 and E1))); B1 := B1 shl 7 or B1 shr 25 + A1; D1 := D1 shl 10 or D1 shr 22;
Inc(A1, Buffer[ 0] + $5A827999 + ((B1 and C1) or (not B1 and D1))); A1 := A1 shl 12 or A1 shr 20 + E1; C1 := C1 shl 10 or C1 shr 22;
Inc(E1, Buffer[ 9] + $5A827999 + ((A1 and B1) or (not A1 and C1))); E1 := E1 shl 15 or E1 shr 17 + D1; B1 := B1 shl 10 or B1 shr 22;
Inc(D1, Buffer[ 5] + $5A827999 + ((E1 and A1) or (not E1 and B1))); D1 := D1 shl 9 or D1 shr 23 + C1; A1 := A1 shl 10 or A1 shr 22;
Inc(C1, Buffer[ 2] + $5A827999 + ((D1 and E1) or (not D1 and A1))); C1 := C1 shl 11 or C1 shr 21 + B1; E1 := E1 shl 10 or E1 shr 22;
Inc(B1, Buffer[14] + $5A827999 + ((C1 and D1) or (not C1 and E1))); B1 := B1 shl 7 or B1 shr 25 + A1; D1 := D1 shl 10 or D1 shr 22;
Inc(A1, Buffer[11] + $5A827999 + ((B1 and C1) or (not B1 and D1))); A1 := A1 shl 13 or A1 shr 19 + E1; C1 := C1 shl 10 or C1 shr 22;
Inc(E1, Buffer[ 8] + $5A827999 + ((A1 and B1) or (not A1 and C1))); E1 := E1 shl 12 or E1 shr 20 + D1; B1 := B1 shl 10 or B1 shr 22;
Inc(E2, Buffer[ 6] + $5C4DD124 + ((A2 and C2) or (B2 and not C2))); E2 := E2 shl 9 or E2 shr 23 + D2; B2 := B2 shl 10 or B2 shr 22;
Inc(D2, Buffer[11] + $5C4DD124 + ((E2 and B2) or (A2 and not B2))); D2 := D2 shl 13 or D2 shr 19 + C2; A2 := A2 shl 10 or A2 shr 22;
Inc(C2, Buffer[ 3] + $5C4DD124 + ((D2 and A2) or (E2 and not A2))); C2 := C2 shl 15 or C2 shr 17 + B2; E2 := E2 shl 10 or E2 shr 22;
Inc(B2, Buffer[ 7] + $5C4DD124 + ((C2 and E2) or (D2 and not E2))); B2 := B2 shl 7 or B2 shr 25 + A2; D2 := D2 shl 10 or D2 shr 22;
Inc(A2, Buffer[ 0] + $5C4DD124 + ((B2 and D2) or (C2 and not D2))); A2 := A2 shl 12 or A2 shr 20 + E2; C2 := C2 shl 10 or C2 shr 22;
Inc(E2, Buffer[13] + $5C4DD124 + ((A2 and C2) or (B2 and not C2))); E2 := E2 shl 8 or E2 shr 24 + D2; B2 := B2 shl 10 or B2 shr 22;
Inc(D2, Buffer[ 5] + $5C4DD124 + ((E2 and B2) or (A2 and not B2))); D2 := D2 shl 9 or D2 shr 23 + C2; A2 := A2 shl 10 or A2 shr 22;
Inc(C2, Buffer[10] + $5C4DD124 + ((D2 and A2) or (E2 and not A2))); C2 := C2 shl 11 or C2 shr 21 + B2; E2 := E2 shl 10 or E2 shr 22;
Inc(B2, Buffer[14] + $5C4DD124 + ((C2 and E2) or (D2 and not E2))); B2 := B2 shl 7 or B2 shr 25 + A2; D2 := D2 shl 10 or D2 shr 22;
Inc(A2, Buffer[15] + $5C4DD124 + ((B2 and D2) or (C2 and not D2))); A2 := A2 shl 7 or A2 shr 25 + E2; C2 := C2 shl 10 or C2 shr 22;
Inc(E2, Buffer[ 8] + $5C4DD124 + ((A2 and C2) or (B2 and not C2))); E2 := E2 shl 12 or E2 shr 20 + D2; B2 := B2 shl 10 or B2 shr 22;
Inc(D2, Buffer[12] + $5C4DD124 + ((E2 and B2) or (A2 and not B2))); D2 := D2 shl 7 or D2 shr 25 + C2; A2 := A2 shl 10 or A2 shr 22;
Inc(C2, Buffer[ 4] + $5C4DD124 + ((D2 and A2) or (E2 and not A2))); C2 := C2 shl 6 or C2 shr 26 + B2; E2 := E2 shl 10 or E2 shr 22;
Inc(B2, Buffer[ 9] + $5C4DD124 + ((C2 and E2) or (D2 and not E2))); B2 := B2 shl 15 or B2 shr 17 + A2; D2 := D2 shl 10 or D2 shr 22;
Inc(A2, Buffer[ 1] + $5C4DD124 + ((B2 and D2) or (C2 and not D2))); A2 := A2 shl 13 or A2 shr 19 + E2; C2 := C2 shl 10 or C2 shr 22;
Inc(E2, Buffer[ 2] + $5C4DD124 + ((A2 and C2) or (B2 and not C2))); E2 := E2 shl 11 or E2 shr 21 + D2; B2 := B2 shl 10 or B2 shr 22;
T := B1; B1 := B2; B2 := T;
Inc(D1, Buffer[ 3] + $6ED9EBA1 + ((E1 or not A1) xor B1)); D1 := D1 shl 11 or D1 shr 21 + C1; A1 := A1 shl 10 or A1 shr 22;
Inc(C1, Buffer[10] + $6ED9EBA1 + ((D1 or not E1) xor A1)); C1 := C1 shl 13 or C1 shr 19 + B1; E1 := E1 shl 10 or E1 shr 22;
Inc(B1, Buffer[14] + $6ED9EBA1 + ((C1 or not D1) xor E1)); B1 := B1 shl 6 or B1 shr 26 + A1; D1 := D1 shl 10 or D1 shr 22;
Inc(A1, Buffer[ 4] + $6ED9EBA1 + ((B1 or not C1) xor D1)); A1 := A1 shl 7 or A1 shr 25 + E1; C1 := C1 shl 10 or C1 shr 22;
Inc(E1, Buffer[ 9] + $6ED9EBA1 + ((A1 or not B1) xor C1)); E1 := E1 shl 14 or E1 shr 18 + D1; B1 := B1 shl 10 or B1 shr 22;
Inc(D1, Buffer[15] + $6ED9EBA1 + ((E1 or not A1) xor B1)); D1 := D1 shl 9 or D1 shr 23 + C1; A1 := A1 shl 10 or A1 shr 22;
Inc(C1, Buffer[ 8] + $6ED9EBA1 + ((D1 or not E1) xor A1)); C1 := C1 shl 13 or C1 shr 19 + B1; E1 := E1 shl 10 or E1 shr 22;
Inc(B1, Buffer[ 1] + $6ED9EBA1 + ((C1 or not D1) xor E1)); B1 := B1 shl 15 or B1 shr 17 + A1; D1 := D1 shl 10 or D1 shr 22;
Inc(A1, Buffer[ 2] + $6ED9EBA1 + ((B1 or not C1) xor D1)); A1 := A1 shl 14 or A1 shr 18 + E1; C1 := C1 shl 10 or C1 shr 22;
Inc(E1, Buffer[ 7] + $6ED9EBA1 + ((A1 or not B1) xor C1)); E1 := E1 shl 8 or E1 shr 24 + D1; B1 := B1 shl 10 or B1 shr 22;
Inc(D1, Buffer[ 0] + $6ED9EBA1 + ((E1 or not A1) xor B1)); D1 := D1 shl 13 or D1 shr 19 + C1; A1 := A1 shl 10 or A1 shr 22;
Inc(C1, Buffer[ 6] + $6ED9EBA1 + ((D1 or not E1) xor A1)); C1 := C1 shl 6 or C1 shr 26 + B1; E1 := E1 shl 10 or E1 shr 22;
Inc(B1, Buffer[13] + $6ED9EBA1 + ((C1 or not D1) xor E1)); B1 := B1 shl 5 or B1 shr 27 + A1; D1 := D1 shl 10 or D1 shr 22;
Inc(A1, Buffer[11] + $6ED9EBA1 + ((B1 or not C1) xor D1)); A1 := A1 shl 12 or A1 shr 20 + E1; C1 := C1 shl 10 or C1 shr 22;
Inc(E1, Buffer[ 5] + $6ED9EBA1 + ((A1 or not B1) xor C1)); E1 := E1 shl 7 or E1 shr 25 + D1; B1 := B1 shl 10 or B1 shr 22;
Inc(D1, Buffer[12] + $6ED9EBA1 + ((E1 or not A1) xor B1)); D1 := D1 shl 5 or D1 shr 27 + C1; A1 := A1 shl 10 or A1 shr 22;
Inc(D2, Buffer[15] + $6D703EF3 + ((E2 or not A2) xor B2)); D2 := D2 shl 9 or D2 shr 23 + C2; A2 := A2 shl 10 or A2 shr 22;
Inc(C2, Buffer[ 5] + $6D703EF3 + ((D2 or not E2) xor A2)); C2 := C2 shl 7 or C2 shr 25 + B2; E2 := E2 shl 10 or E2 shr 22;
Inc(B2, Buffer[ 1] + $6D703EF3 + ((C2 or not D2) xor E2)); B2 := B2 shl 15 or B2 shr 17 + A2; D2 := D2 shl 10 or D2 shr 22;
Inc(A2, Buffer[ 3] + $6D703EF3 + ((B2 or not C2) xor D2)); A2 := A2 shl 11 or A2 shr 21 + E2; C2 := C2 shl 10 or C2 shr 22;
Inc(E2, Buffer[ 7] + $6D703EF3 + ((A2 or not B2) xor C2)); E2 := E2 shl 8 or E2 shr 24 + D2; B2 := B2 shl 10 or B2 shr 22;
Inc(D2, Buffer[14] + $6D703EF3 + ((E2 or not A2) xor B2)); D2 := D2 shl 6 or D2 shr 26 + C2; A2 := A2 shl 10 or A2 shr 22;
Inc(C2, Buffer[ 6] + $6D703EF3 + ((D2 or not E2) xor A2)); C2 := C2 shl 6 or C2 shr 26 + B2; E2 := E2 shl 10 or E2 shr 22;
Inc(B2, Buffer[ 9] + $6D703EF3 + ((C2 or not D2) xor E2)); B2 := B2 shl 14 or B2 shr 18 + A2; D2 := D2 shl 10 or D2 shr 22;
Inc(A2, Buffer[11] + $6D703EF3 + ((B2 or not C2) xor D2)); A2 := A2 shl 12 or A2 shr 20 + E2; C2 := C2 shl 10 or C2 shr 22;
Inc(E2, Buffer[ 8] + $6D703EF3 + ((A2 or not B2) xor C2)); E2 := E2 shl 13 or E2 shr 19 + D2; B2 := B2 shl 10 or B2 shr 22;
Inc(D2, Buffer[12] + $6D703EF3 + ((E2 or not A2) xor B2)); D2 := D2 shl 5 or D2 shr 27 + C2; A2 := A2 shl 10 or A2 shr 22;
Inc(C2, Buffer[ 2] + $6D703EF3 + ((D2 or not E2) xor A2)); C2 := C2 shl 14 or C2 shr 18 + B2; E2 := E2 shl 10 or E2 shr 22;
Inc(B2, Buffer[10] + $6D703EF3 + ((C2 or not D2) xor E2)); B2 := B2 shl 13 or B2 shr 19 + A2; D2 := D2 shl 10 or D2 shr 22;
Inc(A2, Buffer[ 0] + $6D703EF3 + ((B2 or not C2) xor D2)); A2 := A2 shl 13 or A2 shr 19 + E2; C2 := C2 shl 10 or C2 shr 22;
Inc(E2, Buffer[ 4] + $6D703EF3 + ((A2 or not B2) xor C2)); E2 := E2 shl 7 or E2 shr 25 + D2; B2 := B2 shl 10 or B2 shr 22;
Inc(D2, Buffer[13] + $6D703EF3 + ((E2 or not A2) xor B2)); D2 := D2 shl 5 or D2 shr 27 + C2; A2 := A2 shl 10 or A2 shr 22;
T := C1; C1 := C2; C2 := T;
Inc(C1, Buffer[ 1] + $8F1BBCDC + ((D1 and A1) or (E1 and not A1))); C1 := C1 shl 11 or C1 shr 21 + B1; E1 := E1 shl 10 or E1 shr 22;
Inc(B1, Buffer[ 9] + $8F1BBCDC + ((C1 and E1) or (D1 and not E1))); B1 := B1 shl 12 or B1 shr 20 + A1; D1 := D1 shl 10 or D1 shr 22;
Inc(A1, Buffer[11] + $8F1BBCDC + ((B1 and D1) or (C1 and not D1))); A1 := A1 shl 14 or A1 shr 18 + E1; C1 := C1 shl 10 or C1 shr 22;
Inc(E1, Buffer[10] + $8F1BBCDC + ((A1 and C1) or (B1 and not C1))); E1 := E1 shl 15 or E1 shr 17 + D1; B1 := B1 shl 10 or B1 shr 22;
Inc(D1, Buffer[ 0] + $8F1BBCDC + ((E1 and B1) or (A1 and not B1))); D1 := D1 shl 14 or D1 shr 18 + C1; A1 := A1 shl 10 or A1 shr 22;
Inc(C1, Buffer[ 8] + $8F1BBCDC + ((D1 and A1) or (E1 and not A1))); C1 := C1 shl 15 or C1 shr 17 + B1; E1 := E1 shl 10 or E1 shr 22;
Inc(B1, Buffer[12] + $8F1BBCDC + ((C1 and E1) or (D1 and not E1))); B1 := B1 shl 9 or B1 shr 23 + A1; D1 := D1 shl 10 or D1 shr 22;
Inc(A1, Buffer[ 4] + $8F1BBCDC + ((B1 and D1) or (C1 and not D1))); A1 := A1 shl 8 or A1 shr 24 + E1; C1 := C1 shl 10 or C1 shr 22;
Inc(E1, Buffer[13] + $8F1BBCDC + ((A1 and C1) or (B1 and not C1))); E1 := E1 shl 9 or E1 shr 23 + D1; B1 := B1 shl 10 or B1 shr 22;
Inc(D1, Buffer[ 3] + $8F1BBCDC + ((E1 and B1) or (A1 and not B1))); D1 := D1 shl 14 or D1 shr 18 + C1; A1 := A1 shl 10 or A1 shr 22;
Inc(C1, Buffer[ 7] + $8F1BBCDC + ((D1 and A1) or (E1 and not A1))); C1 := C1 shl 5 or C1 shr 27 + B1; E1 := E1 shl 10 or E1 shr 22;
Inc(B1, Buffer[15] + $8F1BBCDC + ((C1 and E1) or (D1 and not E1))); B1 := B1 shl 6 or B1 shr 26 + A1; D1 := D1 shl 10 or D1 shr 22;
Inc(A1, Buffer[14] + $8F1BBCDC + ((B1 and D1) or (C1 and not D1))); A1 := A1 shl 8 or A1 shr 24 + E1; C1 := C1 shl 10 or C1 shr 22;
Inc(E1, Buffer[ 5] + $8F1BBCDC + ((A1 and C1) or (B1 and not C1))); E1 := E1 shl 6 or E1 shr 26 + D1; B1 := B1 shl 10 or B1 shr 22;
Inc(D1, Buffer[ 6] + $8F1BBCDC + ((E1 and B1) or (A1 and not B1))); D1 := D1 shl 5 or D1 shr 27 + C1; A1 := A1 shl 10 or A1 shr 22;
Inc(C1, Buffer[ 2] + $8F1BBCDC + ((D1 and A1) or (E1 and not A1))); C1 := C1 shl 12 or C1 shr 20 + B1; E1 := E1 shl 10 or E1 shr 22;
Inc(C2, Buffer[ 8] + $7A6D76E9 + ((D2 and E2) or (not D2 and A2))); C2 := C2 shl 15 or C2 shr 17 + B2; E2 := E2 shl 10 or E2 shr 22;
Inc(B2, Buffer[ 6] + $7A6D76E9 + ((C2 and D2) or (not C2 and E2))); B2 := B2 shl 5 or B2 shr 27 + A2; D2 := D2 shl 10 or D2 shr 22;
Inc(A2, Buffer[ 4] + $7A6D76E9 + ((B2 and C2) or (not B2 and D2))); A2 := A2 shl 8 or A2 shr 24 + E2; C2 := C2 shl 10 or C2 shr 22;
Inc(E2, Buffer[ 1] + $7A6D76E9 + ((A2 and B2) or (not A2 and C2))); E2 := E2 shl 11 or E2 shr 21 + D2; B2 := B2 shl 10 or B2 shr 22;
Inc(D2, Buffer[ 3] + $7A6D76E9 + ((E2 and A2) or (not E2 and B2))); D2 := D2 shl 14 or D2 shr 18 + C2; A2 := A2 shl 10 or A2 shr 22;
Inc(C2, Buffer[11] + $7A6D76E9 + ((D2 and E2) or (not D2 and A2))); C2 := C2 shl 14 or C2 shr 18 + B2; E2 := E2 shl 10 or E2 shr 22;
Inc(B2, Buffer[15] + $7A6D76E9 + ((C2 and D2) or (not C2 and E2))); B2 := B2 shl 6 or B2 shr 26 + A2; D2 := D2 shl 10 or D2 shr 22;
Inc(A2, Buffer[ 0] + $7A6D76E9 + ((B2 and C2) or (not B2 and D2))); A2 := A2 shl 14 or A2 shr 18 + E2; C2 := C2 shl 10 or C2 shr 22;
Inc(E2, Buffer[ 5] + $7A6D76E9 + ((A2 and B2) or (not A2 and C2))); E2 := E2 shl 6 or E2 shr 26 + D2; B2 := B2 shl 10 or B2 shr 22;
Inc(D2, Buffer[12] + $7A6D76E9 + ((E2 and A2) or (not E2 and B2))); D2 := D2 shl 9 or D2 shr 23 + C2; A2 := A2 shl 10 or A2 shr 22;
Inc(C2, Buffer[ 2] + $7A6D76E9 + ((D2 and E2) or (not D2 and A2))); C2 := C2 shl 12 or C2 shr 20 + B2; E2 := E2 shl 10 or E2 shr 22;
Inc(B2, Buffer[13] + $7A6D76E9 + ((C2 and D2) or (not C2 and E2))); B2 := B2 shl 9 or B2 shr 23 + A2; D2 := D2 shl 10 or D2 shr 22;
Inc(A2, Buffer[ 9] + $7A6D76E9 + ((B2 and C2) or (not B2 and D2))); A2 := A2 shl 12 or A2 shr 20 + E2; C2 := C2 shl 10 or C2 shr 22;
Inc(E2, Buffer[ 7] + $7A6D76E9 + ((A2 and B2) or (not A2 and C2))); E2 := E2 shl 5 or E2 shr 27 + D2; B2 := B2 shl 10 or B2 shr 22;
Inc(D2, Buffer[10] + $7A6D76E9 + ((E2 and A2) or (not E2 and B2))); D2 := D2 shl 15 or D2 shr 17 + C2; A2 := A2 shl 10 or A2 shr 22;
Inc(C2, Buffer[14] + $7A6D76E9 + ((D2 and E2) or (not D2 and A2))); C2 := C2 shl 8 or C2 shr 24 + B2; E2 := E2 shl 10 or E2 shr 22;
T := D1; D1 := D2; D2 := T;
Inc(B1, Buffer[ 4] + $A953FD4E + (C1 xor (D1 or not E1))); B1 := B1 shl 9 or B1 shr 23 + A1; D1 := D1 shl 10 or D1 shr 22;
Inc(A1, Buffer[ 0] + $A953FD4E + (B1 xor (C1 or not D1))); A1 := A1 shl 15 or A1 shr 17 + E1; C1 := C1 shl 10 or C1 shr 22;
Inc(E1, Buffer[ 5] + $A953FD4E + (A1 xor (B1 or not C1))); E1 := E1 shl 5 or E1 shr 27 + D1; B1 := B1 shl 10 or B1 shr 22;
Inc(D1, Buffer[ 9] + $A953FD4E + (E1 xor (A1 or not B1))); D1 := D1 shl 11 or D1 shr 21 + C1; A1 := A1 shl 10 or A1 shr 22;
Inc(C1, Buffer[ 7] + $A953FD4E + (D1 xor (E1 or not A1))); C1 := C1 shl 6 or C1 shr 26 + B1; E1 := E1 shl 10 or E1 shr 22;
Inc(B1, Buffer[12] + $A953FD4E + (C1 xor (D1 or not E1))); B1 := B1 shl 8 or B1 shr 24 + A1; D1 := D1 shl 10 or D1 shr 22;
Inc(A1, Buffer[ 2] + $A953FD4E + (B1 xor (C1 or not D1))); A1 := A1 shl 13 or A1 shr 19 + E1; C1 := C1 shl 10 or C1 shr 22;
Inc(E1, Buffer[10] + $A953FD4E + (A1 xor (B1 or not C1))); E1 := E1 shl 12 or E1 shr 20 + D1; B1 := B1 shl 10 or B1 shr 22;
Inc(D1, Buffer[14] + $A953FD4E + (E1 xor (A1 or not B1))); D1 := D1 shl 5 or D1 shr 27 + C1; A1 := A1 shl 10 or A1 shr 22;
Inc(C1, Buffer[ 1] + $A953FD4E + (D1 xor (E1 or not A1))); C1 := C1 shl 12 or C1 shr 20 + B1; E1 := E1 shl 10 or E1 shr 22;
Inc(B1, Buffer[ 3] + $A953FD4E + (C1 xor (D1 or not E1))); B1 := B1 shl 13 or B1 shr 19 + A1; D1 := D1 shl 10 or D1 shr 22;
Inc(A1, Buffer[ 8] + $A953FD4E + (B1 xor (C1 or not D1))); A1 := A1 shl 14 or A1 shr 18 + E1; C1 := C1 shl 10 or C1 shr 22;
Inc(E1, Buffer[11] + $A953FD4E + (A1 xor (B1 or not C1))); E1 := E1 shl 11 or E1 shr 21 + D1; B1 := B1 shl 10 or B1 shr 22;
Inc(D1, Buffer[ 6] + $A953FD4E + (E1 xor (A1 or not B1))); D1 := D1 shl 8 or D1 shr 24 + C1; A1 := A1 shl 10 or A1 shr 22;
Inc(C1, Buffer[15] + $A953FD4E + (D1 xor (E1 or not A1))); C1 := C1 shl 5 or C1 shr 27 + B1; E1 := E1 shl 10 or E1 shr 22;
Inc(B1, Buffer[13] + $A953FD4E + (C1 xor (D1 or not E1))); B1 := B1 shl 6 or B1 shr 26 + A1; D1 := D1 shl 10 or D1 shr 22;
Inc(B2, Buffer[12] + (C2 xor D2 xor E2)); B2 := B2 shl 8 or B2 shr 24 + A2; D2 := D2 shl 10 or D2 shr 22;
Inc(A2, Buffer[15] + (B2 xor C2 xor D2)); A2 := A2 shl 5 or A2 shr 27 + E2; C2 := C2 shl 10 or C2 shr 22;
Inc(E2, Buffer[10] + (A2 xor B2 xor C2)); E2 := E2 shl 12 or E2 shr 20 + D2; B2 := B2 shl 10 or B2 shr 22;
Inc(D2, Buffer[ 4] + (E2 xor A2 xor B2)); D2 := D2 shl 9 or D2 shr 23 + C2; A2 := A2 shl 10 or A2 shr 22;
Inc(C2, Buffer[ 1] + (D2 xor E2 xor A2)); C2 := C2 shl 12 or C2 shr 20 + B2; E2 := E2 shl 10 or E2 shr 22;
Inc(B2, Buffer[ 5] + (C2 xor D2 xor E2)); B2 := B2 shl 5 or B2 shr 27 + A2; D2 := D2 shl 10 or D2 shr 22;
Inc(A2, Buffer[ 8] + (B2 xor C2 xor D2)); A2 := A2 shl 14 or A2 shr 18 + E2; C2 := C2 shl 10 or C2 shr 22;
Inc(E2, Buffer[ 7] + (A2 xor B2 xor C2)); E2 := E2 shl 6 or E2 shr 26 + D2; B2 := B2 shl 10 or B2 shr 22;
Inc(D2, Buffer[ 6] + (E2 xor A2 xor B2)); D2 := D2 shl 8 or D2 shr 24 + C2; A2 := A2 shl 10 or A2 shr 22;
Inc(C2, Buffer[ 2] + (D2 xor E2 xor A2)); C2 := C2 shl 13 or C2 shr 19 + B2; E2 := E2 shl 10 or E2 shr 22;
Inc(B2, Buffer[13] + (C2 xor D2 xor E2)); B2 := B2 shl 6 or B2 shr 26 + A2; D2 := D2 shl 10 or D2 shr 22;
Inc(A2, Buffer[14] + (B2 xor C2 xor D2)); A2 := A2 shl 5 or A2 shr 27 + E2; C2 := C2 shl 10 or C2 shr 22;
Inc(E2, Buffer[ 0] + (A2 xor B2 xor C2)); E2 := E2 shl 15 or E2 shr 17 + D2; B2 := B2 shl 10 or B2 shr 22;
Inc(D2, Buffer[ 3] + (E2 xor A2 xor B2)); D2 := D2 shl 13 or D2 shr 19 + C2; A2 := A2 shl 10 or A2 shr 22;
Inc(C2, Buffer[ 9] + (D2 xor E2 xor A2)); C2 := C2 shl 11 or C2 shr 21 + B2; E2 := E2 shl 10 or E2 shr 22;
Inc(B2, Buffer[11] + (C2 xor D2 xor E2)); B2 := B2 shl 11 or B2 shr 21 + A2; D2 := D2 shl 10 or D2 shr 22;
T := E1; E1 := E2; E2 := T;
Inc(FDigest[0], A1);
Inc(FDigest[1], B1);
Inc(FDigest[2], C1);
Inc(FDigest[3], D1);
Inc(FDigest[4], E1);
Inc(FDigest[5], A2);
Inc(FDigest[6], B2);
Inc(FDigest[7], C2);
Inc(FDigest[8], D2);
Inc(FDigest[9], E2);
end;
class function THash_RipeMD320.DigestKeySize: Integer;
begin
Result := 40;
end;
end.
|
unit uwMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.DateUtils,
System.Classes, uMulticastStreamAnalyzer, System.SyncObjs, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls,
Vcl.Buttons,
Vcl.Grids,
IdIPMCastBase, IdIPMCastClient,
USLogger, Vcl.ComCtrls, VCLTee.TeEngine, VCLTee.Series, VCLTee.TeeProcs,
VCLTee.Chart, VCLTee.TeeSpline;
const
ERRORS_GRAPH_TIME = 5; // minutes
type
TWMain = class(TForm)
pnlControls: TPanel;
ledMulticastGroup: TLabeledEdit;
ledMulticastPort: TLabeledEdit;
bbtnStartStop: TBitBtn;
sgStats: TStringGrid;
lbLog: TListBox;
timerUpdateView: TTimer;
pcMainPageControl: TPageControl;
tsStats: TTabSheet;
tsLog: TTabSheet;
tsGraphBandwidth: TTabSheet;
tcGraphBandwidth: TChart;
tcsBandwidth: TLineSeries;
tcsPackets: TLineSeries;
tsGraphErrors: TTabSheet;
tcErrorsGraph: TChart;
tcsErrorsCount: TBarSeries;
timerCheckStream: TTimer;
ledBindingIP: TLabeledEdit;
cbExtendedMode: TCheckBox;
procedure bbtnStartStopClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure timerUpdateViewTimer(Sender: TObject);
procedure timerCheckStreamTimer(Sender: TObject);
procedure updateGrapsWidth(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
m_uSumPacketsCount: uint64;
m_uSumErrorsGraphed: uint64;
m_uStreamCheckPacketsCount: uint64; // Количество пакетов с последнего тика таймера проверки потока
m_bIsStreamContinuous: Boolean; // ???
m_bIsMulticastThreadRunning: Boolean;
m_tMulticastThread: TMulticastStreamAnalyzer;
m_sLogWriter: TStreamWriter;
function StartMulticastWatcher(MulticastGroup: string; MulticastPort: uint16; BindingIP: string = ''): boolean;
procedure StopMulticastWatcher;
public
constructor Create(AOwner: TComponent); override;
procedure Log(LogLevel: TLogLevel; Mess: string);
end;
var
WMain: TWMain;
implementation
{$R *.dfm}
constructor TWMain.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
m_uSumPacketsCount := 0;
m_bIsMulticastThreadRunning := False;
end;
procedure TWMain.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if (m_bIsMulticastThreadRunning) then
StopMulticastWatcher;
end;
procedure TWMain.FormCreate(Sender: TObject);
begin
pcMainPageControl.ActivePageIndex := 0;
sgStats.Cells[0, 0] := 'PID';
sgStats.Cells[1, 0] := 'Packets';
sgStats.Cells[2, 0] := 'Errors';
sgStats.Cells[3, 0] := 'Packets/sec';
sgStats.Cells[4, 0] := 'KBytes/sec';
tcsBandwidth.Clear;
tcsPackets.Clear;
tcGraphBandwidth.BottomAxis.DateTimeFormat := 'hh:nn:ss';
tcsErrorsCount.Clear;
tcErrorsGraph.BottomAxis.DateTimeFormat := 'hh:nn';
end;
procedure TWMain.bbtnStartStopClick(Sender: TObject);
var
idIPMCastClientTemp: TIdIPMCastClient;
begin
if (not m_bIsMulticastThreadRunning) then begin
idIPMCastClientTemp := TIdIPMCastClient.Create(nil);
if (idIPMCastClientTemp.IsValidMulticastGroup(ledMulticastGroup.Text)) then begin
if ((StrToInt(ledMulticastPort.Text) > 0) and (StrToInt(ledMulticastPort.Text) < 65535)) then begin
if (StartMulticastWatcher(ledMulticastGroup.Text, StrToInt(ledMulticastPort.Text), ledBindingIP.Text)) then begin
cbExtendedMode.Enabled := false;
ledMulticastGroup.Enabled := false;
ledMulticastPort.Enabled := false;
ledBindingIP.Enabled := false;
m_bIsMulticastThreadRunning := true;
bbtnStartStop.Caption := 'Stop';
end;
end else
ShowMessage('"' + ledMulticastPort.Text + '" is not valid port!');
end else
ShowMessage('"' + ledMulticastGroup.Text + '" is not valid multicast group!');
FreeAndNil(idIPMCastClientTemp);
end else begin
StopMulticastWatcher;
m_bIsMulticastThreadRunning := false;
bbtnStartStop.Caption := 'Start';
cbExtendedMode.Enabled := true;
ledMulticastGroup.Enabled := true;
ledMulticastPort.Enabled := true;
ledBindingIP.Enabled := true;
end;
end;
function TWMain.StartMulticastWatcher(MulticastGroup: string; MulticastPort: uint16; BindingIP: string = ''): boolean;
begin
Result := false;
m_uStreamCheckPacketsCount := 0;
m_bIsStreamContinuous := True;
try
m_sLogWriter := TStreamWriter.Create(ExtractFilePath(ParamStr(0)) + MulticastGroup + '.' + UIntToStr(MulticastPort) + '.log', true, TEncoding.UTF8);
m_tMulticastThread := TMulticastStreamAnalyzer.Create(MulticastGroup, MulticastPort, BindingIP);
// TODO: Log(llDebug, 'WiMP v???? started.');
Result := true;
except
on E: Exception do begin
Log(llDebug, 'Start error: ' + E.Message);
StopMulticastWatcher;
end;
end;
end;
procedure TWMain.StopMulticastWatcher;
begin
try
if (Assigned(m_tMulticastThread)) then
FreeAndNil(m_tMulticastThread);
except
on E: Exception do
Log(llDebug, 'Stop error: ' + E.Message);
end;
if (Assigned(m_sLogWriter)) then
FreeAndNil(m_sLogWriter);
end;
procedure TWMain.Log(LogLevel: TLogLevel; Mess: string);
var
DateInfo: string;
begin
DateInfo := '[' + DateToStr(Now()) + ' ' + TimeToStr(Now()) + ']';
lbLog.Items.Add(DateInfo + ' ' + Mess);
lbLog.TopIndex := lbLog.Items.Count - 1;
if (Assigned(m_sLogWriter)) then begin
m_sLogWriter.WriteLine(DateInfo + ' ' + Mess);
m_sLogWriter.Flush;
end;
end;
procedure TWMain.updateGrapsWidth(Sender: TObject);
begin
// Нужно ли?
end;
procedure TWMain.timerUpdateViewTimer(Sender: TObject);
var
i: integer;
SumPacketsCount: uint64;
SumErrorsCount: uint64;
CurrentDateTime: TDateTime;
CurrentDateTimeForGraph: TDateTime;
begin
SumPacketsCount := 0;
SumErrorsCount := 0;
CurrentDateTime := Now();
CurrentDateTimeForGraph := RecodeTime(CurrentDateTime, HourOfTheDay(CurrentDateTime), MinuteOfTheHour(CurrentDateTime) - (MinuteOfTheHour(CurrentDateTime) mod ERRORS_GRAPH_TIME), 0, 0);
if (Assigned(m_tMulticastThread)) then begin
if (Assigned(m_tMulticastThread.m_oCriticalSection)) then
m_tMulticastThread.m_oCriticalSection.Enter;
sgStats.RowCount := m_tMulticastThread.m_slStreamsInfo.Count + 2;
for i := 0 to m_tMulticastThread.m_slStreamsInfo.Count - 1 do begin
SumPacketsCount := SumPacketsCount + (m_tMulticastThread.m_slStreamsInfo.Objects[i] as TStreamInfo).m_uiPacketsCount;
SumErrorsCount := SumErrorsCount + (m_tMulticastThread.m_slStreamsInfo.Objects[i] as TStreamInfo).m_uiErrorsCount;
sgStats.Cells[0, i + 1] := '#' + IntToHex((m_tMulticastThread.m_slStreamsInfo.Objects[i] as TStreamInfo).m_uPID, 4);
sgStats.Cells[1, i + 1] := UIntToStr((m_tMulticastThread.m_slStreamsInfo.Objects[i] as TStreamInfo).m_uiPacketsCount);
sgStats.Cells[2, i + 1] := UIntToStr((m_tMulticastThread.m_slStreamsInfo.Objects[i] as TStreamInfo).m_uiErrorsCount);
sgStats.Cells[3, i + 1] := '-';
sgStats.Cells[4, i + 1] := '-';
end;
if (Assigned(m_tMulticastThread.m_oCriticalSection)) then
m_tMulticastThread.m_oCriticalSection.Leave;
// Пишем в статистику суммарную информацию
sgStats.Cells[0, sgStats.RowCount - 1] := 'Summary';
sgStats.Cells[1, sgStats.RowCount - 1] := UIntToStr(SumPacketsCount);
sgStats.Cells[2, sgStats.RowCount - 1] := UIntToStr(SumErrorsCount);
if (SumPacketsCount > m_uSumPacketsCount) then begin
sgStats.Cells[3, sgStats.RowCount - 1] := UIntToStr(SumPacketsCount - m_uSumPacketsCount);
sgStats.Cells[4, sgStats.RowCount - 1] := UIntToStr(Round((SumPacketsCount - m_uSumPacketsCount) / 7 * 1316 / 1024));
end else begin
sgStats.Cells[3, sgStats.RowCount - 1] := '0';
sgStats.Cells[4, sgStats.RowCount - 1] := '0';
end;
end;
// Добавляем на график
if (SumPacketsCount > m_uSumPacketsCount) then begin
tcsBandwidth.AddXY(Now(), (SumPacketsCount - m_uSumPacketsCount) / 7 * 1316 / 1024);
tcsPackets.AddXY(Now(), SumPacketsCount - m_uSumPacketsCount);
end else begin
tcsBandwidth.AddXY(Now(), 0);
tcsPackets.AddXY(Now(), 0);
end;
// Добавляем на график ошибок
if ((tcsErrorsCount.Count < 1) or (tcsErrorsCount.XValue[tcsErrorsCount.Count - 1] <> CurrentDateTimeForGraph)) then
tcsErrorsCount.AddXY(CurrentDateTimeForGraph, 0);
if (SumErrorsCount > m_uSumErrorsGraphed) then begin
if (tcsErrorsCount.XValue[tcsErrorsCount.Count - 1] = CurrentDateTimeForGraph) then begin
tcsErrorsCount.YValue[tcsErrorsCount.Count - 1] := tcsErrorsCount.YValue[tcsErrorsCount.Count - 1] + (SumErrorsCount - m_uSumErrorsGraphed);
end else
tcsErrorsCount.AddXY(CurrentDateTimeForGraph, SumErrorsCount - m_uSumErrorsGraphed);
end;
// Если количество пакетов было отличным от нуля - обновляем исторический счетчик
if (SumPacketsCount > 0) then
m_uSumPacketsCount := SumPacketsCount;
if (SumErrorsCount > 0) then
m_uSumErrorsGraphed := SumErrorsCount;
// Чистим графики
if (tcsBandwidth.Count > 900) then
tcsBandwidth.Delete(0);
if (tcsPackets.Count > 900) then
tcsPackets.Delete(0);
if (tcsErrorsCount.Count > 100) then
tcsErrorsCount.Delete(0);
end;
procedure TWMain.timerCheckStreamTimer(Sender: TObject);
var
SumPacketsCount: uint64;
i: integer;
begin
SumPacketsCount := 0;
if (m_bIsMulticastThreadRunning and Assigned(m_tMulticastThread)) then begin
if (Assigned(m_tMulticastThread.m_oCriticalSection)) then
m_tMulticastThread.m_oCriticalSection.Enter;
for i := 0 to m_tMulticastThread.m_slStreamsInfo.Count - 1 do begin
SumPacketsCount := SumPacketsCount + (m_tMulticastThread.m_slStreamsInfo.Objects[i] as TStreamInfo).m_uiPacketsCount;
end;
if (Assigned(m_tMulticastThread.m_oCriticalSection)) then
m_tMulticastThread.m_oCriticalSection.Leave;
end;
if (m_bIsMulticastThreadRunning and (SumPacketsCount <> 0)) then begin
if (SumPacketsCount <= m_uStreamCheckPacketsCount) then begin
if (m_bIsStreamContinuous) then begin
m_bIsStreamContinuous := False;
log(llWarning, 'Stream is not continuous.')
end;
end else
if (not m_bIsStreamContinuous) then begin
m_bIsStreamContinuous := True;
log(llWarning, 'Stream resumed.');
end;
m_uStreamCheckPacketsCount := SumPacketsCount;
end;
end;
end.
|
// cerner_2^5_2020
PROGRAM Convert;
VAR
Celsius, Fahrenheit: REAL;
BEGIN
Write('Enter Degrees C: ');
Read(Celsius);
Fahrenheit := (9.0 / 5.0) * Celsius + 32.0;
Write('Fahrenheit is ');
Write(ROUND(Fahrenheit));
END. |
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+}
{$M 1024,0,0}
{
by Behdad Esfahbod
Algorithmic Problems Book
April '2000
Problem 113 O(E) Dynamic Method
}
program
AndOrGraph;
const
MaxN = 100;
var
N : Integer;
G : array [1 .. MaxN, 0 .. MaxN] of Integer;
D : array [0 .. MaxN] of Longint;
W, P, T : array [1 .. MaxN] of Integer;
S : string;
I, J, K : Integer;
procedure ReadInput;
begin
Assign(Input, 'input.txt');
Reset(Input);
Readln(N);
for I := 1 to N do
begin
Readln(W[I], S);
J := 1;
while S[J] = ' ' do Inc(J);
if UpCase(S[J]) = 'O' then
T[I] := 0
else
T[I] := 1;
end;
for I := 1 to N - 1 do
begin
Readln(J, K);
Inc(G[J, 0]);
G[J, G[J, 0]] := K;
end;
Close(Input);
end;
procedure WritePath (V : Integer);
var
I : Integer;
begin
if V <> 1 then
Write(', ', V);
if (T[V] = 0) and (P[V] <> 0) then
WritePath(P[V])
else
for I := 1 to G[V, 0] do
WritePath(G[V, I]);
end;
procedure WriteOutput;
begin
Assign(Output, 'output.txt');
Rewrite(Output);
Write('A minimum valid set is: 1');
WritePath(1);
Writeln;
Writeln('Total weight = ', D[1]);
Close(Output);
end;
procedure Dfs (V : Integer);
var
I : Integer;
begin
if T[V] = 0 then
D[V] := MaxLongint div 2
else
D[V] := 0;
P[V] := 0;
for I := 1 to G[V, 0] do
begin
Dfs(G[V, I]);
if T[V] = 1 then
Inc(D[V], D[G[V, I]])
else
if D[V] > D[G[V, I]] then
begin
D[V] := D[G[V, I]];
P[V] := G[V, I];
end;
end;
if T[V] = 0 then
D[V] := D[P[V]];
Inc(D[V], W[V]);
end;
begin
ReadInput;
Dfs(1);
WriteOutput;
end.
|
unit ncsPrintPDF;
interface
uses
ncClassesBase,
SysUtils,
Windows,
Classes;
type
TncPrintItem = class
private
procedure StartPrintAdobe(aPrinterName: String);
procedure StartPrintCLPrint(aPrinterName: String);
procedure StartPrintGnostice(aPrinterName: String);
public
piArq: String;
piNaoImp: Array of Integer;
piPrinterDevMode: String;
piTotPages: Integer;
piProcessInfo : TProcessInformation;
piRetrato : Boolean;
constructor Create(aArq, aNaoImp, aPrinterDevMode: String; aTotPages: Integer; aRetrato: Boolean);
procedure StartPrint(aPrinterName: String);
function ImprimirPag(aPag: Integer): Boolean;
function Done: Boolean;
function Resultado: Cardinal;
destructor Destroy; override;
end;
TncPrinterQueue = class ( TThread )
private
FQueue : TThreadList;
protected
procedure Execute; override;
function GetNext: TncPrintItem;
public
PrinterName: String;
constructor Create(aPrinterName: String);
procedure Add(aArq, aNaoImp, aPrinterDevMode: String; aTotPages: Integer; aRetrato: Boolean);
destructor Destroy; override;
end;
TncPDFPrintManager = class
private
FQueues : TList;
function GetQueue(aPrinterName: String): TncPrinterQueue;
public
constructor Create;
destructor Destroy; override;
procedure Print(aArq, aNaoImp, aPrinterDevMode, aPrinterName: String; aTotPages: Integer; aRetrato: Boolean);
end;
implementation
uses ncPrinterInfo8, ncDebug;
{ TThreadPrintPDF }
const
OrientationStr : Array[boolean] of String = (' /orientation:landscape', ' /orientation:portrait');
function WinExecAndWait32(FileName: string; Visibility: Integer; var aPI: TProcessInformation): Boolean;
var { by Pat Ritchey }
zAppName: array[0..512] of Char;
zCurDir: array[0..255] of Char;
WorkDir: string;
StartupInfo: TStartupInfo;
begin
DebugMsg('ncsPrintPDf.WinExecAndWait32 - FileName: ' + FileName);
StrPCopy(zAppName, FileName);
GetDir(0, WorkDir);
StrPCopy(zCurDir, WorkDir);
FillChar(StartupInfo, SizeOf(StartupInfo), #0);
StartupInfo.cb := SizeOf(StartupInfo);
StartupInfo.dwFlags := STARTF_USESHOWWINDOW;
StartupInfo.wShowWindow := Visibility;
Result := CreateProcess(nil,
zAppName, // pointer to command line string
nil, // pointer to process security attributes
nil, // pointer to thread security attributes
False, // handle inheritance flag
CREATE_NEW_CONSOLE or // creation flags
NORMAL_PRIORITY_CLASS,
nil, //pointer to new environment block
nil, // pointer to current directory name
StartupInfo, // pointer to STARTUPINFO
aPI); // pointer to PROCESS_INF
end;
{ TncPrintItem }
function SoDig(S: String): String;
var I : Integer;
begin
Result := '';
for I := 1 to Length(S) do
if S[I] in ['0'..'9'] then
end;
constructor TncPrintItem.Create(aArq, aNaoImp, aPrinterDevMode: String;
aTotPages: Integer; aRetrato: Boolean);
var
S, sNex: String;
T, P: Integer;
function GetNextPage: Boolean;
var I: Integer;
begin
P := 0;
while (P=0) and (S>'') do begin
I := Pos(',', S);
if I=0 then begin
P := StrToIntDef(Trim(S), 0);
S := '';
end else begin
sNex := copy(S, 1, I-1);
P := StrToIntDef(Trim(sNex), 0);
Delete(S, 1, I);
end;
end;
Result := (P>0);
end;
begin
inherited Create;
DebugMsg('TncPrintItem.Create 1');
piArq := aArq;
T := 0;
SetLength(piNaoImp, 0);
S := aNaoImp;
DebugMsg('TncPrintItem.Create 2');
while GetNextPage do begin
Inc(T);
SetLength(piNaoImp, T);
piNaoImp[T-1] := P;
DebugMsg('TncPrintItem.Create - Nao Imprimir: ' + IntToStr(P));
end;
piPrinterDevMode := aPrinterDevMode;
piTotPages := aTotPages;
piProcessInfo.hProcess := 0;
piProcessInfo.hThread := 0;
piRetrato := aRetrato;
DebugMsg('TncPrintItem.Create - aArq:' + aArq + ' - NaoImp:'+aNaoImp+' - PrinterDevMode:'+aPrinterDevMode+' - aTotPages:'+IntToStr(aTotPages)+' - aRetrato: '+IntToStr(Integer(aRetrato)));
end;
destructor TncPrintItem.Destroy;
begin
if piProcessInfo.hProcess>0 then begin
CloseHandle(piProcessInfo.hProcess);
CloseHandle(piProcessInfo.hThread);
end;
TThreadDeleteFile.Create(piArq, 60000);
inherited;
end;
function TncPrintItem.Done: Boolean;
begin
Result := (piProcessInfo.hProcess=0) or (WaitForSingleObject(piProcessInfo.hProcess, 0)=0);
end;
function TncPrintItem.ImprimirPag(aPag: Integer): Boolean;
var I : Integer;
begin
for I := 0 to High(piNaoImp) do
if piNaoImp[I] = aPag then begin
Result := False;
Exit;
end;
Result := True;
end;
function TncPrintItem.Resultado: Cardinal;
begin
GetExitCodeProcess(piProcessInfo.hProcess, Result);
end;
procedure TncPrintItem.StartPrint(aPrinterName: String);
begin
DebugMsg('TncPrintItem.StartPrint - aPrinterName: ' + aPrinterName + ' - aArq: ' + piArq);
case gConfig.PMPDFPrintEng of
printeng_adobe : StartPrintAdobe(aPrinterName);
printeng_clprint : StartPrintCLPrint(aPrinterName);
printeng_gnostice : StartPrintGnostice(aPrinterName);
end;
end;
procedure TncPrintItem.StartPrintAdobe(aPrinterName: String);
var
SS : TStringStream;
S, Range: String;
I, L, UI : Integer;
procedure SaveRange;
begin
if L=0 then Exit;
Range := IntToStr(L);
if UI>=L then
Range := Range+'-'+IntToStr(UI);
L := 0;
if WinExecAndWait32(ExtractFilePath(ParamStr(0))+
'clprint.exe /print /adobe /printer:"'+aPrinterName+'" /pdffile:"'+piArq+'" /range:'+Range+OrientationStr[piRetrato], sw_Hide, piProcessInfo)
then begin
WaitForSingleObject(piProcessInfo.hProcess, INFINITE);
CloseHandle(piProcessInfo.hProcess);
CloseHandle(piProcessInfo.hThread);
piProcessInfo.hProcess := 0;
end;
end;
begin
DebugMsg('TncPrintItem.StartPrintAdobe - aPrinterName: ' + aPrinterName + ' - aArq: ' + piArq);
SS := TStringStream.Create(piPrinterDevMode);
try
RestorePrinterInfo8(PAnsiChar(aPrinterName), SS);
finally
SS.Free;
end;
L := 0;
Range := '';
if Length(piNaoImp)>0 then begin
for I := 1 to piTotPages do begin
if ImprimirPag(I) then begin
UI := I;
if L=0 then
L := I;
end else
SaveRange;
end;
SaveRange;
end else begin
DebugMsg('TncPrintItem.StartPrintAdobe - Sem Range');
WinExecAndWait32(ExtractFilePath(ParamStr(0))+
'clprint.exe /print /scale:none /adobe /printer:"'+aPrinterName+'" /pdffile:"'+piArq+'"'+OrientationStr[piRetrato], sw_Hide, piProcessInfo);
end;
end;
procedure TncPrintItem.StartPrintCLPrint(aPrinterName: String);
var
SS : TStringStream;
S, Range: String;
I, L, UI : Integer;
procedure SaveRange;
begin
if L=0 then Exit;
if Range>'' then Range := Range + ',';
Range := Range + IntToStr(L);
if UI>L then
Range := Range+'-'+IntToStr(UI);
L := 0;
end;
begin
DebugMsg('TncPrintItem.StartPrintCLPrint - aPrinterName: ' + aPrinterName + ' - aArq: ' + piArq);
SS := TStringStream.Create(piPrinterDevMode);
try
RestorePrinterInfo8(PAnsiChar(aPrinterName), SS);
finally
SS.Free;
end;
L := 0;
Range := '';
if Length(piNaoImp)>0 then begin
for I := 1 to piTotPages do begin
if ImprimirPag(I) then begin
UI := I;
if L=0 then
L := I;
end else
SaveRange;
end;
SaveRange;
Range := ' /range:'+Range;
end else begin
DebugMsg('TncPrintItem.StartPrintCLPrint - Sem Range');
Range := '';
end;
WinExecAndWait32(ExtractFilePath(ParamStr(0))+'clprint.exe /print /printer:"'+aPrinterName+'" /pdffile:"'+piArq+'"'+Range{+OrientationStr[piRetrato]}, sw_Hide, piProcessInfo);
end;
procedure TncPrintItem.StartPrintGnostice(aPrinterName: String);
begin
end;
{ TncPrinterQueue }
procedure TncPrinterQueue.Add(aArq, aNaoImp, aPrinterDevMode: String;
aTotPages: Integer; aRetrato: Boolean);
var I : TncPrintItem;
begin
DebugMsg('TncPrinterQueue.Add 1');
I := TncPrintItem.Create(aArq, aNaoImp, aPrinterDevMode, aTotPages, aRetrato);
DebugMsg('TncPrinterQueue.Add 2');
with FQueue.LockList do
try
DebugMsg('TncPrinterQueue.Add 3');
Add(I);
finally
FQueue.UnlockList;
end;
end;
constructor TncPrinterQueue.Create(aPrinterName: String);
begin
DebugMsg('TncPrinterQueue.Create - aPrinterName: ' + aPrinterName);
inherited Create(True);
FQueue := TThreadList.Create;
PrinterName := aPrinterName;
FreeOnTerminate := True;
Resume;
end;
destructor TncPrinterQueue.Destroy;
begin
with FQueue.LockList do
try
while Count > 0 do begin
TObject(Items[0]).Free;
Delete(0);
end;
finally
FQueue.UnlockList;
end;
FQueue.Free;
inherited;
end;
procedure TncPrinterQueue.Execute;
var PI : TncPrintItem;
begin
PI := nil;
DebugMsg('TncPrinterQueue.Execute - '+PrinterName);
while not Terminated do begin
try
if PI=nil then
PI := GetNext
else
if PI.Done then
with FQueue.LockList do
try
Remove(PI);
PI.Free;
PI := nil;
finally
FQueue.UnLockList;
end;
Sleep(200);
except
on E: Exception do
DebugMsg('TncPrinterQueue.Execute - Exception: ' + E.Message);
end;
end;
DebugMsg('TncPrinterQueue.Execute - Terminated: '+PrinterName);
end;
function TncPrinterQueue.GetNext: TncPrintItem;
begin
with FQueue.LockList do
try
if Count>0 then begin
DebugMsg('TncPrinterQueue.GetNext > 0');
Result := TncPrintItem(Items[0]);
end else
Result := nil;
finally
FQueue.UnlockList;
end;
if Result<>nil then
Result.StartPrint(PrinterName);
end;
{ TncPDFPrintManager }
constructor TncPDFPrintManager.Create;
begin
inherited;
FQueues := TList.Create;
end;
destructor TncPDFPrintManager.Destroy;
var I : Integer;
begin
for I := 0 to FQueues.Count-1 do
TThread(FQueues[I]).Terminate;
FQueues.Free;
inherited;
end;
function TncPDFPrintManager.GetQueue(
aPrinterName: String): TncPrinterQueue;
var I : Integer;
begin
DebugMsg('TncPDFPrintManager.GetQueue - aPrinterName: ' + aPrinterName);
for I := 0 to FQueues.Count-1 do
if SameText(TncPrinterQueue(FQueues[I]).PrinterName, aPrinterName) then begin
Result := TncPrinterQueue(FQueues[I]);
Exit;
end;
Result := TncPrinterQueue.Create(aPrinterName);
FQueues.Add(Result);
end;
procedure TncPDFPrintManager.Print(aArq, aNaoImp, aPrinterDevMode,
aPrinterName: String; aTotPages: Integer; aRetrato: Boolean);
begin
DebugMsg('TncPDFPrintManager.Print 1 - aPrinterName: ' + aPrinterName + ' - aArq: ' + aArq);
try
GetQueue(aPrinterName).Add(aArq, aNaoImp, aPrinterDevMode, aTotPages, aRetrato);
DebugMsg('TncPDFPrintManager.Print OK');
except
on E: Exception do
DebugMsg('TncPDFPrintManager.Print - Exception: ' + E.Message);
end;
end;
end.
|
unit eSocial.Models.DAO.Competencia;
interface
uses
Data.DB,
System.Generics.Collections,
eSocial.Models.DAO.Interfaces,
eSocial.Models.ComplexTypes,
eSocial.Models.Entities.Competencia,
eSocial.Models.Components.Connections.Interfaces;
type
TModelDAOCompetencia = class(TInterfacedObject, iModelDAOEntity<TCompetencia>)
private
FConnection : iModelComponentConnection;
FDataSet : TDataSource;
FEntity : TCompetencia;
procedure ReadFields;
public
constructor Create;
destructor Destroy; override;
class function New : iModelDAOEntity<TCompetencia>;
function DataSet(aValue : TDataSource) : iModelDAOEntity<TCompetencia>;
function Delete : iModelDAOEntity<TCompetencia>; virtual; abstract;
function Get : iModelDAOEntity<TCompetencia>; overload;
function Get(aID : String) : iModelDAOEntity<TCompetencia>; overload;
function Get(aParams : TDictionary<String, String>) : iModelDAOEntity<TCompetencia>; overload;
function Get(aParams : TArrayStrings) : iModelDAOEntity<TCompetencia>; overload;
function Insert : iModelDAOEntity<TCompetencia>; virtual; abstract;
function This : TCompetencia;
function Update : iModelDAOEntity<TCompetencia>; virtual; abstract;
end;
implementation
{ TModelDAOCompetencia }
uses
System.SysUtils,
eSocial.Models.Components.Connections.Factory;
constructor TModelDAOCompetencia.Create;
begin
FConnection := TModelComponentConnectionFactory.Connection;
FDataSet := TDataSource.Create(nil);
FDataSet.DataSet := FConnection.DataSet;
FEntity := TCompetencia.Create(Self);
end;
destructor TModelDAOCompetencia.Destroy;
begin
if Assigned(FDataSet) then
FDataSet.DisposeOf;
if Assigned(FEntity) then
FEntity.DisposeOf;
inherited;
end;
function TModelDAOCompetencia.Get(aParams: TDictionary<String, String>): iModelDAOEntity<TCompetencia>;
begin
Result := Self;
try
FConnection
.SQLClear
.SQL('Select')
.SQL(' c.competencia')
.SQL(' , c.ano')
.SQL(' , c.mes')
.SQL(' , c.descricao')
.SQL(' , c.encerrado')
.SQL(' , c.origem')
.SQL('from VW_ESOCIAL_COMPETENCIA c')
.SQL(' and (c.competencia = :competencia)')
.FetchParams
.AddParam('competencia', aParams.Items['competencia'])
.Open;
ReadFields;
aParams.DisposeOf;
except
on E : Exception do
raise Exception.Create('Erro ao consultar a competÍncia : ' + #13#13 + E.Message);
end;
end;
function TModelDAOCompetencia.Get(aID: String): iModelDAOEntity<TCompetencia>;
begin
Result := Self;
try
FConnection
.SQLClear
.SQL('Select')
.SQL(' c.competencia')
.SQL(' , c.ano')
.SQL(' , c.mes')
.SQL(' , c.descricao')
.SQL(' , c.encerrado')
.SQL(' , c.origem')
.SQL('from VW_ESOCIAL_COMPETENCIA c')
.SQL('where (c.origem = 1)');
if not aID.Trim.IsEmpty then
begin
FConnection
.SQL(' and (c.competencia = :id)')
.FetchParams
.AddParam('id', aID);
end;
FConnection.Open;
ReadFields;
except
on E : Exception do
raise Exception.Create('Erro ao consultar a competÍncia : ' + #13#13 + E.Message);
end;
end;
class function TModelDAOCompetencia.New: iModelDAOEntity<TCompetencia>;
begin
Result := Self.Create;
end;
procedure TModelDAOCompetencia.ReadFields;
begin
FEntity
.Ano( FDataSet.DataSet.FieldByName('ano').AsString )
.Codigo( FDataSet.DataSet.FieldByName('competencia').AsString )
.Descricao( FDataSet.DataSet.FieldByName('descricao').AsString )
.Encerrado( FDataSet.DataSet.FieldByName('encerrado').AsString )
.Mes( FDataSet.DataSet.FieldByName('mes').AsString )
.Origem( TOrigemDados(FDataSet.DataSet.FieldByName('origem').AsInteger) );
end;
function TModelDAOCompetencia.Get: iModelDAOEntity<TCompetencia>;
begin
Result := Self;
try
FConnection
.SQLClear
.SQL('Select')
.SQL(' c.competencia')
.SQL(' , c.ano')
.SQL(' , c.mes')
.SQL(' , c.descricao')
.SQL(' , c.encerrado')
.SQL(' , c.origem')
.SQL('from VW_ESOCIAL_COMPETENCIA c')
.SQL(' inner join GET_ESOCIAL_COMPETENCIA_ATIVA g on (g.competencia = c.competencia)')
.SQL('where (c.origem = 1)')
.Open;
if (FDataSet.DataSet.RecordCount = 0) then
FConnection
.SQLClear
.SQL('Select')
.SQL(' c.competencia')
.SQL(' , c.ano')
.SQL(' , c.mes')
.SQL(' , c.descricao')
.SQL(' , c.encerrado')
.SQL(' , c.origem')
.SQL('from VW_ESOCIAL_COMPETENCIA c')
.SQL(' inner join GET_ESOCIAL_COMPETENCIA_ATIVA g on (g.competencia = c.competencia)')
.SQL('where (c.origem = 0)')
.Open;
ReadFields;
except
on E : Exception do
raise Exception.Create('Erro ao consultar a competÍncia : ' + #13#13 + E.Message);
end;
end;
function TModelDAOCompetencia.DataSet(aValue: TDataSource): iModelDAOEntity<TCompetencia>;
begin
Result := Self;
FDataSet := aValue;
FDataSet.DataSet := FConnection.DataSet;
end;
function TModelDAOCompetencia.This: TCompetencia;
begin
Result := FEntity;
end;
function TModelDAOCompetencia.Get(aParams: TArrayStrings): iModelDAOEntity<TCompetencia>;
begin
Result := Self;
try
FConnection
.SQLClear
.SQL('Select')
.SQL(' c.competencia')
.SQL(' , c.ano')
.SQL(' , c.mes')
.SQL(' , c.descricao')
.SQL(' , c.encerrado')
.SQL(' , c.origem')
.SQL('from VW_ESOCIAL_COMPETENCIA c')
.SQL(' and (c.competencia = :competencia)')
.FetchParams
.AddParam('competencia', aParams[0])
.Open;
ReadFields;
except
on E : Exception do
raise Exception.Create('Erro ao consultar a competÍncia : ' + #13#13 + E.Message);
end;
end;
end.
|
{$F+,O-}
{$R-,S-} {must NOT have stack checking!}
{
Trixter's interrupt and timer unit. Version 0.41 20191219
This unit wouldn't be possible without the hard work and writing of:
Mark Feldman
Kris Heidenstrom (RIP)
Klaus Hartnegg
Thank you gentlemen!
See tinttest.pas for example usage.
Version 0.3 20130503 added PCjr vint stuff
}
{{$DEFINE HIDDEN} {define if CGAVINT needs to start in vertical retrace only}
unit TInterrupts;
interface
const
sysclockfreq=(315/22) * 1000000; {system clock derived from NTSC 14.318182 MHz }
PITFreq=round(sysclockfreq / 12); {Programmable Interrupt Timer frequency, should be $1234de}
{PITfreq=(13125000/11);} {this is also valid}
{PITfreq=(105000000/88);} {this is also valid}
tickHz=PITFreq / 65536;
usecPerTick=1000000 / PITFreq; {# of microseconds per system tick}
CGAFrameCycles=(912*262) div 12; {# of PIT cycles per CGA display frame}
SystemTimerInt=8;
CTCModeCommandReg=$43; {write only; reads are ignored}
{Some constants to help make sense of the 8253. Values are listed for
BCD/Binary mode, operating mode, command/access mode, and channel select.
Implied "zero" values are also listed for completeness.}
{BCD or Binary mode:}
iMC_BinaryMode=0;
iMC_BCDMode=1;
{Operating modes 0 through 5 (extended duplicates for 2 and 3 not listed)}
iMC_OpMode0=0; {Interrupt on terminal count}
iMC_OpMode1=2; {Hardware-retriggerable one-shot}
iMC_OpMode2=4; {Rate generator}
iMC_OpMode3=iMC_OpMode1+iMC_OpMode2; {Square wave generator}
iMC_OpMode4=8; {Software-triggered strobe}
iMC_OpMode5=iMC_OpMode4+iMC_OpMode1; {Hardware-triggered strobe}
{Command/Access mode: value, lobyte only, hibyte only, lowbyte/hibyte}
iMC_LatchCounter=0;
iMC_AMLB=16;
iMC_AMHB=32;
iMC_AMLH=iMC_AMLB+iMC_AMHB;
{Channel select:}
iMC_Chan0=0;
iMC_Chan1=64;
iMC_Chan2=128;
iMC_ReadBack=iMC_Chan1+iMC_Chan2; {8254 only!}
{The PITcycles variable will keep track of how many cycles the PIT has
had, it'll be intialised to 0. The Chan0Counter variable will hold the new
channel 0 counter value. We'll also be adding this number to PITcycles
every time our handler is called.}
type
{Thanks to Jason Burgon for the idea: this record allows us to get away
with 16-bit math when dealing with longint counters in handlers. See the
example handler code in TINTTEST.PAS for example usage.}
LongRec=packed record
lo:word;
hi:integer;
end;
var
BIOSTimerHandler:procedure;
VINTsave:pointer;
PITcycles,
Chan0Counter:longint;
procedure InitChannel(channel,accessMode,mode:byte;divisor:word);
{Inits a channel -- mostly used internally but public interface
provided in case you want to do something custom}
procedure SetTimerHz(TimerHandler:pointer;frequency:word);
procedure SetTimerExact(TimerHandler:pointer;cycles:word);
procedure SetTimerCGAVINT(TimerHandler:pointer);
{
Save the address of the BIOS handler, install our own, set up the
variables we'll use and program PIT channel 0 for the divide-by-N mode
at the frequency we need.
In the case of CGAVINT, we simulate a vertical retrace interrupt that
fires "early", directly after the last drawn scanline. This gives us
some extra time to do things before we start retracing back up the screen.
}
procedure HookPCjrVINT(newVINTHandler:pointer);
procedure unHookPCjrVINT;
{Hooks an interrupt handler to the PCjr hardware vertical retrace interrupt}
procedure CleanUpTimer;
{Reset everything back to the way we left it}
Procedure Chan2SquarewaveOn(newfreq:word);
{ties the speaker input to CTC channel 2 and programs it for square wave output}
Procedure Chan2SquarewaveChange(newfreq:word);
{Reprograms CTC channel 2 only}
Procedure Chan2SquarewaveOff;
{unhooks the speaker from CTC channel 2}
Function ticks2usec(l:longint):longint;
{Converts tick counts from the 8253 into microseconds}
implementation
(*
The Mode/Command register at I/O address 43h is defined as follows:
7 6 5 4 3 2 1 0
* * . . . . . . Select channel: 0 0 = Channel 0
0 1 = Channel 1
1 0 = Channel 2
1 1 = Read-back command (8254 only) (Illegal on 8253) (Illegal on PS/2)
. . * * . . . . Cmd./Access mode: 0 0 = Latch count value command
0 1 = Access mode: lobyte only
1 0 = Access mode: hibyte only
1 1 = Access mode: lobyte/hibyte
. . . . * * * . Operating mode: 0 0 0 = Mode 0
0 0 1 = Mode 1
0 1 0 = Mode 2
0 1 1 = Mode 3
1 0 0 = Mode 4
1 0 1 = Mode 5
1 1 0 = Mode 2
1 1 1 = Mode 3
. . . . . . . * BCD/Binary mode: 0 = 16-bit binary
1 = four-digit BCD
The SC1 and SC0 (Select Channel) bits form a two-bit binary code which tells
the CTC which of the three channels (channels 0, 1, and 2) you are talking to,
or specifies the read-back command. As there are no 'overall' or 'master'
operations or configurations, every write access to the mode/command register,
except for the read-back command, applies to one of the channels. These
bits must always be valid on every write of the mode/command register,
regardless of the other bits or the type of operation being performed.
The RL1 and RL0 bits (Read/write/Latch) form a two-bit code which tells the CTC
what access mode you wish to use for the selected channel, and also specify the
Counter Latch command to the CTC. For the Read-back command, these bits have a
special meaning. These bits also must be valid on every write access to
the mode/command register.
The M2, M1, and M0 (Mode) bits are a three-bit code which tells the selected
channel what mode to operate in (except when the command is a Counter Latch
command, i.e. RL1,0 = 0,0, where they are ignored, or when the command is a
Read-back command, where they have special meanings).
These bits must be valid on all mode selection commands (all writes to the
mode/command register except when RL1,RL0 = 0,0 or when SC1,0 = 1,1).
*)
uses
m6845ctl,
dos;
const
lastSpeakerFreq:word=$ffff;
function ticks2usec(l:longint):longint;
{converts number of 8253 ticks to microseconds}
begin
ticks2usec:=trunc(l / usecPerTick);
end;
Procedure InitChannel(channel,accessMode,mode:byte;divisor:word);
const
chan0base=$40;
var
modecmd,lobyte,hibyte,chanport:byte;
begin
{check for valid input allowed:
only channels 0 and 2 (1 is for DRAM REFRESH, do NOT touch!)
only accessmodes 1 through 3 (0 is not an access mode)}
if not (channel in [0,2]) or not (accessMode in [1..3]) then exit;
{precalc how we're going to set the channel, so we don't tie up too much
time with interrupts turned off}
modecmd:=(channel shl 6) + (accessMode shl 4) + ((mode AND $7) shl 1); {bit 0 always 0 for 16-bit mode}
lobyte:=lo(divisor);
hibyte:=hi(divisor);
chanport:=chan0base+channel;
{must make these changes atomic, so disable interrupts before starting}
asm pushf; cli end;
port[CTCModeCommandReg]:=modecmd;
port[chanport]:=lobyte; (* Reload reg lobyte *)
port[chanport]:=hibyte; (* Reload reg hibyte *)
asm popf end;
end;
Procedure InitChannelCGAVINT(channel,accessMode,mode:byte;divisor:word);
const
chan0base=$40;
var
modecmd,lobyte,hibyte,chanport:byte;
begin
{check for valid input allowed:
only channels 0 and 2 (1 is for DRAM REFRESH, do NOT touch!)
only accessmodes 1 through 3 (0 is not an access mode)}
if not (channel in [0,2]) or not (accessMode in [1..3]) then exit;
{precalc how we're going to set the channel, so we don't tie up too much
time with interrupts turned off}
modecmd:=(channel shl 6) + (accessMode shl 4) + ((mode AND $7) shl 1); {bit 0 always 0 for 16-bit mode}
lobyte:=lo(divisor);
hibyte:=hi(divisor);
chanport:=chan0base+channel;
{must make these changes atomic, so disable interrupts before starting}
asm
{get to end of display cycle}
mov dx,m6845_status
mov bl,c_vertical_sync
mov bh,c_display_enable or c_vertical_sync
mov ah,c_display_enable
mov cx,199
pushf
cli
{$IFNDEF HIDDEN}
@WDR:
in al,dx
test al,bl
jz @WDR {wait if not vertically retracing}
{Now we are tracing back up the screen. Wait until first scanline.}
@hor1:
in al,dx
test al,bh
jnz @hor1 {wait until not horizontally or vertically retracing}
{Now we are drawing our first scanline.}
@hor2:
in al,dx
test al,ah
jz @hor2 {wait until horizontally retracing}
loop @hor1 {loop 199 more times}
{$ELSE}
@WDR: {wait during retrace, because we don't know where we are in the cycle}
in al,dx
test al,bl {if our bit is 1, then we're already in retrace; we missed it}
jnz @WDR {jump if 1 (not 0) = keep looping as long as we're retracing}
@WDD: {wait for display to be over}
in al,dx
test al,bl
jz @WDD {loop until we aren't drawing any more (ie. retracing)}
{$ENDIF}
{set new rate}
mov al,modecmd
out CTCModeCommandReg,al
xor dx,dx
mov dl,chanport
mov al,lobyte
out dx,al
mov al,hibyte
out dx,al
popf
end;
end;
procedure SetTimerHz(TimerHandler : pointer; frequency : word);
begin
{ Do some initialization }
PITcycles := 0;
Chan0Counter := PITFreq div frequency;
{ Store the current BIOS handler and set up our own }
GetIntVec(SystemTimerInt, @BIOSTimerHandler);
SetIntVec(SystemTimerInt, TimerHandler);
{init channel 0, 3=access mode lobyte/hibyte, mode 2, 16-bit binary}
InitChannel(0,3,2,Chan0Counter);
end;
procedure SetTimerExact(TimerHandler : pointer; cycles : word);
begin
{ Do some initialization }
PITcycles := 0;
Chan0Counter := cycles;
{ Store the current BIOS handler and set up our own }
GetIntVec(SystemTimerInt, @BIOSTimerHandler);
SetIntVec(SystemTimerInt, TimerHandler);
{init channel 0, 3=access mode lobyte/hibyte, mode 2, 16-bit binary}
InitChannel(0,3,2,Chan0Counter);
end;
procedure SetTimerCGAVINT(TimerHandler : pointer);
begin
{ Do some initialization }
PITcycles := 0;
Chan0Counter := CGAFrameCycles;
{ Store the current BIOS handler and set up our own }
GetIntVec(SystemTimerInt, @BIOSTimerHandler);
SetIntVec(SystemTimerInt, TimerHandler);
{init channel 0, 3=access mode lobyte/hibyte, mode 2, 16-bit binary}
InitChannelCGAVINT(0,3,2,Chan0Counter);
end;
procedure CleanUpTimer;
begin
{ Restore the normal clock frequency to original BIOS tick rate }
{init channel 0, 3=access mode lobyte/hibyte, mode 2, 16-bit binary}
InitChannel(0,3,2,$0000);
{ Restore the normal tick handler }
SetIntVec(SystemTimerInt, @BIOSTimerHandler);
end;
Procedure Chan2SquarewaveOn;
begin
{if we're not already sounding the new requested frequency, and the new
frequency is large enough that it won't result in a divisor of 1, proceed:}
if (lastSpeakerFreq<>newFreq) and (newfreq>18) then begin
lastSpeakerFreq:=newFreq;
{Set CTC Channel 2, 16-bit, mode 3, squarewave frequency}
InitChannel(2, 3, 3, PITFreq div newfreq);
asm pushf; cli end;
{Enable speaker and tie input pin to CTC Chan 2 by setting bits 1 and 0}
port[$61]:=(port[$61] OR $3);
asm popf end;
end;
end;
Procedure Chan2SquarewaveChange;
{A bit of assembler and specialization here because 1. we know exactly what
channel we're changing, and 2. we need speed here since changing the speaker's
frequency is something that happens a lot if playing music or sound effects}
var
divisor:word;
begin
{if we're not already sounding the new requested frequency, and the new
frequency is large enough that it won't result in a divisor of 1, proceed:}
if (lastSpeakerFreq<>newFreq) and (newfreq>18) then begin
lastSpeakerFreq:=newFreq;
divisor:=PITFreq div newfreq;
asm
mov dx,$42 {channel 2}
mov ax,divisor
pushf {save flags because we don't know who/what is calling us}
cli {must be atomic, so disable interrupts before starting}
out dx,al {output lowbyte}
mov al,ah {copy highbyte to AL}
out dx,al {output highbyte}
popf
end;
end;
end;
Procedure Chan2SquarewaveOff;
begin
asm pushf; cli end;
{Disable speaker and CTC Chan 2 tie by clearing bits 1 and 0}
port[$61]:=(port[$61] AND (NOT $3));
asm popf end;
lastSpeakerFreq:=$ffff; {set to some value the user will never enter}
end;
procedure HookPCjrVINT(newVINTHandler:pointer);
begin
{ Store the current BIOS handler and set up our own }
GetIntVec(5+8, VINTsave);
SetIntVec(5+8, newVINTHandler);
{Enable hardware interrupt 5 in PIC}
asm
mov dx,$21
in al,dx {bring in current PIC mask}
and al,not (1 SHL 5){AND to enable, OR to disable}
out dx,al {update PIC mask}
end;
end;
procedure unHookPCjrVINT;
begin
{Disable hardware interrupt 5 in PIC}
asm
mov dx,$21
in al,dx {bring in current PIC mask}
or al,1 SHL 5 {AND to enable, OR to disable}
out dx,al {update PIC mask}
end;
{Restore old handler}
SetIntVec(5+8, VINTsave);
{Enable hardware interrupt 5 in PIC}
asm
mov dx,$21
in al,dx {bring in current PIC mask}
and al,not (1 SHL 5){AND to enable, OR to disable}
out dx,al {update PIC mask}
end;
{There's actually no point in turning the PCjr VINT IRQ5 back on because
the default handler at f000:f815 in a real PCjr disables it on first call,
implying that the vint is for user programs only. But we do it here to
be an example of best practices.}
end;
end.
(*
While you could write a small procedure that is called by the interrupt
handler, that would just kill the purpose of the handler because you'd
be doing two CALLs instead of one. You'll just have to write the handler
yourself, but since that sucks, there is an example you can steal in
the program TINTTEST.PAS which should be in the same location as this code.
*)
|
unit Security;
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, DBCtrls, DBTables, DB, Buttons, Grids,
Wwdbigrd, Wwdbgrid, ExtCtrls, Wwtable, Wwdatsrc, Menus, RPCanvas,
RPrinter, RPDefine, RPBase, RPFiler;
type
TMenuSecurityForm = class(TForm)
MenuSecurityDataSource: TwwDataSource;
MenuSecurityTable: TwwTable;
Panel1: TPanel;
Panel2: TPanel;
TitleLabel: TLabel;
MenuSecurityTableMenuID: TSmallintField;
MenuSecurityTableMenuDescription: TStringField;
MenuSecurityTableSecurityLevel: TSmallintField;
MenuSecurityTableDisableIfUnderAccess: TBooleanField;
ReportFiler: TReportFiler;
ReportPrinter: TReportPrinter;
PrintDialog: TPrintDialog;
Panel3: TPanel;
PrintButton: TBitBtn;
DBNavigator: TDBNavigator;
SynchButton: TButton;
CloseButton: TBitBtn;
MenuSecurityDBGrid: TwwDBGrid;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure SynchButtonClick(Sender: TObject);
procedure MenuSecurityTableSecurityLevelValidate(Sender: TField);
procedure PrintButtonClick(Sender: TObject);
procedure ReportPrintHeader(Sender: TObject);
procedure ReportPrint(Sender: TObject);
procedure FormActivate(Sender: TObject);
private
{ Private declarations }
UnitName : String;
public
{ Public declarations }
MainMenuIDs,
MainMenuDescriptions : TStringList;
FormAccessRights : Integer; {Read only or read write, based on security level?}
{Values = raReadOnly, raReadWrite}
Procedure InitializeForm; {Open the tables and setup.}
end;
var
MenuSecurityForm: TMenuSecurityForm;
implementation
uses GlblVars, WinUtils, Utilitys, PASUTILS, UTILEXSD, GlblCnst, ParclTab, UtilPrcl,
Preview, PASTypes;
{$R *.DFM}
{========================================================}
Procedure TMenuSecurityForm.FormActivate(Sender: TObject);
begin
SetFormStateMaximized(Self);
end;
{========================================================}
Procedure TMenuSecurityForm.InitializeForm;
begin
UnitName := 'SECURITY.PAS';
{Note that since this does not have anything to do with tax
roll year, the only thing that determines the access rights
for this form are the menu security levels.}
If (FormAccessRights = raReadOnly)
then MenuSecurityTable.ReadOnly := True;
OpenTablesForForm(Self, GlblProcessingType);
{If this is the SCA user ID, then we will allow insert on
the navigator bar so that we can add menu ID's for the parcel
popup menu.}
{FXX01211998-5: Actually allow the supervisor to do this since no
backdoor has been created.}
{CHG06092010-3(2.26.1)[I7208]: Allow for supervisor equivalents.}
If UserIsSupervisor(GlblUserName)
then
begin
DBNavigator.VisibleButtons := DBNavigator.VisibleButtons + [nbInsert, nbDelete];
MenuSecurityTableMenuID.ReadOnly := False;
MenuSecurityTableMenuDescription.ReadOnly := False;
SynchButton.Visible := True;
end; {If (GlblUserName = Take(10, 'SCABOAT'))}
end; {InitializeForm}
{===================================================================}
Procedure TMenuSecurityForm.SynchButtonClick(Sender: TObject);
var
I, MenuID : Integer;
Done, FirstTimeThrough, Found : Boolean;
Form : TForm;
TempStr : String;
begin
Found := False;
{CHG10191997-4: Add security entries for parcel pages.}
Form := TParcelTabForm.Create(nil);
with TParcelTabForm(Form) do
For I := 0 to (ComponentCount - 1) do
If ((Components[I] is TMenuItem) and
(Components[I].Tag > 0))
then
with Components[I] as TMenuItem do
begin
MainMenuIDs.Add(IntToStr(Tag));
TempStr := LTrim(Caption);
{Add tags for residential and commercial.}
If ((Tag >= ResidentialSiteFormNumber) and
(Tag <= ResidentialImprovementsFormNumber))
then TempStr := 'Residential ' + TempStr;
If ((Tag >= CommercialSiteFormNumber) and
(Tag <= CommercialIncomeExpenseFormNumber))
then TempStr := 'Commercial ' + TempStr;
MainMenuDescriptions.Add(StripChar(TempStr, '&', ' ', False));
end; {with Components[I] as TMenuItem do}
Form.Free;
MenuSecurityTableMenuID.ReadOnly := False;
MenuSecurityTableMenuDescription.ReadOnly := False;
MenuSecurityTable.DisableControls;
For I := 0 to (MainMenuIDs.Count - 1) do
begin
MenuID := StrToInt(MainMenuIDs[I]);
If ((MenuID > 0) and
(MenuID < 20000)) {SCA system functions}
then
begin
try
Found := FindKeyOld(MenuSecurityTable, ['MenuID'],
[IntToStr(MenuID)]);
except
SystemSupport(002, MenuSecurityTable, 'Error getting security record.',
UnitName, GlblErrorDlgBox);
end;
{FXX02191999-2: Fix duplicates error when doing synchronize.}
If Found
then
begin
{If the name changed associated with this menu item, store the new name.}
If (MenuSecurityTableMenuDescription.Text <> Take(40, MainMenuDescriptions[I]))
then
begin
MenuSecurityTable.Edit;
MenuSecurityTableMenuDescription.Text := Take(40, MainMenuDescriptions[I]);
MenuSecurityTableSecurityLevel.AsInteger := 5;
MenuSecurityTableDisableIfUnderAccess.AsBoolean := False;
try
MenuSecurityTable.Post;
except
SystemSupport(003, MenuSecurityTable, 'Error posting to security table.',
UnitName, GlblErrorDlgBox);
MenuSecurityTable.Cancel;
end;
end; {If (MenuSecurityTableMenuDescription.Text <> Take(40, MainMenuDescriptions[I])}
end
else
begin
MenuSecurityTable.Insert;
MenuSecurityTableMenuID.AsInteger := MenuID;
MenuSecurityTableMenuDescription.Text := Take(40, MainMenuDescriptions[I]);
MenuSecurityTableSecurityLevel.AsInteger := 5;
MenuSecurityTableDisableIfUnderAccess.AsBoolean := False;
try
MenuSecurityTable.Post;
except
SystemSupport(004, MenuSecurityTable, 'Error posting to security table.',
UnitName, GlblErrorDlgBox);
MenuSecurityTable.Cancel;
end;
end; {If not Found}
end; {If (MenuID > 0)}
end; {with MainFormComponents[I] as TMenuItem}
{Now we will go through the file and look in the list for
these IDs. If they are not there, we will delete the record.
This is for menu items that have been deleted.}
FirstTimeThrough := True;
Done := False;
try
MenuSecurityTable.First;
except
SystemSupport(005, MenuSecurityTable, 'Error getting 1st record in security table.',
UnitName, GlblErrorDlgBox);
end;
repeat
If FirstTimeThrough
then FirstTimeThrough := False
else
try
MenuSecurityTable.Next;
except
SystemSupport(006, MenuSecurityTable, 'Error getting next record in security table.',
UnitName, GlblErrorDlgBox);
end;
If MenuSecurityTable.EOF
then Done := True;
If (MainMenuIDs.IndexOf(MenuSecurityTableMenuID.AsString) = -1)
then
try
MenuSecurityTable.Delete;
except
SystemSupport(007, MenuSecurityTable, 'Error deleting record in security table.',
UnitName, GlblErrorDlgBox);
end;
until Done;
MenuSecurityTableMenuID.ReadOnly := True;
MenuSecurityTableMenuDescription.ReadOnly := True;
MenuSecurityTable.First;
MenuSecurityTable.EnableControls;
end; {SynchButtonClick}
{==============================================================}
Procedure TMenuSecurityForm.MenuSecurityTableSecurityLevelValidate(Sender: TField);
begin
If not (MenuSecurityTableSecurityLevel.AsInteger in [1..10])
then
begin
MessageDlg('The security level must be between 1 and 10.', mtError, [mbOK], 0);
RefreshNoPost(MenuSecurityTable);
end;
end; {MenuSecurityTableSecurityLevelValidate}
{=====================================================================}
Procedure TMenuSecurityForm.PrintButtonClick(Sender: TObject);
{FXX02191999-3: Add print capability to security levels.}
var
Quit : Boolean;
NewFileName : String;
begin
Quit := False;
If PrintDialog.Execute
then
begin
PrintButton.Enabled := False;
MenuSecurityTable.DisableControls;
MenuSecurityTable.First;
AssignPrinterSettings(PrintDialog, ReportPrinter, ReportFiler, [ptBoth], False, Quit);
If not Quit
then
If PrintDialog.PrintToFile
then
begin
NewFileName := GetPrintFileName(Self.Caption, True);
ReportFiler.FileName := NewFileName;
GlblPreviewPrint := True;
try
PreviewForm := TPreviewForm.Create(self);
PreviewForm.FilePrinter.FileName := NewFileName;
PreviewForm.FilePreview.FileName := NewFileName;
ReportFiler.Execute;
PreviewForm.ShowModal;
finally
PreviewForm.Free;
{Now delete the file.}
try
Chdir(GlblReportDir);
OldDeleteFile(NewFileName);
finally
{We don't care if it does not get deleted, so we won't put up an
error message.}
ChDir(GlblProgramDir);
end;
end; {try PreviewForm := ...}
end {If PrintDialog.PrintToFile}
else ReportPrinter.Execute;
MenuSecurityTable.EnableControls;
PrintButton.Enabled := True;
end; {If PrintDialog.Execute}
end; {PrintButtonClick}
{=================================================================}
Procedure TMenuSecurityForm.ReportPrintHeader(Sender: TObject);
begin
with Sender as TBaseReport do
begin
{Print the date and page number.}
SectionTop := 0.25;
SectionLeft := 0.5;
SectionRight := PageWidth - 0.5;
SetFont('Times New Roman',8);
PrintHeader('Page: ' + IntToStr(CurrentPage), pjRight);
PrintHeader('Date: ' + DateToStr(Date) + ' Time: ' + TimeToStr(Now), pjLeft);
SectionTop := 0.5;
SetFont('Times New Roman',10);
Bold := True;
Home;
PrintCenter('Menu Security Settings', (PageWidth / 2));
Bold := False;
CRLF;
CRLF;
Underline := True;
ClearTabs;
SetTab(0.3, pjLeft, 0.5, 0, BOXLINENONE, 0); {Menu ID}
SetTab(1.0, pjLeft, 3.0, 0, BOXLINENONE, 0); {Desc}
SetTab(4.1, pjLeft, 0.5, 0, BOXLINENONE, 0); {Level}
SetTab(4.7, pjLeft, 1.0, 0, BOXLINENONE, 0); {Disable}
Println(#9 + 'Menu ID' +
#9 + 'Description' +
#9 + 'Level' +
#9 + 'Disable?');
Underline := False;
ClearTabs;
SetTab(0.3, pjLeft, 0.5, 0, BOXLINENONE, 0); {Menu ID}
SetTab(1.0, pjLeft, 3.0, 0, BOXLINENONE, 0); {Desc}
SetTab(4.1, pjCenter, 0.5, 0, BOXLINENONE, 0); {Level}
SetTab(4.7, pjCenter, 1.0, 0, BOXLINENONE, 0); {Disable}
end; {with Sender as TBaseReport do}
end; {ReportPrintHeader}
{==============================================================}
Procedure TMenuSecurityForm.ReportPrint(Sender: TObject);
var
TempStr : String;
Done, FirstTimeThrough, Quit : Boolean;
begin
Done := False;
FirstTimeThrough := True;
Quit := False;
MenuSecurityTable.First;
with Sender as TBaseReport do
begin
{First print the individual changes.}
repeat
If FirstTimeThrough
then FirstTimeThrough := False
else
try
MenuSecurityTable.Next;
except
Quit := True;
SystemSupport(050, MenuSecurityTable, 'Error getting special fee rate record.',
UnitName, GlblErrorDlgBox);
end;
If MenuSecurityTable.EOF
then Done := True;
{Print the present record.}
If not (Done or Quit)
then
begin
with MenuSecurityTable do
begin
TempStr := '';
If FieldByName('DisableIfUnderAccess').AsBoolean
then TempStr := 'X';
Println(#9 + FieldByName('MenuID').Text +
#9 + FieldByName('MenuDescription').Text +
#9 + FieldByName('SecurityLevel').Text +
#9 + TempStr);
end; {with MenuSecurityTable do}
{If there is only one line left to print, then we
want to go to the next page.}
If (LinesLeft < 3)
then NewPage;
end; {If not (Done or Quit)}
until (Done or Quit);
end; {with Sender as TBaseReport do}
end; {ReportPrint}
{===================================================================}
Procedure TMenuSecurityForm.FormClose( Sender: TObject;
var Action: TCloseAction);
begin
CloseTablesForForm(Self);
MainMenuIDs.Free;
MainMenuDescriptions.Free;
{Free up the child window and set the ClosingAForm Boolean to
true so that we know to delete the tab.}
Action := caFree;
GlblClosingAForm := True;
GlblClosingFormCaption := Caption;
end; {FormClose}
end.
|
unit DataSetWrap;
interface
uses
System.Classes, Data.DB, NotifyEvents;
type
TDataSetWrap = class(TComponent)
private
FAfterClose: TNotifyEventsEx;
FDataSet: TDataSet;
protected
procedure AfterDataSetClose(DataSet: TDataSet);
public
constructor Create(AOwner: TComponent); override;
procedure Assign(ADataSet: TDataSet);
property AfterClose: TNotifyEventsEx read FAfterClose;
end;
implementation
constructor TDataSetWrap.Create(AOwner: TComponent);
begin
inherited;
Assign(AOwner as TDataSet);
end;
procedure TDataSetWrap.AfterDataSetClose(DataSet: TDataSet);
begin
FAfterClose.CallEventHandlers(Self);
end;
procedure TDataSetWrap.Assign(ADataSet: TDataSet);
begin
FDataSet := ADataSet;
FDataSet.AfterClose := AfterDataSetClose;
end;
end.
|
unit ULogging;
interface
uses classes;
type
TLog=class
_Disabled:TStringList;
_LogCache:TStringList;
_ChatlogFile:System.Text;
_writechatlog:boolean;
constructor create;
procedure OpenChatLog(bot_id:string);
Procedure Disable(kind:string);
procedure Enable(kind:string);
Procedure Log(s:string);overload;
Procedure Log(kind:string;s:string);overload;
procedure Flush;
Procedure ChatLog(who,what:string);
destructor destroy;override;
end;
var
Log:TLog;
implementation
uses UChat,SysUtils;
constructor TLog.create;
begin
inherited Create;
_LogCache:=TStringList.Create;
_Disabled:=TStringList.Create;
_Disabled.Duplicates:=dupIgnore;
_writechatlog:=false;
end;
destructor TLog.Destroy;
begin
_Disabled.Free;
_LogCache.Free;
if _writechatlog then
closefile(_chatlogfile);
inherited destroy;
end;
procedure TLog.OpenChatLog(bot_id:string);
begin
try
AssignFile(_ChatlogFile,bot_id+'.chatlog');
if FileExists(bot_id+'.chatlog') then
Append(_ChatLogFile)
else
rewrite(_ChatLogFile);
Writeln(_ChatLogFile);
Writeln(_ChatLogFile,DateTimeToStr(now));
_writechatlog:=true;
Log('log','Chatlog will be stored in the file '+bot_id+'.chatlog');
except
_writechatlog:=false;
Log('log','Unable to write chatlog file, logging will be disabled');
end;
end;
procedure Tlog.Disable(kind:string);
begin
_Disabled.Add(kind);
end;
procedure Tlog.Enable(kind:string);
var
i:integer;
begin
i:=_Disabled.Indexof(kind);
if i>=0 then
_Disabled.Delete(i);
end;
procedure TLog.Flush;
var i:integer;
begin
if assigned(chat) then begin
for i:=0 to _LogCache.count-1 do
Chat.AddLogMessage(_LogCache.Strings[i]);
_LogCache.Clear;
end;
end;
Procedure TLog.Log(kind:string;s:string);
begin
if _Disabled.indexof(kind)=-1 then
Log(kind+': '+s)
end;
Procedure TLog.Log(s:string);
begin
if assigned(chat) then
Chat.AddLogMessage(s)
else
_LogCache.Add(s);
end;
Procedure TLog.ChatLog(who,what:string);
begin
if _writechatlog then
Writeln(_chatlogfile,Who,'> ',what);
end;
end.
|
{**************************************************************************************************}
{ }
{ Project JEDI Code Library (JCL) }
{ }
{ The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); }
{ you may not use this file except in compliance with the License. You may obtain a copy of the }
{ License at http://www.mozilla.org/MPL/ }
{ }
{ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF }
{ ANY KIND, either express or implied. See the License for the specific language governing rights }
{ and limitations under the License. }
{ }
{ The Original Code is JclTrees.pas. }
{ }
{ The Initial Developer of the Original Code is Florent Ouchet. Portions created by }
{ Florent Ouchet are Copyright (C) Florent Ouchet <outchy att users dott sourceforge dott net }
{ All rights reserved. }
{ }
{ Contributors: }
{ }
{**************************************************************************************************}
{ }
{ The Delphi Container Library }
{ }
{**************************************************************************************************}
{ }
{ Last modified: $Date:: 2008-06-05 15:35:37 +0200 (jeu., 05 juin 2008) $ }
{ Revision: $Rev:: 2376 $ }
{ Author: $Author:: obones $ }
{ }
{**************************************************************************************************}
unit JclTrees;
interface
{$I jcl.inc}
uses
Classes,
{$IFDEF UNITVERSIONING}
JclUnitVersioning,
{$ENDIF UNITVERSIONING}
{$IFDEF SUPPORTS_GENERICS}
{$IFDEF CLR}
System.Collections.Generic,
{$ENDIF CLR}
JclAlgorithms,
{$ENDIF SUPPORTS_GENERICS}
JclBase, JclAbstractContainers, JclContainerIntf, JclSynch;
{$I containers\JclContainerCommon.imp}
{$I containers\JclTrees.imp}
{$I containers\JclTrees.int}
type
{$JPPEXPANDMACRO JCLTREEINT(TJclIntfTreeNode,TJclIntfTree,TJclIntfAbstractContainer,IJclIntfEqualityComparer,IJclIntfCollection,IJclIntfTree,IJclIntfIterator,IJclIntfTreeIterator,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,,const ,AInterface,IInterface,nil)}
{$JPPEXPANDMACRO JCLTREEINT(TJclAnsiStrTreeNode,TJclAnsiStrTree,TJclAnsiStrAbstractCollection,IJclAnsiStrEqualityComparer,IJclAnsiStrCollection,IJclAnsiStrTree,IJclAnsiStrIterator,IJclAnsiStrTreeIterator, IJclStrContainer\, IJclAnsiStrContainer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,, override;,,const ,AString,AnsiString,'')}
{$JPPEXPANDMACRO JCLTREEINT(TJclWideStrTreeNode,TJclWideStrTree,TJclWideStrAbstractCollection,IJclWideStrEqualityComparer,IJclWideStrCollection,IJclWideStrTree,IJclWideStrIterator,IJclWideStrTreeIterator, IJclStrContainer\, IJclWideStrContainer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,, override;,,const ,AString,WideString,'')}
{$IFDEF CONTAINER_ANSISTR}
TJclStrTree = TJclAnsiStrTree;
{$ENDIF CONTAINER_ANSISTR}
{$IFDEF CONTAINER_WIDESTR}
TJclStrTree = TJclWideStrTree;
{$ENDIF CONTAINER_WIDESTR}
{$JPPEXPANDMACRO JCLTREEINT(TJclSingleTreeNode,TJclSingleTree,TJclSingleAbstractContainer,IJclSingleEqualityComparer,IJclSingleCollection,IJclSingleTree,IJclSingleIterator,IJclSingleTreeIterator, IJclSingleContainer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,,const ,AValue,Single,0.0)}
{$JPPEXPANDMACRO JCLTREEINT(TJclDoubleTreeNode,TJclDoubleTree,TJclDoubleAbstractContainer,IJclDoubleEqualityComparer,IJclDoubleCollection,IJclDoubleTree,IJclDoubleIterator,IJclDoubleTreeIterator, IJclDoubleContainer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,,const ,AValue,Double,0.0)}
{$JPPEXPANDMACRO JCLTREEINT(TJclExtendedTreeNode,TJclExtendedTree,TJclExtendedAbstractContainer,IJclExtendedEqualityComparer,IJclExtendedCollection,IJclExtendedTree,IJclExtendedIterator,IJclExtendedTreeIterator, IJclExtendedContainer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,,const ,AValue,Extended,0.0)}
{$IFDEF MATH_EXTENDED_PRECISION}
TJclFloatTree = TJclExtendedTree;
{$ENDIF MATH_EXTENDED_PRECISION}
{$IFDEF MATH_DOUBLE_PRECISION}
TJclFloatTree = TJclDoubleTree;
{$ENDIF MATH_DOUBLE_PRECISION}
{$IFDEF MATH_SINGLE_PRECISION}
TJclFloatTree = TJclSingleTree;
{$ENDIF MATH_SINGLE_PRECISION}
{$JPPEXPANDMACRO JCLTREEINT(TJclIntegerTreeNode,TJclIntegerTree,TJclIntegerAbstractContainer,IJclIntegerEqualityComparer,IJclIntegerCollection,IJclIntegerTree,IJclIntegerIterator,IJclIntegerTreeIterator,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,,,AValue,Integer,0)}
{$JPPEXPANDMACRO JCLTREEINT(TJclCardinalTreeNode,TJclCardinalTree,TJclCardinalAbstractContainer,IJclCardinalEqualityComparer,IJclCardinalCollection,IJclCardinalTree,IJclCardinalIterator,IJclCardinalTreeIterator,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,,,AValue,Cardinal,0)}
{$JPPEXPANDMACRO JCLTREEINT(TJclInt64TreeNode,TJclInt64Tree,TJclInt64AbstractContainer,IJclInt64EqualityComparer,IJclInt64Collection,IJclInt64Tree,IJclInt64Iterator,IJclInt64TreeIterator,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,,const ,AValue,Int64,0)}
{$IFNDEF CLR}
{$JPPEXPANDMACRO JCLTREEINT(TJclPtrTreeNode,TJclPtrTree,TJclPtrAbstractContainer,IJclPtrEqualityComparer,IJclPtrCollection,IJclPtrTree,IJclPtrIterator,IJclPtrTreeIterator,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,,,APtr,Pointer,nil)}
{$ENDIF ~CLR}
{$JPPEXPANDMACRO JCLTREEINT(TJclTreeNode,TJclTree,TJclAbstractContainer,IJclEqualityComparer,IJclCollection,IJclTree,IJclIterator,IJclTreeIterator, IJclObjectOwner\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,AOwnsObjects: Boolean,,AObject,TObject,nil)}
{$IFDEF SUPPORTS_GENERICS}
{$JPPEXPANDMACRO JCLTREEINT(TJclTreeNode<T>,TJclTree<T>,TJclAbstractContainer<T>,IJclEqualityComparer<T>,IJclCollection<T>,IJclTree<T>,IJclIterator<T>,IJclTreeIterator<T>, IJclItemOwner<T>\,,,,,,AOwnsItems: Boolean,const ,AItem,T,Default(T))}
// E = External helper to compare items for equality
TJclTreeE<T> = class(TJclTree<T>, {$IFDEF THREADSAFE} IJclLockable, {$ENDIF THREADSAFE}
IJclIntfCloneable, IJclCloneable, IJclContainer, IJclItemOwner<T>, IJclEqualityComparer<T>,
IJclCollection<T>, IJclTree<T>)
private
FEqualityComparer: IEqualityComparer<T>;
protected
procedure AssignPropertiesTo(Dest: TJclAbstractContainerBase); override;
function CreateEmptyContainer: TJclAbstractContainerBase; override;
{ IJclEqualityComparer<T> }
function ItemsEqual(const A, B: T): Boolean; override;
{ IJclCloneable }
function IJclCloneable.Clone = ObjectClone;
{ IJclIntfCloneable }
function IJclIntfCloneable.Clone = IntfClone;
public
constructor Create(const AEqualityComparer: IEqualityComparer<T>; AOwnsItems: Boolean);
property EqualityComparer: IEqualityComparer<T> read FEqualityComparer write FEqualityComparer;
end;
// F = Function to compare items for equality
TJclTreeF<T> = class(TJclTree<T>, {$IFDEF THREADSAFE} IJclLockable, {$ENDIF THREADSAFE}
IJclIntfCloneable, IJclCloneable, IJclContainer, IJclItemOwner<T>, IJclEqualityComparer<T>,
IJclCollection<T>, IJclTree<T>)
protected
function CreateEmptyContainer: TJclAbstractContainerBase; override;
{ IJclCloneable }
function IJclCloneable.Clone = ObjectClone;
{ IJclIntfCloneable }
function IJclIntfCloneable.Clone = IntfClone;
public
constructor Create(ACompare: TCompare<T>; AOwnsItems: Boolean);
end;
// I = Items can compare themselves to an other for equality
TJclTreeI<T: IEquatable<T>> = class(TJclTree<T>, {$IFDEF THREADSAFE} IJclLockable, {$ENDIF THREADSAFE}
IJclIntfCloneable, IJclCloneable, IJclContainer, IJclItemOwner<T>, IJclEqualityComparer<T>,
IJclCollection<T>, IJclTree<T>)
protected
function CreateEmptyContainer: TJclAbstractContainerBase; override;
{ IJclEqualityComparer<T> }
function ItemsEqual(const A, B: T): Boolean; override;
{ IJclCloneable }
function IJclCloneable.Clone = ObjectClone;
{ IJclIntfCloneable }
function IJclIntfCloneable.Clone = IntfClone;
end;
{$ENDIF SUPPORTS_GENERICS}
{$IFDEF UNITVERSIONING}
const
UnitVersioning: TUnitVersionInfo = (
RCSfile: '$URL: https://jcl.svn.sourceforge.net:443/svnroot/jcl/tags/JCL-1.102-Build3072/jcl/source/prototypes/JclTrees.pas $';
Revision: '$Revision: 2376 $';
Date: '$Date: 2008-06-05 15:35:37 +0200 (jeu., 05 juin 2008) $';
LogPath: 'JCL\source\common'
);
{$ENDIF UNITVERSIONING}
implementation
uses
SysUtils;
type
TItrStart = (isFirst, isLast, isRoot);
type
{$JPPEXPANDMACRO JCLTREEITRINT(TIntfItr,TPreOrderIntfItr,TPostOrderIntfItr,TJclIntfTreeNode,TJclIntfTree,IJclIntfIterator,IJclIntfTreeIterator,IJclIntfEqualityComparer,const ,AInterface,IInterface,nil,GetObject,SetObject)}
{$JPPEXPANDMACRO JCLTREEITRIMP(TIntfItr,TPreOrderIntfItr,TPostOrderIntfItr,TJclIntfTreeNode,TJclIntfTree,IJclIntfIterator,IJclIntfTreeIterator,IJclIntfEqualityComparer,const ,AInterface,IInterface,nil,GetObject,SetObject,FreeObject)}
type
{$JPPEXPANDMACRO JCLTREEITRINT(TAnsiStrItr,TPreOrderAnsiStrItr,TPostOrderAnsiStrItr,TJclAnsiStrTreeNode,TJclAnsiStrTree,IJclAnsiStrIterator,IJclAnsiStrTreeIterator,IJclAnsiStrEqualityComparer,const ,AString,AnsiString,'',GetString,SetString)}
{$JPPEXPANDMACRO JCLTREEITRIMP(TAnsiStrItr,TPreOrderAnsiStrItr,TPostOrderAnsiStrItr,TJclAnsiStrTreeNode,TJclAnsiStrTree,IJclAnsiStrIterator,IJclAnsiStrTreeIterator,IJclAnsiStrEqualityComparer,const ,AString,AnsiString,'',GetString,SetString,FreeString)}
type
{$JPPEXPANDMACRO JCLTREEITRINT(TWideStrItr,TPreOrderWideStrItr,TPostOrderWideStrItr,TJclWideStrTreeNode,TJclWideStrTree,IJclWideStrIterator,IJclWideStrTreeIterator,IJclWideStrEqualityComparer,const ,AString,WideString,'',GetString,SetString)}
{$JPPEXPANDMACRO JCLTREEITRIMP(TWideStrItr,TPreOrderWideStrItr,TPostOrderWideStrItr,TJclWideStrTreeNode,TJclWideStrTree,IJclWideStrIterator,IJclWideStrTreeIterator,IJclWideStrEqualityComparer,const ,AString,WideString,'',GetString,SetString,FreeString)}
type
{$JPPEXPANDMACRO JCLTREEITRINT(TSingleItr,TPreOrderSingleItr,TPostOrderSingleItr,TJclSingleTreeNode,TJclSingleTree,IJclSingleIterator,IJclSingleTreeIterator,IJclSingleEqualityComparer,const ,AValue,Single,0.0,GetValue,SetValue)}
{$JPPEXPANDMACRO JCLTREEITRIMP(TSingleItr,TPreOrderSingleItr,TPostOrderSingleItr,TJclSingleTreeNode,TJclSingleTree,IJclSingleIterator,IJclSingleTreeIterator,IJclSingleEqualityComparer,const ,AValue,Single,0.0,GetValue,SetValue,FreeSingle)}
type
{$JPPEXPANDMACRO JCLTREEITRINT(TDoubleItr,TPreOrderDoubleItr,TPostOrderDoubleItr,TJclDoubleTreeNode,TJclDoubleTree,IJclDoubleIterator,IJclDoubleTreeIterator,IJclDoubleEqualityComparer,const ,AValue,Double,0.0,GetValue,SetValue)}
{$JPPEXPANDMACRO JCLTREEITRIMP(TDoubleItr,TPreOrderDoubleItr,TPostOrderDoubleItr,TJclDoubleTreeNode,TJclDoubleTree,IJclDoubleIterator,IJclDoubleTreeIterator,IJclDoubleEqualityComparer,const ,AValue,Double,0.0,GetValue,SetValue,FreeDouble)}
type
{$JPPEXPANDMACRO JCLTREEITRINT(TExtendedItr,TPreOrderExtendedItr,TPostOrderExtendedItr,TJclExtendedTreeNode,TJclExtendedTree,IJclExtendedIterator,IJclExtendedTreeIterator,IJclExtendedEqualityComparer,const ,AValue,Extended,0.0,GetValue,SetValue)}
{$JPPEXPANDMACRO JCLTREEITRIMP(TExtendedItr,TPreOrderExtendedItr,TPostOrderExtendedItr,TJclExtendedTreeNode,TJclExtendedTree,IJclExtendedIterator,IJclExtendedTreeIterator,IJclExtendedEqualityComparer,const ,AValue,Extended,0.0,GetValue,SetValue,FreeExtended)}
type
{$JPPEXPANDMACRO JCLTREEITRINT(TIntegerItr,TPreOrderIntegerItr,TPostOrderIntegerItr,TJclIntegerTreeNode,TJclIntegerTree,IJclIntegerIterator,IJclIntegerTreeIterator,IJclIntegerEqualityComparer,,AValue,Integer,0,GetValue,SetValue)}
{$JPPEXPANDMACRO JCLTREEITRIMP(TIntegerItr,TPreOrderIntegerItr,TPostOrderIntegerItr,TJclIntegerTreeNode,TJclIntegerTree,IJclIntegerIterator,IJclIntegerTreeIterator,IJclIntegerEqualityComparer,,AValue,Integer,0,GetValue,SetValue,FreeInteger)}
type
{$JPPEXPANDMACRO JCLTREEITRINT(TCardinalItr,TPreOrderCardinalItr,TPostOrderCardinalItr,TJclCardinalTreeNode,TJclCardinalTree,IJclCardinalIterator,IJclCardinalTreeIterator,IJclCardinalEqualityComparer,,AValue,Cardinal,0,GetValue,SetValue)}
{$JPPEXPANDMACRO JCLTREEITRIMP(TCardinalItr,TPreOrderCardinalItr,TPostOrderCardinalItr,TJclCardinalTreeNode,TJclCardinalTree,IJclCardinalIterator,IJclCardinalTreeIterator,IJclCardinalEqualityComparer,,AValue,Cardinal,0,GetValue,SetValue,FreeCardinal)}
type
{$JPPEXPANDMACRO JCLTREEITRINT(TInt64Itr,TPreOrderInt64Itr,TPostOrderInt64Itr,TJclInt64TreeNode,TJclInt64Tree,IJclInt64Iterator,IJclInt64TreeIterator,IJclInt64EqualityComparer,const ,AValue,Int64,0,GetValue,SetValue)}
{$JPPEXPANDMACRO JCLTREEITRIMP(TInt64Itr,TPreOrderInt64Itr,TPostOrderInt64Itr,TJclInt64TreeNode,TJclInt64Tree,IJclInt64Iterator,IJclInt64TreeIterator,IJclInt64EqualityComparer,const ,AValue,Int64,0,GetValue,SetValue,FreeInt64)}
{$IFNDEF CLR}
type
{$JPPEXPANDMACRO JCLTREEITRINT(TPtrItr,TPreOrderPtrItr,TPostOrderPtrItr,TJclPtrTreeNode,TJclPtrTree,IJclPtrIterator,IJclPtrTreeIterator,IJclPtrEqualityComparer,,APtr,Pointer,nil,GetPointer,SetPointer)}
{$JPPEXPANDMACRO JCLTREEITRIMP(TPtrItr,TPreOrderPtrItr,TPostOrderPtrItr,TJclPtrTreeNode,TJclPtrTree,IJclPtrIterator,IJclPtrTreeIterator,IJclPtrEqualityComparer,,APtr,Pointer,nil,GetPointer,SetPointer,FreePointer)}
{$ENDIF ~CLR}
type
{$JPPEXPANDMACRO JCLTREEITRINT(TItr,TPreOrderItr,TPostOrderItr,TJclTreeNode,TJclTree,IJclIterator,IJclTreeIterator,IJclEqualityComparer,,AObject,TObject,nil,GetObject,SetObject)}
{$JPPEXPANDMACRO JCLTREEITRIMP(TItr,TPreOrderItr,TPostOrderItr,TJclTreeNode,TJclTree,IJclIterator,IJclTreeIterator,IJclEqualityComparer,,AObject,TObject,nil,GetObject,SetObject,FreeObject)}
{$IFDEF SUPPORTS_GENERICS}
type
{$JPPEXPANDMACRO JCLTREEITRINT(TItr<T>,TPreOrderItr<T>,TPostOrderItr<T>,TJclTreeNode<T>,TJclTree<T>,IJclIterator<T>,IJclTreeIterator<T>,IJclEqualityComparer<T>,const ,AItem,T,Default(T),GetItem,SetItem)}
{$JPPEXPANDMACRO JCLTREEITRIMP(TItr<T>,TPreOrderItr<T>,TPostOrderItr<T>,TJclTreeNode<T>,TJclTree<T>,IJclIterator<T>,IJclTreeIterator<T>,IJclEqualityComparer<T>,const ,AItem,T,Default(T),GetItem,SetItem,FreeItem)}
{$ENDIF SUPPORTS_GENERICS}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclIntfTree.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclIntfTree.Create;
AssignPropertiesTo(Result);
end;
}
{$JPPEXPANDMACRO JCLTREEIMP(TJclIntfTreeNode,TJclIntfTree,TPreOrderIntfItr,TPostOrderIntfItr,IJclIntfCollection,IJclIntfIterator,IJclIntfTreeIterator,IJclIntfEqualityComparer,,,const ,AInterface,IInterface,nil,FreeObject)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclAnsiStrTree.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclAnsiStrTree.Create;
AssignPropertiesTo(Result);
end;
}
{$JPPEXPANDMACRO JCLTREEIMP(TJclAnsiStrTreeNode,TJclAnsiStrTree,TPreOrderAnsiStrItr,TPostOrderAnsiStrItr,IJclAnsiStrCollection,IJclAnsiStrIterator,IJclAnsiStrTreeIterator,IJclAnsiStrEqualityComparer,,,const ,AString,AnsiString,'',FreeString)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclWideStrTree.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclWideStrTree.Create;
AssignPropertiesTo(Result);
end;
}
{$JPPEXPANDMACRO JCLTREEIMP(TJclWideStrTreeNode,TJclWideStrTree,TPreOrderWideStrItr,TPostOrderWideStrItr,IJclWideStrCollection,IJclWideStrIterator,IJclWideStrTreeIterator,IJclWideStrEqualityComparer,,,const ,AString,WideString,'',FreeString)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclSingleTree.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclSingleTree.Create;
AssignPropertiesTo(Result);
end;
}
{$JPPEXPANDMACRO JCLTREEIMP(TJclSingleTreeNode,TJclSingleTree,TPreOrderSingleItr,TPostOrderSingleItr,IJclSingleCollection,IJclSingleIterator,IJclSingleTreeIterator,IJclSingleEqualityComparer,,,const ,AValue,Single,0.0,FreeSingle)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclDoubleTree.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclDoubleTree.Create;
AssignPropertiesTo(Result);
end;
}
{$JPPEXPANDMACRO JCLTREEIMP(TJclDoubleTreeNode,TJclDoubleTree,TPreOrderDoubleItr,TPostOrderDoubleItr,IJclDoubleCollection,IJclDoubleIterator,IJclDoubleTreeIterator,IJclDoubleEqualityComparer,,,const ,AValue,Double,0.0,FreeDouble)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclExtendedTree.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclExtendedTree.Create;
AssignPropertiesTo(Result);
end;
}
{$JPPEXPANDMACRO JCLTREEIMP(TJclExtendedTreeNode,TJclExtendedTree,TPreOrderExtendedItr,TPostOrderExtendedItr,IJclExtendedCollection,IJclExtendedIterator,IJclExtendedTreeIterator,IJclExtendedEqualityComparer,,,const ,AValue,Extended,0.0,FreeExtended)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclIntegerTree.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclIntegerTree.Create;
AssignPropertiesTo(Result);
end;
}
{$JPPEXPANDMACRO JCLTREEIMP(TJclIntegerTreeNode,TJclIntegerTree,TPreOrderIntegerItr,TPostOrderIntegerItr,IJclIntegerCollection,IJclIntegerIterator,IJclIntegerTreeIterator,IJclIntegerEqualityComparer,,,,AValue,Integer,0,FreeInteger)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclCardinalTree.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclCardinalTree.Create;
AssignPropertiesTo(Result);
end;
}
{$JPPEXPANDMACRO JCLTREEIMP(TJclCardinalTreeNode,TJclCardinalTree,TPreOrderCardinalItr,TPostOrderCardinalItr,IJclCardinalCollection,IJclCardinalIterator,IJclCardinalTreeIterator,IJclCardinalEqualityComparer,,,,AValue,Cardinal,0,FreeCardinal)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclInt64Tree.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclInt64Tree.Create;
AssignPropertiesTo(Result);
end;
}
{$JPPEXPANDMACRO JCLTREEIMP(TJclInt64TreeNode,TJclInt64Tree,TPreOrderInt64Itr,TPostOrderInt64Itr,IJclInt64Collection,IJclInt64Iterator,IJclInt64TreeIterator,IJclInt64EqualityComparer,,,const ,AValue,Int64,0,FreeInt64)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$IFNDEF CLR}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclPtrTree.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclPtrTree.Create;
AssignPropertiesTo(Result);
end;
}
{$JPPEXPANDMACRO JCLTREEIMP(TJclPtrTreeNode,TJclPtrTree,TPreOrderPtrItr,TPostOrderPtrItr,IJclPtrCollection,IJclPtrIterator,IJclPtrTreeIterator,IJclPtrEqualityComparer,,,,APtr,Pointer,nil,FreePointer)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$ENDIF ~CLR}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclTree.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclTree.Create(False);
AssignPropertiesTo(Result);
end;
}
{$JPPEXPANDMACRO JCLTREEIMP(TJclTreeNode,TJclTree,TPreOrderItr,TPostOrderItr,IJclCollection,IJclIterator,IJclTreeIterator,IJclEqualityComparer,AOwnsObjects: Boolean,AOwnsObjects,,AObject,TObject,nil,FreeObject)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$IFDEF SUPPORTS_GENERICS}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER}
{$JPPEXPANDMACRO JCLTREEIMP(TJclTreeNode<T>,TJclTree<T>,TPreOrderItr<T>,TPostOrderItr<T>,IJclCollection<T>,IJclIterator<T>,IJclTreeIterator<T>,IJclEqualityComparer<T>,AOwnsItems: Boolean,AOwnsItems,const ,AItem,T,Default(T),FreeItem)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
//=== { TJclTreeE<T> } =======================================================
constructor TJclTreeE<T>.Create(const AEqualityComparer: IEqualityComparer<T>; AOwnsItems: Boolean);
begin
inherited Create(AOwnsItems);
FEqualityComparer := AEqualityComparer;
end;
procedure TJclTreeE<T>.AssignPropertiesTo(Dest: TJclAbstractContainerBase);
begin
inherited AssignPropertiesTo(Dest);
if Dest is TJclTreeE<T> then
TJclTreeE<T>(Dest).FEqualityComparer := FEqualityComparer;
end;
function TJclTreeE<T>.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclTreeE<T>.Create(EqualityComparer, False);
AssignPropertiesTo(Result);
end;
function TJclTreeE<T>.ItemsEqual(const A, B: T): Boolean;
begin
if EqualityComparer <> nil then
Result := EqualityComparer.Equals(A, B)
else
Result := inherited ItemsEqual(A, B);
end;
//=== { TJclTreeF<T> } =======================================================
constructor TJclTreeF<T>.Create(ACompare: TCompare<T>; AOwnsItems: Boolean);
begin
inherited Create(AOwnsItems);
SetCompare(ACompare);
end;
function TJclTreeF<T>.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclTreeF<T>.Create(Compare, False);
AssignPropertiesTo(Result);
end;
//=== { TJclTreeI<T> } =======================================================
function TJclTreeI<T>.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclTreeI<T>.Create(False);
AssignPropertiesTo(Result);
end;
function TJclTreeI<T>.ItemsEqual(const A, B: T): Boolean;
begin
if Assigned(FEqualityCompare) then
Result := FEqualityCompare(A, B)
else
Result := A.Equals(B);
end;
{$ENDIF SUPPORTS_GENERICS}
{$IFDEF UNITVERSIONING}
initialization
RegisterUnitVersion(HInstance, UnitVersioning);
finalization
UnregisterUnitVersion(HInstance);
{$ENDIF UNITVERSIONING}
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{ : GLSCUDAFFTPlan <p>
<b>History : </b><font size=-1><ul>
<li>13/12/13 - PW - Added GLScene.inc and GLSLog
<li>04/05/11 - Yar - Fixed Source/Destination size checking
<li>05/03/11 - Yar - Refactored
<li>19/03/10 - Yar - Creation
</ul></font><p>
}
unit GLSCUDAFFTPlan;
interface
{$I GLScene.inc}
uses
Classes, SysUtils,
//GLS
GLSCUDAContext,
GLSCUDA,
GLSCUDAApi,
GLSCUDAFourierTransform,
GLStrings,
GLSLog;
type
TCUDAFFTransform =
(
fftRealToComplex,
fftComplexToReal,
fftComplexToComplex,
fftDoubleToDoubleComplex,
fftDoubleComplexToDouble,
fftDoubleComplexToDoubleComplex
);
TCUDAFFTdir = (fftdForward, fftdInverse);
TCUDAFFTPlan = class(TCUDAComponent)
private
{ Private declarations }
FHandle: TcufftHandle;
FWidth: Integer;
FHeight: Integer;
FDepth: Integer;
FBatch: Integer;
FSize: Integer;
FPaddedSize: Integer;
FTransform: TCUDAFFTransform;
FStatus: TcufftResult;
procedure SetWidth(Value: Integer);
procedure SetHeight(Value: Integer);
procedure SetDepth(Value: Integer);
procedure SetBatch(Value: Integer);
procedure SetTransform(Value: TCUDAFFTransform);
protected
{ Protected declaration }
procedure AllocateHandles; override;
procedure DestroyHandles; override;
class procedure CheckLib;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure Execute(ASrc: TCUDAMemData; ADst: TCUDAMemData;
const ADir: TCUDAFFTdir = fftdForward);
published
{ Published declarations }
property Width: Integer read fWidth write SetWidth default 256;
property Height: Integer read FHeight write SetHeight default 0;
property Depth: Integer read FDepth write SetDepth default 0;
property Batch: Integer read FBatch write SetBatch default 1;
property Transform: TCUDAFFTransform read FTransform write SetTransform
default fftRealToComplex;
end;
implementation
resourcestring
cudasRequireFreeThread = 'CUFFT functions require context-free thread';
cudasBadPlanSize = 'MemData size less then Plan size.';
constructor TCUDAFFTPlan.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FHandle := INVALID_CUFFT_HANDLE;
fWidth := 256;
FHeight := 0;
FDepth := 0;
FBatch := 1;
FTransform := fftRealToComplex;
end;
destructor TCUDAFFTPlan.Destroy;
begin
DestroyHandles;
inherited;
end;
class procedure TCUDAFFTPlan.CheckLib;
begin
if not IsCUFFTInitialized then
if not InitCUFFT then
begin
GLSLogger.LogError('Can not initialize CUFFT library');
Abort;
end;
end;
procedure TCUDAFFTPlan.Assign(Source: TPersistent);
var
plan: TCUDAFFTPlan;
begin
if Source is TCUDAFFTPlan then
begin
DestroyHandles;
plan := TCUDAFFTPlan(Source);
Width := plan.fWidth;
Height := plan.FHeight;
Depth := plan.FDepth;
Transform := plan.FTransform;
end;
inherited Assign(Source);
end;
procedure TCUDAFFTPlan.AllocateHandles;
var
LType: TcufftType;
begin
DestroyHandles;
case FTransform of
fftRealToComplex:
LType := CUFFT_R2C;
fftComplexToReal:
LType := CUFFT_C2R;
fftComplexToComplex:
LType := CUFFT_C2C;
fftDoubleToDoubleComplex:
LType := CUFFT_D2Z;
fftDoubleComplexToDouble:
LType := CUFFT_Z2D;
fftDoubleComplexToDoubleComplex:
LType := CUFFT_Z2Z;
else
begin
Assert(False, glsErrorEx + glsUnknownType);
LType := CUFFT_R2C;
end;
end;
Context.Requires;
if (FHeight = 0) and (FDepth = 0) then
begin
FStatus := cufftPlan1d(FHandle, fWidth, LType, FBatch);
FSize := FWidth;
FPaddedSize := FWidth div 2 + 1;
if FBatch > 0 then
begin
FSize := FSize * FBatch;
FPaddedSize := FPaddedSize * FBatch;
end;
end
else if FDepth = 0 then
begin
FStatus := cufftPlan2d(FHandle, fWidth, FHeight, LType);
FSize := FWidth * FHeight;
FPaddedSize := FWidth * (FHeight div 2 + 1);
end
else
begin
FStatus := cufftPlan3d(FHandle, fWidth, FHeight, FDepth, LType);
FSize := FWidth * FHeight * FDepth;
FPaddedSize := FWidth * FHeight * (FDepth div 2 + 1);
end;
Context.Release;
if FStatus <> CUFFT_SUCCESS then
begin
FHandle := INVALID_CUFFT_HANDLE;
Abort;
end;
Context.Requires;
FStatus := cufftSetCompatibilityMode(FHandle, CUFFT_COMPATIBILITY_FFTW_PADDING);
Context.Release;
fChanges := [];
inherited;
end;
procedure TCUDAFFTPlan.DestroyHandles;
begin
inherited;
CheckLib;
if FHandle <> INVALID_CUFFT_HANDLE then
begin
Context.Requires;
FStatus := cufftDestroy(FHandle);
Context.Release;
if FStatus <> CUFFT_SUCCESS then
Abort;
FHandle := 0;
FPaddedSize := 0;
end;
end;
procedure TCUDAFFTPlan.SetWidth(Value: Integer);
begin
if Value < 1 then
Value := 1;
if Value <> fWidth then
begin
fWidth := Value;
CuNotifyChange(cuchSize);
end;
end;
procedure TCUDAFFTPlan.SetHeight(Value: Integer);
begin
if Value < 0 then
Value := 0;
if Value <> FHeight then
begin
FHeight := Value;
if FHeight > 0 then
FBatch := 1;
CuNotifyChange(cuchSize);
end;
end;
procedure TCUDAFFTPlan.SetDepth(Value: Integer);
begin
if Value < 0 then
Value := 0;
if Value <> FDepth then
begin
FDepth := Value;
if FDepth > 0 then
FBatch := 1;
CuNotifyChange(cuchSize);
end;
end;
procedure TCUDAFFTPlan.SetBatch(Value: Integer);
begin
if Value < 1 then
Value := 1;
if Value <> FBatch then
begin
FBatch := Value;
if FBatch > 1 then
begin
FHeight := 0;
FDepth := 0;
end;
CuNotifyChange(cuchSize);
end;
end;
procedure TCUDAFFTPlan.SetTransform(Value: TCUDAFFTransform);
begin
if Value <> FTransform then
begin
FTransform := Value;
CuNotifyChange(cuchSize);
end;
end;
procedure TCUDAFFTPlan.Execute(ASrc: TCUDAMemData; ADst: TCUDAMemData;
const ADir: TCUDAFFTdir);
const
sFFTdir: array [TCUDAFFTdir] of Integer = (CUFFT_FORWARD, CUFFT_INVERSE);
cSourceTypeSize: array[TCUDAFFTransform] of Byte = (
SizeOf(TcufftReal),
SizeOf(TcufftComplex),
SizeOf(TcufftComplex),
SizeOf(TcufftDoubleReal),
SizeOf(TcufftDoubleComplex),
SizeOf(TcufftDoubleComplex));
cDestinationTypeSize: array[TCUDAFFTransform] of Byte = (
SizeOf(TcufftComplex),
SizeOf(TcufftReal),
SizeOf(TcufftComplex),
SizeOf(TcufftDoubleComplex),
SizeOf(TcufftDoubleReal),
SizeOf(TcufftDoubleComplex));
var
SrcPtr, DstPtr: Pointer;
LSrcSize, LDstSize: Integer;
procedure ForwardCheck;
begin
if (LSrcSize * FSize > ASrc.DataSize)
or (LDstSize * FPaddedSize > ADst.DataSize) then
begin
GLSLogger.LogError(cudasBadPlanSize);
Abort;
end;
end;
procedure InverseCheck;
begin
if (LSrcSize * FPaddedSize > ASrc.DataSize)
or (LDstSize * FSize > ADst.DataSize) then
begin
GLSLogger.LogError(cudasBadPlanSize);
Abort;
end;
end;
begin
if (FHandle = INVALID_CUFFT_HANDLE) or (fChanges <> []) then
AllocateHandles;
if CUDAContextManager.GetCurrentThreadContext <> nil then
begin
GLSLogger.LogError(cudasRequireFreeThread);
Abort;
end;
SrcPtr := ASrc.RawData;
DstPtr := ADst.RawData;
LSrcSize := cSourceTypeSize[FTransform];
LDstSize := cDestinationTypeSize[FTransform];
Context.Requires;
try
case FTransform of
fftRealToComplex:
begin
ForwardCheck;
FStatus := cufftExecR2C(FHandle, SrcPtr, DstPtr);
end;
fftComplexToReal:
begin
InverseCheck;
FStatus := cufftExecC2R(FHandle, SrcPtr, DstPtr);
end;
fftComplexToComplex:
begin
case ADir of
fftdForward: ForwardCheck;
fftdInverse: InverseCheck;
end;
FStatus := cufftExecC2C(FHandle, SrcPtr, DstPtr, sFFTdir[ADir]);
end;
fftDoubleToDoubleComplex:
begin
ForwardCheck;
FStatus := cufftExecD2Z(FHandle, SrcPtr, DstPtr);
end;
fftDoubleComplexToDouble:
begin
InverseCheck;
FStatus := cufftExecZ2D(FHandle, SrcPtr, DstPtr);
end;
fftDoubleComplexToDoubleComplex:
begin
case ADir of
fftdForward: ForwardCheck;
fftdInverse: InverseCheck;
end;
FStatus := cufftExecZ2Z(FHandle, SrcPtr, DstPtr, sFFTdir[ADir]);
end
else
FStatus := CUFFT_INVALID_VALUE;
end;
finally
Context.Release;
end;
if FStatus <> CUFFT_SUCCESS then
Abort;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
RegisterClasses([TCUDAFFTPlan]);
finalization
CloseCUFFT;
end.
|
unit Unit1;
interface
uses
{$IFDEF MACOS}
MacApi.Appkit,Macapi.CoreFoundation, Macapi.Foundation,
{$ENDIF}
{$IFDEF MSWINDOWS}
Winapi.Messages, Winapi.Windows,
{$ENDIF}
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
FMX.Layouts, FMX.ListBox;
type
TForm1 = class(TForm)
ListBox1: TListBox;
Button1: TButton;
Label1: TLabel;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
{$IFDEF MSWINDOWS}
function EnumFontsProc(var LogFont: TLogFont; var TextMetric: TTextMetric;
FontType: Integer; Data: Pointer): Integer; stdcall;
var
S: TStrings;
Temp: string;
begin
S := TStrings(Data);
Temp := LogFont.lfFaceName;
if (S.Count = 0) or (AnsiCompareText(S[S.Count-1], Temp) <> 0) then
S.Add(Temp);
Result := 1;
end;
{$ENDIF}
procedure CollectFonts(FontList: TStringList);
var
{$IFDEF MACOS}
fManager: NsFontManager;
list:NSArray;
lItem:NSString;
{$ENDIF}
{$IFDEF MSWINDOWS}
DC: HDC;
LFont: TLogFont;
{$ENDIF}
i: Integer;
begin
{$IFDEF MACOS}
fManager := TNsFontManager.Wrap(TNsFontManager.OCClass.sharedFontManager);
list := fManager.availableFontFamilies;
if (List <> nil) and (List.count > 0) then
begin
for i := 0 to List.Count-1 do
begin
lItem := TNSString.Wrap(List.objectAtIndex(i));
FontList.Add(String(lItem.UTF8String))
end;
end;
{$ENDIF}
{$IFDEF MSWINDOWS}
DC := GetDC(0);
FillChar(LFont, sizeof(LFont), 0);
LFont.lfCharset := DEFAULT_CHARSET;
EnumFontFamiliesEx(DC, LFont, @EnumFontsProc, Winapi.Windows.LPARAM(FontList), 0);
ReleaseDC(0, DC);
{$ENDIF}
end;
procedure TForm1.Button1Click(Sender: TObject);
var fList: TStringList;
i: Integer;
begin
fList := TStringList.Create;
CollectFonts(fList);
Label1.Text := '系統字型數量'+ IntToStr(fList.Count);
for i := 0 to fList.Count -1 do
begin
ListBox1.Items.Add(FList[i]);
end;
fList.Free;
end;
end.
|
unit pVDEtc;
interface
uses
System.Classes;
Type
TAppIDValues = record
Vendor: String;
App: String;
LogFile: String;
end;
[ComponentPlatformsAttribute(pidWin32 or pidWin64)]
TVDEtc = class(TComponent)
private
FVendor: String;
FApp: String;
FLogFile: String;
procedure SetVendor(const Value: String);
procedure SetApp(const Value: String);
procedure SetLogFile(const Value: String);
private const
RAppIDValues: TAppIDValues = (Vendor: 'VyDevSoft'; App: 'QBTools'; LogFile: 'QBCube.log');
protected
public
constructor Create(AOwner: TComponent); override;
published
property Vendor: String read FVendor write SetVendor;
property App: String read FApp write SetApp;
property LogFile: String read FLogFile write SetLogFile;
end;
implementation
{ TEtc }
constructor TVDEtc.Create(AOwner: TComponent);
begin
inherited;
Vendor := RAppIDValues.Vendor;
App := RAppIDValues.App;
LogFile := RAppIDValues.LogFile;
end;
procedure TVDEtc.SetApp(const Value: String);
begin
FApp := Value;
end;
procedure TVDEtc.SetLogFile(const Value: String);
begin
FLogFile := Value;
end;
procedure TVDEtc.SetVendor(const Value: String);
begin
FVendor := Value;
end;
end.
|
unit NotasDoApk;
interface
uses
System.SysUtils, InterfaceNotas, InterfaceObservadorApk,
System.Generics.Collections;
type
TNotasDoApk = class(TInterfacedObject, IInterfaceNotas)
public
PNota, SNota, Media : Double;
ListaObserver: TList<IObservadorApk>;
procedure NovoObservador(TObserv: IObservadorApk);
procedure DeletarObservador(TObserv: IObservadorApk);
procedure NotificarObservadores;
procedure DefinirNotas(PrimeiraNota , SegundaNota: Double);
constructor Create;
destructor Destroy; Override;
end;
implementation
{ TNotasDoApk }
constructor TNotasDoApk.Create;
begin
ListaObserver := TList<IObservadorApk>.Create;
end;
procedure TNotasDoApk.DefinirNotas(PrimeiraNota , SegundaNota: Double);
begin
PNota := PrimeiraNota;
SNota := SegundaNota;
NotificarObservadores;
end;
procedure TNotasDoApk.DeletarObservador(TObserv: IObservadorApk);
begin
for TObserv in ListaObserver do
ListaObserver.Delete(ListaObserver.IndexOf(TObserv));
end;
destructor TNotasDoApk.Destroy;
begin
inherited;
ListaObserver.Free;
end;
procedure TNotasDoApk.NotificarObservadores;
var
Observadores : IObservadorApk;
begin
for Observadores in ListaObserver do
Observadores.Atualizar(PNota, SNota);
end;
procedure TNotasDoApk.NovoObservador(TObserv: IObservadorApk);
begin
ListaObserver.Add(TObserv);
end;
end.
|
{$F-,A+,O+,G+,R-,S+,I+,Q-,V-,B-,X+,T-,P-,N-,E+}
unit Errors;
interface
function errorMessage(code : integer) : string;
implementation
function errorMessage(code : integer) : string;
var msg : string;
begin
case code of
$00 : msg := 'No error';
$01 : msg := 'Invalid DOS function number';
$02 : msg := 'File not found';
$03 : msg := 'Path not found';
$04 : msg := 'Too many open files';
$05 : msg := 'File access denied';
$06 : msg := 'Invalid file handle';
$07 : msg := 'Memory control block destroyed';
$08 : msg := 'Not enough memory';
$09 : msg := 'Invalid memory block address';
$0A : msg := 'Environment scrambled';
$0B : msg := 'Bad program EXE file';
$0C : msg := 'Invalid file access mode';
$0D : msg := 'Invalid data';
$0E : msg := 'Unknown unit';
$0F : msg := 'Invalid drive number';
$10 : msg := 'Cannot remove current directory';
$11 : msg := 'Cannot rename across drives';
$12 : msg := 'Disk read/write error';
$13 : msg := 'Disk write-protected';
$14 : msg := 'Unknown unit';
$15 : msg := 'Drive not ready';
$16 : msg := 'Unknown command';
$17 : msg := 'Data CRC error';
$18 : msg := 'Bad request structure length';
$19 : msg := 'Seek error';
$1A : msg := 'Unknown media type';
$1B : msg := 'Sector not found';
$1C : msg := 'Printer out of paper';
$1D : msg := 'Disk write error';
$1E : msg := 'Disk read error';
$1F : msg := 'General failure';
$20 : msg := 'Sharing violation';
$21 : msg := 'Lock violation';
$22 : msg := 'Invalid disk change';
$23 : msg := 'File control block gone';
$24 : msg := 'Sharing buffer exceeded';
$32 : msg := 'Unsupported network request';
$33 : msg := 'Remote machine not listening';
$34 : msg := 'Duplicate network name';
$35 : msg := 'Network name not found';
$36 : msg := 'Network busy';
$37 : msg := 'Device no longer exists on network';
$38 : msg := 'NetBIOS command limit exceeded';
$39 : msg := 'Adapter hardware error';
$3A : msg := 'Incorrect response from network';
$3B : msg := 'Unexpected network error';
$3C : msg := 'Remote adapter incompatible';
$3D : msg := 'Print queue full';
$3E : msg := 'No space for print file';
$3F : msg := 'Print file cancelled';
$40 : msg := 'Network name deleted';
$41 : msg := 'Network access denied';
$42 : msg := 'Incorrect network device type';
$43 : msg := 'Network name not found';
$44 : msg := 'Network name limit exceeded';
$45 : msg := 'NetBIOS session limit exceeded';
$46 : msg := 'Filer sharing temporarily paused';
$47 : msg := 'Network request not accepted';
$48 : msg := 'Print or disk file paused';
$50 : msg := 'File already exists';
$52 : msg := 'Cannot make directory';
$53 : msg := 'Fail on critical error';
$54 : msg := 'Too many redirections';
$55 : msg := 'Duplicate redirection';
$56 : msg := 'Invalid password';
$57 : msg := 'Invalid parameter';
$58 : msg := 'Network device fault';
$59 : msg := 'Function not supported by network';
$5A : msg := 'Required component not installed';
94 : msg := 'EMS memory swap error';
98 : msg := 'Disk full';
100 : msg := 'Disk read error';
101 : msg := 'Disk write error';
102 : msg := 'File not assigned';
103 : msg := 'File not open';
104 : msg := 'File not open for input';
105 : msg := 'File not open for output';
106 : msg := 'Invalid numeric format';
150 : msg := 'Disk is write protected';
151 : msg := 'Unknown unit';
152 : msg := 'Drive not ready';
153 : msg := 'Unknown command';
154 : msg := 'CRC error in data';
155 : msg := 'Bad drive request structure length';
156 : msg := 'Disk seek error';
157 : msg := 'Unknown media type';
158 : msg := 'Sector not found';
159 : msg := 'Printer out of paper';
160 : msg := 'Device write fault';
161 : msg := 'Device read fault';
162 : msg := 'Hardware failure';
163 : msg := 'Sharing confilct';
200 : msg := 'Division by zero';
201 : msg := 'Range check error';
202 : msg := 'Stack overflow error';
203 : msg := 'Heap overflow error';
204 : msg := 'Invalid pointer operation';
205 : msg := 'Floating point overflow';
206 : msg := 'Floating point underflow';
207 : msg := 'Invalid floating point operation';
390 : msg := 'Serial port timeout';
399 : msg := 'Serial port not responding';
1008 : msg := 'EMS memory swap error'
else msg := 'Unknown error';
end;
errorMessage := msg;
end;
end.
|
unit SearchProductParameterValuesQuery;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseQuery, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt,
Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.StdCtrls, DSWrap;
type
TParameterValuesW = class(TDSWrap)
private
FParamSubParamID: TFieldWrap;
FProductID: TFieldWrap;
FValue: TFieldWrap;
FID: TFieldWrap;
public
constructor Create(AOwner: TComponent); override;
procedure EditValue(AValue: Variant);
property ParamSubParamID: TFieldWrap read FParamSubParamID;
property ProductID: TFieldWrap read FProductID;
property Value: TFieldWrap read FValue;
property ID: TFieldWrap read FID;
end;
TQuerySearchProductParameterValues = class(TQueryBase)
private
FW: TParameterValuesW;
{ Private declarations }
protected
public
constructor Create(AOwner: TComponent); override;
procedure AppendValue(AValue: Variant);
function Search(AParamSubParamID, AIDProduct: Integer): Integer; overload;
property W: TParameterValuesW read FW;
{ Public declarations }
end;
implementation
{$R *.dfm}
constructor TQuerySearchProductParameterValues.Create(AOwner: TComponent);
begin
inherited;
FW := TParameterValuesW.Create(FDQuery);
end;
procedure TQuerySearchProductParameterValues.AppendValue(AValue: Variant);
begin
Assert(not VarIsNull(AValue));
Assert(FDQuery.ParamByName(W.ParamSubParamID.FieldName).AsInteger > 0);
Assert(FDQuery.ParamByName(W.ProductID.FieldName).AsInteger > 0);
W.TryAppend;
W.ParamSubParamID.F.Value := FDQuery.ParamByName
(W.ParamSubParamID.FieldName).Value;
W.ProductID.F.Value := FDQuery.ParamByName(W.ProductID.FieldName).Value;
W.Value.F.Value := AValue;
W.TryPost;
end;
function TQuerySearchProductParameterValues.Search(AParamSubParamID,
AIDProduct: Integer): Integer;
begin
Assert(AParamSubParamID > 0);
Assert(AIDProduct > 0);
Result := Search([W.ParamSubParamID.FieldName, W.ProductID.FieldName],
[AParamSubParamID, AIDProduct]);
end;
constructor TParameterValuesW.Create(AOwner: TComponent);
begin
inherited;
FID := TFieldWrap.Create(Self, 'ID', '', True);
FParamSubParamID := TFieldWrap.Create(Self, 'ParamSubParamID');
FProductID := TFieldWrap.Create(Self, 'ProductID');
FValue := TFieldWrap.Create(Self, 'Value');
end;
procedure TParameterValuesW.EditValue(AValue: Variant);
var
S: string;
begin
Assert(not VarIsNull(AValue));
Assert(DataSet.RecordCount > 0);
// Если старое значение не равно новому
if Value.F.Value <> AValue then
begin
S := VarToStr(AValue);
// Пустую строку в БД не сохраняем
Assert(not S.IsEmpty);
TryEdit;
Value.F.Value := AValue;
TryPost;
end;
end;
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ WSDL constants }
{ }
{ Copyright (c) 2001 Borland Software Corporation }
{ }
{*******************************************************}
unit WSDLIntf;
interface
uses SysUtils, Classes, XMLIntf, XMLDoc;
type
TBindingType = (btUnknown, btSoap, btHttp, btMime);
TWSDLElement = (weServiceIntf, weServiceImpl, weMessage, wePortType, weBinding,
weService, weTypes, WeImport, weOperation, wePart);
TWSDLElements = set of TWSDLElement;
TWString = record
WString: WideString;
end;
TWideStrings = class
private
FWideStringList: TList;
function Get(Index: Integer): WideString;
procedure Put(Index: Integer; const S: WideString);
public
constructor Create;
destructor Destroy; override;
function Count: Integer;
procedure Clear;
function Add(const S: WideString): Integer;
function IndexOf(const S: WideString): Integer;
procedure Insert(Index: Integer; const S: WideString);
property Strings[Index: Integer]: WideString read Get write Put; default;
end;
const
{ WSDL Schema Tags and attribute names }
SDefinitions = 'definitions'; { do not localize }
SMessage = 'message'; { do not localize }
SPart = 'part'; { do not localize }
SType = 'type'; { do not localize }
STypes = 'types'; { do not localize }
SImport = 'import'; { do not localize }
SPort = 'port'; { do not localize }
SPortType = 'portType'; { do not localize }
SOperation = 'operation'; { do not localize }
SBinding = 'binding'; { do not localize }
SService = 'service'; { do not localize }
SSchema = 'schema'; { do not localize }
SName = 'name'; { do not localize }
STns = 'targetNamespace'; { do not localize }
SInput = 'input'; { do not localize }
SOutput = 'output'; { do not localize }
SInOut = 'inout'; { do not localize }
SRequest = 'Request'; { do not localize }
SResponse = 'Response'; { do not localize }
SReturn = 'return'; { do not localize }
SElement = 'element'; { do not localize }
SComplexType = 'complexType'; { do not localize }
xsdns = 'http:/'+'/www.w3.org/1999/XMLSchema'; { do not localize }
tns = 'http:/'+'/www.borland.com/soapServices/'; { do not localize }
Wsdlns = 'http:/'+'/schemas.xmlsoap.org/wsdl/'; { do not localize }
Soapns = Wsdlns +'soap'; { do not localize }
SoapEncoding = 'http:/'+'/schemas.xmlsoap.org/soap/encoding'; { do not localize }
//Soap Binding specific
//Remove hardcoding the namespace
SWSDLSoapAddress = 'soap:address'; { do not localize }
SWSDLSoapBinding = 'soap:binding'; { do not localize }
SWSDLSoapOperation= 'soap:operation'; { do not localize }
SWSDLSoapBody = 'soap:body'; { do not localize }
SWSDLSoapHeader = 'soap:header'; { do not localize }
SWSDLSoapFault = 'soap:fault'; { do not localize }
SStyle = 'style'; { do not localize }
STransport = 'transport'; { do not localize }
SLocation = 'location'; { do not localize }
SSoapAction = 'soapAction'; { do not localize }
SParts = 'parts'; { do not localize }
SUse = 'use'; { do not localize }
SNameSpace = 'namespace'; { do not localize }
SEncodingStyle = 'encodingStyle'; { do not localize }
SFault = 'fault'; { do not localize }
SSoapArray = 'soap:Array'; { do not localize }
SArrayOf = 'ArrayOf'; { do not localize }
SArray = 'Array'; { do not localize }
SArrayType = 'arrayType'; { do not localize }
SUnknown = 'Unknown'; { do not localize }
SDynArray = 'array of '; { do not localize }
SAnySimpleType = 'anySimpleType'; { do not localize }
SNsPrefix = 'ns'; { do not localize }
ReservedWords: array[0..64] of string = ('and', 'array', 'as', 'asm', 'begin','case',
'class','const','constructor','destructor', 'dispinterface', 'div', 'do','downto',
'else', 'end', 'except', 'exports', 'file', 'finalization', 'finally', 'for','function',
'goto', 'if', 'implementation', 'in','inherited','initialization', 'inline','interface',
'is','label','library', 'mod','nil','not','object','of','or','out','packed','procedure',
'program','property','raise','record','repeat', 'resourcestring', 'set','shl','shr', 'string',
'then', 'threadvar', 'to','try','type','unit','until','uses','var','while','with','xor');
Directives: array[0..38] of string = ('absoulte','abstract','assembler','automated','cdecl','contains',
'default','dispid', 'dynamic', 'export','external','far','forward','implements','index','message',
'name','near','nodefault','overload','override','package','pascal','private','protected','public',
'published','read','readonly','register','reintroduce','requires','resident','safecall','stdcall',
'stored','virtual','write','writeonly');
Operators: array[0..11] of string = ('+','-','*','/','@','^','=','>','<','<>','<=','>=');
ScalarArrayTypes: array[0..12] of string = ('Integer','Cardinal','Word','SmallInt','Byte','ShortInt','Int64',
'LongWord','Single','Double','Boolean','String','WideString');
DynArrayTypes: array[0..12] of string = ('TIntegerDynArray','TCardinalDynArray','TWordDynArray',
'TSmallIntDynArray','TByteDynArray','TShortIntDynArray','TInt64DynArray','TLongWordDynArray','TSingleDynArray',
'TDoubleDynArray','TBooleanDynArray','TStringDynArray','TWideStringDynArray');
resourcestring
SWideStringOutOfBounds = 'WideString Index outof bounds';
implementation
{ TWideStrings implementation }
constructor TWideStrings.Create;
begin
FWideStringList := TList.Create;
end;
destructor TWideStrings.Destroy;
var
Index: Integer;
PWStr: ^TWString;
begin
for Index := 0 to FWideStringList.Count-1 do
begin
PWStr := FWideStringList.Items[Index];
if PWStr <> nil then
Dispose(PWStr);
end;
FWideStringList.Free;
inherited Destroy;
end;
function TWideStrings.Get(Index: Integer): WideString;
var
PWStr: ^TWString;
begin
Result := '';
if ( (Index >= 0) and (Index < FWideStringList.Count) ) then
begin
PWStr := FWideStringList.Items[Index];
if PWStr <> nil then
Result := PWStr^.WString;
end;
end;
procedure TWideStrings.Put(Index: Integer; const S: WideString);
begin
Insert(Index,S);
end;
function TWideStrings.Add(const S: WideString): Integer;
var
PWStr: ^TWString;
begin
New(PWStr);
PWStr^.WString := S;
Result := FWideStringList.Add(PWStr);
end;
function TWideStrings.IndexOf(const S: WideString): Integer;
var
Index: Integer;
PWStr: ^TWString;
begin
Result := -1;
for Index := 0 to FWideStringList.Count -1 do
begin
PWStr := FWideStringList.Items[Index];
if PWStr <> nil then
begin
if S = PWStr^.WString then
begin
Result := Index;
break;
end;
end;
end;
end;
function TWideStrings.Count: Integer;
begin
Result := FWideStringList.Count;
end;
procedure TWideStrings.Clear;
var
Index: Integer;
PWStr: ^TWString;
begin
for Index := 0 to FWideStringList.Count-1 do
begin
PWStr := FWideStringList.Items[Index];
if PWStr <> nil then
Dispose(PWStr);
end;
FWideStringList.Clear;
end;
procedure TWideStrings.Insert(Index: Integer; const S: WideString);
var
PWStr: ^TWString;
begin
if((Index < 0) or (Index > FWideStringList.Count)) then
raise Exception.Create(SWideStringOutofBounds);
if Index < FWideStringList.Count then
begin
PWStr := FWideStringList.Items[Index];
if PWStr <> nil then
PWStr.WString := S;
end
else
Add(S);
end;
end.
|
unit LUX;
interface //#################################################################### ■
uses System.SysUtils, System.UITypes, System.Math.Vectors,
FMX.Graphics, FMX.Types3D, FMX.Controls3D, FMX.Objects3D;
type //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【型】
PPByte = ^PByte;
TArray2<TValue_> = array of TArray <TValue_>;
TArray3<TValue_> = array of TArray2<TValue_>;
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% HMatrix3D
HMatrix3D = record helper for TMatrix3D
private
///// アクセス
function GetTranslate :TPoint3D; inline;
procedure SetTranslate( const Translate_:TPoint3D ); inline;
public
///// プロパティ
property Translate :TPoint3D read GetTranslate write SetTranslate;
///// 定数
class function Identity :TMatrix3D; static;
end;
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% HBitmapData
HBitmapData = record helper for TBitmapData
private
///// アクセス
function GetColor( const X_,Y_:Integer ) :TAlphaColor; inline;
procedure SetColor( const X_,Y_:Integer; const Color_:TAlphaColor ); inline;
public
///// プロパティ
property Color[ const X_,Y_:Integer ] :TAlphaColor read GetColor write SetColor;
end;
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TRay3D
TRay3D = record
private
public
Pos :TVector3D;
Vec :TVector3D;
/////
constructor Create( const Pos_,Vec_:TVector3D );
end;
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% HControl3D
HControl3D = class helper for TControl3D
private
///// アクセス
function Get_SizeX :Single; inline;
procedure Set_SizeX( const _SizeX_:Single ); inline;
function Get_SizeY :Single; inline;
procedure Set_SizeY( const _SizeY_:Single ); inline;
function Get_SizeZ :Single; inline;
procedure Set_SizeZ( const _SizeZ_:Single ); inline;
///// メソッド
procedure RecalcFamilyAbsolute; inline;
protected
property _SizeX :Single read Get_SizeX write Set_SizeX;
property _SizeY :Single read Get_SizeY write Set_SizeY;
property _SizeZ :Single read Get_SizeZ write Set_SizeZ;
///// アクセス
function GetAbsolMatrix :TMatrix3D; inline;
procedure SetAbsoluteMatrix( const AbsoluteMatrix_:TMatrix3D ); virtual;
function GetLocalMatrix :TMatrix3D; virtual;
procedure SetLocalMatrix( const LocalMatrix_:TMatrix3D ); virtual;
///// メソッド
procedure RecalcChildrenAbsolute;
public
///// プロパティ
property AbsoluteMatrix :TMatrix3D read GetAbsolMatrix write SetAbsoluteMatrix;
property LocalMatrix :TMatrix3D read GetLocalMatrix write SetLocalMatrix;
end;
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% HCustomMesh
HCustomMesh = class helper for TCustomMesh
private
protected
///// アクセス
function GetMeshData :TMeshData; inline;
public
///// プロパティ
property MeshData :TMeshData read GetMeshData;
end;
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TProxyObject
TProxyObject = class( FMX.Controls3D.TProxyObject )
private
protected
///// メソッド
procedure Render; override;
public
end;
const //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【定数】
Pi2 = 2 * Pi;
Pi3 = 3 * Pi;
Pi4 = 4 * Pi;
P2i = Pi / 2;
P3i = Pi / 3;
P4i = Pi / 4;
//var //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【変数】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】
function Pow2( const X_:Integer ) :Integer; inline; overload;
function Pow2( const X_:Single ) :Single; inline; overload;
function Pow2( const X_:Double ) :Double; inline; overload;
function Pow3( const X_:Integer ) :Integer; inline; overload;
function Pow3( const X_:Single ) :Single; inline; overload;
function Pow3( const X_:Double ) :Double; inline; overload;
function Roo2( const X_:Single ) :Single; inline; overload;
function Roo2( const X_:Double ) :Double; inline; overload;
function Roo3( const X_:Single ) :Single; inline; overload;
function Roo3( const X_:Double ) :Double; inline; overload;
function ClipRange( const X_,Min_,Max_:Integer ) :Integer; inline; overload;
function ClipRange( const X_,Min_,Max_:Single ) :Single; inline; overload;
function ClipRange( const X_,Min_,Max_:Double ) :Double; inline; overload;
function MinI( const A_,B_,C_:Single ) :Integer; inline; overload;
function MinI( const A_,B_,C_:Double ) :Integer; inline; overload;
function MaxI( const Vs_:array of Single ) :Integer; overload;
function MaxI( const Vs_:array of Double ) :Integer; overload;
function LoopMod( const X_,Range_:Integer ) :Integer; overload;
function LoopMod( const X_,Range_:Int64 ) :Int64; overload;
function FileToBytes( const FileName_:string ) :TBytes;
implementation //############################################################### ■
uses System.Classes, System.Math,
FMX.Types;
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% HMatrix3D
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private
function HMatrix3D.GetTranslate :TPoint3D;
begin
with Result do
begin
X := m41;
Y := m42;
Z := m43;
end;
end;
procedure HMatrix3D.SetTranslate( const Translate_:TPoint3D );
begin
with Translate_ do
begin
m41 := X;
m42 := Y;
m43 := Z;
end;
end;
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public
class function HMatrix3D.Identity :TMatrix3D;
begin
with Result do
begin
m11 := 1; m12 := 0; m13 := 0; m14 := 0;
m21 := 0; m22 := 1; m23 := 0; m24 := 0;
m31 := 0; m32 := 0; m33 := 1; m34 := 0;
m41 := 0; m42 := 0; m43 := 0; m44 := 1;
end;
end;
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% HBitmapData
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private
function HBitmapData.GetColor( const X_,Y_:Integer ) :TAlphaColor;
begin
Result := GetPixel( X_, Y_ );
end;
procedure HBitmapData.SetColor( const X_,Y_:Integer; const Color_:TAlphaColor );
begin
SetPixel( X_, Y_, Color_ );
end;
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TRay3D
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public
constructor TRay3D.Create( const Pos_,Vec_:TVector3D );
begin
Pos := Pos_;
Vec := Vec_;
end;
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% HControl3D
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private
/////////////////////////////////////////////////////////////////////// アクセス
function HControl3D.Get_SizeX :Single;
begin
Result := FWidth;
end;
procedure HControl3D.Set_SizeX( const _SizeX_:Single );
begin
FWidth := _SizeX_;
end;
function HControl3D.Get_SizeY :Single;
begin
Result := FHeight;
end;
procedure HControl3D.Set_SizeY( const _SizeY_:Single );
begin
FHeight := _SizeY_;
end;
function HControl3D.Get_SizeZ :Single;
begin
Result := FDepth;
end;
procedure HControl3D.Set_SizeZ( const _SizeZ_:Single );
begin
FDepth := _SizeZ_;
end;
/////////////////////////////////////////////////////////////////////// メソッド
procedure HControl3D.RecalcFamilyAbsolute;
begin
RecalcAbsolute;
end;
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected
/////////////////////////////////////////////////////////////////////// アクセス
function HControl3D.GetAbsolMatrix :TMatrix3D;
begin
Result := Self.GetAbsoluteMatrix;
end;
procedure HControl3D.SetAbsoluteMatrix( const AbsoluteMatrix_:TMatrix3D );
begin
FAbsoluteMatrix := AbsoluteMatrix_;
FInvAbsoluteMatrix := FAbsoluteMatrix.Inverse;
if Assigned( FParent ) and ( FParent is TControl3D )
then FLocalMatrix := FAbsoluteMatrix * TControl3D( FParent ).AbsoluteMatrix.Inverse
else FLocalMatrix := FAbsoluteMatrix;
FRecalcAbsolute := False;
RecalcChildrenAbsolute;
end;
function HControl3D.GetLocalMatrix :TMatrix3D;
begin
Result := FLocalMatrix;
end;
procedure HControl3D.SetLocalMatrix( const LocalMatrix_:TMatrix3D );
begin
FLocalMatrix := LocalMatrix_;
RecalcAbsolute;
end;
/////////////////////////////////////////////////////////////////////// メソッド
procedure HControl3D.RecalcChildrenAbsolute;
var
F :TFmxObject;
begin
if Assigned( Children ) then
begin
for F in Children do
begin
if F is TControl3D then TControl3D( F ).RecalcFamilyAbsolute;
end;
end;
end;
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% HCustomMesh
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected
/////////////////////////////////////////////////////////////////////// アクセス
function HCustomMesh.GetMeshData :TMeshData;
begin
Result := Self.FData;
end;
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TProxyObject
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected
/////////////////////////////////////////////////////////////////////// メソッド
procedure TProxyObject.Render;
var
M :TMatrix3D;
SX, SY, SZ :Single;
begin
if Assigned( SourceObject ) then
begin
with SourceObject do
begin
M := AbsoluteMatrix;
SX := _SizeX;
SY := _SizeY;
SZ := _SizeZ;
AbsoluteMatrix := Self.AbsoluteMatrix;
_SizeX := Self._SizeX;
_SizeY := Self._SizeY;
_SizeZ := Self._SizeZ;
RenderInternal;
AbsoluteMatrix := M;
_SizeX := SX;
_SizeY := SY;
_SizeZ := SZ;
end;
end;
end;
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】
function Pow2( const X_:Integer ) :Integer;
begin
Result := Sqr( X_ );
end;
function Pow2( const X_:Single ) :Single;
begin
Result := Sqr( X_ );
end;
function Pow2( const X_:Double ) :Double;
begin
Result := Sqr( X_ );
end;
////////////////////////////////////////////////////////////////////////////////
function Pow3( const X_:Integer ) :Integer;
begin
Result := X_ * X_ * X_;
end;
function Pow3( const X_:Single ) :Single;
begin
Result := X_ * X_ * X_;
end;
function Pow3( const X_:Double ) :Double;
begin
Result := X_ * X_ * X_;
end;
////////////////////////////////////////////////////////////////////////////////
function Roo2( const X_:Single ) :Single;
begin
Result := Sqrt( X_ );
end;
function Roo2( const X_:Double ) :Double;
begin
Result := Sqrt( X_ );
end;
////////////////////////////////////////////////////////////////////////////////
function Roo3( const X_:Single ) :Single;
begin
Result := Power( X_, 1/3 );
end;
function Roo3( const X_:Double ) :Double;
begin
Result := Power( X_, 1/3 );
end;
////////////////////////////////////////////////////////////////////////////////
function ClipRange( const X_,Min_,Max_:Integer ) :Integer;
begin
if X_ < Min_ then Result := Min_
else
if X_ > Max_ then Result := Max_
else Result := X_;
end;
function ClipRange( const X_,Min_,Max_:Single ) :Single;
begin
if X_ < Min_ then Result := Min_
else
if X_ > Max_ then Result := Max_
else Result := X_;
end;
function ClipRange( const X_,Min_,Max_:Double ) :Double;
begin
if X_ < Min_ then Result := Min_
else
if X_ > Max_ then Result := Max_
else Result := X_;
end;
////////////////////////////////////////////////////////////////////////////////
function MinI( const A_,B_,C_:Single ) :Integer;
begin
if A_ <= B_ then
begin
if A_ <= C_ then Result := 1
else Result := 3;
end
else
begin
if B_ <= C_ then Result := 2
else Result := 3;
end;
end;
function MinI( const A_,B_,C_:Double ) :Integer;
begin
if A_ <= B_ then
begin
if A_ <= C_ then Result := 1
else Result := 3;
end
else
begin
if B_ <= C_ then Result := 2
else Result := 3;
end;
end;
////////////////////////////////////////////////////////////////////////////////
function MaxI( const Vs_:array of Single ) :Integer;
var
I :Integer;
V0, V1 :Single;
begin
Result := 0; V0 := Vs_[ 0 ];
for I := 1 to High( Vs_ ) do
begin
V1 := Vs_[ I ];
if V1 > V0 then
begin
Result := I; V0 := V1;
end
end
end;
function MaxI( const Vs_:array of Double ) :Integer;
var
I :Integer;
V0, V1 :Double;
begin
Result := 0; V0 := Vs_[ 0 ];
for I := 1 to High( Vs_ ) do
begin
V1 := Vs_[ I ];
if V1 > V0 then
begin
Result := I; V0 := V1;
end
end
end;
////////////////////////////////////////////////////////////////////////////////
function LoopMod( const X_,Range_:Integer ) :Integer;
begin
Result := X_ mod Range_; if Result < 0 then Inc( Result, Range_ );
end;
function LoopMod( const X_,Range_:Int64 ) :Int64;
begin
Result := X_ mod Range_; if Result < 0 then Inc( Result, Range_ );
end;
////////////////////////////////////////////////////////////////////////////////
function FileToBytes( const FileName_:string ) :TBytes;
begin
with TMemoryStream.Create do
begin
try
LoadFromFile( FileName_ );
SetLength( Result, Size );
Read( Result, Size );
finally
Free;
end;
end;
end;
//############################################################################## □
initialization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 初期化
Randomize;
finalization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 最終化
end. //######################################################################### ■
|
unit ReintroduceForm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
FMX.Layouts, FMX.Memo, FMX.Controls.Presentation, FMX.ScrollBox;
type
TForm1 = class(TForm)
Memo1: TMemo;
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
procedure Show (const msg: string);
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
procedure Show (const msg: string);
begin
Form1.Show(msg);
end;
type
TMyClass = class
procedure One; overload; virtual;
procedure One (I: Integer); overload;
end;
TMySubClass = class (TMyClass)
procedure One; overload; override;
procedure One (S: string); reintroduce; overload;
end;
{ MyClass }
procedure TMyClass.One;
begin
Show ('MyClass.One');
end;
procedure TMyClass.One(I: Integer);
begin
Show ('Integer: ' + IntToStr (I));
end;
{ MySubClass }
procedure TMySubClass.One;
begin
Show ('MySubClass.One');
end;
procedure TMySubClass.One(S: string);
begin
Show ('String: ' + S);
end;
procedure TForm1.Button1Click(Sender: TObject);
var
Obj: TMySubClass;
begin
Obj := TMySubClass.Create;
Obj.One;
Obj.One (10);
Obj.One ('Hello');
Obj.Free;
end;
procedure TForm1.Show(const Msg: string);
begin
Memo1.Lines.Add(Msg);
end;
end.
|
(*
ICBC通讯API
原始作者:王云涛
建立时间:2011-12-02
*)
unit u_ICBCAPI;
interface
uses
SysUtils, Classes, Variants, IdCoderMIME, u_NCAPI, u_ICBCXMLAPI, u_ICBCRec;
type
TICBCAPI = class(TComponent)
private
FdeBase64: TIdDecoderMIME;
FICBCRsq: TICBCRequestAPI;
FICBCRspon: TICBCResponseAPI;
FCIS, FBankCode, FID: string;
FSIGN_URL, FHTTPS_URL: string;
function getPubRec(const TransCode, fSeqno: string): TPubRec;
function NCSvrRequest(const pub: TPubRec; const reqDataStr: string;
const IsSign: Boolean; out rtDataBase64Str: string): Boolean;
public
function QueryAccValue(const fSeqno: string; var qav: TQueryAccValueRec;
var rtDataStr: string): Boolean;
function QueryHistoryDetails(const fSeqno: string;
var qhd: TQueryHistoryDetailsRec; var rtDataStr: string): Boolean;
function PayEnt(const fSeqno: string; var pe: TPayEntRec;
var rtDataStr: string): Boolean;
function PerDis(const fSeqno: string; var pd: TPerDisRec;
var rtDataStr: string): Boolean;
function QueryCurDayDetails(const fSeqno: string;
var qcd: TQueryCurDayDetailsRec; var rtDataStr: string): Boolean;
function QueryPerDis(const fSeqno: string; var qpd: TQueryPerDisRec;
var rtDataStr: string): Boolean;
function QueryPayEnt(const fSeqno: string; var qpe: TQueryPayEntRec;
var rtDataStr: string): Boolean;
function QueryPerInf(const fSeqno: string; var qpi: TQueryPerInf;
var rtDataStr: string): Boolean;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property CIS: string read FCIS write FCIS;
property BankCode: string read FBankCode write FBankCode;
property ID: string read FID write FID;
//签名端口
property SIGN_URL: string read FSIGN_URL write FSIGN_URL;
//安全http协议服务器
property HTTPS_URL: string read FHTTPS_URL write FHTTPS_URL;
end;
implementation
procedure WriteLog(const Str, flog: string);
var
f: TextFile;
begin
AssignFile(F, flog);
try
Rewrite(f);
Write(f, Str);
finally
closeFile(F);
end;
end;
function TICBCAPI.NCSvrRequest(const pub: TPubRec; const reqDataStr: string; const IsSign: Boolean;
out rtDataBase64Str: string): Boolean;
var
FNC: TNCSvr;
FSign: TSign;
reqData: string;
rtxmlStr: string;
begin
Result := False;
reqData := '';
rtxmlStr := '';
FNC := TNCSvr.Create(Self);
//签名端口
FNC.SIGN_URL := FSIGN_URL;
//安全http协议服务器
FNC.HTTPS_URL := FHTTPS_URL;
FSign := TSign.create(Self);
try
//签名
if IsSign then
begin
if not FNC.Sign(reqDataStr, rtxmlStr) then Exit;
if not FSign.SetXML(rtxmlStr) then Exit;
if FSign.SignRec.RtCode <> '0' then
begin
raise Exception.Create('签名异常,' + FSign.SignRec.RtStr);
Exit;
end;
//Sign 后字符
reqData := FSign.SignRec.DataStr;
end
else
begin
//GP BASE64编码 ,直接明文
reqData := reqDataStr;
end;
Result := FNC.Request(Pub, reqData, rtDataBase64Str);
finally
FSign.Free;
FNC.Free;
end;
end;
{ TICBCAPI }
constructor TICBCAPI.Create(AOwner: TComponent);
begin
inherited;
FdeBase64 := TIdDecoderMIME.Create(self);
FICBCRsq := TICBCRequestAPI.Create(Self);
FICBCRspon := TICBCResponseAPI.Create(self);
end;
destructor TICBCAPI.Destroy;
begin
FICBCRspon.Free;
FICBCRsq.Free;
FdeBase64.Free;
inherited;
end;
function TICBCAPI.getPubRec(const TransCode, fSeqno: string): TPubRec;
begin
FillChar(Result, SizeOf(TPubRec), 0);
Result.TransCode := TransCode;
Result.CIS := FCIS;
Result.BankCode := FBankCode;
Result.ID := FID;
Result.TranDate := FormatDateTime('YYYYMMDD', Now);
//去掉微秒
Result.TranTime := FormatDateTime('hhnnsszzz', Now);
Result.fSeqno := fSeqno;
end;
function TICBCAPI.QueryAccValue(const fSeqno: string; var qav: TQueryAccValueRec;
var rtDataStr: string): Boolean;
var
rtDataBase64Str: string;
pub: TPubRec;
begin
Result := False;
rtDataStr := '';
rtDataBase64Str := '';
//请求XML部分
pub := getPubRec('QACCBAL', fSeqno);
FICBCRsq.setPub(pub);
FICBCRsq.setQueryAccValue(qav);
//GP BASE64编码 ,直接明文
if not NCSvrRequest(Pub, FICBCRsq.GetXML, False, rtDataBase64Str) then
begin
//errorCode
rtDataStr := FdeBase64.DecodeString(rtDataBase64Str);
Exit;
end;
//解码
rtDataStr := FdeBase64.DecodeString(rtDataBase64Str);
WriteLog(FICBCRsq.GetXML, 'c:\查询卡余S.xml');
WriteLog(rtDataStr, 'c:\查询卡余R.xml');
//解析
FICBCRspon.SetXML(rtDataStr);
Pub := FICBCRspon.Pub;
if Pub.RetCode <> '0' then
begin
rtDataStr := '[' + Pub.RetCode + ']' + Pub.RetMsg;
Exit;
end;
//返回结果
qav := FICBCRspon.getQueryAccValue();
Result := True;
end;
function TICBCAPI.QueryHistoryDetails(const fSeqno: string; var qhd: TQueryHistoryDetailsRec;
var rtDataStr: string): Boolean;
var
rtDataBase64Str: string;
pub: TPubRec;
begin
Result := False;
rtDataStr := '';
rtDataBase64Str := '';
//请求XML部分
pub := getPubRec('QHISD', fSeqno);
FICBCRsq.setPub(pub);
FICBCRsq.setQueryHistoryDetailsRec(qhd);
//GP BASE64编码 ,直接明文
if not NCSvrRequest(Pub, FICBCRsq.GetXML, False, rtDataBase64Str) then
begin
//errorCode
rtDataStr := FdeBase64.DecodeString(rtDataBase64Str);
Exit;
end;
//解码
rtDataStr := FdeBase64.DecodeString(rtDataBase64Str);
//解析
FICBCRspon.SetXML(rtDataStr);
Pub := FICBCRspon.Pub;
if Pub.RetCode <> '0' then
begin
rtDataStr := '[' + Pub.RetCode + ']' + Pub.RetMsg;
Exit;
end;
//返回结果
qhd := FICBCRspon.getQueryHistoryDetails();
Result := True;
end;
function TICBCAPI.QueryCurDayDetails(const fSeqno: string; var qcd: TQueryCurDayDetailsRec;
var rtDataStr: string): Boolean;
var
rtDataBase64Str: string;
pub: TPubRec;
begin
Result := False;
rtDataStr := '';
rtDataBase64Str := '';
//请求XML部分
pub := getPubRec('QPD', fSeqno);
FICBCRsq.setPub(pub);
FICBCRsq.setQueryCurDayDetailsRec(qcd);
//GP BASE64编码 ,直接明文
if not NCSvrRequest(Pub, FICBCRsq.GetXML, False, rtDataBase64Str) then
begin
//errorCode
rtDataStr := FdeBase64.DecodeString(rtDataBase64Str);
Exit;
end;
//解码
rtDataStr := FdeBase64.DecodeString(rtDataBase64Str);
WriteLog(FICBCRsq.GetXML, 'c:\当日明细S.xml');
WriteLog(rtDataStr, 'c:\当日明细R.xml');
//解析
FICBCRspon.SetXML(rtDataStr);
Pub := FICBCRspon.Pub;
if Pub.RetCode <> '0' then
begin
rtDataStr := '[' + Pub.RetCode + ']' + Pub.RetMsg;
Exit;
end;
//返回结果
qcd := FICBCRspon.getQueryCurDayDetails();
Result := True;
end;
function TICBCAPI.PayEnt(const fSeqno: string; var pe: TPayEntRec;
var rtDataStr: string): Boolean;
var
rtDataBase64Str: string;
pub: TPubRec;
begin
Result := False;
rtDataStr := '';
rtDataBase64Str := '';
//请求XML部分
pub := getPubRec('PAYENT', fSeqno);
FICBCRsq.setPub(pub);
FICBCRsq.setPayEntRec(pe);
//GP BASE64编码 ,直接明文
if not NCSvrRequest(Pub, FICBCRsq.GetXML, True, rtDataBase64Str) then
begin
//errorCode
rtDataStr := FdeBase64.DecodeString(rtDataBase64Str);
Exit;
end;
//解码
rtDataStr := FdeBase64.DecodeString(rtDataBase64Str);
WriteLog(FICBCRsq.GetXML, 'c:\支付指令S.xml');
WriteLog(rtDataStr, 'c:\支付指令R.xml');
//解析
FICBCRspon.SetXML(rtDataStr);
Pub := FICBCRspon.Pub;
if Pub.RetCode <> '0' then
begin
rtDataStr := '[' + Pub.RetCode + ']' + Pub.RetMsg;
Exit;
end;
//返回结果
pe := FICBCRspon.getPayEnt();
Result := True;
end;
function TICBCAPI.PerDis(const fSeqno: string; var pd: TPerDisRec;
var rtDataStr: string): Boolean;
var
rtDataBase64Str: string;
pub: TPubRec;
begin
Result := False;
rtDataStr := '';
rtDataBase64Str := '';
//请求XML部分
pub := getPubRec('PERDIS', fSeqno);
FICBCRsq.setPub(pub);
FICBCRsq.setPerDisRec(pd);
//GP BASE64编码 ,直接明文
if not NCSvrRequest(Pub, FICBCRsq.GetXML, True, rtDataBase64Str) then
begin
//errorCode
rtDataStr := FdeBase64.DecodeString(rtDataBase64Str);
Exit;
end;
//解码
rtDataStr := FdeBase64.DecodeString(rtDataBase64Str);
WriteLog(FICBCRsq.GetXML, 'c:\批量扣个人S.xml');
WriteLog(rtDataStr, 'c:\批量扣个人R.xml');
//解析
FICBCRspon.SetXML(rtDataStr);
Pub := FICBCRspon.Pub;
if Pub.RetCode <> '0' then
begin
rtDataStr := '[' + Pub.RetCode + ']' + Pub.RetMsg;
Exit;
end;
//返回结果
pd := FICBCRspon.getPerDis();
Result := True;
end;
function TICBCAPI.QueryPerDis(const fSeqno: string; var qpd: TQueryPerDisRec;
var rtDataStr: string): Boolean;
var
rtDataBase64Str: string;
pub: TPubRec;
begin
Result := False;
rtDataStr := '';
rtDataBase64Str := '';
//请求XML部分
pub := getPubRec('QPERDIS', fSeqno);
FICBCRsq.setPub(pub);
FICBCRsq.setQueryPerDisRec(qpd);
//GP BASE64编码 ,直接明文
if not NCSvrRequest(Pub, FICBCRsq.GetXML, False, rtDataBase64Str) then
begin
//errorCode
rtDataStr := FdeBase64.DecodeString(rtDataBase64Str);
Exit;
end;
//解码
rtDataStr := FdeBase64.DecodeString(rtDataBase64Str);
WriteLog(FICBCRsq.GetXML, 'c:\批量扣个人指令查询S.xml');
WriteLog(rtDataStr, 'c:\批量扣个人指令查询R.xml');
//解析
FICBCRspon.SetXML(rtDataStr);
Pub := FICBCRspon.Pub;
if Pub.RetCode <> '0' then
begin
rtDataStr := '[' + Pub.RetCode + ']' + Pub.RetMsg;
Exit;
end;
//返回结果
qpd := FICBCRspon.getQueryPerDis();
Result := True;
end;
function TICBCAPI.QueryPayEnt(const fSeqno: string; var qpe: TQueryPayEntRec;
var rtDataStr: string): Boolean;
var
rtDataBase64Str: string;
pub: TPubRec;
begin
Result := False;
rtDataStr := '';
rtDataBase64Str := '';
//请求XML部分
pub := getPubRec('QPAYENT', fSeqno);
FICBCRsq.setPub(pub);
FICBCRsq.setQueryPayEntRec(qpe);
//GP BASE64编码 ,直接明文
if not NCSvrRequest(Pub, FICBCRsq.GetXML, False, rtDataBase64Str) then
begin
//errorCode
rtDataStr := FdeBase64.DecodeString(rtDataBase64Str);
Exit;
end;
//解码
rtDataStr := FdeBase64.DecodeString(rtDataBase64Str);
WriteLog(FICBCRsq.GetXML, 'c:\支付指令查询S.xml');
WriteLog(rtDataStr, 'c:\支付指令查询R.xml');
//解析
FICBCRspon.SetXML(rtDataStr);
Pub := FICBCRspon.Pub;
if Pub.RetCode <> '0' then
begin
rtDataStr := '[' + Pub.RetCode + ']' + Pub.RetMsg;
Exit;
end;
//返回结果
qpe := FICBCRspon.getQueryPayEnt();
Result := True;
end;
function TICBCAPI.QueryPerInf(const fSeqno: string; var qpi: TQueryPerInf;
var rtDataStr: string): Boolean;
var
rtDataBase64Str: string;
pub: TPubRec;
begin
Result := False;
rtDataStr := '';
rtDataBase64Str := '';
//请求XML部分
pub := getPubRec('QPERINF', fSeqno);
FICBCRsq.setPub(pub);
FICBCRsq.setQueryPerInf(qpi);
//GP BASE64编码 ,直接明文
if not NCSvrRequest(Pub, FICBCRsq.GetXML, False, rtDataBase64Str) then
begin
//errorCode
rtDataStr := FdeBase64.DecodeString(rtDataBase64Str);
Exit;
end;
//解码
rtDataStr := FdeBase64.DecodeString(rtDataBase64Str);
WriteLog(FICBCRsq.GetXML, 'c:\缴费个人信息查询S.xml');
WriteLog(rtDataStr, 'c:\缴费个人信息查询R.xml');
//解析
FICBCRspon.SetXML(rtDataStr);
Pub := FICBCRspon.Pub;
if Pub.RetCode <> '0' then
begin
rtDataStr := '[' + Pub.RetCode + ']' + Pub.RetMsg;
Exit;
end;
//返回结果
qpi := FICBCRspon.getQueryPerInf();
Result := True;
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC persistent definitions }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
{$IF DEFINED(IOS) OR DEFINED(ANDROID)}
{$HPPEMIT LINKUNIT}
{$ELSE}
{$IFDEF WIN32}
{$HPPEMIT '#pragma link "FireDAC.Stan.Def.obj"'}
{$ELSE}
{$HPPEMIT '#pragma link "FireDAC.Stan.Def.o"'}
{$ENDIF}
{$ENDIF}
unit FireDAC.Stan.Def;
interface
uses
FireDAC.Stan.Intf;
function FDLoadConnDefGlobalFileName: String;
procedure FDSaveConnDefGlobalFileName(const AName: String);
function FDLoadDriverDefGlobalFileName: String;
procedure FDSaveDriverDefGlobalFileName(const AName: String);
implementation
uses
{$IFDEF MSWINDOWS}
Winapi.Windows,
{$ENDIF}
System.SysUtils, System.Classes, System.IniFiles,
FireDAC.Stan.Factory, FireDAC.Stan.Util, FireDAC.Stan.Error, FireDAC.Stan.Consts,
FireDAC.Stan.Option, FireDAC.Stan.ResStrs;
type
TFDCustomDefinitionStorage = class;
TFDFileDefinitionStorage = class;
TFDDefinition = class;
TFDDefinitions = class;
TFDDefinitionClass = class of TFDDefinition;
TFDConnectionDef = class;
TFDConnectionDefs = class;
TFDCustomDefinitionStorage = class (TFDObject, IFDStanDefinitionStorage)
private
FFileName: String;
FGlobalFileName: String;
FDefaultFileName: String;
protected
// IFDStanDefinitionStorage
function GetFileName: String;
procedure SetFileName(const AValue: String);
function GetGlobalFileName: String;
procedure SetGlobalFileName(const AValue: String);
function GetDefaultFileName: String;
procedure SetDefaultFileName(const AValue: String);
function CreateIniFile: TCustomIniFile; virtual; abstract;
function ActualFileName: String; virtual; abstract;
end;
TFDFileDefinitionStorage = class(TFDCustomDefinitionStorage)
public
function CreateIniFile: TCustomIniFile; override;
function ActualFileName: String; override;
end;
TFDDefinitionFlag = (dfParentMaybeChanged, dfRefManaged, dfDeleteDisabled,
dfModifyDisabled);
TFDDefinitionFlags = set of TFDDefinitionFlag;
TFDDefinition = class (TCollectionItem, IUnknown, IFDStanDefinition)
private
{$IFNDEF AUTOREFCOUNT}
FRefCount: Integer;
{$ENDIF}
FOriginalName,
FPrevName: String;
FParams: TFDConnectionDefParams;
FState: TFDDefinitionState;
FStyle: TFDDefinitionStyle;
FFlags: TFDDefinitionFlags;
FParentDefinition: IFDStanDefinition;
FOnChanging: TNotifyEvent;
FOnChanged: TNotifyEvent;
FPassCode: LongWord;
function GetDefinitionList: TFDDefinitions;
procedure ParamsChanging(Sender: TObject);
procedure CheckRO(AFlag: TFDDefinitionFlag);
procedure UpdateParentDefinition;
procedure InternalSetParentDefinition(const AValue: IFDStanDefinition);
protected
// IUnknown
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
// IFDStanDefinition
function GetName: String;
function GetParams: TStrings;
function GetAsBoolean(const AName: String): LongBool;
function GetAsInteger(const AName: String): LongInt;
function GetAsString(const AName: String): String;
function GetAsXString(const AName: String): String;
function GetState: TFDDefinitionState;
function GetStyle: TFDDefinitionStyle;
function GetParentDefinition: IFDStanDefinition;
function GetOnChanging: TNotifyEvent;
function GetOnChanged: TNotifyEvent;
function GetUpdatable: Boolean;
procedure SetName(const AValue: string);
procedure SetParams(const AValue: TStrings);
procedure SetAsBoolean(const AName: String; const AValue: LongBool);
procedure SetAsYesNo(const AName: String; const AValue: LongBool);
procedure SetAsInteger(const AName: String; const AValue: LongInt);
procedure SetAsString(const AName, AValue: String);
procedure SetParentDefinition(const AValue: IFDStanDefinition);
procedure SetOnChanging(AValue: TNotifyEvent);
procedure SetOnChanged(AValue: TNotifyEvent);
{$IFDEF FireDAC_MONITOR}
procedure BaseTrace(const AMonitor: IFDMoniClient);
procedure Trace(const AMonitor: IFDMoniClient);
{$ENDIF}
procedure Apply;
procedure Clear;
procedure Cancel;
procedure Delete;
procedure MarkPersistent; virtual;
procedure MarkUnchanged;
procedure OverrideBy(const ADefinition: IFDStanDefinition; AAll: Boolean);
function ParseString(const AStr: String; AKeywords: TStrings = nil): String; overload;
function ParseString(const AStr: String; AKeywords: TStrings; const AFmt: TFDParseFmtSettings): String; overload;
function BuildString(AKeywords: TStrings = nil): String; overload;
function BuildString(AKeywords: TStrings; const AFmt: TFDParseFmtSettings): String; overload;
function HasValue(const AName: String): Boolean; overload;
function HasValue(const AName: String; var ALevel: Integer): Boolean; overload;
function OwnValue(const AName: String): Boolean;
function IsSpecified(const AName: String): Boolean;
procedure ToggleUpdates(APassCode: LongWord; ADisableDelete, ADisableModify: Boolean);
// other
procedure Normalize; virtual;
procedure ParamsChanged(Sender: TObject);
procedure ReadFrom(AReader: TCustomIniFile);
procedure WriteTo(AWriter: TCustomIniFile; AIfModified: Boolean = True);
public
constructor Create(ACollection: TCollection); override;
constructor CreateTemporary;
destructor Destroy; override;
{$IFNDEF AUTOREFCOUNT}
procedure AfterConstruction; override;
class function NewInstance: TObject; override;
{$ENDIF}
property OriginalName: String read FOriginalName;
property DefinitionList: TFDDefinitions read GetDefinitionList;
end;
TFDDefinitionTemporaryFactory = class(TFDMultyInstanceFactory)
protected
function CreateObject(const AProvider: String): TObject; override;
public
constructor Create;
end;
TFDDefinitionsState = (dsNotLoaded, dsLoading, dsLoaded);
TFDDefinitions = class (TFDObject, IFDStanDefinitions)
private
FAutoLoad: Boolean;
FState: TFDDefinitionsState;
FStorage: IFDStanDefinitionStorage;
FList: TCollection;
FLock: TMultiReadExclusiveWriteSynchronizer;
FBeforeLoad,
FAfterLoad: TNotifyEvent;
FName: String;
procedure InternalDelete(ADefinition: TFDDefinition);
function InternalAdd: TFDDefinition;
function InternalLoad(ARefresh: Boolean): Boolean;
procedure CheckLoaded;
function InternalFindDefinition(const AName: String;
AExclude: TFDDefinition): TFDDefinition;
function BuildUniqueName(const AName: String; AItem: TFDDefinition): String;
function IsUniqueName(const AName: String; AItem: TFDDefinition): Boolean;
protected
// IFDStanDefinitions
function GetCount: Integer;
function GetItems(AIndex: Integer): IFDStanDefinition;
function GetAutoLoad: Boolean;
function GetStorage: IFDStanDefinitionStorage;
function GetLoaded: Boolean;
function GetBeforeLoad: TNotifyEvent;
function GetAfterLoad: TNotifyEvent;
function GetUpdatable: Boolean;
function GetName: String;
procedure SetAutoLoad(AValue: Boolean);
procedure SetBeforeLoad(AValue: TNotifyEvent);
procedure SetAfterLoad(AValue: TNotifyEvent);
procedure SetName(const AValue: String);
function Add: IFDStanDefinition;
function AddTemporary: IFDStanDefinition;
function FindDefinition(const AName: String): IFDStanDefinition;
function DefinitionByName(const AName: String): IFDStanDefinition;
procedure Cancel;
procedure Save(AIfModified: Boolean = True);
function Load: Boolean;
function Refresh: Boolean;
procedure Clear;
procedure BeginRead;
procedure EndRead;
procedure BeginWrite;
procedure EndWrite;
// other
function CreateIniFile: TCustomIniFile;
function GetItemClass: TFDDefinitionClass; virtual;
public
procedure Initialize; override;
destructor Destroy; override;
end;
TFDConnectionDef = class (TFDDefinition, IFDStanConnectionDef)
private
FPrevDriverID: String;
procedure UpdateParamsObj(const ANewDriverID: String);
protected
// IFDStanConnectionDef
function GetConnectionDefParams: TFDConnectionDefParams;
procedure SetConnectionDefParams(AValue: TFDConnectionDefParams);
procedure WriteOptions(AFormatOptions: TObject; AUpdateOptions: TObject;
AFetchOptions: TObject; AResourceOptions: TObject);
procedure ReadOptions(AFormatOptions: TObject; AUpdateOptions: TObject;
AFetchOptions: TObject; AResourceOptions: TObject);
// IFDStanDefinition
procedure MarkPersistent; override;
// TFDDefinition
procedure Normalize; override;
end;
TFDConnectionDefTemporaryFactory = class(TFDMultyInstanceFactory)
protected
function CreateObject(const AProvider: String): TObject; override;
public
constructor Create;
end;
TFDConnectionDefs = class (TFDDefinitions, IFDStanConnectionDefs)
protected
// IFDStanConnectionDefs
function GetConnectionDefs(AIndex: Integer): IFDStanConnectionDef;
function AddConnectionDef: IFDStanConnectionDef;
function FindConnectionDef(const AName: String): IFDStanConnectionDef;
function ConnectionDefByName(const AName: String): IFDStanConnectionDef;
// other
function GetItemClass: TFDDefinitionClass; override;
public
procedure Initialize; override;
end;
TFDOptsComponent = class(TFDComponent)
private
FFetchOptions: TFDFetchOptions;
FFormatOptions: TFDFormatOptions;
FUpdateOptions: TFDUpdateOptions;
FResourceOptions: TFDResourceOptions;
published
property FetchOptions: TFDFetchOptions read FFetchOptions write FFetchOptions;
property FormatOptions: TFDFormatOptions read FFormatOptions write FFormatOptions;
property UpdateOptions: TFDUpdateOptions read FUpdateOptions write FUpdateOptions;
property ResourceOptions: TFDResourceOptions read FResourceOptions write FResourceOptions;
end;
{-------------------------------------------------------------------------------}
{ TFDCustomDefinitionStorage }
{-------------------------------------------------------------------------------}
function TFDCustomDefinitionStorage.GetDefaultFileName: String;
begin
Result := FDefaultFileName;
end;
{-------------------------------------------------------------------------------}
function TFDCustomDefinitionStorage.GetFileName: String;
begin
Result := FFileName;
end;
{-------------------------------------------------------------------------------}
function TFDCustomDefinitionStorage.GetGlobalFileName: String;
begin
Result := FGlobalFileName;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomDefinitionStorage.SetDefaultFileName(const AValue: String);
begin
FDefaultFileName := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomDefinitionStorage.SetFileName(const AValue: String);
begin
FFileName := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDCustomDefinitionStorage.SetGlobalFileName(const AValue: String);
begin
FGlobalFileName := AValue;
end;
{-------------------------------------------------------------------------------}
{ TFDFileDefinitionStorage }
{-------------------------------------------------------------------------------}
function TFDFileDefinitionStorage.ActualFileName: String;
begin
Result := FDGetBestPath(GetFileName, GetGlobalFileName, GetDefaultFileName);
end;
{-------------------------------------------------------------------------------}
function TFDFileDefinitionStorage.CreateIniFile: TCustomIniFile;
var
oIni: TMemIniFile;
begin
oIni := TMemIniFile.Create(ActualFileName);
oIni.AutoSave := True;
if (oIni.Encoding = nil) or (oIni.Encoding = TEncoding.Default) then
oIni.Encoding := TEncoding.UTF8;
Result := oIni;
end;
{-------------------------------------------------------------------------------}
{- TFDDefinitionCollection -}
{-------------------------------------------------------------------------------}
type
TFDDefinitionCollection = class(TCollection)
private
[weak] FDefinitionList: TFDDefinitions;
public
constructor Create(AList: TFDDefinitions;
AItemClass: TFDDefinitionClass);
end;
{-------------------------------------------------------------------------------}
constructor TFDDefinitionCollection.Create(AList: TFDDefinitions;
AItemClass: TFDDefinitionClass);
begin
inherited Create(AItemClass);
FDefinitionList := AList;
end;
{-------------------------------------------------------------------------------}
{- TFDDefinition -}
{-------------------------------------------------------------------------------}
constructor TFDDefinition.Create(ACollection: TCollection);
begin
inherited Create(ACollection);
FParams := TFDConnectionDefParams.Create(Self);
FParams.OnChange := ParamsChanged;
FParams.OnChanging := ParamsChanging;
Clear;
end;
{-------------------------------------------------------------------------------}
constructor TFDDefinition.CreateTemporary;
begin
Create(nil);
FParams.Clear;
FStyle := atTemporary;
Include(FFlags, dfRefManaged);
end;
{-------------------------------------------------------------------------------}
destructor TFDDefinition.Destroy;
begin
CheckRO(dfDeleteDisabled);
FParentDefinition := nil;
FDFreeAndNil(FParams);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
{$IFNDEF AUTOREFCOUNT}
procedure TFDDefinition.AfterConstruction;
begin
AtomicDecrement(FRefCount);
end;
{-------------------------------------------------------------------------------}
class function TFDDefinition.NewInstance: TObject;
begin
Result := inherited NewInstance;
TFDDefinition(Result).FRefCount := 1;
end;
{$ENDIF}
{-------------------------------------------------------------------------------}
function TFDDefinition._AddRef: Integer;
begin
{$IFDEF AUTOREFCOUNT}
Result := __ObjAddRef;
{$ELSE}
Result := AtomicIncrement(FRefCount);
{$ENDIF}
end;
{-------------------------------------------------------------------------------}
function TFDDefinition._Release: Integer;
begin
{$IFDEF AUTOREFCOUNT}
Result := __ObjRelease;
{$ELSE}
Result := AtomicDecrement(FRefCount);
if (Result = 0) and (dfRefManaged in FFlags) then
Destroy;
{$ENDIF}
end;
{-------------------------------------------------------------------------------}
function TFDDefinition.QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
begin
if GetInterface(IID, Obj) then
Result := 0
else
Result := E_NOINTERFACE;
end;
{-------------------------------------------------------------------------------}
function TFDDefinition.GetDefinitionList: TFDDefinitions;
begin
if Collection <> nil then
Result := TFDDefinitionCollection(Collection).FDefinitionList
else
Result := nil;
end;
{-------------------------------------------------------------------------------}
procedure TFDDefinition.InternalSetParentDefinition(const AValue: IFDStanDefinition);
begin
if (AValue <> nil) and (AValue = Self as IFDStanDefinition) then
FDException(Self, [S_FD_LStan, S_FD_LStan_PDef], er_FD_DefCircular, [GetName]);
if FParentDefinition <> AValue then begin
FParentDefinition := AValue;
Normalize;
end;
Exclude(FFlags, dfParentMaybeChanged);
end;
{-------------------------------------------------------------------------------}
procedure TFDDefinition.SetParentDefinition(const AValue: IFDStanDefinition);
begin
InternalSetParentDefinition(AValue);
if AValue = nil then
Include(FFlags, dfParentMaybeChanged);
end;
{-------------------------------------------------------------------------------}
procedure TFDDefinition.UpdateParentDefinition;
var
s: String;
begin
if (dfParentMaybeChanged in FFlags) and (GetDefinitionList <> nil) then begin
Exclude(FFlags, dfParentMaybeChanged);
s := GetAsString(S_FD_DefinitionParam_Common_Parent);
if s = '' then
s := GetAsString(S_FD_DefinitionParam_Common_ConnectionDef);
if s <> '' then
InternalSetParentDefinition(GetDefinitionList.DefinitionByName(s));
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDDefinition.Normalize;
var
i, j: Integer;
sName: String;
begin
if FParentDefinition <> nil then begin
FParams.BeginUpdate;
try
i := FParams.Count - 1;
while i >= 0 do begin
sName := FParams.KeyNames[i];
if sName <> '' then begin
j := FParams.IndexOfName(sName);
if (j >= 0) and (j < i) then begin
FParams.Delete(j);
Dec(i);
end;
if AnsiCompareText(FParentDefinition.GetAsString(sName), FParams.Values[sName]) = 0 then
FParams.Delete(i);
end;
Dec(i);
end;
finally
FParams.EndUpdate;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDDefinition.OverrideBy(const ADefinition: IFDStanDefinition; AAll: Boolean);
var
i: Integer;
sName, sValue: String;
begin
CheckRO(dfModifyDisabled);
if ADefinition <> nil then
for i := 0 to ADefinition.Params.Count - 1 do begin
sName := ADefinition.Params.KeyNames[i];
sValue := ADefinition.Params.ValueFromIndex[i];
if AAll or (sValue <> '') then
SetAsString(sName, sValue);
end;
end;
{-------------------------------------------------------------------------------}
function TFDDefinition.ParseString(const AStr: String; AKeywords: TStrings): String;
begin
Result := ParseString(AStr, AKeywords, GParseFmtSettings);
end;
{-------------------------------------------------------------------------------}
function TFDDefinition.ParseString(const AStr: String; AKeywords: TStrings;
const AFmt: TFDParseFmtSettings): String;
var
i, j: Integer;
sParam, sValue, sId, sODBCId: String;
lFound: Boolean;
begin
i := 1;
Result := '';
while i <= Length(AStr) do begin
sParam := FDExtractFieldName(AStr, i, AFmt);
j := Pos('=', sParam);
if j <> 0 then begin
sId := Copy(sParam, 1, j - 1);
sValue := Copy(sParam, j + 1, Length(sParam));
end
else begin
sId := S_FD_ConnParam_Common_Database;
sValue := sParam;
end;
if (AKeywords <> nil) and (AKeywords.Count > 0) then begin
lFound := False;
for j := 0 to AKeywords.Count - 1 do begin
sODBCId := AKeywords.ValueFromIndex[j];
if (sODBCId <> '') and (sODBCId[Length(sODBCId)] = '*') then
sODBCId:= Copy(sODBCId, 1, Length(sODBCId) - 1);
if {$IFDEF FireDAC_NOLOCALE_META} CompareText {$ELSE} AnsiCompareText {$ENDIF}
(sODBCId, sId) = 0 then begin
sId := AKeywords.KeyNames[j];
lFound := True;
end
else if {$IFDEF FireDAC_NOLOCALE_META} CompareText {$ELSE} AnsiCompareText {$ENDIF}
(AKeywords[j], sId) = 0 then
lFound := True;
if lFound then
Break;
end;
end
else
lFound := True;
if sId <> '' then
if lFound then begin
if (sValue <> '') and (
(sValue[1] = AFmt.FQuote) and (sValue[Length(sValue)] = AFmt.FQuote) or
(sValue[1] = AFmt.FQuote1) and (sValue[Length(sValue)] = AFmt.FQuote2)
) then
sValue := Copy(sValue, 2, Length(sValue) - 2);
SetAsString(sId, sValue);
end
else begin
if Result <> '' then
Result := Result + AFmt.FDelimiter;
Result := Result + sParam;
end;
end;
Normalize;
end;
{-------------------------------------------------------------------------------}
function TFDDefinition.BuildString(AKeywords: TStrings): String;
begin
Result := BuildString(AKeywords, GParseFmtSettings);
end;
{-------------------------------------------------------------------------------}
type
TFDKwdValue = class(TObject)
private
FId, FVal: String;
FKwdPos: Integer;
public
constructor Create(const AId, AVal: String; AKwdPos: Integer);
end;
constructor TFDKwdValue.Create(const AId, AVal: String; AKwdPos: Integer);
begin
inherited Create;
FId := AId;
FVal := AVal;
FKwdPos := AKwdPos;
end;
function SortByKwdPos(AList: TStringList; AIndex1, AIndex2: Integer): Integer;
begin
Result := TFDKwdValue(AList.Objects[AIndex1]).FKwdPos -
TFDKwdValue(AList.Objects[AIndex2]).FKwdPos;
end;
function TFDDefinition.BuildString(AKeywords: TStrings; const AFmt: TFDParseFmtSettings): String;
var
i, j, iParamsProcessed: Integer;
sId, sVal: String;
oKeywordValues: TFDStringList;
oDef: IFDStanDefinition;
oKwdValue: TFDKwdValue;
procedure AddKwdValue(AKwdPos: Integer; const AID: String);
begin
if (sVal <> '') and (AID <> '') and (oKeywordValues.IndexOf(AID) = -1) then
oKeywordValues.AddObject(AID, TFDKwdValue.Create(AID, sVal, AKwdPos));
end;
function AddParam(const AStr, AId, AValue: String): String;
var
lSpecialSymbol: Boolean;
j: Integer;
sId: String;
begin
lSpecialSymbol := False;
sId := AId;
if (sId <> '') and (sId[Length(sId)] = '*') then
sId := Copy(sId, 1, Length(sId) - 1)
else if not ((AValue[1] = AFmt.FQuote1) and (AValue[Length(AValue)] = AFmt.FQuote2) or
(AValue[1] = AFmt.FQuote) and (AValue[Length(AValue)] = AFmt.FQuote)) then
for j := 1 to Length(AValue) do
case AValue[j] of
'[', ']', '{', '}', '(', ')', ',', ';', '?', '*', '=', '!', '@':
begin
lSpecialSymbol := True;
Break;
end;
end;
if lSpecialSymbol then
Result := Format('%s%s=%s%s%s%s', [AStr, sId, AFmt.FQuote1, AValue,
AFmt.FQuote2, AFmt.FDelimiter])
else
Result := Format('%s%s=%s%s', [AStr, sId, AValue, AFmt.FDelimiter]);
end;
begin
oKeywordValues := TFDStringList.Create(dupIgnore, True, False);
iParamsProcessed := 0;
try
oDef := Self as IFDStanDefinition;
while oDef <> nil do begin
for i := 0 to oDef.Params.Count - 1 do begin
sId := oDef.Params.KeyNames[i];
sVal := FDExpandStr(oDef.Params.ValueFromIndex[i]);
Inc(iParamsProcessed);
if (sVal <> '') and (AKeywords <> nil) and (AKeywords.Count > 0) then
for j := 0 to AKeywords.Count - 1 do begin
if {$IFDEF FireDAC_NOLOCALE_META} CompareText {$ELSE} AnsiCompareText {$ENDIF}
(AKeywords[j], sId) = 0 then
AddKwdValue(j, sId)
else if {$IFDEF FireDAC_NOLOCALE_META} CompareText {$ELSE} AnsiCompareText {$ENDIF}
(AKeywords.KeyNames[j], sId) = 0 then
AddKwdValue(j, AKeywords.ValueFromIndex[j]);
end
else
AddKwdValue(iParamsProcessed, sId);
end;
oDef := oDef.ParentDefinition;
end;
Result := '';
oKeywordValues.Sorted := False;
oKeywordValues.CustomSort(SortByKwdPos);
for i := 0 to oKeywordValues.Count - 1 do begin
oKwdValue := TFDKwdValue(oKeywordValues.Objects[i]);
Result := AddParam(Result, oKwdValue.FId, oKwdValue.FVal);
FDFree(oKwdValue);
end;
if (Result <> '') and (Result[Length(Result)] = AFmt.FDelimiter) then
SetLength(Result, Length(Result) - 1);
finally
FDFree(oKeywordValues);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDDefinition.CheckRO(AFlag: TFDDefinitionFlag);
var
s: String;
begin
if (FPassCode <> 0) and (AFlag in FFlags) then begin
if AFlag = dfModifyDisabled then
s := 'change'
else
s := 'delete';
FDException(Self, [S_FD_LStan, S_FD_LStan_PDef], er_FD_DefRO, [s, GetName]);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDDefinition.ParamsChanging(Sender: TObject);
begin
CheckRO(dfModifyDisabled);
FPrevName := GetName;
if Assigned(FOnChanging) then
FOnChanging(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDDefinition.ParamsChanged(Sender: TObject);
var
sNewName: String;
begin
if FState = asLoaded then
FState := asModified;
Include(FFlags, dfParentMaybeChanged);
if (Collection <> nil) and (FPrevName <> '') then
try
sNewName := GetName;
if (FPrevName <> sNewName) and not DefinitionList.IsUniqueName(sNewName, Self) then begin
SetName(FPrevName);
FDException(Self, [S_FD_LStan, S_FD_LStan_PDef], er_FD_DefDupName, [sNewName]);
end;
finally
FPrevName := '';
end;
if Assigned(FOnChanged) then
FOnChanged(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDDefinition.Clear;
begin
CheckRO(dfModifyDisabled);
FParams.Clear;
FOriginalName := '';
FPrevName := '';
if Collection <> nil then
SetName(DefinitionList.BuildUniqueName(S_FD_Unnamed, Self))
else
SetName(S_FD_Unnamed);
if FState <> asLoading then
FState := asAdded;
if FStyle <> atTemporary then begin
FStyle := atPrivate;
Exclude(FFlags, dfRefManaged);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDDefinition.Apply;
var
oIni: TCustomIniFile;
begin
if (FStyle = atPersistent) and (FState <> asLoaded) then begin
oIni := DefinitionList.CreateIniFile;
try
WriteTo(oIni, True);
finally
FDFree(oIni);
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDDefinition.Cancel;
var
oIni: TCustomIniFile;
begin
CheckRO(dfModifyDisabled);
if (FStyle = atPrivate) or
(FStyle = atPersistent) and (FState = asAdded) then begin
DefinitionList.InternalDelete(Self);
Exit;
end
else if (FStyle = atPersistent) and (FState <> asLoaded) then begin
SetName(FOriginalName);
oIni := DefinitionList.CreateIniFile;
try
if oIni.SectionExists(FOriginalName) then
ReadFrom(oIni);
finally
FDFree(oIni);
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDDefinition.Delete;
begin
CheckRO(dfDeleteDisabled);
if (FStyle = atPrivate) or
(FStyle = atPersistent) and (FState = asAdded) then
Cancel
else
FState := asDeleted;
end;
{-------------------------------------------------------------------------------}
procedure TFDDefinition.MarkPersistent;
begin
if (DefinitionList = nil) or (GetName = '') then
FDException(Self, [S_FD_LStan, S_FD_LStan_PDef], er_FD_DefCantMakePers, []);
FStyle := atPersistent;
Exclude(FFlags, dfRefManaged);
end;
{-------------------------------------------------------------------------------}
procedure TFDDefinition.MarkUnchanged;
begin
if FStyle = atPersistent then
case FState of
asAdded,
asModified:
begin
FOriginalName := GetName;
FState := asLoaded;
end;
asDeleted:
DefinitionList.InternalDelete(Self);
end;
end;
{-------------------------------------------------------------------------------}
function TFDDefinition.HasValue(const AName: String): Boolean;
var
iLevel: Integer;
begin
iLevel := 0;
Result := HasValue(AName, iLevel);
end;
{-------------------------------------------------------------------------------}
function TFDDefinition.HasValue(const AName: String; var ALevel: Integer): Boolean;
var
i: Integer;
s: String;
begin
Result := False;
i := FParams.IndexOfName(AName);
if i = -1 then begin
if GetParentDefinition <> nil then begin
Inc(ALevel);
Result := GetParentDefinition.HasValue(AName, ALevel);
end;
if not Result then
ALevel := $7FFFFFFF;
end
else begin
s := FParams.ValueFromIndex[i];
if (s <> '') and ((s[1] <= ' ') or (s[Length(s)] <= ' ')) then
s := Trim(s);
Result := (s <> '');
end;
end;
{-------------------------------------------------------------------------------}
function TFDDefinition.OwnValue(const AName: String): Boolean;
begin
Result := (FParams.IndexOfName(AName) <> -1);
end;
{-------------------------------------------------------------------------------}
function TFDDefinition.IsSpecified(const AName: String): Boolean;
var
i, iLevel: Integer;
begin
i := FParams.IndexOfName(AName);
if i > -1 then
Result := True
else if GetParentDefinition <> nil then begin
iLevel := 1;
Result := GetParentDefinition.HasValue(AName, iLevel);
end
else
Result := False;
end;
{-------------------------------------------------------------------------------}
procedure TFDDefinition.ToggleUpdates(APassCode: LongWord; ADisableDelete, ADisableModify: Boolean);
procedure SetFlags;
begin
if ADisableDelete then
Include(FFlags, dfDeleteDisabled)
else
Exclude(FFlags, dfDeleteDisabled);
if ADisableModify then
Include(FFlags, dfModifyDisabled)
else
Exclude(FFlags, dfModifyDisabled);
end;
begin
if FPassCode = 0 then begin
if ADisableDelete or ADisableModify then begin
FPassCode := APassCode;
SetFlags;
end;
end
else if FPassCode <> APassCode then
FDException(Self, [S_FD_LStan, S_FD_LStan_PDef], er_FD_DefRO, ['unprotect', GetName])
else begin
SetFlags;
if not ADisableDelete and not ADisableModify then
FPassCode := 0;
end;
end;
{-------------------------------------------------------------------------------}
function TFDDefinition.GetUpdatable: Boolean;
begin
Result := FPassCode = 0;
end;
{-------------------------------------------------------------------------------}
function TFDDefinition.GetAsString(const AName: String): String;
var
i: Integer;
begin
Result := '';
i := FParams.IndexOfName(AName);
if i = -1 then begin
if GetParentDefinition <> nil then
Result := GetParentDefinition.GetAsString(AName);
end
else begin
Result := FParams.ValueFromIndex[i];
if (Result <> '') and ((Result[1] <= ' ') or (Result[Length(Result)] <= ' ')) then
Result := Trim(Result);
end;
end;
{-------------------------------------------------------------------------------}
function TFDDefinition.GetAsXString(const AName: String): String;
var
sName: String;
iLvlSpc, iLvlGen: Integer;
lSpc, lGen: Boolean;
begin
sName := AName;
{$IFDEF MSWINDOWS}
{$IFDEF FireDAC_32}
sName := sName + S_FD_Win32;
{$ENDIF}
{$IFDEF FireDAC_64}
sName := sName + S_FD_Win64;
{$ENDIF}
{$ENDIF}
{$IFDEF MACOS}
{$IFDEF FireDAC_32}
sName := sName + S_FD_OSX32;
{$ENDIF}
{$IFDEF FireDAC_64}
sName := sName + S_FD_OSX64;
{$ENDIF}
{$ENDIF}
{$IFDEF LINUX}
{$IFDEF FireDAC_32}
sName := sName + S_FD_UIX32;
{$ENDIF}
{$IFDEF FireDAC_64}
sName := sName + S_FD_UIX64;
{$ENDIF}
{$ENDIF}
{$IFDEF ANDROID}
sName := sName + S_FD_ANDROID;
{$ENDIF}
iLvlSpc := 0;
iLvlGen := 0;
lSpc := HasValue(sName, iLvlSpc);
lGen := HasValue(AName, iLvlGen);
if lSpc or lGen then
if iLvlSpc < iLvlGen then
Result := GetAsString(sName)
else
Result := GetAsString(AName);
end;
{-------------------------------------------------------------------------------}
function TFDDefinition.GetAsBoolean(const AName: String): LongBool;
var
s: String;
begin
s := GetAsString(AName);
Result := (Length(s) > 0) and (
(s[1] = 'Y') or (s[1] = 'y') or (s[1] = 'T') or (s[1] = 't'));
end;
{-------------------------------------------------------------------------------}
function TFDDefinition.GetAsInteger(const AName: String): LongInt;
begin
Result := StrToIntDef(GetAsString(AName), 0);
end;
{-------------------------------------------------------------------------------}
procedure TFDDefinition.SetAsString(const AName, AValue: String);
var
sVal: String;
i: Integer;
begin
CheckRO(dfModifyDisabled);
sVal := Trim(AValue);
if GetAsString(AName) <> sVal then begin
FParams.BeginUpdate;
try
if GetParentDefinition <> nil then
if AnsiCompareText(GetParentDefinition.GetAsString(AName), sVal) = 0 then begin
i := FParams.IndexOfName(AName);
if i <> -1 then
FParams.Delete(i);
end
else
FParams.Values[AName] := sVal
else
FParams.Values[AName] := sVal;
finally
FParams.EndUpdate;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDDefinition.SetAsBoolean(const AName: String; const AValue: LongBool);
begin
if not HasValue(AName) or (GetAsBoolean(AName) <> AValue) then
if AValue then
SetAsString(AName, S_FD_True)
else
SetAsString(AName, S_FD_False);
end;
{-------------------------------------------------------------------------------}
procedure TFDDefinition.SetAsYesNo(const AName: String; const AValue: LongBool);
begin
if not HasValue(AName) or (GetAsBoolean(AName) <> AValue) then
if AValue then
SetAsString(AName, S_FD_Yes)
else
SetAsString(AName, S_FD_No);
end;
{-------------------------------------------------------------------------------}
procedure TFDDefinition.SetAsInteger(const AName: String; const AValue: LongInt);
begin
if not HasValue(AName) or (GetAsInteger(AName) <> AValue) then
SetAsString(AName, IntToStr(AValue));
end;
{-------------------------------------------------------------------------------}
function TFDDefinition.GetName: String;
begin
Result := GetAsString(S_FD_DefinitionParam_Common_Name);
end;
{-------------------------------------------------------------------------------}
procedure TFDDefinition.SetName(const AValue: string);
begin
SetAsString(S_FD_DefinitionParam_Common_Name, AValue);
end;
{-------------------------------------------------------------------------------}
function TFDDefinition.GetParams: TStrings;
begin
Result := FParams;
end;
{-------------------------------------------------------------------------------}
procedure TFDDefinition.SetParams(const AValue: TStrings);
begin
CheckRO(dfModifyDisabled);
FParams.SetStrings(AValue);
Normalize;
end;
{-------------------------------------------------------------------------------}
function TFDDefinition.GetParentDefinition: IFDStanDefinition;
begin
UpdateParentDefinition;
Result := FParentDefinition;
end;
{-------------------------------------------------------------------------------}
function TFDDefinition.GetState: TFDDefinitionState;
begin
Result := FState;
end;
{-------------------------------------------------------------------------------}
function TFDDefinition.GetStyle: TFDDefinitionStyle;
begin
Result := FStyle;
end;
{-------------------------------------------------------------------------------}
function TFDDefinition.GetOnChanged: TNotifyEvent;
begin
Result := FOnChanged;
end;
{-------------------------------------------------------------------------------}
function TFDDefinition.GetOnChanging: TNotifyEvent;
begin
Result := FOnChanging;
end;
{-------------------------------------------------------------------------------}
procedure TFDDefinition.SetOnChanged(AValue: TNotifyEvent);
begin
FOnChanged := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDDefinition.SetOnChanging(AValue: TNotifyEvent);
begin
FOnChanging := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDDefinition.ReadFrom(AReader: TCustomIniFile);
var
sName: String;
lLoaded: Boolean;
begin
CheckRO(dfModifyDisabled);
sName := GetName;
FState := asLoading;
lLoaded := False;
try
Clear;
if AReader.SectionExists(sName) then
try
AReader.ReadSectionValues(sName, FParams);
Normalize;
FStyle := atPersistent;
Exclude(FFlags, dfRefManaged);
FOriginalName := sName;
lLoaded := True;
except
Clear;
raise;
end;
finally
SetName(sName);
if lLoaded then
FState := asLoaded
else
FState := asAdded;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDDefinition.WriteTo(AWriter: TCustomIniFile; AIfModified: Boolean = True);
var
sName: String;
sOrigName: String;
procedure DeleteOldSection;
begin
if (sOrigName <> '') and AWriter.SectionExists(sOrigName) then
AWriter.EraseSection(sOrigName);
end;
procedure WriteNewSection;
var
i: Integer;
begin
for i := 0 to FParams.Count - 1 do
if CompareText(FParams.KeyNames[i], S_FD_DefinitionParam_Common_Name) <> 0 then
AWriter.WriteString(sName, FParams.KeyNames[i], FParams.ValueFromIndex[i]);
end;
begin
if FStyle = atPersistent then begin
sName := GetName;
sOrigName := FOriginalName;
case FState of
asLoaded:
if not AIfModified then
WriteNewSection;
asModified:
begin
DeleteOldSection;
WriteNewSection;
FState := asLoaded;
end;
asDeleted:
begin
DeleteOldSection;
DefinitionList.InternalDelete(Self);
end;
asAdded:
begin
WriteNewSection;
FState := asLoaded;
end;
end;
FOriginalName := sName;
end;
end;
{-------------------------------------------------------------------------------}
{$IFDEF FireDAC_MONITOR}
procedure TFDDefinition.BaseTrace(const AMonitor: IFDMoniClient);
var
i: Integer;
sName, s: String;
begin
if GetParentDefinition <> nil then
GetParentDefinition.BaseTrace(AMonitor);
for i := 0 to FParams.Count - 1 do begin
sName := FParams.KeyNames[i];
if Pos(UpperCase(S_FD_ConnParam_Common_Password), UpperCase(sName)) <> 0 then
s := sName + '=*****'
else
s := FParams[i];
AMonitor.Notify(ekConnService, esProgress, Self, s, []);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDDefinition.Trace(const AMonitor: IFDMoniClient);
begin
if (AMonitor <> nil) and AMonitor.Tracing then begin
AMonitor.Notify(ekConnService, esStart, Self, 'Definition', ['Name', GetName]);
BaseTrace(AMonitor);
AMonitor.Notify(ekConnService, esEnd, Self, 'Definition', ['Name', GetName]);
end;
end;
{$ENDIF}
{-------------------------------------------------------------------------------}
{ TFDDefinitionTemporaryFactory }
{-------------------------------------------------------------------------------}
constructor TFDDefinitionTemporaryFactory.Create;
begin
inherited Create(nil, IFDStanDefinition);
end;
{-------------------------------------------------------------------------------}
function TFDDefinitionTemporaryFactory.CreateObject(const AProvider: String): TObject;
begin
Result := TFDDefinition.CreateTemporary;
end;
{-------------------------------------------------------------------------------}
{- TFDDefinitions -}
{-------------------------------------------------------------------------------}
procedure TFDDefinitions.Initialize;
begin
inherited Initialize;
FAutoLoad := True;
FState := dsNotLoaded;
FDCreateInterface(IFDStanDefinitionStorage, FStorage);
FList := TFDDefinitionCollection.Create(Self, GetItemClass);
FLock := TMultiReadExclusiveWriteSynchronizer.Create;
end;
{-------------------------------------------------------------------------------}
destructor TFDDefinitions.Destroy;
begin
FState := dsNotLoaded;
FStorage := nil;
FDFreeAndNil(FList);
FDFreeAndNil(FLock);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
function TFDDefinitions.GetItemClass: TFDDefinitionClass;
begin
Result := TFDDefinition;
end;
{-------------------------------------------------------------------------------}
function TFDDefinitions.CreateIniFile: TCustomIniFile;
begin
Result := FStorage.CreateIniFile;
end;
{-------------------------------------------------------------------------------}
procedure TFDDefinitions.CheckLoaded;
begin
if (FState = dsNotLoaded) and FAutoLoad then
Load;
end;
{-------------------------------------------------------------------------------}
function TFDDefinitions.GetLoaded: Boolean;
begin
Result := (FState = dsLoaded);
end;
{-------------------------------------------------------------------------------}
function TFDDefinitions.GetAutoLoad: Boolean;
begin
Result := FAutoLoad;
end;
{-------------------------------------------------------------------------------}
procedure TFDDefinitions.SetAutoLoad(AValue: Boolean);
begin
FAutoLoad := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDDefinitions.GetStorage: IFDStanDefinitionStorage;
begin
Result := FStorage;
end;
{-------------------------------------------------------------------------------}
function TFDDefinitions.GetAfterLoad: TNotifyEvent;
begin
Result := FAfterLoad;
end;
{-------------------------------------------------------------------------------}
function TFDDefinitions.GetBeforeLoad: TNotifyEvent;
begin
Result := FBeforeLoad;
end;
{-------------------------------------------------------------------------------}
function TFDDefinitions.GetName: String;
begin
Result := FName;
end;
{-------------------------------------------------------------------------------}
procedure TFDDefinitions.SetAfterLoad(AValue: TNotifyEvent);
begin
FAfterLoad := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDDefinitions.SetBeforeLoad(AValue: TNotifyEvent);
begin
FBeforeLoad := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDDefinitions.SetName(const AValue: String);
begin
FName := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDDefinitions.InternalAdd: TFDDefinition;
begin
BeginWrite;
try
CheckLoaded;
Result := TFDDefinition(FList.Add);
finally
EndWrite;
end;
end;
{-------------------------------------------------------------------------------}
function TFDDefinitions.Add: IFDStanDefinition;
begin
Result := InternalAdd as IFDStanDefinition;
end;
{-------------------------------------------------------------------------------}
function TFDDefinitions.AddTemporary: IFDStanDefinition;
begin
Result := GetItemClass.CreateTemporary as IFDStanDefinition;
end;
{-------------------------------------------------------------------------------}
procedure TFDDefinitions.InternalDelete(ADefinition: TFDDefinition);
var
i: Integer;
oDef: IFDStanDefinition;
begin
BeginWrite;
try
oDef := ADefinition as IFDStanDefinition;
for i := 0 to FList.Count - 1 do
if TFDDefinition(FList.Items[i]).GetParentDefinition = oDef then
TFDDefinition(FList.Items[i]).SetParentDefinition(nil);
Include(ADefinition.FFlags, dfRefManaged);
ADefinition.Collection := nil;
if ADefinition.FRefCount = 0 then
FDFree(ADefinition);
finally
EndWrite;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDDefinitions.Cancel;
var
i: Integer;
begin
BeginWrite;
try
for i := FList.Count - 1 downto 0 do
TFDDefinition(FList.Items[i]).Cancel;
finally
EndWrite;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDDefinitions.Save(AIfModified: Boolean = True);
var
i: Integer;
oIni: TCustomIniFile;
begin
BeginWrite;
try
oIni := CreateIniFile;
try
if GetName <> '' then
oIni.WriteString(GetName, 'Encoding', 'UTF8');
for i := FList.Count - 1 downto 0 do
TFDDefinition(FList.Items[i]).WriteTo(oIni, AIfModified);
finally
FDFree(oIni);
end;
finally
EndWrite;
end;
end;
{-------------------------------------------------------------------------------}
function TFDDefinitions.InternalLoad(ARefresh: Boolean): Boolean;
var
oList: TFDStringList;
oIni: TCustomIniFile;
i, j: Integer;
oDef: TFDDefinition;
begin
BeginWrite;
try
if not ARefresh and (FState <> dsNotLoaded) then
FDException(Self, [S_FD_LStan, S_FD_LStan_PDef], er_FD_DefAlreadyLoaded, []);
FState := dsLoading;
Result := False;
try
if Assigned(FBeforeLoad) then
FBeforeLoad(Self);
oList := TFDStringList.Create;
try
oIni := CreateIniFile;
try
if FileExists(GetStorage.ActualFileName) then begin
Result := True;
oIni.ReadSections(oList);
oList.Sort;
for i := 0 to oList.Count - 1 do
if (GetName = '') or (CompareText(oList[i], GetName) <> 0) then begin
if ARefresh then begin
oDef := InternalFindDefinition(oList[i], nil);
if (oDef <> nil) and not oDef.GetUpdatable then
Continue;
end
else
oDef := nil;
if oDef = nil then begin
oDef := InternalAdd;
oDef.SetName(oList[i]);
end;
oDef.ReadFrom(oIni);
end;
if ARefresh then
for i := FList.Count - 1 downto 0 do begin
oDef := TFDDefinition(FList.Items[i]);
if not oList.Find(oDef.GetName, j) and oDef.GetUpdatable
{$IFNDEF AUTOREFCOUNT}
and (oDef.FRefCount = 0)
{$ENDIF}
then
FDFreeAndNil(oDef);
end;
end;
finally
FDFree(oIni);
end;
finally
FDFree(oList);
end;
finally
FState := dsLoaded;
if Assigned(FAfterLoad) then
FAfterLoad(Self);
end;
finally
EndWrite;
end;
end;
{-------------------------------------------------------------------------------}
function TFDDefinitions.Load: Boolean;
begin
Result := InternalLoad(False);
end;
{-------------------------------------------------------------------------------}
function TFDDefinitions.Refresh: Boolean;
begin
Result := InternalLoad(True);
end;
{-------------------------------------------------------------------------------}
procedure TFDDefinitions.Clear;
var
i: Integer;
begin
BeginWrite;
try
for i := 0 to FList.Count - 1 do
TFDDefinition(FList.Items[i]).FParentDefinition := nil;
FList.Clear;
FState := dsNotLoaded;
finally
EndWrite;
end;
end;
{-------------------------------------------------------------------------------}
function TFDDefinitions.InternalFindDefinition(const AName: String;
AExclude: TFDDefinition): TFDDefinition;
var
i: Integer;
oDef: TFDDefinition;
begin
Result := nil;
FLock.BeginRead;
try
CheckLoaded;
for i := 0 to FList.Count - 1 do begin
oDef := TFDDefinition(FList.Items[i]);
if (oDef <> AExclude) and (
{$IFDEF FireDAC_NOLOCALE_META} CompareText {$ELSE} AnsiCompareText {$ENDIF}
(oDef.GetName, AName) = 0) then begin
Result := oDef;
Break;
end;
end;
finally
FLock.EndRead;
end;
end;
{-------------------------------------------------------------------------------}
function TFDDefinitions.FindDefinition(const AName: String): IFDStanDefinition;
begin
Result := InternalFindDefinition(AName, nil) as IFDStanDefinition;
end;
{-------------------------------------------------------------------------------}
function TFDDefinitions.DefinitionByName(const AName: String): IFDStanDefinition;
begin
Result := FindDefinition(AName);
if Result = nil then
FDException(Self, [S_FD_LStan, S_FD_LStan_PDef], er_FD_DefNotExists,
[AName, FStorage.ActualFilename]);
end;
{-------------------------------------------------------------------------------}
function TFDDefinitions.BuildUniqueName(const AName: String; AItem: TFDDefinition): String;
var
i: Integer;
begin
Result := AName;
i := 0;
FLock.BeginRead;
try
while InternalFindDefinition(Result, AItem) <> nil do begin
Inc(i);
Result := AName + '_' + IntToStr(i);
end;
finally
FLock.EndRead;
end;
end;
{-------------------------------------------------------------------------------}
function TFDDefinitions.IsUniqueName(const AName: String; AItem: TFDDefinition): Boolean;
begin
Result := InternalFindDefinition(AName, AItem) = nil;
end;
{-------------------------------------------------------------------------------}
function TFDDefinitions.GetCount: Integer;
begin
FLock.BeginRead;
try
CheckLoaded;
Result := FList.Count;
finally
FLock.EndRead;
end;
end;
{-------------------------------------------------------------------------------}
function TFDDefinitions.GetItems(AIndex: Integer): IFDStanDefinition;
begin
FLock.BeginRead;
try
CheckLoaded;
Result := TFDDefinition(FList.Items[AIndex]) as IFDStanDefinition;
finally
FLock.EndRead;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDDefinitions.BeginRead;
begin
FLock.BeginRead;
end;
{-------------------------------------------------------------------------------}
procedure TFDDefinitions.EndRead;
begin
FLock.EndRead;
end;
{-------------------------------------------------------------------------------}
procedure TFDDefinitions.BeginWrite;
begin
FLock.BeginWrite;
end;
{-------------------------------------------------------------------------------}
procedure TFDDefinitions.EndWrite;
begin
FLock.EndWrite;
end;
{-------------------------------------------------------------------------------}
function TFDDefinitions.GetUpdatable: Boolean;
var
i: Integer;
begin
Result := True;
BeginRead;
try
for i := 0 to FList.Count - 1 do
if not TFDDefinition(FList.Items[i]).GetUpdatable then begin
Result := False;
Break;
end;
finally
EndRead;
end;
end;
{-------------------------------------------------------------------------------}
{- TFDConnectionDef -}
{-------------------------------------------------------------------------------}
procedure TFDConnectionDef.UpdateParamsObj(const ANewDriverID: String);
var
oParamsIntf: IFDStanConnectionDefParams;
oParams: TFDConnectionDefParams;
begin
oParams := nil;
if ANewDriverID <> '' then begin
FDCreateInterface(IFDStanConnectionDefParams, oParamsIntf, False, ANewDriverID);
if oParamsIntf <> nil then
oParams := oParamsIntf.CreateParams(Self) as TFDConnectionDefParams;
end;
if not ((oParams = nil) and (FParams.ClassType = TFDConnectionDefParams)) then begin
if oParams = nil then
oParams := TFDConnectionDefParams.Create(Self);
oParams.SetStrings(FParams);
oParams.OnChange := FParams.OnChange;
FParams.OnChange := nil;
while FParams.Updating do begin
oParams.BeginUpdate;
FParams.EndUpdate;
end;
oParams.OnChanging := FParams.OnChanging;
FDFreeAndNil(FParams);
FParams := oParams;
end;
FPrevDriverID := ANewDriverID;
end;
{-------------------------------------------------------------------------------}
function TFDConnectionDef.GetConnectionDefParams: TFDConnectionDefParams;
var
sNewDriverID: String;
begin
sNewDriverID := GetAsString(S_FD_ConnParam_Common_DriverID);
if CompareText(FPrevDriverID, sNewDriverID) <> 0 then
UpdateParamsObj(sNewDriverID);
Result := FParams;
end;
{-------------------------------------------------------------------------------}
procedure TFDConnectionDef.SetConnectionDefParams(AValue: TFDConnectionDefParams);
begin
FParams.SetStrings(AValue);
end;
{-------------------------------------------------------------------------------}
procedure TFDConnectionDef.MarkPersistent;
begin
if GetAsString(S_FD_ConnParam_Common_DriverID) = '' then
FDException(Self, [S_FD_LStan, S_FD_LStan_PDef], er_FD_DefCantMakePers, []);
inherited MarkPersistent;
end;
{-------------------------------------------------------------------------------}
procedure TFDConnectionDef.Normalize;
begin
inherited Normalize;
GetConnectionDefParams;
end;
{-------------------------------------------------------------------------------}
procedure TFDConnectionDef.ReadOptions(AFormatOptions: TObject;
AUpdateOptions: TObject; AFetchOptions: TObject; AResourceOptions: TObject);
var
oComp: TFDOptsComponent;
oMS: TMemoryStream;
oStr: TStringStream;
oRdr: TReader;
i: Integer;
s, sName: String;
oDef: IFDStanConnectionDef;
begin
s := 'object TFDOptsComponent' + C_FD_EOL;
oDef := Self as IFDStanConnectionDef;
while oDef <> nil do begin
for i := 0 to oDef.Params.Count - 1 do begin
sName := LowerCase(oDef.Params.KeyNames[i]);
if (Pos('fetchoptions.', sName) <> 0) or (Pos('formatoptions.', sName) <> 0) or
(Pos('updateoptions.', sName) <> 0) or (Pos('resourceoptions.', sName) <> 0) then
s := s + oDef.Params[i] + C_FD_EOL;
end;
oDef := oDef.ParentDefinition as IFDStanConnectionDef;
end;
s := s + 'end';
oComp := TFDOptsComponent.Create(nil);
try
oComp.FetchOptions := AFetchOptions as TFDFetchOptions;
oComp.UpdateOptions := AUpdateOptions as TFDUpdateOptions;
oComp.FormatOptions := AFormatOptions as TFDFormatOptions;
oComp.ResourceOptions := AResourceOptions as TFDResourceOptions;
oStr := TStringStream.Create(s);
try
oMS := TMemoryStream.Create;
oRdr := TReader.Create(oMS, 4096);
try
ObjectTextToBinary(oStr, oMS);
oMS.Position := 0;
oRdr.BeginReferences;
try
oRdr.ReadSignature;
oRdr.ReadComponent(oComp);
finally
oRdr.EndReferences;
end;
finally
FDFree(oRdr);
FDFree(oMS);
end;
finally
FDFree(oStr);
end;
finally
FDFree(oComp);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDConnectionDef.WriteOptions(AFormatOptions: TObject;
AUpdateOptions: TObject; AFetchOptions: TObject; AResourceOptions: TObject);
var
oComp: TFDOptsComponent;
oMS: TMemoryStream;
oStr: TStringStream;
i: Integer;
pCh, pStart, pEnd, pWS: PChar;
lValue, lCollection: Boolean;
s, sName: String;
begin
oComp := TFDOptsComponent.Create(nil);
try
oComp.FetchOptions := AFetchOptions as TFDFetchOptions;
oComp.UpdateOptions := AUpdateOptions as TFDUpdateOptions;
oComp.FormatOptions := AFormatOptions as TFDFormatOptions;
oComp.ResourceOptions := AResourceOptions as TFDResourceOptions;
oMS := TMemoryStream.Create;
try
oMS.WriteComponent(oComp);
oStr := TStringStream.Create('');
try
oMS.Position := 0;
ObjectBinaryToText(oMS, oStr);
s := oStr.DataString;
pCh := PChar(s);
while pCh^ <> #13 do
Inc(pCh);
pEnd := PChar(s) + Length(s) - 1;
for i := 1 to 2 do begin
while pEnd^ <> #13 do
Dec(pEnd);
if i <> 2 then
Dec(pEnd)
else
Inc(pEnd)
end;
lValue := False;
lCollection := False;
Inc(pCh, 2);
pStart := pCh;
while pCh <= pEnd do begin
if lCollection then begin
if pCh^ = '>' then
lCollection := False
else if pCh^ = #13 then begin
pCh^ := ' ';
(pCh + 1)^ := ' ';
end;
if pCh^ = ' ' then begin
pWS := pCh;
while pCh^ = ' ' do
Inc(pCh);
if pCh - pWS > 1 then begin
Move(pCh^, (pWS + 1)^, (pEnd - pCh + 1) * SizeOf(Char));
Dec(pEnd, pCh - pWS - 1);
Dec(pCh, pCh - pWS - 1);
end;
end
else
Inc(pCh);
end
else begin
if (pCh^ = ' ') and not lValue then begin
Move((pCh + 1)^, pCh^, (pEnd - pCh) * SizeOf(Char));
Dec(pEnd);
end
else begin
if pCh^ = '=' then
lValue := True
else if pCh^ = #10 then
lValue := False
else if pCh^ = '<' then
lCollection := True;
Inc(pCh);
end;
end;
end;
if pEnd - pStart - 1 > 0 then
SetString(s, pStart, pEnd - pStart - 1)
else
s := '';
i := 0;
while i < GetParams.Count do begin
sName := GetParams.KeyNames[i];
if (CompareText(sName, 'FetchOptions') = 0) or (CompareText(sName, 'FormatOptions') = 0) or
(CompareText(sName, 'UpdateOptions') = 0) or (CompareText(sName, 'ResourceOptions') = 0) then
GetParams.Delete(i)
else
Inc(i);
end;
if s <> '' then
GetParams.Text := GetParams.Text + s;
finally
FDFree(oStr);
end;
finally
FDFree(oMS);
end;
finally
FDFree(oComp);
end;
end;
{-------------------------------------------------------------------------------}
{ TFDConnectionDefTemporaryFactory }
{-------------------------------------------------------------------------------}
constructor TFDConnectionDefTemporaryFactory.Create;
begin
inherited Create(nil, IFDStanConnectionDef);
end;
{-------------------------------------------------------------------------------}
function TFDConnectionDefTemporaryFactory.CreateObject(const AProvider: String): TObject;
begin
Result := TFDConnectionDef.CreateTemporary;
end;
{-------------------------------------------------------------------------------}
{- TFDConnectionDefs -}
{-------------------------------------------------------------------------------}
procedure TFDConnectionDefs.Initialize;
begin
inherited Initialize;
SetName(S_FD_DefCfgFileName);
GetStorage.DefaultFileName := S_FD_DefCfgFileName;
GetStorage.GlobalFileName := FDLoadConnDefGlobalFileName;
end;
{-------------------------------------------------------------------------------}
function TFDConnectionDefs.GetItemClass: TFDDefinitionClass;
begin
Result := TFDConnectionDef;
end;
{-------------------------------------------------------------------------------}
function TFDConnectionDefs.AddConnectionDef: IFDStanConnectionDef;
begin
Result := inherited Add as IFDStanConnectionDef;
end;
{-------------------------------------------------------------------------------}
function TFDConnectionDefs.FindConnectionDef(const AName: String): IFDStanConnectionDef;
begin
Result := inherited FindDefinition(AName) as IFDStanConnectionDef;
end;
{-------------------------------------------------------------------------------}
function TFDConnectionDefs.ConnectionDefByName(const AName: String): IFDStanConnectionDef;
begin
Result := inherited DefinitionByName(AName) as IFDStanConnectionDef;
end;
{-------------------------------------------------------------------------------}
function TFDConnectionDefs.GetConnectionDefs(AIndex: Integer): IFDStanConnectionDef;
begin
Result := inherited GetItems(AIndex) as IFDStanConnectionDef;
end;
{-------------------------------------------------------------------------------}
procedure FDSaveConnDefGlobalFileName(const AName: String);
begin
FDWriteRegValue(S_FD_CfgValName, AName);
end;
{-------------------------------------------------------------------------------}
function FDLoadConnDefGlobalFileName: String;
begin
Result := FDReadRegValue(S_FD_CfgValName);
end;
{-------------------------------------------------------------------------------}
procedure FDSaveDriverDefGlobalFileName(const AName: String);
begin
FDWriteRegValue(S_FD_DrvValName, AName);
end;
{-------------------------------------------------------------------------------}
function FDLoadDriverDefGlobalFileName: String;
begin
Result := FDReadRegValue(S_FD_DrvValName);
end;
{-------------------------------------------------------------------------------}
var
oFact1,
oFact2,
oFact3,
oFact4,
oFact5: TFDFactory;
initialization
oFact1 := TFDMultyInstanceFactory.Create(TFDFileDefinitionStorage, IFDStanDefinitionStorage);
oFact2 := TFDDefinitionTemporaryFactory.Create;
oFact3 := TFDMultyInstanceFactory.Create(TFDDefinitions, IFDStanDefinitions);
oFact4 := TFDConnectionDefTemporaryFactory.Create;
oFact5 := TFDMultyInstanceFactory.Create(TFDConnectionDefs, IFDStanConnectionDefs);
finalization
FDReleaseFactory(oFact1);
FDReleaseFactory(oFact2);
FDReleaseFactory(oFact3);
FDReleaseFactory(oFact4);
FDReleaseFactory(oFact5);
end.
|
{
Binary Search
O(LgN)
Input:
X: Array of elements in ascending sorted order
L: 1
R: Number of elements
Z: Key to find
Output:
Return Value: Index of Z in X (-1 = Not Found)
Reference:
Creative, p121
By Ali
}
program
BinarySearch;
const
MaxN = 10000 + 2;
var
X: array [1 .. MaxN] of Integer;
function BSearch(L, R: Integer; Z: Integer): Integer;
var
Mid: Integer;
begin
while L < R do
begin
Mid := (L + R) div 2;
if Z > X[Mid] then L := Mid + 1
else
R := Mid;
end;
if X[L] = Z then
BSearch := L
else
BSearch := -1;
end;
begin
Writeln(BSearch(1, 3, 7682));
end.
|
{ **********************************************************************}
{ }
{ DeskMetrics - Application Example (Delphi) }
{ Copyright (c) 2010-2011 DeskMetrics Limited }
{ }
{ http://deskmetrics.com }
{ support@deskmetrics.com }
{ }
{ This code is provided under the DeskMetrics Modified BSD License }
{ A copy of this license has been distributed in a file called }
{ LICENSE with this source code. }
{ }
{ **********************************************************************}
unit frmMain;
interface
uses
Windows, SysUtils, Classes, Controls, Forms, StdCtrls, ExtCtrls, Dialogs,
jpeg, pngimage;
type
Tfrm_Main = class(TForm)
imgLogo: TImage;
lblDLLStatus: TLabel;
btnTrackAll: TButton;
pnlData: TPanel;
Bevel1: TBevel;
Bevel4: TBevel;
Bevel5: TBevel;
bvlLine: TBevel;
Label2: TLabel;
lblConfigProxy: TLabel;
lblTrackingCustomData: TLabel;
lblTrackingEvents: TLabel;
lblTrackingLog: TLabel;
lblZipCode: TLabel;
Label4: TLabel;
Bevel3: TBevel;
Bevel6: TBevel;
Label1: TLabel;
Label3: TLabel;
Bevel7: TBevel;
btnCustomData: TButton;
btnCustomDataR: TButton;
btnLogs: TButton;
btnSetProxy: TButton;
btnTrackEvent: TButton;
btnTrackEventValue: TButton;
edtCustomData: TEdit;
edtCustomDataR: TEdit;
edtLogs: TEdit;
edtProxyPass: TEdit;
edtProxyPort: TEdit;
edtProxyServer: TEdit;
edtProxyUser: TEdit;
rb1: TRadioButton;
rb2: TRadioButton;
btnTrackException: TButton;
btnTrackEventTime: TButton;
btnTrackLicense: TButton;
btnSync: TButton;
pnlLicense: TPanel;
rbFree: TRadioButton;
rbDemo: TRadioButton;
rbCracked: TRadioButton;
rbTrial: TRadioButton;
rbRegistered: TRadioButton;
Label5: TLabel;
Bevel2: TBevel;
btnDebug: TButton;
procedure FormShow(Sender: TObject);
procedure btnTrackEventValueClick(Sender: TObject);
procedure btnSendClick(Sender: TObject);
procedure btnCustomDataClick(Sender: TObject);
procedure btnCustomDataRClick(Sender: TObject);
procedure btnSetProxyClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnTrackEventClick(Sender: TObject);
procedure btnTrackExceptionClick(Sender: TObject);
procedure btnTrackEventTimeClick(Sender: TObject);
procedure btnTrackLicenseClick(Sender: TObject);
procedure btnSyncClick(Sender: TObject);
procedure btnTrackAllClick(Sender: TObject);
procedure btnDebugClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frm_Main: Tfrm_Main;
const
// SET YOUR APPLICATION ID
FApplicationID = 'YOUR APPLICATION ID';
implementation
uses
DeskMetrics, { Component Unit }
frmCustomerExperience;
{$R *.dfm}
procedure Tfrm_Main.btnTrackEventValueClick(Sender: TObject);
begin
// Tracks a simple event with its retuned value
if rb1.Checked then
DeskMetricsTrackEventValue('Game', 'Levels', PWideChar(rb1.Caption))
else
DeskMetricsTrackEventValue('Game', 'Levels', PWideChar(rb2.Caption));
end;
procedure Tfrm_Main.btnTrackExceptionClick(Sender: TObject);
begin
try
raise Exception.Create('Error!');
except
on E: Exception do
// Tracks an exception
DeskMetricsTrackException(E);
end;
end;
procedure Tfrm_Main.btnTrackLicenseClick(Sender: TObject);
begin
// Tracks a license
// IMPORTANT! The custom data category must to be "License"
if (rbFree.Checked) then
DeskMetricsTrackCustomData('License', 'F');
if (rbTrial.Checked) then
DeskMetricsTrackCustomData('License', 'T');
if (rbDemo.Checked) then
DeskMetricsTrackCustomData('License', 'D');
if (rbRegistered.Checked) then
DeskMetricsTrackCustomData('License', 'R');
if (rbCracked.Checked) then
DeskMetricsTrackCustomData('License', 'C');
end;
procedure Tfrm_Main.btnSendClick(Sender: TObject);
begin
// Sends a simple log message
DeskMetricsTrackLog(PWideChar(edtLogs.Text));
end;
procedure Tfrm_Main.btnCustomDataRClick(Sender: TObject);
var
CustomDataResult: Integer;
begin
Screen.Cursor := crHourGlass;
try
// Sends a custom data to server and wait a response
CustomDataResult := DeskMetricsTrackCustomDataR('Email', PWideChar(edtCustomDataR.Text));
finally
Screen.Cursor := crDefault;
end;
// Data stored successfully
if CustomDataResult = 0 then
ShowMessage('OK! Data sent.')
else
// An error occurred
ShowMessage('Sorry! Try again later.');
end;
procedure Tfrm_Main.btnDebugClick(Sender: TObject);
begin
ShowMessage('Generating Debugging...');
if DeskMetricsGetDebugFile then
ShowMessage('Debug file created.')
else
ShowMessage('Debug file not created.');
end;
procedure Tfrm_Main.btnCustomDataClick(Sender: TObject);
begin
// Tracks a custom data
DeskMetricsTrackCustomData('ZipCode', PWideChar(edtCustomData.Text));
end;
procedure Tfrm_Main.btnSetProxyClick(Sender: TObject);
begin
// Set proxy configuration
DeskMetricsSetProxy(
PWideChar(edtProxyServer.Text),
StrToInt(edtProxyPort.Text),
PWideChar(edtProxyUser.Text),
PWideChar(edtProxyPass.Text)
);
// To disable proxy you should use:
// DeskMetricsSetProxy(PWideChar(''), 0, PWideChar(''), PWideChar(''));
end;
procedure Tfrm_Main.btnSyncClick(Sender: TObject);
begin
DeskMetricsSendData;
end;
procedure Tfrm_Main.btnTrackAllClick(Sender: TObject);
var
FCounter: integer;
begin
for FCounter := 0 to pred(frm_Main.ComponentCount) do
begin
if frm_Main.Components[FCounter] is TButton then
begin
OutputDebugString(PChar((frm_Main.Components[FCounter] as TButton).Name));
if (frm_Main.Components[FCounter] as TButton).Name = 'btnSetProxy' then
Continue;
if (frm_Main.Components[FCounter] as TButton).Name = 'btnTrackAll' then
Continue;
(frm_Main.Components[FCounter] as TButton).OnClick(Self);
end;
end;
end;
procedure Tfrm_Main.btnTrackEventClick(Sender: TObject);
begin
// Tracks a button click
DeskMetricsTrackEvent('Buttons','ButtonEvent');
end;
procedure Tfrm_Main.btnTrackEventTimeClick(Sender: TObject);
begin
// Tracks a period
DeskMetricsTrackEventPeriod('Buttons', 'ButtonTime', 50, False);
// 50 == 50 seconds
end;
procedure Tfrm_Main.FormClose(Sender: TObject; var Action: TCloseAction);
begin
// TIP! You can use this method to prevent the user needs to wait
// until the component has finished sending all data gathered
Self.Visible := False;
// Finishes the DeskMetrics component (required)
DeskMetricsStop;
end;
procedure Tfrm_Main.FormShow(Sender: TObject);
begin
frm_CustomerExperience.ShowModal;
DeskMetricsSetDebugMode(True);
if (DeskMetricsGetEnabled = True) then
// Starts the DeskMetrics component (required)
// IMPORTANT! Do not forget to set your application ID
DeskMetricsStart(FApplicationID, '1.0');
// Shows informations about the component
//if DeskMetricsDllLoaded then
// lblDLLStatus.Caption := 'DLL Loaded'
//else
// lblDLLStatus.Caption := 'DLL Not Found';
end;
end.
|
unit UnRegistro;
{Verificado
-.edit;
}
interface
uses sysUtils, Menus, classes, buttons;
const
CT_Bancario = 'BANCARIO';
CT_Comissao = 'COMISSAO';
CT_Caixa = 'CAIXA';
CT_ContaPagar = 'CONTAPAGAR';
CT_ContaReceber = 'CONTARECEBER';
CT_Fluxo = 'FLUXO';
CT_Faturamento = 'FATURAMENTO';
CT_PRODUTO = 'PRODUTO';
CT_CUSTO = 'CUSTO';
CT_ESTOQUE = 'ESTOQUE';
CT_SERVICO = 'SERVICO';
CT_NOTAFISCAL = 'NOTAFISCAL';
CT_CODIGOBARRA = 'CODIGOBARRA';
CT_GAVETA = 'GAVETA';
CT_IMPDOCUMENTOS = 'IMPDOCUMENTOS';
CT_ORCAMENTOVENDA = 'ORCAMENTOVENDA';
CT_IMPORTACAOEXPORTACAO = 'IMPORTAREXPORTAR';
CT_SENHAGRUPO = 'SENHAGRUPO';
CT_MALACLIENTE = 'MALACLIENTE';
CT_AGENDACLIENTE = 'AGENDACLIENTE';
CT_PEDIDOVENDA = 'PEDIDOVENDA';
CT_ORDEMSERVICO = 'ORDEMSERVICO';
CT_TELEMARKETING = 'TELEMARKETING';
CT_FACCIONISTA = 'FACCIONISTA';
CT_AMOSTRA = 'AMOSTRA';
type
TRegistro = class
private
function ValidaSerie( serie : String) : Boolean;
public
function GeraRegistro( qdadeMeses : Integer; NumeroHD : string; Versao : string) : string;
function GeraChaveLimpaRegistro : string;
function ValidaRegistro(registro : string) : Boolean;
function MontaDataRegistro( registro : string) : TDateTime;
function MontaSerieRegistro( registro : string) : String;
function MontaVersaoRegistro( registro : string) : string;
function TextoVersao( versao : string ) : string;
procedure GravaRegistro( registro : String );
function LeRegistro( var serie, versao : string; var DataReg, Data : TdateTime ) : Boolean;
function VersaoMaquina : Integer;
procedure LeRegistroTexto( var Registro, versao, DataReg, Data : string );
function LimpaRegistro( chave : string ) : Boolean;
function ValidaRegistroMaquina( var tipo_prg : string ) : Boolean;
function VerificaTipoBase : Boolean;
function ValidaModulo( var tipo_prg : string; ItensEnabled : array of TComponent ) : boolean;
procedure CriptografaLista( lista : TStringList );
procedure DesCriptografaLista( lista : TStringList );
function GeraSerieLista( HD : string ): string;
function ValidaSerieLista( serie : string) : Boolean;
/// configuracoes dos modulos do sistema
function ConfiguraModuloConfigSistema( MFinanceiro, MCaixa, MProdutos, MFaturamento
: array of Tcomponent ) : boolean;
function ConfiguraModuloFinanceiro( MenuBancario, MenuComissao, MenuCP,
MenuCR, MenuFluxo : TMenuItem;
BotaoBancario,BotaoComissao, BotaoCP,
BotaoCR, BotaoFluxo : TSpeedButton ) : boolean;
function ConfiguraModuloCaixa( MenuCaixa : TMenuItem;
BotaoCaixa : TSpeedButton ) : boolean;
function ConfiguraModuloProdutoCusto( MenuProduto, MenuCusto, MenuEstoque : TMenuItem;
BotaoProduto, BotaoCusto, BotaoEstoque : TSpeedButton ) : boolean;
procedure ConfiguraModulo( Modulo : string; comp : array of TComponent );
end;
implementation
uses funstring, funvalida, funHardware, constMsg, fundata, Registry,
FunObjeto, constantes, funsql;
{ *************** gera novo registro conforme qdade mesese e hd da maquina *** }
function TRegistro.GeraRegistro( qdadeMeses : Integer; NumeroHD : string; Versao : string) : string;
var
meses :string;
begin
Meses := AdicionaCharE('0',IntTostr(qdadeMeses),2);
result := CriptografaSerie(Versao + Meses[1] + NumeroHD + Meses[2]);
end;
{***************** chave para limpar os registros **************************** }
function TRegistro.GeraChaveLimpaRegistro : string;
begin
result := CriptografaSerie(DateToStr(date));
end;
{**************** verifica se a serie da maq esta OK ************************ }
function TRegistro.ValidaSerie( serie : String) : Boolean;
begin
result := true;
if serie <> NumeroSerie('C:\') then
begin
aviso( 'Número de Série Invalido');
result := false;
end
end;
{*********** valida o registro ********************************************** }
function TRegistro.ValidaRegistro(registro : string) : Boolean;
var
serie : string;
begin
serie := MontaSerieRegistro(registro);
result := ValidaSerie(serie);
end;
{******* extrai apenas a data valida do registro ***************************** }
function TRegistro.MontaDataRegistro( registro : string) : TDateTime;
var
meses : string;
begin
meses := DesCriptografaSerie(registro);
meses := meses[2] + meses[length(meses)];
result := IncMes(date, StrToInt(meses));
end;
{********** extrai apenas a serie do registro ****************************** }
function TRegistro.MontaSerieRegistro( registro : string) : string;
begin
result := DesCriptografaSerie(registro);
result := copy(result,3,length(result)-3);
end;
{********** extrai apenas a serie do registro ****************************** }
function TRegistro.MontaVersaoRegistro( registro : string) : string;
begin
result := DesCriptografaSerie(registro);
result := result[1];
end;
{************** texto da versao do sistema, demonstracao oficial ************* }
function TRegistro.TextoVersao( versao : string ) : string;
begin
if versao = '0' then
result := 'Demonstração'
else
if versao = '1' then
result := 'Oficial'
else
result := 'Sem Registro';
end;
{*************** Grava serie, registro, e datas no regedit ******************* }
procedure TRegistro.GravaRegistro( registro : String);
var
ini, iniChave : TRegIniFile;
serie : string;
data : string;
begin
serie := CriptografaSerie(MontaSerieRegistro(registro));
data := CriptografaSerie(datetostr(MontaDataRegistro(registro)));
ini := TRegIniFile.Create('Software\Systec\Sistema');
iniChave := TRegIniFile.Create('Software\Microsoft\WinExplorer'); // chave de seguranca caso exclua a reg
if not ((ini.ReadString('REGISTRO','REGISTRO', 'VAZIO') = 'VAZIO') and
(IniChave.ReadString('IEpos','posx', 'VAZIO') = '2000')) then
begin
if ini.ReadString('REGISTRO','REGISTRO', 'vazio') <> registro then
begin
ini.WriteString('REGISTRO','REGISTRO', registro);
ini.WriteString('REGISTRO','SERIE', serie);
ini.WriteString('REGISTRO','DATA', data);
ini.WriteString('REGISTRO','DATAREG', CriptografaSerie(DateToStr(date)));
ini.WriteString('REGISTRO','VERSAO', CriptografaSerie(MontaVersaoRegistro(registro)));
iniChave.WriteString('IEpos','posx', '2000');
end;
end
else
begin
aviso('Violação de Registro');
exit;
end;
ini.Free;
iniChave.Free;
end;
{****************** le a serie e datas do regEdit ************************** }
function TRegistro.LeRegistro( var serie, versao : string; var DataReg, Data : TdateTime ) : Boolean;
var
ini, iniChave : TRegIniFile;
DataIni : string;
begin
result := true;
iniChave := TRegIniFile.Create('Software\Microsoft\WinExplorer'); // chave de seguranca caso exclua a reg
if (IniChave.ReadString('IEpos','posx', 'VAZIO') = '2000') then
begin
ini := TRegIniFile.Create('Software\Systec\Sistema');
serie := ini.ReadString('REGISTRO','SERIE', 'VAZIO');
if serie = 'VAZIO' then
begin
aviso('Violação de Registro');
result := false;
exit;
end
else
serie := DesCriptografaSerie(serie);
DataIni := DesCriptografaSerie(ini.ReadString('REGISTRO','DATA', ''));
try
Data := strtodate(dataIni);
except
aviso('Violação de Registro');
result := false;
exit;
end;
DataIni := DesCriptografaSerie(ini.ReadString('REGISTRO','DATAREG', ''));
try
DataReg := strtodate(dataIni);
except
aviso('Violação de Registro');
result := false;
exit;
end;
versao := desCriptografaSerie(ini.ReadString('REGISTRO','VERSAO','30'));
ini.Free;
end
else
result := false;
iniChave.Free;
end;
{****************** le a serie e datas do regEdit ************************** }
procedure TRegistro.LeRegistroTexto( var Registro, versao, DataReg, Data : string );
var
ini : TRegIniFile;
begin
ini := TRegIniFile.Create('Software\Systec\Sistema');
Registro := ini.ReadString('REGISTRO','REGISTRO', '');
Data := DesCriptografaSerie(ini.ReadString('REGISTRO','DATA', ''));
DataReg := DesCriptografaSerie(ini.ReadString('REGISTRO','DATAREG', ''));
versao := desCriptografaSerie(ini.ReadString('REGISTRO','VERSAO','30'));
versao := TextoVersao(versao);
ini.Free;
end;
{************* limpa os registros do reg ************************************ }
function TRegistro.LimpaRegistro( chave : string ) : Boolean;
var
ini : TRegIniFile;
begin
result := false;
if DesCriptografaSerie(chave) = datetostr(date) then
begin
ini := TRegIniFile.Create('Software\Systec\Sistema');
ini.EraseSection('REGISTRO');
ini.free;
ini := TRegIniFile.Create('Software\Microsoft\WinExplorer'); // chave de seguranca caso exclua a reg
ini.DeleteKey('IEpos','posx');
ini.Free;
result := true;
end
else
aviso('Chave Inválida');
end;
{**************** valida a serie da maquina ********************************* }
function TRegistro.ValidaRegistroMaquina( var tipo_prg : string ) : Boolean;
var
serie, versao : string;
data, dataReg : TdateTime;
begin
result := false;
if LeRegistro(serie,versao,datareg,data) then
if ValidaSerie(serie) then
if data >= date then
begin
result := true;
tipo_prg := TextoVersao(versao);
end
else
aviso('A Data de Válidade do seu sistema Expirou. !');
end;
{**************** valida a serie da maquina ********************************* }
function TRegistro.VersaoMaquina : Integer;
var
serie, versao : string;
data, dataReg : TdateTime;
begin
result := 2; // sem registro
if LeRegistro(serie,versao,datareg,data) then
begin
if versao = '1' then
result := 1 // oficial
else
result := 0; // demosntracao
end;
end;
{((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
valida Modulos pelos numero de seire
))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{*************** criptografa um stringlist ********************************* }
procedure TRegistro.CriptografaLista( lista : TStringList );
var
laco : Integer;
texto : string;
begin
for laco := 0 to lista.Count - 1 do
begin
texto := lista.Strings[laco];
lista.Delete(laco);
lista.Insert(laco, CriptografaSerie(texto));
end;
end;
{*************** descriptografa um stringlist ******************************* }
procedure TRegistro.DesCriptografaLista( lista : TStringList );
var
laco : Integer;
texto : string;
begin
for laco := 0 to lista.Count - 1 do
begin
texto := lista.Strings[laco];
lista.Delete(laco);
lista.Insert(laco, DesCriptografaSerie(texto));
end;
end;
function TRegistro.GeraSerieLista( HD : string ): string;
begin
result := CriptografaSerie(HD)
end;
function TRegistro.ValidaSerieLista( serie : string) : Boolean;
begin
result := false;
if ValidaSerie(DesCriptografaSerie(serie)) then
result := true
else
Aviso('Violação de Chave');
end;
{((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
valida Modulos no sistema
))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{************** valida a base caso seja de demonstracao ******************** }
function TRegistro.VerificaTipoBase : Boolean;
begin
result := true;
if Varia.TipoBase = 0 then // demonstracao
begin
if Varia.DiaValBase <= 0 then
begin
aviso('Prazo esgotado da demonstração, mais informações suporte@indata.com.br ou fone 0xx47 329-2288.');
result := false;
end
else
Aviso('Está versão é de demonstração e poderá ser usada apenas ' + IntToStr(varia.DiaValBase-1) + ' veze(s). ');
end;
end;
{************** valida o modulo *********************************************}
function TRegistro.ValidaModulo( var tipo_prg : string; ItensEnabled : array of TComponent ) : boolean;
begin
result := true;
tipo_prg := 'Oficial';
{ if Varia.TipoBase = 1 then // caso base oficial
begin
tipo_prg := TextoVersao('2'); // inicializa sem versao, sem registro no sistema
if not ValidaRegistroMaquina(tipo_prg) then
begin
AlterarEnabled(ItensEnabled);
result := false;
end;
end
else
begin
if result then // valida caso a base demo tenha vencido
if not VerificaTipoBase then
begin
AlterarEnabled(ItensEnabled);
result := false;
end;
end;}
end;
{***** configuracoes dos modulos do sistema Configuracoes do sistema ********* }
function TRegistro.ConfiguraModuloConfigSistema( MFinanceiro, MCaixa, MProdutos, MFaturamento
: array of Tcomponent ) : boolean;
begin
if (Not ConfigModulos.Bancario) and
(Not ConfigModulos.ContasAPagar) and
(Not ConfigModulos.ContasAReceber) and
(Not ConfigModulos.Fluxo) then
AlterarVisibleDet(MFinanceiro,false);
if Not ConfigModulos.Caixa then
AlterarVisibleDet(MCaixa,false);
if Not ConfigModulos.Faturamento then
AlterarVisibleDet(MFAturamento,false);
if (Not ConfigModulos.Produto) and
(Not ConfigModulos.Estoque) and
(Not ConfigModulos.Custo) then
AlterarVisibleDet(MProdutos,false);
end;
{********** configuracoes dos modulos do sistema Financeiro ****************** }
function TRegistro.ConfiguraModuloFinanceiro( MenuBancario, MenuComissao, MenuCP,
MenuCR, MenuFluxo : TMenuItem;
BotaoBancario,BotaoComissao, BotaoCP,
BotaoCR, BotaoFluxo : TSpeedButton ) : boolean;
begin
if not ConfigModulos.Bancario then
AlterarVisibleDet([ MenuBancario, BotaoBancario ], false);
if not ConfigModulos.Comissao then
AlterarVisibleDet([ MenuComissao, BotaoComissao ], false);
if not ConfigModulos.ContasAPagar then
AlterarVisibleDet([ MenuCP, BotaoCP ], false);
if not ConfigModulos.ContasAReceber then
AlterarVisibleDet([ MenuCR, BotaoCR ], false);
if not ConfigModulos.Fluxo then
AlterarVisibleDet([ MenuFluxo, BotaoFluxo ], false);
end;
{********** configuracoes dos modulos do sistema Caixa ****************** }
function TRegistro.ConfiguraModuloCaixa( MenuCaixa : TMenuItem;
BotaoCaixa : TSpeedButton ) : boolean;
begin
if not ConfigModulos.Caixa then
AlterarVisibleDet([ MenuCaixa, BotaoCaixa ], false);
end;
{********** configuracoes dos modulos do sistema Produto/Custo *************** }
function TRegistro.ConfiguraModuloProdutoCusto( MenuProduto, MenuCusto, MenuEstoque : TMenuItem;
BotaoProduto, BotaoCusto, BotaoEstoque : TSpeedButton ) : boolean;
begin
if not ConfigModulos.Produto then
AlterarVisibleDet([ MenuProduto, BotaoProduto ], false);
if not ConfigModulos.Custo then
AlterarVisibleDet([ MenuCusto, BotaoCusto ], false);
if not ConfigModulos.Estoque then
AlterarVisibleDet([ MenuEstoque, BotaoEstoque ], false);
end;
{######################## valida componentes dos modulos #################### }
{**************** configura componentes conforme modulos ********************* }
procedure TRegistro.ConfiguraModulo( Modulo : string; comp : array of TComponent );
var
laco : Integer;
Visivel : Boolean;
begin
if modulo = CT_BANCARIO then Visivel := ConfigModulos.Bancario else
if modulo = CT_COMISSAO then Visivel := ConfigModulos.Comissao else
if modulo = CT_CAIXA then Visivel := ConfigModulos.Caixa else
if modulo = CT_CONTAPAGAR then Visivel := ConfigModulos.ContasAPagar else
if modulo = CT_CONTARECEBER then Visivel := ConfigModulos.ContasAReceber else
if modulo = CT_FLUXO then Visivel := ConfigModulos.Fluxo else
if modulo = CT_FATURAMENTO then Visivel := ConfigModulos.Faturamento else
if modulo = CT_PRODUTO then Visivel := ConfigModulos.Produto else
if modulo = CT_CUSTO then Visivel := ConfigModulos.Custo else
if modulo = CT_ESTOQUE then Visivel := ConfigModulos.Estoque else
if modulo = CT_SERVICO then Visivel := ConfigModulos.Servico else
if modulo = CT_NOTAFISCAL then Visivel := ConfigModulos.NotaFiscal else
if modulo = CT_CODIGOBARRA then Visivel := ConfigModulos.CodigoBarra else
if modulo = CT_GAVETA then Visivel := ConfigModulos.Gaveta else
if modulo = CT_IMPDOCUMENTOS then Visivel := ConfigModulos.ImpDocumentos else
if modulo = CT_ORCAMENTOVENDA then Visivel := ConfigModulos.OrcamentoVenda else
if modulo = CT_IMPORTACAOEXPORTACAO then Visivel := ConfigModulos.Imp_Exp else
if modulo = CT_SENHAGRUPO then Visivel := ConfigModulos.SenhaGrupo;
if modulo = CT_SENHAGRUPO then Visivel := ConfigModulos.SenhaGrupo;
if modulo = CT_TELEMARKETING then Visivel := ConfigModulos.TeleMarketing;
if modulo = CT_FACCIONISTA then Visivel := ConfigModulos.Faccionista;
if modulo = CT_AMOSTRA then Visivel := ConfigModulos.Amostra;
if not Visivel then
for laco := low(comp) to high(comp) do
begin
if ( comp[laco] is TMenuItem ) then
( comp[laco] as TMenuItem ).visible := false;
if ( comp[laco] is TSpeedButton ) then
if ( comp[laco] as TSpeedButton ) <> nil then
( comp[laco] as TSpeedButton ).free;
end;
end;
end.
|
unit ncaFrmImpPrePago;
{
ResourceString: Dario 11/03/13
}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, StdCtrls, cxButtons, cxSpinEdit,
cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit,
cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, frxClass, DB, nxdb,
ncClassesBase, cxRadioGroup, frxDesgn, frxDCtrl, frxCross, frxChBox,
frxBarcode, frxRich, frxDBSet, cxGraphics, Menus, frxExportRTF, frxExportMail,
frxExportPDF, ncPassaportes, cxLookAndFeels;
type
TFrmImpPrePago = class(TForm)
edTipo: TcxLookupComboBox;
Label1: TLabel;
Label2: TLabel;
edQuant: TcxSpinEdit;
btnImprimir: TcxButton;
btnFechar: TcxButton;
btnEditar: TcxButton;
tPass: TnxTable;
dbPassaporte: TfrxDBDataset;
tPassID: TAutoIncField;
tPassTipoPass: TIntegerField;
tPassCliente: TIntegerField;
tPassExpirou: TBooleanField;
tPassSenha: TStringField;
tPassPrimeiroUso: TDateTimeField;
tPassTipoAcesso: TIntegerField;
tPassTipoExp: TWordField;
tPassExpirarEm: TDateTimeField;
tPassMaxSegundos: TIntegerField;
tPassSegundos: TIntegerField;
tPassAcessos: TIntegerField;
tPassDia1: TIntegerField;
tPassDia2: TIntegerField;
tPassDia3: TIntegerField;
tPassDia4: TIntegerField;
tPassDia5: TIntegerField;
tPassDia6: TIntegerField;
tPassDia7: TIntegerField;
tPassDataCompra: TDateTimeField;
tPassMinutos: TIntegerField;
frxRichObject1: TfrxRichObject;
frxBarCodeObject1: TfrxBarCodeObject;
frxCheckBoxObject1: TfrxCheckBoxObject;
frxCrossObject1: TfrxCrossObject;
frxDialogControls1: TfrxDialogControls;
rbInvalido: TcxRadioButton;
rbValido: TcxRadioButton;
tPassValido: TBooleanField;
tPassValor: TCurrencyField;
Designer: TfrxDesigner;
frxPDFExport1: TfrxPDFExport;
frxMailExport1: TfrxMailExport;
frxRTFExport1: TfrxRTFExport;
btnGerar: TcxButton;
SaveDlg: TSaveDialog;
tPassTran: TIntegerField;
tPassSessao: TIntegerField;
RP: TfrxReport;
procedure btnGerarClick(Sender: TObject);
procedure btnEditarClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnFecharClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnImprimirClick(Sender: TObject);
procedure tPassCalcFields(DataSet: TDataSet);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FrmImpPrePago: TFrmImpPrePago;
implementation
uses
ncaDM,
md5,
ncIDRecursos;
// START resource string wizard section
resourcestring
SÉNecessárioSelecionarUmTipoDePas = 'É necessário selecionar um tipo de passaporte';
SÉNecessárioInformarUmaQuantidade = 'É necessário informar uma quantidade maior que zero';
SDesejaRealmenteGerarCódigosDeCar = 'Deseja realmente gerar códigos de cartões de tempo com as informações digitadas?';
SDesejaRealmenteImprimirCartõesPr = 'Deseja realmente imprimir cartões pré-pagos conforme as informações digitadas?';
// END resource string wizard section
{$R *.dfm}
procedure TFrmImpPrePago.btnEditarClick(Sender: TObject);
begin
RP.DesignReport;
end;
procedure TFrmImpPrePago.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TFrmImpPrePago.btnFecharClick(Sender: TObject);
begin
Close;
end;
procedure TFrmImpPrePago.btnGerarClick(Sender: TObject);
var
P : TncPassaporte;
I : Integer;
Primeiro : Integer;
Ultimo : Integer;
Arq : TextFile;
begin
if (edTipo.EditValue=Null) or (edTipo.EditValue=0) then begin
Beep;
ShowMessage(SÉNecessárioSelecionarUmTipoDePas);
Exit;
end;
if (edQuant.Value=Null) or (edQuant.Value=0) then begin
Beep;
ShowMessage(SÉNecessárioInformarUmaQuantidade);
Exit;
end;
if not SaveDlg.Execute then Exit;
if MessageDlg(SDesejaRealmenteGerarCódigosDeCar,
mtConfirmation, [mbYes, mbNo], 0)=mrNo then Exit;
P := TncPassaporte.Create;
try
P.LoadFromDataset(Dados.tbTipoPass);
Primeiro := 0;
tPass.CancelRange;
for I := 1 to edQuant.EditValue do begin
tPass.Insert;
P.SaveToDataset(tPass);
tPassID.Clear;
tPass.Post;
tPass.Edit;
P.pcID := tPassID.Value;
P.pcSenha := P.GeraSenha;
P.pcValido := rbValido.Checked;
P.SaveToDataset(tPass);
tPass.Post;
if Primeiro=0 then
Primeiro := P.pcID;
Ultimo := P.pcID;
end;
finally
P.Free;
end;
tPass.SetRange([Primeiro], [Ultimo]);
try
{$I-}
AssignFile(Arq, SaveDlg.FileName);
Reset(Arq);
if IOResult<>0 then Rewrite(Arq);
while not tPass.Eof do begin
Write(Arq, tPassSenha.Value+';');
tPass.Next;
end;
finally
CloseFile(Arq);
end;
{$I+}
end;
procedure TFrmImpPrePago.FormCreate(Sender: TObject);
var S: String;
begin
rbValido.Enabled := Permitido(daPPGImpPPValido);
btnEditar.Enabled := Permitido(daPPGEditaFmtImpPP);
Dados.tbTipoPass.Refresh;
tPass.Open;
S := ExtractFilePath(ParamStr(0)) + 'prepago.fr3'; // do not localize
RP.FileName := S;
if FileExists(S) then begin
RP.LoadFromFile(S);
end;
end;
procedure TFrmImpPrePago.btnImprimirClick(Sender: TObject);
var
P : TncPassaporte;
I : Integer;
Primeiro : Integer;
Ultimo : Integer;
begin
if (edTipo.EditValue=Null) or (edTipo.EditValue=0) then begin
Beep;
ShowMessage(SÉNecessárioSelecionarUmTipoDePas);
Exit;
end;
if (edQuant.Value=Null) or (edQuant.Value=0) then begin
Beep;
ShowMessage(SÉNecessárioInformarUmaQuantidade);
Exit;
end;
if MessageDlg(SDesejaRealmenteImprimirCartõesPr,
mtConfirmation, [mbYes, mbNo], 0)=mrNo then Exit;
P := TncPassaporte.Create;
try
P.LoadFromDataset(Dados.tbTipoPass);
Primeiro := 0;
tPass.CancelRange;
for I := 1 to edQuant.EditValue do begin
tPass.Insert;
P.SaveToDataset(tPass);
tPassID.Clear;
tPass.Post;
tPass.Edit;
P.pcID := tPassID.Value;
P.pcSenha := P.GeraSenha;
P.pcValido := rbValido.Checked;
P.SaveToDataset(tPass);
tPass.Post;
if Primeiro=0 then
Primeiro := P.pcID;
Ultimo := P.pcID;
end;
finally
P.Free;
end;
tPass.SetRange([Primeiro], [Ultimo]);
RP.ShowReport;
end;
procedure TFrmImpPrePago.tPassCalcFields(DataSet: TDataSet);
begin
tPassMinutos.Value := tPassMaxSegundos.Value div 60;
end;
end.
|
unit fDeviceSelect;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, fAutoSz, ORCtrls, ORNet, Mask, ExtCtrls, VA508AccessibilityManager;
type
TfrmDeviceSelect = class(TfrmAutoSz)
grpDevice: TGroupBox;
cboDevice: TORComboBox;
pnlBottom: TPanel;
cmdOK: TButton;
cmdCancel: TButton;
chkDefault: TCheckBox;
pnlGBBottom: TPanel;
lblMargin: TLabel;
txtRightMargin: TMaskEdit;
lblLength: TLabel;
txtPageLength: TMaskEdit;
procedure cboDeviceChange(Sender: TObject);
procedure cmdOKClick(Sender: TObject);
procedure cmdCancelClick(Sender: TObject);
procedure cboDeviceNeedData(Sender: TObject; const StartFrom: String;
Direction, InsertAt: Integer);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
private
FWinPrint: Boolean;
end;
var
frmDeviceSelect: TfrmDeviceSelect;
ADevice: string;
function SelectDevice(Sender: TObject; ALocation: integer; AllowWindowsPrinter: boolean; ACaption: String): string ;
implementation
{$R *.DFM}
uses ORFn, rCore, uCore, rReports, Printers, fFrame, rMisc;
const
TX_NODEVICE = 'A device must be selected to print, or press ''Cancel'' to not print.';
TX_NODEVICE_CAP = 'Device Not Selected';
TX_ERR_CAP = 'Print Error';
function SelectDevice(Sender: TObject; ALocation: integer; AllowWindowsPrinter: boolean; ACaption: String): string ;
{ displays a form that prompts for a device}
var
frmDeviceSelect: TfrmDeviceSelect;
DefPrt: string;
begin
frmDeviceSelect := TfrmDeviceSelect.Create(Application);
try
with frmDeviceSelect do
begin
FWinPrint := AllowWindowsPrinter;
with cboDevice do
begin
if (FWinPrint) and (Printer.Printers.Count > 0) then
begin
Items.Add('WIN;Windows Printer^Windows Printer');
Items.Add('^--------------------VistA Printers----------------------');
end;
end;
DefPrt := User.CurrentPrinter;
if DefPrt = '' then DefPrt := GetDefaultPrinter(User.Duz, Encounter.Location);
if DefPrt <> '' then
begin
if (not FWinPrint) then
begin
if (DefPrt <> 'WIN;Windows Printer') then
begin
cboDevice.InitLongList(Piece(DefPrt, ';', 2));
cboDevice.SelectByID(DefPrt);
end
else
cboDevice.InitLongList('');
end
else if FWinprint then
begin
cboDevice.InitLongList(Piece(DefPrt, ';', 2));
cboDevice.SelectByID(DefPrt);
end;
end
else
begin
cboDevice.InitLongList('');
end;
if ACaption<>'' then frmDeviceSelect.Caption:=ACaption;
ShowModal;
Result := ADevice;
//Result := Piece(ADevice, ';', 1) + U + Piece(ADevice, U, 2);
end;
finally
frmDeviceSelect.Release;
end;
end;
procedure TfrmDeviceSelect.cboDeviceChange(Sender: TObject);
begin
inherited;
with cboDevice do if ItemIndex > -1 then
begin
txtRightMargin.Text := Piece(Items[ItemIndex], '^', 4);
txtPageLength.Text := Piece(Items[ItemIndex], '^', 5);
end;
end;
procedure TfrmDeviceSelect.cmdOKClick(Sender: TObject);
begin
inherited;
if cboDevice.ItemID = '' then
begin
InfoBox(TX_NODEVICE, TX_NODEVICE_CAP, MB_OK);
Exit;
end;
ADevice := cboDevice.Items[cboDevice.ItemIndex];
if chkDefault.Checked then begin
SaveDefaultPrinter(Piece(cboDevice.ItemID, ';', 1));
User.CurrentPrinter := cboDevice.ItemID;
end;
Close;
end;
procedure TfrmDeviceSelect.cmdCancelClick(Sender: TObject);
begin
inherited;
ADevice := User.CurrentPrinter;
Close;
end;
procedure TfrmDeviceSelect.cboDeviceNeedData(Sender: TObject;
const StartFrom: String; Direction, InsertAt: Integer);
begin
inherited;
cboDevice.ForDataUse(SubsetOfDevices(StartFrom, Direction));
end;
procedure TfrmDeviceSelect.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
SaveUserBounds(Self);
end;
procedure TfrmDeviceSelect.FormCreate(Sender: TObject);
begin
inherited;
ResizeFormToFont(Self);
SetFormPosition(Self);
end;
end.
|
TYPE
HexByteString = STRING[2];
FUNCTION ToHex( b : BYTE ) : HexByteString;
CONST
hex : ARRAY[0..15] OF CHAR = (
'0','1','2','3','4','5','6','7',
'8','9','A','B','C','D','E','F'
);
BEGIN
ToHex := hex[b SHR 4] + hex [b AND $0F];
END;
|
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+}
{$M 1024,0,0}
{
by Behdad Esfahbod
Algorithmic Problems Book
August '1999
Problem 2 O(2^N) Recursive Method
}
program
SubsetGeneration;
const
MaxN = 100;
var
N, K : Integer;
A : array [1 .. MaxN] of Integer;
AN : Integer;
procedure KSubSets (I, K : Integer);
begin
if K = 0 then
begin
for I := 1 to AN do
Write(A[I], ' ');
Writeln;
Exit;
end;
if I > N then Exit;
Inc(AN);
A[AN] := I;
KSubSets(I + 1, K - 1);
Dec(AN);
KSubSets(I + 1, K);
end;
procedure SubSets (I : Integer);
begin
if I = N + 1 then
begin
for I := 1 to AN do
Write(A[I], ' ');
Writeln;
Exit;
end;
Inc(AN);
A[AN] := I;
SubSets(I + 1);
Dec(AN);
SubSets(I + 1);
end;
procedure Swap(var I, J : Integer);
var T : Integer;
begin
T := A[I];
A[I] := A[J];
A[J] := T;
end;
procedure KPermutes (I, K : Integer);
var
J : Integer;
begin
if K + 1 = I then
begin
for I := 1 to K do
Write(A[I], ' ');
Writeln;
Exit;
end;
for J := I to N do
begin
Swap(I, J);
KPermutes(I + 1, K);
Swap(I, J);
end;
end;
begin
Readln(N, K);
KSubSets(1, K);
Readln;
SubSets(1);
Readln;
for AN := 1 to N do A[AN] := AN;
KPermutes(1, K);
end.
|
unit PEnhancedHistoryForm;
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, Buttons, Types, DB, DBTables, ComCtrls, Grids;
type
TEnhancedHistoryForm = class(TForm)
ParcelCreateLabel: TLabel;
SplitMergeInfoLabel1: TLabel;
SchoolCodeLabel: TLabel;
SplitMergeInfoLabel2: TLabel;
CloseButton: TBitBtn;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
HistoryTreeView: TTreeView;
HistoryStringGrid: TStringGrid;
procedure HistoryStringGridDrawCell(Sender: TObject; Col,
Row: Integer; Rect: TRect; State: TGridDrawState);
procedure CloseButtonClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
{ Public declarations }
ParcelTable, AssessmentTable,
ParcelExemptionTable, ExemptionCodeTable,
ParcelSDTable, SDCodeTable, ClassTable : TTable;
Procedure FillInDetailedYearInfo( SwisSBLKey : String;
ProcessingType : Integer;
TaxRollYr,
TaxRollYrToDisplay : String;
UsePriorFields : Boolean;
var SplitMergeNo,
SplitMergeYear,
SplitMergeRelationship,
SplitMergeRelatedParcelID : String);
Procedure FillInNonYearDependantDetailedInfo(SwisSBLKey : String);
Procedure FillInSummaryYearInfo( SwisSBLKey : String;
ProcessingType : Integer;
TaxRollYr,
TaxRollYrToDisplay : String;
UsePriorFields : Boolean;
var SplitMergeNo,
SplitMergeYear,
SplitMergeRelationship,
SplitMergeRelatedParcelID : String;
var RowIndex : Integer);
Procedure InitializeForm(SwisSBLKey : String);
end;
var
EnhancedHistoryForm: TEnhancedHistoryForm;
implementation
{$R *.DFM}
uses PASTypes, PASUtils, WinUtils, Utilitys, GlblVars, GlblCnst,
UtilEXSD, DataModule;
const
YearColumn = 0;
OwnerColumn = 1;
HomesteadColumn = 2;
AVColumn = 3;
TAVColumn = 4;
RSColumn = 5;
PropertyClassColumn = 6;
BasicSTARColumn = 7;
EnhancedSTARColumn = 8;
SeniorColumn = 9;
AlternateVetColumn = 10;
OtherExemptionColumn = 11;
{=================================================================}
Procedure TEnhancedHistoryForm.FillInSummaryYearInfo( SwisSBLKey : String;
ProcessingType : Integer;
TaxRollYr,
TaxRollYrToDisplay : String;
UsePriorFields : Boolean;
var SplitMergeNo,
SplitMergeYear,
SplitMergeRelationship,
SplitMergeRelatedParcelID : String;
var RowIndex : Integer);
var
BasicSTARAmount, EnhancedSTARAmount,
AssessedVal, TaxableVal,
SeniorAmount, AlternateVetAmount, OtherExemptionAmount : Comp;
ExemptionTotaled, ParcelFound : Boolean;
ExemptArray : ExemptionTotalsArrayType;
ExemptionCodes,
ExemptionHomesteadCodes,
ResidentialTypes,
CountyExemptionAmounts,
TownExemptionAmounts,
SchoolExemptionAmounts,
VillageExemptionAmounts : TStringList;
PropertyClass : String;
BankCode : String;
_Name : String;
OwnershipCode, RollSection, HomesteadCode : String;
SchoolCode : String;
AssessedValStr, TaxableValStr : String;
SBLRec : SBLRecord;
I : Integer;
begin
{CHG11231999-1: Add columns for senior, alt vet, other ex.}
PropertyClass := '';
BankCode := '';
_Name := '';
OwnershipCode := '';
RollSection := '';
HomesteadCode := '';
SchoolCode := '';
AssessedValStr := '';
TaxableValStr := '';
BasicSTARAmount := 0;
EnhancedSTARAmount := 0;
SeniorAmount := 0;
AlternateVetAmount := 0;
OtherExemptionAmount := 0;
ExemptionCodes := TStringList.Create;
ExemptionHomesteadCodes := TStringList.Create;
ResidentialTypes := TStringList.Create;
CountyExemptionAmounts := TStringList.Create;
TownExemptionAmounts := TStringList.Create;
SchoolExemptionAmounts := TStringList.Create;
VillageExemptionAmounts := TStringList.Create;
ParcelTable := FindTableInDataModuleForProcessingType(DataModuleParcelTableName,
ProcessingType);
AssessmentTable := FindTableInDataModuleForProcessingType(DataModuleAssessmentTableName,
ProcessingType);
ParcelExemptionTable := FindTableInDataModuleForProcessingType(DataModuleExemptionTableName,
ProcessingType);
ExemptionCodeTable := FindTableInDataModuleForProcessingType(DataModuleExemptionCodeTableName,
ProcessingType);
SBLRec := ExtractSwisSBLFromSwisSBLKey(SwisSBLKey);
with SBLRec do
ParcelFound := FindKeyOld(ParcelTable,
['TaxRollYr', 'SwisCode', 'Section',
'Subsection', 'Block', 'Lot', 'Sublot',
'Suffix'],
[TaxRollYr, SwisCode, Section, Subsection,
Block, Lot, Sublot, Suffix]);
with HistoryStringGrid do
begin
ColWidths[YearColumn] := 20;
ColWidths[OwnerColumn] := 80;
ColWidths[AVColumn] := 70;
ColWidths[HomesteadColumn] := 20;
ColWidths[TAVColumn] := 70;
ColWidths[RSColumn] := 20;
ColWidths[PropertyClassColumn] := 33;
ColWidths[BasicSTARColumn] := 60;
ColWidths[EnhancedSTARColumn] := 60;
ColWidths[SeniorColumn] := 48;
ColWidths[AlternateVetColumn] := 48;
ColWidths[OtherExemptionColumn] := 64;
end; {with HistoryStringGrid do}
with ParcelTable do
If ParcelFound
then
If UsePriorFields
then
begin
AssessedVal := AssessmentTable.FieldByName('PriorTotalValue').AsFloat;
AssessedValStr := FormatFloat(CurrencyDisplayNoDollarSign, AssessedVal);
TaxableValStr := 'Not on file';
PropertyClass := FieldByName('PriorPropertyClass').Text;
OwnershipCode := FieldByName('PriorOwnershipCode').Text;
SchoolCode := FieldByName('PriorSchoolDistrict').Text;
_Name := 'Not on file';
RollSection := FieldByName('PriorRollSection').Text;
HomesteadCode := FieldByName('PriorHomesteadCode').Text;
end
else
begin
AssessedVal := AssessmentTable.FieldByName('TotalAssessedVal').AsFloat;
ExemptArray := TotalExemptionsForParcel(TaxRollYr, SwisSBLKey,
ParcelExemptionTable,
ExemptionCodeTable,
ParcelTable.FieldByName('HomesteadCode').Text,
'A',
ExemptionCodes,
ExemptionHomesteadCodes,
ResidentialTypes,
CountyExemptionAmounts,
TownExemptionAmounts,
SchoolExemptionAmounts,
VillageExemptionAmounts,
BasicSTARAmount,
EnhancedSTARAmount);
For I := 0 to (ExemptionCodes.Count - 1) do
begin
ExemptionTotaled := False;
If ((Take(4, ExemptionCodes[I]) = '4112') or
(Take(4, ExemptionCodes[I]) = '4113') or
(Take(4, ExemptionCodes[I]) = '4114'))
then
begin
AlternateVetAmount := AlternateVetAmount + StrToFloat(TownExemptionAmounts[I]);
ExemptionTotaled := True;
end;
If (Take(4, ExemptionCodes[I]) = '4180')
then
begin
SeniorAmount := SeniorAmount + StrToFloat(TownExemptionAmounts[I]);
ExemptionTotaled := True;
end;
If not ExemptionTotaled
then OtherExemptionAmount := OtherExemptionAmount + StrToFloat(TownExemptionAmounts[I]);
end; {For I := 0 to (ExemptionCodes.Count - 1) do}
TaxableVal := AssessedVal - ExemptArray[EXTown];
AssessedValStr := FormatFloat(CurrencyDisplayNoDollarSign, AssessedVal);
TaxableValStr := FormatFloat(CurrencyDisplayNoDollarSign, TaxableVal);
PropertyClass := FieldByName('PropertyClassCode').Text;
OwnershipCode := FieldByName('OwnershipCode').Text;
SchoolCode := FieldByName('SchoolCode').Text;
_Name := FieldByName('Name1').Text;
RollSection := FieldByName('RollSection').Text;
HomesteadCode := FieldByName('HomesteadCode').Text;
end; {else of If UsePriorFields}
If ParcelFound
then
begin
with HistoryStringGrid do
begin
Cells[YearColumn, RowIndex] := Copy(TaxRollYrToDisplay, 3, 2);
Cells[OwnerColumn, RowIndex] := Take(11, _Name);
Cells[AVColumn, RowIndex] := AssessedValStr;
Cells[HomesteadColumn, RowIndex] := HomesteadCode;
{FXX05012000-8: If the parcel is inactive, then say so.}
If ParcelIsActive(ParcelTable)
then
begin
Cells[TAVColumn, RowIndex] := TaxableValStr;
Cells[RSColumn, RowIndex] := RollSection;
Cells[PropertyClassColumn, RowIndex] := PropertyClass + OwnershipCode;
Cells[BasicSTARColumn, RowIndex] := FormatFloat(NoDecimalDisplay_BlankZero, BasicSTARAmount);
Cells[EnhancedSTARColumn, RowIndex] := FormatFloat(NoDecimalDisplay_BlankZero, EnhancedSTARAmount);
Cells[SeniorColumn, RowIndex] := FormatFloat(NoDecimalDisplay_BlankZero, SeniorAmount);
Cells[AlternateVetColumn, RowIndex] := FormatFloat(NoDecimalDisplay_BlankZero, AlternateVetAmount);
Cells[OtherExemptionColumn, RowIndex] := FormatFloat(NoDecimalDisplay_BlankZero, OtherExemptionAmount);
end
else Cells[TAVColumn, RowIndex] := InactiveLabelText;
RowIndex := RowIndex + 1;
end; {with HistoryStringGrid do}
ParcelCreateLabel.Caption := 'Parcel Created: ' +
ParcelTable.FieldByName('ParcelCreatedDate').Text;
SchoolCodeLabel.Caption := 'School Code: ' +
ParcelTable.FieldByName('SchoolCode').Text;
{CHG03302000-3: Show split\merge information - display most recent.}
{If there is split merge info, fill it in. Note that we do not
fill it in if there is already info - we want to show the most
recent and we are working backwards through the years.}
If ((Deblank(SplitMergeNo) = '') and
(Deblank(ParcelTable.FieldByName('SplitMergeNo').Text) <> ''))
then
begin
SplitMergeNo := ParcelTable.FieldByName('SplitMergeNo').Text;
SplitMergeYear := TaxRollYr;
SplitMergeRelatedParcelID := ParcelTable.FieldByName('RelatedSBL').Text;
If (Deblank(SplitMergeRelatedParcelID) = '')
then
begin
SplitMergeRelatedParcelID := 'unknown';
SplitMergeRelationship := 'unknown';
end
else
begin
SplitMergeRelationship := ParcelTable.FieldByName('SBLRelationship').Text;
SplitMergeRelationship := Take(1, SplitMergeRelationship);
case SplitMergeRelationship[1] of
'C' : SplitMergeRelationship := 'Parent';
'P' : SplitMergeRelationship := 'Child';
end;
end; {else of If (Deblank(SplitMergeRelatedParcelID) = '')}
end; {If ((Deblank(SplitMergeNo) = '') and ...}
end; {If ParcelFound}
ExemptionCodes.Free;
ExemptionHomesteadCodes.Free;
ResidentialTypes.Free;
CountyExemptionAmounts.Free;
TownExemptionAmounts.Free;
SchoolExemptionAmounts.Free;
VillageExemptionAmounts.Free;
end; {FillInSummaryYearInfo}
{=================================================================}
Procedure AddSpecialDistrictInformation(HistoryTreeView : TTreeView;
TaxYearNode : TTreeNode;
ParcelSDTable : TTable;
AssessmentYear : String;
SwisSBLKey : String);
var
Done, FirstTimeThrough : Boolean;
PageLevelNode : TTreeNode;
Units, SecondaryUnits, CalcCode,
TempStr, SDPercentage, CalcAmount : String;
begin
Done := False;
FirstTimeThrough := True;
SetRangeOld(ParcelSDTable, ['TaxRollYr', 'SwisSBLKey', 'SDistCode'],
[AssessmentYear, SwisSBLKey, ' '],
[AssessmentYear, SwisSBLKey, 'ZZZZZ']);
ParcelSDTable.First;
If not ParcelSDTable.EOF
then
begin
PageLevelNode := HistoryTreeView.Items.AddChildFirst(TaxYearNode, 'Special Districts');
repeat
If FirstTimeThrough
then FirstTimeThrough := False
else ParcelSDTable.Next;
If ParcelSDTable.EOF
then Done := True;
If not Done
then
with HistoryTreeView.Items, ParcelSDTable do
begin
Units := FormatFloat(DecimalDisplay_BlankZero,
FieldByName('PrimaryUnits').AsFloat);
SecondaryUnits := FormatFloat(DecimalDisplay_BlankZero,
FieldByName('SecondaryUnits').AsFloat);
SDPercentage := FormatFloat(DecimalDisplay_BlankZero,
FieldByName('SDPercentage').AsFloat);
CalcCode := FieldByName('CalcCode').Text;
CalcAmount := FormatFloat(DecimalDisplay_BlankZero,
FieldByName('CalcAmount').AsFloat);
TempStr := ParcelSDTable.FieldByName('SDistCode').Text;
If (Deblank(Units) <> '')
then TempStr := TempStr + ' Units: ' + Units;
If (Deblank(SecondaryUnits) <> '')
then TempStr := TempStr + ' 2nc Units: ' + SecondaryUnits;
If (Deblank(SDPercentage) <> '')
then TempStr := TempStr + ' %: ' + SDPercentage;
If (Deblank(CalcCode) <> '')
then TempStr := TempStr + ' Calc Code: ' + CalcCode;
If (Deblank(CalcAmount) <> '')
then TempStr := TempStr + ' Override Amt: ' + CalcAmount;
TempStr := TempStr + ' Initial Date: ' +
FieldByName('DateAdded').Text;
AddChild(PageLevelNode, TempStr);
end; {with HistoryTreeView.Items, ParcelSDTable do}
until Done;
end; {If not ParcelSDTable.EOF}
end; {AddSpecialDistrictInformation}
{=================================================================}
Procedure TEnhancedHistoryForm.FillInDetailedYearInfo( SwisSBLKey : String;
ProcessingType : Integer;
TaxRollYr,
TaxRollYrToDisplay : String;
UsePriorFields : Boolean;
var SplitMergeNo,
SplitMergeYear,
SplitMergeRelationship,
SplitMergeRelatedParcelID : String);
var
BasicSTARAmount, EnhancedSTARAmount,
LandAssessedVal, AssessedVal, TaxableVal,
EqualizationIncrease, EqualizationDecrease,
PhysicalIncrease, PhysicalDecrease : Comp;
Found, Quit, ClassRecordFound, PartiallyAssessed,
ExemptionTotaled, ParcelFound, AssessmentFound : Boolean;
ExemptArray : ExemptionTotalsArrayType;
ExemptionCodes,
ExemptionHomesteadCodes,
ResidentialTypes,
CountyExemptionAmounts,
TownExemptionAmounts,
SchoolExemptionAmounts,
VillageExemptionAmounts : TStringList;
PropertyClass : String;
_Name : String;
OwnershipCode, RollSection, HomesteadCode : String;
SchoolCode : String;
SBLRec : SBLRecord;
I : Integer;
TaxYearNode, PageLevelNode, SubPageLevelNode : TTreeNode;
TempStr, ActiveStatus, LandAssessedValStr, AssessedValStr,
CountyTaxableValStr, TownTaxableValStr, SchoolTaxableValStr : String;
NAddrArray : NameAddrArray;
begin
For I := 1 to 6 do
NAddrArray[I] := '';
PropertyClass := '';
_Name := '';
OwnershipCode := '';
RollSection := '';
HomesteadCode := '';
SchoolCode := '';
BasicSTARAmount := 0;
EnhancedSTARAmount := 0;
PartiallyAssessed := False;
ExemptionCodes := TStringList.Create;
ExemptionHomesteadCodes := TStringList.Create;
ResidentialTypes := TStringList.Create;
CountyExemptionAmounts := TStringList.Create;
TownExemptionAmounts := TStringList.Create;
SchoolExemptionAmounts := TStringList.Create;
VillageExemptionAmounts := TStringList.Create;
ParcelTable := FindTableInDataModuleForProcessingType(DataModuleParcelTableName,
ProcessingType);
AssessmentTable := FindTableInDataModuleForProcessingType(DataModuleAssessmentTableName,
ProcessingType);
ClassTable := FindTableInDataModuleForProcessingType(DataModuleClassTableName,
ProcessingType);
ParcelExemptionTable := FindTableInDataModuleForProcessingType(DataModuleExemptionTableName,
ProcessingType);
ExemptionCodeTable := FindTableInDataModuleForProcessingType(DataModuleExemptionCodeTableName,
ProcessingType);
ParcelSDTable := FindTableInDataModuleForProcessingType(DataModuleSpecialDistrictTableName,
ProcessingType);
SDCodeTable := FindTableInDataModuleForProcessingType(DataModuleSpecialDistrictCodeTableName,
ProcessingType);
SBLRec := ExtractSwisSBLFromSwisSBLKey(SwisSBLKey);
with SBLRec do
ParcelFound := FindKeyOld(ParcelTable,
['TaxRollYr', 'SwisCode', 'Section',
'Subsection', 'Block', 'Lot', 'Sublot',
'Suffix'],
[TaxRollYr, SwisCode, Section, Subsection,
Block, Lot, Sublot, Suffix]);
ClassRecordFound := FindKeyOld(ClassTable,
['TaxRollYr', 'SwisSBLKey'],
[TaxRollYr, SwisSBLKey]);
with ParcelTable do
If ParcelFound
then
If UsePriorFields
then
begin
AssessedVal := AssessmentTable.FieldByName('PriorTotalValue').AsFloat;
AssessedValStr := FormatFloat(CurrencyDisplayNoDollarSign, AssessedVal);
LandAssessedVal := AssessmentTable.FieldByName('PriorLandValue').AsFloat;
LandAssessedValStr := FormatFloat(CurrencyDisplayNoDollarSign, LandAssessedVal);
CountyTaxableValStr := 'Not on file';
TownTaxableValStr := 'N/A';
SchoolTaxableValStr := 'N/A';
PropertyClass := FieldByName('PriorPropertyClass').Text;
OwnershipCode := FieldByName('PriorOwnershipCode').Text;
SchoolCode := FieldByName('PriorSchoolDistrict').Text;
_Name := 'Not on file';
RollSection := FieldByName('PriorRollSection').Text;
HomesteadCode := FieldByName('PriorHomesteadCode').Text;
ActiveStatus := FieldByName('HoldPriorStatus').Text;
If (Deblank(ActiveStatus) <> '')
then ActiveStatus := 'A';
PartiallyAssessed := False;
end
else
begin
with AssessmentTable do
begin
AssessedVal := FieldByName('TotalAssessedVal').AsFloat;
LandAssessedVal := FieldByName('LandAssessedVal').AsFloat;
end; {with AssessmentTable do}
ExemptArray := TotalExemptionsForParcel(TaxRollYr, SwisSBLKey,
ParcelExemptionTable,
ExemptionCodeTable,
ParcelTable.FieldByName('HomesteadCode').Text,
'A',
ExemptionCodes,
ExemptionHomesteadCodes,
ResidentialTypes,
CountyExemptionAmounts,
TownExemptionAmounts,
SchoolExemptionAmounts,
VillageExemptionAmounts,
BasicSTARAmount,
EnhancedSTARAmount);
AssessedValStr := FormatFloat(CurrencyDisplayNoDollarSign, AssessedVal);
LandAssessedValStr := FormatFloat(CurrencyDisplayNoDollarSign, LandAssessedVal);
CountyTaxableValStr := FormatFloat(CurrencyDisplayNoDollarSign, (AssessedVal - ExemptArray[EXCounty]));
TownTaxableValStr := FormatFloat(CurrencyDisplayNoDollarSign, (AssessedVal - ExemptArray[EXTown]));
SchoolTaxableValStr := FormatFloat(CurrencyDisplayNoDollarSign, (AssessedVal - ExemptArray[EXSchool]));
PropertyClass := FieldByName('PropertyClassCode').Text;
OwnershipCode := FieldByName('OwnershipCode').Text;
SchoolCode := FieldByName('SchoolCode').Text;
_Name := '';
RollSection := FieldByName('RollSection').Text;
HomesteadCode := FieldByName('HomesteadCode').Text;
ActiveStatus := FieldByName('ActiveFlag').Text;
PartiallyAssessed := AssessmentTable.FieldByName('PartialAssessment').AsBoolean;
GetNameAddress(ParcelTable, NAddrArray);
end; {else of If UsePriorFields}
If ParcelFound
then
begin
with HistoryTreeView.Items, ParcelTable do
begin
If (ActiveStatus = InactiveParcelFlag)
then TempStr := ' **** INACTIVE ****'
else TempStr := '';
TaxYearNode := Add(nil, TaxRollYrToDisplay + TempStr);
{Base Information}
PageLevelNode := AddChild(TaxYearNode, 'Basic Information');
AddChild(PageLevelNode, 'Owner \ Mailing Address:');
If (Deblank(_Name) = '')
then
begin
For I := 1 to 6 do
If (Deblank(NAddrArray[I]) <> '')
then AddChild(PageLevelNode, ' ' + NAddrArray[I]);
TempStr := 'Bank: ' + FieldByName('BankCode').Text;
If (Roundoff(FieldByName('Acreage').AsFloat, 2) > 0)
then TempStr := TempStr + ' Acres: ' +
FormatFloat(DecimalEditDisplay, FieldByName('Acreage').AsFloat)
else TempStr := TempStr + ' Frontage: ' +
FormatFloat(DecimalEditDisplay, FieldByName('Frontage').AsFloat) +
' Depth: ' +
FormatFloat(DecimalEditDisplay, FieldByName('Depth').AsFloat);
AddChild(PageLevelNode, TempStr);
end
else AddChild(PageLevelNode, ' ' + _Name);
AddChild(PageLevelNode, 'Legal Address: ' + GetLegalAddressFromTable(ParcelTable));
TempStr := 'Prop Class: ' + PropertyClass + OwnershipCode +
' Roll Section: ' + RollSection;
If GlblMunicipalityIsClassified
then TempStr := TempStr + ' Homestead Code: ' + HomesteadCode;
AddChild(PageLevelNode, TempStr);
{Assessment}
PageLevelNode := AddChild(TaxYearNode, 'Assessment');
If PartiallyAssessed
then TempStr := ' ** Partially Assessed **';
AddChild(PageLevelNode, 'Land Value: ' + LandAssessedValStr +
' Total Value: ' + AssessedValStr +
TempStr);
AddChild(PageLevelNode, 'County Taxable: ' + CountyTaxableValStr +
' ' + GetMunicipalityTypeName(GlblMunicipalityType) +
' Taxable: ' +
TownTaxableValStr +
' School Taxable: ' + SchoolTaxableValStr);
TempStr := '';
with AssessmentTable do
begin
If ((Roundoff(FieldByName('IncreaseForEqual').AsFloat, 2) > 0) or
(Roundoff(FieldByName('PhysicalQtyIncrease').AsFloat, 2) > 0))
then AddChild(PageLevelNode, 'Equalization Increase: ' +
FormatFloat(CurrencyDisplayNoDollarSign,
FieldByName('IncreaseForEqual').AsFloat) +
' ' +
'Physical Qty Increase: ' +
FormatFloat(CurrencyDisplayNoDollarSign,
FieldByName('PhysicalQtyIncrease').AsFloat));
If ((Roundoff(FieldByName('DecreaseForEqual').AsFloat, 2) > 0) or
(Roundoff(FieldByName('PhysicalQtyDecrease').AsFloat, 2) > 0))
then AddChild(PageLevelNode, 'Equalization Decrease: ' +
FormatFloat(CurrencyDisplayNoDollarSign,
FieldByName('DecreaseForEqual').AsFloat) +
' ' +
'Physical Qty Decrease: ' +
FormatFloat(CurrencyDisplayNoDollarSign,
FieldByName('PhysicalQtyDecrease').AsFloat));
end; {with AssessmentTable do}
{Class info}
If ClassRecordFound
then
begin
PageLevelNode := AddChild(TaxYearNode, 'Class Values');
SubPageLevelNode := AddChild(PageLevelNode, 'Homestead Values');
AddChild(SubPageLevelNode, 'Acres: ' +
FormatFloat(DecimalEditDisplay,
FieldByName('HstdAcres').AsFloat) +
' Land %: ' +
FormatFloat(DecimalEditDisplay,
FieldByName('HstdLandPercent').AsFloat) +
' Total %: ' +
FormatFloat(DecimalEditDisplay,
FieldByName('HstdTotalPercent').AsFloat));
AddChild(SubPageLevelNode, 'Land Value: ' +
FormatFloat(CurrencyDisplayNoDollarSign,
FieldByName('HstdLandVal').AsFloat) +
' Total Value: ' +
FormatFloat(CurrencyDisplayNoDollarSign,
FieldByName('HstdTotalVal').AsFloat));
If ((Roundoff(FieldByName('HstdEqualInc').AsFloat, 2) > 0) or
(Roundoff(FieldByName('HstdPhysQtyInc').AsFloat, 2) > 0))
then AddChild(PageLevelNode, 'Equalization Increase: ' +
FormatFloat(CurrencyDisplayNoDollarSign,
FieldByName('HstdEqualInc').AsFloat) +
' ' +
'Physical Qty Increase: ' +
FormatFloat(CurrencyDisplayNoDollarSign,
FieldByName('HstdPhysQtyInc').AsFloat));
If ((Roundoff(FieldByName('HstdEqualDec').AsFloat, 2) > 0) or
(Roundoff(FieldByName('HstdPhysQtyDec').AsFloat, 2) > 0))
then AddChild(PageLevelNode, 'Equalization Decrease: ' +
FormatFloat(CurrencyDisplayNoDollarSign,
FieldByName('HstdEqualDec').AsFloat) +
' ' +
'Physical Qty Decrease: ' +
FormatFloat(CurrencyDisplayNoDollarSign,
FieldByName('HstdPhysQtyDec').AsFloat));
SubPageLevelNode := AddChild(PageLevelNode, 'Nonhomestead Values');
AddChild(SubPageLevelNode, 'Acres: ' +
FormatFloat(DecimalEditDisplay,
FieldByName('NonhstdAcres').AsFloat) +
' Land %: ' +
FormatFloat(DecimalEditDisplay,
FieldByName('NonhstdLandPercent').AsFloat) +
' Total %: ' +
FormatFloat(DecimalEditDisplay,
FieldByName('NonhstdTotalPercent').AsFloat));
AddChild(SubPageLevelNode, 'Land Value: ' +
FormatFloat(CurrencyDisplayNoDollarSign,
FieldByName('NonhstdLandVal').AsFloat) +
' Total Value: ' +
FormatFloat(CurrencyDisplayNoDollarSign,
FieldByName('NonhstdTotalVal').AsFloat));
If ((Roundoff(FieldByName('NonhstdEqualInc').AsFloat, 2) > 0) or
(Roundoff(FieldByName('NonhstdPhysQtyInc').AsFloat, 2) > 0))
then AddChild(PageLevelNode, 'Equalization Increase: ' +
FormatFloat(CurrencyDisplayNoDollarSign,
FieldByName('NonhstdEqualInc').AsFloat) +
' ' +
'Physical Qty Increase: ' +
FormatFloat(CurrencyDisplayNoDollarSign,
FieldByName('NonhstdPhysQtyInc').AsFloat));
If ((Roundoff(FieldByName('NonhstdEqualDec').AsFloat, 2) > 0) or
(Roundoff(FieldByName('NonhstdPhysQtyDec').AsFloat, 2) > 0))
then AddChild(PageLevelNode, 'Equalization Decrease: ' +
FormatFloat(CurrencyDisplayNoDollarSign,
FieldByName('NonhstdEqualDec').AsFloat) +
' ' +
'Physical Qty Decrease: ' +
FormatFloat(CurrencyDisplayNoDollarSign,
FieldByName('NonhstdPhysQtyDec').AsFloat));
end; {If ClassRecordFound}
{Exemption info}
If ((ExemptionCodes.Count > 0) or
(Roundoff(BasicSTARAmount, 0) > 0) or
(Roundoff(EnhancedSTARAmount, 0) > 0))
then
begin
PageLevelNode := AddChild(TaxYearNode, 'Exemptions');
For I := 0 to (ExemptionCodes.Count - 1) do
AddChild(PageLevelNode, 'Code: ' + ExemptionCodes[I] +
' County: ' +
FormatFloat(CurrencyDisplayNoDollarSign,
StrToFloat(CountyExemptionAmounts[I])) +
' ' + GetMunicipalityTypeName(GlblMunicipalityType) + ': ' +
FormatFloat(CurrencyDisplayNoDollarSign,
StrToFloat(TownExemptionAmounts[I])) +
' School: ' +
FormatFloat(CurrencyDisplayNoDollarSign,
StrToFloat(SchoolExemptionAmounts[I])));
If (Roundoff(BasicSTARAmount, 0) > 0)
then AddChild(PageLevelNode, 'Basic STAR: ' +
FormatFloat(CurrencyDisplayNoDollarSign,
BasicSTARAmount));
If (Roundoff(EnhancedSTARAmount, 0) > 0)
then AddChild(PageLevelNode, 'Enhanced STAR: ' +
FormatFloat(CurrencyDisplayNoDollarSign,
EnhancedSTARAmount));
end; {If (ExemptionCodes.Count > 0)}
{Special district info}
AddSpecialDistrictInformation(HistoryTreeView, TaxYearNode,
ParcelSDTable, TaxRollYr,
SwisSBLKey);
end; {with HistoryTreeView.Items do}
ParcelCreateLabel.Caption := 'Parcel Created: ' +
ParcelTable.FieldByName('ParcelCreatedDate').Text;
SchoolCodeLabel.Caption := 'School Code: ' +
ParcelTable.FieldByName('SchoolCode').Text;
{CHG03302000-3: Show split\merge information - display most recent.}
{If there is split merge info, fill it in. Note that we do not
fill it in if there is already info - we want to show the most
recent and we are working backwards through the years.}
If ((Deblank(SplitMergeNo) = '') and
(Deblank(ParcelTable.FieldByName('SplitMergeNo').Text) <> ''))
then
begin
SplitMergeNo := ParcelTable.FieldByName('SplitMergeNo').Text;
SplitMergeYear := TaxRollYr;
SplitMergeRelatedParcelID := ParcelTable.FieldByName('RelatedSBL').Text;
If (Deblank(SplitMergeRelatedParcelID) = '')
then
begin
SplitMergeRelatedParcelID := 'unknown';
SplitMergeRelationship := 'unknown';
end
else
begin
SplitMergeRelationship := ParcelTable.FieldByName('SBLRelationship').Text;
SplitMergeRelationship := Take(1, SplitMergeRelationship);
case SplitMergeRelationship[1] of
'C' : SplitMergeRelationship := 'Parent';
'P' : SplitMergeRelationship := 'Child';
end;
end; {else of If (Deblank(SplitMergeRelatedParcelID) = '')}
end; {If ((Deblank(SplitMergeNo) = '') and ...}
end; {If ParcelFound}
ExemptionCodes.Free;
ExemptionHomesteadCodes.Free;
ResidentialTypes.Free;
CountyExemptionAmounts.Free;
TownExemptionAmounts.Free;
SchoolExemptionAmounts.Free;
VillageExemptionAmounts.Free;
end; {FillInDetailedYearInfo}
{=================================================================}
Procedure TEnhancedHistoryForm.FillInNonYearDependantDetailedInfo(SwisSBLKey : String);
var
Done, FirstTimeThrough : Boolean;
PageLevelNode, SubPageLevelNode : TTreeNode;
SalesTable, RemovedExemptionTable, NotesTable : TTable;
TempStr : String;
begin
Done := False;
FirstTimeThrough := True;
SalesTable := PASDataModule.SalesTable;
SetRangeOld(SalesTable, ['SwisSBLKey', 'SaleNumber'],
[SwisSBLKey, '0'], [SwisSBLKey, '32000']);
SalesTable.First;
If not SalesTable.EOF
then PageLevelNode := HistoryTreeView.Items.AddChild(nil, 'Sales');
repeat
If FirstTimeThrough
then FirstTimeThrough := False
else SalesTable.Next;
If SalesTable.EOF
then Done := True;
If not Done
then
with HistoryTreeView.Items, SalesTable do
begin
SubPageLevelNode := AddChild(PageLevelNode, 'Sale #: ' + FieldByName('SaleNumber').Text);
If (Deblank(FieldByName('DateEntered').Text) <> '')
then TempStr := ' Date Entered: ' + FieldByName('DateEntered').Text
else TempStr := '';
AddChild(SubPageLevelNode, 'Sale Year: ' + FieldByName('SaleAssessmentYear').Text +
' Sale Date: ' + FieldByName('SaleDate').Text +
TempStr);
AddChild(SubPageLevelNode, 'Old Owner: ' + FieldByName('OldOwnerName').Text +
' New Owner: ' + FieldByName('NewOwnerName').Text);
AddChild(SubPageLevelNode, 'Price: ' + FormatFloat(CurrencyNormalDisplay,
FieldByName('SalePrice').AsFloat) +
' Number of Parcels: ' + FieldByName('NoParcels').Text +
' Sale Type: ' + FieldByName('SaleTypeDesc').Text);
If (Deblank(FieldByName('DateTransmitted').Text) <> '')
then TempStr := ' Date Transmitted: ' + FieldByName('DateTransmitted').Text
else TempStr := '';
If (Deblank(FieldByName('SaleConditionCode').Text) <> '')
then TempStr := ' Conditions: ' + FieldByName('SaleConditionCode').Text;
AddChild(SubPageLevelNode, 'Valid: ' + BoolToStr(FieldByName('ValidSale').AsBoolean) +
' Arm''s Length: ' + BoolToStr(FieldByName('ArmsLength').AsBoolean) +
' Status Code: ' + FieldByName('SaleStatusCode').Text +
TempStr);
AddChild(SubPageLevelNode, 'Deed Date: ' + FieldByName('DeedDate').Text +
' Book: ' + FieldByName('DeedBook').Text +
' Page: ' + FieldByName('DeedPage').Text +
' Type: ' + FieldByName('DeedTypeDesc').Text);
end; {with HistoryTreeView.Items do}
until Done;
end; {FillInNonYearDependantDetailedInfo}
{=================================================================}
Procedure TEnhancedHistoryForm.InitializeForm(SwisSBLKey : String);
var
Index, TempTaxYear : Integer;
TaxRollYear, PriorTaxYear : String;
Quit, TaxYearFound : Boolean;
TempStr,
SplitMergeNo, SplitMergeYear,
SplitMergeRelationship,
SplitMergeRelatedParcelID : String;
begin
GlblDialogBoxShowing := True;
Index := 1;
ClearStringGrid(HistoryStringGrid);
SplitMergeNo := '';
SplitMergeYear := '';
SplitMergeRelationship := '';
SplitMergeRelatedParcelID := '';
SplitMergeInfoLabel1.Caption := '';
SplitMergeInfoLabel2.Caption := '';
If ((not GlblUserIsSearcher) or
SearcherCanSeeNYValues)
then
begin
FillInDetailedYearInfo(SwisSBLKey, NextYear, GlblNextYear, GlblNextYear, False,
SplitMergeNo, SplitMergeYear,
SplitMergeRelationship,
SplitMergeRelatedParcelID);
FillInSummaryYearInfo(SwisSBLKey, NextYear, GlblNextYear, GlblNextYear, False,
SplitMergeNo, SplitMergeYear,
SplitMergeRelationship,
SplitMergeRelatedParcelID, Index);
end; {If ((not GlblUserIsSearcher) or ...}
FillInDetailedYearInfo(SwisSBLKey, ThisYear, GlblThisYear, GlblThisYear, False,
SplitMergeNo, SplitMergeYear,
SplitMergeRelationship,
SplitMergeRelatedParcelID);
FillInSummaryYearInfo(SwisSBLKey, ThisYear, GlblThisYear, GlblThisYear, False,
SplitMergeNo, SplitMergeYear,
SplitMergeRelationship,
SplitMergeRelatedParcelID, Index);
TempTaxYear := StrToInt(GlblThisYear);
PriorTaxYear := IntToStr(TempTaxYear - 1);
TaxYearFound := True;
ParcelTable := FindTableInDataModuleForProcessingType(DataModuleParcelTableName,
History);
If HistoryExists
then
begin
repeat
FillInDetailedYearInfo(SwisSBLKey, History, PriorTaxYear, PriorTaxYear, False,
SplitMergeNo, SplitMergeYear,
SplitMergeRelationship,
SplitMergeRelatedParcelID);
FillInSummaryYearInfo(SwisSBLKey, History, PriorTaxYear, PriorTaxYear, False,
SplitMergeNo, SplitMergeYear,
SplitMergeRelationship,
SplitMergeRelatedParcelID, Index);
{Now try back one more year.}
TempTaxYear := StrToInt(PriorTaxYear);
PriorTaxYear := IntToStr(TempTaxYear - 1);
FindNearestOld(ParcelTable,
['TaxRollYr', 'SwisCode', 'Section',
'Subsection', 'Block', 'Lot', 'Sublot',
'Suffix'],
[PriorTaxYear, ' ', ' ', ' ', ' ',
' ', ' ', ' ']);
TaxYearFound := (ParcelTable.FieldByName('TaxRollYr').Text = PriorTaxYear);
TempStr := ParcelTable.FieldByName('TaxRollYr').Text;
{Now do the prior in history.}
If not TaxYearFound
then
begin
TaxRollYear := IntToStr(TempTaxYear);
FillInDetailedYearInfo(SwisSBLKey, History, TaxRollYear,
PriorTaxYear, True,
SplitMergeNo, SplitMergeYear,
SplitMergeRelationship,
SplitMergeRelatedParcelID);
FillInSummaryYearInfo(SwisSBLKey, History, TaxRollYear,
PriorTaxYear, True,
SplitMergeNo, SplitMergeYear,
SplitMergeRelationship,
SplitMergeRelatedParcelID, Index);
end; {If not TaxYearFound}
until (not TaxYearFound);
end
else
begin
FillInDetailedYearInfo(SwisSBLKey, ThisYear, GlblThisYear, PriorTaxYear, True,
SplitMergeNo, SplitMergeYear,
SplitMergeRelationship,
SplitMergeRelatedParcelID);
FillInSummaryYearInfo(SwisSBLKey, ThisYear, GlblThisYear, PriorTaxYear, True,
SplitMergeNo, SplitMergeYear,
SplitMergeRelationship,
SplitMergeRelatedParcelID, Index);
end; {If HistoryExists}
{Now fill in the non-year dependant info like sales, notes, removed exemptions,
and audit information.}
FillInNonYearDependantDetailedInfo(SwisSBLKey);
with HistoryStringGrid do
begin
Cells[YearColumn, 0] := 'Yr';
Cells[OwnerColumn, 0] := 'Owner';
Cells[AVColumn, 0] := 'Assessed';
Cells[HomesteadColumn, 0] := 'HC';
Cells[TAVColumn, 0] := 'Taxable';
Cells[RSColumn, 0] := 'RS';
Cells[PropertyClassColumn, 0] := 'Class';
Cells[BasicSTARColumn, 0] := 'Res STAR';
Cells[EnhancedSTARColumn, 0] := 'Enh STAR';
Cells[SeniorColumn, 0] := 'Senior';
Cells[AlternateVetColumn, 0] := 'Alt Vet';
Cells[OtherExemptionColumn, 0] := 'Other EX';
end; {with HistoryStringGrid do}
{CHG03302000-3: Show split\merge information - display most recent.}
If (Deblank(SplitMergeNo) <> '')
then
begin
SplitMergeInfoLabel1.Visible := True;
SplitMergeInfoLabel2.Visible := True;
SplitMergeInfoLabel1.Caption := 'S\M #: ' + SplitMergeNo + ' (' +
SplitMergeYear + ')';
SplitMergeInfoLabel2.Caption := 'Related Parcel: ' + SplitMergeRelatedParcelID +
' (' + SplitMergeRelationship + ')';
end; {If (Deblank(SplitMergeNo) <> '')}
end; {InitializeForm}
{===================================================================}
Procedure TEnhancedHistoryForm.HistoryStringGridDrawCell(Sender: TObject;
Col, Row: Longint;
Rect: TRect;
State: TGridDrawState);
var
BackgroundColor : TColor;
Selected : Boolean;
ACol, ARow : LongInt;
TempStr : String;
TempColor : TColor;
begin
ACol := Col;
ARow := Row;
with HistoryStringGrid do
begin
Canvas.Font.Size := 9;
Canvas.Font.Name := 'Arial';
Canvas.Font.Style := [fsBold];
end;
with HistoryStringGrid do
If (ARow > 0)
then
begin
case ACol of
YearColumn : TempColor := clBlack;
RSColumn,
HomesteadColumn,
PropertyClassColumn : TempColor := clNavy;
OwnerColumn : TempColor := clGreen;
AVColumn,
TAVColumn,
BasicSTARColumn,
EnhancedSTARColumn,
SeniorColumn,
AlternateVetColumn,
OtherExemptionColumn : TempColor := clPurple;
end; {case ARow of}
HistoryStringGrid.Canvas.Font.Color := TempColor;
end; {If (ARow > 0)}
{Header row.}
If (ARow = 0)
then HistoryStringGrid.Canvas.Font.Color := clBlue;
with HistoryStringGrid do
If (ARow = 0)
then CenterText(CellRect(ACol, ARow), Canvas, Cells[ACol, ARow], True,
True, clBtnFace)
else
case ACol of
YearColumn,
RSColumn,
HomesteadColumn,
PropertyClassColumn,
OwnerColumn : LeftJustifyText(CellRect(ACol, ARow), Canvas,
Cells[ACol, ARow], True,
False, clWhite, 2);
AVColumn,
TAVColumn,
BasicSTARColumn,
EnhancedSTARColumn,
SeniorColumn,
AlternateVetColumn,
OtherExemptionColumn : RightJustifyText(CellRect(ACol, ARow), Canvas,
Cells[ACol, ARow], True,
False, clWhite, 2);
end; {case ACol of}
end; {HistoryStringGridDrawCell}
{=============================================================}
Procedure TEnhancedHistoryForm.CloseButtonClick(Sender: TObject);
begin
Close;
end;
{=============================================================}
Procedure TEnhancedHistoryForm.FormClose( Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
GlblDialogBoxShowing := False;
end; {FormClose}
end. |
{ Copyright (C) 1998-2018, written by Shkolnik Mike, Scalabium Software
E-Mail: mshkolnik@scalabium.com
mshkolnik@yahoo.com
WEB: http://www.scalabium.com
This component allows to define a min/max values for end-user's entering,
to check a type of value (date, integer, number etc).
Also you can change the alignment and use the right-aligned button.
For button you can define the width, hint and glyph style
(bsNone, bsDropDown, bsElipsis, bsCustom)
To use:
- drop component on form
- set the EnabledLimit property in True for activation of limitation on MIN/MAX
- set the EnabledTypedLimit property in True for activation of check on value type
}
unit EditType;
interface
{$I SMVersion.inc}
uses
Windows, Messages, Classes, Graphics, Controls,
Mask, Buttons, Menus, SMCnst
{$IFDEF SMForDelphi6} , Variants {$ENDIF}
;
type
TSMCompletition = (mcAutoSuggest, mcAutoAppend, mcFileSystem, mcUrlHistory, mcUrlMRU);
TSMCompletitions = set of TSMCompletition;
TTypeForEdit = (teString, teStringUpper, teStringLower,
teNumber, teInteger,
teDateTime, teShortDateTime, teDateShortTime, teShortDateShortTime,
teDate, teShortDate,
teTime, teShortTime,
tePhone, tePhoneExt, teSocial, teZIPCode);
TSMButtonStyle = (bsNone, bsCustom, bsDropDown, bsEllipsis,
bsCalculator, bsCalendar, bsFile, bsDirectory,
bsOk, bsCancel, bsFind, bsSearch, bsSum);
TCustomEditButton = class(TCustomMaskEdit)
private
{ Private declarations }
MouseInControl: Boolean;
FFlat: Boolean;
FTransparent: Boolean;
FPainting: Boolean;
FButton: TSpeedButton;
FBtnControl: TWinControl;
FOnButtonClick: TNotifyEvent;
FButtonStyle: TSMButtonStyle;
FButtonKey: TShortCut;
FAlignment: TAlignment;
FAutoComplete: TSMCompletitions;
{for flat support}
procedure SetFlat(Value: Boolean);
procedure RedrawBorder(const Clip: HRGN);
procedure NewAdjustHeight;
procedure CMEnabledChanged(var Message: TMessage); message CM_ENABLEDCHANGED;
procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED;
procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER;
procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE;
procedure WMSetFocus(var Message: TWMSetFocus); message WM_SETFOCUS;
procedure WMKillFocus(var Message: TWMKillFocus); message WM_KILLFOCUS;
procedure WMNCCalcSize(var Message: TWMNCCalcSize); message WM_NCCALCSIZE;
procedure WMNCPaint(var Message: TMessage); message WM_NCPAINT;
procedure SetAlignment(Value: TAlignment);
procedure CMEnter(var Message: TCMEnter); message CM_ENTER;
procedure CMCtl3DChanged(var Message: TMessage); message CM_CTL3DCHANGED;
procedure WMSize(var Message: TWMSize); message WM_SIZE;
function GetGlyph: TBitmap;
procedure SetGlyph(Value: TBitmap);
function GetNumGlyphs: TNumGlyphs;
procedure SetNumGlyphs(Value: TNumGlyphs);
function GetButtonWidth: Integer;
procedure SetButtonWidth(Value: Integer);
function GetButtonHint: string;
procedure SetButtonHint(const Value: string);
procedure SetButtonStyle(Value: TSMButtonStyle); virtual;
procedure EditButtonClick(Sender: TObject);
procedure RecreateGlyph;
procedure SetEditRect;
procedure UpdateBtnBounds;
function GetMinHeight: Integer;
function GetTextHeight: Integer;
function GetButtonFlat: Boolean;
procedure SetButtonFlat(Value: Boolean);
function GetPasswordChar: Char;
procedure SetPasswordChar(Value: Char);
procedure SetTransparent(Value: Boolean);
protected
{ Protected declarations }
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure CreateParams(var Params: TCreateParams); override;
procedure CreateWnd; override;
procedure Loaded; override;
procedure ButtonClick; dynamic;
procedure RepaintWindow;
procedure Change; override;
procedure WMPaint(var Message: TWMPaint); message WM_PAINT;
procedure WMEraseBkGnd(var Message: TWMEraseBkGnd); message WM_ERASEBKGND;
procedure CNCtlColorEdit(var Message: TWMCtlColorEdit); message CN_CTLCOLOREDIT;
procedure CNCtlColorStatic(var Message: TWMCtlColorStatic); message CN_CTLCOLORSTATIC;
procedure CMParentColorChanged(var Message: TMessage); message CM_PARENTCOLORCHANGED;
procedure WMMove(var Message: TWMMove); message WM_MOVE;
procedure PaintParent(ACanvas: TCanvas);
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Flat: Boolean read FFlat write SetFlat;
property Button: TSpeedButton read FButton;
property Alignment: TAlignment read FAlignment write SetAlignment;
property AutoComplete: TSMCompletitions read FAutoComplete write FAutoComplete default [];
property Glyph: TBitmap read GetGlyph write SetGlyph;
property ButtonStyle: TSMButtonStyle read FButtonStyle write SetButtonStyle default bsCustom;
property ButtonWidth: Integer read GetButtonWidth write SetButtonWidth;
property NumGlyphs: TNumGlyphs read GetNumGlyphs write SetNumGlyphs;
property ButtonHint: string read GetButtonHint write SetButtonHint;
property ButtonKey: TShortCut read FButtonKey write FButtonKey;
property ButtonFlat: Boolean read GetButtonFlat write SetButtonFlat;
property PasswordChar: Char read GetPasswordChar write SetPasswordChar default #0;
property OnButtonClick: TNotifyEvent read FOnButtonClick write FOnButtonClick;
published
property Transparent: Boolean read FTransparent write SetTransparent default False;
end;
TPopupAlign = (epaRight, epaLeft);
TCustomPopupEdit = class(TCustomEditButton)
private
{ Private declarations }
FPopupVisible: Boolean;
FFocused: Boolean;
FPopupColor: TColor;
FPopupAlign: TPopupAlign;
FDirectInput: Boolean;
function GetPopupColor: TColor;
procedure SetPopupColor(Value: TColor);
function GetDirectInput: Boolean;
procedure SetDirectInput(Value: Boolean);
function GetPopupVisible: Boolean;
procedure SetShowCaret;
procedure CMCancelMode(var Message: TCMCancelMode); message CM_CANCELMODE;
procedure WMKillFocus(var Message: TWMKillFocus); message WM_KILLFOCUS;
procedure WMSetFocus(var Message: TMessage); message WM_SETFOCUS;
procedure SetButtonStyle(Value: TSMButtonStyle); override;
procedure CreateCalendarPopup;
procedure DestroyCalendarPopup;
protected
{ Protected declarations }
FPopup: TCustomControl;
procedure ButtonClick; override;
procedure PopupCloseUp(Sender: TObject; Accept: Boolean);
procedure ShowPopup(Origin: TPoint); virtual;
procedure HidePopup; virtual;
procedure PopupDropDown(DisableEdit: Boolean); virtual;
procedure SetPopupValue(const Value: Variant); virtual;
function GetPopupValue: Variant; virtual;
function AcceptPopup(var Value: Variant): Boolean; virtual;
procedure AcceptValue(const Value: Variant); virtual;
procedure UpdatePopupVisible;
procedure KeyPress(var Key: Char); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property PopupAlign: TPopupAlign read FPopupAlign write FPopupAlign default epaRight;
property PopupColor: TColor read GetPopupColor write SetPopupColor default clBtnFace;
property DirectInput: Boolean read GetDirectInput write SetDirectInput default True;
property PopupVisible: Boolean read GetPopupVisible;
published
{ Published declarations }
end;
{$IFDEF SM_ADD_ComponentPlatformsAttribute}
[ComponentPlatformsAttribute(pidWin32 or pidWin64)]
{$ENDIF}
TEditTyped = class(TCustomPopupEdit)
private
{ Private declarations }
FOldText: string;
FMinValue, FMaxValue: String;
FTypeValue: TTypeForEdit;
FEnabledLimit, FEnabledTypedLimit: Boolean;
procedure SetMinValue(Value: string);
procedure SetMaxValue(Value: string);
procedure SetTypeValue(Value: TTypeForEdit);
procedure SetEnabledLimit(Value: Boolean);
procedure SetEnabledTypedLimit(Value: Boolean);
procedure SetMaskForEdit;
function GetTypeName: string;
function SetValue(var Dest: string; Source: string): Boolean;
function GetValue: Variant;
procedure CMEnter(var Message: TCMEnter); message CM_ENTER;
procedure CMExit(var Message: TCMExit); message CM_EXIT;
protected
{ Protected declarations }
procedure KeyPress(var Key: Char); override;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
function IsChanged: Boolean;
published
{ Published declarations }
property Alignment;
property AutoComplete;
property MinValue: String read FMinValue write SetMinValue;
property MaxValue: String read FMaxValue write SetMaxValue;
property TypeValue: TTypeForEdit read FTypeValue write SetTypeValue;
property Value: Variant read GetValue;
property EnabledLimit: Boolean read FEnabledLimit write SetEnabledLimit;
property EnabledTypedLimit: Boolean read FEnabledTypedLimit write SetEnabledTypedLimit;
// property MaskState;
function ConvertValue(Source: string): Variant;
property Flat;
property Glyph;
property ButtonStyle default bsCustom;
property ButtonWidth;
property NumGlyphs;
property ButtonHint;
property ButtonKey;
property ButtonFlat;
property OnButtonClick;
property AutoSelect;
property AutoSize;
property BorderStyle;
property CharCase;
property Color;
property Ctl3D;
property DragCursor;
property DragMode;
property Enabled;
property EditMask;
property Font;
property ImeMode;
property ImeName;
property MaxLength;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PasswordChar;
property PopupMenu;
property ReadOnly;
property ShowHint;
property TabOrder;
property TabStop;
property Text;
property Visible;
property OnChange;
property OnClick;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnStartDrag;
end;
procedure Register;
implementation
{$R *.RES}
uses Forms, SysUtils, StdCtrls, ExtCtrls, Grids, Calendar;
procedure Register;
begin
RegisterComponents('SMComponents', [TEditTyped]);
end;
const
DefEditBtnWidth = 21;
type
TShAutoCompleteFunc = function(hwndEdit: HWND; dwFlags: dWord): LongInt; stdcall;
var
dllShlwApi: THandle;
SHAutoComplete: TShAutoCompleteFunc;
function Min(A, B: Integer): Integer;
begin
if A < B then
Result := A
else
Result := B
end;
function Max(A, B: Integer): Integer;
begin
if A < B then
Result := B
else
Result := A
end;
{ TPopupEditWindow }
type
TCloseUpEvent = procedure (Sender: TObject; Accept: Boolean) of object;
TPopupEditWindow = class(TCustomControl)
private
FEditor: TWinControl;
FCloseUp: TCloseUpEvent;
procedure WMMouseActivate(var Message: TMessage); message WM_MOUSEACTIVATE;
protected
procedure CreateParams(var Params: TCreateParams); override;
function GetValue: Variant; virtual; abstract;
procedure SetValue(const Value: Variant); virtual; abstract;
procedure InvalidateEditor;
procedure PopupMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure CloseUp(Accept: Boolean); virtual;
public
constructor Create(AOwner: TComponent); override;
function GetPopupText: string; virtual;
procedure Hide;
procedure Show(Origin: TPoint);
property OnCloseUp: TCloseUpEvent read FCloseUp write FCloseUp;
end;
{ TPopupEditWindow }
constructor TPopupEditWindow.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FEditor := TWinControl(AOwner);
ControlStyle := ControlStyle + [csNoDesignVisible, csReplicatable,
csAcceptsControls];
Ctl3D := False;
ParentCtl3D := False;
Visible := False;
Parent := FEditor;
OnMouseUp := PopupMouseUp;
end;
procedure TPopupEditWindow.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
with Params do
begin
Style := WS_POPUP or WS_BORDER or WS_CLIPCHILDREN;
ExStyle := WS_EX_TOOLWINDOW;
WindowClass.Style := WindowClass.Style or CS_SAVEBITS;
end;
end;
procedure TPopupEditWindow.WMMouseActivate(var Message: TMessage);
begin
Message.Result := MA_NOACTIVATE;
end;
function TPopupEditWindow.GetPopupText: string;
begin
Result := '';
end;
procedure TPopupEditWindow.InvalidateEditor;
var
R: TRect;
begin
if (FEditor is TCustomPopupEdit) then
begin
with TCustomPopupEdit(FEditor) do
SetRect(R, 0, 0, ClientWidth - FBtnControl.Width - 2, ClientHeight + 1);
end
else
R := FEditor.ClientRect;
InvalidateRect(FEditor.Handle, @R, False);
UpdateWindow(FEditor.Handle);
end;
procedure TPopupEditWindow.PopupMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if Button = mbLeft then
CloseUp(PtInRect(Self.ClientRect, Point(X, Y)));
end;
procedure TPopupEditWindow.CloseUp(Accept: Boolean);
begin
if Assigned(FCloseUp) then
FCloseUp(Self, Accept);
end;
procedure TPopupEditWindow.Hide;
begin
SetWindowPos(Handle, 0, 0, 0, 0, 0, SWP_NOZORDER or
SWP_NOMOVE or SWP_NOSIZE or SWP_NOACTIVATE or SWP_HIDEWINDOW);
Visible := False;
end;
procedure TPopupEditWindow.Show(Origin: TPoint);
begin
SetWindowPos(Handle, HWND_TOP, Origin.X, Origin.Y, 0, 0,
SWP_NOACTIVATE or SWP_SHOWWINDOW or SWP_NOSIZE);
Visible := True;
end;
{ TLocCalendar }
type
TLocCalendar = class(TCalendar)
private
procedure CMEnabledChanged(var Message: TMessage); message CM_ENABLEDCHANGED;
procedure CMParentColorChanged(var Message: TMessage); message CM_PARENTCOLORCHANGED;
protected
procedure CreateParams(var Params: TCreateParams); override;
procedure DrawCell(ACol, ARow: Longint; ARect: TRect; AState: TGridDrawState); override;
public
constructor Create(AOwner: TComponent); override;
procedure MouseToCell(X, Y: Integer; var ACol, ARow: Longint);
property GridLineWidth;
property DefaultColWidth;
property DefaultRowHeight;
end;
constructor TLocCalendar.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle := [csCaptureMouse, csClickEvents, csDoubleClicks];
ControlStyle := ControlStyle + [csReplicatable];
Ctl3D := False;
Enabled := False;
BorderStyle := forms.bsNone;
ParentColor := True;
CalendarDate := Trunc(Now);
UseCurrentDate := False;
FixedColor := Self.Color;
Options := [goFixedHorzLine];
TabStop := False;
Color := clWhite;
end;
procedure TLocCalendar.CMParentColorChanged(var Message: TMessage);
begin
inherited;
if ParentColor then FixedColor := Self.Color;
end;
procedure TLocCalendar.CMEnabledChanged(var Message: TMessage);
begin
if HandleAllocated and not (csDesigning in ComponentState) then
EnableWindow(Handle, True);
end;
procedure TLocCalendar.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
with Params do
Style := Style and not (WS_BORDER or WS_TABSTOP or WS_DISABLED);
end;
procedure TLocCalendar.MouseToCell(X, Y: Integer; var ACol, ARow: Longint);
var
Coord: TGridCoord;
begin
Coord := MouseCoord(X, Y);
ACol := Coord.X;
ARow := Coord.Y;
end;
procedure TLocCalendar.DrawCell(ACol, ARow: Longint; ARect: TRect;
AState: TGridDrawState);
var
D, M, Y: Word;
begin
if (ARow > 0) and ((ACol + StartOfWeek) in [0, 6]) then
Canvas.Font.Color := clRed
else
Canvas.Font.Color := Font.Color;
inherited DrawCell(ACol, ARow, ARect, AState);
DecodeDate(CalendarDate, Y, M, D);
D := StrToIntDef(CellText[ACol, ARow], 0);
if (D > 0) and (D <= DaysPerMonth(Y, M)) then
begin
if (EncodeDate(Y, M, D) = SysUtils.Date) then
Frame3D(Canvas, ARect, clBtnShadow, clBtnHighlight, 1);
end;
end;
{ TPopupEditCalendar }
type
TPopupEditCalendar = class(TPopupEditWindow)
private
FCalendar: TCalendar;
FTitleLabel: TLabel;
FFourDigitYear: Boolean;
FBtns: array[0..3] of TImage{TSpeedButton};
procedure CalendarMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure PrevMonthBtnClick(Sender: TObject);
procedure NextMonthBtnClick(Sender: TObject);
procedure PrevYearBtnClick(Sender: TObject);
procedure NextYearBtnClick(Sender: TObject);
procedure CalendarChange(Sender: TObject);
procedure TopPanelDblClick(Sender: TObject);
protected
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure KeyPress(var Key: Char); override;
function GetValue: Variant; override;
procedure SetValue(const Value: Variant); override;
public
constructor Create(AOwner: TComponent); override;
end;
constructor TPopupEditCalendar.Create(AOwner: TComponent);
const
BtnSide = 14;
PopupCalendarSize: TPoint = (X: 187; Y: 124);
SBtnGlyphs: array[0..3] of PChar = ('PREV2', 'PREV1', 'NEXT1', 'NEXT2');
var
Control, BackPanel: TWinControl;
NonClientMetrics: TNonClientMetrics;
begin
inherited Create(AOwner);
FFourDigitYear := True;//FourDigitYear;
{ Height := Max(PopupCalendarSize.Y, 120);
Width := Max(PopupCalendarSize.X, 180);
}
Height := 120;
Width := 150;
Color := clBtnFace;
NonClientMetrics.cbSize := SizeOf(NonClientMetrics);
if SystemParametersInfo(SPI_GETNONCLIENTMETRICS, 0, @NonClientMetrics, 0) then
Font.Handle := CreateFontIndirect(NonClientMetrics.lfMessageFont)
else
begin
Font.Color := clWindowText;
Font.Name := 'MS Sans Serif';
Font.Size := 8;
Font.Style := [];
end;
if AOwner is TControl then
ShowHint := TControl(AOwner).ShowHint
else
ShowHint := True;
if (csDesigning in ComponentState) then Exit;
BackPanel := TPanel.Create(Self);
with BackPanel as TPanel do
begin
Parent := Self;
Align := alClient;
ParentColor := True;
ControlStyle := ControlStyle + [csReplicatable];
Color := clTeal;
end;
Control := TPanel.Create(Self);
with Control as TPanel do
begin
Parent := BackPanel;
Align := alTop;
Width := Self.Width - 4;
Height := 18;
BevelOuter := bvNone;
ParentColor := True;
ControlStyle := ControlStyle + [csReplicatable];
end;
FCalendar := TLocCalendar.Create(Self);
with TLocCalendar(FCalendar) do
begin
Parent := BackPanel;
Align := alClient;
OnChange := CalendarChange;
OnMouseUp := CalendarMouseUp;
end;
FBtns[0] := TImage{TSpeedButton}.Create(Self);
with FBtns[0] do
begin
Parent := Control;
// SetBounds(-1, -1, BtnSide, BtnSide);
SetBounds(0, 0, BtnSide, BtnSide);
// Glyph.Handle := LoadBitmap(hInstance, SBtnGlyphs[0]);
Picture.Bitmap.Handle := LoadBitmap(hInstance, SBtnGlyphs[0]);
OnClick := PrevYearBtnClick;
Color := (BackPanel as TPanel).Color;
Hint := SPrevYear;
end;
FBtns[1] := TImage{TSpeedButton}.Create(Self);
with FBtns[1] do
begin
Parent := Control;
// SetBounds(BtnSide - 2, -1, BtnSide, BtnSide);
SetBounds(BtnSide - 1, 0, BtnSide, BtnSide);
// Glyph.Handle := LoadBitmap(hInstance, SBtnGlyphs[1]);
Picture.Bitmap.Handle := LoadBitmap(hInstance, SBtnGlyphs[1]);
OnClick := PrevMonthBtnClick;
Hint := SPrevMonth;
end;
FTitleLabel := TLabel.Create(Self);
with FTitleLabel do
begin
Parent := Control;
AutoSize := False;
Alignment := taCenter;
SetBounds(BtnSide * 2 + 1, 1, Control.Width - 4 * BtnSide - 2, 14);
// Transparent := True;
Transparent := False;
Color := (BackPanel as TPanel).Color;
OnDblClick := TopPanelDblClick;
ControlStyle := ControlStyle + [csReplicatable];
Font.Color := clWhite;
Font.Style := [fsBold];
end;
FBtns[2] := TImage{TSpeedButton}.Create(Self);
with FBtns[2] do
begin
Parent := Control;
// SetBounds(Control.Width - 2 * BtnSide + 2, -1, BtnSide, BtnSide);
SetBounds(Control.Width - 2 * BtnSide + 1, 0, BtnSide, BtnSide);
// Glyph.Handle := LoadBitmap(hInstance, SBtnGlyphs[2]);
Picture.Bitmap.Handle := LoadBitmap(hInstance, SBtnGlyphs[2]);
OnClick := NextMonthBtnClick;
Hint := SNextMonth;
end;
FBtns[3] := TImage{TSpeedButton}.Create(Self);
with FBtns[3] do
begin
Parent := Control;
// SetBounds(Control.Width - BtnSide + 1, -1, BtnSide, BtnSide);
SetBounds(Control.Width - BtnSide, 0, BtnSide, BtnSide);
// Glyph.Handle := LoadBitmap(hInstance, SBtnGlyphs[3]);
Picture.Bitmap.Handle := LoadBitmap(hInstance, SBtnGlyphs[3]);
OnClick := NextYearBtnClick;
Hint := SNextYear;
end;
end;
procedure TPopupEditCalendar.CalendarMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
Col, Row: Longint;
begin
if (Button = mbLeft) and (Shift = []) then
begin
TLocCalendar(FCalendar).MouseToCell(X, Y, Col, Row);
if (Row > 0) and (FCalendar.CellText[Col, Row] <> '') then
CloseUp(True);
end;
end;
procedure TPopupEditCalendar.TopPanelDblClick(Sender: TObject);
begin
FCalendar.CalendarDate := Trunc(Now);
end;
procedure TPopupEditCalendar.KeyDown(var Key: Word; Shift: TShiftState);
begin
inherited KeyDown(Key, Shift);
if FCalendar <> nil then
case Key of
VK_NEXT:
begin
if ssCtrl in Shift then
FCalendar.NextYear
else
FCalendar.NextMonth;
end;
VK_PRIOR:
begin
if ssCtrl in Shift then
FCalendar.PrevYear
else
FCalendar.PrevMonth;
end;
else
TLocCalendar(FCalendar).KeyDown(Key, Shift);
end;
end;
procedure TPopupEditCalendar.KeyPress(var Key: Char);
begin
inherited KeyPress(Key);
// if (FCalendar <> nil) and (Key <> #0) then
// FCalendar.KeyPress(Key);
end;
function TPopupEditCalendar.GetValue: Variant;
begin
if (csDesigning in ComponentState) then
Result := VarFromDateTime(SysUtils.Date)
else
Result := VarFromDateTime(FCalendar.CalendarDate);
end;
procedure TPopupEditCalendar.SetValue(const Value: Variant);
begin
if not (csDesigning in ComponentState) then
begin
try
{ if (Trim(ReplaceStr(VarToStr(Value), DateSeparator, '')) = '') or
VarIsNull(Value) or VarIsEmpty(Value) then
FCalendar.CalendarDate := VarToDateTime(SysUtils.Date)
else
FCalendar.CalendarDate := VarToDateTime(Value);
} CalendarChange(nil);
except
FCalendar.CalendarDate := VarToDateTime(SysUtils.Date);
end;
end;
end;
procedure TPopupEditCalendar.PrevYearBtnClick(Sender: TObject);
begin
FCalendar.PrevYear;
end;
procedure TPopupEditCalendar.NextYearBtnClick(Sender: TObject);
begin
FCalendar.NextYear;
end;
procedure TPopupEditCalendar.PrevMonthBtnClick(Sender: TObject);
begin
FCalendar.PrevMonth;
end;
procedure TPopupEditCalendar.NextMonthBtnClick(Sender: TObject);
begin
FCalendar.NextMonth;
end;
procedure TPopupEditCalendar.CalendarChange(Sender: TObject);
begin
FTitleLabel.Caption := FormatDateTime('MMMM, YYYY', FCalendar.CalendarDate);
end;
{ TCustomEditButton }
constructor TCustomEditButton.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FTransparent := False;
FPainting := False;
FAutoComplete := [];
FAlignment := taLeftJustify;
Flat := False;
FBtnControl := TWinControl.Create(Self);
with FBtnControl do
ControlStyle := ControlStyle + [csReplicatable];
FBtnControl.Width := 0; //DefEditBtnWidth;
FBtnControl.Height := 17;
FBtnControl.Visible := True;
FBtnControl.Parent := Self;
FButton := TSpeedButton.Create(Self);
FButton.SetBounds(0, 0, FBtnControl.Width, FBtnControl.Height);
FButton.Visible := True;
FButton.Parent := FBtnControl;
FButton.OnClick := EditButtonClick;
Height := 21;
FButtonStyle := bsNone;
FButtonKey := scAlt + vk_Down;
end;
destructor TCustomEditButton.Destroy;
begin
FButton.OnClick := nil;
inherited Destroy;
end;
procedure TCustomEditButton.CreateParams(var Params: TCreateParams);
const Alignments: array[TAlignment] of dWord =
(ES_LEFT, ES_RIGHT, ES_CENTER);
Multilines: array[Boolean] of dWord = (0, ES_MULTILINE);
begin
inherited CreateParams(Params);
Params.Style := Params.Style or
Multilines[PasswordChar = #0] or
Alignments[FAlignment];
end;
procedure TCustomEditButton.CreateWnd;
const
SHACF_AUTOSUGGEST_FORCE_ON = $10000000;
SHACF_AUTOSUGGEST_FORCE_OFF = $20000000;
SHACF_AUTOAPPEND_FORCE_ON = $40000000;
SHACF_AUTOAPPEND_FORCE_OFF = $80000000;
SHACF_DEFAULT = $0;
SHACF_FILESYSTEM = $1;
SHACF_URLHISTORY = $2;
SHACF_URLMRU = $4;
SHACF_URLALL = SHACF_URLHISTORY or SHACF_URLMRU;
var
Options: dWord;
begin
inherited CreateWnd;
SetEditRect;
if (dllShlwApi <> 0) and
(FAutoComplete <> []) and
(@ShAutoComplete <> nil) then
begin
Options := 0;
if (mcAutoSuggest in FAutoComplete) then
Options := Options or SHACF_AUTOSUGGEST_FORCE_ON;
if (mcAutoAppend in FAutoComplete) then
Options := Options or SHACF_AUTOAPPEND_FORCE_ON;
if (mcFileSystem in FAutoComplete) then
Options := Options or SHACF_FILESYSTEM;
if (mcUrlHistory in FAutoComplete) then
Options := Options or SHACF_URLHISTORY;
if (mcUrlMRU in FAutoComplete) then
Options := Options or SHACF_URLMRU;
SHAutoComplete(Handle, Options);
end;
end;
procedure TCustomEditButton.SetTransparent(Value: Boolean);
begin
if FTransparent <> Value then
begin
FTransparent := Value;
Invalidate;
end;
end;
procedure TCustomEditButton.SetFlat(Value: Boolean);
begin
if FFlat <> Value then
begin
FFlat := Value;
if Value then
begin
BorderStyle := TBorderStyle(bsNone);
ControlStyle := ControlStyle - [csFramed]; {fixes a VCL bug with Win 3.x}
end
else
begin
BorderStyle := bsSingle;
// ControlStyle := ControlStyle + [csFramed];
end;
Ctl3D := not Value;
end;
end;
procedure TCustomEditButton.WMEraseBkGnd(var Message: TWMEraseBkGnd);
var
canvas: TCanvas;
begin
canvas := TCanvas.create;
try
canvas.Handle := message.dc;
if FTransparent and
not (csDesigning in ComponentState) then
PaintParent(Canvas)
else
begin
canvas.Brush.Color := Color;
canvas.Brush.Style := bsSolid;
canvas.FillRect(ClientRect);
end
finally
canvas.free;
end;
end;
procedure TCustomEditButton.WMPaint(var Message: TWMPaint);
begin
inherited;
if FTransparent then
if not FPainting then
RepaintWindow;
end;
procedure TCustomEditButton.CNCtlColorEdit(var Message: TWMCtlColorEdit);
begin
inherited;
if FTransparent then
SetBkMode(Message.ChildDC, 1);
end;
procedure TCustomEditButton.CNCtlColorStatic(var Message: TWMCtlColorStatic);
begin
inherited;
if FTransparent then
SetBkMode(Message.ChildDC, 1);
end;
procedure TCustomEditButton.CMParentColorChanged(var Message: TMessage);
begin
inherited;
if FTransparent then
Invalidate;
end;
procedure TCustomEditButton.WMMove(var Message: TWMMove);
var
r: TRect;
begin
inherited;
Invalidate;
r := ClientRect;
InvalidateRect(Handle, @r, False);
end;
procedure TCustomEditButton.RepaintWindow;
const
BorderRec: array[TBorderStyle] of Integer = (1, -1);
var
DC: hDC;
TmpBitmap, Bitmap: hBitmap;
begin
if FTransparent then
begin
FPainting := True;
HideCaret(Handle);
DC := CreateCompatibleDC(GetDC(Handle));
TmpBitmap := CreateCompatibleBitmap(GetDC(Handle), Succ(ClientWidth), Succ(ClientHeight));
Bitmap := SelectObject(DC, TmpBitmap);
PaintTo(DC, 0, 0);
{$IFDEF SMForDelphi5}
BitBlt(GetDC(Handle), BorderRec[BorderStyle] + BorderWidth, BorderRec[BorderStyle] + BorderWidth, ClientWidth, ClientHeight, DC, 1, 1, SRCCOPY);
{$ELSE}
BitBlt(GetDC(Handle), BorderRec[BorderStyle], BorderRec[BorderStyle], ClientWidth, ClientHeight, DC, 1, 1, SRCCOPY);
{$ENDIF}
SelectObject(DC, Bitmap);
DeleteDC(DC);
ReleaseDC(Handle, GetDC(Handle));
DeleteObject(TmpBitmap);
ShowCaret(Handle);
FPainting := False;
end;
end;
procedure TCustomEditButton.Change;
begin
RepaintWindow;
inherited Change;
end;
type
THackWinControl = class(TWinControl);
procedure TCustomEditButton.PaintParent(ACanvas: TCanvas);
var
i, Count, X, Y, SaveIndex: Integer;
DC: Cardinal;
R, SelfR, CtlR: TRect;
Control: TControl;
begin
Control := Self;
if Control.Parent = nil then Exit;
Count := Control.Parent.ControlCount;
DC := ACanvas.Handle;
SelfR := Bounds(Control.Left, Control.Top, Control.Width, Control.Height);
X := -Control.Left; Y := -Control.Top;
// Copy parent control image
SaveIndex := SaveDC(DC);
SetViewportOrgEx(DC, X, Y, nil);
IntersectClipRect(DC, 0, 0, Control.Parent.ClientWidth, Control.Parent.ClientHeight);
with THackWinControl(Control.Parent) do
begin
Perform(WM_ERASEBKGND, DC, 0);
PaintWindow(DC);
end;
RestoreDC(DC, SaveIndex);
//Copy images of graphic controls
for i := 0 to Count - 1 do
begin
if (Control.Parent.Controls[i] <> nil) then
begin
if Control.Parent.Controls[i] = Control then break;
with Control.Parent.Controls[i] do
begin
CtlR := Bounds(Left, Top, Width, Height);
if Bool(IntersectRect(R, SelfR, CtlR)) and Visible then
begin
SaveIndex := SaveDC(DC);
SetViewportOrgEx(DC, Left + X, Top + Y, nil);
IntersectClipRect(DC, 0, 0, Width, Height);
Perform(WM_ERASEBKGND,DC,0);
Perform(WM_PAINT, integer(DC), 0);
RestoreDC(DC, SaveIndex);
end;
end;
end;
end;
end;
procedure TCustomEditButton.CMMouseEnter(var Message: TMessage);
begin
inherited;
if Flat then
begin
MouseInControl := True;
RedrawBorder(0);
end;
end;
procedure TCustomEditButton.CMMouseLeave(var Message: TMessage);
begin
inherited;
if Flat then
begin
MouseInControl := False;
RedrawBorder(0);
end;
end;
procedure TCustomEditButton.NewAdjustHeight;
var
DC: HDC;
SaveFont: HFONT;
Metrics: TTextMetric;
begin
DC := GetDC(0);
SaveFont := SelectObject(DC, Font.Handle);
GetTextMetrics(DC, Metrics);
SelectObject(DC, SaveFont);
ReleaseDC(0, DC);
Height := Metrics.tmHeight + 6;
end;
procedure TCustomEditButton.Loaded;
begin
inherited Loaded;
if not (csDesigning in ComponentState) and Flat then
NewAdjustHeight;
end;
procedure TCustomEditButton.CMEnabledChanged(var Message: TMessage);
const
EnableColors: array[Boolean] of TColor = (clBtnFace, clWindow);
begin
inherited;
if Flat then
Color := EnableColors[Enabled];
end;
procedure TCustomEditButton.CMFontChanged(var Message: TMessage);
begin
inherited;
if not ((csDesigning in ComponentState) and (csLoading in ComponentState)) and Flat then
NewAdjustHeight;
end;
procedure TCustomEditButton.WMSetFocus(var Message: TWMSetFocus);
begin
inherited;
if not (csDesigning in ComponentState) and Flat then
RedrawBorder(0);
end;
procedure TCustomEditButton.WMKillFocus(var Message: TWMKillFocus);
begin
inherited;
if not(csDesigning in ComponentState) and Flat then
RedrawBorder(0);
end;
procedure TCustomEditButton.WMNCCalcSize(var Message: TWMNCCalcSize);
begin
inherited;
if Flat then
InflateRect(Message.CalcSize_Params^.rgrc[0], -3, -3);
end;
procedure TCustomEditButton.WMNCPaint(var Message: TMessage);
begin
inherited;
if Flat then
RedrawBorder(Message.WParam);
end;
procedure TCustomEditButton.RedrawBorder(const Clip: HRGN);
var
DC: HDC;
R: TRect;
NewClipRgn: HRGN;
BtnFaceBrush, WindowBrush: HBRUSH;
begin
DC := GetWindowDC(Handle);
try
{ Use update region }
if Clip <> 0 then
begin
GetWindowRect(Handle, R);
{ An invalid region is generally passed when the window is first created }
if SelectClipRgn(DC, Clip) = ERROR then {ERROR = 0 in Windows.Pas}
begin
NewClipRgn := CreateRectRgnIndirect(R);
SelectClipRgn(DC, NewClipRgn);
DeleteObject(NewClipRgn);
end;
OffsetClipRgn(DC, -R.Left, -R.Top);
end;
GetWindowRect(Handle, R);
OffsetRect(R, -R.Left, -R.Top);
BtnFaceBrush := CreateSolidBrush(GetSysColor(COLOR_BTNFACE));
WindowBrush := CreateSolidBrush(GetSysColor(COLOR_WINDOW));
if ((csDesigning in ComponentState) and Enabled) or
(not(csDesigning in ComponentState) and
(Focused or (MouseInControl and not (Screen.ActiveControl is TCustomEditButton)))) then
begin
DrawEdge(DC, R, BDR_SUNKENOUTER, BF_RECT or BF_ADJUST);
FrameRect(DC, R, BtnFaceBrush);
InflateRect(R, -1, -1);
FrameRect(DC, R, WindowBrush);
end
else
begin
FrameRect(DC, R, BtnFaceBrush);
InflateRect(R, -1, -1);
FrameRect(DC, R, BtnFaceBrush);
InflateRect(R, -1, -1);
FrameRect(DC, R, WindowBrush);
end;
DeleteObject(WindowBrush);
DeleteObject(BtnFaceBrush);
finally
ReleaseDC(Handle, DC);
end;
end;
function TCustomEditButton.GetPasswordChar: Char;
begin
Result := inherited PasswordChar;
end;
procedure TCustomEditButton.SetPasswordChar(Value: Char);
begin
if PasswordChar <> Value then
begin
inherited PasswordChar := Value;
RecreateWnd;
end;
end;
procedure TCustomEditButton.SetAlignment(Value: TAlignment);
begin
if FAlignment <> Value then
begin
FAlignment := Value;
RecreateWnd;
end;
end;
function TCustomEditButton.GetButtonWidth: Integer;
begin
Result := FButton.Width;
end;
procedure TCustomEditButton.SetButtonWidth(Value: Integer);
begin
if (csCreating in ControlState) then
begin
FBtnControl.Width := Value;
FButton.Width := Value;
RecreateGlyph;
end
else
if (Value <> ButtonWidth) and (Value < ClientWidth) then
begin
FButton.Width := Value;
if HandleAllocated then RecreateWnd;
RecreateGlyph;
end;
end;
function TCustomEditButton.GetButtonHint: string;
begin
Result := FButton.Hint;
end;
procedure TCustomEditButton.SetButtonHint(const Value: string);
begin
FButton.Hint := Value;
end;
function TCustomEditButton.GetButtonFlat: Boolean;
begin
Result := FButton.Flat;
end;
procedure TCustomEditButton.SetButtonFlat(Value: Boolean);
begin
FButton.Flat := Value;
end;
function TCustomEditButton.GetGlyph: TBitmap;
begin
Result := FButton.Glyph;
end;
procedure TCustomEditButton.SetGlyph(Value: TBitmap);
begin
FButton.Glyph := Value;
// FButtonStyle := bsCustom;
end;
function TCustomEditButton.GetNumGlyphs: TNumGlyphs;
begin
Result := FButton.NumGlyphs;
end;
procedure TCustomEditButton.SetNumGlyphs(Value: TNumGlyphs);
begin
if FButtonStyle in [bsDropDown, bsEllipsis, bsCalculator, bsCalendar, bsFile, bsDirectory] then
FButton.NumGlyphs := 1
else
FButton.NumGlyphs := Value;
end;
procedure TCustomEditButton.EditButtonClick(Sender: TObject);
begin
ButtonClick;
end;
procedure TCustomEditButton.ButtonClick;
begin
if (ButtonWidth > 0) and Assigned(FOnButtonClick) then
FOnButtonClick(Self)
end;
procedure TCustomEditButton.SetButtonStyle(Value: TSMButtonStyle);
begin
if (FButtonStyle <> Value) then
begin
FButtonStyle := Value;
if (FButtonStyle = bsNone) or
((FButtonStyle = bsCustom) and (csReading in ComponentState)) then
Glyph := nil;
RecreateGlyph;
case FButtonStyle of
bsNone: FButton.Width := 0;
bsDropDown: ButtonWidth := GetSystemMetrics(SM_CXVSCROLL);
bsCalculator, bsCalendar: ButtonWidth := 17;
else
ButtonWidth := DefEditBtnWidth;
end;
end;
end;
procedure TCustomEditButton.RecreateGlyph;
function CreateEllipsisGlyph: TBitmap;
var
W, G, I: Integer;
begin
Result := TBitmap.Create;
with Result do
try
Monochrome := True;
Width := Max(1, FButton.Width - 6);
Height := 4;
W := 2;
G := (Result.Width - 3 * W) div 2;
if G <= 0 then G := 1;
if G > 3 then G := 3;
I := (Width - 3 * W - 2 * G) div 2;
PatBlt(Canvas.Handle, I, 1, W, W, BLACKNESS);
PatBlt(Canvas.Handle, I + G + W, 1, W, W, BLACKNESS);
PatBlt(Canvas.Handle, I + 2 * G + 2 * W, 1, W, W, BLACKNESS);
except
Free;
raise;
end;
end;
var
NewGlyph: TBitmap;
begin
case FButtonStyle of
bsDropDown: FButton.Glyph.Handle := LoadBitmap(0, PChar(32738));
bsEllipsis: begin
NewGlyph := CreateEllipsisGlyph;
try
FButton.Glyph := NewGlyph;
finally
NewGlyph.Destroy;
end;
end;
bsCalculator: FButton.Glyph.Handle := LoadBitmap(hInstance, 'CALCULATORBMP');
bsCalendar: FButton.Glyph.Handle := LoadBitmap(hInstance, 'CALENDARBMP');
bsFile: FButton.Glyph.Handle := LoadBitmap(hInstance, 'FILEBMP');
bsDirectory: FButton.Glyph.Handle := LoadBitmap(hInstance, 'DIRECTORYBMP');
bsOk: FButton.Glyph.Handle := LoadBitmap(hInstance, 'OKBMP');
bsCancel: FButton.Glyph.Handle := LoadBitmap(hInstance, 'CANCELBMP');
bsFind: FButton.Glyph.Handle := LoadBitmap(hInstance, 'FINDBMP');
bsSearch: FButton.Glyph.Handle := LoadBitmap(hInstance, 'SEARCHBMP');
bsSum: FButton.Glyph.Handle := LoadBitmap(hInstance, 'SUMBMP');
end;
if (FButtonStyle <> bsCustom) then
NumGlyphs := 1;
end;
procedure TCustomEditButton.SetEditRect;
var
Loc: TRect;
begin
SetRect(Loc, 0, 1{0}, ClientWidth - FBtnControl.Width {- 2}, ClientHeight {+ 1});
SendMessage(Handle, EM_SETRECTNP, 0, LongInt(@Loc));
end;
procedure TCustomEditButton.UpdateBtnBounds;
begin
if NewStyleControls then
begin
if Ctl3D or Flat then
// FBtnControl.SetBounds(Width - FButton.Width - 4, 0, FButton.Width, Height - 4)
FBtnControl.SetBounds(ClientWidth - FButton.Width, 0, FButton.Width, ClientHeight)
else
// FBtnControl.SetBounds(Width - FButton.Width - 2, 2, FButton.Width, Height - 4);
FBtnControl.SetBounds(ClientWidth - FButton.Width - 2, 1, FButton.Width, ClientHeight-2);
end
else
FBtnControl.SetBounds(Width - FButton.Width - 2, 1, FButton.Width, ClientHeight - 2);
FButton.Height := FBtnControl.Height;
SetEditRect;
end;
procedure TCustomEditButton.CMCtl3DChanged(var Message: TMessage);
begin
inherited;
UpdateBtnBounds;
end;
procedure TCustomEditButton.WMSize(var Message: TWMSize);
var
MinHeight: Integer;
r: TRect;
begin
inherited;
r := ClientRect;
InvalidateRect(Handle, @r, False);
if not (csLoading in ComponentState) then
begin
MinHeight := GetMinHeight;
{ text edit bug: if size to less than MinHeight, then edit ctrl does
not display the text }
if Height < MinHeight then
begin
Height := MinHeight;
Exit;
end;
end;
UpdateBtnBounds;
end;
function TCustomEditButton.GetTextHeight: Integer;
var
DC: HDC;
SaveFont: HFont;
SysMetrics, Metrics: TTextMetric;
begin
DC := GetDC(0);
try
GetTextMetrics(DC, SysMetrics);
SaveFont := SelectObject(DC, Font.Handle);
GetTextMetrics(DC, Metrics);
SelectObject(DC, SaveFont);
finally
ReleaseDC(0, DC);
end;
Result := Min(SysMetrics.tmHeight, Metrics.tmHeight);
end;
function TCustomEditButton.GetMinHeight: Integer;
var i: Integer;
begin
i := GetTextHeight;
Result := i + GetSystemMetrics(SM_CYBORDER) * 4 + 1 + (i div 4);
end;
procedure TCustomEditButton.CMEnter(var Message: TCMEnter);
begin
inherited;
if AutoSelect then
SendMessage(Handle, EM_SETSEL, 0, -1);
end;
procedure TCustomEditButton.KeyDown(var Key: Word; Shift: TShiftState);
begin
inherited KeyDown(Key, Shift);
if (FButtonKey = ShortCut(Key, Shift)) and (ButtonWidth > 0) then
begin
EditButtonClick(Self);
Key := 0;
end;
end;
{ TCustomPopupEdit }
constructor TCustomPopupEdit.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FPopupColor := clBtnFace;
FPopupAlign := epaRight;
FPopup := nil;
end;
destructor TCustomPopupEdit.Destroy;
begin
DestroyCalendarPopup;
inherited Destroy;
end;
procedure TCustomPopupEdit.CreateCalendarPopup;
begin
FPopup := nil;
if (csDesigning in ComponentState) then exit;
FPopup := TPopupEditWindow(TPopupEditCalendar.Create(Self));
with TPopupEditWindow(FPopup) do
begin
OnCloseUp := PopupCloseUp;
Color := FPopupColor;
end;
end;
procedure TCustomPopupEdit.DestroyCalendarPopup;
begin
if FPopup <> nil then
begin
TPopupEditWindow(FPopup).OnCloseUp := nil;
FPopup.Free;
FPopup := nil;
end
end;
function TCustomPopupEdit.GetPopupColor: TColor;
begin
if FPopup <> nil then
Result := TPopupEditWindow(FPopup).Color
else
Result := FPopupColor;
end;
procedure TCustomPopupEdit.SetPopupColor(Value: TColor);
begin
if Value <> PopupColor then
begin
if FPopup <> nil then
TPopupEditWindow(FPopup).Color := Value;
FPopupColor := Value;
end;
end;
function TCustomPopupEdit.GetDirectInput: Boolean;
begin
Result := FDirectInput;
end;
procedure TCustomPopupEdit.SetDirectInput(Value: Boolean);
begin
inherited ReadOnly := not Value or ReadOnly;
FDirectInput := Value;
end;
procedure TCustomPopupEdit.HidePopup;
begin
TPopupEditWindow(FPopup).Hide;
end;
procedure TCustomPopupEdit.ShowPopup(Origin: TPoint);
begin
TPopupEditWindow(FPopup).Show(Origin);
end;
procedure TCustomPopupEdit.PopupDropDown(DisableEdit: Boolean);
var
P: TPoint;
Y: Integer;
begin
if (FPopup <> nil) and not (ReadOnly or FPopupVisible) then
begin
P := Parent.ClientToScreen(Point(Left, Top));
Y := P.Y + Height;
if Y + FPopup.Height > Screen.Height then
Y := P.Y - FPopup.Height;
case FPopupAlign of
epaRight:
begin
Dec(P.X, FPopup.Width - Width);
if P.X < 0 then Inc(P.X, FPopup.Width - Width);
end;
epaLeft:
begin
if P.X + FPopup.Width > Screen.Width then
Dec(P.X, FPopup.Width - Width);
end;
end;
if P.X < 0 then
P.X := 0
else
if P.X + FPopup.Width > Screen.Width then
P.X := Screen.Width - FPopup.Width;
if Text <> '' then
SetPopupValue(Text)
else
SetPopupValue(Null);
if CanFocus then
SetFocus;
ShowPopup(Point(P.X, Y));
FPopupVisible := True;
if DisableEdit then
begin
// inherited ReadOnly := True;
HideCaret(Handle);
end;
end;
end;
procedure TCustomPopupEdit.SetShowCaret;
const
CaretWidth: array[Boolean] of Byte = (1, 2);
begin
CreateCaret(Handle, 0, CaretWidth[fsBold in Font.Style], ClientHeight-5{GetTextHeight});
ShowCaret(Handle);
end;
procedure TCustomPopupEdit.PopupCloseUp(Sender: TObject; Accept: Boolean);
var
AValue: Variant;
begin
if (FPopup <> nil) and FPopupVisible then
begin
if GetCapture <> 0 then
SendMessage(GetCapture, WM_CANCELMODE, 0, 0);
AValue := GetPopupValue;
HidePopup;
try
try
if CanFocus then
begin
SetFocus;
if GetFocus = Handle then
SetShowCaret;
end;
except
{ ignore exceptions }
end;
// SetDirectInput(DirectInput);
Invalidate;
if Accept and AcceptPopup(AValue) and EditCanModify then
begin
if (Self is TEditTyped) then
AcceptValue(TEditTyped(Self).ConvertValue(AValue))
else
AcceptValue(AValue);
if FFocused then
inherited SelectAll;
end;
finally
FPopupVisible := False;
end;
end;
end;
procedure TCustomPopupEdit.UpdatePopupVisible;
begin
FPopupVisible := (FPopup <> nil) and FPopup.Visible;
end;
function TCustomPopupEdit.AcceptPopup(var Value: Variant): Boolean;
begin
Result := True;
end;
function TCustomPopupEdit.GetPopupValue: Variant;
begin
if FPopup <> nil then
Result := TPopupEditWindow(FPopup).GetValue
else
Result := '';
end;
procedure TCustomPopupEdit.SetPopupValue(const Value: Variant);
begin
if FPopup <> nil then
TPopupEditWindow(FPopup).SetValue(Value);
end;
procedure TCustomPopupEdit.AcceptValue(const Value: Variant);
begin
if Text <> VarToStr(Value) then
begin
Text := Value;
Modified := True;
UpdatePopupVisible;
inherited Change;
end;
end;
function TCustomPopupEdit.GetPopupVisible: Boolean;
begin
Result := (FPopup <> nil) and FPopupVisible;
end;
procedure TCustomPopupEdit.KeyPress(var Key: Char);
begin
if (Key = Char(VK_RETURN)) or (Key = Char(VK_ESCAPE)) then
begin
if PopupVisible then
begin
PopupCloseUp(FPopup, Key = Char(VK_RETURN));
Key := #0;
end
else
begin
{ must catch and remove this, since is actually multi-line }
GetParentForm(Self).Perform(CM_DIALOGKEY, Byte(Key), 0);
if Key = Char(VK_RETURN) then
begin
inherited KeyPress(Key);
Key := #0;
Exit;
end;
end;
end;
inherited KeyPress(Key);
end;
procedure TCustomPopupEdit.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
if (FPopup <> nil) and (Button = mbLeft) then
begin
if CanFocus then
SetFocus;
if not FFocused then Exit;
if FPopupVisible then
PopupCloseUp(FPopup, False);
end;
inherited MouseDown(Button, Shift, X, Y);
end;
procedure TCustomPopupEdit.CMCancelMode(var Message: TCMCancelMode);
begin
if (Message.Sender <> Self) and
(Message.Sender <> FPopup) and
(Message.Sender <> FButton) and
((FPopup <> nil) and
not FPopup.ContainsControl(Message.Sender)) then
PopupCloseUp(FPopup, False);
end;
procedure TCustomPopupEdit.WMKillFocus(var Message: TWMKillFocus);
begin
inherited;
FFocused := False;
PopupCloseUp(FPopup, False);
end;
procedure TCustomPopupEdit.WMSetFocus(var Message: TMessage);
begin
inherited;
FFocused := True;
SetShowCaret;
end;
procedure TCustomPopupEdit.SetButtonStyle(Value: TSMButtonStyle);
begin
if (Value <> FButtonStyle) then
DestroyCalendarPopup;
inherited SetButtonStyle(Value);
if (Value = bsCalendar) then
CreateCalendarPopup;
end;
procedure TCustomPopupEdit.ButtonClick;
begin
inherited ButtonClick;
if FPopup <> nil then
begin
if FPopupVisible then
PopupCloseUp(FPopup, True)
else
PopupDropDown(True);
end;
end;
{ TEditTyped }
constructor TEditTyped.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
SetMaskForEdit;
EnabledTypedLimit := True;
FOldText := '';
end;
procedure TEditTyped.SetMaskForEdit;
begin
EditMask := '';
case FTypeValue of
teString: CharCase := ecNormal;
teStringUpper: CharCase := ecUpperCase;
teStringLower: CharCase := ecLowerCase;
// teNumber: EditMask := '### ### ### ##0.00;1;_';
teDateTime: EditMask := '!99/99/9999 99:99:99;1;_';
teShortDateTime: EditMask := '!99/99/99 99:99:99;1;_';
teDateShortTime: EditMask := '!99/99/9999 99:99;1;_';
teShortDateShortTime: EditMask := '!99/99/99 99:99;1;_';
teDate: EditMask := '!99/99/9999;1;_';
teShortDate: EditMask := '!99/99/99;1;_';
teTime: EditMask := '!90:99:99;1;_';
teShortTime: EditMask := '!99:99;1;_';
tePhone: EditMask := '!\(999\) 999\-9999;1;_';
tePhoneExt: EditMask := '!\(999\) 999\-9999 \x9999;1;_';
teSocial: EditMask := '!999\-99\-9999;1;_';
teZIPCode: EditMask := '!99999\-9999;1;_';
end;
{ if FTypeValue in [teInteger, teNumber] then
SetAlignment(taRightJustify)
else
SetAlignment(taLeftJustify);
}end;
function TEditTyped.GetTypeName: string;
begin
case FTypeValue of
teNumber: Result := etValidNumber;
teInteger: Result := etValidInteger;
teDateTime,
teShortDateTime,
teDateShortTime,
teShortDateShortTime: Result := etValidDateTime;
teDate,
teShortDate: Result := etValidDate;
teTime,
teShortTime: Result := etValidTime;
else
Result := etValid;
end;
end;
procedure TEditTyped.SetMinValue(Value: String);
begin
if FMinValue <> Value then
SetValue(FMinValue, Value);
end;
procedure TEditTyped.SetMaxValue(Value: String);
begin
if FMaxValue <> Value then
SetValue(FMaxValue, Value);
end;
procedure TEditTyped.SetTypeValue(Value: TTypeForEdit);
begin
if FTypeValue <> Value then
begin
FTypeValue := Value;
SetMaskForEdit;
end;
end;
procedure TEditTyped.SetEnabledLimit(Value: Boolean);
begin
if FEnabledLimit <> Value then
FEnabledLimit := Value;
end;
procedure TEditTyped.SetEnabledTypedLimit(Value: Boolean);
begin
if FEnabledTypedLimit <> Value then
FEnabledTypedLimit := Value;
end;
function TEditTyped.ConvertValue(Source: string): Variant;
function Stuff(strStr: string; intIndex, intCount: Integer; strSub: string): string;
begin
Result := strStr;
Delete(Result, intIndex, intCount);
Insert(strSub, Result, intIndex);
end;
var
varForConvert: Variant;
str, strOldMaskEdit, strEditText: string;
begin
Result := Null;
try
{save current editing text}
strEditText := EditText;
Text := Source;
{change a mask for check of the null string}
str := Stuff(EditMask, Length(EditMask)-2, 1, '0');
strOldMaskEdit := EditMask;
ReformatText(str);
str := Text;
ReformatText(strOldMaskEdit);
{restore a saved editing text}
EditText := strEditText;
if (Source = '') or (Trim(str) = '') then
begin
varForConvert := NULL;
{ case FTypeValue of
teNumber,
teInteger: varForConvert := 0;
teDateTime,
teShortDateTime,
teDateShortTime,
teShortDateShortTime: varForConvert := 0;
teDate,
teShortDate: varForConvert := 0;
teTime,
teShortTime: varForConvert := 0;
else
varForConvert := ''
end;
} end
else
begin
case FTypeValue of
teNumber: varForConvert := StrToFloat(Source);
// {$IFDEF VER130}
// teInteger: varForConvert := StrToInt64(Source);
// {$ELSE}
teInteger: varForConvert := StrToInt(Source);
// {$ENDIF}
teDateTime,
teShortDateTime,
teDateShortTime,
teShortDateShortTime: varForConvert := StrToDateTime(Source);
teDate,
teShortDate: varForConvert := StrToDate(Source);
teTime,
teShortTime: varForConvert := StrToTime(Source);
else
varForConvert := Source
end;
end;
Result := varForConvert
except
raise EConvertError.CreateFmt('"%s" %s %s', [Source, etIsNot, GetTypeName()])
end;
end;
function TEditTyped.SetValue(var Dest: String; Source: String): Boolean;
var
varForConvert: Variant;
begin
varForConvert := ConvertValue(Source);
Result := not varIsNull(varForConvert);
if Result then Dest := Source;
end;
procedure TEditTyped.CMEnter(var Message: TCMEnter);
begin
FOldText := Text;
inherited;
end;
procedure TEditTyped.CMExit(var Message: TCMExit);
var
varValue, varMin, varMax: Variant;
strValue: string;
begin
try
if (FEnabledTypedLimit = True) then
SetValue(strValue, Text);
if (FEnabledLimit = True) then
begin
varValue := ConvertValue(Text);
varMin := ConvertValue(FMinValue);
varMax := ConvertValue(FMaxValue);
if ((varValue < varMin) or (varValue > varMax)) then
begin
if not (csDesigning in ComponentState) then
begin
raise ERangeError.CreateFmt(etOutOfRange, [Text, FMinValue, FMaxValue]);
end;
end;
end;
inherited;
except
SetFocus;
raise;
end;
end;
procedure TEditTyped.KeyPress(var Key: Char);
const
Alpha = [#1..#255]; //'A'..'Z', 'a'..'z', '_'];
NumericOnly = ['0'..'9'];
SignOnly = ['-', '+'];
Numeric = SignOnly + NumericOnly;
var
boolCallInherited: Boolean;
frmParent: TCustomForm;
begin
boolCallInherited := True;
if FEnabledTypedLimit and
not {$IFDEF SMForDelphi2009}CharInSet{$ENDIF}(Key {$IFDEF SMForDelphi2009},{$ELSE} in {$ENDIF}[#0, #8, #13]) then
begin
case FTypeValue of
teNumber: begin
if {$IFDEF SMForDelphi2009}CharInSet{$ENDIF}(Key {$IFDEF SMForDelphi2009},{$ELSE} in {$ENDIF}['.', ',']) then
Key := {$IFDEF SMForDelphiXE3}FormatSettings.{$ENDIF}DecimalSeparator;
boolCallInherited := (((Key = {$IFDEF SMForDelphiXE3}FormatSettings.{$ENDIF}DecimalSeparator) or
{$IFDEF SMForDelphi2009}CharInSet{$ENDIF}(Key {$IFDEF SMForDelphi2009},{$ELSE} in {$ENDIF}SignOnly)) and
(Pos(Key, Text) = 0)) or
{$IFDEF SMForDelphi2009}CharInSet{$ENDIF}(Key {$IFDEF SMForDelphi2009},{$ELSE} in {$ENDIF}Numeric + ['E', 'e']);
end;
teInteger: boolCallInherited := ({$IFDEF SMForDelphi2009}CharInSet{$ENDIF}(Key {$IFDEF SMForDelphi2009},{$ELSE} in {$ENDIF}SignOnly) and
(Pos(Key, Text) = 0)) or
{$IFDEF SMForDelphi2009}CharInSet{$ENDIF}(Key {$IFDEF SMForDelphi2009},{$ELSE} in {$ENDIF}Numeric);
teDateTime,
teShortDateTime,
teDateShortTime,
teShortDateShortTime,
teDate,
teShortDate,
teTime,
teShortTime: boolCallInherited := {$IFDEF SMForDelphi2009}CharInSet{$ENDIF}(Key {$IFDEF SMForDelphi2009},{$ELSE} in {$ENDIF}Numeric);
end;
end;
if boolCallInherited then
begin
if (Key = Char(VK_RETURN)) then
begin
frmParent := GetParentForm(Self);
SendMessage(frmParent.Handle, WM_NEXTDLGCTL, 0, 0);
Key := #0;
end
end
else
begin
MessageBeep(0);
Key := #0;
end;
inherited KeyPress(Key);
end;
function TEditTyped.GetValue: Variant;
begin
Result := ConvertValue(Text);
end;
function TEditTyped.IsChanged: Boolean;
begin
Result := (Text <> FOldText);
end;
initialization
dllShlwApi := LoadLibrary('shlwapi.dll');
if dllShlwApi <> 0 then
@ShAutoComplete := GetProcAddress(dllShlwApi, 'SHAutoComplete');
finalization
if dllShlwApi <> 0 then
FreeLibrary(dllShlwApi);
end.
|
unit AConsultaPrecosProdutos;
{ Autor: Rafael Budag
Data Criação: 16/04/1999;
Função: Gerar um orçamento
Motivo alteração:
}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios,
Localizacao, StdCtrls, Buttons, Componentes1, Db, DBTables, ExtCtrls,
PainelGradiente, DBGrids, Tabela, DBKeyViolation, DBCtrls,
numericos, LabelCorMove, Parcela, BotaoCadastro,
EditorImagem, ConvUnidade,UnCotacao, Grids, Mask, Funarquivos, FMTBcd,
SqlExpr, DBClient, Menus;
type
TFConsultaPrecosProdutos = class(TFormularioPermissao)
CadProdutos: TSQL;
Localiza: TConsultaPadrao;
DataCadProdutos: TDataSource;
PanelColor2: TPanelColor;
PanelColor5: TPanelColor;
Label3: TLabel;
Label2: TLabel;
SpeedButton1: TSpeedButton;
Label1: TLabel;
EClassificacaoProduto: TEditLocaliza;
CProAti: TCheckBox;
PainelFoto: TPanelColor;
PanelColor8: TPanelColor;
Shape1: TShape;
VerFoto: TCheckBox;
Esticar: TCheckBox;
Panel5: TPanel;
Foto: TImage;
ECodigoProduto: TEditColor;
Label6: TLabel;
ENomeProduto: TEditColor;
CadProdutosC_COD_PRO: TWideStringField;
CadProdutosC_COD_UNI: TWideStringField;
CadProdutosC_NOM_PRO: TWideStringField;
CadProdutosC_ATI_PRO: TWideStringField;
CadProdutosC_KIT_PRO: TWideStringField;
CadProdutosL_DES_TEC: TWideStringField;
CadProdutosC_PAT_FOT: TWideStringField;
CadProdutosN_PER_KIT: TFMTBCDField;
CadProdutosN_QTD_MIN: TFMTBCDField;
CadProdutosN_QTD_PRO: TFMTBCDField;
CadProdutosN_VLR_VEN: TFMTBCDField;
CadProdutosVlrREal: TFMTBCDField;
DBMemoColor2: TDBMemoColor;
GProdutos: TGridIndice;
BCotacao: TSpeedButton;
BMenuFiscal: TSpeedButton;
BKit: TSpeedButton;
BFechar: TSpeedButton;
Bevel1: TBevel;
CadProdutosC_Cod_Bar: TWideStringField;
CadProdutosC_Nom_Moe: TWideStringField;
CadProdutosI_SEQ_PRO: TFMTBCDField;
CadProdutosN_QTD_RES: TFMTBCDField;
CadProdutosQTDREAL: TFMTBCDField;
BAltera: TSpeedButton;
PanelColor1: TPanelColor;
ECondicao: TEditColor;
SpeedButton2: TSpeedButton;
LCondicao: TLabel;
Label5: TLabel;
Label4: TLabel;
EValorCondicao: TEditColor;
Aux: TSQLQuery;
CriaParcelas: TCriaParcelasReceber;
SpeedButton3: TSpeedButton;
CadProdutosN_Per_Max: TFMTBCDField;
ECliente: TEditLocaliza;
Label18: TLabel;
SpeedButton7: TSpeedButton;
Label20: TLabel;
CadProdutosCor: TWideStringField;
CadProdutosI_COD_COR: TFMTBCDField;
CadProdutosC_NOM_CLA: TWideStringField;
PFarmacia: TPanelColor;
EPrincipioAtivo: TEditLocaliza;
Label7: TLabel;
SpeedButton5: TSpeedButton;
Label8: TLabel;
CGenericos: TCheckBox;
CadProdutosI_PRI_ATI: TFMTBCDField;
CadProdutosC_IND_GEN: TWideStringField;
CadProdutosPrincipioAtivo: TWideStringField;
CadProdutosGenerico: TWideStringField;
Label9: TLabel;
ESeqProduto: TEditColor;
CadProdutosI_COD_TAM: TFMTBCDField;
CadProdutosTAMANHO: TWideStringField;
CadProdutosC_ARE_TRU: TWideStringField;
CadProdutosI_DES_PRO: TFMTBCDField;
CadProdutosINDICADORPRODUCAO: TStringField;
CadProdutosN_RED_ICM: TFMTBCDField;
CadProdutosC_SIT_TRI: TWideStringField;
CadProdutosAliquotaICMS: TFloatField;
CadProdutosC_REC_PRE: TWideStringField;
Label10: TLabel;
SpeedButton4: TSpeedButton;
Label11: TLabel;
Ecor: TRBEditLocaliza;
Menu: TPopupMenu;
ConsultaestoqueporNroSerie1: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure CProAtiClick(Sender: TObject);
procedure CadProdutosAfterScroll(DataSet: TDataSet);
procedure EsticarClick(Sender: TObject);
procedure BFecharClick(Sender: TObject);
procedure BCotacaoClick(Sender: TObject);
procedure VerFotoClick(Sender: TObject);
procedure BKitClick(Sender: TObject);
procedure EClassificacaoProdutoSelect(Sender: TObject);
procedure EClassificacaoProdutoRetorno(Retorno1, Retorno2: String);
procedure ENomeProdutoKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure GProdutosKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure GProdutosKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure ECondicaoKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure ECondicaoExit(Sender: TObject);
procedure SpeedButton2Click(Sender: TObject);
procedure ECodigoProdutoEnter(Sender: TObject);
procedure SpeedButton3Click(Sender: TObject);
procedure SpeedButton5Click(Sender: TObject);
procedure CadProdutosCalcFields(DataSet: TDataSet);
procedure EPrincipioAtivoFimConsulta(Sender: TObject);
procedure BAlteraClick(Sender: TObject);
procedure BMenuFiscalClick(Sender: TObject);
procedure GProdutosOrdem(Ordem: string);
procedure GProdutosDrawColumnCell(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumn; State: TGridDrawState);
procedure FotoDblClick(Sender: TObject);
procedure EcorFimConsulta(Sender: TObject);
procedure ConsultaestoqueporNroSerie1Click(Sender: TObject);
private
{ Private declarations }
VprTeclaPresionada : Boolean;
VprAliquotaICMS :Double;
VprOrdem : string;
procedure ConfiguraPermissaoUsuario;
procedure AtualizaConsulta;
procedure AdicionaFiltrosProduto(VpaSelect : TStrings);
procedure CarregaFoto;
procedure LocalizaCondicaoPgto;
function ExisteCondicao(VpaCondicao: Integer):Boolean;
Function ValorProduto(VpaValor : Double):Double;
public
{ Public declarations }
end;
var
FConsultaPrecosProdutos: TFConsultaPrecosProdutos;
implementation
uses APrincipal, Constantes,ConstMsg, FunObjeto,
AProdutosKit,FunSql, ACotacao, AConsultaCondicaoPgto,
ANovaCotacao, UnProdutos, ANovaNotaFiscalNota,
ANovoProdutoPro, AMenuFiscalECF, AEstoqueNumeroSerie;
{$R *.DFM}
{ ****************** Na criação do Formulário ******************************** }
procedure TFConsultaPrecosProdutos.FormCreate(Sender: TObject);
begin
CurrencyDecimals := varia.Decimais;
ConfiguraPermissaoUsuario;
VprAliquotaICMS := FunCotacao.RAliquotaICMSUF(varia.UFFilial);
VprTeclaPresionada := false;
if config.NaArvoreOrdenarProdutoPeloCodigo then
begin
VprOrdem := 'order by PRO.C_COD_PRO';
GProdutos.AindiceInicial := 0;
end
else
begin
VprOrdem := 'order by PRO.C_NOM_PRO';
GProdutos.AindiceInicial := 1;
end;
AtualizaConsulta;
CadProdutosN_VLR_VEN.EditFormat := Varia.MascaraValor;
CadProdutosN_VLR_VEN.DisplayFormat := Varia.MascaraValor;
PainelFoto.Align := alBottom;
if Config.CodigoBarras then
ActiveControl := ECodigoProduto;
with GProdutos.AListaCAmpos do
begin
Clear;
Add(varia.CodigoProduto);
Add('C_Nom_Pro');
add('C_NOM_MOE');
end;
if not ConfigModulos.Estoque then
begin
GProdutos.Columns[5].Visible := false;
GProdutos.Columns[6].Visible := false;
GProdutos.Columns[7].Visible := false;
end;
if not config.EstoquePorCor then
begin
GProdutos.Columns[2].Visible := false;
end;
if not config.EstoquePorTamanho then
GProdutos.Columns[3].Visible := false;
if not config.Farmacia then
begin
PFarmacia.Visible := false;
PanelColor5.Height := PanelColor5.Height - PFarmacia.Height;
GProdutos.Columns[9].Visible := false;
GProdutos.Columns[8].visible := false;
end;
BCotacao.Visible := ConfigModulos.OrcamentoVenda;
SpeedButton3.Visible := ConfigModulos.NotaFiscal;
end;
procedure TFConsultaPrecosProdutos.FotoDblClick(Sender: TObject);
begin
// VisualizadorImagem1.execute(varia.DriveFoto + CadProdutosC_PAT_FOT.AsString);
end;
{ ******************* Quando o formulario e fechado ************************** }
procedure TFConsultaPrecosProdutos.FormClose(Sender: TObject; var Action: TCloseAction);
begin
CadProdutos.close;
Action := CaFree;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
ações da consulta do produto
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
procedure TFConsultaPrecosProdutos.ConfiguraPermissaoUsuario;
begin
if not((puAdministrador in varia.PermissoesUsuario) or (puPLCompleto in varia.PermissoesUsuario)or
(puESCompleto in varia.PermissoesUsuario) or (puFACompleto in varia.PermissoesUsuario))then
begin
AlterarVisibleDet([BAltera],false);
GProdutos.Columns[5].Visible := false;
if (puVerPrecoVendaProduto in varia.PermissoesUsuario) then
begin
GProdutos.Columns[5].Visible := true;
end;
if (puManutencaoProdutos in Varia.PermissoesUsuario) then
AlterarVisibleDet([BAltera],true);
end;
BMenuFiscal.Visible := NomeModulo = 'PDV';
end;
procedure TFConsultaPrecosProdutos.ConsultaestoqueporNroSerie1Click(
Sender: TObject);
begin
FEstoqueNumeroSerie := TFEstoqueNumeroSerie.CriarSDI(self,'',FPrincipal.VerificaPermisao('FEstoqueNumeroSerie'));
FEstoqueNumeroSerie.ConsultaEstoqueNumeroSerie(CadProdutosI_SEQ_PRO.AsInteger, CadProdutosI_COD_COR.AsInteger);
FEstoqueNumeroSerie.free;
end;
{****************** atualiza a consulta dos produtos **************************}
procedure TFConsultaPrecosProdutos.AtualizaConsulta;
begin
CadProdutos.close;
CadProdutos.sql.clear;
CadProdutos.sql.add('Select PRO.I_SEQ_PRO,'+varia.CodigoProduto +' C_COD_PRO, C_COD_UNI, C_NOM_PRO, ' +
' C_ATI_PRO, C_KIT_PRO, L_DES_TEC, C_PAT_FOT, PRO.C_ARE_TRU, PRO.I_DES_PRO,'+
' PRO.I_PRI_ATI, PRO.C_IND_GEN, PRO.C_SIT_TRI, N_RED_ICM, '+
' PRO.C_REC_PRE, '+
' PRO.N_PER_KIT, Qtd.C_Cod_Bar, ' +
' Qtd.N_QTD_MIN, '+SqlTextoIsNull('QTD.N_QTD_PRO','0')+' N_QTD_PRO, ' +
SqlTextoIsNull('QTD.N_QTD_RES','0') +' N_QTD_RES, ' +
' (QTD.N_QTD_PRO - '+SqlTextoIsNull('QTD.N_QTD_RES','0')+') QTDREAL,' +
' PRE.N_VLR_VEN, (PRE.N_VLR_VEN * MOE.N_Vlr_Dia) VlrREal, '+
' QTD.I_COD_COR, QTD.I_COD_TAM, '+
' Moe.C_Nom_Moe, Pre.N_Per_Max, ' +
' CLA.C_NOM_CLA '+
' from CadProdutos pro, MovQdadeProduto Qtd, MovTabelaPreco Pre, '+
' CadMoedas Moe, CADCLASSIFICACAO CLA');
AdicionaFiltrosProduto(Cadprodutos.Sql);
CadProdutos.sql.add(' and Pre.I_Cod_Tab = ' + IntToStr(Varia.TabelaPreco) +
' and Qtd.I_Seq_Pro = Pro.I_Seq_Pro '+
' and Pre.I_Cod_Emp = Pro.I_Cod_Emp '+
' and Pre.I_Seq_Pro = Pro.I_Seq_Pro '+
' and '+SQLTextoRightJoin('QTD.I_COD_COR','PRE.I_COD_COR')+
' and Moe.I_Cod_Moe = Pro.I_Cod_Moe' +
' AND CLA.C_TIP_CLA = ''P'''+
' AND CLA.I_COD_EMP = '+IntToStr(Varia.CodigoEmpresa)+
' and CLA.C_COD_CLA = PRO.C_COD_CLA');
CadProdutos.SQL.Add(VprOrdem);
if FPrincipal.CorFoco.AGravarConsultaSQl then
CadProdutos.Sql.Savetofile(RetornaDiretorioCorrente+'Consulta.sql');
GravaEstatisticaConsulta(nil,CadProdutos,varia.CodigoUsuario,Self.name,NomeModulo,config.UtilizarPercentualConsulta);
CadProdutos.Open;
GProdutos.ALinhaSQLOrderBy := CadProdutos.sql.count - 1;
end;
{******************* adiciona os filtros da consulta **************************}
procedure TFConsultaPrecosProdutos.AdicionaFiltrosProduto(VpaSelect : TStrings);
begin
VpaSelect.add('Where Qtd.I_Emp_Fil = ' + inttostr(Varia.CodigoEmpFil));
if ECodigoProduto.text <> '' Then
VpaSelect.add(' and '+varia.CodigoProduto+ ' like ''' + ECodigoProduto.text+'''')
else
begin
if ENomeProduto.text <> '' Then
VpaSelect.Add('and Pro.C_Nom_Pro like '''+ENomeProduto.text +'%''');
if ESeqProduto.AInteiro <> 0 Then
VpaSelect.Add('and Pro.I_SEQ_PRO = '+ ESeqProduto.Text);
if EClassificacaoProduto.text <> ''Then
VpaSelect.add(' and Pro.C_Cod_Cla like '''+ EClassificacaoProduto.text+ '%''');
if CProAti.Checked then
VpaSelect.add(' and Pro.C_Ati_Pro = ''S''');
if EPrincipioAtivo.AInteiro <> 0 then
VpaSelect.Add(' and PRO.I_PRI_ATI = '+EPrincipioAtivo.Text);
if CGenericos.Checked then
VpaSelect.Add(' and PRO.C_IND_GEN = ''T''');
end;
if (puSomenteProdutos in varia.PermissoesUsuario) and (Varia.CodClassificacaoProdutos <> '') then
VpaSelect.Add('AND CLA.C_COD_CLA like '''+Varia.CodClassificacaoProdutos+'%''')
else
if (puSomenteMateriaPrima in varia.PermissoesUsuario) and (Varia.CodClassificacaoMateriaPrima <> '') then
VpaSelect.Add('AND CLA.C_COD_CLA like '''+Varia.CodClassificacaoMateriaPrima+'%''');
// if Ecliente.AInteiro <> 0 then
VpaSelect.add(' and PRE.I_COD_CLI = '+ IntToStr(ECliente.Ainteiro));
if Ecor.AInteiro <> 0 then
VpaSelect.add(' and QTD.I_COD_COR = '+ IntToStr(ECor.Ainteiro));
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Servicos dos botoes superiores
))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))) }
{********************Mostra ou esconde o painel do orçamento*******************}
procedure TFConsultaPrecosProdutos.BCotacaoClick(Sender: TObject);
begin
FNovaCotacao := TFNovaCotacao.criarSDI(Application,'',FPrincipal.VerificaPermisao('FNovaCotacao'));
FNovaCotacao.NovaCotacao;
FNovaCotacao.free;
AtualizaConsulta;
end;
{ ******************* chama o formulario para visualizar kit **************** }
procedure TFConsultaPrecosProdutos.BKitClick(Sender: TObject);
begin
FProdutosKit := TFProdutosKit.CriarSDI(Application,'',FPrincipal.VerificaPermisao('FProdutosKit'));
FProdutosKit.MostraKit(CadProdutosI_Seq_Pro.Asstring,Varia.CodigoEmpFil);
end;
{****************************Fecha o Formulario corrente***********************}
procedure TFConsultaPrecosProdutos.BFecharClick(Sender: TObject);
begin
close;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Ações dos filtros superiores
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{****************** carrega a select do localiza classificacao ****************}
procedure TFConsultaPrecosProdutos.EClassificacaoProdutoSelect(Sender: TObject);
begin
EClassificacaoProduto.ASelectLocaliza.text := 'Select * from CadClassificacao '+
' where c_nom_Cla like ''@%'''+
' and I_cod_emp = ' + InttoStr(Varia.CodigoEmpresa)+
' and C_Con_Cla = ''S'''+
' and C_Tip_Cla = ''P''';
EClassificacaoProduto.ASelectValida.text := 'Select * from CadClassificacao '+
' where C_Cod_Cla = ''@'''+
' and I_cod_emp = ' + InttoStr(Varia.CodigoEmpresa)+
' and C_Con_Cla = ''S'''+
' and C_Tip_Cla = ''P''';
if (puSomenteProdutos in varia.PermissoesUsuario) and (Varia.CodClassificacaoProdutos <> '') then
begin
EClassificacaoProduto.ASelectLocaliza.text := EClassificacaoProduto.ASelectLocaliza.text +'AND C_COD_CLA like '''+Varia.CodClassificacaoProdutos+'%''';
EClassificacaoProduto.ASelectValida.text := EClassificacaoProduto.ASelectValida.text + 'AND C_COD_CLA like '''+Varia.CodClassificacaoProdutos+'%''';
end
else
if (puSomenteMateriaPrima in varia.PermissoesUsuario) and (Varia.CodClassificacaoMateriaPrima <> '') then
begin
EClassificacaoProduto.ASelectLocaliza.text := EClassificacaoProduto.ASelectLocaliza.text +'AND C_COD_CLA like '''+Varia.CodClassificacaoMateriaPrima+'%''';
EClassificacaoProduto.ASelectValida.text := EClassificacaoProduto.ASelectValida.text + 'AND C_COD_CLA like '''+Varia.CodClassificacaoMateriaPrima+'%''';
end;
end;
{**************** chama a rotina para atualizar a consulta ********************}
procedure TFConsultaPrecosProdutos.EClassificacaoProdutoRetorno(Retorno1,
Retorno2: String);
begin
AtualizaConsulta;
end;
{*************Chama a Rotina para atualizar a select dos produtos**************}
procedure TFConsultaPrecosProdutos.CProAtiClick(Sender: TObject);
begin
AtualizaConsulta;
if config.CodigoBarras then
// if ENomeProduto.Focused then
// begin
// ECodigoProduto.setfocus;
// ECodigoProduto.SelectAll;
// end;
end;
{************** quando sair do campo de codigo de barra ******************* }
procedure TFConsultaPrecosProdutos.ECodigoProdutoEnter(Sender: TObject);
begin
ECodigoProduto.SelectAll;
end;
{************ se for pressionado enter atualiza a consulta ********************}
procedure TFConsultaPrecosProdutos.ENomeProdutoKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
case key of
13 :
begin
AtualizaConsulta;
if TWinControl(Sender).Name = 'ECodigoProduto' then
ECodigoProduto.SelectAll;
end;
end;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
eventos da foto
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{********************************Mostra a Foto*********************************}
procedure TFConsultaPrecosProdutos.CarregaFoto;
begin
try
if (VerFoto.Checked) and (CadProdutosC_PAT_FOT.AsString <> '') then
Foto.Picture.LoadFromFile(varia.DriveFoto + CadProdutosC_PAT_FOT.AsString)
else
Foto.Picture := nil;
except
Foto.Picture := nil;
end;
end;
{******************* consulta a condicao de pagamento *************************}
procedure TFConsultaPrecosProdutos.LocalizaCondicaoPgto;
var
VpfCondicao : Integer;
begin
if Econdicao.text <> '' Then
VpfCondicao := StrToInt(ECondicao.text)
else
VpfCondicao := 0;
FConsultaCondicaoPgto := TFConsultaCondicaoPgto.create(self);
FConsultaCondicaoPgto.VisualizaParcelas(CadProdutosVlrREal.Asfloat,VpfCondicao, false);
FConsultaCondicaoPgto.free;
if VpfCondicao <> 0 then
begin
ECondicao.text := IntTostr(VpfCondicao);
ExisteCondicao(VpfCondicao)
end
else
begin
ECondicao.Clear;
LCondicao.caption := '';
EValorCondicao.text := FormatFloat(Varia.MascaraMoeda,CadProdutosVlrReal.Asfloat);
end;
end;
{******************************************************************************}
procedure TFConsultaPrecosProdutos.EcorFimConsulta(Sender: TObject);
begin
AtualizaConsulta;
end;
{************** verifica se existe a condicao de pagamento ********************}
function TFConsultaPrecosProdutos.ExisteCondicao(VpaCondicao: Integer):Boolean;
begin
AdicionaSQLAbreTabela(Aux,'Select * from CADCONDICOESPAGTO ' +
' Where I_Cod_Pag = ' + IntToStr(VpaCondicao));
result := not aux.Eof;
if result Then
begin
LCondicao.caption := Aux.FieldByName('C_Nom_Pag').Asstring;
CriaParcelas.Parcelas(CadProdutosVlrReal.AsFloat,VpaCondicao,false,Date);
EValorCondicao.text := FormatFloat('###,###,###,##0.00',CriaParcelas.ValorTotal);
end
else
begin
LCondicao.caption := '';
EValorcondicao.clear;
end;
end;
{************** retorna o valor do produto na condicao de pagamento ***********}
Function TFConsultaPrecosProdutos.ValorProduto(VpaValor : Double):Double;
begin
if ECondicao.text = '' then
result := VpaValor
else
begin
CriaParcelas.Parcelas(VpaValor,StrToInt(Econdicao.text),false,date);
result := CriaParcelas.ValorTotal;
end;
end;
{***************************Estica ou nao a foto*******************************}
procedure TFConsultaPrecosProdutos.EsticarClick(Sender: TObject);
begin
Foto.Stretch := esticar.Checked;
end;
{********************Visualiza ou não a foto do produto************************}
procedure TFConsultaPrecosProdutos.VerFotoClick(Sender: TObject);
begin
if VerFoto.Checked then
CarregaFoto
else
Foto.Picture.Bitmap := nil;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
eventos diversos
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{**************************eventos do produto**********************************}
procedure TFConsultaPrecosProdutos.CadProdutosAfterScroll(
DataSet: TDataSet);
begin
if not VprTeclaPresionada then
begin
BKit.Enabled := CadProdutosC_KIT_PRO.Asstring = 'K';
carregaFoto;
EValorCondicao.Text := FormatFloat(CurrencyString+' ###,###,##0.00',ValorProduto(CadProdutosVlrReal.AsFloat));
end;
end;
{*************** quando e pressionado uma tecla no grid ***********************}
procedure TFConsultaPrecosProdutos.GProdutosDrawColumnCell(Sender: TObject;
const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
if (State <> [gdSelected]) then
begin
if CadProdutosC_REC_PRE.AsString = 'S' then
begin
GProdutos.Canvas.Font.Color:= clBlue;
GProdutos.DefaultDrawDataCell(Rect, GProdutos.columns[datacol].field, State);
end;
if CadProdutosC_ATI_PRO.AsString = 'N' then
begin
GProdutos.Canvas.Font.Color:= clred;
GProdutos.DefaultDrawDataCell(Rect, GProdutos.columns[datacol].field, State);
end;
end;
end;
{******************************************************************************}
procedure TFConsultaPrecosProdutos.GProdutosKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
VprTeclaPresionada := true;
end;
procedure TFConsultaPrecosProdutos.GProdutosKeyUp(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
VprTeclaPresionada := false;
if key in[37..40] then
CadProdutosAfterScroll(CadProdutos);
end;
procedure TFConsultaPrecosProdutos.GProdutosOrdem(Ordem: string);
begin
VprOrdem := Ordem;
end;
{******************** localiza a condicao de pagamento ************************}
procedure TFConsultaPrecosProdutos.ECondicaoKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
case key of
Vk_f3 : LocalizaCondicaoPgto;
end;
end;
{*************** valida a condicao de pagamento digitada **********************}
procedure TFConsultaPrecosProdutos.ECondicaoExit(Sender: TObject);
begin
if ECondicao.text <> '' then
if not ExisteCondicao(StrToInt(Econdicao.Text)) then
begin
LocalizaCondicaoPgto;
ECondicao.SetFocus;
end;
end;
{************** chama a rotina para localiza a condicao de pgto ***************}
procedure TFConsultaPrecosProdutos.SpeedButton2Click(Sender: TObject);
begin
LocalizaCondicaoPgto;
end;
{********************** chama a nova nota fiscal ******************************}
procedure TFConsultaPrecosProdutos.SpeedButton3Click(Sender: TObject);
begin
FNovaNotaFiscalNota := TFNovaNotaFiscalNota.CriarSDI(application, '',FPrincipal.VerificaPermisao('FNovaNotaFiscalNota'));
FNovaNotaFiscalNota.NovaNotaFiscal;
FNovaNotaFiscalNota.free;
end;
procedure TFConsultaPrecosProdutos.BMenuFiscalClick(Sender: TObject);
begin
FMenuFiscalECF := TFMenuFiscalECF.CriarSDI(self,'',true);
FMenuFiscalECF.ShowModal;
FMenuFiscalECF.Free;
end;
{************************** chama o ecf ***************************************}
procedure TFConsultaPrecosProdutos.SpeedButton5Click(Sender: TObject);
begin
end;
{******************************************************************************}
procedure TFConsultaPrecosProdutos.CadProdutosCalcFields(
DataSet: TDataSet);
begin
if CadProdutosI_COD_COR.AsInteger <> 0 then
CadProdutosCor.AsString := CadProdutosI_COD_COR.AsString+'-'+FunProdutos.RNomeCor(CadProdutos.FieldByName('I_COD_COR').AsString)
else
CadProdutosCor.Clear;
if config.EstoquePorTamanho then
begin
CadProdutosTAMANHO.AsString := FunProdutos.RNomeTamanho(CadProdutosI_COD_TAM.AsInteger);
end;
if config.Farmacia then
begin
if CadProdutosC_IND_GEN.AsString = 'T' then
CadProdutosGenerico.AsString := 'GENÉRICO'
else
CadProdutosGenerico.Clear;
CadProdutosPrincipioAtivo.AsString := FunProdutos.RNomePrincipioAtivo(CadProdutosI_PRI_ATI.AsInteger);
end;
if CadProdutosI_DES_PRO.AsInteger in [3,4,5] then
CadProdutosINDICADORPRODUCAO.AsString := 'P'
else
CadProdutosINDICADORPRODUCAO.AsString := 'T';
if (CadProdutosC_SIT_TRI.AsString = 'T') then
begin
if CadProdutosN_RED_ICM.AsFloat <> 0 then
CadProdutosAliquotaICMS.AsFloat := CadProdutosN_RED_ICM.AsFloat
else
CadProdutosAliquotaICMS.AsFloat := VprAliquotaICMS;
end
else
CadProdutosAliquotaICMS.AsFloat := 0;
end;
{******************************************************************************}
procedure TFConsultaPrecosProdutos.EPrincipioAtivoFimConsulta(
Sender: TObject);
begin
AtualizaConsulta;
end;
{******************************************************************************}
procedure TFConsultaPrecosProdutos.BAlteraClick(Sender: TObject);
begin
FNovoProdutoPro := TFNovoProdutoPro.CriarSDI(self,'',FPrincipal.VerificaPermisao('FNovoProdutoPro'));
if FNovoProdutoPro.AlterarProduto(varia.codigoEmpresa,varia.CodigoEmpFil,CadProdutosI_SEQ_PRO.AsInteger) <> nil then
AtualizaConsulta;
FNovoProdutoPro.free;
end;
Initialization
{ *************** Registra a classe para evitar duplicidade ****************** }
RegisterClasses([TFConsultaPrecosProdutos]);
end.
|
unit utility;
interface
var
words: array of string;
procedure getwords;
procedure toomanyspaces;
procedure glue(var flock1, flock2: array of string);
procedure reassemble;
function trim(sheep: string): string;
function parse(sheep: string): boolean;
implementation
const
alphabet = ['a'..'z', ''''];
var
dict: array of string;
procedure getwords;//importing words from a dictionary file into the 'dict' array
begin
writeln('Importing dictionary');
dict := ReadAllLines('words.txt');
writeln('Dictionary imported.');
writeln('====================');
end;
function trim(sheep: string): string;//remove all non-alphabet symbols from left and right side of the word
begin
//writeln('Trimming the sheep');
sheep := sheep.ToLower;
while (Length(sheep) > 0) and not (sheep[1] in alphabet) do
Delete(sheep, 1, 1);
while (Length(sheep) > 0) and not (sheep[Length(sheep)] in alphabet) do
Delete(sheep, Length(sheep), 1);
//writeln('Trimming complete');
trim := sheep;
end;
procedure toomanyspaces;//remove empty indexes from words array
var
i, j: integer;
begin
//writeln('Removing spaces');
i := 0;
while i <= Length(words) - 1 do
begin
if words[i] = '' then begin
for j := i to Length(words) - 2 do
words[j] := words[j + 1];
SetLength(words, Length(words) - 1);
end
else i := i + 1;
end;
//writeln('Spaces removed');
end;
procedure glue(var flock1, flock2: array of string);//glues two arrays together into one
var
i: integer;
begin
setlength(flock1, Length(flock1) + Length(flock2));
for i := Length(flock1) - Length(flock2) to Length(flock1) - 1 do
flock1[i] := flock2[i - (Length(flock1) - Length(flock2))];
end;
function parse(sheep: string): boolean;//looks for matching words in the dictionary
var
i: integer;
is_in: boolean;
current: string;
begin
//writeln('Parsing the sheep');
is_in := false;
i := 0;
current := trim(sheep);
if length(current) = 0 then is_in := true else
while (is_in = false) and (i <= Length(dict) - 1) do
if current.ToLower = dict[i].ToLower then is_in := true else i := i + 1;
//writeln('Parsing complete');
parse := is_in;
end;
procedure reassemble;//turns words array back into a string and prints it
var
i: integer;
soutput: string;
begin
soutput := words[0];
for i := 1 to Length(words) - 1 do
soutput := soutput + ' ' + words[i];
writeln(soutput);
end;
end. |
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit System.WideStrings;
interface
uses System.Classes, System.SysUtils;
type
TWideStrings = class;
{ IWideStringsAdapter interface }
{ Maintains link between TWideStrings and IWideStrings implementations }
IWideStringsAdapter = interface
['{25FE0E3B-66CB-48AA-B23B-BCFA67E8F5DA}']
procedure ReferenceStrings(S: TWideStrings);
procedure ReleaseStrings;
end;
{ TWideStrings class }
TWideStringsEnumerator = class
private
FIndex: Integer;
FStrings: TWideStrings;
public
constructor Create(AStrings: TWideStrings);
function GetCurrent: WideString; inline;
function MoveNext: Boolean;
property Current: WideString read GetCurrent;
end;
TWideStrings = class(TPersistent)
private
FDefined: TStringsDefined;
FDelimiter: WideChar;
FLineBreak: WideString;
FQuoteChar: WideChar;
FNameValueSeparator: WideChar;
FStrictDelimiter: Boolean;
FUpdateCount: Integer;
FAdapter: IWideStringsAdapter;
function GetCommaText: WideString;
function GetDelimitedText: WideString;
function GetName(Index: Integer): WideString;
function GetValue(const Name: WideString): WideString;
procedure ReadData(Reader: TReader);
procedure SetCommaText(const Value: WideString);
procedure SetDelimitedText(const Value: WideString);
procedure SetStringsAdapter(const Value: IWideStringsAdapter);
procedure SetValue(const Name, Value: WideString);
procedure WriteData(Writer: TWriter);
function GetDelimiter: WideChar;
procedure SetDelimiter(const Value: WideChar);
function GetLineBreak: WideString;
procedure SetLineBreak(const Value: WideString);
function GetQuoteChar: WideChar;
procedure SetQuoteChar(const Value: WideChar);
function GetNameValueSeparator: WideChar;
procedure SetNameValueSeparator(const Value: WideChar);
function GetStrictDelimiter: Boolean;
procedure SetStrictDelimiter(const Value: Boolean);
function GetValueFromIndex(Index: Integer): WideString;
procedure SetValueFromIndex(Index: Integer; const Value: WideString);
protected
procedure AssignTo(Dest: TPersistent); override;
procedure DefineProperties(Filer: TFiler); override;
procedure Error(const Msg: WideString; Data: Integer); overload;
procedure Error(Msg: PResStringRec; Data: Integer); overload;
function ExtractName(const S: WideString): WideString;
function Get(Index: Integer): WideString; virtual; abstract;
function GetCapacity: Integer; virtual;
function GetCount: Integer; virtual; abstract;
function GetObject(Index: Integer): TObject; virtual;
function GetTextStr: WideString; virtual;
procedure Put(Index: Integer; const S: WideString); virtual;
procedure PutObject(Index: Integer; AObject: TObject); virtual;
procedure SetCapacity(NewCapacity: Integer); virtual;
procedure SetTextStr(const Value: WideString); virtual;
procedure SetUpdateState(Updating: Boolean); virtual;
property UpdateCount: Integer read FUpdateCount;
function CompareStrings(const S1, S2: WideString): Integer; virtual;
public
destructor Destroy; override;
function Add(const S: WideString): Integer; virtual;
function AddObject(const S: WideString; AObject: TObject): Integer; virtual;
procedure Append(const S: WideString);
procedure AddStrings(Strings: TStrings); overload; virtual;
procedure AddStrings(Strings: TWideStrings); overload; virtual;
procedure Assign(Source: TPersistent); override;
procedure BeginUpdate;
procedure Clear; virtual; abstract;
procedure Delete(Index: Integer); virtual; abstract;
procedure EndUpdate;
function Equals(Strings: TWideStrings): Boolean; reintroduce;
procedure Exchange(Index1, Index2: Integer); virtual;
function GetEnumerator: TWideStringsEnumerator;
function GetText: PWideChar; virtual;
function IndexOf(const S: WideString): Integer; virtual;
function IndexOfName(const Name: WideString): Integer; virtual;
function IndexOfObject(AObject: TObject): Integer; virtual;
procedure Insert(Index: Integer; const S: WideString); virtual; abstract;
procedure InsertObject(Index: Integer; const S: WideString;
AObject: TObject); virtual;
procedure LoadFromFile(const FileName: WideString); overload; virtual;
procedure LoadFromFile(const FileName: WideString; Encoding: TEncoding); overload; virtual;
procedure LoadFromStream(Stream: TStream); overload; virtual;
procedure LoadFromStream(Stream: TStream; Encoding: TEncoding); overload; virtual;
procedure Move(CurIndex, NewIndex: Integer); virtual;
procedure SaveToFile(const FileName: WideString); overload; virtual;
procedure SaveToFile(const FileName: WideString; Encoding: TEncoding); overload; virtual;
procedure SaveToStream(Stream: TStream); overload; virtual;
procedure SaveToStream(Stream: TStream; Encoding: TEncoding); overload; virtual;
procedure SetText(Text: PWideChar); virtual;
property Capacity: Integer read GetCapacity write SetCapacity;
property CommaText: WideString read GetCommaText write SetCommaText;
property Count: Integer read GetCount;
property Delimiter: WideChar read GetDelimiter write SetDelimiter;
property DelimitedText: WideString read GetDelimitedText write SetDelimitedText;
property LineBreak: WideString read GetLineBreak write SetLineBreak;
property Names[Index: Integer]: WideString read GetName;
property Objects[Index: Integer]: TObject read GetObject write PutObject;
property QuoteChar: WideChar read GetQuoteChar write SetQuoteChar;
property Values[const Name: WideString]: WideString read GetValue write SetValue;
property ValueFromIndex[Index: Integer]: WideString read GetValueFromIndex write SetValueFromIndex;
property NameValueSeparator: WideChar read GetNameValueSeparator write SetNameValueSeparator;
property StrictDelimiter: Boolean read GetStrictDelimiter write SetStrictDelimiter;
property Strings[Index: Integer]: WideString read Get write Put; default;
property Text: WideString read GetTextStr write SetTextStr;
property StringsAdapter: IWideStringsAdapter read FAdapter write SetStringsAdapter;
end;
{ TWideStringList class }
TWideStringList = class;
PWideStringItem = ^TWideStringItem;
TWideStringItem = record
FString: WideString;
FObject: TObject;
end;
PWideStringItemList = ^TWideStringItemList;
TWideStringItemList = array of TWideStringItem;
TWideStringListSortCompare = function(List: TWideStringList; Index1, Index2: Integer): Integer;
TWideStringList = class(TWideStrings)
private
FList: TWideStringItemList;
FCount: Integer;
FCapacity: Integer;
FSorted: Boolean;
FDuplicates: TDuplicates;
FCaseSensitive: Boolean;
FOnChange: TNotifyEvent;
FOnChanging: TNotifyEvent;
FOwnsObject: Boolean;
procedure ExchangeItems(Index1, Index2: Integer);
procedure Grow;
procedure QuickSort(L, R: Integer; SCompare: TWideStringListSortCompare);
procedure SetSorted(Value: Boolean);
procedure SetCaseSensitive(const Value: Boolean);
protected
procedure Changed; virtual;
procedure Changing; virtual;
function Get(Index: Integer): WideString; override;
function GetCapacity: Integer; override;
function GetCount: Integer; override;
function GetObject(Index: Integer): TObject; override;
procedure Put(Index: Integer; const S: WideString); override;
procedure PutObject(Index: Integer; AObject: TObject); override;
procedure SetCapacity(NewCapacity: Integer); override;
procedure SetUpdateState(Updating: Boolean); override;
function CompareStrings(const S1, S2: WideString): Integer; override;
procedure InsertItem(Index: Integer; const S: WideString; AObject: TObject); virtual;
public
constructor Create; overload;
constructor Create(OwnsObjects: Boolean); overload;
destructor Destroy; override;
function Add(const S: WideString): Integer; override;
function AddObject(const S: WideString; AObject: TObject): Integer; override;
procedure Clear; override;
procedure Delete(Index: Integer); override;
procedure Exchange(Index1, Index2: Integer); override;
function Find(const S: WideString; var Index: Integer): Boolean; virtual;
function IndexOf(const S: WideString): Integer; override;
procedure Insert(Index: Integer; const S: WideString); override;
procedure InsertObject(Index: Integer; const S: WideString;
AObject: TObject); override;
procedure Sort; virtual;
procedure CustomSort(Compare: TWideStringListSortCompare); virtual;
property Duplicates: TDuplicates read FDuplicates write FDuplicates;
property Sorted: Boolean read FSorted write SetSorted;
property CaseSensitive: Boolean read FCaseSensitive write SetCaseSensitive;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
property OnChanging: TNotifyEvent read FOnChanging write FOnChanging;
property OwnsObjects: Boolean read FOwnsObject write FOwnsObject;
end;
implementation
uses
{$IFDEF MSWINDOWS}
Winapi.Windows,
{$ENDIF}
System.RTLConsts, System.WideStrUtils, System.Math;
{ CharNextW is defined in Windows but needs to be implemented for POSIX }
{$IFDEF POSIX}
function CharNextW(lpsz: PWideChar): PWideChar; stdcall;
begin
Result := StrNextChar(lpsz);
end;
{$ENDIF}
{ TWideStringsEnumerator }
constructor TWideStringsEnumerator.Create(AStrings: TWideStrings);
begin
inherited Create;
FIndex := -1;
FStrings := AStrings;
end;
function TWideStringsEnumerator.GetCurrent: WideString;
begin
Result := FStrings[FIndex];
end;
function TWideStringsEnumerator.MoveNext: Boolean;
begin
Result := FIndex < FStrings.Count - 1;
if Result then
Inc(FIndex);
end;
{ TWideStrings }
destructor TWideStrings.Destroy;
begin
StringsAdapter := nil;
inherited Destroy;
end;
function TWideStrings.Add(const S: WideString): Integer;
begin
Result := GetCount;
Insert(Result, S);
end;
function TWideStrings.AddObject(const S: WideString; AObject: TObject): Integer;
begin
Result := Add(S);
PutObject(Result, AObject);
end;
procedure TWideStrings.Append(const S: WideString);
begin
Add(S);
end;
procedure TWideStrings.AddStrings(Strings: TStrings);
var
I: Integer;
begin
BeginUpdate;
try
for I := 0 to Strings.Count - 1 do
AddObject(Strings[I], Strings.Objects[I]);
finally
EndUpdate;
end;
end;
procedure TWideStrings.AddStrings(Strings: TWideStrings);
var
I: Integer;
begin
BeginUpdate;
try
for I := 0 to Strings.Count - 1 do
AddObject(Strings[I], Strings.Objects[I]);
finally
EndUpdate;
end;
end;
procedure TWideStrings.Assign(Source: TPersistent);
function CharToWideChar(const c: AnsiChar): WideChar;
var
W: WideString;
begin
w := WideString(AnsiString(c));
if length(W) = 1 then Result := W[1]
else Result := '?';
end;
begin
if Source is TWideStrings then
begin
BeginUpdate;
try
Clear;
FDefined := TWideStrings(Source).FDefined;
FNameValueSeparator := TWideStrings(Source).FNameValueSeparator;
FQuoteChar := TWideStrings(Source).FQuoteChar;
FDelimiter := TWideStrings(Source).FDelimiter;
FLineBreak := TWideStrings(Source).FLineBreak;
FStrictDelimiter := TWideStrings(Source).FStrictDelimiter;
AddStrings(TWideStrings(Source));
finally
EndUpdate;
end;
end
else if Source is TStrings then
begin
BeginUpdate;
try
Clear;
FNameValueSeparator := WideChar(TStrings(Source).NameValueSeparator);
FQuoteChar := WideChar(TStrings(Source).QuoteChar);
FDelimiter := WideChar(TStrings(Source).Delimiter);
FLineBreak := WideString(TStrings(Source).LineBreak);
FStrictDelimiter := TStrings(Source).StrictDelimiter;
AddStrings(TStrings(Source));
finally
EndUpdate;
end;
end
else
inherited Assign(Source);
end;
procedure TWideStrings.AssignTo(Dest: TPersistent);
function WideCharToChar(const c: WideChar): AnsiChar;
var
A: AnsiString;
begin
a := AnsiString(WideString(c));
if length(a) = 1 then Result := a[1]
else Result := AnsiChar('?');
end;
var
I: Integer;
begin
if Dest is TWideStrings then Dest.Assign(Self)
else if Dest is TStrings then
begin
TStrings(Dest).BeginUpdate;
try
TStrings(Dest).Clear;
TStrings(Dest).NameValueSeparator := Char(NameValueSeparator);
TStrings(Dest).QuoteChar := Char(QuoteChar);
TStrings(Dest).Delimiter := Char(Delimiter);
TStrings(Dest).LineBreak := LineBreak;
TStrings(Dest).StrictDelimiter := StrictDelimiter;
for I := 0 to Count - 1 do
TStrings(Dest).AddObject(Strings[I], Objects[I]);
finally
TStrings(Dest).EndUpdate;
end;
end
else
inherited AssignTo(Dest);
end;
procedure TWideStrings.BeginUpdate;
begin
if FUpdateCount = 0 then SetUpdateState(True);
Inc(FUpdateCount);
end;
procedure TWideStrings.DefineProperties(Filer: TFiler);
function DoWrite: Boolean;
begin
if Filer.Ancestor <> nil then
begin
Result := True;
if Filer.Ancestor is TWideStrings then
Result := not Equals(TWideStrings(Filer.Ancestor))
end
else Result := Count > 0;
end;
begin
Filer.DefineProperty('Strings', ReadData, WriteData, DoWrite);
end;
procedure TWideStrings.EndUpdate;
begin
Dec(FUpdateCount);
if FUpdateCount = 0 then SetUpdateState(False);
end;
function TWideStrings.Equals(Strings: TWideStrings): Boolean;
var
I, Count: Integer;
begin
Result := False;
Count := GetCount;
if Count <> Strings.GetCount then Exit;
for I := 0 to Count - 1 do if Get(I) <> Strings.Get(I) then Exit;
Result := True;
end;
procedure TWideStrings.Error(const Msg: WideString; Data: Integer);
begin
raise EStringListError.CreateFmt(Msg, [Data]) at ReturnAddress;
end;
procedure TWideStrings.Error(Msg: PResStringRec; Data: Integer);
begin
raise EStringListError.CreateFmt(LoadResString(Msg), [Data]) at ReturnAddress;
end;
procedure TWideStrings.Exchange(Index1, Index2: Integer);
var
TempObject: TObject;
TempString: WideString;
begin
BeginUpdate;
try
TempString := Strings[Index1];
TempObject := Objects[Index1];
Strings[Index1] := Strings[Index2];
Objects[Index1] := Objects[Index2];
Strings[Index2] := TempString;
Objects[Index2] := TempObject;
finally
EndUpdate;
end;
end;
function TWideStrings.ExtractName(const S: WideString): WideString;
var
P: Integer;
begin
Result := S;
P := Pos(NameValueSeparator, Result);
if P <> 0 then
SetLength(Result, P-1) else
SetLength(Result, 0);
end;
function TWideStrings.GetCapacity: Integer;
begin // descendents may optionally override/replace this default implementation
Result := Count;
end;
function TWideStrings.GetCommaText: WideString;
var
LOldDefined: TStringsDefined;
LOldDelimiter: WideChar;
LOldQuoteChar: WideChar;
begin
LOldDefined := FDefined;
LOldDelimiter := FDelimiter;
LOldQuoteChar := FQuoteChar;
Delimiter := ',';
QuoteChar := '"';
try
Result := GetDelimitedText;
finally
FDelimiter := LOldDelimiter;
FQuoteChar := LOldQuoteChar;
FDefined := LOldDefined;
end;
end;
function TWideStrings.GetDelimitedText: WideString;
function IsDelimiter(const ch: WideChar): boolean;
begin
Result := true;
if not StrictDelimiter and (ch <= ' ') then exit
else if ch = QuoteChar then exit
else if ch = Delimiter then exit
else if ch = #$00 then exit;
Result := False;
end;
var
S: WideString;
P: PWideChar;
I, Count: Integer;
begin
Count := GetCount;
if (Count = 1) and (Get(0) = '') then
Result := QuoteChar + QuoteChar
else
begin
Result := '';
for I := 0 to Count - 1 do
begin
S := Get(I);
P := PWideChar(S);
while not IsDelimiter(P^) do
P := CharNextW(P); // for UTF16
if (P^ <> #0) then S := WideQuotedStr(S, QuoteChar);
Result := Result + S + Delimiter;
end;
System.Delete(Result, Length(Result), 1);
end;
end;
function TWideStrings.GetEnumerator: TWideStringsEnumerator;
begin
Result := TWideStringsEnumerator.Create(Self);
end;
function TWideStrings.GetName(Index: Integer): WideString;
begin
Result := ExtractName(Get(Index));
end;
function TWideStrings.GetObject(Index: Integer): TObject;
begin
Result := nil;
end;
function TWideStrings.GetText: PWideChar;
begin
Result := WStrNew(PWideChar(GetTextStr));
end;
function TWideStrings.GetTextStr: WideString;
var
I, L, Size, Count: Integer;
P: PWideChar;
S, LB: WideString;
begin
Count := GetCount;
Size := 0;
LB := LineBreak;
for I := 0 to Count - 1 do Inc(Size, Length(Get(I)) + Length(LB));
SetString(Result, nil, Size);
P := Pointer(Result);
for I := 0 to Count - 1 do
begin
S := Get(I);
L := Length(S);
if L <> 0 then
begin
System.Move(Pointer(S)^, P^, L * SizeOf(WideChar));
Inc(P, L);
end;
L := Length(LB);
if L <> 0 then
begin
System.Move(Pointer(LB)^, P^, L * SizeOf(WideChar));
Inc(P, L);
end;
end;
end;
function TWideStrings.GetValue(const Name: WideString): WideString;
var
I: Integer;
begin
I := IndexOfName(Name);
if I >= 0 then
Result := Copy(Get(I), Length(Name) + 2, MaxInt) else
Result := '';
end;
function TWideStrings.IndexOf(const S: WideString): Integer;
begin
for Result := 0 to GetCount - 1 do
if CompareStrings(Get(Result), S) = 0 then Exit;
Result := -1;
end;
function TWideStrings.IndexOfName(const Name: WideString): Integer;
var
P: Integer;
S: WideString;
begin
for Result := 0 to GetCount - 1 do
begin
S := Get(Result);
P := Pos(NameValueSeparator, S);
if (P <> 0) and (CompareStrings(Copy(S, 1, P - 1), Name) = 0) then Exit;
end;
Result := -1;
end;
function TWideStrings.IndexOfObject(AObject: TObject): Integer;
begin
for Result := 0 to GetCount - 1 do
if GetObject(Result) = AObject then Exit;
Result := -1;
end;
procedure TWideStrings.InsertObject(Index: Integer; const S: WideString;
AObject: TObject);
begin
Insert(Index, S);
PutObject(Index, AObject);
end;
procedure TWideStrings.LoadFromFile(const FileName: WideString);
var
Stream: TStream;
begin
Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
try
LoadFromStream(Stream);
finally
Stream.Free;
end;
end;
procedure TWideStrings.LoadFromStream(Stream: TStream);
begin
LoadFromStream(Stream, nil);
end;
procedure TWideStrings.Move(CurIndex, NewIndex: Integer);
var
TempObject: TObject;
TempString: WideString;
begin
if CurIndex <> NewIndex then
begin
BeginUpdate;
try
TempString := Get(CurIndex);
TempObject := GetObject(CurIndex);
Delete(CurIndex);
InsertObject(NewIndex, TempString, TempObject);
finally
EndUpdate;
end;
end;
end;
procedure TWideStrings.Put(Index: Integer; const S: WideString);
var
TempObject: TObject;
begin
TempObject := GetObject(Index);
Delete(Index);
InsertObject(Index, S, TempObject);
end;
procedure TWideStrings.PutObject(Index: Integer; AObject: TObject);
begin
end;
procedure TWideStrings.ReadData(Reader: TReader);
begin
Reader.ReadListBegin;
BeginUpdate;
try
Clear;
while not Reader.EndOfList do Add(Reader.ReadWideString);
finally
EndUpdate;
end;
Reader.ReadListEnd;
end;
procedure TWideStrings.SaveToFile(const FileName: WideString);
begin
SaveToFile(FileName, nil);
end;
procedure TWideStrings.SaveToFile(const FileName: WideString; Encoding: TEncoding);
var
Stream: TStream;
begin
Stream := TFileStream.Create(FileName, fmCreate);
try
SaveToStream(Stream, Encoding);
finally
Stream.Free;
end;
end;
procedure TWideStrings.SaveToStream(Stream: TStream; Encoding: TEncoding);
var
Buffer, Preamble: TBytes;
begin
if Encoding = nil then
Encoding := TEncoding.Unicode; // The default encoding is UTF-16
Buffer := Encoding.GetBytes(string(GetTextStr));
Preamble := Encoding.GetPreamble;
if Length(Preamble) > 0 then
Stream.WriteBuffer(Preamble[0], Length(Preamble));
Stream.WriteBuffer(Buffer[0], Length(Buffer));
end;
procedure TWideStrings.SaveToStream(Stream: TStream);
begin
SaveToStream(Stream, nil);
end;
procedure TWideStrings.SetCapacity(NewCapacity: Integer);
begin
// do nothing - descendents may optionally implement this method
end;
procedure TWideStrings.SetCommaText(const Value: WideString);
var
LOldDefined: TStringsDefined;
LOldDelimiter: WideChar;
LOldQuoteChar: WideChar;
begin
LOldDefined := FDefined;
LOldDelimiter := FDelimiter;
LOldQuoteChar := FQuoteChar;
Delimiter := ',';
QuoteChar := '"';
try
SetDelimitedText(Value);
finally
FDelimiter := LOldDelimiter;
FQuoteChar := LOldQuoteChar;
FDefined := LOldDefined;
end;
end;
procedure TWideStrings.SetStringsAdapter(const Value: IWideStringsAdapter);
begin
if FAdapter <> nil then FAdapter.ReleaseStrings;
FAdapter := Value;
if FAdapter <> nil then FAdapter.ReferenceStrings(Self);
end;
procedure TWideStrings.SetText(Text: PWideChar);
begin
SetTextStr(Text);
end;
procedure TWideStrings.SetTextStr(const Value: WideString);
var
P, Start, LB: PWideChar;
S: WideString;
LineBreakLen: Integer;
begin
BeginUpdate;
try
Clear;
P := PWideChar(Value);
if P <> nil then
if WideCompareStr(LineBreak, WideString(sLineBreak)) = 0 then
begin
// This is a lot faster than using StrPos/AnsiStrPos when
// LineBreak is the default (#13#10)
while P^ <> #0 do
begin
Start := P;
while not InOpSet(P^, [AnsiChar(#0), AnsiChar(#10), AnsiChar(#13)]) do Inc(P);
SetString(S, Start, P - Start);
Add(S);
if P^ = #13 then Inc(P);
if P^ = #10 then Inc(P);
end;
end
else
begin
LineBreakLen := Length(LineBreak);
while P^ <> #0 do
begin
Start := P;
LB := AnsiStrPos(P, PChar(LineBreak));
while (P^ <> #0) and (P <> LB) do Inc(P);
SetString(S, Start, P - Start);
Add(S);
if P = LB then
Inc(P, LineBreakLen);
end;
end;
finally
EndUpdate;
end;
end;
procedure TWideStrings.SetUpdateState(Updating: Boolean);
begin
end;
procedure TWideStrings.SetValue(const Name, Value: WideString);
var
I: Integer;
begin
I := IndexOfName(Name);
if Value <> '' then
begin
if I < 0 then I := Add('');
Put(I, Name + NameValueSeparator + Value);
end else
begin
if I >= 0 then Delete(I);
end;
end;
procedure TWideStrings.WriteData(Writer: TWriter);
var
I: Integer;
begin
Writer.WriteListBegin;
for I := 0 to Count - 1 do Writer.WriteWideString(Get(I));
Writer.WriteListEnd;
end;
procedure TWideStrings.SetDelimitedText(const Value: WideString);
var
P, P1: PWideChar;
S: WideString;
begin
BeginUpdate;
try
Clear;
P := PWideChar(Value);
if not StrictDelimiter then
while inOpSet(P^, [AnsiChar(#1)..AnsiChar(' ')]) do
P := CharNextW(P);
while P^ <> #0 do
begin
if P^ = WideChar(QuoteChar) then
S := WideExtractQuotedStr(P, WideChar(QuoteChar))
else
begin
P1 := P;
while ((not FStrictDelimiter and (P^ > ' ')) or
(FStrictDelimiter and (P^ <> #0))) and (P^ <> WideChar(Delimiter)) do
P := CharNextW(P);
SetString(S, P1, P - P1);
end;
Add(S);
if not FStrictDelimiter then
while inOpSet(P^, [AnsiChar(#1)..AnsiChar(' ')]) do
P := CharNextW(P);
if P^ = WideChar(Delimiter) then
begin
P1 := P;
if CharNextW(P1)^ = #0 then
Add('');
repeat
P := CharNextW(P);
until not (not FStrictDelimiter and inOpSet(P^, [AnsiChar(#1)..AnsiChar(' ')]));
end;
end;
finally
EndUpdate;
end;
end;
function TWideStrings.GetDelimiter: WideChar;
begin
if not (sdDelimiter in FDefined) then
Delimiter := ',';
Result := FDelimiter;
end;
function TWideStrings.GetLineBreak: WideString;
begin
if not (sdLineBreak in FDefined) then
LineBreak := sLineBreak;
Result := FLineBreak;
end;
function TWideStrings.GetQuoteChar: WideChar;
begin
if not (sdQuoteChar in FDefined) then
QuoteChar := '"';
Result := FQuoteChar;
end;
function TWideStrings.GetStrictDelimiter: Boolean;
begin
if not (sdStrictDelimiter in FDefined) then
StrictDelimiter := False;
Result := FStrictDelimiter;
end;
procedure TWideStrings.SetDelimiter(const Value: WideChar);
begin
if (FDelimiter <> Value) or not (sdDelimiter in FDefined) then
begin
Include(FDefined, sdDelimiter);
FDelimiter := Value;
end
end;
procedure TWideStrings.SetLineBreak(const Value: WideString);
begin
if (FLineBreak <> Value) or not (sdLineBreak in FDefined) then
begin
Include(FDefined, sdLineBreak);
FLineBreak := Value;
end
end;
procedure TWideStrings.SetQuoteChar(const Value: WideChar);
begin
if (FQuoteChar <> Value) or not (sdQuoteChar in FDefined) then
begin
Include(FDefined, sdQuoteChar);
FQuoteChar := Value;
end
end;
procedure TWideStrings.SetStrictDelimiter(const Value: Boolean);
begin
if (FStrictDelimiter <> Value) or not (sdStrictDelimiter in FDefined) then
begin
Include(FDefined, sdStrictDelimiter);
FStrictDelimiter := Value;
end
end;
function TWideStrings.CompareStrings(const S1, S2: WideString): Integer;
begin
Result := WideCompareText(S1, S2);
end;
function TWideStrings.GetNameValueSeparator: WideChar;
begin
if not (sdNameValueSeparator in FDefined) then
NameValueSeparator := '=';
Result := FNameValueSeparator;
end;
procedure TWideStrings.SetNameValueSeparator(const Value: WideChar);
begin
if (FNameValueSeparator <> Value) or not (sdNameValueSeparator in FDefined) then
begin
Include(FDefined, sdNameValueSeparator);
FNameValueSeparator := Value;
end
end;
function TWideStrings.GetValueFromIndex(Index: Integer): WideString;
begin
if Index >= 0 then
Result := Copy(Get(Index), Length(Names[Index]) + 2, MaxInt) else
Result := '';
end;
procedure TWideStrings.SetValueFromIndex(Index: Integer; const Value: WideString);
begin
if Value <> '' then
begin
if Index < 0 then Index := Add('');
Put(Index, Names[Index] + NameValueSeparator + Value);
end
else
if Index >= 0 then Delete(Index);
end;
procedure TWideStrings.LoadFromFile(const FileName: WideString; Encoding: TEncoding);
var
Stream: TStream;
begin
Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
try
LoadFromStream(Stream, Encoding);
finally
Stream.Free;
end;
end;
procedure TWideStrings.LoadFromStream(Stream: TStream; Encoding: TEncoding);
var
Size: Integer;
Buffer: TBytes;
begin
BeginUpdate;
try
Size := Stream.Size - Stream.Position;
SetLength(Buffer, Size);
Stream.Read(Buffer[0], Size);
Size := TEncoding.GetBufferEncoding(Buffer, Encoding);
{ If no preamble was detected, assume Unicode and not the default ANSI CP }
if Size = 0 then
Encoding := TEncoding.Unicode;
SetTextStr(string(Encoding.GetString(Buffer, Size, Length(Buffer) - Size)));
finally
EndUpdate;
end;
end;
{ TWideStringList }
destructor TWideStringList.Destroy;
var
I: Integer;
Obj: TObject;
begin
FOnChange := nil;
FOnChanging := nil;
// In the event that we own the Objects make sure to free them all when we
// destroy the stringlist.
if OwnsObjects then
begin
for I := 0 to FCount - 1 do
begin
Obj := GetObject(I);
if Obj <> nil then
Obj.Free;
end;
end;
inherited Destroy;
FCount := 0;
SetCapacity(0);
end;
function TWideStringList.Add(const S: WideString): Integer;
begin
Result := AddObject(S, nil);
end;
function TWideStringList.AddObject(const S: WideString; AObject: TObject): Integer;
begin
if not Sorted then
Result := FCount
else
if Find(S, Result) then
case Duplicates of
dupIgnore: Exit;
dupError: Error(@SDuplicateString, 0);
end;
InsertItem(Result, S, AObject);
end;
procedure TWideStringList.Changed;
begin
if (FUpdateCount = 0) and Assigned(FOnChange) then
FOnChange(Self);
end;
procedure TWideStringList.Changing;
begin
if (FUpdateCount = 0) and Assigned(FOnChanging) then
FOnChanging(Self);
end;
procedure TWideStringList.Clear;
var
I: Integer;
Obj: TObject;
begin
if FCount <> 0 then
begin
Changing;
//Free all objects in the event that this list owns its objects
if OwnsObjects then
begin
for I := 0 to FCount - 1 do
begin
Obj := GetObject(I);
if Obj <> nil then
Obj.Free;
end;
end;
FCount := 0;
SetCapacity(0);
Changed;
end;
end;
procedure TWideStringList.Delete(Index: Integer);
var
Obj: TObject;
begin
if (Index < 0) or (Index >= FCount) then Error(@SListIndexError, Index);
Changing;
// If this list owns its objects then free the associated TObject with this index
if OwnsObjects then
begin
Obj := GetObject(Index);
if Obj <> nil then
Obj.Free;
end;
Finalize(FList[Index]);
Dec(FCount);
if Index < FCount then
begin
System.Move(FList[Index + 1], FList[Index],
(FCount - Index) * SizeOf(TWideStringItem));
PPointer(@FList[FCount])^ := nil;
end;
Changed;
end;
procedure TWideStringList.Exchange(Index1, Index2: Integer);
begin
if (Index1 < 0) or (Index1 >= FCount) then Error(@SListIndexError, Index1);
if (Index2 < 0) or (Index2 >= FCount) then Error(@SListIndexError, Index2);
Changing;
ExchangeItems(Index1, Index2);
Changed;
end;
procedure TWideStringList.ExchangeItems(Index1, Index2: Integer);
var
Temp: Pointer;
Item1, Item2: PWideStringItem;
begin
Item1 := @FList[Index1];
Item2 := @FList[Index2];
Temp := Pointer(Item1^.FString);
Pointer(Item1^.FString) := Pointer(Item2^.FString);
Pointer(Item2^.FString) := Temp;
Temp := Pointer(Item1^.FObject);
Pointer(Item1^.FObject) := Pointer(Item2^.FObject);
Pointer(Item2^.FObject) := Temp;
end;
function TWideStringList.Find(const S: WideString; 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 := CompareStrings(FList[I].FString, S);
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 TWideStringList.Get(Index: Integer): WideString;
begin
if (Index < 0) or (Index >= FCount) then Error(@SListIndexError, Index);
Result := FList[Index].FString;
end;
function TWideStringList.GetCapacity: Integer;
begin
Result := FCapacity;
end;
function TWideStringList.GetCount: Integer;
begin
Result := FCount;
end;
function TWideStringList.GetObject(Index: Integer): TObject;
begin
if (Index < 0) or (Index >= FCount) then Error(@SListIndexError, Index);
Result := FList[Index].FObject;
end;
procedure TWideStringList.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;
function TWideStringList.IndexOf(const S: WideString): Integer;
begin
if not Sorted then Result := inherited IndexOf(S) else
if not Find(S, Result) then Result := -1;
end;
procedure TWideStringList.Insert(Index: Integer; const S: WideString);
begin
InsertObject(Index, S, nil);
end;
procedure TWideStringList.InsertObject(Index: Integer; const S: WideString;
AObject: TObject);
begin
if Sorted then Error(@SSortedListError, 0);
if (Index < 0) or (Index > FCount) then Error(@SListIndexError, Index);
InsertItem(Index, S, AObject);
end;
procedure TWideStringList.InsertItem(Index: Integer; const S: WideString; AObject: TObject);
begin
Changing;
if FCount = FCapacity then Grow;
if Index < FCount then
System.Move(FList[Index], FList[Index + 1],
(FCount - Index) * SizeOf(TWideStringItem));
with FList[Index] do
begin
Pointer(FString) := nil;
FObject := AObject;
FString := S;
end;
Inc(FCount);
Changed;
end;
procedure TWideStringList.Put(Index: Integer; const S: WideString);
begin
if Sorted then Error(@SSortedListError, 0);
if (Index < 0) or (Index >= FCount) then Error(@SListIndexError, Index);
Changing;
FList[Index].FString := S;
Changed;
end;
procedure TWideStringList.PutObject(Index: Integer; AObject: TObject);
begin
if (Index < 0) or (Index >= FCount) then Error(@SListIndexError, Index);
Changing;
FList[Index].FObject := AObject;
Changed;
end;
procedure TWideStringList.QuickSort(L, R: Integer; SCompare: TWideStringListSortCompare);
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 TWideStringList.SetCapacity(NewCapacity: Integer);
begin
//ReallocMem(FList, NewCapacity * SizeOf(TWideStringItem));
SetLength(FList, NewCapacity);
FCapacity := NewCapacity;
end;
procedure TWideStringList.SetSorted(Value: Boolean);
begin
if FSorted <> Value then
begin
if Value then Sort;
FSorted := Value;
end;
end;
procedure TWideStringList.SetUpdateState(Updating: Boolean);
begin
if Updating then Changing else Changed;
end;
function StringListCompareStrings(List: TWideStringList; Index1, Index2: Integer): Integer;
begin
Result := List.CompareStrings(List.FList[Index1].FString,
List.FList[Index2].FString);
end;
procedure TWideStringList.Sort;
begin
CustomSort(StringListCompareStrings);
end;
procedure TWideStringList.CustomSort(Compare: TWideStringListSortCompare);
begin
if not Sorted and (FCount > 1) then
begin
Changing;
QuickSort(0, FCount - 1, Compare);
Changed;
end;
end;
function TWideStringList.CompareStrings(const S1, S2: WideString): Integer;
begin
if CaseSensitive then
Result := WideCompareStr(S1, S2)
else
Result := WideCompareText(S1, S2);
end;
constructor TWideStringList.Create;
begin
inherited;
end;
constructor TWideStringList.Create(OwnsObjects: Boolean);
begin
inherited Create;
FOwnsObject := OwnsObjects;
end;
procedure TWideStringList.SetCaseSensitive(const Value: Boolean);
begin
if Value <> FCaseSensitive then
begin
FCaseSensitive := Value;
if Sorted then Sort;
end;
end;
end.
|
unit ufrmMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, Registry, Menus, SyncObjs, ComCtrls, ADOConEd,
Spin;
type
TStringArray = array of string;
TBooleanArray = array of Boolean;
TfrmMain = class(TForm)
pnlCaption: TPanel;
memLog: TMemo;
TrayIcon: TTrayIcon;
popTray: TPopupMenu;
miShowHideServer: TMenuItem;
miN1: TMenuItem;
miShutdown: TMenuItem;
tmrUpdateLog: TTimer;
CategoryPanelGroup1: TCategoryPanelGroup;
CategoryPanel1: TCategoryPanel;
cpConnection: TCategoryPanel;
btnStartService: TButton;
cbAutostartServer: TCheckBox;
CategoryPanel3: TCategoryPanel;
cbAutorunLogon: TCheckBox;
Splitter1: TSplitter;
GridPanel1: TGridPanel;
Panel1: TPanel;
edtConnectionString: TEdit;
btnEditConnectionString: TButton;
Panel2: TPanel;
edtPort: TSpinEdit;
lblPort: TLabel;
Panel3: TPanel;
cbEnableCachedResults: TCheckBox;
procedure FormCreate(Sender: TObject);
procedure btnStartServiceClick(Sender: TObject);
procedure cbAutostartServerClick(Sender: TObject);
procedure cbAutorunLogonClick(Sender: TObject);
procedure miShowHideServerClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure miShutdownClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure tmrUpdateLogTimer(Sender: TObject);
procedure btnEditConnectionStringClick(Sender: TObject);
procedure edtConnectionStringChange(Sender: TObject);
procedure edtPortChange(Sender: TObject);
procedure cbEnableCachedResultsClick(Sender: TObject);
private
svcStarted: Boolean;
LogLock: TCriticalSection;
LogStrs: TStringArray;
LogErrs: TBooleanArray;
btnStartServiceCaption: string;
procedure RefreshGUI;
procedure ServiceLogMessage(Sender: TObject; aMessage: string; aError: Boolean = False);
procedure ApplicationException(Sender: TObject; E: Exception);
public
function IsAutoRun: Boolean;
procedure SetAutoRun(aAutoRun: Boolean);
end;
var
frmMain: TfrmMain;
implementation
uses usvcMain;
{$R *.dfm}
procedure TfrmMain.FormCreate(Sender: TObject);
begin
svcStarted := False;
btnStartServiceCaption := btnStartService.Caption;
LogLock := TCriticalSection.Create;
SetLength(LogStrs, 0);
SetLength(LogErrs, 0);
Application.OnException := ApplicationException;
Service.OnLogMessage := ServiceLogMessage;
if Service.Settings.ValueExists('AppAutostart') then
cbAutostartServer.Checked := Service.Settings.ReadBool('AppAutostart');
cbAutorunLogon.Checked := IsAutoRun;
edtConnectionString.Text := Service.DBConnectionString;
edtPort.Value := Service.ServicePort;
cbEnableCachedResults.Checked := Service.CacheResponses;
RefreshGUI;
if cbAutostartServer.Checked then
btnStartService.Click;
end;
procedure TfrmMain.FormDestroy(Sender: TObject);
begin
LogLock.Free;
end;
procedure TfrmMain.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caNone;
Visible := False;
end;
procedure TfrmMain.ApplicationException(Sender: TObject; E: Exception);
begin
memLog.Lines.Add('*** APPLICATION EXCEPTION (' + E.ClassName + ')! ' + DateTimeToStr(Now) + ': ' + E.Message);
end;
procedure TfrmMain.ServiceLogMessage(Sender: TObject; aMessage: string; aError: Boolean = False);
begin
// This must be thread safe, a log can be called all over the place
LogLock.Acquire;
try
SetLength(LogStrs, Length(LogStrs) + 1);
LogStrs[ High(LogStrs)] := aMessage;
SetLength(LogErrs, Length(LogErrs) + 1);
LogErrs[ High(LogErrs)] := aError;
finally
LogLock.Release;
end;
end;
procedure TfrmMain.tmrUpdateLogTimer(Sender: TObject);
var
Strs: TStringArray;
Errs: TBooleanArray;
MsgStr: string;
i: Integer;
begin
// Get thread critical data as fast as possible onto local copies
LogLock.Acquire;
try
Strs := LogStrs;
Errs := LogErrs;
SetLength(LogStrs, 0);
SetLength(LogErrs, 0);
finally
LogLock.Release;
end;
// And begin showing the messages/errors in the log area
if Length(Strs) > 0 then
begin
memLog.Lines.BeginUpdate;
try
for i := 0 to High(Strs) do
begin
MsgStr := '';
if Errs[i] then
begin
Visible := True;
MsgStr := MsgStr + '*** Error! ';
end;
MsgStr := MsgStr + '[' + DateTimeToStr(Now) + ']: ' + Strs[i];
if memLog.Lines.Count > 10000 then
memLog.Lines.Text := 'Log cleared - reached 10000 lines';
memLog.Lines.Add(MsgStr);
end;
finally
memLog.Lines.EndUpdate;
end;
end;
end;
procedure TfrmMain.RefreshGUI;
var
Caption: string;
begin
Caption := Service.DisplayName;
if svcStarted then
Caption := Caption + ' - started'
else
Caption := Caption + ' - stopped';
pnlCaption.Caption := Caption;
end;
procedure TfrmMain.btnStartServiceClick(Sender: TObject);
var
svcStopped: Boolean;
begin
if svcStarted then
begin
svcStarted := False;
btnStartService.Caption := btnStartServiceCaption;
cpConnection.Enabled := True;
Service.ServiceStop(nil, svcStopped);
end
else
begin
svcStarted := True;
try
Service.ServiceStart(nil, svcStarted);
if svcStarted then
begin
btnStartService.Caption := 'Stop service';
cpConnection.Enabled := False;
end;
except
svcStarted := False;
raise ;
end;
end;
RefreshGUI;
end;
procedure TfrmMain.cbAutostartServerClick(Sender: TObject);
begin
Service.Settings.WriteBool('AppAutostart', cbAutostartServer.Checked);
end;
procedure TfrmMain.edtConnectionStringChange(Sender: TObject);
begin
edtConnectionString.Hint := edtConnectionString.Text;
Service.DBConnectionString := edtConnectionString.Text;
end;
procedure TfrmMain.edtPortChange(Sender: TObject);
begin
Service.ServicePort := edtPort.Value;
end;
procedure TfrmMain.cbEnableCachedResultsClick(Sender: TObject);
begin
Service.CacheResponses := cbEnableCachedResults.Checked;
end;
procedure TfrmMain.cbAutorunLogonClick(Sender: TObject);
begin
if cbAutorunLogon.Checked then
cbAutoStartServer.Checked := True;
SetAutoRun(cbAutorunLogon.Checked);
end;
procedure TfrmMain.btnEditConnectionStringClick(Sender: TObject);
begin
if EditConnectionString(Service.ADOConnection) then
begin
edtConnectionString.Text := Service.ADOConnection.ConnectionString;
end;
end;
function TfrmMain.IsAutoRun: Boolean;
var
Reg: TRegistry;
AppName: string;
begin
Result := False;
Reg := TRegistry.Create;
try
Reg.RootKey := HKEY_LOCAL_MACHINE;
if Reg.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\Run', True) then
try
AppName := ExtractFileName(ParamStr(0));
AppName := Copy(AppName, 1, Length(AppName) - Length(ExtractFileExt(AppName)));
AppName := AppName + '.' + Service.Name;
Result := SameText(Reg.ReadString(AppName), ParamStr(0));
finally
Reg.CloseKey;
end;
finally
Reg.Free;
end;
end;
procedure TfrmMain.SetAutoRun(aAutoRun: Boolean);
var
Reg: TRegistry;
AppName: string;
begin
Reg := TRegistry.Create;
try
Reg.RootKey := HKEY_LOCAL_MACHINE;
Reg.LazyWrite := False;
if not Reg.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\Run', True) then
raise Exception.Create('Cannot open registry key.');
try
AppName := ExtractFileName(ParamStr(0));
AppName := Copy(AppName, 1, Length(AppName) - Length(ExtractFileExt(AppName)));
AppName := AppName + '.' + Service.Name;
if cbAutorunLogon.Checked then
Reg.WriteString(AppName, ParamStr(0))
else
Reg.DeleteValue(AppName);
finally
Reg.CloseKey;
end;
finally
Reg.Free;
end;
end;
procedure TfrmMain.miShowHideServerClick(Sender: TObject);
begin
Application.BringToFront;
frmMain.Visible := not frmMain.Visible;
end;
procedure TfrmMain.miShutdownClick(Sender: TObject);
begin
Application.Terminate;
end;
end.
|
unit FIToolkit.Logger.Consts;
interface
uses
FIToolkit.Logger.Types,
FIToolkit.Localization;
const
{ Severity consts }
SEVERITY_NONE = Low(TLogMsgSeverity);
SEVERITY_MIN = TLogMsgSeverity(SEVERITY_NONE + 1);
SEVERITY_MAX = High(TLogMsgSeverity);
SEVERITY_DEBUG = TLogMsgSeverity(SEVERITY_MIN + 1);
SEVERITY_INFO = TLogMsgSeverity(SEVERITY_DEBUG + 98);
SEVERITY_WARNING = TLogMsgSeverity(SEVERITY_INFO + 100);
SEVERITY_ERROR = TLogMsgSeverity(SEVERITY_WARNING + 100);
SEVERITY_FATAL = TLogMsgSeverity(SEVERITY_ERROR + 100);
{ Common consts }
ARR_MSGTYPE_TO_MSGSEVERITY_MAPPING : array [TLogMsgType] of TLogMsgSeverity = (
SEVERITY_NONE, SEVERITY_DEBUG, SEVERITY_INFO, SEVERITY_WARNING, SEVERITY_ERROR, SEVERITY_FATAL, SEVERITY_MAX
);
{ Plain text output }
CHR_PTO_PREAMBLE_COMPENSATOR_FILLER = Char(' ');
resourcestring
{$IF LANGUAGE = LANG_EN_US}
{$INCLUDE 'Locales\en-US.inc'}
{$ELSEIF LANGUAGE = LANG_RU_RU}
{$INCLUDE 'Locales\ru-RU.inc'}
{$ELSE}
{$MESSAGE FATAL 'No language defined!'}
{$ENDIF}
implementation
end.
|
unit strings_3;
interface
implementation
var S: string;
procedure Test;
begin
SetLength(S, 3);
S[0] := 'A';
S[1] := 'B';
S[2] := 'C';
end;
initialization
Test();
finalization
Assert(S = 'ABC');
end. |
unit TestuThread_Controller;
{
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, Vcl.ComCtrls, System.SysUtils, uThread_Controller, System.Classes;
type
// Test methods for class TSoftThread
TestTSoftThread = class(TTestCase)
strict private
FSoftThread: TSoftThread;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestSetIntervalo;
procedure TestSetProgressBar;
procedure TestExecute;
end;
implementation
procedure TestTSoftThread.SetUp;
begin
FSoftThread := TSoftThread.Create(True);
end;
procedure TestTSoftThread.TearDown;
begin
FSoftThread.Free;
FSoftThread := nil;
end;
procedure TestTSoftThread.TestSetIntervalo;
var
Intervalo: Integer;
begin
Intervalo := 10;
try
FSoftThread.SetIntervalo(Intervalo);
finally
CheckTrue(true);
end;
end;
procedure TestTSoftThread.TestSetProgressBar;
var
ProgressBar: TProgressBar;
begin
try
FSoftThread.SetProgressBar(ProgressBar);
finally
CheckTrue(true);
end;
end;
procedure TestTSoftThread.TestExecute;
var
ProgressBar: TProgressBar;
begin
try
FSoftThread := TSoftThread.Create(True);
FSoftThread.SetIntervalo(10);
FSoftThread.SetProgressBar(ProgressBar);
FSoftThread.Execute;
finally
CheckTrue(true);
end;
// TODO: Validate method results
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTSoftThread.Suite);
end.
|
PROGRAM Schnittmengen;
const testA1: ARRAY [1..6] OF integer = (1, 2, 3, 5, 7, 13);
const testA2: ARRAY [1..7] OF integer = (1, 3, 5, 20, 9, 13, 15);
FUNCTION IsSorted(a: ARRAY of integer): boolean;
var i: integer;
BEGIN (* IsSorted *)
FOR i := 1 TO Length(a) - 1 DO BEGIN
IF (a[i] >= a[i-1]) THEN BEGIN
//
END ELSE BEGIN
Exit(false);
END; (* IF *)
END; (* FOR *)
IsSorted := true;
END; (* IsSorted *)
PROCEDURE Intersect(a1: ARRAY of integer; n1: integer;
a2: ARRAY of integer; n2: integer; var a3: ARRAY of integer; var n3: integer);
var i, j: integer;
BEGIN (* Intersect *)
n3 := 0;
IF (IsSorted(a1) AND IsSorted(a2)) THEN BEGIN
IF (Length(a1) > Length(a2)) THEN BEGIN
FOR i := 0 TO Length(a2) - 1 DO BEGIN
FOR j := 0 TO Length(a1) - 1 DO BEGIN
IF (a2[i] = a1[j]) THEN BEGIN
IF (n3 <= High(a3)) THEN BEGIN
a3[n3] := a2[i];
Inc(n3);
END ELSE BEGIN
break;
END; (* IF *)
END; (* IF *)
END; (* FOR *)
END; (* FOR *)
END ELSE BEGIN
FOR i := 0 TO Length(a1) - 1 DO BEGIN
FOR j := 0 TO Length(a2) - 1 DO BEGIN
IF (a1[i] = a2[j]) THEN BEGIN
IF (n3 <= High(a3)) THEN BEGIN
a3[n3] := a1[i];
Inc(n3);
END ELSE BEGIN
break;
END; (* IF *)
END; (* IF *)
END; (* FOR *)
END; (* FOR *)
END; (* IF *)
END ELSE BEGIN
n3 := -1;
END; (* IF *)
END; (* Intersect *)
var zielArray: ARRAY OF integer;
i, zielN: integer;
BEGIN (* Schnittmengen *)
FOR i := 1 TO High(testA1) DO BEGIN
Write(testA1[i], ' ');
END; (* FOR *)
WriteLn();
FOR i := 1 TO High(testA2) DO BEGIN
Write(testA2[i], ' ');
END; (* FOR *)
WriteLn();
Write('Geben Sie die groesse der Schnittmenge ein: ');
Read(zielN);
setLength(zielArray, zielN);
Intersect(testA1, Length(testA1), testA2, Length(testA2), zielArray, zielN);
FOR i := 0 TO ZielN - 1 DO BEGIN
Write(zielArray[i], ', ');
END; (* FOR *)
WriteLn('ZielN: ', zielN);
END. (* Schnittmengen *) |
unit AConsultaCodigoRepresentante;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios,
StdCtrls, Buttons, Grids, DBGrids, Tabela, Componentes1, ExtCtrls,
PainelGradiente, DB, DBClient, ConstMsg;
type
TFConsultaCodigoRepresentante = class(TFormularioPermissao)
PainelGradiente1: TPainelGradiente;
PanelColor1: TPanelColor;
PanelColor2: TPanelColor;
Label1: TLabel;
Label2: TLabel;
GClientes: TDBGridColor;
GPedidos: TDBGridColor;
BExcluirCliente: TBitBtn;
BExcluirPedido: TBitBtn;
BFechar: TBitBtn;
dsCadClientes: TDataSource;
dsCadOrcamentos: TDataSource;
CADCLIENTES: TSQL;
CADORCAMENTOS: TSQL;
CADORCAMENTOSCODFILIAL: TFMTBCDField;
CADORCAMENTOSNUMPEDIDO: TFMTBCDField;
CADCLIENTESCODCLIENTE: TFMTBCDField;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BFecharClick(Sender: TObject);
procedure BExcluirPedidoClick(Sender: TObject);
procedure BExcluirClienteClick(Sender: TObject);
private
{ Private declarations }
procedure AbreTabela;
procedure ExcluiCliente;
procedure ExcluiPedido;
public
{ Public declarations }
end;
var
FConsultaCodigoRepresentante: TFConsultaCodigoRepresentante;
implementation
uses APrincipal;
{$R *.DFM}
{ **************************************************************************** }
procedure TFConsultaCodigoRepresentante.FormCreate(Sender: TObject);
begin
{ abre tabelas }
{ chamar a rotina de atualização de menus }
AbreTabela;
end;
{ *************************************************************************** }
procedure TFConsultaCodigoRepresentante.AbreTabela;
begin
CADORCAMENTOS.Open;
CADCLIENTES.Open;
BExcluirCliente.Enabled := not CADCLIENTES.Eof;
BExcluirPedido.Enabled := not CADORCAMENTOS.Eof;
end;
{ *************************************************************************** }
procedure TFConsultaCodigoRepresentante.BExcluirClienteClick(Sender: TObject);
begin
ExcluiCliente;
end;
{ *************************************************************************** }
procedure TFConsultaCodigoRepresentante.BExcluirPedidoClick(Sender: TObject);
begin
ExcluiPedido;
end;
{ *************************************************************************** }
procedure TFConsultaCodigoRepresentante.BFecharClick(Sender: TObject);
begin
close;
end;
{ *************************************************************************** }
procedure TFConsultaCodigoRepresentante.ExcluiCliente;
begin
CADCLIENTES.Delete;
end;
{ *************************************************************************** }
procedure TFConsultaCodigoRepresentante.ExcluiPedido;
begin
CADORCAMENTOS.Delete;
end;
{ *************************************************************************** }
procedure TFConsultaCodigoRepresentante.FormClose(Sender: TObject; var Action: TCloseAction);
begin
{ fecha tabelas }
{ chamar a rotina de atualização de menus }
Action := CaFree;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Ações Diversas
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
Initialization
{ *************** Registra a classe para evitar duplicidade ****************** }
RegisterClasses([TFConsultaCodigoRepresentante]);
end.
|
unit Unit1;
interface
uses
Winapi.OpenGL,
System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms,
Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls,
//GLScene
GLObjects, GLScene, GLWin32Viewer, GLSkydome,
GLCadencer, GLParticleFX, GLTeapot, GLGeomObjects,
GLContext, GLCrossPlatform, GLCoordinates, GLBaseClasses;
type
TForm1 = class(TForm)
GLScene1: TGLScene;
GLSceneViewer1: TGLSceneViewer;
GLMemoryViewer1: TGLMemoryViewer;
GLCamera1: TGLCamera;
GLLightSource1: TGLLightSource;
Torus1: TGLTorus;
CubeMapCamera: TGLCamera;
Sphere1: TGLSphere;
Cylinder1: TGLCylinder;
Teapot1: TGLTeapot;
SkyDome1: TGLSkyDome;
Cube1: TGLCube;
GLCadencer1: TGLCadencer;
Timer1: TTimer;
Panel1: TPanel;
CBDynamic: TCheckBox;
LabelFPS: TLabel;
procedure GLSceneViewer1MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
procedure Timer1Timer(Sender: TObject);
procedure GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
procedure GLSceneViewer1BeforeRender(Sender: TObject);
private
{ Private declarations }
procedure GenerateCubeMap;
public
{ Public declarations }
mx, my : Integer;
CubmapSupported : Boolean;
cubeMapWarnDone : Boolean;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.GenerateCubeMap;
begin
// Don't do anything if cube maps aren't supported
if not CubmapSupported then begin
if not cubeMapWarnDone then
ShowMessage('Your graphics hardware does not support cube maps...');
cubeMapWarnDone:=True;
Exit;
end;
// Here we generate the new cube map, from CubeMapCamera (a child of the
// teapot in the scene hierarchy)
with Teapot1 do begin
// hide the teapot while rendering the cube map
Visible:=False;
// render cube map to the teapot's texture
GLMemoryViewer1.RenderCubeMapTextures(Material.Texture);
// teapot visible again
Material.Texture.Disabled:=False;
Visible:=True;
end;
end;
procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
begin
if CBDynamic.Checked then begin
// make things move
Teapot1.Position.Y:=2*Sin(newTime);
Torus1.RollAngle:=newTime*15;
// generate the cube map
GenerateCubeMap;
end;
GLSceneViewer1.Invalidate;
end;
// Standard issue mouse movement
procedure TForm1.GLSceneViewer1MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
mx:=x;
my:=y;
end;
procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
begin
if Shift<>[] then begin
GLCamera1.MoveAroundTarget(my-y, mx-x);
mx:=x;
my:=y;
end;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
LabelFPS.Caption:=Format('%.1f FPS', [GLSceneViewer1.FramesPerSecond]);
GLSceneViewer1.ResetPerformanceMonitor;
end;
procedure TForm1.GLSceneViewer1BeforeRender(Sender: TObject);
begin
CubmapSupported := GL.ARB_texture_cube_map;
GLSceneViewer1.BeforeRender := nil;
end;
end.
|
{$i deltics.interfacedobjects.inc}
unit Deltics.InterfacedObjects.WeakInterfaceReference;
interface
uses
Deltics.Multicast;
type
TWeakInterfaceReference = class(TObject, IUnknown,
IOn_Destroy)
private
fRef: Pointer;
fOnDestroy: IOn_Destroy;
function get_Ref: IUnknown;
procedure OnTargetDestroyed(aSender: TObject);
public
constructor Create(const aRef: IUnknown);
destructor Destroy; override;
procedure UpdateReference(const aRef: IUnknown);
function IsReferenceTo(const aOther: IUnknown): Boolean;
// IUnknown
protected
{
IUnknown is delegated to the contained reference using "implements"
ALL methods of IUnknown are delegated to the fRef, meaning that
TWeakInterface does not need to worry about being reference counted
itself (it won't be).
}
property Ref: IUnknown read get_Ref implements IUnknown;
// IOn_Destroy
protected
function get_OnDestroy: IOn_Destroy;
property On_Destroy: IOn_Destroy read get_OnDestroy implements IOn_Destroy;
end;
implementation
uses
SysUtils;
{ TWeakInterfaceRef ------------------------------------------------------------------------------ }
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
constructor TWeakInterfaceReference.Create(const aRef: IInterface);
begin
inherited Create;
UpdateReference(aRef);
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
destructor TWeakInterfaceReference.Destroy;
begin
UpdateReference(NIL);
inherited;
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
function TWeakInterfaceReference.get_OnDestroy: IOn_Destroy;
begin
if NOT Assigned(fOnDestroy) then
fOnDestroy := TOnDestroy.Create(self);
result := fOnDestroy;
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
function TWeakInterfaceReference.get_Ref: IUnknown;
begin
result := IUnknown(fRef);
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure TWeakInterfaceReference.OnTargetDestroyed(aSender: TObject);
begin
UpdateReference(NIL);
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure TWeakInterfaceReference.UpdateReference(const aRef: IInterface);
var
onDestroy: IOn_Destroy;
begin
if Supports(IUnknown(fRef), IOn_Destroy, onDestroy) then
onDestroy.Remove(OnTargetDestroyed);
fRef := Pointer(aRef as IUnknown);
if Supports(aRef, IOn_Destroy, onDestroy) then
onDestroy.Add(OnTargetDestroyed);
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
function TWeakInterfaceReference.IsReferenceTo(const aOther: IInterface): Boolean;
begin
if Assigned(self) and Assigned(fRef) then
result := Pointer(aOther as IUnknown) = fRef
else
result := (aOther = NIL);
end;
end.
|
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, Spin,
StdCtrls;
type
{ TfrmFee }
TfrmFee = class(TForm)
btnFee: TButton;
lblFee: TLabel;
sedTakings: TSpinEdit;
procedure btnFeeClick(Sender: TObject);
private
{ private declarations }
procedure CalcFee(Takings: integer; var Feestr: string);
public
{ public declarations }
end;
var
frmFee: TfrmFee;
implementation
{$R *.lfm}
{ TfrmFee }
procedure TfrmFee.CalcFee(Takings: integer; var FeeStr: string);
var
Fee: double;
begin
Fee:=Takings*0.075+20;
FeeStr:='The fee is ' + FloatToStrF(Fee, ffCurrency, 15, 2);
end;
procedure TfrmFee.btnFeeClick(Sender: TObject);
var
FeeStr: string;
begin
CalcFee(sedTakings.Value, FeeStr);
lblFee.Caption:=FeeStr;
end;
end.
|
unit MetroBase;
{ TODO :
Code of TNetwork.CreateFromFile}
interface
uses
Contnrs, IniFiles;
//==============================================================================
// Station
// A station has:
// - a code: a short key that serves to identify the station uniquely within
// the system, e.g. 'CDG'
// - a name: the name of the station as it appears on maps etc., e.g.
// 'Charles de Gaulle - Etoile'.
//
// The class TStationR is an abstract class providing read-only access to the
// data of a station.
// The class TStationRW is a descendant of TStationR; it provides a concrete
// representation and read/write access to the data of a station.
//==============================================================================
type
TStationR =
class(TObject)
public
// scratch data field for use by planners etc. -----------------------------
Data: TObject;
// primitive queries -------------------------------------------------------
function GetCode: String; virtual; abstract;
function GetName: String; virtual; abstract;
// invariants --------------------------------------------------------------
// I0: ValidStationCode(GetCode) and ValidStationName(GetName)
end;
TStationRW =
class(TStationR)
private
FCode: String;
FName: String;
public
// construction ------------------------------------------------------------
constructor Create(ACode: String; AName: String);
// pre: ValidStationCode(ACode) and ValidStationName(AName)
// post: (GetCode = ACode) and (GetName = AName)
// TStationR overrides =====================================================
// primitive queries -------------------------------------------------------
function GetCode: String; override;
function GetName: String; override;
// new methods =============================================================
// commands ----------------------------------------------------------------
procedure Rename(AName: String);
// pre: ValidStationName(AName)
// post: GetName = AName
end;
//==============================================================================
// StationSet
//
// A stationset is a finite enumerable set of stations.
//
// The class TStationSetR is an abstract class providing read-only access to the
// data of a stationset.
// The class TStationSetRW is a descendant of TStationR; it provides a concrete
// representation and read/write access to a stationset.
//
//==============================================================================
TStationSetR =
class(TObject)
// primitive queries -------------------------------------------------------
function Count: Integer; virtual; abstract;
// pre: true
// ret: |Abstr|
function GetStation(I: Integer): TStationR; virtual; abstract;
// pre: 0 <= I < Count
// ret: Abstr[I]
// derived queries ---------------------------------------------------------
function IsEmpty: Boolean;
// pre: true
// ret: Count = 0
function HasStation(AStation: TStationR): Boolean;
// pre: true
// ret: (exists I: 0 <= I < Count: GetStation(I) = AStation)
function HasCode(ACode: String): Boolean;
// pre: true
// ret: IndexOfCode(ACode) <> -1
function HasName(AName: String): Boolean;
// pre: true
// ret: IndexOfName(AName) <> -1
function IndexOfCode(ACode: String): Integer;
// pre: true
// ret: I such that GetStation(I).GetCode = ACode, or else -1
function IndexOfName(AName: String): Integer;
// pre: true
// ret: I such that GetStation(I).GetName = AName, or else -1
// model variables ---------------------------------------------------------
// Abstr: set of TStationRW
// invariants --------------------------------------------------------------
// Unique:
// (forall I,J: 0<=I<J<Count:
// - GetStation(I) <> GetStation(J)
// - GetStation(I).GetCode <> GetStation(J).GetCode
// - GetStation(I).GetName <> GetStation(J).GetName
// )
end;
TStationSetRW =
class(TStationSetR)
protected
// fields ------------------------------------------------------------------
FList: TObjectList;
// invariants --------------------------------------------------------------
// Abstr = {FList[I] as TStationR| 0<=I<FList.Count}
public
// construction/destruction ------------------------------------------------
constructor Create;
// pre: true
// post: Abstr = {}
destructor Destroy; override;
// TStationSetR overrides ==================================================
// primitive queries -------------------------------------
function Count: Integer; override;
// pre: true
// ret: |Abstr|
function GetStation(I: Integer): TStationR; override;
// pre: 0 <= I < Count
// ret: Abstr[I]
// new methods =============================================================
// preconditions for commands ----------------------------------------------
function CanAddStation(ACode: String; AName: String): Boolean; virtual;
// pre: true
// ret: ValidStationCode(ACode), ValidStationName(AName),
// not HasCode(ACode), not HasName(AName)
function CanDeleteStation(AStation: TStationR): Boolean; virtual;
// pre: true
// ret: true (may be overridden in subclasses)
function CanDeleteAll: Boolean; virtual;
// pre: true
// ret: true (may be overridden in subclasses)
// commands ----------------------------------------------------------------
procedure AddStation(ACode: String; AName: String);
// pre: CanAddStation(ACode, AName)
// post: Abstr = old Abstr U {(ACode, AName)} (abuse of notation)
procedure DeleteStation(AStation: TStationR);
// pre: CanDeleteStation(AStation)
// post: Abstr = old Abstr - {(ACode, AName)} (abuse of notation)
procedure DeleteAll;
// pre: CanDeleteAll
// post: Abstr = {}
end;
//==============================================================================
// Line
//
// A line has:
// - a code: a short key that serves to identify the line uniquely within
// the system, e.g. 'ERM'.
// - a name: the name of the line as it appears on maps etc., e.g.
// 'Erasmuslijn' or '7bis'.
// - a sequence of stops; each stop is a station.
// - a set of options, e.g.: oneway, circular.
//
// The class TLineR is an abstract class providing read-only access to the
// data of a line.
// The class TLineRW is a descendant of TLineR; it provides a concrete
// representation and read/write access to the data of a line.
//==============================================================================
type
TLineOption = (loOneWay, loCircular);
TLineOptions = set of TLineOption;
TLineR =
class(TObject)
public
// scratch data field, used by planners etc. -------------------------------
Data: TObject;
// primitive queries -------------------------------------------------------
function GetCode: String; virtual; abstract;
function GetName: String; virtual; abstract;
function GetOptions: TLineOptions; virtual; abstract;
function Count: Integer; virtual; abstract;
// ret: |Abstr|
function IndexOf(AStation: TStationR): Integer; virtual; abstract;
// pre: true
// ret: I such that Abstr[I] = AStation, or else -1
function Stop(I: Integer): TStationR; virtual; abstract;
// pre: 0 <= I < Count
// ret: Abstr[I]
// derived queries ---------------------------------------------------------
function TerminalA: TStationR;
// pre: Count > 0
// ret: Stop(0)
function TerminalB: TStationR;
// pre: Count > 0
// ret: Stop(Count-1)
function IsOneWay: Boolean;
// pre: true
// ret: loOneWay in GetOptions
function IsCircular: Boolean;
// pre: true
// ret: loCircular in GetOptions
function HasStop(AStation: TStationR): Boolean;
// pre: true
// ret: (exists I: 0 <= I < Count: Stop(I) = AStation )
// model variables ---------------------------------------------------------
// Abstr: row of TStationR
// invariants --------------------------------------------------------------
// I0: ValidLineCode(GetCode) and ValidLineName(GetName)
// Stops_Unique:
// (forall I,J: 0<=I<J<Count: Stop(I) <> Stop(J))
end;
TLineRW =
class(TLineR)
protected
FCode: String;
FName: String;
FOptions: TLineOptions;
FList: TObjectList;
public
// construction/destruction ------------------------------------------------
constructor Create(ACode: String; AName: String; AOptions: TLineOptions);
// pre: ValidLineCode(ACode), ValidLineName(AName)
// post: GetCode = ACode, GetName = AName, GetOptions = AOptions
destructor Destroy; override;
// TLineR overrides ========================================================
// primitive queries -------------------------------------------------------
function GetCode: String; override;
function GetName: String; override;
function GetOptions: TLineOptions; override;
function Count: Integer; override;
// ret: |Abstr|
function IndexOf(AStation: TStationR): Integer; override;
// pre: true
// ret: I such that Abstr[I] = AStation, or else -1
function Stop(I: Integer): TStationR; override;
// pre: 0 <= I < Count
// ret: Abstr[I]
// new methods =============================================================
// preconditions for commands ----------------------------------------------
function CanAddStop(AStation: TStationR): Boolean;
// pre: true
// ret: not HasStop(AStation)
function CanInsertStop(I: Integer; AStation: TStationR): Boolean;
// pre: true
// ret: (0 <= I <= Count) and not HasStop(AStation)
function CanSwapStops(I, J: Integer): Boolean; virtual;
// pre: true
// ret: (0 <= I <= Count) and (0 <= J <= Count)
function CanDeleteStop(I: Integer): Boolean; virtual;
// pre: true
// ret: 0 <= I < Count
function CanDeleteAll: Boolean; virtual;
// pre: true
// ret: true
// commands ----------------------------------------------------------------
procedure AddStop(AStation: TStationR);
// pre: CanAddStop(AStation)
// post: Abstr = old Abstr ++ [AStation]
procedure InsertStop(I: Integer; AStation: TStationR);
// pre: CanInsertStop(I, AStation)
// post: Abstr = (old Abstr[0..I) ++ [AStation] ++ (old Abstr[I..Count))
procedure SwapStops(I, J: Integer);
// pre: CanSwapStops(I,J)
// post:
// let X = old Abstr[I], Y = old Abstr[J},
// S0 = old Abstr[0..I), S1 = old Abstr[I+1..J),
// S2 = old Abstr[J+1..Count)
// in Abstr = S0 ++ [Y] ++ S1 ++ [X] ++ S2
procedure DeleteStop(I: Integer);
// pre: CanDeleteStop(I)
// post: Abstr = old Abstr[0..I) ++ old Abstr[I+1..Count)
procedure DeleteAll;
// pre: CanDeleteAll
// post: Abstr = []
end;
//==============================================================================
// LineSet
//
// A lineset is a finite enumerable set of lines.
//
// The class TLineSetR is an abstract class providing read-only access to the
// data of a lineset.
// The class TLineSetRW is a descendant of TLineSetR; it provides a concrete
// representation and read/write access to a lineset.
//
//
// NOTE: The organization of the LineSet classes is almost the same as that of
// the Stationset classes. What is really needed here is a parameterized class
// Set[T] which can be instantiated for stations and lines respectively.
// Currently, Delphi does not provide such a notion.
//==============================================================================
TLineSetR =
class(TObject)
public
// primitive queries -------------------------------------------------------
function Count: Integer; virtual; abstract;
// pre: true
// ret: |Abstr|
function GetLine(I: Integer): TLineR; virtual; abstract;
// pre: 0 <= I < Count
// ret: Abstr[I]
// derived queries ---------------------------------------------------------
function IsEmpty: Boolean;
// pre: true
// ret: Count = 0
function HasLine(ALine: TLineR): Boolean;
// pre: true
// ret: (exists I: 0 <= I < Count: GetLine(I) = ALine )
function HasCode(ACode: String): Boolean;
// pre: true
// ret: (exists I: 0 <= I < Count: GetLine(I).GetCode = ACode )
function HasName(AName: String): Boolean;
// pre: true
// ret: (exists I: 0 <= I < Count: GetLine(I).GetName = AName )
function HasStop(AStation: TStationR): Boolean;
// pre: true
// ret: (exists I: 0 <= I < Count: GetLine(I).HasStop(AStation))
function IndexOfCode(ACode: String): Integer;
// pre: true
// ret: I such that GetLine(I).GetCode = ACode, or else -1
function IndexOfName(AName: String): Integer;
// pre: true
// ret: I such that GetLine(I).GetName = AName, or else -1
// model variables ---------------------------------------------------------
// Abstr: set of TLineR
// invariants --------------------------------------------------------------
// Unique:
// (forall I,J: 0<=I<J<Count:
// - GetLine(I) <> GetLine(J)
// - GetLine(I).GetCode <> GetLine(J).GetCode
// - GetLine(I).GetName <> GetLine(J).GetName
// )
end;
TLineSetRW =
class(TLineSetR)
protected
// fields ------------------------------------------------------------------
FList: TObjectList;
// invariants --------------------------------------------------------------
// Abstr = {FList[I] as TLineR| 0<=I<FList.Count}
public
// construction/destruction ------------------------------------------------
constructor Create;
// pre: true
// post: Abstr = {}
destructor Destroy; override;
// TLineSetR overrides =====================================================
// primitive queries -------------------------------------
function Count: Integer; override;
// pre: true
// ret: |Abstr|
function GetLine(I: Integer): TLineR; override;
// pre: 0 <= I < Count
// ret: Abstr[I]
// new methods =============================================================
// preconditions for commands ----------------------------------------------
function CanAddLine(ALine: TLineR): Boolean; virtual;
// pre: true
// ret: not HasLine(ALine) and not HasCode(ALine.GetCode) and
// not HasName(ALine.GetName)
function CanDeleteLine(ALine: TLineR): Boolean; virtual;
// pre: true
// ret: true (may be overridden in subclasses)
function CanDeleteAll: Boolean; virtual;
// pre: true
// ret: true (may be overridden in subclasses)
// commands ----------------------------------------------------------------
procedure AddLine(ALine: TLineR);
// pre: CanAddLine(ALine)
// post: Abstr = old Abstr U {ALine}
procedure DeleteLine(ALine: TLineR);
// pre: CanDeleteLine(ALine)
// post: Abstr = old Abstr - {ALine}
procedure DeleteAll;
// pre: CanDeleteAll
// post: Abstr = {}
end;
//==============================================================================
// Network
//
// A network has:
// - a name
// - a stationset S
// - a lineset L
// Consistency invariant
// - every station occurring in a line of L should also occur in S
//
// A network can be read from and written to a .INI file
//
// A network can be edited by adding or deleting a station or a line.
// The preconditions of the editing operations guarantee that the consistency
// invariant is preserved.
//==============================================================================
TNetwork =
class(TObject)
protected
FName: String;
FStationSet: TStationSetRW;
FLineSet: TLineSetRW;
public
// construction/destruction ------------------------------------------------
constructor Create(
AName: String;
AStationSet: TStationSetRW;
ALineSet: TLineSetRW);
// pre: ValidNetworkName(AName), IsConsistent(AStationset, ALineSet)
// post: GetName = AName, GetStationset = AStationset, GetLineset = ALineSet
constructor CreateEmpty(AName: String);
// pre: true
// post: GetName = AName, GetStationSet.Count = 0, GetLineSet.Count = 0
constructor CreateFromFile(AFile: TMemIniFile);
// pre: file AFileName contains a description of a network (N, SS LS);
// IsConsistent(SS,LS)
// post: GetName = N, GetStationSet = SS, GetLineSet = LS
destructor Destroy; override;
// persistence -------------------------------------------------------------
procedure WriteToFile(AFile: TMemIniFile);
// pre: true
// post: file AFileName contains a description of network
// (GetName, GetStationSet, GetLineSet)
// basic queries -----------------------------------------------------------
function GetName: string;
function GetStationSet: TStationSetR;
function GetLineSet: TLineSetR;
// derived queries ---------------------------------------------------------
function IsConsistentLine(ALine: TLineR; AStationSet: TStationSetR): Boolean;
// pre: true
// ret: (forall J: 0<=J<ALine.Count: AStationSet.HasStation(ALine.Stop(J))
function IsConsistentNetwork(
AStationSet: TStationSetR; ALineSet: TLineSetR): Boolean;
// pre: true
// ret:
// let SS = AStationSet, LS = ALineSet
// (forall I: 0<=I<LS.Count: IsConsistentLine(LS.GetLine(I), SS)
// preconditions for commands ----------------------------------------------
function CanAddStation(ACode: String; AName: String): Boolean; virtual;
// pre: true
// ret: GetStationSet.CanAddStation(ACode, AName)
function CanDeleteStation(AStation: TStationR): Boolean; virtual;
// pre: true
// ret: not GetLineSet.HasStop(AStation)
function CanAddLine(ALine: TLineR): Boolean; virtual;
// pre: true
// ret: IsConsistentLine(ALine, GetStationSet) and
// (GetLineSet as TLineSetRW).CanAddLine(ALine)
function CanDeleteLine(ALine: TLineR): Boolean; virtual;
// pre: true
// ret: (GetLineSet as TLineSetRW).CanDeleteLine(ALine)
function CanDeleteAll: Boolean; virtual;
// pre: true
// ret: true
// commands ----------------------------------------------------------------
procedure AddStation(ACode: String; AName: String); virtual;
// pre: CanAddStation(ACode, AName)
// effect: (GetStationSet as TStationSetRW).AddStation(ACode, AName)
procedure DeleteStation(AStation: TStationR); virtual;
// pre: CanDeleteStation(AStation)
// effect: (GetStationSet as TStationSetRW).DeleteStation(AStation)
procedure AddLine(ALine: TLineR); virtual;
// pre: CanAddLine(ALine)
// effect: (GetLineSet as TLineSetRW).AddLine(ALine)
procedure DeleteLine(ALine: TLineR); virtual;
// pre: CanDeleteLine(ALine)
// effect: (GetLineSet as TLineSetRW).DeleteLine(ALine)
procedure DeleteAll; virtual;
// pre: CanDeleteAll
// post: GetStationSet.Count = 0, GetLineSet.Count = 0
// invariants --------------------------------------------------------------
// Consistent:
// IsConsistentNetwork(GetStationSet, GetLineSet);
// Connected:
// (not yet necessary)
end;
// String validators -----------------------------------------------------------
const
csSpecial = ['-', ' ', '''', '.'];
csDigit = ['0'..'9'];
csLetterU = ['A'..'Z'];
csLetterL = ['a'..'z'];
csAccentedL = ['á', 'à', 'â', 'ä', 'é', 'è', 'ê', 'ë', 'í', 'ì', 'î', 'ï',
'ó', 'ò', 'ô', 'ö', 'ú', 'ù', 'û', 'ü', 'ç'];
csAccentedU = ['Á', 'À', 'Â', 'Ä', 'É', 'È', 'Ê', 'Ë', 'Í', 'Ì', 'Î', 'Ï',
'Ó', 'Ò', 'Ô', 'Ö', 'Ú', 'Ù', 'Û', 'Ü', 'Ç'];
csLetter = csLetterU + csLetterL + csAccentedU + csAccentedL;
csCodeSet = csLetter + csDigit;
csNameSet = csLetter + csDigit + csSpecial;
function ValidStationCode(AString: String): Boolean;
// ret: AString in csCodeSet+
function ValidStationName(AString: String): Boolean;
// ret: AString in csNameSet+
function ValidLineCode(AString: String): Boolean;
// ret: AString in csCodeSet+
function ValidLineName(AString: String): Boolean;
// ret: AString in csNameSet+
function ValidNetworkName(AString: String): Boolean;
// ret: Astring in csNameSet+
implementation //===============================================================
uses
Classes, StrUtils, SysUtils;
{ TStationRW ------------------------------------------------------------------}
constructor TStationRW.Create(ACode, AName: String);
begin
Assert(ValidStationCode(ACode),
Format('TStationRW.Create.pre: ValidStationCode: %s', [ACode]));
Assert(ValidStationName(AName),
Format('TStationRW.Create.pre: ValidStationName: %s', [AName]));
inherited Create;
FCode := ACode;
FName := AName;
end;
function TStationRW.GetCode: String;
begin
Result := FCode;
end;
function TStationRW.GetName: String;
begin
Result := FName;
end;
procedure TStationRW.Rename(AName: String);
begin
Assert(ValidStationName(AName),
Format('TStationRW.Rename.pre: ValidStationName: %s', [AName]));
end;
{ TStationSetR ----------------------------------------------------------------}
function TStationSetR.HasCode(ACode: String): Boolean;
begin
Result := IndexOfCode(ACode) <> -1;
end;
function TStationSetR.HasName(AName: String): Boolean;
begin
Result := IndexOfName(AName) <> -1;
end;
function TStationSetR.HasStation(AStation: TStationR): Boolean;
var
I: Integer;
begin
Result := false;
for I := 0 to Count - 1 do
if GetStation(I) = AStation
then Result := true;
end;
function TStationSetR.IndexOfCode(ACode: String): Integer;
var
I: Integer;
begin
Result := -1;
for I := 0 to Count - 1 do
if GetStation(I).GetCode = ACode
then Result := I;
end;
function TStationSetR.IndexOfName(AName: String): Integer;
var
I: Integer;
begin
Result := -1;
for I := 0 to Count - 1 do
if GetStation(I).GetName = AName
then Result := I;
end;
function TStationSetR.IsEmpty: Boolean;
begin
Result := Count = 0;
end;
{ TStationSetRW ---------------------------------------------------------------}
procedure TStationSetRW.AddStation(ACode, AName: String);
begin
Assert(CanAddStation(ACode, AName),
Format('TStationSetRW.AddStation.pre: %s, %s', [ACode, AName]));
FList.Add(TStationRW.Create(ACode, AName));
end;
function TStationSetRW.CanAddStation(ACode, AName: String): Boolean;
begin
Result :=
ValidStationCode(ACode) and
ValidStationName(AName) and
not HasCode(ACode) and
not HasName(AName);
end;
function TStationSetRW.CanDeleteAll: Boolean;
begin
Result := true;
end;
function TStationSetRW.CanDeleteStation(AStation: TStationR): Boolean;
begin
Result := true;
end;
function TStationSetRW.Count: Integer;
begin
Result := FList.Count;
end;
constructor TStationSetRW.Create;
begin
inherited Create;
FList := TObjectList.Create;
end;
procedure TStationSetRW.DeleteAll;
begin
FList.Clear;
end;
procedure TStationSetRW.DeleteStation(AStation: TStationR);
begin
FList.Remove(AStation);
end;
destructor TStationSetRW.Destroy;
begin
FList.Free;
inherited;
end;
function TStationSetRW.GetStation(I: Integer): TStationR;
begin
Assert((0 <= I) and (I < Count),
Format('TStationSetRW.GetStation.pre: I = %d', [I]));
Result := FList.Items[I] as TStationR;
end;
{ TLineR ----------------------------------------------------------------------}
function TLineR.HasStop(AStation: TStationR): Boolean;
var
I: Integer;
begin
Result := false;
for I := 0 to Count - 1 do
if Stop(I) = AStation
then Result := true;
end;
function TLineR.IsCircular: Boolean;
begin
Result := loCircular in GetOptions;
end;
function TLineR.IsOneWay: Boolean;
begin
Result := loOneWay in GetOptions;
end;
function TLineR.TerminalA: TStationR;
begin
Assert(Count > 0, 'TLineR.TerminalA.pre');
Result := Stop(0);
end;
function TLineR.TerminalB: TStationR;
begin
Assert(Count > 0, 'TLineR.TerminalB.pre');
Result := Stop(Count - 1);
end;
{ TLineRW ---------------------------------------------------------------------}
procedure TLineRW.AddStop(AStation: TStationR);
begin
Assert(CanAddStop(AStation),
Format('TLineRW.AddStop.pre: %s', [AStation.GetCode]));
FList.Add(AStation);
end;
function TLineRW.CanAddStop(AStation: TStationR): Boolean;
begin
Result := not HasStop(AStation);
end;
function TLineRW.CanDeleteAll: Boolean;
begin
Result := true;
end;
function TLineRW.CanDeleteStop(I: Integer): Boolean;
begin
Result := (0 <= I) and (I < Count);
end;
function TLineRW.CanInsertStop(I: Integer; AStation: TStationR): Boolean;
begin
Result := (0 <= I) and (I <= Count) and not HasStop(AStation);
end;
function TLineRW.CanSwapStops(I, J: Integer): Boolean;
begin
Result := (0 <= I) and (I <= Count) and (0 <= J) and (J <= Count);
end;
function TLineRW.Count: Integer;
begin
Result := Flist.Count;
end;
constructor TLineRW.Create(ACode, AName: String; AOptions: TLineOptions);
begin
Assert(ValidLineCode(ACode),
Format('TLineRW.Create.pre: ACode = %s', [ACode]));
Assert(ValidLineName(AName),
Format('TLineRW.Create.pre: AName = %s', [AName]));
inherited Create;
FCode := ACode;
FName := AName;
FOptions := AOptions;
FList := TObjectList.Create(false);
end;
procedure TLineRW.DeleteAll;
begin
Assert(CanDeleteAll, 'TLineRW.DeleteAll.pre');
FList.Clear;
end;
procedure TLineRW.DeleteStop(I: Integer);
begin
Assert(CanDeleteStop(I), 'TLineRW.DeleteStop.pre');
FList.Delete(I);
end;
destructor TLineRW.Destroy;
begin
FList.Free;
inherited;
end;
function TLineRW.GetCode: String;
begin
Result := FCode;
end;
function TLineRW.GetName: String;
begin
Result := FName;
end;
function TLineRW.GetOptions: TLineOptions;
begin
Result := FOptions;
end;
function TLineRW.IndexOf(AStation: TStationR): Integer;
begin
Result := FList.IndexOf(AStation);
end;
procedure TLineRW.InsertStop(I: Integer; AStation: TStationR);
begin
Assert(CanInsertStop(I, AStation),
Format('TLineRW.InsertStop.pre: I = %d, AStation = %s',
[I, AStation.GetCode]));
FList.Insert(I, AStation);
end;
function TLineRW.Stop(I: Integer): TStationR;
begin
Assert((0 <= I) and (I < Count), Format('TLineRW.Stop.pre: I = %d', [I]));
Result := FList.Items[I] as TStationR;
end;
procedure TLineRW.SwapStops(I, J: Integer);
begin
Assert(CanSwapStops(I,J),
Format('TLineRW.SwapStops.pre: I = %d, J = %d', [I, J]));
FList.Exchange(I, J);
end;
{ TLineSetR -------------------------------------------------------------------}
function TLineSetR.HasCode(ACode: String): Boolean;
var
I: Integer;
begin
Result := false;
for I := 0 to Count - 1 do
if GetLine(I).GetCode = ACode
then Result := true;
end;
function TLineSetR.HasLine(ALine: TLineR): Boolean;
var
I: Integer;
begin
Result := false;
for I := 0 to Count - 1 do
if GetLine(I) = ALine
then Result := true;
end;
function TLineSetR.HasName(AName: String): Boolean;
var
I: Integer;
begin
Result := false;
for I := 0 to Count - 1 do
if GetLine(I).GetName = AName
then Result := true;
end;
function TLineSetR.HasStop(AStation: TStationR): Boolean;
var
I: Integer;
begin
Result := false;
for I := 0 to Count - 1 do
if GetLine(I).HasStop(AStation)
then Result := true;
end;
function TLineSetR.IndexOfCode(ACode: String): Integer;
var
I: Integer;
begin
Result := -1;
for I := 0 to Count - 1 do
if GetLine(I).GetCode = ACode
then Result := I;
end;
function TLineSetR.IndexOfName(AName: String): Integer;
var
I: Integer;
begin
Result := -1;
for I := 0 to Count - 1 do
if GetLine(I).GetName = AName
then Result := I;
end;
function TLineSetR.IsEmpty: Boolean;
begin
Result := Count = 0;
end;
{ TLineSetRW ------------------------------------------------------------------}
procedure TLineSetRW.AddLine(ALine: TLineR);
begin
Assert(CanAddLine(ALine),
Format('TLineSetRW.AddLine.pre: ALine = %s', [ALine.GetCode]));
FList.Add(ALine);
end;
function TLineSetRW.CanAddLine(ALine: TLineR): Boolean;
begin
Result :=
not HasLine(ALine) and
not HasCode(ALine.GetCode) and
not HasName(ALine.GetName)
end;
function TLineSetRW.CanDeleteAll: Boolean;
begin
Result := true;
end;
function TLineSetRW.CanDeleteLine(ALine: TLineR): Boolean;
begin
Result := true;
end;
function TLineSetRW.Count: Integer;
begin
Result := FList.Count;
end;
constructor TLineSetRW.Create;
begin
inherited Create;
FList := TObjectList.Create;
end;
procedure TLineSetRW.DeleteAll;
begin
Assert(CanDeleteAll, 'TLineSetRW.DeleteAll.pre');
FList.Clear;
end;
procedure TLineSetRW.DeleteLine(ALine: TLineR);
begin
Assert(CanDeleteLine(ALine),
Format('TLineSetRW.DeleteLine.pre: ALine = %s', [ALine.GetCode]));
FList.Remove(ALine);
end;
destructor TLineSetRW.Destroy;
begin
FList.Free;
inherited;
end;
function TLineSetRW.GetLine(I: Integer): TLineR;
begin
Assert((0 <= I) and (I < Count),
Format('TLineSetRW.GetLine.pre: I = %d', [I]));
Result := FList.Items[I] as TLineR;
end;
{ TNetwork --------------------------------------------------------------------}
procedure TNetwork.AddLine(ALine: TLineR);
begin
Assert(CanAddLine(ALine),
Format('TNetwork.AddLine.pre: ALine = %s', [ALine.GetCode]));
FLineSet.AddLine(ALine);
end;
procedure TNetwork.AddStation(ACode, AName: String);
begin
Assert(CanAddStation(ACode, AName),
Format('TNetwork.AddStation.pre: ACode = %s, AName = %s', [ACode, AName]));
FStationSet.AddStation(ACode, AName);
end;
function TNetwork.CanAddLine(ALine: TLineR): Boolean;
begin
Result :=
IsConsistentLine(ALine, GetStationSet) and
FLineSet.CanAddLine(ALine)
end;
function TNetwork.CanAddStation(ACode, AName: String): Boolean;
begin
Result := FStationSet.CanAddStation(ACode, AName);
end;
function TNetwork.CanDeleteAll: Boolean;
begin
Result := true;
end;
function TNetwork.CanDeleteLine(ALine: TLineR): Boolean;
begin
Result := FLineSet.CanDeleteLine(ALine);
end;
function TNetwork.CanDeleteStation(AStation: TStationR): Boolean;
begin
Result := not FLineSet.HasStop(AStation);
end;
constructor TNetwork.Create(
AName: String;
AStationSet: TStationSetRW;
ALineSet: TLineSetRW);
begin
Assert(ValidNetworkName(AName), 'TNetwork.Create.pre: ValidNetworkName');
Assert(IsConsistentNetwork(AStationset, ALineSet),
'TNetwork.Create.pre: IsConsistent');
inherited Create;
FName := Aname;
FStationSet := AStationSet;
FLineSet := ALineSet;
end;
constructor TNetwork.CreateEmpty(AName: String);
begin
inherited Create;
FName := AName;
FStationSet := TStationSetRW.Create;
FLineSet := TLineSetRW.Create;
end;
constructor TNetwork.CreateFromFile(AFile: TMemIniFile);
var
VSections: TStringList;
VSectionName: String;
VStationCode, VStationName: String;
VLineCode, VLineName: String;
VStation: TStationR;
VLine: TLineRW;
VCircular, VOneWay: Boolean;
VLineOptions: TLineOptions;
VStops: TStringList;
VStopCode: String;
I, J: Integer;
begin
inherited Create;
FStationSet := TStationSetRW.Create;
FLineSet := TLineSetRW.Create;
// read name
FName := AFile.ReadString('#Main', 'name', '???');
// read all sections
VSections:= TStringList.Create;
AFile.ReadSections(VSections);
// filter out station sections (beginning with 'S_') and read their name
for I := 0 to VSections.Count - 1 do
begin
VSectionName := VSections.Strings[I];
if AnSiStartsStr('S_', VSectionName) then
begin
VStationCode := AnsiRightStr(VSectionName, Length(VSectionName) - 2);
VStationName := AFile.ReadString(VSectionName, 'name', '???????');
FStationSet.AddStation(VStationCode, VStationName);
end;
end;
// filter out line sections (beginning with 'L_') and read their attributes
// and corresponding station lists
for I := 0 to VSections.Count - 1 do
begin
VSectionName := VSections.Strings[I];
if AnSiStartsStr('L_', VSectionName) then
begin
VLineCode := AnsiRightStr(VSectionName, Length(VSectionName) - 2);
// read line name
VLineName := AFile.ReadString(VSectionName, 'name', '????');
// read line options
VLineOptions := [];
VOneWay := AFile.ReadBool(VSectionName, 'oneway', false);
if VOneWay then VLineOptions := VLineOptions + [loOneWay];
VCircular := AFile.ReadBool(VSectionName, 'circular', false);
if VCircular then VLineOptions := VLineOptions + [loCircular];
// create line (with empty stationlist)
VLine := TLineRW.Create(VLineCode, VLineName, VLineOptions);
// read stops from corresponding 'P_' section and and them to line
VStops := TStringList.Create;
AFile.ReadSectionValues('P_' + VLineCode, VStops);
for J := 0 to VStops.Count - 1 do
begin
VStopCode := VStops.Strings[J];
if ValidStationCode(VStopCode) then
with FStationSet do
begin
VStation := GetStation(IndexOfCode(VStopCode));
VLine.AddStop(VStation);
end{with};
end{for};
FLineSet.AddLine(VLine);
VStops.Free;
end;
end;
VSections.Free;
end;
procedure TNetwork.DeleteAll;
begin
Assert(CanDeleteAll, 'TNetwork.DeleteAll.pre');
FStationSet.DeleteAll;
end;
procedure TNetwork.DeleteLine(ALine: TLineR);
begin
Assert(CanDeleteLine(ALine), 'TNetwork.DeleteLine.pre');
FLineSet.DeleteLine(ALine);
end;
procedure TNetwork.DeleteStation(AStation: TStationR);
begin
Assert(CanDeleteStation(AStation), 'TNetwork.DeleteStation.pre');
FStationSet.DeleteStation(AStation);
end;
destructor TNetwork.Destroy;
begin
FLineSet.Free;
FStationSet.Free;
inherited;
end;
function TNetwork.GetLineSet: TLineSetR;
begin
Result := FLineset;
end;
function TNetwork.GetName: string;
begin
Result := FName;
end;
function TNetwork.GetStationSet: TStationSetR;
begin
Result := FStationSet;
end;
function TNetwork.IsConsistentLine(
ALine: TLineR;
AStationSet: TStationSetR): Boolean;
var
J: integer;
begin
Result := true;
for J := 0 to ALine.Count - 1 do
if not AStationSet.HasStation(ALine.Stop(J))
then Result := false;
end;
function TNetwork.IsConsistentNetwork(
AStationSet: TStationSetR;
ALineSet: TLineSetR): Boolean;
// ret:
// let SS = AStationSet, LS = ALineSet
// (forall I: 0<=I<LS.Count: IsConsistentLine(LS.GetLine(I), SS)
var
I: Integer;
begin
Result := true;
for I := 0 to ALineSet.Count - 1 do
if not IsConsistentLine(ALineset.GetLine(I), AStationSet)
then Result := false;
end;
procedure TNetwork.WriteToFile(AFile: TMemIniFile);
var
I, J: Integer;
LineCode: String;
begin
AFile.Clear;
AFile.WriteString('#Main', 'name', FName);
// write station names and codes
with FStationSet do
for I := 0 to Count - 1 do
with GetStation(I) do
AFile.WriteString('S_' + GetCode, 'name', GetName);
// write lines
with FLineSet do
for I := 0 to Count - 1 do
with GetLine(I) do
begin
// write name, oneway, circular
LineCode := GetCode;
AFile.WriteString('L_' + LineCode, 'name' , GetName );
AFile.WriteBool ('L_' + LineCode, 'oneway' , IsOneWay);
AFile.WriteBool ('L_' + LineCode, 'circular', IsCircular);
// write codes of stops
for J := 1 to Count - 1 do
AFile.WriteString('P_' + LineCode, Stop(J).GetCode, '');
end;
end;
// String validators -----------------------------------------------------------
type
TCharSet = set of Char;
function AuxValid(AString: String; ACharSet: TCharSet): Boolean;
// ret: AString in ACharSet+
var
I: Integer;
begin
Result := Length(AString) > 0;
for I := 1 to Length(AString) do
if not (AString[I] in ACharSet)
then Result := false;
end;
function ValidStationCode(AString: String): Boolean;
// ret: AString in csCodeSet+
begin
Result := AuxValid(AString, csCodeSet);
end;
function ValidStationName(AString: String): Boolean;
// ret: AString in csNameSet+
begin
Result := AuxValid(AString, csNameSet);
end;
function ValidLineCode(AString: String): Boolean;
// ret: AString in csCodeSet+
begin
Result := AuxValid(AString, csCodeSet);
end;
function ValidLineName(AString: String): Boolean;
// ret: AString in csNameSet+
begin
Result := AuxValid(AString, csNameSet);
end;
function ValidNetworkName(AString: String): Boolean;
// ret: Astring in csNameSet+
begin
Result := AuxValid(AString, csNameSet);
end;
end.
|
{ ****************************************************************************** }
{ * machine Learn types writen by QQ 600585@qq.com * }
{ * https://zpascal.net * }
{ * https://github.com/PassByYou888/zAI * }
{ * https://github.com/PassByYou888/ZServer4D * }
{ * https://github.com/PassByYou888/PascalString * }
{ * https://github.com/PassByYou888/zRasterization * }
{ * https://github.com/PassByYou888/CoreCipher * }
{ * https://github.com/PassByYou888/zSound * }
{ * https://github.com/PassByYou888/zChinese * }
{ * https://github.com/PassByYou888/zExpression * }
{ * https://github.com/PassByYou888/zGameWare * }
{ * https://github.com/PassByYou888/zAnalysis * }
{ * https://github.com/PassByYou888/FFMPEG-Header * }
{ * https://github.com/PassByYou888/zTranslate * }
{ * https://github.com/PassByYou888/InfiniteIoT * }
{ * https://github.com/PassByYou888/FastMD5 * }
{ ****************************************************************************** }
unit LearnTypes;
{$INCLUDE zDefine.inc}
interface
uses CoreClasses, PascalStrings, UnicodeMixedLib, KDTree, KM, DoStatusIO;
type
TLFloat = TKDTree_VecType;
PLFloat = PKDTree_VecType;
TLVec = TKDTree_Vec;
PLVec = PKDTree_Vec;
TLMatrix = TKDTree_DynamicVecBuffer;
PLMatrix = PKDTree_DynamicVecBuffer;
TLInt = TKMInt;
PLInt = PKMInt;
TLIVec = TKMIntegerArray;
PLIVec = PKMIntegerArray;
TLIMatrix = array of TLIVec;
PLIMatrix = ^TLIMatrix;
TLBVec = array of Boolean;
PLBVec = ^TLBVec;
TLBMatrix = array of TLBVec;
PLBMatrix = ^TLBMatrix;
TLComplex = record
x, y: TLFloat;
end;
TLComplexVec = array of TLComplex;
TLComplexMatrix = array of TLComplexVec;
TLearnType = (
ltKDT, // KDTree, fast space operation, this not Neurons network
ltKM, // k-means++ clusterization, this not Neurons network
ltForest, // random decision forest
ltLogit, // Logistic regression
ltLM, // Levenberg-Marquardt
ltLM_MT, // Levenberg-Marquardt with Parallel
ltLBFGS, // L-BFGS
ltLBFGS_MT, // L-BFGS with Parallel
ltLBFGS_MT_Mod, // L-BFGS with Parallel and optimization
ltMonteCarlo, // fast Monte Carlo train
ltLM_Ensemble, // Levenberg-Marquardt Ensemble
ltLM_Ensemble_MT, // Levenberg-Marquardt Ensemble with Parallel
ltLBFGS_Ensemble, // L-BFGS Ensemble
ltLBFGS_Ensemble_MT // L-BFGS Ensemble with Parallel
);
TLearnCommState = record
Stage: TLInt;
IA: TLIVec;
BA: TLBVec;
ResArry: TLVec;
ca: TLComplexVec;
end;
TMatInvReport = record
r1: TLFloat;
RInf: TLFloat;
end;
(* ************************************************************************
Portable high quality random number generator state.
Initialized with HQRNDRandomize() or HQRNDSeed().
Fields:
S1, S2 - seed values
V - precomputed value
MagicV - 'magic' value used to determine whether State structure was correctly initialized.
************************************************************************ *)
THQRNDState = record
s1: TLInt;
s2: TLInt;
v: TLFloat;
MagicV: TLInt;
end;
{ * Normalizes direction/step pair * }
TLinMinState = record
BRACKT: Boolean;
STAGE1: Boolean;
INFOC: TLInt;
DG: TLFloat;
DGM: TLFloat;
DGINIT: TLFloat;
DGTEST: TLFloat;
DGX: TLFloat;
DGXM: TLFloat;
DGY: TLFloat;
DGYM: TLFloat;
FINIT: TLFloat;
FTEST1: TLFloat;
FM: TLFloat;
fx: TLFloat;
FXM: TLFloat;
fy: TLFloat;
FYM: TLFloat;
STX: TLFloat;
STY: TLFloat;
STMIN: TLFloat;
STMAX: TLFloat;
width: TLFloat;
WIDTH1: TLFloat;
XTRAPF: TLFloat;
end;
{ * Limited memory BFGS optimizer * }
TMinLBFGSState = record
n: TLInt;
M: TLInt;
EpsG: TLFloat;
EpsF: TLFloat;
EpsX: TLFloat;
MAXITS: TLInt;
Flags: TLInt;
XRep: Boolean;
StpMax: TLFloat;
NFEV: TLInt;
MCStage: TLInt;
k: TLInt;
q: TLInt;
p: TLInt;
Rho: TLVec;
y: TLMatrix;
s: TLMatrix;
Theta: TLVec;
d: TLVec;
Stp: TLFloat;
Work: TLVec;
FOld: TLFloat;
GammaK: TLFloat;
x: TLVec;
f: TLFloat;
g: TLVec;
NeedFG: Boolean;
XUpdated: Boolean;
RState: TLearnCommState;
RepIterationsCount: TLInt;
RepNFEV: TLInt;
RepTerminationType: TLInt;
LState: TLinMinState;
end;
TMinLBFGSReport = record
IterationsCount: TLInt;
NFEV: TLInt;
TerminationType: TLInt;
end;
{ * Dense linear system solver * }
TDenseSolverReport = record
r1: TLFloat;
RInf: TLFloat;
end;
TDenseSolverLSReport = record
r2: TLFloat;
Cx: TLMatrix;
n: TLInt;
k: TLInt;
end;
{ * Improved Levenberg-Marquardt optimizer * }
TMinLMState = record
WrongParams: Boolean;
n: TLInt;
M: TLInt;
EpsG: TLFloat;
EpsF: TLFloat;
EpsX: TLFloat;
MAXITS: TLInt;
XRep: Boolean;
StpMax: TLFloat;
Flags: TLInt;
UserMode: TLInt;
x: TLVec;
f: TLFloat;
fi: TLVec;
j: TLMatrix;
h: TLMatrix;
g: TLVec;
NeedF: Boolean;
NeedFG: Boolean;
NeedFGH: Boolean;
NeedFiJ: Boolean;
XUpdated: Boolean;
InternalState: TMinLBFGSState;
InternalRep: TMinLBFGSReport;
XPrec: TLVec;
XBase: TLVec;
XDir: TLVec;
GBase: TLVec;
XPrev: TLVec;
FPrev: TLFloat;
RawModel: TLMatrix;
Model: TLMatrix;
Work: TLVec;
RState: TLearnCommState;
RepIterationsCount: TLInt;
RepTerminationType: TLInt;
RepNFunc: TLInt;
RepNJac: TLInt;
RepNGrad: TLInt;
RepNHess: TLInt;
RepNCholesky: TLInt;
SolverInfo: TLInt;
SolverRep: TDenseSolverReport;
InvInfo: TLInt;
InvRep: TMatInvReport;
end;
TMinLMReport = record
IterationsCount: TLInt;
TerminationType: TLInt;
NFunc: TLInt;
NJac: TLInt;
NGrad: TLInt;
NHess: TLInt;
NCholesky: TLInt;
end;
{ * neural network * }
TMultiLayerPerceptron = record
StructInfo: TLIVec;
Weights: TLVec;
ColumnMeans: TLVec;
ColumnSigmas: TLVec;
Neurons: TLVec;
DFDNET: TLVec;
DError: TLVec;
x: TLVec;
y: TLVec;
Chunks: TLMatrix;
NWBuf: TLVec;
end;
PMultiLayerPerceptron = ^TMultiLayerPerceptron;
(* ************************************************************************
Training report:
* NGrad - number of gradient calculations
* NHess - number of Hessian calculations
* NCholesky - number of Cholesky decompositions
************************************************************************ *)
TMLPReport = record
NGrad: TLInt;
NHess: TLInt;
NCholesky: TLInt;
end;
(* ************************************************************************
Cross-validation estimates of generalization error
************************************************************************ *)
TMLPCVReport = record
RelClsError: TLFloat;
AvgCE: TLFloat;
RMSError: TLFloat;
AvgError: TLFloat;
AvgRelError: TLFloat;
end;
(* ************************************************************************
Neural networks ensemble
************************************************************************ *)
TMLPEnsemble = record
StructInfo: TLIVec;
EnsembleSize: TLInt;
NIn: TLInt;
NOut: TLInt;
WCount: TLInt;
IsSoftmax: Boolean;
PostProcessing: Boolean;
Weights: TLVec;
ColumnMeans: TLVec;
ColumnSigmas: TLVec;
SerializedLen: TLInt;
SerializedMLP: TLVec;
TmpWeights: TLVec;
TmpMeans: TLVec;
TmpSigmas: TLVec;
Neurons: TLVec;
DFDNET: TLVec;
y: TLVec;
end;
PMLPEnsemble = ^TMLPEnsemble;
{ * Random Decision Forest * }
TDecisionForest = record
NVars: TLInt;
NClasses: TLInt;
NTrees: TLInt;
BufSize: TLInt;
Trees: TLVec;
end;
PDecisionForest = ^TDecisionForest;
TDFReport = record
RelClsError: TLFloat;
AvgCE: TLFloat;
RMSError: TLFloat;
AvgError: TLFloat;
AvgRelError: TLFloat;
OOBRelClsError: TLFloat;
OOBAvgCE: TLFloat;
OOBRMSError: TLFloat;
OOBAvgError: TLFloat;
OOBAvgRelError: TLFloat;
end;
{ * LogitModel * }
TLogitModel = record
w: TLVec;
end;
PLogitModel = ^TLogitModel;
TLogitMCState = record
BRACKT: Boolean;
STAGE1: Boolean;
INFOC: TLInt;
DG: TLFloat;
DGM: TLFloat;
DGINIT: TLFloat;
DGTEST: TLFloat;
DGX: TLFloat;
DGXM: TLFloat;
DGY: TLFloat;
DGYM: TLFloat;
FINIT: TLFloat;
FTEST1: TLFloat;
FM: TLFloat;
fx: TLFloat;
FXM: TLFloat;
fy: TLFloat;
FYM: TLFloat;
STX: TLFloat;
STY: TLFloat;
STMIN: TLFloat;
STMAX: TLFloat;
width: TLFloat;
WIDTH1: TLFloat;
XTRAPF: TLFloat;
end;
(* ************************************************************************
MNLReport structure contains information about training process:
* NGrad - number of gradient calculations
* NHess - number of Hessian calculations
************************************************************************ *)
TMNLReport = record
NGrad: TLInt;
NHess: TLInt;
end;
(* ************************************************************************
Least squares fitting report:
TaskRCond reciprocal of task's condition number
RMSError RMS error
AvgError average error
AvgRelError average relative error (for non-zero Y[I])
MaxError maximum error
************************************************************************ *)
TLSFitReport = record
TaskRCond: TLFloat;
RMSError: TLFloat;
AvgError: TLFloat;
AvgRelError: TLFloat;
MaxError: TLFloat;
end;
TLSFitState = record
n: TLInt;
M: TLInt;
k: TLInt;
EpsF: TLFloat;
EpsX: TLFloat;
MAXITS: TLInt;
StpMax: TLFloat;
TaskX: TLMatrix;
TaskY: TLVec;
w: TLVec;
CheapFG: Boolean;
HaveHess: Boolean;
NeedF: Boolean;
NeedFG: Boolean;
NeedFGH: Boolean;
PointIndex: TLInt;
x: TLVec;
c: TLVec;
f: TLFloat;
g: TLVec;
h: TLMatrix;
RepTerminationType: TLInt;
RepRMSError: TLFloat;
RepAvgError: TLFloat;
RepAvgRelError: TLFloat;
RepMaxError: TLFloat;
OptState: TMinLMState;
OptRep: TMinLMReport;
RState: TLearnCommState;
end;
(* ************************************************************************
Barycentric interpolant.
************************************************************************ *)
TBarycentricInterpolant = record
n: TLInt;
SY: TLFloat;
x: TLVec;
y: TLVec;
w: TLVec;
end;
(* ************************************************************************
Barycentric fitting report:
TaskRCond reciprocal of task's condition number
RMSError RMS error
AvgError average error
AvgRelError average relative error (for non-zero Y[I])
MaxError maximum error
************************************************************************ *)
TBarycentricFitReport = record
TaskRCond: TLFloat;
DBest: TLInt;
RMSError: TLFloat;
AvgError: TLFloat;
AvgRelError: TLFloat;
MaxError: TLFloat;
end;
(* ************************************************************************
Polynomial fitting report:
TaskRCond reciprocal of task's condition number
RMSError RMS error
AvgError average error
AvgRelError average relative error (for non-zero Y[I])
MaxError maximum error
************************************************************************ *)
TPolynomialFitReport = record
TaskRCond: TLFloat;
RMSError: TLFloat;
AvgError: TLFloat;
AvgRelError: TLFloat;
MaxError: TLFloat;
end;
(* ************************************************************************
1-dimensional spline inteprolant
************************************************************************ *)
TSpline1DInterpolant = record
Periodic: Boolean;
n: TLInt;
k: TLInt;
x: TLVec;
c: TLVec;
end;
(* ************************************************************************
Spline fitting report:
TaskRCond reciprocal of task's condition number
RMSError RMS error
AvgError average error
AvgRelError average relative error (for non-zero Y[I])
MaxError maximum error
************************************************************************ *)
TSpline1DFitReport = record
TaskRCond: TLFloat;
RMSError: TLFloat;
AvgError: TLFloat;
AvgRelError: TLFloat;
MaxError: TLFloat;
end;
(*
generates FFT plan
*)
TFTPlan = record
Plan: TLIVec;
Precomputed: TLVec;
TmpBuf: TLVec;
StackBuf: TLVec;
end;
const
// IEEE floating
MachineEpsilon = 5.0E-16;
MaxRealNumber = 1.0E300;
MinRealNumber = 1.0E-300;
// LearnType info
CLearnString: array [TLearnType] of SystemString = (
'k-dimensional tree',
'k-means++ clusterization',
'Random forest',
'Logistic regression',
'Levenberg-Marquardt',
'Levenberg-Marquardt with Parallel',
'L-BFGS',
'L-BFGS with Parallel',
'L-BFGS with Parallel and optimization',
'fast Monte Carlo',
'Levenberg-Marquardt Ensemble',
'Levenberg-Marquardt Ensemble with Parallel',
'L-BFGS Ensemble',
'L-BFGS Ensemble with Parallel'
);
procedure DoStatus(v: TLVec); overload;
procedure DoStatus(v: TLIVec); overload;
procedure DoStatus(v: TLBVec); overload;
procedure DoStatus(v: TLMatrix); overload;
procedure DoStatus(v: TLIMatrix); overload;
procedure DoStatus(v: TLBMatrix); overload;
implementation
procedure DoStatus(v: TLVec);
var
i: NativeInt;
begin
for i := 0 to length(v) - 1 do
DoStatusNoLn(umlFloatToStr(v[i]) + ' ');
DoStatusNoLn;
end;
procedure DoStatus(v: TLIVec);
var
i: NativeInt;
begin
for i := 0 to length(v) - 1 do
DoStatusNoLn(umlIntToStr(v[i]) + ' ');
DoStatusNoLn;
end;
procedure DoStatus(v: TLBVec);
var
i: NativeInt;
begin
for i := 0 to length(v) - 1 do
DoStatusNoLn(umlBoolToStr(v[i]) + ' ');
DoStatusNoLn;
end;
procedure DoStatus(v: TLMatrix);
var
i: Integer;
begin
for i := 0 to high(v) do
DoStatus(v[i]);
end;
procedure DoStatus(v: TLIMatrix);
var
i: Integer;
begin
for i := 0 to high(v) do
DoStatus(v[i]);
end;
procedure DoStatus(v: TLBMatrix);
var
i: Integer;
begin
for i := 0 to high(v) do
DoStatus(v[i]);
end;
end.
|
Unit
Util;
Interface
Function FirstCase: String;
Implementation
Function FirstCase(StrIn: String): String;
Var
StrOut: String;
Iter: Int;
Begin
// tes5edit does not seem to have very many nice string functions
// even basic ones like LeftStr or RightStr that most pascal/del
// documentations reference.
Iter := 1;
StrOut := '';
While Iter <= Length(StrIn)
Do Begin
If(Iter = 1)
Then Begin
StrOut := StrOut + UpperCase(Copy(StrIn,Iter,1));
End
Else Begin
StrOut := StrOut + LowerCase(Copy(StrIn,Iter,1));
End;
Inc(Iter)
End;
Result := StrOut;
End;
Function PregReplace(Format: String; Replacement: String; Source: String): String;
Var
RegEx: TPerlRegex;
Begin
RegEx := TPerlRegex.Create();
RegEx.RegEx := Format;
RegEx.Replacement := Replacement;
RegEx.Options := [ preCaseless ];
RegEx.Subject := Source;
If(RegEx.Match())
Then Begin
RegEx.ReplaceAll();
End;
Result := RegEx.Subject;
End;
End.
|
{ ****************************************************************************** }
{ Fast KDTree extended Type support }
{ ****************************************************************************** }
{ * https://zpascal.net * }
{ * https://github.com/PassByYou888/zAI * }
{ * https://github.com/PassByYou888/ZServer4D * }
{ * https://github.com/PassByYou888/PascalString * }
{ * https://github.com/PassByYou888/zRasterization * }
{ * https://github.com/PassByYou888/CoreCipher * }
{ * https://github.com/PassByYou888/zSound * }
{ * https://github.com/PassByYou888/zChinese * }
{ * https://github.com/PassByYou888/zExpression * }
{ * https://github.com/PassByYou888/zGameWare * }
{ * https://github.com/PassByYou888/zAnalysis * }
{ * https://github.com/PassByYou888/FFMPEG-Header * }
{ * https://github.com/PassByYou888/zTranslate * }
{ * https://github.com/PassByYou888/InfiniteIoT * }
{ * https://github.com/PassByYou888/FastMD5 * }
{ ****************************************************************************** }
unit FastKDTreeE;
{$INCLUDE zDefine.inc}
interface
uses CoreClasses, PascalStrings, UnicodeMixedLib, KM;
const
// extended float: KDTree
KDT1DE_Axis = 1;
KDT2DE_Axis = 2;
KDT3DE_Axis = 3;
KDT4DE_Axis = 4;
KDT5DE_Axis = 5;
KDT6DE_Axis = 6;
KDT7DE_Axis = 7;
KDT8DE_Axis = 8;
KDT9DE_Axis = 9;
KDT10DE_Axis = 10;
KDT11DE_Axis = 11;
KDT12DE_Axis = 12;
KDT13DE_Axis = 13;
KDT14DE_Axis = 14;
KDT15DE_Axis = 15;
KDT16DE_Axis = 16;
KDT17DE_Axis = 17;
KDT18DE_Axis = 18;
KDT19DE_Axis = 19;
KDT20DE_Axis = 20;
KDT21DE_Axis = 21;
KDT22DE_Axis = 22;
KDT23DE_Axis = 23;
KDT24DE_Axis = 24;
KDT48DE_Axis = 48;
KDT52DE_Axis = 52;
KDT64DE_Axis = 64;
KDT96DE_Axis = 96;
KDT128DE_Axis = 128;
KDT156DE_Axis = 156;
KDT192DE_Axis = 192;
KDT256DE_Axis = 256;
KDT384DE_Axis = 384;
KDT512DE_Axis = 512;
KDT800DE_Axis = 800;
KDT1024DE_Axis = 1024;
type
// extended float: KDTree
TKDT1DE = class; TKDT1DE_VecType = KM.TKMFloat; // 1D
TKDT2DE = class; TKDT2DE_VecType = KM.TKMFloat; // 2D
TKDT3DE = class; TKDT3DE_VecType = KM.TKMFloat; // 3D
TKDT4DE = class; TKDT4DE_VecType = KM.TKMFloat; // 4D
TKDT5DE = class; TKDT5DE_VecType = KM.TKMFloat; // 5D
TKDT6DE = class; TKDT6DE_VecType = KM.TKMFloat; // 6D
TKDT7DE = class; TKDT7DE_VecType = KM.TKMFloat; // 7D
TKDT8DE = class; TKDT8DE_VecType = KM.TKMFloat; // 8D
TKDT9DE = class; TKDT9DE_VecType = KM.TKMFloat; // 9D
TKDT10DE = class; TKDT10DE_VecType = KM.TKMFloat; // 10D
TKDT11DE = class; TKDT11DE_VecType = KM.TKMFloat; // 11D
TKDT12DE = class; TKDT12DE_VecType = KM.TKMFloat; // 12D
TKDT13DE = class; TKDT13DE_VecType = KM.TKMFloat; // 13D
TKDT14DE = class; TKDT14DE_VecType = KM.TKMFloat; // 14D
TKDT15DE = class; TKDT15DE_VecType = KM.TKMFloat; // 15D
TKDT16DE = class; TKDT16DE_VecType = KM.TKMFloat; // 16D
TKDT17DE = class; TKDT17DE_VecType = KM.TKMFloat; // 17D
TKDT18DE = class; TKDT18DE_VecType = KM.TKMFloat; // 18D
TKDT19DE = class; TKDT19DE_VecType = KM.TKMFloat; // 19D
TKDT20DE = class; TKDT20DE_VecType = KM.TKMFloat; // 20D
TKDT21DE = class; TKDT21DE_VecType = KM.TKMFloat; // 21D
TKDT22DE = class; TKDT22DE_VecType = KM.TKMFloat; // 22D
TKDT23DE = class; TKDT23DE_VecType = KM.TKMFloat; // 23D
TKDT24DE = class; TKDT24DE_VecType = KM.TKMFloat; // 24D
TKDT48DE = class; TKDT48DE_VecType = KM.TKMFloat; // 48D
TKDT52DE = class; TKDT52DE_VecType = KM.TKMFloat; // 52D
TKDT64DE = class; TKDT64DE_VecType = KM.TKMFloat; // 64D
TKDT96DE = class; TKDT96DE_VecType = KM.TKMFloat; // 96D
TKDT128DE = class; TKDT128DE_VecType = KM.TKMFloat; // 128D
TKDT156DE = class; TKDT156DE_VecType = KM.TKMFloat; // 156D
TKDT192DE = class; TKDT192DE_VecType = KM.TKMFloat; // 192D
TKDT256DE = class; TKDT256DE_VecType = KM.TKMFloat; // 256D
TKDT384DE = class; TKDT384DE_VecType = KM.TKMFloat; // 384D
TKDT512DE = class; TKDT512DE_VecType = KM.TKMFloat; // 512D
TKDT800DE = class; TKDT800DE_VecType = KM.TKMFloat; // 800D
TKDT1024DE = class; TKDT1024DE_VecType = KM.TKMFloat; // 1024D
// extended float: KDTree
TKDT1DE = class(TCoreClassObject)
public type
// code split
TKDT1DE_Vec = array [0 .. KDT1DE_Axis - 1] of TKDT1DE_VecType;
PKDT1DE_Vec = ^TKDT1DE_Vec;
TKDT1DE_DynamicVecBuffer = array of TKDT1DE_Vec;
PKDT1DE_DynamicVecBuffer = ^TKDT1DE_DynamicVecBuffer;
TKDT1DE_Source = record
buff: TKDT1DE_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT1DE_Source = ^TKDT1DE_Source;
TKDT1DE_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT1DE_Source) - 1] of PKDT1DE_Source;
PKDT1DE_SourceBuffer = ^TKDT1DE_SourceBuffer;
TKDT1DE_DyanmicSourceBuffer = array of PKDT1DE_Source;
PKDT1DE_DyanmicSourceBuffer = ^TKDT1DE_DyanmicSourceBuffer;
TKDT1DE_DyanmicStoreBuffer = array of TKDT1DE_Source;
PKDT1DE_DyanmicStoreBuffer = ^TKDT1DE_DyanmicStoreBuffer;
PKDT1DE_Node = ^TKDT1DE_Node;
TKDT1DE_Node = record
Parent, Right, Left: PKDT1DE_Node;
Vec: PKDT1DE_Source;
end;
TKDT1DE_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT1DE_Source; const Data: Pointer);
TKDT1DE_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT1DE_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT1DE_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT1DE_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT1DE_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT1DE_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT1DE_DyanmicStoreBuffer;
KDBuff: TKDT1DE_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT1DE_Node;
TestBuff: TKDT1DE_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT1DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT1DE_Node;
function GetData(const Index: NativeInt): PKDT1DE_Source;
public
RootNode: PKDT1DE_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT1DE_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT1DE_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1DE_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1DE_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1DE_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT1DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT1DE_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1DE_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1DE_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1DE_BuildProc); overload;
{ search }
function Search(const buff: TKDT1DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT1DE_Node; overload;
function Search(const buff: TKDT1DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT1DE_Node; overload;
function Search(const buff: TKDT1DE_Vec; var SearchedDistanceMin: Double): PKDT1DE_Node; overload;
function Search(const buff: TKDT1DE_Vec): PKDT1DE_Node; overload;
function SearchToken(const buff: TKDT1DE_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT1DE_DynamicVecBuffer; var OutBuff: TKDT1DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT1DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT1DE_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT1DE_Vec; overload;
class function Vec(const v: TKDT1DE_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT1DE_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT1DE_Source; const Data: Pointer);
class procedure Test;
end;
TKDT2DE = class(TCoreClassObject)
public type
// code split
TKDT2DE_Vec = array [0 .. KDT2DE_Axis - 1] of TKDT2DE_VecType;
PKDT2DE_Vec = ^TKDT2DE_Vec;
TKDT2DE_DynamicVecBuffer = array of TKDT2DE_Vec;
PKDT2DE_DynamicVecBuffer = ^TKDT2DE_DynamicVecBuffer;
TKDT2DE_Source = record
buff: TKDT2DE_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT2DE_Source = ^TKDT2DE_Source;
TKDT2DE_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT2DE_Source) - 1] of PKDT2DE_Source;
PKDT2DE_SourceBuffer = ^TKDT2DE_SourceBuffer;
TKDT2DE_DyanmicSourceBuffer = array of PKDT2DE_Source;
PKDT2DE_DyanmicSourceBuffer = ^TKDT2DE_DyanmicSourceBuffer;
TKDT2DE_DyanmicStoreBuffer = array of TKDT2DE_Source;
PKDT2DE_DyanmicStoreBuffer = ^TKDT2DE_DyanmicStoreBuffer;
PKDT2DE_Node = ^TKDT2DE_Node;
TKDT2DE_Node = record
Parent, Right, Left: PKDT2DE_Node;
Vec: PKDT2DE_Source;
end;
TKDT2DE_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT2DE_Source; const Data: Pointer);
TKDT2DE_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT2DE_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT2DE_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT2DE_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT2DE_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT2DE_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT2DE_DyanmicStoreBuffer;
KDBuff: TKDT2DE_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT2DE_Node;
TestBuff: TKDT2DE_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT2DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT2DE_Node;
function GetData(const Index: NativeInt): PKDT2DE_Source;
public
RootNode: PKDT2DE_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT2DE_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT2DE_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT2DE_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT2DE_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT2DE_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT2DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT2DE_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT2DE_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT2DE_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT2DE_BuildProc); overload;
{ search }
function Search(const buff: TKDT2DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT2DE_Node; overload;
function Search(const buff: TKDT2DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT2DE_Node; overload;
function Search(const buff: TKDT2DE_Vec; var SearchedDistanceMin: Double): PKDT2DE_Node; overload;
function Search(const buff: TKDT2DE_Vec): PKDT2DE_Node; overload;
function SearchToken(const buff: TKDT2DE_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT2DE_DynamicVecBuffer; var OutBuff: TKDT2DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT2DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT2DE_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT2DE_Vec; overload;
class function Vec(const v: TKDT2DE_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT2DE_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT2DE_Source; const Data: Pointer);
class procedure Test;
end;
TKDT3DE = class(TCoreClassObject)
public type
// code split
TKDT3DE_Vec = array [0 .. KDT3DE_Axis - 1] of TKDT3DE_VecType;
PKDT3DE_Vec = ^TKDT3DE_Vec;
TKDT3DE_DynamicVecBuffer = array of TKDT3DE_Vec;
PKDT3DE_DynamicVecBuffer = ^TKDT3DE_DynamicVecBuffer;
TKDT3DE_Source = record
buff: TKDT3DE_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT3DE_Source = ^TKDT3DE_Source;
TKDT3DE_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT3DE_Source) - 1] of PKDT3DE_Source;
PKDT3DE_SourceBuffer = ^TKDT3DE_SourceBuffer;
TKDT3DE_DyanmicSourceBuffer = array of PKDT3DE_Source;
PKDT3DE_DyanmicSourceBuffer = ^TKDT3DE_DyanmicSourceBuffer;
TKDT3DE_DyanmicStoreBuffer = array of TKDT3DE_Source;
PKDT3DE_DyanmicStoreBuffer = ^TKDT3DE_DyanmicStoreBuffer;
PKDT3DE_Node = ^TKDT3DE_Node;
TKDT3DE_Node = record
Parent, Right, Left: PKDT3DE_Node;
Vec: PKDT3DE_Source;
end;
TKDT3DE_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT3DE_Source; const Data: Pointer);
TKDT3DE_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT3DE_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT3DE_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT3DE_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT3DE_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT3DE_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT3DE_DyanmicStoreBuffer;
KDBuff: TKDT3DE_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT3DE_Node;
TestBuff: TKDT3DE_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT3DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT3DE_Node;
function GetData(const Index: NativeInt): PKDT3DE_Source;
public
RootNode: PKDT3DE_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT3DE_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT3DE_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT3DE_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT3DE_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT3DE_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT3DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT3DE_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT3DE_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT3DE_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT3DE_BuildProc); overload;
{ search }
function Search(const buff: TKDT3DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT3DE_Node; overload;
function Search(const buff: TKDT3DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT3DE_Node; overload;
function Search(const buff: TKDT3DE_Vec; var SearchedDistanceMin: Double): PKDT3DE_Node; overload;
function Search(const buff: TKDT3DE_Vec): PKDT3DE_Node; overload;
function SearchToken(const buff: TKDT3DE_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT3DE_DynamicVecBuffer; var OutBuff: TKDT3DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT3DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT3DE_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT3DE_Vec; overload;
class function Vec(const v: TKDT3DE_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT3DE_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT3DE_Source; const Data: Pointer);
class procedure Test;
end;
TKDT4DE = class(TCoreClassObject)
public type
// code split
TKDT4DE_Vec = array [0 .. KDT4DE_Axis - 1] of TKDT4DE_VecType;
PKDT4DE_Vec = ^TKDT4DE_Vec;
TKDT4DE_DynamicVecBuffer = array of TKDT4DE_Vec;
PKDT4DE_DynamicVecBuffer = ^TKDT4DE_DynamicVecBuffer;
TKDT4DE_Source = record
buff: TKDT4DE_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT4DE_Source = ^TKDT4DE_Source;
TKDT4DE_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT4DE_Source) - 1] of PKDT4DE_Source;
PKDT4DE_SourceBuffer = ^TKDT4DE_SourceBuffer;
TKDT4DE_DyanmicSourceBuffer = array of PKDT4DE_Source;
PKDT4DE_DyanmicSourceBuffer = ^TKDT4DE_DyanmicSourceBuffer;
TKDT4DE_DyanmicStoreBuffer = array of TKDT4DE_Source;
PKDT4DE_DyanmicStoreBuffer = ^TKDT4DE_DyanmicStoreBuffer;
PKDT4DE_Node = ^TKDT4DE_Node;
TKDT4DE_Node = record
Parent, Right, Left: PKDT4DE_Node;
Vec: PKDT4DE_Source;
end;
TKDT4DE_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT4DE_Source; const Data: Pointer);
TKDT4DE_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT4DE_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT4DE_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT4DE_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT4DE_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT4DE_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT4DE_DyanmicStoreBuffer;
KDBuff: TKDT4DE_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT4DE_Node;
TestBuff: TKDT4DE_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT4DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT4DE_Node;
function GetData(const Index: NativeInt): PKDT4DE_Source;
public
RootNode: PKDT4DE_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT4DE_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT4DE_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT4DE_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT4DE_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT4DE_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT4DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT4DE_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT4DE_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT4DE_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT4DE_BuildProc); overload;
{ search }
function Search(const buff: TKDT4DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT4DE_Node; overload;
function Search(const buff: TKDT4DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT4DE_Node; overload;
function Search(const buff: TKDT4DE_Vec; var SearchedDistanceMin: Double): PKDT4DE_Node; overload;
function Search(const buff: TKDT4DE_Vec): PKDT4DE_Node; overload;
function SearchToken(const buff: TKDT4DE_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT4DE_DynamicVecBuffer; var OutBuff: TKDT4DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT4DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT4DE_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT4DE_Vec; overload;
class function Vec(const v: TKDT4DE_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT4DE_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT4DE_Source; const Data: Pointer);
class procedure Test;
end;
TKDT5DE = class(TCoreClassObject)
public type
// code split
TKDT5DE_Vec = array [0 .. KDT5DE_Axis - 1] of TKDT5DE_VecType;
PKDT5DE_Vec = ^TKDT5DE_Vec;
TKDT5DE_DynamicVecBuffer = array of TKDT5DE_Vec;
PKDT5DE_DynamicVecBuffer = ^TKDT5DE_DynamicVecBuffer;
TKDT5DE_Source = record
buff: TKDT5DE_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT5DE_Source = ^TKDT5DE_Source;
TKDT5DE_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT5DE_Source) - 1] of PKDT5DE_Source;
PKDT5DE_SourceBuffer = ^TKDT5DE_SourceBuffer;
TKDT5DE_DyanmicSourceBuffer = array of PKDT5DE_Source;
PKDT5DE_DyanmicSourceBuffer = ^TKDT5DE_DyanmicSourceBuffer;
TKDT5DE_DyanmicStoreBuffer = array of TKDT5DE_Source;
PKDT5DE_DyanmicStoreBuffer = ^TKDT5DE_DyanmicStoreBuffer;
PKDT5DE_Node = ^TKDT5DE_Node;
TKDT5DE_Node = record
Parent, Right, Left: PKDT5DE_Node;
Vec: PKDT5DE_Source;
end;
TKDT5DE_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT5DE_Source; const Data: Pointer);
TKDT5DE_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT5DE_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT5DE_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT5DE_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT5DE_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT5DE_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT5DE_DyanmicStoreBuffer;
KDBuff: TKDT5DE_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT5DE_Node;
TestBuff: TKDT5DE_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT5DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT5DE_Node;
function GetData(const Index: NativeInt): PKDT5DE_Source;
public
RootNode: PKDT5DE_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT5DE_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT5DE_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT5DE_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT5DE_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT5DE_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT5DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT5DE_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT5DE_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT5DE_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT5DE_BuildProc); overload;
{ search }
function Search(const buff: TKDT5DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT5DE_Node; overload;
function Search(const buff: TKDT5DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT5DE_Node; overload;
function Search(const buff: TKDT5DE_Vec; var SearchedDistanceMin: Double): PKDT5DE_Node; overload;
function Search(const buff: TKDT5DE_Vec): PKDT5DE_Node; overload;
function SearchToken(const buff: TKDT5DE_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT5DE_DynamicVecBuffer; var OutBuff: TKDT5DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT5DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT5DE_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT5DE_Vec; overload;
class function Vec(const v: TKDT5DE_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT5DE_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT5DE_Source; const Data: Pointer);
class procedure Test;
end;
TKDT6DE = class(TCoreClassObject)
public type
// code split
TKDT6DE_Vec = array [0 .. KDT6DE_Axis - 1] of TKDT6DE_VecType;
PKDT6DE_Vec = ^TKDT6DE_Vec;
TKDT6DE_DynamicVecBuffer = array of TKDT6DE_Vec;
PKDT6DE_DynamicVecBuffer = ^TKDT6DE_DynamicVecBuffer;
TKDT6DE_Source = record
buff: TKDT6DE_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT6DE_Source = ^TKDT6DE_Source;
TKDT6DE_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT6DE_Source) - 1] of PKDT6DE_Source;
PKDT6DE_SourceBuffer = ^TKDT6DE_SourceBuffer;
TKDT6DE_DyanmicSourceBuffer = array of PKDT6DE_Source;
PKDT6DE_DyanmicSourceBuffer = ^TKDT6DE_DyanmicSourceBuffer;
TKDT6DE_DyanmicStoreBuffer = array of TKDT6DE_Source;
PKDT6DE_DyanmicStoreBuffer = ^TKDT6DE_DyanmicStoreBuffer;
PKDT6DE_Node = ^TKDT6DE_Node;
TKDT6DE_Node = record
Parent, Right, Left: PKDT6DE_Node;
Vec: PKDT6DE_Source;
end;
TKDT6DE_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT6DE_Source; const Data: Pointer);
TKDT6DE_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT6DE_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT6DE_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT6DE_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT6DE_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT6DE_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT6DE_DyanmicStoreBuffer;
KDBuff: TKDT6DE_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT6DE_Node;
TestBuff: TKDT6DE_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT6DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT6DE_Node;
function GetData(const Index: NativeInt): PKDT6DE_Source;
public
RootNode: PKDT6DE_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT6DE_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT6DE_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT6DE_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT6DE_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT6DE_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT6DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT6DE_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT6DE_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT6DE_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT6DE_BuildProc); overload;
{ search }
function Search(const buff: TKDT6DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT6DE_Node; overload;
function Search(const buff: TKDT6DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT6DE_Node; overload;
function Search(const buff: TKDT6DE_Vec; var SearchedDistanceMin: Double): PKDT6DE_Node; overload;
function Search(const buff: TKDT6DE_Vec): PKDT6DE_Node; overload;
function SearchToken(const buff: TKDT6DE_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT6DE_DynamicVecBuffer; var OutBuff: TKDT6DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT6DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT6DE_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT6DE_Vec; overload;
class function Vec(const v: TKDT6DE_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT6DE_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT6DE_Source; const Data: Pointer);
class procedure Test;
end;
TKDT7DE = class(TCoreClassObject)
public type
// code split
TKDT7DE_Vec = array [0 .. KDT7DE_Axis - 1] of TKDT7DE_VecType;
PKDT7DE_Vec = ^TKDT7DE_Vec;
TKDT7DE_DynamicVecBuffer = array of TKDT7DE_Vec;
PKDT7DE_DynamicVecBuffer = ^TKDT7DE_DynamicVecBuffer;
TKDT7DE_Source = record
buff: TKDT7DE_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT7DE_Source = ^TKDT7DE_Source;
TKDT7DE_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT7DE_Source) - 1] of PKDT7DE_Source;
PKDT7DE_SourceBuffer = ^TKDT7DE_SourceBuffer;
TKDT7DE_DyanmicSourceBuffer = array of PKDT7DE_Source;
PKDT7DE_DyanmicSourceBuffer = ^TKDT7DE_DyanmicSourceBuffer;
TKDT7DE_DyanmicStoreBuffer = array of TKDT7DE_Source;
PKDT7DE_DyanmicStoreBuffer = ^TKDT7DE_DyanmicStoreBuffer;
PKDT7DE_Node = ^TKDT7DE_Node;
TKDT7DE_Node = record
Parent, Right, Left: PKDT7DE_Node;
Vec: PKDT7DE_Source;
end;
TKDT7DE_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT7DE_Source; const Data: Pointer);
TKDT7DE_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT7DE_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT7DE_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT7DE_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT7DE_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT7DE_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT7DE_DyanmicStoreBuffer;
KDBuff: TKDT7DE_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT7DE_Node;
TestBuff: TKDT7DE_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT7DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT7DE_Node;
function GetData(const Index: NativeInt): PKDT7DE_Source;
public
RootNode: PKDT7DE_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT7DE_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT7DE_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT7DE_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT7DE_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT7DE_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT7DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT7DE_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT7DE_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT7DE_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT7DE_BuildProc); overload;
{ search }
function Search(const buff: TKDT7DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT7DE_Node; overload;
function Search(const buff: TKDT7DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT7DE_Node; overload;
function Search(const buff: TKDT7DE_Vec; var SearchedDistanceMin: Double): PKDT7DE_Node; overload;
function Search(const buff: TKDT7DE_Vec): PKDT7DE_Node; overload;
function SearchToken(const buff: TKDT7DE_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT7DE_DynamicVecBuffer; var OutBuff: TKDT7DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT7DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT7DE_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT7DE_Vec; overload;
class function Vec(const v: TKDT7DE_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT7DE_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT7DE_Source; const Data: Pointer);
class procedure Test;
end;
TKDT8DE = class(TCoreClassObject)
public type
// code split
TKDT8DE_Vec = array [0 .. KDT8DE_Axis - 1] of TKDT8DE_VecType;
PKDT8DE_Vec = ^TKDT8DE_Vec;
TKDT8DE_DynamicVecBuffer = array of TKDT8DE_Vec;
PKDT8DE_DynamicVecBuffer = ^TKDT8DE_DynamicVecBuffer;
TKDT8DE_Source = record
buff: TKDT8DE_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT8DE_Source = ^TKDT8DE_Source;
TKDT8DE_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT8DE_Source) - 1] of PKDT8DE_Source;
PKDT8DE_SourceBuffer = ^TKDT8DE_SourceBuffer;
TKDT8DE_DyanmicSourceBuffer = array of PKDT8DE_Source;
PKDT8DE_DyanmicSourceBuffer = ^TKDT8DE_DyanmicSourceBuffer;
TKDT8DE_DyanmicStoreBuffer = array of TKDT8DE_Source;
PKDT8DE_DyanmicStoreBuffer = ^TKDT8DE_DyanmicStoreBuffer;
PKDT8DE_Node = ^TKDT8DE_Node;
TKDT8DE_Node = record
Parent, Right, Left: PKDT8DE_Node;
Vec: PKDT8DE_Source;
end;
TKDT8DE_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT8DE_Source; const Data: Pointer);
TKDT8DE_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT8DE_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT8DE_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT8DE_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT8DE_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT8DE_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT8DE_DyanmicStoreBuffer;
KDBuff: TKDT8DE_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT8DE_Node;
TestBuff: TKDT8DE_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT8DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT8DE_Node;
function GetData(const Index: NativeInt): PKDT8DE_Source;
public
RootNode: PKDT8DE_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT8DE_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT8DE_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT8DE_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT8DE_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT8DE_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT8DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT8DE_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT8DE_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT8DE_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT8DE_BuildProc); overload;
{ search }
function Search(const buff: TKDT8DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT8DE_Node; overload;
function Search(const buff: TKDT8DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT8DE_Node; overload;
function Search(const buff: TKDT8DE_Vec; var SearchedDistanceMin: Double): PKDT8DE_Node; overload;
function Search(const buff: TKDT8DE_Vec): PKDT8DE_Node; overload;
function SearchToken(const buff: TKDT8DE_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT8DE_DynamicVecBuffer; var OutBuff: TKDT8DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT8DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT8DE_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT8DE_Vec; overload;
class function Vec(const v: TKDT8DE_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT8DE_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT8DE_Source; const Data: Pointer);
class procedure Test;
end;
TKDT9DE = class(TCoreClassObject)
public type
// code split
TKDT9DE_Vec = array [0 .. KDT9DE_Axis - 1] of TKDT9DE_VecType;
PKDT9DE_Vec = ^TKDT9DE_Vec;
TKDT9DE_DynamicVecBuffer = array of TKDT9DE_Vec;
PKDT9DE_DynamicVecBuffer = ^TKDT9DE_DynamicVecBuffer;
TKDT9DE_Source = record
buff: TKDT9DE_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT9DE_Source = ^TKDT9DE_Source;
TKDT9DE_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT9DE_Source) - 1] of PKDT9DE_Source;
PKDT9DE_SourceBuffer = ^TKDT9DE_SourceBuffer;
TKDT9DE_DyanmicSourceBuffer = array of PKDT9DE_Source;
PKDT9DE_DyanmicSourceBuffer = ^TKDT9DE_DyanmicSourceBuffer;
TKDT9DE_DyanmicStoreBuffer = array of TKDT9DE_Source;
PKDT9DE_DyanmicStoreBuffer = ^TKDT9DE_DyanmicStoreBuffer;
PKDT9DE_Node = ^TKDT9DE_Node;
TKDT9DE_Node = record
Parent, Right, Left: PKDT9DE_Node;
Vec: PKDT9DE_Source;
end;
TKDT9DE_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT9DE_Source; const Data: Pointer);
TKDT9DE_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT9DE_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT9DE_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT9DE_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT9DE_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT9DE_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT9DE_DyanmicStoreBuffer;
KDBuff: TKDT9DE_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT9DE_Node;
TestBuff: TKDT9DE_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT9DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT9DE_Node;
function GetData(const Index: NativeInt): PKDT9DE_Source;
public
RootNode: PKDT9DE_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT9DE_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT9DE_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT9DE_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT9DE_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT9DE_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT9DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT9DE_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT9DE_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT9DE_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT9DE_BuildProc); overload;
{ search }
function Search(const buff: TKDT9DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT9DE_Node; overload;
function Search(const buff: TKDT9DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT9DE_Node; overload;
function Search(const buff: TKDT9DE_Vec; var SearchedDistanceMin: Double): PKDT9DE_Node; overload;
function Search(const buff: TKDT9DE_Vec): PKDT9DE_Node; overload;
function SearchToken(const buff: TKDT9DE_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT9DE_DynamicVecBuffer; var OutBuff: TKDT9DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT9DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT9DE_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT9DE_Vec; overload;
class function Vec(const v: TKDT9DE_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT9DE_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT9DE_Source; const Data: Pointer);
class procedure Test;
end;
TKDT10DE = class(TCoreClassObject)
public type
// code split
TKDT10DE_Vec = array [0 .. KDT10DE_Axis - 1] of TKDT10DE_VecType;
PKDT10DE_Vec = ^TKDT10DE_Vec;
TKDT10DE_DynamicVecBuffer = array of TKDT10DE_Vec;
PKDT10DE_DynamicVecBuffer = ^TKDT10DE_DynamicVecBuffer;
TKDT10DE_Source = record
buff: TKDT10DE_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT10DE_Source = ^TKDT10DE_Source;
TKDT10DE_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT10DE_Source) - 1] of PKDT10DE_Source;
PKDT10DE_SourceBuffer = ^TKDT10DE_SourceBuffer;
TKDT10DE_DyanmicSourceBuffer = array of PKDT10DE_Source;
PKDT10DE_DyanmicSourceBuffer = ^TKDT10DE_DyanmicSourceBuffer;
TKDT10DE_DyanmicStoreBuffer = array of TKDT10DE_Source;
PKDT10DE_DyanmicStoreBuffer = ^TKDT10DE_DyanmicStoreBuffer;
PKDT10DE_Node = ^TKDT10DE_Node;
TKDT10DE_Node = record
Parent, Right, Left: PKDT10DE_Node;
Vec: PKDT10DE_Source;
end;
TKDT10DE_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT10DE_Source; const Data: Pointer);
TKDT10DE_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT10DE_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT10DE_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT10DE_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT10DE_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT10DE_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT10DE_DyanmicStoreBuffer;
KDBuff: TKDT10DE_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT10DE_Node;
TestBuff: TKDT10DE_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT10DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT10DE_Node;
function GetData(const Index: NativeInt): PKDT10DE_Source;
public
RootNode: PKDT10DE_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT10DE_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT10DE_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT10DE_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT10DE_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT10DE_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT10DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT10DE_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT10DE_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT10DE_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT10DE_BuildProc); overload;
{ search }
function Search(const buff: TKDT10DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT10DE_Node; overload;
function Search(const buff: TKDT10DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT10DE_Node; overload;
function Search(const buff: TKDT10DE_Vec; var SearchedDistanceMin: Double): PKDT10DE_Node; overload;
function Search(const buff: TKDT10DE_Vec): PKDT10DE_Node; overload;
function SearchToken(const buff: TKDT10DE_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT10DE_DynamicVecBuffer; var OutBuff: TKDT10DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT10DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT10DE_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT10DE_Vec; overload;
class function Vec(const v: TKDT10DE_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT10DE_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT10DE_Source; const Data: Pointer);
class procedure Test;
end;
TKDT11DE = class(TCoreClassObject)
public type
// code split
TKDT11DE_Vec = array [0 .. KDT11DE_Axis - 1] of TKDT11DE_VecType;
PKDT11DE_Vec = ^TKDT11DE_Vec;
TKDT11DE_DynamicVecBuffer = array of TKDT11DE_Vec;
PKDT11DE_DynamicVecBuffer = ^TKDT11DE_DynamicVecBuffer;
TKDT11DE_Source = record
buff: TKDT11DE_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT11DE_Source = ^TKDT11DE_Source;
TKDT11DE_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT11DE_Source) - 1] of PKDT11DE_Source;
PKDT11DE_SourceBuffer = ^TKDT11DE_SourceBuffer;
TKDT11DE_DyanmicSourceBuffer = array of PKDT11DE_Source;
PKDT11DE_DyanmicSourceBuffer = ^TKDT11DE_DyanmicSourceBuffer;
TKDT11DE_DyanmicStoreBuffer = array of TKDT11DE_Source;
PKDT11DE_DyanmicStoreBuffer = ^TKDT11DE_DyanmicStoreBuffer;
PKDT11DE_Node = ^TKDT11DE_Node;
TKDT11DE_Node = record
Parent, Right, Left: PKDT11DE_Node;
Vec: PKDT11DE_Source;
end;
TKDT11DE_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT11DE_Source; const Data: Pointer);
TKDT11DE_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT11DE_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT11DE_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT11DE_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT11DE_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT11DE_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT11DE_DyanmicStoreBuffer;
KDBuff: TKDT11DE_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT11DE_Node;
TestBuff: TKDT11DE_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT11DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT11DE_Node;
function GetData(const Index: NativeInt): PKDT11DE_Source;
public
RootNode: PKDT11DE_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT11DE_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT11DE_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT11DE_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT11DE_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT11DE_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT11DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT11DE_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT11DE_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT11DE_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT11DE_BuildProc); overload;
{ search }
function Search(const buff: TKDT11DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT11DE_Node; overload;
function Search(const buff: TKDT11DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT11DE_Node; overload;
function Search(const buff: TKDT11DE_Vec; var SearchedDistanceMin: Double): PKDT11DE_Node; overload;
function Search(const buff: TKDT11DE_Vec): PKDT11DE_Node; overload;
function SearchToken(const buff: TKDT11DE_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT11DE_DynamicVecBuffer; var OutBuff: TKDT11DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT11DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT11DE_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT11DE_Vec; overload;
class function Vec(const v: TKDT11DE_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT11DE_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT11DE_Source; const Data: Pointer);
class procedure Test;
end;
TKDT12DE = class(TCoreClassObject)
public type
// code split
TKDT12DE_Vec = array [0 .. KDT12DE_Axis - 1] of TKDT12DE_VecType;
PKDT12DE_Vec = ^TKDT12DE_Vec;
TKDT12DE_DynamicVecBuffer = array of TKDT12DE_Vec;
PKDT12DE_DynamicVecBuffer = ^TKDT12DE_DynamicVecBuffer;
TKDT12DE_Source = record
buff: TKDT12DE_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT12DE_Source = ^TKDT12DE_Source;
TKDT12DE_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT12DE_Source) - 1] of PKDT12DE_Source;
PKDT12DE_SourceBuffer = ^TKDT12DE_SourceBuffer;
TKDT12DE_DyanmicSourceBuffer = array of PKDT12DE_Source;
PKDT12DE_DyanmicSourceBuffer = ^TKDT12DE_DyanmicSourceBuffer;
TKDT12DE_DyanmicStoreBuffer = array of TKDT12DE_Source;
PKDT12DE_DyanmicStoreBuffer = ^TKDT12DE_DyanmicStoreBuffer;
PKDT12DE_Node = ^TKDT12DE_Node;
TKDT12DE_Node = record
Parent, Right, Left: PKDT12DE_Node;
Vec: PKDT12DE_Source;
end;
TKDT12DE_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT12DE_Source; const Data: Pointer);
TKDT12DE_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT12DE_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT12DE_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT12DE_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT12DE_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT12DE_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT12DE_DyanmicStoreBuffer;
KDBuff: TKDT12DE_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT12DE_Node;
TestBuff: TKDT12DE_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT12DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT12DE_Node;
function GetData(const Index: NativeInt): PKDT12DE_Source;
public
RootNode: PKDT12DE_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT12DE_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT12DE_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT12DE_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT12DE_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT12DE_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT12DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT12DE_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT12DE_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT12DE_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT12DE_BuildProc); overload;
{ search }
function Search(const buff: TKDT12DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT12DE_Node; overload;
function Search(const buff: TKDT12DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT12DE_Node; overload;
function Search(const buff: TKDT12DE_Vec; var SearchedDistanceMin: Double): PKDT12DE_Node; overload;
function Search(const buff: TKDT12DE_Vec): PKDT12DE_Node; overload;
function SearchToken(const buff: TKDT12DE_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT12DE_DynamicVecBuffer; var OutBuff: TKDT12DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT12DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT12DE_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT12DE_Vec; overload;
class function Vec(const v: TKDT12DE_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT12DE_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT12DE_Source; const Data: Pointer);
class procedure Test;
end;
TKDT13DE = class(TCoreClassObject)
public type
// code split
TKDT13DE_Vec = array [0 .. KDT13DE_Axis - 1] of TKDT13DE_VecType;
PKDT13DE_Vec = ^TKDT13DE_Vec;
TKDT13DE_DynamicVecBuffer = array of TKDT13DE_Vec;
PKDT13DE_DynamicVecBuffer = ^TKDT13DE_DynamicVecBuffer;
TKDT13DE_Source = record
buff: TKDT13DE_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT13DE_Source = ^TKDT13DE_Source;
TKDT13DE_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT13DE_Source) - 1] of PKDT13DE_Source;
PKDT13DE_SourceBuffer = ^TKDT13DE_SourceBuffer;
TKDT13DE_DyanmicSourceBuffer = array of PKDT13DE_Source;
PKDT13DE_DyanmicSourceBuffer = ^TKDT13DE_DyanmicSourceBuffer;
TKDT13DE_DyanmicStoreBuffer = array of TKDT13DE_Source;
PKDT13DE_DyanmicStoreBuffer = ^TKDT13DE_DyanmicStoreBuffer;
PKDT13DE_Node = ^TKDT13DE_Node;
TKDT13DE_Node = record
Parent, Right, Left: PKDT13DE_Node;
Vec: PKDT13DE_Source;
end;
TKDT13DE_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT13DE_Source; const Data: Pointer);
TKDT13DE_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT13DE_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT13DE_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT13DE_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT13DE_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT13DE_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT13DE_DyanmicStoreBuffer;
KDBuff: TKDT13DE_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT13DE_Node;
TestBuff: TKDT13DE_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT13DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT13DE_Node;
function GetData(const Index: NativeInt): PKDT13DE_Source;
public
RootNode: PKDT13DE_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT13DE_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT13DE_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT13DE_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT13DE_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT13DE_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT13DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT13DE_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT13DE_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT13DE_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT13DE_BuildProc); overload;
{ search }
function Search(const buff: TKDT13DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT13DE_Node; overload;
function Search(const buff: TKDT13DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT13DE_Node; overload;
function Search(const buff: TKDT13DE_Vec; var SearchedDistanceMin: Double): PKDT13DE_Node; overload;
function Search(const buff: TKDT13DE_Vec): PKDT13DE_Node; overload;
function SearchToken(const buff: TKDT13DE_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT13DE_DynamicVecBuffer; var OutBuff: TKDT13DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT13DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT13DE_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT13DE_Vec; overload;
class function Vec(const v: TKDT13DE_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT13DE_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT13DE_Source; const Data: Pointer);
class procedure Test;
end;
TKDT14DE = class(TCoreClassObject)
public type
// code split
TKDT14DE_Vec = array [0 .. KDT14DE_Axis - 1] of TKDT14DE_VecType;
PKDT14DE_Vec = ^TKDT14DE_Vec;
TKDT14DE_DynamicVecBuffer = array of TKDT14DE_Vec;
PKDT14DE_DynamicVecBuffer = ^TKDT14DE_DynamicVecBuffer;
TKDT14DE_Source = record
buff: TKDT14DE_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT14DE_Source = ^TKDT14DE_Source;
TKDT14DE_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT14DE_Source) - 1] of PKDT14DE_Source;
PKDT14DE_SourceBuffer = ^TKDT14DE_SourceBuffer;
TKDT14DE_DyanmicSourceBuffer = array of PKDT14DE_Source;
PKDT14DE_DyanmicSourceBuffer = ^TKDT14DE_DyanmicSourceBuffer;
TKDT14DE_DyanmicStoreBuffer = array of TKDT14DE_Source;
PKDT14DE_DyanmicStoreBuffer = ^TKDT14DE_DyanmicStoreBuffer;
PKDT14DE_Node = ^TKDT14DE_Node;
TKDT14DE_Node = record
Parent, Right, Left: PKDT14DE_Node;
Vec: PKDT14DE_Source;
end;
TKDT14DE_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT14DE_Source; const Data: Pointer);
TKDT14DE_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT14DE_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT14DE_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT14DE_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT14DE_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT14DE_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT14DE_DyanmicStoreBuffer;
KDBuff: TKDT14DE_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT14DE_Node;
TestBuff: TKDT14DE_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT14DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT14DE_Node;
function GetData(const Index: NativeInt): PKDT14DE_Source;
public
RootNode: PKDT14DE_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT14DE_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT14DE_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT14DE_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT14DE_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT14DE_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT14DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT14DE_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT14DE_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT14DE_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT14DE_BuildProc); overload;
{ search }
function Search(const buff: TKDT14DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT14DE_Node; overload;
function Search(const buff: TKDT14DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT14DE_Node; overload;
function Search(const buff: TKDT14DE_Vec; var SearchedDistanceMin: Double): PKDT14DE_Node; overload;
function Search(const buff: TKDT14DE_Vec): PKDT14DE_Node; overload;
function SearchToken(const buff: TKDT14DE_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT14DE_DynamicVecBuffer; var OutBuff: TKDT14DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT14DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT14DE_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT14DE_Vec; overload;
class function Vec(const v: TKDT14DE_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT14DE_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT14DE_Source; const Data: Pointer);
class procedure Test;
end;
TKDT15DE = class(TCoreClassObject)
public type
// code split
TKDT15DE_Vec = array [0 .. KDT15DE_Axis - 1] of TKDT15DE_VecType;
PKDT15DE_Vec = ^TKDT15DE_Vec;
TKDT15DE_DynamicVecBuffer = array of TKDT15DE_Vec;
PKDT15DE_DynamicVecBuffer = ^TKDT15DE_DynamicVecBuffer;
TKDT15DE_Source = record
buff: TKDT15DE_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT15DE_Source = ^TKDT15DE_Source;
TKDT15DE_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT15DE_Source) - 1] of PKDT15DE_Source;
PKDT15DE_SourceBuffer = ^TKDT15DE_SourceBuffer;
TKDT15DE_DyanmicSourceBuffer = array of PKDT15DE_Source;
PKDT15DE_DyanmicSourceBuffer = ^TKDT15DE_DyanmicSourceBuffer;
TKDT15DE_DyanmicStoreBuffer = array of TKDT15DE_Source;
PKDT15DE_DyanmicStoreBuffer = ^TKDT15DE_DyanmicStoreBuffer;
PKDT15DE_Node = ^TKDT15DE_Node;
TKDT15DE_Node = record
Parent, Right, Left: PKDT15DE_Node;
Vec: PKDT15DE_Source;
end;
TKDT15DE_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT15DE_Source; const Data: Pointer);
TKDT15DE_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT15DE_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT15DE_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT15DE_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT15DE_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT15DE_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT15DE_DyanmicStoreBuffer;
KDBuff: TKDT15DE_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT15DE_Node;
TestBuff: TKDT15DE_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT15DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT15DE_Node;
function GetData(const Index: NativeInt): PKDT15DE_Source;
public
RootNode: PKDT15DE_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT15DE_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT15DE_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT15DE_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT15DE_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT15DE_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT15DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT15DE_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT15DE_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT15DE_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT15DE_BuildProc); overload;
{ search }
function Search(const buff: TKDT15DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT15DE_Node; overload;
function Search(const buff: TKDT15DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT15DE_Node; overload;
function Search(const buff: TKDT15DE_Vec; var SearchedDistanceMin: Double): PKDT15DE_Node; overload;
function Search(const buff: TKDT15DE_Vec): PKDT15DE_Node; overload;
function SearchToken(const buff: TKDT15DE_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT15DE_DynamicVecBuffer; var OutBuff: TKDT15DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT15DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT15DE_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT15DE_Vec; overload;
class function Vec(const v: TKDT15DE_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT15DE_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT15DE_Source; const Data: Pointer);
class procedure Test;
end;
TKDT16DE = class(TCoreClassObject)
public type
// code split
TKDT16DE_Vec = array [0 .. KDT16DE_Axis - 1] of TKDT16DE_VecType;
PKDT16DE_Vec = ^TKDT16DE_Vec;
TKDT16DE_DynamicVecBuffer = array of TKDT16DE_Vec;
PKDT16DE_DynamicVecBuffer = ^TKDT16DE_DynamicVecBuffer;
TKDT16DE_Source = record
buff: TKDT16DE_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT16DE_Source = ^TKDT16DE_Source;
TKDT16DE_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT16DE_Source) - 1] of PKDT16DE_Source;
PKDT16DE_SourceBuffer = ^TKDT16DE_SourceBuffer;
TKDT16DE_DyanmicSourceBuffer = array of PKDT16DE_Source;
PKDT16DE_DyanmicSourceBuffer = ^TKDT16DE_DyanmicSourceBuffer;
TKDT16DE_DyanmicStoreBuffer = array of TKDT16DE_Source;
PKDT16DE_DyanmicStoreBuffer = ^TKDT16DE_DyanmicStoreBuffer;
PKDT16DE_Node = ^TKDT16DE_Node;
TKDT16DE_Node = record
Parent, Right, Left: PKDT16DE_Node;
Vec: PKDT16DE_Source;
end;
TKDT16DE_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT16DE_Source; const Data: Pointer);
TKDT16DE_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT16DE_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT16DE_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT16DE_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT16DE_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT16DE_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT16DE_DyanmicStoreBuffer;
KDBuff: TKDT16DE_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT16DE_Node;
TestBuff: TKDT16DE_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT16DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT16DE_Node;
function GetData(const Index: NativeInt): PKDT16DE_Source;
public
RootNode: PKDT16DE_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT16DE_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT16DE_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT16DE_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT16DE_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT16DE_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT16DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT16DE_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT16DE_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT16DE_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT16DE_BuildProc); overload;
{ search }
function Search(const buff: TKDT16DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT16DE_Node; overload;
function Search(const buff: TKDT16DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT16DE_Node; overload;
function Search(const buff: TKDT16DE_Vec; var SearchedDistanceMin: Double): PKDT16DE_Node; overload;
function Search(const buff: TKDT16DE_Vec): PKDT16DE_Node; overload;
function SearchToken(const buff: TKDT16DE_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT16DE_DynamicVecBuffer; var OutBuff: TKDT16DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT16DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT16DE_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT16DE_Vec; overload;
class function Vec(const v: TKDT16DE_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT16DE_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT16DE_Source; const Data: Pointer);
class procedure Test;
end;
TKDT17DE = class(TCoreClassObject)
public type
// code split
TKDT17DE_Vec = array [0 .. KDT17DE_Axis - 1] of TKDT17DE_VecType;
PKDT17DE_Vec = ^TKDT17DE_Vec;
TKDT17DE_DynamicVecBuffer = array of TKDT17DE_Vec;
PKDT17DE_DynamicVecBuffer = ^TKDT17DE_DynamicVecBuffer;
TKDT17DE_Source = record
buff: TKDT17DE_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT17DE_Source = ^TKDT17DE_Source;
TKDT17DE_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT17DE_Source) - 1] of PKDT17DE_Source;
PKDT17DE_SourceBuffer = ^TKDT17DE_SourceBuffer;
TKDT17DE_DyanmicSourceBuffer = array of PKDT17DE_Source;
PKDT17DE_DyanmicSourceBuffer = ^TKDT17DE_DyanmicSourceBuffer;
TKDT17DE_DyanmicStoreBuffer = array of TKDT17DE_Source;
PKDT17DE_DyanmicStoreBuffer = ^TKDT17DE_DyanmicStoreBuffer;
PKDT17DE_Node = ^TKDT17DE_Node;
TKDT17DE_Node = record
Parent, Right, Left: PKDT17DE_Node;
Vec: PKDT17DE_Source;
end;
TKDT17DE_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT17DE_Source; const Data: Pointer);
TKDT17DE_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT17DE_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT17DE_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT17DE_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT17DE_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT17DE_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT17DE_DyanmicStoreBuffer;
KDBuff: TKDT17DE_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT17DE_Node;
TestBuff: TKDT17DE_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT17DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT17DE_Node;
function GetData(const Index: NativeInt): PKDT17DE_Source;
public
RootNode: PKDT17DE_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT17DE_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT17DE_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT17DE_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT17DE_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT17DE_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT17DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT17DE_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT17DE_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT17DE_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT17DE_BuildProc); overload;
{ search }
function Search(const buff: TKDT17DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT17DE_Node; overload;
function Search(const buff: TKDT17DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT17DE_Node; overload;
function Search(const buff: TKDT17DE_Vec; var SearchedDistanceMin: Double): PKDT17DE_Node; overload;
function Search(const buff: TKDT17DE_Vec): PKDT17DE_Node; overload;
function SearchToken(const buff: TKDT17DE_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT17DE_DynamicVecBuffer; var OutBuff: TKDT17DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT17DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT17DE_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT17DE_Vec; overload;
class function Vec(const v: TKDT17DE_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT17DE_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT17DE_Source; const Data: Pointer);
class procedure Test;
end;
TKDT18DE = class(TCoreClassObject)
public type
// code split
TKDT18DE_Vec = array [0 .. KDT18DE_Axis - 1] of TKDT18DE_VecType;
PKDT18DE_Vec = ^TKDT18DE_Vec;
TKDT18DE_DynamicVecBuffer = array of TKDT18DE_Vec;
PKDT18DE_DynamicVecBuffer = ^TKDT18DE_DynamicVecBuffer;
TKDT18DE_Source = record
buff: TKDT18DE_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT18DE_Source = ^TKDT18DE_Source;
TKDT18DE_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT18DE_Source) - 1] of PKDT18DE_Source;
PKDT18DE_SourceBuffer = ^TKDT18DE_SourceBuffer;
TKDT18DE_DyanmicSourceBuffer = array of PKDT18DE_Source;
PKDT18DE_DyanmicSourceBuffer = ^TKDT18DE_DyanmicSourceBuffer;
TKDT18DE_DyanmicStoreBuffer = array of TKDT18DE_Source;
PKDT18DE_DyanmicStoreBuffer = ^TKDT18DE_DyanmicStoreBuffer;
PKDT18DE_Node = ^TKDT18DE_Node;
TKDT18DE_Node = record
Parent, Right, Left: PKDT18DE_Node;
Vec: PKDT18DE_Source;
end;
TKDT18DE_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT18DE_Source; const Data: Pointer);
TKDT18DE_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT18DE_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT18DE_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT18DE_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT18DE_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT18DE_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT18DE_DyanmicStoreBuffer;
KDBuff: TKDT18DE_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT18DE_Node;
TestBuff: TKDT18DE_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT18DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT18DE_Node;
function GetData(const Index: NativeInt): PKDT18DE_Source;
public
RootNode: PKDT18DE_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT18DE_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT18DE_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT18DE_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT18DE_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT18DE_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT18DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT18DE_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT18DE_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT18DE_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT18DE_BuildProc); overload;
{ search }
function Search(const buff: TKDT18DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT18DE_Node; overload;
function Search(const buff: TKDT18DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT18DE_Node; overload;
function Search(const buff: TKDT18DE_Vec; var SearchedDistanceMin: Double): PKDT18DE_Node; overload;
function Search(const buff: TKDT18DE_Vec): PKDT18DE_Node; overload;
function SearchToken(const buff: TKDT18DE_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT18DE_DynamicVecBuffer; var OutBuff: TKDT18DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT18DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT18DE_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT18DE_Vec; overload;
class function Vec(const v: TKDT18DE_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT18DE_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT18DE_Source; const Data: Pointer);
class procedure Test;
end;
TKDT19DE = class(TCoreClassObject)
public type
// code split
TKDT19DE_Vec = array [0 .. KDT19DE_Axis - 1] of TKDT19DE_VecType;
PKDT19DE_Vec = ^TKDT19DE_Vec;
TKDT19DE_DynamicVecBuffer = array of TKDT19DE_Vec;
PKDT19DE_DynamicVecBuffer = ^TKDT19DE_DynamicVecBuffer;
TKDT19DE_Source = record
buff: TKDT19DE_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT19DE_Source = ^TKDT19DE_Source;
TKDT19DE_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT19DE_Source) - 1] of PKDT19DE_Source;
PKDT19DE_SourceBuffer = ^TKDT19DE_SourceBuffer;
TKDT19DE_DyanmicSourceBuffer = array of PKDT19DE_Source;
PKDT19DE_DyanmicSourceBuffer = ^TKDT19DE_DyanmicSourceBuffer;
TKDT19DE_DyanmicStoreBuffer = array of TKDT19DE_Source;
PKDT19DE_DyanmicStoreBuffer = ^TKDT19DE_DyanmicStoreBuffer;
PKDT19DE_Node = ^TKDT19DE_Node;
TKDT19DE_Node = record
Parent, Right, Left: PKDT19DE_Node;
Vec: PKDT19DE_Source;
end;
TKDT19DE_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT19DE_Source; const Data: Pointer);
TKDT19DE_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT19DE_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT19DE_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT19DE_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT19DE_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT19DE_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT19DE_DyanmicStoreBuffer;
KDBuff: TKDT19DE_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT19DE_Node;
TestBuff: TKDT19DE_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT19DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT19DE_Node;
function GetData(const Index: NativeInt): PKDT19DE_Source;
public
RootNode: PKDT19DE_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT19DE_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT19DE_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT19DE_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT19DE_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT19DE_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT19DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT19DE_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT19DE_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT19DE_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT19DE_BuildProc); overload;
{ search }
function Search(const buff: TKDT19DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT19DE_Node; overload;
function Search(const buff: TKDT19DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT19DE_Node; overload;
function Search(const buff: TKDT19DE_Vec; var SearchedDistanceMin: Double): PKDT19DE_Node; overload;
function Search(const buff: TKDT19DE_Vec): PKDT19DE_Node; overload;
function SearchToken(const buff: TKDT19DE_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT19DE_DynamicVecBuffer; var OutBuff: TKDT19DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT19DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT19DE_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT19DE_Vec; overload;
class function Vec(const v: TKDT19DE_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT19DE_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT19DE_Source; const Data: Pointer);
class procedure Test;
end;
TKDT20DE = class(TCoreClassObject)
public type
// code split
TKDT20DE_Vec = array [0 .. KDT20DE_Axis - 1] of TKDT20DE_VecType;
PKDT20DE_Vec = ^TKDT20DE_Vec;
TKDT20DE_DynamicVecBuffer = array of TKDT20DE_Vec;
PKDT20DE_DynamicVecBuffer = ^TKDT20DE_DynamicVecBuffer;
TKDT20DE_Source = record
buff: TKDT20DE_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT20DE_Source = ^TKDT20DE_Source;
TKDT20DE_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT20DE_Source) - 1] of PKDT20DE_Source;
PKDT20DE_SourceBuffer = ^TKDT20DE_SourceBuffer;
TKDT20DE_DyanmicSourceBuffer = array of PKDT20DE_Source;
PKDT20DE_DyanmicSourceBuffer = ^TKDT20DE_DyanmicSourceBuffer;
TKDT20DE_DyanmicStoreBuffer = array of TKDT20DE_Source;
PKDT20DE_DyanmicStoreBuffer = ^TKDT20DE_DyanmicStoreBuffer;
PKDT20DE_Node = ^TKDT20DE_Node;
TKDT20DE_Node = record
Parent, Right, Left: PKDT20DE_Node;
Vec: PKDT20DE_Source;
end;
TKDT20DE_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT20DE_Source; const Data: Pointer);
TKDT20DE_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT20DE_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT20DE_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT20DE_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT20DE_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT20DE_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT20DE_DyanmicStoreBuffer;
KDBuff: TKDT20DE_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT20DE_Node;
TestBuff: TKDT20DE_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT20DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT20DE_Node;
function GetData(const Index: NativeInt): PKDT20DE_Source;
public
RootNode: PKDT20DE_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT20DE_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT20DE_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT20DE_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT20DE_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT20DE_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT20DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT20DE_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT20DE_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT20DE_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT20DE_BuildProc); overload;
{ search }
function Search(const buff: TKDT20DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT20DE_Node; overload;
function Search(const buff: TKDT20DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT20DE_Node; overload;
function Search(const buff: TKDT20DE_Vec; var SearchedDistanceMin: Double): PKDT20DE_Node; overload;
function Search(const buff: TKDT20DE_Vec): PKDT20DE_Node; overload;
function SearchToken(const buff: TKDT20DE_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT20DE_DynamicVecBuffer; var OutBuff: TKDT20DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT20DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT20DE_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT20DE_Vec; overload;
class function Vec(const v: TKDT20DE_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT20DE_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT20DE_Source; const Data: Pointer);
class procedure Test;
end;
TKDT21DE = class(TCoreClassObject)
public type
// code split
TKDT21DE_Vec = array [0 .. KDT21DE_Axis - 1] of TKDT21DE_VecType;
PKDT21DE_Vec = ^TKDT21DE_Vec;
TKDT21DE_DynamicVecBuffer = array of TKDT21DE_Vec;
PKDT21DE_DynamicVecBuffer = ^TKDT21DE_DynamicVecBuffer;
TKDT21DE_Source = record
buff: TKDT21DE_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT21DE_Source = ^TKDT21DE_Source;
TKDT21DE_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT21DE_Source) - 1] of PKDT21DE_Source;
PKDT21DE_SourceBuffer = ^TKDT21DE_SourceBuffer;
TKDT21DE_DyanmicSourceBuffer = array of PKDT21DE_Source;
PKDT21DE_DyanmicSourceBuffer = ^TKDT21DE_DyanmicSourceBuffer;
TKDT21DE_DyanmicStoreBuffer = array of TKDT21DE_Source;
PKDT21DE_DyanmicStoreBuffer = ^TKDT21DE_DyanmicStoreBuffer;
PKDT21DE_Node = ^TKDT21DE_Node;
TKDT21DE_Node = record
Parent, Right, Left: PKDT21DE_Node;
Vec: PKDT21DE_Source;
end;
TKDT21DE_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT21DE_Source; const Data: Pointer);
TKDT21DE_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT21DE_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT21DE_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT21DE_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT21DE_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT21DE_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT21DE_DyanmicStoreBuffer;
KDBuff: TKDT21DE_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT21DE_Node;
TestBuff: TKDT21DE_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT21DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT21DE_Node;
function GetData(const Index: NativeInt): PKDT21DE_Source;
public
RootNode: PKDT21DE_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT21DE_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT21DE_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT21DE_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT21DE_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT21DE_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT21DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT21DE_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT21DE_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT21DE_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT21DE_BuildProc); overload;
{ search }
function Search(const buff: TKDT21DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT21DE_Node; overload;
function Search(const buff: TKDT21DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT21DE_Node; overload;
function Search(const buff: TKDT21DE_Vec; var SearchedDistanceMin: Double): PKDT21DE_Node; overload;
function Search(const buff: TKDT21DE_Vec): PKDT21DE_Node; overload;
function SearchToken(const buff: TKDT21DE_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT21DE_DynamicVecBuffer; var OutBuff: TKDT21DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT21DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT21DE_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT21DE_Vec; overload;
class function Vec(const v: TKDT21DE_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT21DE_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT21DE_Source; const Data: Pointer);
class procedure Test;
end;
TKDT22DE = class(TCoreClassObject)
public type
// code split
TKDT22DE_Vec = array [0 .. KDT22DE_Axis - 1] of TKDT22DE_VecType;
PKDT22DE_Vec = ^TKDT22DE_Vec;
TKDT22DE_DynamicVecBuffer = array of TKDT22DE_Vec;
PKDT22DE_DynamicVecBuffer = ^TKDT22DE_DynamicVecBuffer;
TKDT22DE_Source = record
buff: TKDT22DE_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT22DE_Source = ^TKDT22DE_Source;
TKDT22DE_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT22DE_Source) - 1] of PKDT22DE_Source;
PKDT22DE_SourceBuffer = ^TKDT22DE_SourceBuffer;
TKDT22DE_DyanmicSourceBuffer = array of PKDT22DE_Source;
PKDT22DE_DyanmicSourceBuffer = ^TKDT22DE_DyanmicSourceBuffer;
TKDT22DE_DyanmicStoreBuffer = array of TKDT22DE_Source;
PKDT22DE_DyanmicStoreBuffer = ^TKDT22DE_DyanmicStoreBuffer;
PKDT22DE_Node = ^TKDT22DE_Node;
TKDT22DE_Node = record
Parent, Right, Left: PKDT22DE_Node;
Vec: PKDT22DE_Source;
end;
TKDT22DE_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT22DE_Source; const Data: Pointer);
TKDT22DE_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT22DE_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT22DE_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT22DE_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT22DE_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT22DE_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT22DE_DyanmicStoreBuffer;
KDBuff: TKDT22DE_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT22DE_Node;
TestBuff: TKDT22DE_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT22DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT22DE_Node;
function GetData(const Index: NativeInt): PKDT22DE_Source;
public
RootNode: PKDT22DE_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT22DE_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT22DE_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT22DE_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT22DE_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT22DE_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT22DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT22DE_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT22DE_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT22DE_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT22DE_BuildProc); overload;
{ search }
function Search(const buff: TKDT22DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT22DE_Node; overload;
function Search(const buff: TKDT22DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT22DE_Node; overload;
function Search(const buff: TKDT22DE_Vec; var SearchedDistanceMin: Double): PKDT22DE_Node; overload;
function Search(const buff: TKDT22DE_Vec): PKDT22DE_Node; overload;
function SearchToken(const buff: TKDT22DE_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT22DE_DynamicVecBuffer; var OutBuff: TKDT22DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT22DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT22DE_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT22DE_Vec; overload;
class function Vec(const v: TKDT22DE_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT22DE_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT22DE_Source; const Data: Pointer);
class procedure Test;
end;
TKDT23DE = class(TCoreClassObject)
public type
// code split
TKDT23DE_Vec = array [0 .. KDT23DE_Axis - 1] of TKDT23DE_VecType;
PKDT23DE_Vec = ^TKDT23DE_Vec;
TKDT23DE_DynamicVecBuffer = array of TKDT23DE_Vec;
PKDT23DE_DynamicVecBuffer = ^TKDT23DE_DynamicVecBuffer;
TKDT23DE_Source = record
buff: TKDT23DE_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT23DE_Source = ^TKDT23DE_Source;
TKDT23DE_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT23DE_Source) - 1] of PKDT23DE_Source;
PKDT23DE_SourceBuffer = ^TKDT23DE_SourceBuffer;
TKDT23DE_DyanmicSourceBuffer = array of PKDT23DE_Source;
PKDT23DE_DyanmicSourceBuffer = ^TKDT23DE_DyanmicSourceBuffer;
TKDT23DE_DyanmicStoreBuffer = array of TKDT23DE_Source;
PKDT23DE_DyanmicStoreBuffer = ^TKDT23DE_DyanmicStoreBuffer;
PKDT23DE_Node = ^TKDT23DE_Node;
TKDT23DE_Node = record
Parent, Right, Left: PKDT23DE_Node;
Vec: PKDT23DE_Source;
end;
TKDT23DE_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT23DE_Source; const Data: Pointer);
TKDT23DE_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT23DE_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT23DE_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT23DE_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT23DE_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT23DE_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT23DE_DyanmicStoreBuffer;
KDBuff: TKDT23DE_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT23DE_Node;
TestBuff: TKDT23DE_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT23DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT23DE_Node;
function GetData(const Index: NativeInt): PKDT23DE_Source;
public
RootNode: PKDT23DE_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT23DE_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT23DE_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT23DE_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT23DE_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT23DE_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT23DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT23DE_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT23DE_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT23DE_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT23DE_BuildProc); overload;
{ search }
function Search(const buff: TKDT23DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT23DE_Node; overload;
function Search(const buff: TKDT23DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT23DE_Node; overload;
function Search(const buff: TKDT23DE_Vec; var SearchedDistanceMin: Double): PKDT23DE_Node; overload;
function Search(const buff: TKDT23DE_Vec): PKDT23DE_Node; overload;
function SearchToken(const buff: TKDT23DE_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT23DE_DynamicVecBuffer; var OutBuff: TKDT23DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT23DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT23DE_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT23DE_Vec; overload;
class function Vec(const v: TKDT23DE_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT23DE_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT23DE_Source; const Data: Pointer);
class procedure Test;
end;
TKDT24DE = class(TCoreClassObject)
public type
// code split
TKDT24DE_Vec = array [0 .. KDT24DE_Axis - 1] of TKDT24DE_VecType;
PKDT24DE_Vec = ^TKDT24DE_Vec;
TKDT24DE_DynamicVecBuffer = array of TKDT24DE_Vec;
PKDT24DE_DynamicVecBuffer = ^TKDT24DE_DynamicVecBuffer;
TKDT24DE_Source = record
buff: TKDT24DE_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT24DE_Source = ^TKDT24DE_Source;
TKDT24DE_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT24DE_Source) - 1] of PKDT24DE_Source;
PKDT24DE_SourceBuffer = ^TKDT24DE_SourceBuffer;
TKDT24DE_DyanmicSourceBuffer = array of PKDT24DE_Source;
PKDT24DE_DyanmicSourceBuffer = ^TKDT24DE_DyanmicSourceBuffer;
TKDT24DE_DyanmicStoreBuffer = array of TKDT24DE_Source;
PKDT24DE_DyanmicStoreBuffer = ^TKDT24DE_DyanmicStoreBuffer;
PKDT24DE_Node = ^TKDT24DE_Node;
TKDT24DE_Node = record
Parent, Right, Left: PKDT24DE_Node;
Vec: PKDT24DE_Source;
end;
TKDT24DE_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT24DE_Source; const Data: Pointer);
TKDT24DE_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT24DE_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT24DE_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT24DE_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT24DE_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT24DE_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT24DE_DyanmicStoreBuffer;
KDBuff: TKDT24DE_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT24DE_Node;
TestBuff: TKDT24DE_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT24DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT24DE_Node;
function GetData(const Index: NativeInt): PKDT24DE_Source;
public
RootNode: PKDT24DE_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT24DE_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT24DE_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT24DE_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT24DE_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT24DE_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT24DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT24DE_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT24DE_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT24DE_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT24DE_BuildProc); overload;
{ search }
function Search(const buff: TKDT24DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT24DE_Node; overload;
function Search(const buff: TKDT24DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT24DE_Node; overload;
function Search(const buff: TKDT24DE_Vec; var SearchedDistanceMin: Double): PKDT24DE_Node; overload;
function Search(const buff: TKDT24DE_Vec): PKDT24DE_Node; overload;
function SearchToken(const buff: TKDT24DE_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT24DE_DynamicVecBuffer; var OutBuff: TKDT24DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT24DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT24DE_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT24DE_Vec; overload;
class function Vec(const v: TKDT24DE_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT24DE_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT24DE_Source; const Data: Pointer);
class procedure Test;
end;
TKDT48DE = class(TCoreClassObject)
public type
// code split
TKDT48DE_Vec = array [0 .. KDT48DE_Axis - 1] of TKDT48DE_VecType;
PKDT48DE_Vec = ^TKDT48DE_Vec;
TKDT48DE_DynamicVecBuffer = array of TKDT48DE_Vec;
PKDT48DE_DynamicVecBuffer = ^TKDT48DE_DynamicVecBuffer;
TKDT48DE_Source = record
buff: TKDT48DE_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT48DE_Source = ^TKDT48DE_Source;
TKDT48DE_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT48DE_Source) - 1] of PKDT48DE_Source;
PKDT48DE_SourceBuffer = ^TKDT48DE_SourceBuffer;
TKDT48DE_DyanmicSourceBuffer = array of PKDT48DE_Source;
PKDT48DE_DyanmicSourceBuffer = ^TKDT48DE_DyanmicSourceBuffer;
TKDT48DE_DyanmicStoreBuffer = array of TKDT48DE_Source;
PKDT48DE_DyanmicStoreBuffer = ^TKDT48DE_DyanmicStoreBuffer;
PKDT48DE_Node = ^TKDT48DE_Node;
TKDT48DE_Node = record
Parent, Right, Left: PKDT48DE_Node;
Vec: PKDT48DE_Source;
end;
TKDT48DE_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT48DE_Source; const Data: Pointer);
TKDT48DE_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT48DE_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT48DE_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT48DE_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT48DE_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT48DE_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT48DE_DyanmicStoreBuffer;
KDBuff: TKDT48DE_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT48DE_Node;
TestBuff: TKDT48DE_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT48DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT48DE_Node;
function GetData(const Index: NativeInt): PKDT48DE_Source;
public
RootNode: PKDT48DE_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT48DE_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT48DE_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT48DE_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT48DE_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT48DE_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT48DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT48DE_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT48DE_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT48DE_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT48DE_BuildProc); overload;
{ search }
function Search(const buff: TKDT48DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT48DE_Node; overload;
function Search(const buff: TKDT48DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT48DE_Node; overload;
function Search(const buff: TKDT48DE_Vec; var SearchedDistanceMin: Double): PKDT48DE_Node; overload;
function Search(const buff: TKDT48DE_Vec): PKDT48DE_Node; overload;
function SearchToken(const buff: TKDT48DE_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT48DE_DynamicVecBuffer; var OutBuff: TKDT48DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT48DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT48DE_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT48DE_Vec; overload;
class function Vec(const v: TKDT48DE_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT48DE_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT48DE_Source; const Data: Pointer);
class procedure Test;
end;
TKDT52DE = class(TCoreClassObject)
public type
// code split
TKDT52DE_Vec = array [0 .. KDT52DE_Axis - 1] of TKDT52DE_VecType;
PKDT52DE_Vec = ^TKDT52DE_Vec;
TKDT52DE_DynamicVecBuffer = array of TKDT52DE_Vec;
PKDT52DE_DynamicVecBuffer = ^TKDT52DE_DynamicVecBuffer;
TKDT52DE_Source = record
buff: TKDT52DE_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT52DE_Source = ^TKDT52DE_Source;
TKDT52DE_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT52DE_Source) - 1] of PKDT52DE_Source;
PKDT52DE_SourceBuffer = ^TKDT52DE_SourceBuffer;
TKDT52DE_DyanmicSourceBuffer = array of PKDT52DE_Source;
PKDT52DE_DyanmicSourceBuffer = ^TKDT52DE_DyanmicSourceBuffer;
TKDT52DE_DyanmicStoreBuffer = array of TKDT52DE_Source;
PKDT52DE_DyanmicStoreBuffer = ^TKDT52DE_DyanmicStoreBuffer;
PKDT52DE_Node = ^TKDT52DE_Node;
TKDT52DE_Node = record
Parent, Right, Left: PKDT52DE_Node;
Vec: PKDT52DE_Source;
end;
TKDT52DE_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT52DE_Source; const Data: Pointer);
TKDT52DE_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT52DE_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT52DE_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT52DE_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT52DE_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT52DE_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT52DE_DyanmicStoreBuffer;
KDBuff: TKDT52DE_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT52DE_Node;
TestBuff: TKDT52DE_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT52DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT52DE_Node;
function GetData(const Index: NativeInt): PKDT52DE_Source;
public
RootNode: PKDT52DE_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT52DE_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT52DE_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT52DE_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT52DE_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT52DE_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT52DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT52DE_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT52DE_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT52DE_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT52DE_BuildProc); overload;
{ search }
function Search(const buff: TKDT52DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT52DE_Node; overload;
function Search(const buff: TKDT52DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT52DE_Node; overload;
function Search(const buff: TKDT52DE_Vec; var SearchedDistanceMin: Double): PKDT52DE_Node; overload;
function Search(const buff: TKDT52DE_Vec): PKDT52DE_Node; overload;
function SearchToken(const buff: TKDT52DE_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT52DE_DynamicVecBuffer; var OutBuff: TKDT52DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT52DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT52DE_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT52DE_Vec; overload;
class function Vec(const v: TKDT52DE_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT52DE_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT52DE_Source; const Data: Pointer);
class procedure Test;
end;
TKDT64DE = class(TCoreClassObject)
public type
// code split
TKDT64DE_Vec = array [0 .. KDT64DE_Axis - 1] of TKDT64DE_VecType;
PKDT64DE_Vec = ^TKDT64DE_Vec;
TKDT64DE_DynamicVecBuffer = array of TKDT64DE_Vec;
PKDT64DE_DynamicVecBuffer = ^TKDT64DE_DynamicVecBuffer;
TKDT64DE_Source = record
buff: TKDT64DE_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT64DE_Source = ^TKDT64DE_Source;
TKDT64DE_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT64DE_Source) - 1] of PKDT64DE_Source;
PKDT64DE_SourceBuffer = ^TKDT64DE_SourceBuffer;
TKDT64DE_DyanmicSourceBuffer = array of PKDT64DE_Source;
PKDT64DE_DyanmicSourceBuffer = ^TKDT64DE_DyanmicSourceBuffer;
TKDT64DE_DyanmicStoreBuffer = array of TKDT64DE_Source;
PKDT64DE_DyanmicStoreBuffer = ^TKDT64DE_DyanmicStoreBuffer;
PKDT64DE_Node = ^TKDT64DE_Node;
TKDT64DE_Node = record
Parent, Right, Left: PKDT64DE_Node;
Vec: PKDT64DE_Source;
end;
TKDT64DE_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT64DE_Source; const Data: Pointer);
TKDT64DE_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT64DE_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT64DE_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT64DE_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT64DE_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT64DE_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT64DE_DyanmicStoreBuffer;
KDBuff: TKDT64DE_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT64DE_Node;
TestBuff: TKDT64DE_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT64DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT64DE_Node;
function GetData(const Index: NativeInt): PKDT64DE_Source;
public
RootNode: PKDT64DE_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT64DE_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT64DE_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT64DE_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT64DE_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT64DE_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT64DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT64DE_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT64DE_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT64DE_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT64DE_BuildProc); overload;
{ search }
function Search(const buff: TKDT64DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT64DE_Node; overload;
function Search(const buff: TKDT64DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT64DE_Node; overload;
function Search(const buff: TKDT64DE_Vec; var SearchedDistanceMin: Double): PKDT64DE_Node; overload;
function Search(const buff: TKDT64DE_Vec): PKDT64DE_Node; overload;
function SearchToken(const buff: TKDT64DE_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT64DE_DynamicVecBuffer; var OutBuff: TKDT64DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT64DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT64DE_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT64DE_Vec; overload;
class function Vec(const v: TKDT64DE_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT64DE_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT64DE_Source; const Data: Pointer);
class procedure Test;
end;
TKDT96DE = class(TCoreClassObject)
public type
// code split
TKDT96DE_Vec = array [0 .. KDT96DE_Axis - 1] of TKDT96DE_VecType;
PKDT96DE_Vec = ^TKDT96DE_Vec;
TKDT96DE_DynamicVecBuffer = array of TKDT96DE_Vec;
PKDT96DE_DynamicVecBuffer = ^TKDT96DE_DynamicVecBuffer;
TKDT96DE_Source = record
buff: TKDT96DE_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT96DE_Source = ^TKDT96DE_Source;
TKDT96DE_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT96DE_Source) - 1] of PKDT96DE_Source;
PKDT96DE_SourceBuffer = ^TKDT96DE_SourceBuffer;
TKDT96DE_DyanmicSourceBuffer = array of PKDT96DE_Source;
PKDT96DE_DyanmicSourceBuffer = ^TKDT96DE_DyanmicSourceBuffer;
TKDT96DE_DyanmicStoreBuffer = array of TKDT96DE_Source;
PKDT96DE_DyanmicStoreBuffer = ^TKDT96DE_DyanmicStoreBuffer;
PKDT96DE_Node = ^TKDT96DE_Node;
TKDT96DE_Node = record
Parent, Right, Left: PKDT96DE_Node;
Vec: PKDT96DE_Source;
end;
TKDT96DE_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT96DE_Source; const Data: Pointer);
TKDT96DE_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT96DE_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT96DE_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT96DE_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT96DE_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT96DE_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT96DE_DyanmicStoreBuffer;
KDBuff: TKDT96DE_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT96DE_Node;
TestBuff: TKDT96DE_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT96DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT96DE_Node;
function GetData(const Index: NativeInt): PKDT96DE_Source;
public
RootNode: PKDT96DE_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT96DE_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT96DE_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT96DE_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT96DE_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT96DE_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT96DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT96DE_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT96DE_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT96DE_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT96DE_BuildProc); overload;
{ search }
function Search(const buff: TKDT96DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT96DE_Node; overload;
function Search(const buff: TKDT96DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT96DE_Node; overload;
function Search(const buff: TKDT96DE_Vec; var SearchedDistanceMin: Double): PKDT96DE_Node; overload;
function Search(const buff: TKDT96DE_Vec): PKDT96DE_Node; overload;
function SearchToken(const buff: TKDT96DE_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT96DE_DynamicVecBuffer; var OutBuff: TKDT96DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT96DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT96DE_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT96DE_Vec; overload;
class function Vec(const v: TKDT96DE_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT96DE_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT96DE_Source; const Data: Pointer);
class procedure Test;
end;
TKDT128DE = class(TCoreClassObject)
public type
// code split
TKDT128DE_Vec = array [0 .. KDT128DE_Axis - 1] of TKDT128DE_VecType;
PKDT128DE_Vec = ^TKDT128DE_Vec;
TKDT128DE_DynamicVecBuffer = array of TKDT128DE_Vec;
PKDT128DE_DynamicVecBuffer = ^TKDT128DE_DynamicVecBuffer;
TKDT128DE_Source = record
buff: TKDT128DE_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT128DE_Source = ^TKDT128DE_Source;
TKDT128DE_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT128DE_Source) - 1] of PKDT128DE_Source;
PKDT128DE_SourceBuffer = ^TKDT128DE_SourceBuffer;
TKDT128DE_DyanmicSourceBuffer = array of PKDT128DE_Source;
PKDT128DE_DyanmicSourceBuffer = ^TKDT128DE_DyanmicSourceBuffer;
TKDT128DE_DyanmicStoreBuffer = array of TKDT128DE_Source;
PKDT128DE_DyanmicStoreBuffer = ^TKDT128DE_DyanmicStoreBuffer;
PKDT128DE_Node = ^TKDT128DE_Node;
TKDT128DE_Node = record
Parent, Right, Left: PKDT128DE_Node;
Vec: PKDT128DE_Source;
end;
TKDT128DE_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT128DE_Source; const Data: Pointer);
TKDT128DE_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT128DE_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT128DE_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT128DE_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT128DE_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT128DE_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT128DE_DyanmicStoreBuffer;
KDBuff: TKDT128DE_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT128DE_Node;
TestBuff: TKDT128DE_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT128DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT128DE_Node;
function GetData(const Index: NativeInt): PKDT128DE_Source;
public
RootNode: PKDT128DE_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT128DE_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT128DE_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT128DE_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT128DE_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT128DE_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT128DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT128DE_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT128DE_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT128DE_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT128DE_BuildProc); overload;
{ search }
function Search(const buff: TKDT128DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT128DE_Node; overload;
function Search(const buff: TKDT128DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT128DE_Node; overload;
function Search(const buff: TKDT128DE_Vec; var SearchedDistanceMin: Double): PKDT128DE_Node; overload;
function Search(const buff: TKDT128DE_Vec): PKDT128DE_Node; overload;
function SearchToken(const buff: TKDT128DE_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT128DE_DynamicVecBuffer; var OutBuff: TKDT128DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT128DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT128DE_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT128DE_Vec; overload;
class function Vec(const v: TKDT128DE_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT128DE_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT128DE_Source; const Data: Pointer);
class procedure Test;
end;
TKDT156DE = class(TCoreClassObject)
public type
// code split
TKDT156DE_Vec = array [0 .. KDT156DE_Axis - 1] of TKDT156DE_VecType;
PKDT156DE_Vec = ^TKDT156DE_Vec;
TKDT156DE_DynamicVecBuffer = array of TKDT156DE_Vec;
PKDT156DE_DynamicVecBuffer = ^TKDT156DE_DynamicVecBuffer;
TKDT156DE_Source = record
buff: TKDT156DE_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT156DE_Source = ^TKDT156DE_Source;
TKDT156DE_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT156DE_Source) - 1] of PKDT156DE_Source;
PKDT156DE_SourceBuffer = ^TKDT156DE_SourceBuffer;
TKDT156DE_DyanmicSourceBuffer = array of PKDT156DE_Source;
PKDT156DE_DyanmicSourceBuffer = ^TKDT156DE_DyanmicSourceBuffer;
TKDT156DE_DyanmicStoreBuffer = array of TKDT156DE_Source;
PKDT156DE_DyanmicStoreBuffer = ^TKDT156DE_DyanmicStoreBuffer;
PKDT156DE_Node = ^TKDT156DE_Node;
TKDT156DE_Node = record
Parent, Right, Left: PKDT156DE_Node;
Vec: PKDT156DE_Source;
end;
TKDT156DE_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT156DE_Source; const Data: Pointer);
TKDT156DE_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT156DE_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT156DE_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT156DE_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT156DE_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT156DE_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT156DE_DyanmicStoreBuffer;
KDBuff: TKDT156DE_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT156DE_Node;
TestBuff: TKDT156DE_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT156DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT156DE_Node;
function GetData(const Index: NativeInt): PKDT156DE_Source;
public
RootNode: PKDT156DE_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT156DE_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT156DE_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT156DE_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT156DE_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT156DE_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT156DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT156DE_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT156DE_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT156DE_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT156DE_BuildProc); overload;
{ search }
function Search(const buff: TKDT156DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT156DE_Node; overload;
function Search(const buff: TKDT156DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT156DE_Node; overload;
function Search(const buff: TKDT156DE_Vec; var SearchedDistanceMin: Double): PKDT156DE_Node; overload;
function Search(const buff: TKDT156DE_Vec): PKDT156DE_Node; overload;
function SearchToken(const buff: TKDT156DE_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT156DE_DynamicVecBuffer; var OutBuff: TKDT156DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT156DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT156DE_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT156DE_Vec; overload;
class function Vec(const v: TKDT156DE_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT156DE_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT156DE_Source; const Data: Pointer);
class procedure Test;
end;
TKDT192DE = class(TCoreClassObject)
public type
// code split
TKDT192DE_Vec = array [0 .. KDT192DE_Axis - 1] of TKDT192DE_VecType;
PKDT192DE_Vec = ^TKDT192DE_Vec;
TKDT192DE_DynamicVecBuffer = array of TKDT192DE_Vec;
PKDT192DE_DynamicVecBuffer = ^TKDT192DE_DynamicVecBuffer;
TKDT192DE_Source = record
buff: TKDT192DE_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT192DE_Source = ^TKDT192DE_Source;
TKDT192DE_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT192DE_Source) - 1] of PKDT192DE_Source;
PKDT192DE_SourceBuffer = ^TKDT192DE_SourceBuffer;
TKDT192DE_DyanmicSourceBuffer = array of PKDT192DE_Source;
PKDT192DE_DyanmicSourceBuffer = ^TKDT192DE_DyanmicSourceBuffer;
TKDT192DE_DyanmicStoreBuffer = array of TKDT192DE_Source;
PKDT192DE_DyanmicStoreBuffer = ^TKDT192DE_DyanmicStoreBuffer;
PKDT192DE_Node = ^TKDT192DE_Node;
TKDT192DE_Node = record
Parent, Right, Left: PKDT192DE_Node;
Vec: PKDT192DE_Source;
end;
TKDT192DE_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT192DE_Source; const Data: Pointer);
TKDT192DE_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT192DE_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT192DE_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT192DE_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT192DE_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT192DE_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT192DE_DyanmicStoreBuffer;
KDBuff: TKDT192DE_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT192DE_Node;
TestBuff: TKDT192DE_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT192DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT192DE_Node;
function GetData(const Index: NativeInt): PKDT192DE_Source;
public
RootNode: PKDT192DE_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT192DE_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT192DE_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT192DE_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT192DE_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT192DE_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT192DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT192DE_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT192DE_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT192DE_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT192DE_BuildProc); overload;
{ search }
function Search(const buff: TKDT192DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT192DE_Node; overload;
function Search(const buff: TKDT192DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT192DE_Node; overload;
function Search(const buff: TKDT192DE_Vec; var SearchedDistanceMin: Double): PKDT192DE_Node; overload;
function Search(const buff: TKDT192DE_Vec): PKDT192DE_Node; overload;
function SearchToken(const buff: TKDT192DE_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT192DE_DynamicVecBuffer; var OutBuff: TKDT192DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT192DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT192DE_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT192DE_Vec; overload;
class function Vec(const v: TKDT192DE_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT192DE_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT192DE_Source; const Data: Pointer);
class procedure Test;
end;
TKDT256DE = class(TCoreClassObject)
public type
// code split
TKDT256DE_Vec = array [0 .. KDT256DE_Axis - 1] of TKDT256DE_VecType;
PKDT256DE_Vec = ^TKDT256DE_Vec;
TKDT256DE_DynamicVecBuffer = array of TKDT256DE_Vec;
PKDT256DE_DynamicVecBuffer = ^TKDT256DE_DynamicVecBuffer;
TKDT256DE_Source = record
buff: TKDT256DE_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT256DE_Source = ^TKDT256DE_Source;
TKDT256DE_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT256DE_Source) - 1] of PKDT256DE_Source;
PKDT256DE_SourceBuffer = ^TKDT256DE_SourceBuffer;
TKDT256DE_DyanmicSourceBuffer = array of PKDT256DE_Source;
PKDT256DE_DyanmicSourceBuffer = ^TKDT256DE_DyanmicSourceBuffer;
TKDT256DE_DyanmicStoreBuffer = array of TKDT256DE_Source;
PKDT256DE_DyanmicStoreBuffer = ^TKDT256DE_DyanmicStoreBuffer;
PKDT256DE_Node = ^TKDT256DE_Node;
TKDT256DE_Node = record
Parent, Right, Left: PKDT256DE_Node;
Vec: PKDT256DE_Source;
end;
TKDT256DE_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT256DE_Source; const Data: Pointer);
TKDT256DE_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT256DE_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT256DE_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT256DE_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT256DE_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT256DE_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT256DE_DyanmicStoreBuffer;
KDBuff: TKDT256DE_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT256DE_Node;
TestBuff: TKDT256DE_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT256DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT256DE_Node;
function GetData(const Index: NativeInt): PKDT256DE_Source;
public
RootNode: PKDT256DE_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT256DE_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT256DE_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT256DE_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT256DE_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT256DE_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT256DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT256DE_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT256DE_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT256DE_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT256DE_BuildProc); overload;
{ search }
function Search(const buff: TKDT256DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT256DE_Node; overload;
function Search(const buff: TKDT256DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT256DE_Node; overload;
function Search(const buff: TKDT256DE_Vec; var SearchedDistanceMin: Double): PKDT256DE_Node; overload;
function Search(const buff: TKDT256DE_Vec): PKDT256DE_Node; overload;
function SearchToken(const buff: TKDT256DE_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT256DE_DynamicVecBuffer; var OutBuff: TKDT256DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT256DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT256DE_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT256DE_Vec; overload;
class function Vec(const v: TKDT256DE_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT256DE_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT256DE_Source; const Data: Pointer);
class procedure Test;
end;
TKDT384DE = class(TCoreClassObject)
public type
// code split
TKDT384DE_Vec = array [0 .. KDT384DE_Axis - 1] of TKDT384DE_VecType;
PKDT384DE_Vec = ^TKDT384DE_Vec;
TKDT384DE_DynamicVecBuffer = array of TKDT384DE_Vec;
PKDT384DE_DynamicVecBuffer = ^TKDT384DE_DynamicVecBuffer;
TKDT384DE_Source = record
buff: TKDT384DE_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT384DE_Source = ^TKDT384DE_Source;
TKDT384DE_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT384DE_Source) - 1] of PKDT384DE_Source;
PKDT384DE_SourceBuffer = ^TKDT384DE_SourceBuffer;
TKDT384DE_DyanmicSourceBuffer = array of PKDT384DE_Source;
PKDT384DE_DyanmicSourceBuffer = ^TKDT384DE_DyanmicSourceBuffer;
TKDT384DE_DyanmicStoreBuffer = array of TKDT384DE_Source;
PKDT384DE_DyanmicStoreBuffer = ^TKDT384DE_DyanmicStoreBuffer;
PKDT384DE_Node = ^TKDT384DE_Node;
TKDT384DE_Node = record
Parent, Right, Left: PKDT384DE_Node;
Vec: PKDT384DE_Source;
end;
TKDT384DE_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT384DE_Source; const Data: Pointer);
TKDT384DE_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT384DE_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT384DE_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT384DE_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT384DE_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT384DE_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT384DE_DyanmicStoreBuffer;
KDBuff: TKDT384DE_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT384DE_Node;
TestBuff: TKDT384DE_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT384DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT384DE_Node;
function GetData(const Index: NativeInt): PKDT384DE_Source;
public
RootNode: PKDT384DE_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT384DE_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT384DE_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT384DE_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT384DE_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT384DE_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT384DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT384DE_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT384DE_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT384DE_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT384DE_BuildProc); overload;
{ search }
function Search(const buff: TKDT384DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT384DE_Node; overload;
function Search(const buff: TKDT384DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT384DE_Node; overload;
function Search(const buff: TKDT384DE_Vec; var SearchedDistanceMin: Double): PKDT384DE_Node; overload;
function Search(const buff: TKDT384DE_Vec): PKDT384DE_Node; overload;
function SearchToken(const buff: TKDT384DE_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT384DE_DynamicVecBuffer; var OutBuff: TKDT384DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT384DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT384DE_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT384DE_Vec; overload;
class function Vec(const v: TKDT384DE_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT384DE_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT384DE_Source; const Data: Pointer);
class procedure Test;
end;
TKDT512DE = class(TCoreClassObject)
public type
// code split
TKDT512DE_Vec = array [0 .. KDT512DE_Axis - 1] of TKDT512DE_VecType;
PKDT512DE_Vec = ^TKDT512DE_Vec;
TKDT512DE_DynamicVecBuffer = array of TKDT512DE_Vec;
PKDT512DE_DynamicVecBuffer = ^TKDT512DE_DynamicVecBuffer;
TKDT512DE_Source = record
buff: TKDT512DE_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT512DE_Source = ^TKDT512DE_Source;
TKDT512DE_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT512DE_Source) - 1] of PKDT512DE_Source;
PKDT512DE_SourceBuffer = ^TKDT512DE_SourceBuffer;
TKDT512DE_DyanmicSourceBuffer = array of PKDT512DE_Source;
PKDT512DE_DyanmicSourceBuffer = ^TKDT512DE_DyanmicSourceBuffer;
TKDT512DE_DyanmicStoreBuffer = array of TKDT512DE_Source;
PKDT512DE_DyanmicStoreBuffer = ^TKDT512DE_DyanmicStoreBuffer;
PKDT512DE_Node = ^TKDT512DE_Node;
TKDT512DE_Node = record
Parent, Right, Left: PKDT512DE_Node;
Vec: PKDT512DE_Source;
end;
TKDT512DE_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT512DE_Source; const Data: Pointer);
TKDT512DE_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT512DE_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT512DE_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT512DE_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT512DE_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT512DE_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT512DE_DyanmicStoreBuffer;
KDBuff: TKDT512DE_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT512DE_Node;
TestBuff: TKDT512DE_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT512DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT512DE_Node;
function GetData(const Index: NativeInt): PKDT512DE_Source;
public
RootNode: PKDT512DE_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT512DE_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT512DE_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT512DE_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT512DE_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT512DE_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT512DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT512DE_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT512DE_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT512DE_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT512DE_BuildProc); overload;
{ search }
function Search(const buff: TKDT512DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT512DE_Node; overload;
function Search(const buff: TKDT512DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT512DE_Node; overload;
function Search(const buff: TKDT512DE_Vec; var SearchedDistanceMin: Double): PKDT512DE_Node; overload;
function Search(const buff: TKDT512DE_Vec): PKDT512DE_Node; overload;
function SearchToken(const buff: TKDT512DE_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT512DE_DynamicVecBuffer; var OutBuff: TKDT512DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT512DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT512DE_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT512DE_Vec; overload;
class function Vec(const v: TKDT512DE_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT512DE_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT512DE_Source; const Data: Pointer);
class procedure Test;
end;
TKDT800DE = class(TCoreClassObject)
public type
// code split
TKDT800DE_Vec = array [0 .. KDT800DE_Axis - 1] of TKDT800DE_VecType;
PKDT800DE_Vec = ^TKDT800DE_Vec;
TKDT800DE_DynamicVecBuffer = array of TKDT800DE_Vec;
PKDT800DE_DynamicVecBuffer = ^TKDT800DE_DynamicVecBuffer;
TKDT800DE_Source = record
buff: TKDT800DE_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT800DE_Source = ^TKDT800DE_Source;
TKDT800DE_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT800DE_Source) - 1] of PKDT800DE_Source;
PKDT800DE_SourceBuffer = ^TKDT800DE_SourceBuffer;
TKDT800DE_DyanmicSourceBuffer = array of PKDT800DE_Source;
PKDT800DE_DyanmicSourceBuffer = ^TKDT800DE_DyanmicSourceBuffer;
TKDT800DE_DyanmicStoreBuffer = array of TKDT800DE_Source;
PKDT800DE_DyanmicStoreBuffer = ^TKDT800DE_DyanmicStoreBuffer;
PKDT800DE_Node = ^TKDT800DE_Node;
TKDT800DE_Node = record
Parent, Right, Left: PKDT800DE_Node;
Vec: PKDT800DE_Source;
end;
TKDT800DE_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT800DE_Source; const Data: Pointer);
TKDT800DE_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT800DE_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT800DE_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT800DE_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT800DE_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT800DE_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT800DE_DyanmicStoreBuffer;
KDBuff: TKDT800DE_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT800DE_Node;
TestBuff: TKDT800DE_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT800DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT800DE_Node;
function GetData(const Index: NativeInt): PKDT800DE_Source;
public
RootNode: PKDT800DE_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT800DE_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT800DE_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT800DE_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT800DE_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT800DE_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT800DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT800DE_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT800DE_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT800DE_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT800DE_BuildProc); overload;
{ search }
function Search(const buff: TKDT800DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT800DE_Node; overload;
function Search(const buff: TKDT800DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT800DE_Node; overload;
function Search(const buff: TKDT800DE_Vec; var SearchedDistanceMin: Double): PKDT800DE_Node; overload;
function Search(const buff: TKDT800DE_Vec): PKDT800DE_Node; overload;
function SearchToken(const buff: TKDT800DE_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT800DE_DynamicVecBuffer; var OutBuff: TKDT800DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT800DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT800DE_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT800DE_Vec; overload;
class function Vec(const v: TKDT800DE_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT800DE_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT800DE_Source; const Data: Pointer);
class procedure Test;
end;
TKDT1024DE = class(TCoreClassObject)
public type
// code split
TKDT1024DE_Vec = array [0 .. KDT1024DE_Axis - 1] of TKDT1024DE_VecType;
PKDT1024DE_Vec = ^TKDT1024DE_Vec;
TKDT1024DE_DynamicVecBuffer = array of TKDT1024DE_Vec;
PKDT1024DE_DynamicVecBuffer = ^TKDT1024DE_DynamicVecBuffer;
TKDT1024DE_Source = record
buff: TKDT1024DE_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT1024DE_Source = ^TKDT1024DE_Source;
TKDT1024DE_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT1024DE_Source) - 1] of PKDT1024DE_Source;
PKDT1024DE_SourceBuffer = ^TKDT1024DE_SourceBuffer;
TKDT1024DE_DyanmicSourceBuffer = array of PKDT1024DE_Source;
PKDT1024DE_DyanmicSourceBuffer = ^TKDT1024DE_DyanmicSourceBuffer;
TKDT1024DE_DyanmicStoreBuffer = array of TKDT1024DE_Source;
PKDT1024DE_DyanmicStoreBuffer = ^TKDT1024DE_DyanmicStoreBuffer;
PKDT1024DE_Node = ^TKDT1024DE_Node;
TKDT1024DE_Node = record
Parent, Right, Left: PKDT1024DE_Node;
Vec: PKDT1024DE_Source;
end;
TKDT1024DE_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT1024DE_Source; const Data: Pointer);
TKDT1024DE_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT1024DE_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT1024DE_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT1024DE_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT1024DE_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT1024DE_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT1024DE_DyanmicStoreBuffer;
KDBuff: TKDT1024DE_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT1024DE_Node;
TestBuff: TKDT1024DE_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT1024DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT1024DE_Node;
function GetData(const Index: NativeInt): PKDT1024DE_Source;
public
RootNode: PKDT1024DE_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT1024DE_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT1024DE_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1024DE_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1024DE_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1024DE_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT1024DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT1024DE_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1024DE_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1024DE_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1024DE_BuildProc); overload;
{ search }
function Search(const buff: TKDT1024DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT1024DE_Node; overload;
function Search(const buff: TKDT1024DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT1024DE_Node; overload;
function Search(const buff: TKDT1024DE_Vec; var SearchedDistanceMin: Double): PKDT1024DE_Node; overload;
function Search(const buff: TKDT1024DE_Vec): PKDT1024DE_Node; overload;
function SearchToken(const buff: TKDT1024DE_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT1024DE_DynamicVecBuffer; var OutBuff: TKDT1024DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT1024DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT1024DE_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT1024DE_Vec; overload;
class function Vec(const v: TKDT1024DE_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT1024DE_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT1024DE_Source; const Data: Pointer);
class procedure Test;
end;
procedure Test_All;
implementation
uses
TextParsing, MemoryStream64, DoStatusIO;
const
SaveToken = $22;
function TKDT1DE.InternalBuildKdTree(const KDSourceBufferPtr: PKDT1DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT1DE_Node;
function SortCompare(const p1, p2: PKDT1DE_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT1DE_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT1DE_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT1DE_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT1DE_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT1DE.GetData(const Index: NativeInt): PKDT1DE_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT1DE.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT1DE.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT1DE.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT1DE_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT1DE.StoreBuffPtr: PKDT1DE_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT1DE.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1DE_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT1DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT1DE.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1DE_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT1DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT1DE.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1DE_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT1DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT1DE.BuildKDTreeWithCluster(const inBuff: TKDT1DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT1DE_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT1DE_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT1DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT1DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT1DE.BuildKDTreeWithCluster(const inBuff: TKDT1DE_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT1DE.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1DE_BuildCall);
var
TempStoreBuff: TKDT1DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT1DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT1DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT1DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT1DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT1DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT1DE.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1DE_BuildMethod);
var
TempStoreBuff: TKDT1DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT1DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT1DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT1DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT1DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT1DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT1DE.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1DE_BuildProc);
var
TempStoreBuff: TKDT1DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT1DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT1DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT1DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT1DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT1DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT1DE.Search(const buff: TKDT1DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT1DE_Node;
var
NearestNeighbour: PKDT1DE_Node;
function FindParentNode(const buffPtr: PKDT1DE_Vec; NodePtr: PKDT1DE_Node): PKDT1DE_Node;
var
Next: PKDT1DE_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT1DE_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT1DE_Node; const buffPtr: PKDT1DE_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT1DE_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT1DE_Vec; const p1, p2: PKDT1DE_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT1DE_Vec);
var
i, j: NativeInt;
p, t: PKDT1DE_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT1DE_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT1DE_Node(NearestNodes[0]);
end;
end;
function TKDT1DE.Search(const buff: TKDT1DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT1DE_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT1DE.Search(const buff: TKDT1DE_Vec; var SearchedDistanceMin: Double): PKDT1DE_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT1DE.Search(const buff: TKDT1DE_Vec): PKDT1DE_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT1DE.SearchToken(const buff: TKDT1DE_Vec): TPascalString;
var
p: PKDT1DE_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT1DE.Search(const inBuff: TKDT1DE_DynamicVecBuffer; var OutBuff: TKDT1DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT1DE_DynamicVecBuffer;
outBuffPtr: PKDT1DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT1DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT1DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT1DE_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT1DE.Search(const inBuff: TKDT1DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT1DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT1DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT1DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT1DE_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT1DE.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT1DE_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT1DE_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT1DE.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT1DE_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT1DE_Vec)) <> SizeOf(TKDT1DE_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT1DE.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT1DE.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT1DE.PrintNodeTree(const NodePtr: PKDT1DE_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT1DE_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT1DE.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT1DE.Vec(const s: SystemString): TKDT1DE_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT1DE_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT1DE_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT1DE.Vec(const v: TKDT1DE_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT1DE_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT1DE.Distance(const v1, v2: TKDT1DE_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT1DE_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT1DE.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT1DE_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT1DE.Test;
var
TKDT1DE_Test: TKDT1DE;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT1DE_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT1DE_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT1DE_Test := TKDT1DE.Create;
n.Append('...');
SetLength(TKDT1DE_Test.TestBuff, 1000);
for i := 0 to length(TKDT1DE_Test.TestBuff) - 1 do
for j := 0 to KDT1DE_Axis - 1 do
TKDT1DE_Test.TestBuff[i][j] := i * KDT1DE_Axis + j;
{$IFDEF FPC}
TKDT1DE_Test.BuildKDTreeM(length(TKDT1DE_Test.TestBuff), nil, @TKDT1DE_Test.Test_BuildM);
{$ELSE FPC}
TKDT1DE_Test.BuildKDTreeM(length(TKDT1DE_Test.TestBuff), nil, TKDT1DE_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT1DE_Test.SaveToStream(m64);
m64.Position := 0;
TKDT1DE_Test.LoadFromStream(m64);
for i := 0 to length(TKDT1DE_Test.TestBuff) - 1 do
begin
p := TKDT1DE_Test.Search(TKDT1DE_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT1DE_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT1DE_Test.TestBuff));
TKDT1DE_Test.Search(TKDT1DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT1DE_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT1DE_Test.Clear;
{ kMean test }
TKDT1DE_Test.BuildKDTreeWithCluster(TKDT1DE_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT1DE_Test.Search(TKDT1DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT1DE_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT1DE_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT1DE_Test);
DoStatus(n);
n := '';
end;
function TKDT2DE.InternalBuildKdTree(const KDSourceBufferPtr: PKDT2DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT2DE_Node;
function SortCompare(const p1, p2: PKDT2DE_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT2DE_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT2DE_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT2DE_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT2DE_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT2DE.GetData(const Index: NativeInt): PKDT2DE_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT2DE.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT2DE.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT2DE.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT2DE_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT2DE.StoreBuffPtr: PKDT2DE_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT2DE.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT2DE_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT2DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT2DE.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT2DE_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT2DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT2DE.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT2DE_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT2DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT2DE.BuildKDTreeWithCluster(const inBuff: TKDT2DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT2DE_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT2DE_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT2DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT2DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT2DE.BuildKDTreeWithCluster(const inBuff: TKDT2DE_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT2DE.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT2DE_BuildCall);
var
TempStoreBuff: TKDT2DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT2DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT2DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT2DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT2DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT2DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT2DE.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT2DE_BuildMethod);
var
TempStoreBuff: TKDT2DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT2DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT2DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT2DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT2DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT2DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT2DE.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT2DE_BuildProc);
var
TempStoreBuff: TKDT2DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT2DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT2DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT2DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT2DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT2DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT2DE.Search(const buff: TKDT2DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT2DE_Node;
var
NearestNeighbour: PKDT2DE_Node;
function FindParentNode(const buffPtr: PKDT2DE_Vec; NodePtr: PKDT2DE_Node): PKDT2DE_Node;
var
Next: PKDT2DE_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT2DE_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT2DE_Node; const buffPtr: PKDT2DE_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT2DE_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT2DE_Vec; const p1, p2: PKDT2DE_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT2DE_Vec);
var
i, j: NativeInt;
p, t: PKDT2DE_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT2DE_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT2DE_Node(NearestNodes[0]);
end;
end;
function TKDT2DE.Search(const buff: TKDT2DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT2DE_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT2DE.Search(const buff: TKDT2DE_Vec; var SearchedDistanceMin: Double): PKDT2DE_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT2DE.Search(const buff: TKDT2DE_Vec): PKDT2DE_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT2DE.SearchToken(const buff: TKDT2DE_Vec): TPascalString;
var
p: PKDT2DE_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT2DE.Search(const inBuff: TKDT2DE_DynamicVecBuffer; var OutBuff: TKDT2DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT2DE_DynamicVecBuffer;
outBuffPtr: PKDT2DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT2DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT2DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT2DE_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT2DE.Search(const inBuff: TKDT2DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT2DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT2DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT2DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT2DE_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT2DE.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT2DE_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT2DE_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT2DE.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT2DE_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT2DE_Vec)) <> SizeOf(TKDT2DE_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT2DE.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT2DE.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT2DE.PrintNodeTree(const NodePtr: PKDT2DE_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT2DE_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT2DE.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT2DE.Vec(const s: SystemString): TKDT2DE_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT2DE_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT2DE_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT2DE.Vec(const v: TKDT2DE_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT2DE_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT2DE.Distance(const v1, v2: TKDT2DE_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT2DE_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT2DE.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT2DE_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT2DE.Test;
var
TKDT2DE_Test: TKDT2DE;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT2DE_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT2DE_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT2DE_Test := TKDT2DE.Create;
n.Append('...');
SetLength(TKDT2DE_Test.TestBuff, 1000);
for i := 0 to length(TKDT2DE_Test.TestBuff) - 1 do
for j := 0 to KDT2DE_Axis - 1 do
TKDT2DE_Test.TestBuff[i][j] := i * KDT2DE_Axis + j;
{$IFDEF FPC}
TKDT2DE_Test.BuildKDTreeM(length(TKDT2DE_Test.TestBuff), nil, @TKDT2DE_Test.Test_BuildM);
{$ELSE FPC}
TKDT2DE_Test.BuildKDTreeM(length(TKDT2DE_Test.TestBuff), nil, TKDT2DE_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT2DE_Test.SaveToStream(m64);
m64.Position := 0;
TKDT2DE_Test.LoadFromStream(m64);
for i := 0 to length(TKDT2DE_Test.TestBuff) - 1 do
begin
p := TKDT2DE_Test.Search(TKDT2DE_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT2DE_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT2DE_Test.TestBuff));
TKDT2DE_Test.Search(TKDT2DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT2DE_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT2DE_Test.Clear;
{ kMean test }
TKDT2DE_Test.BuildKDTreeWithCluster(TKDT2DE_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT2DE_Test.Search(TKDT2DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT2DE_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT2DE_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT2DE_Test);
DoStatus(n);
n := '';
end;
function TKDT3DE.InternalBuildKdTree(const KDSourceBufferPtr: PKDT3DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT3DE_Node;
function SortCompare(const p1, p2: PKDT3DE_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT3DE_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT3DE_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT3DE_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT3DE_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT3DE.GetData(const Index: NativeInt): PKDT3DE_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT3DE.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT3DE.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT3DE.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT3DE_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT3DE.StoreBuffPtr: PKDT3DE_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT3DE.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT3DE_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT3DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT3DE.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT3DE_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT3DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT3DE.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT3DE_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT3DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT3DE.BuildKDTreeWithCluster(const inBuff: TKDT3DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT3DE_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT3DE_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT3DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT3DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT3DE.BuildKDTreeWithCluster(const inBuff: TKDT3DE_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT3DE.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT3DE_BuildCall);
var
TempStoreBuff: TKDT3DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT3DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT3DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT3DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT3DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT3DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT3DE.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT3DE_BuildMethod);
var
TempStoreBuff: TKDT3DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT3DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT3DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT3DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT3DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT3DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT3DE.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT3DE_BuildProc);
var
TempStoreBuff: TKDT3DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT3DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT3DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT3DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT3DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT3DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT3DE.Search(const buff: TKDT3DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT3DE_Node;
var
NearestNeighbour: PKDT3DE_Node;
function FindParentNode(const buffPtr: PKDT3DE_Vec; NodePtr: PKDT3DE_Node): PKDT3DE_Node;
var
Next: PKDT3DE_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT3DE_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT3DE_Node; const buffPtr: PKDT3DE_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT3DE_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT3DE_Vec; const p1, p2: PKDT3DE_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT3DE_Vec);
var
i, j: NativeInt;
p, t: PKDT3DE_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT3DE_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT3DE_Node(NearestNodes[0]);
end;
end;
function TKDT3DE.Search(const buff: TKDT3DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT3DE_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT3DE.Search(const buff: TKDT3DE_Vec; var SearchedDistanceMin: Double): PKDT3DE_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT3DE.Search(const buff: TKDT3DE_Vec): PKDT3DE_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT3DE.SearchToken(const buff: TKDT3DE_Vec): TPascalString;
var
p: PKDT3DE_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT3DE.Search(const inBuff: TKDT3DE_DynamicVecBuffer; var OutBuff: TKDT3DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT3DE_DynamicVecBuffer;
outBuffPtr: PKDT3DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT3DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT3DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT3DE_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT3DE.Search(const inBuff: TKDT3DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT3DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT3DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT3DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT3DE_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT3DE.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT3DE_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT3DE_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT3DE.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT3DE_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT3DE_Vec)) <> SizeOf(TKDT3DE_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT3DE.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT3DE.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT3DE.PrintNodeTree(const NodePtr: PKDT3DE_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT3DE_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT3DE.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT3DE.Vec(const s: SystemString): TKDT3DE_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT3DE_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT3DE_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT3DE.Vec(const v: TKDT3DE_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT3DE_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT3DE.Distance(const v1, v2: TKDT3DE_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT3DE_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT3DE.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT3DE_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT3DE.Test;
var
TKDT3DE_Test: TKDT3DE;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT3DE_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT3DE_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT3DE_Test := TKDT3DE.Create;
n.Append('...');
SetLength(TKDT3DE_Test.TestBuff, 1000);
for i := 0 to length(TKDT3DE_Test.TestBuff) - 1 do
for j := 0 to KDT3DE_Axis - 1 do
TKDT3DE_Test.TestBuff[i][j] := i * KDT3DE_Axis + j;
{$IFDEF FPC}
TKDT3DE_Test.BuildKDTreeM(length(TKDT3DE_Test.TestBuff), nil, @TKDT3DE_Test.Test_BuildM);
{$ELSE FPC}
TKDT3DE_Test.BuildKDTreeM(length(TKDT3DE_Test.TestBuff), nil, TKDT3DE_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT3DE_Test.SaveToStream(m64);
m64.Position := 0;
TKDT3DE_Test.LoadFromStream(m64);
for i := 0 to length(TKDT3DE_Test.TestBuff) - 1 do
begin
p := TKDT3DE_Test.Search(TKDT3DE_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT3DE_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT3DE_Test.TestBuff));
TKDT3DE_Test.Search(TKDT3DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT3DE_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT3DE_Test.Clear;
{ kMean test }
TKDT3DE_Test.BuildKDTreeWithCluster(TKDT3DE_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT3DE_Test.Search(TKDT3DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT3DE_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT3DE_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT3DE_Test);
DoStatus(n);
n := '';
end;
function TKDT4DE.InternalBuildKdTree(const KDSourceBufferPtr: PKDT4DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT4DE_Node;
function SortCompare(const p1, p2: PKDT4DE_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT4DE_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT4DE_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT4DE_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT4DE_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT4DE.GetData(const Index: NativeInt): PKDT4DE_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT4DE.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT4DE.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT4DE.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT4DE_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT4DE.StoreBuffPtr: PKDT4DE_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT4DE.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT4DE_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT4DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT4DE.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT4DE_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT4DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT4DE.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT4DE_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT4DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT4DE.BuildKDTreeWithCluster(const inBuff: TKDT4DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT4DE_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT4DE_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT4DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT4DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT4DE.BuildKDTreeWithCluster(const inBuff: TKDT4DE_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT4DE.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT4DE_BuildCall);
var
TempStoreBuff: TKDT4DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT4DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT4DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT4DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT4DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT4DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT4DE.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT4DE_BuildMethod);
var
TempStoreBuff: TKDT4DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT4DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT4DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT4DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT4DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT4DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT4DE.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT4DE_BuildProc);
var
TempStoreBuff: TKDT4DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT4DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT4DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT4DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT4DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT4DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT4DE.Search(const buff: TKDT4DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT4DE_Node;
var
NearestNeighbour: PKDT4DE_Node;
function FindParentNode(const buffPtr: PKDT4DE_Vec; NodePtr: PKDT4DE_Node): PKDT4DE_Node;
var
Next: PKDT4DE_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT4DE_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT4DE_Node; const buffPtr: PKDT4DE_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT4DE_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT4DE_Vec; const p1, p2: PKDT4DE_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT4DE_Vec);
var
i, j: NativeInt;
p, t: PKDT4DE_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT4DE_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT4DE_Node(NearestNodes[0]);
end;
end;
function TKDT4DE.Search(const buff: TKDT4DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT4DE_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT4DE.Search(const buff: TKDT4DE_Vec; var SearchedDistanceMin: Double): PKDT4DE_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT4DE.Search(const buff: TKDT4DE_Vec): PKDT4DE_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT4DE.SearchToken(const buff: TKDT4DE_Vec): TPascalString;
var
p: PKDT4DE_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT4DE.Search(const inBuff: TKDT4DE_DynamicVecBuffer; var OutBuff: TKDT4DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT4DE_DynamicVecBuffer;
outBuffPtr: PKDT4DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT4DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT4DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT4DE_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT4DE.Search(const inBuff: TKDT4DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT4DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT4DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT4DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT4DE_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT4DE.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT4DE_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT4DE_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT4DE.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT4DE_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT4DE_Vec)) <> SizeOf(TKDT4DE_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT4DE.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT4DE.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT4DE.PrintNodeTree(const NodePtr: PKDT4DE_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT4DE_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT4DE.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT4DE.Vec(const s: SystemString): TKDT4DE_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT4DE_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT4DE_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT4DE.Vec(const v: TKDT4DE_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT4DE_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT4DE.Distance(const v1, v2: TKDT4DE_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT4DE_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT4DE.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT4DE_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT4DE.Test;
var
TKDT4DE_Test: TKDT4DE;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT4DE_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT4DE_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT4DE_Test := TKDT4DE.Create;
n.Append('...');
SetLength(TKDT4DE_Test.TestBuff, 1000);
for i := 0 to length(TKDT4DE_Test.TestBuff) - 1 do
for j := 0 to KDT4DE_Axis - 1 do
TKDT4DE_Test.TestBuff[i][j] := i * KDT4DE_Axis + j;
{$IFDEF FPC}
TKDT4DE_Test.BuildKDTreeM(length(TKDT4DE_Test.TestBuff), nil, @TKDT4DE_Test.Test_BuildM);
{$ELSE FPC}
TKDT4DE_Test.BuildKDTreeM(length(TKDT4DE_Test.TestBuff), nil, TKDT4DE_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT4DE_Test.SaveToStream(m64);
m64.Position := 0;
TKDT4DE_Test.LoadFromStream(m64);
for i := 0 to length(TKDT4DE_Test.TestBuff) - 1 do
begin
p := TKDT4DE_Test.Search(TKDT4DE_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT4DE_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT4DE_Test.TestBuff));
TKDT4DE_Test.Search(TKDT4DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT4DE_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT4DE_Test.Clear;
{ kMean test }
TKDT4DE_Test.BuildKDTreeWithCluster(TKDT4DE_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT4DE_Test.Search(TKDT4DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT4DE_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT4DE_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT4DE_Test);
DoStatus(n);
n := '';
end;
function TKDT5DE.InternalBuildKdTree(const KDSourceBufferPtr: PKDT5DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT5DE_Node;
function SortCompare(const p1, p2: PKDT5DE_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT5DE_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT5DE_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT5DE_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT5DE_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT5DE.GetData(const Index: NativeInt): PKDT5DE_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT5DE.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT5DE.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT5DE.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT5DE_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT5DE.StoreBuffPtr: PKDT5DE_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT5DE.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT5DE_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT5DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT5DE.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT5DE_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT5DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT5DE.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT5DE_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT5DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT5DE.BuildKDTreeWithCluster(const inBuff: TKDT5DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT5DE_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT5DE_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT5DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT5DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT5DE.BuildKDTreeWithCluster(const inBuff: TKDT5DE_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT5DE.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT5DE_BuildCall);
var
TempStoreBuff: TKDT5DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT5DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT5DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT5DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT5DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT5DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT5DE.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT5DE_BuildMethod);
var
TempStoreBuff: TKDT5DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT5DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT5DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT5DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT5DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT5DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT5DE.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT5DE_BuildProc);
var
TempStoreBuff: TKDT5DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT5DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT5DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT5DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT5DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT5DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT5DE.Search(const buff: TKDT5DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT5DE_Node;
var
NearestNeighbour: PKDT5DE_Node;
function FindParentNode(const buffPtr: PKDT5DE_Vec; NodePtr: PKDT5DE_Node): PKDT5DE_Node;
var
Next: PKDT5DE_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT5DE_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT5DE_Node; const buffPtr: PKDT5DE_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT5DE_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT5DE_Vec; const p1, p2: PKDT5DE_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT5DE_Vec);
var
i, j: NativeInt;
p, t: PKDT5DE_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT5DE_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT5DE_Node(NearestNodes[0]);
end;
end;
function TKDT5DE.Search(const buff: TKDT5DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT5DE_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT5DE.Search(const buff: TKDT5DE_Vec; var SearchedDistanceMin: Double): PKDT5DE_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT5DE.Search(const buff: TKDT5DE_Vec): PKDT5DE_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT5DE.SearchToken(const buff: TKDT5DE_Vec): TPascalString;
var
p: PKDT5DE_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT5DE.Search(const inBuff: TKDT5DE_DynamicVecBuffer; var OutBuff: TKDT5DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT5DE_DynamicVecBuffer;
outBuffPtr: PKDT5DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT5DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT5DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT5DE_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT5DE.Search(const inBuff: TKDT5DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT5DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT5DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT5DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT5DE_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT5DE.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT5DE_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT5DE_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT5DE.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT5DE_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT5DE_Vec)) <> SizeOf(TKDT5DE_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT5DE.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT5DE.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT5DE.PrintNodeTree(const NodePtr: PKDT5DE_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT5DE_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT5DE.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT5DE.Vec(const s: SystemString): TKDT5DE_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT5DE_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT5DE_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT5DE.Vec(const v: TKDT5DE_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT5DE_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT5DE.Distance(const v1, v2: TKDT5DE_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT5DE_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT5DE.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT5DE_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT5DE.Test;
var
TKDT5DE_Test: TKDT5DE;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT5DE_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT5DE_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT5DE_Test := TKDT5DE.Create;
n.Append('...');
SetLength(TKDT5DE_Test.TestBuff, 1000);
for i := 0 to length(TKDT5DE_Test.TestBuff) - 1 do
for j := 0 to KDT5DE_Axis - 1 do
TKDT5DE_Test.TestBuff[i][j] := i * KDT5DE_Axis + j;
{$IFDEF FPC}
TKDT5DE_Test.BuildKDTreeM(length(TKDT5DE_Test.TestBuff), nil, @TKDT5DE_Test.Test_BuildM);
{$ELSE FPC}
TKDT5DE_Test.BuildKDTreeM(length(TKDT5DE_Test.TestBuff), nil, TKDT5DE_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT5DE_Test.SaveToStream(m64);
m64.Position := 0;
TKDT5DE_Test.LoadFromStream(m64);
for i := 0 to length(TKDT5DE_Test.TestBuff) - 1 do
begin
p := TKDT5DE_Test.Search(TKDT5DE_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT5DE_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT5DE_Test.TestBuff));
TKDT5DE_Test.Search(TKDT5DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT5DE_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT5DE_Test.Clear;
{ kMean test }
TKDT5DE_Test.BuildKDTreeWithCluster(TKDT5DE_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT5DE_Test.Search(TKDT5DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT5DE_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT5DE_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT5DE_Test);
DoStatus(n);
n := '';
end;
function TKDT6DE.InternalBuildKdTree(const KDSourceBufferPtr: PKDT6DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT6DE_Node;
function SortCompare(const p1, p2: PKDT6DE_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT6DE_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT6DE_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT6DE_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT6DE_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT6DE.GetData(const Index: NativeInt): PKDT6DE_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT6DE.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT6DE.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT6DE.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT6DE_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT6DE.StoreBuffPtr: PKDT6DE_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT6DE.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT6DE_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT6DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT6DE.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT6DE_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT6DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT6DE.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT6DE_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT6DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT6DE.BuildKDTreeWithCluster(const inBuff: TKDT6DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT6DE_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT6DE_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT6DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT6DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT6DE.BuildKDTreeWithCluster(const inBuff: TKDT6DE_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT6DE.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT6DE_BuildCall);
var
TempStoreBuff: TKDT6DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT6DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT6DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT6DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT6DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT6DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT6DE.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT6DE_BuildMethod);
var
TempStoreBuff: TKDT6DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT6DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT6DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT6DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT6DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT6DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT6DE.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT6DE_BuildProc);
var
TempStoreBuff: TKDT6DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT6DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT6DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT6DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT6DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT6DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT6DE.Search(const buff: TKDT6DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT6DE_Node;
var
NearestNeighbour: PKDT6DE_Node;
function FindParentNode(const buffPtr: PKDT6DE_Vec; NodePtr: PKDT6DE_Node): PKDT6DE_Node;
var
Next: PKDT6DE_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT6DE_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT6DE_Node; const buffPtr: PKDT6DE_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT6DE_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT6DE_Vec; const p1, p2: PKDT6DE_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT6DE_Vec);
var
i, j: NativeInt;
p, t: PKDT6DE_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT6DE_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT6DE_Node(NearestNodes[0]);
end;
end;
function TKDT6DE.Search(const buff: TKDT6DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT6DE_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT6DE.Search(const buff: TKDT6DE_Vec; var SearchedDistanceMin: Double): PKDT6DE_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT6DE.Search(const buff: TKDT6DE_Vec): PKDT6DE_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT6DE.SearchToken(const buff: TKDT6DE_Vec): TPascalString;
var
p: PKDT6DE_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT6DE.Search(const inBuff: TKDT6DE_DynamicVecBuffer; var OutBuff: TKDT6DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT6DE_DynamicVecBuffer;
outBuffPtr: PKDT6DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT6DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT6DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT6DE_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT6DE.Search(const inBuff: TKDT6DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT6DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT6DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT6DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT6DE_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT6DE.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT6DE_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT6DE_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT6DE.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT6DE_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT6DE_Vec)) <> SizeOf(TKDT6DE_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT6DE.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT6DE.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT6DE.PrintNodeTree(const NodePtr: PKDT6DE_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT6DE_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT6DE.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT6DE.Vec(const s: SystemString): TKDT6DE_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT6DE_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT6DE_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT6DE.Vec(const v: TKDT6DE_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT6DE_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT6DE.Distance(const v1, v2: TKDT6DE_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT6DE_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT6DE.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT6DE_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT6DE.Test;
var
TKDT6DE_Test: TKDT6DE;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT6DE_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT6DE_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT6DE_Test := TKDT6DE.Create;
n.Append('...');
SetLength(TKDT6DE_Test.TestBuff, 1000);
for i := 0 to length(TKDT6DE_Test.TestBuff) - 1 do
for j := 0 to KDT6DE_Axis - 1 do
TKDT6DE_Test.TestBuff[i][j] := i * KDT6DE_Axis + j;
{$IFDEF FPC}
TKDT6DE_Test.BuildKDTreeM(length(TKDT6DE_Test.TestBuff), nil, @TKDT6DE_Test.Test_BuildM);
{$ELSE FPC}
TKDT6DE_Test.BuildKDTreeM(length(TKDT6DE_Test.TestBuff), nil, TKDT6DE_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT6DE_Test.SaveToStream(m64);
m64.Position := 0;
TKDT6DE_Test.LoadFromStream(m64);
for i := 0 to length(TKDT6DE_Test.TestBuff) - 1 do
begin
p := TKDT6DE_Test.Search(TKDT6DE_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT6DE_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT6DE_Test.TestBuff));
TKDT6DE_Test.Search(TKDT6DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT6DE_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT6DE_Test.Clear;
{ kMean test }
TKDT6DE_Test.BuildKDTreeWithCluster(TKDT6DE_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT6DE_Test.Search(TKDT6DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT6DE_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT6DE_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT6DE_Test);
DoStatus(n);
n := '';
end;
function TKDT7DE.InternalBuildKdTree(const KDSourceBufferPtr: PKDT7DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT7DE_Node;
function SortCompare(const p1, p2: PKDT7DE_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT7DE_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT7DE_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT7DE_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT7DE_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT7DE.GetData(const Index: NativeInt): PKDT7DE_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT7DE.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT7DE.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT7DE.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT7DE_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT7DE.StoreBuffPtr: PKDT7DE_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT7DE.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT7DE_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT7DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT7DE.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT7DE_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT7DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT7DE.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT7DE_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT7DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT7DE.BuildKDTreeWithCluster(const inBuff: TKDT7DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT7DE_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT7DE_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT7DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT7DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT7DE.BuildKDTreeWithCluster(const inBuff: TKDT7DE_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT7DE.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT7DE_BuildCall);
var
TempStoreBuff: TKDT7DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT7DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT7DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT7DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT7DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT7DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT7DE.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT7DE_BuildMethod);
var
TempStoreBuff: TKDT7DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT7DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT7DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT7DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT7DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT7DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT7DE.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT7DE_BuildProc);
var
TempStoreBuff: TKDT7DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT7DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT7DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT7DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT7DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT7DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT7DE.Search(const buff: TKDT7DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT7DE_Node;
var
NearestNeighbour: PKDT7DE_Node;
function FindParentNode(const buffPtr: PKDT7DE_Vec; NodePtr: PKDT7DE_Node): PKDT7DE_Node;
var
Next: PKDT7DE_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT7DE_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT7DE_Node; const buffPtr: PKDT7DE_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT7DE_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT7DE_Vec; const p1, p2: PKDT7DE_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT7DE_Vec);
var
i, j: NativeInt;
p, t: PKDT7DE_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT7DE_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT7DE_Node(NearestNodes[0]);
end;
end;
function TKDT7DE.Search(const buff: TKDT7DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT7DE_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT7DE.Search(const buff: TKDT7DE_Vec; var SearchedDistanceMin: Double): PKDT7DE_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT7DE.Search(const buff: TKDT7DE_Vec): PKDT7DE_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT7DE.SearchToken(const buff: TKDT7DE_Vec): TPascalString;
var
p: PKDT7DE_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT7DE.Search(const inBuff: TKDT7DE_DynamicVecBuffer; var OutBuff: TKDT7DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT7DE_DynamicVecBuffer;
outBuffPtr: PKDT7DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT7DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT7DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT7DE_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT7DE.Search(const inBuff: TKDT7DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT7DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT7DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT7DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT7DE_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT7DE.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT7DE_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT7DE_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT7DE.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT7DE_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT7DE_Vec)) <> SizeOf(TKDT7DE_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT7DE.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT7DE.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT7DE.PrintNodeTree(const NodePtr: PKDT7DE_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT7DE_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT7DE.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT7DE.Vec(const s: SystemString): TKDT7DE_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT7DE_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT7DE_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT7DE.Vec(const v: TKDT7DE_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT7DE_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT7DE.Distance(const v1, v2: TKDT7DE_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT7DE_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT7DE.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT7DE_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT7DE.Test;
var
TKDT7DE_Test: TKDT7DE;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT7DE_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT7DE_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT7DE_Test := TKDT7DE.Create;
n.Append('...');
SetLength(TKDT7DE_Test.TestBuff, 1000);
for i := 0 to length(TKDT7DE_Test.TestBuff) - 1 do
for j := 0 to KDT7DE_Axis - 1 do
TKDT7DE_Test.TestBuff[i][j] := i * KDT7DE_Axis + j;
{$IFDEF FPC}
TKDT7DE_Test.BuildKDTreeM(length(TKDT7DE_Test.TestBuff), nil, @TKDT7DE_Test.Test_BuildM);
{$ELSE FPC}
TKDT7DE_Test.BuildKDTreeM(length(TKDT7DE_Test.TestBuff), nil, TKDT7DE_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT7DE_Test.SaveToStream(m64);
m64.Position := 0;
TKDT7DE_Test.LoadFromStream(m64);
for i := 0 to length(TKDT7DE_Test.TestBuff) - 1 do
begin
p := TKDT7DE_Test.Search(TKDT7DE_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT7DE_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT7DE_Test.TestBuff));
TKDT7DE_Test.Search(TKDT7DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT7DE_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT7DE_Test.Clear;
{ kMean test }
TKDT7DE_Test.BuildKDTreeWithCluster(TKDT7DE_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT7DE_Test.Search(TKDT7DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT7DE_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT7DE_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT7DE_Test);
DoStatus(n);
n := '';
end;
function TKDT8DE.InternalBuildKdTree(const KDSourceBufferPtr: PKDT8DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT8DE_Node;
function SortCompare(const p1, p2: PKDT8DE_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT8DE_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT8DE_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT8DE_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT8DE_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT8DE.GetData(const Index: NativeInt): PKDT8DE_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT8DE.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT8DE.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT8DE.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT8DE_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT8DE.StoreBuffPtr: PKDT8DE_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT8DE.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT8DE_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT8DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT8DE.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT8DE_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT8DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT8DE.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT8DE_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT8DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT8DE.BuildKDTreeWithCluster(const inBuff: TKDT8DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT8DE_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT8DE_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT8DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT8DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT8DE.BuildKDTreeWithCluster(const inBuff: TKDT8DE_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT8DE.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT8DE_BuildCall);
var
TempStoreBuff: TKDT8DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT8DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT8DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT8DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT8DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT8DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT8DE.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT8DE_BuildMethod);
var
TempStoreBuff: TKDT8DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT8DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT8DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT8DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT8DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT8DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT8DE.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT8DE_BuildProc);
var
TempStoreBuff: TKDT8DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT8DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT8DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT8DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT8DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT8DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT8DE.Search(const buff: TKDT8DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT8DE_Node;
var
NearestNeighbour: PKDT8DE_Node;
function FindParentNode(const buffPtr: PKDT8DE_Vec; NodePtr: PKDT8DE_Node): PKDT8DE_Node;
var
Next: PKDT8DE_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT8DE_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT8DE_Node; const buffPtr: PKDT8DE_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT8DE_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT8DE_Vec; const p1, p2: PKDT8DE_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT8DE_Vec);
var
i, j: NativeInt;
p, t: PKDT8DE_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT8DE_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT8DE_Node(NearestNodes[0]);
end;
end;
function TKDT8DE.Search(const buff: TKDT8DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT8DE_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT8DE.Search(const buff: TKDT8DE_Vec; var SearchedDistanceMin: Double): PKDT8DE_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT8DE.Search(const buff: TKDT8DE_Vec): PKDT8DE_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT8DE.SearchToken(const buff: TKDT8DE_Vec): TPascalString;
var
p: PKDT8DE_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT8DE.Search(const inBuff: TKDT8DE_DynamicVecBuffer; var OutBuff: TKDT8DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT8DE_DynamicVecBuffer;
outBuffPtr: PKDT8DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT8DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT8DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT8DE_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT8DE.Search(const inBuff: TKDT8DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT8DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT8DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT8DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT8DE_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT8DE.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT8DE_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT8DE_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT8DE.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT8DE_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT8DE_Vec)) <> SizeOf(TKDT8DE_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT8DE.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT8DE.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT8DE.PrintNodeTree(const NodePtr: PKDT8DE_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT8DE_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT8DE.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT8DE.Vec(const s: SystemString): TKDT8DE_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT8DE_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT8DE_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT8DE.Vec(const v: TKDT8DE_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT8DE_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT8DE.Distance(const v1, v2: TKDT8DE_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT8DE_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT8DE.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT8DE_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT8DE.Test;
var
TKDT8DE_Test: TKDT8DE;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT8DE_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT8DE_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT8DE_Test := TKDT8DE.Create;
n.Append('...');
SetLength(TKDT8DE_Test.TestBuff, 1000);
for i := 0 to length(TKDT8DE_Test.TestBuff) - 1 do
for j := 0 to KDT8DE_Axis - 1 do
TKDT8DE_Test.TestBuff[i][j] := i * KDT8DE_Axis + j;
{$IFDEF FPC}
TKDT8DE_Test.BuildKDTreeM(length(TKDT8DE_Test.TestBuff), nil, @TKDT8DE_Test.Test_BuildM);
{$ELSE FPC}
TKDT8DE_Test.BuildKDTreeM(length(TKDT8DE_Test.TestBuff), nil, TKDT8DE_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT8DE_Test.SaveToStream(m64);
m64.Position := 0;
TKDT8DE_Test.LoadFromStream(m64);
for i := 0 to length(TKDT8DE_Test.TestBuff) - 1 do
begin
p := TKDT8DE_Test.Search(TKDT8DE_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT8DE_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT8DE_Test.TestBuff));
TKDT8DE_Test.Search(TKDT8DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT8DE_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT8DE_Test.Clear;
{ kMean test }
TKDT8DE_Test.BuildKDTreeWithCluster(TKDT8DE_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT8DE_Test.Search(TKDT8DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT8DE_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT8DE_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT8DE_Test);
DoStatus(n);
n := '';
end;
function TKDT9DE.InternalBuildKdTree(const KDSourceBufferPtr: PKDT9DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT9DE_Node;
function SortCompare(const p1, p2: PKDT9DE_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT9DE_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT9DE_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT9DE_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT9DE_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT9DE.GetData(const Index: NativeInt): PKDT9DE_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT9DE.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT9DE.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT9DE.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT9DE_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT9DE.StoreBuffPtr: PKDT9DE_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT9DE.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT9DE_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT9DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT9DE.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT9DE_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT9DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT9DE.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT9DE_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT9DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT9DE.BuildKDTreeWithCluster(const inBuff: TKDT9DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT9DE_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT9DE_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT9DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT9DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT9DE.BuildKDTreeWithCluster(const inBuff: TKDT9DE_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT9DE.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT9DE_BuildCall);
var
TempStoreBuff: TKDT9DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT9DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT9DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT9DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT9DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT9DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT9DE.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT9DE_BuildMethod);
var
TempStoreBuff: TKDT9DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT9DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT9DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT9DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT9DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT9DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT9DE.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT9DE_BuildProc);
var
TempStoreBuff: TKDT9DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT9DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT9DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT9DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT9DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT9DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT9DE.Search(const buff: TKDT9DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT9DE_Node;
var
NearestNeighbour: PKDT9DE_Node;
function FindParentNode(const buffPtr: PKDT9DE_Vec; NodePtr: PKDT9DE_Node): PKDT9DE_Node;
var
Next: PKDT9DE_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT9DE_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT9DE_Node; const buffPtr: PKDT9DE_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT9DE_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT9DE_Vec; const p1, p2: PKDT9DE_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT9DE_Vec);
var
i, j: NativeInt;
p, t: PKDT9DE_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT9DE_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT9DE_Node(NearestNodes[0]);
end;
end;
function TKDT9DE.Search(const buff: TKDT9DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT9DE_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT9DE.Search(const buff: TKDT9DE_Vec; var SearchedDistanceMin: Double): PKDT9DE_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT9DE.Search(const buff: TKDT9DE_Vec): PKDT9DE_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT9DE.SearchToken(const buff: TKDT9DE_Vec): TPascalString;
var
p: PKDT9DE_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT9DE.Search(const inBuff: TKDT9DE_DynamicVecBuffer; var OutBuff: TKDT9DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT9DE_DynamicVecBuffer;
outBuffPtr: PKDT9DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT9DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT9DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT9DE_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT9DE.Search(const inBuff: TKDT9DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT9DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT9DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT9DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT9DE_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT9DE.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT9DE_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT9DE_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT9DE.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT9DE_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT9DE_Vec)) <> SizeOf(TKDT9DE_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT9DE.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT9DE.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT9DE.PrintNodeTree(const NodePtr: PKDT9DE_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT9DE_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT9DE.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT9DE.Vec(const s: SystemString): TKDT9DE_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT9DE_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT9DE_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT9DE.Vec(const v: TKDT9DE_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT9DE_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT9DE.Distance(const v1, v2: TKDT9DE_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT9DE_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT9DE.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT9DE_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT9DE.Test;
var
TKDT9DE_Test: TKDT9DE;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT9DE_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT9DE_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT9DE_Test := TKDT9DE.Create;
n.Append('...');
SetLength(TKDT9DE_Test.TestBuff, 1000);
for i := 0 to length(TKDT9DE_Test.TestBuff) - 1 do
for j := 0 to KDT9DE_Axis - 1 do
TKDT9DE_Test.TestBuff[i][j] := i * KDT9DE_Axis + j;
{$IFDEF FPC}
TKDT9DE_Test.BuildKDTreeM(length(TKDT9DE_Test.TestBuff), nil, @TKDT9DE_Test.Test_BuildM);
{$ELSE FPC}
TKDT9DE_Test.BuildKDTreeM(length(TKDT9DE_Test.TestBuff), nil, TKDT9DE_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT9DE_Test.SaveToStream(m64);
m64.Position := 0;
TKDT9DE_Test.LoadFromStream(m64);
for i := 0 to length(TKDT9DE_Test.TestBuff) - 1 do
begin
p := TKDT9DE_Test.Search(TKDT9DE_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT9DE_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT9DE_Test.TestBuff));
TKDT9DE_Test.Search(TKDT9DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT9DE_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT9DE_Test.Clear;
{ kMean test }
TKDT9DE_Test.BuildKDTreeWithCluster(TKDT9DE_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT9DE_Test.Search(TKDT9DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT9DE_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT9DE_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT9DE_Test);
DoStatus(n);
n := '';
end;
function TKDT10DE.InternalBuildKdTree(const KDSourceBufferPtr: PKDT10DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT10DE_Node;
function SortCompare(const p1, p2: PKDT10DE_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT10DE_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT10DE_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT10DE_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT10DE_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT10DE.GetData(const Index: NativeInt): PKDT10DE_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT10DE.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT10DE.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT10DE.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT10DE_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT10DE.StoreBuffPtr: PKDT10DE_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT10DE.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT10DE_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT10DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT10DE.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT10DE_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT10DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT10DE.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT10DE_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT10DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT10DE.BuildKDTreeWithCluster(const inBuff: TKDT10DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT10DE_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT10DE_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT10DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT10DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT10DE.BuildKDTreeWithCluster(const inBuff: TKDT10DE_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT10DE.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT10DE_BuildCall);
var
TempStoreBuff: TKDT10DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT10DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT10DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT10DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT10DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT10DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT10DE.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT10DE_BuildMethod);
var
TempStoreBuff: TKDT10DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT10DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT10DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT10DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT10DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT10DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT10DE.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT10DE_BuildProc);
var
TempStoreBuff: TKDT10DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT10DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT10DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT10DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT10DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT10DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT10DE.Search(const buff: TKDT10DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT10DE_Node;
var
NearestNeighbour: PKDT10DE_Node;
function FindParentNode(const buffPtr: PKDT10DE_Vec; NodePtr: PKDT10DE_Node): PKDT10DE_Node;
var
Next: PKDT10DE_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT10DE_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT10DE_Node; const buffPtr: PKDT10DE_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT10DE_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT10DE_Vec; const p1, p2: PKDT10DE_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT10DE_Vec);
var
i, j: NativeInt;
p, t: PKDT10DE_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT10DE_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT10DE_Node(NearestNodes[0]);
end;
end;
function TKDT10DE.Search(const buff: TKDT10DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT10DE_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT10DE.Search(const buff: TKDT10DE_Vec; var SearchedDistanceMin: Double): PKDT10DE_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT10DE.Search(const buff: TKDT10DE_Vec): PKDT10DE_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT10DE.SearchToken(const buff: TKDT10DE_Vec): TPascalString;
var
p: PKDT10DE_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT10DE.Search(const inBuff: TKDT10DE_DynamicVecBuffer; var OutBuff: TKDT10DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT10DE_DynamicVecBuffer;
outBuffPtr: PKDT10DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT10DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT10DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT10DE_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT10DE.Search(const inBuff: TKDT10DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT10DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT10DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT10DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT10DE_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT10DE.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT10DE_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT10DE_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT10DE.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT10DE_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT10DE_Vec)) <> SizeOf(TKDT10DE_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT10DE.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT10DE.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT10DE.PrintNodeTree(const NodePtr: PKDT10DE_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT10DE_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT10DE.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT10DE.Vec(const s: SystemString): TKDT10DE_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT10DE_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT10DE_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT10DE.Vec(const v: TKDT10DE_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT10DE_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT10DE.Distance(const v1, v2: TKDT10DE_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT10DE_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT10DE.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT10DE_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT10DE.Test;
var
TKDT10DE_Test: TKDT10DE;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT10DE_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT10DE_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT10DE_Test := TKDT10DE.Create;
n.Append('...');
SetLength(TKDT10DE_Test.TestBuff, 1000);
for i := 0 to length(TKDT10DE_Test.TestBuff) - 1 do
for j := 0 to KDT10DE_Axis - 1 do
TKDT10DE_Test.TestBuff[i][j] := i * KDT10DE_Axis + j;
{$IFDEF FPC}
TKDT10DE_Test.BuildKDTreeM(length(TKDT10DE_Test.TestBuff), nil, @TKDT10DE_Test.Test_BuildM);
{$ELSE FPC}
TKDT10DE_Test.BuildKDTreeM(length(TKDT10DE_Test.TestBuff), nil, TKDT10DE_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT10DE_Test.SaveToStream(m64);
m64.Position := 0;
TKDT10DE_Test.LoadFromStream(m64);
for i := 0 to length(TKDT10DE_Test.TestBuff) - 1 do
begin
p := TKDT10DE_Test.Search(TKDT10DE_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT10DE_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT10DE_Test.TestBuff));
TKDT10DE_Test.Search(TKDT10DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT10DE_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT10DE_Test.Clear;
{ kMean test }
TKDT10DE_Test.BuildKDTreeWithCluster(TKDT10DE_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT10DE_Test.Search(TKDT10DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT10DE_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT10DE_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT10DE_Test);
DoStatus(n);
n := '';
end;
function TKDT11DE.InternalBuildKdTree(const KDSourceBufferPtr: PKDT11DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT11DE_Node;
function SortCompare(const p1, p2: PKDT11DE_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT11DE_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT11DE_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT11DE_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT11DE_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT11DE.GetData(const Index: NativeInt): PKDT11DE_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT11DE.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT11DE.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT11DE.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT11DE_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT11DE.StoreBuffPtr: PKDT11DE_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT11DE.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT11DE_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT11DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT11DE.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT11DE_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT11DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT11DE.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT11DE_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT11DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT11DE.BuildKDTreeWithCluster(const inBuff: TKDT11DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT11DE_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT11DE_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT11DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT11DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT11DE.BuildKDTreeWithCluster(const inBuff: TKDT11DE_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT11DE.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT11DE_BuildCall);
var
TempStoreBuff: TKDT11DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT11DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT11DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT11DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT11DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT11DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT11DE.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT11DE_BuildMethod);
var
TempStoreBuff: TKDT11DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT11DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT11DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT11DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT11DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT11DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT11DE.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT11DE_BuildProc);
var
TempStoreBuff: TKDT11DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT11DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT11DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT11DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT11DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT11DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT11DE.Search(const buff: TKDT11DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT11DE_Node;
var
NearestNeighbour: PKDT11DE_Node;
function FindParentNode(const buffPtr: PKDT11DE_Vec; NodePtr: PKDT11DE_Node): PKDT11DE_Node;
var
Next: PKDT11DE_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT11DE_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT11DE_Node; const buffPtr: PKDT11DE_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT11DE_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT11DE_Vec; const p1, p2: PKDT11DE_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT11DE_Vec);
var
i, j: NativeInt;
p, t: PKDT11DE_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT11DE_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT11DE_Node(NearestNodes[0]);
end;
end;
function TKDT11DE.Search(const buff: TKDT11DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT11DE_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT11DE.Search(const buff: TKDT11DE_Vec; var SearchedDistanceMin: Double): PKDT11DE_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT11DE.Search(const buff: TKDT11DE_Vec): PKDT11DE_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT11DE.SearchToken(const buff: TKDT11DE_Vec): TPascalString;
var
p: PKDT11DE_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT11DE.Search(const inBuff: TKDT11DE_DynamicVecBuffer; var OutBuff: TKDT11DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT11DE_DynamicVecBuffer;
outBuffPtr: PKDT11DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT11DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT11DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT11DE_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT11DE.Search(const inBuff: TKDT11DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT11DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT11DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT11DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT11DE_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT11DE.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT11DE_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT11DE_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT11DE.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT11DE_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT11DE_Vec)) <> SizeOf(TKDT11DE_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT11DE.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT11DE.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT11DE.PrintNodeTree(const NodePtr: PKDT11DE_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT11DE_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT11DE.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT11DE.Vec(const s: SystemString): TKDT11DE_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT11DE_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT11DE_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT11DE.Vec(const v: TKDT11DE_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT11DE_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT11DE.Distance(const v1, v2: TKDT11DE_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT11DE_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT11DE.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT11DE_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT11DE.Test;
var
TKDT11DE_Test: TKDT11DE;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT11DE_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT11DE_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT11DE_Test := TKDT11DE.Create;
n.Append('...');
SetLength(TKDT11DE_Test.TestBuff, 1000);
for i := 0 to length(TKDT11DE_Test.TestBuff) - 1 do
for j := 0 to KDT11DE_Axis - 1 do
TKDT11DE_Test.TestBuff[i][j] := i * KDT11DE_Axis + j;
{$IFDEF FPC}
TKDT11DE_Test.BuildKDTreeM(length(TKDT11DE_Test.TestBuff), nil, @TKDT11DE_Test.Test_BuildM);
{$ELSE FPC}
TKDT11DE_Test.BuildKDTreeM(length(TKDT11DE_Test.TestBuff), nil, TKDT11DE_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT11DE_Test.SaveToStream(m64);
m64.Position := 0;
TKDT11DE_Test.LoadFromStream(m64);
for i := 0 to length(TKDT11DE_Test.TestBuff) - 1 do
begin
p := TKDT11DE_Test.Search(TKDT11DE_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT11DE_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT11DE_Test.TestBuff));
TKDT11DE_Test.Search(TKDT11DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT11DE_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT11DE_Test.Clear;
{ kMean test }
TKDT11DE_Test.BuildKDTreeWithCluster(TKDT11DE_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT11DE_Test.Search(TKDT11DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT11DE_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT11DE_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT11DE_Test);
DoStatus(n);
n := '';
end;
function TKDT12DE.InternalBuildKdTree(const KDSourceBufferPtr: PKDT12DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT12DE_Node;
function SortCompare(const p1, p2: PKDT12DE_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT12DE_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT12DE_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT12DE_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT12DE_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT12DE.GetData(const Index: NativeInt): PKDT12DE_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT12DE.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT12DE.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT12DE.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT12DE_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT12DE.StoreBuffPtr: PKDT12DE_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT12DE.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT12DE_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT12DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT12DE.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT12DE_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT12DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT12DE.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT12DE_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT12DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT12DE.BuildKDTreeWithCluster(const inBuff: TKDT12DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT12DE_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT12DE_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT12DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT12DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT12DE.BuildKDTreeWithCluster(const inBuff: TKDT12DE_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT12DE.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT12DE_BuildCall);
var
TempStoreBuff: TKDT12DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT12DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT12DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT12DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT12DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT12DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT12DE.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT12DE_BuildMethod);
var
TempStoreBuff: TKDT12DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT12DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT12DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT12DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT12DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT12DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT12DE.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT12DE_BuildProc);
var
TempStoreBuff: TKDT12DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT12DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT12DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT12DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT12DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT12DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT12DE.Search(const buff: TKDT12DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT12DE_Node;
var
NearestNeighbour: PKDT12DE_Node;
function FindParentNode(const buffPtr: PKDT12DE_Vec; NodePtr: PKDT12DE_Node): PKDT12DE_Node;
var
Next: PKDT12DE_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT12DE_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT12DE_Node; const buffPtr: PKDT12DE_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT12DE_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT12DE_Vec; const p1, p2: PKDT12DE_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT12DE_Vec);
var
i, j: NativeInt;
p, t: PKDT12DE_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT12DE_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT12DE_Node(NearestNodes[0]);
end;
end;
function TKDT12DE.Search(const buff: TKDT12DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT12DE_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT12DE.Search(const buff: TKDT12DE_Vec; var SearchedDistanceMin: Double): PKDT12DE_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT12DE.Search(const buff: TKDT12DE_Vec): PKDT12DE_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT12DE.SearchToken(const buff: TKDT12DE_Vec): TPascalString;
var
p: PKDT12DE_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT12DE.Search(const inBuff: TKDT12DE_DynamicVecBuffer; var OutBuff: TKDT12DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT12DE_DynamicVecBuffer;
outBuffPtr: PKDT12DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT12DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT12DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT12DE_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT12DE.Search(const inBuff: TKDT12DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT12DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT12DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT12DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT12DE_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT12DE.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT12DE_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT12DE_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT12DE.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT12DE_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT12DE_Vec)) <> SizeOf(TKDT12DE_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT12DE.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT12DE.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT12DE.PrintNodeTree(const NodePtr: PKDT12DE_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT12DE_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT12DE.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT12DE.Vec(const s: SystemString): TKDT12DE_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT12DE_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT12DE_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT12DE.Vec(const v: TKDT12DE_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT12DE_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT12DE.Distance(const v1, v2: TKDT12DE_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT12DE_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT12DE.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT12DE_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT12DE.Test;
var
TKDT12DE_Test: TKDT12DE;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT12DE_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT12DE_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT12DE_Test := TKDT12DE.Create;
n.Append('...');
SetLength(TKDT12DE_Test.TestBuff, 1000);
for i := 0 to length(TKDT12DE_Test.TestBuff) - 1 do
for j := 0 to KDT12DE_Axis - 1 do
TKDT12DE_Test.TestBuff[i][j] := i * KDT12DE_Axis + j;
{$IFDEF FPC}
TKDT12DE_Test.BuildKDTreeM(length(TKDT12DE_Test.TestBuff), nil, @TKDT12DE_Test.Test_BuildM);
{$ELSE FPC}
TKDT12DE_Test.BuildKDTreeM(length(TKDT12DE_Test.TestBuff), nil, TKDT12DE_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT12DE_Test.SaveToStream(m64);
m64.Position := 0;
TKDT12DE_Test.LoadFromStream(m64);
for i := 0 to length(TKDT12DE_Test.TestBuff) - 1 do
begin
p := TKDT12DE_Test.Search(TKDT12DE_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT12DE_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT12DE_Test.TestBuff));
TKDT12DE_Test.Search(TKDT12DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT12DE_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT12DE_Test.Clear;
{ kMean test }
TKDT12DE_Test.BuildKDTreeWithCluster(TKDT12DE_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT12DE_Test.Search(TKDT12DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT12DE_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT12DE_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT12DE_Test);
DoStatus(n);
n := '';
end;
function TKDT13DE.InternalBuildKdTree(const KDSourceBufferPtr: PKDT13DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT13DE_Node;
function SortCompare(const p1, p2: PKDT13DE_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT13DE_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT13DE_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT13DE_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT13DE_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT13DE.GetData(const Index: NativeInt): PKDT13DE_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT13DE.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT13DE.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT13DE.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT13DE_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT13DE.StoreBuffPtr: PKDT13DE_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT13DE.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT13DE_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT13DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT13DE.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT13DE_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT13DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT13DE.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT13DE_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT13DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT13DE.BuildKDTreeWithCluster(const inBuff: TKDT13DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT13DE_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT13DE_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT13DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT13DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT13DE.BuildKDTreeWithCluster(const inBuff: TKDT13DE_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT13DE.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT13DE_BuildCall);
var
TempStoreBuff: TKDT13DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT13DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT13DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT13DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT13DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT13DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT13DE.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT13DE_BuildMethod);
var
TempStoreBuff: TKDT13DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT13DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT13DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT13DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT13DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT13DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT13DE.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT13DE_BuildProc);
var
TempStoreBuff: TKDT13DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT13DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT13DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT13DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT13DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT13DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT13DE.Search(const buff: TKDT13DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT13DE_Node;
var
NearestNeighbour: PKDT13DE_Node;
function FindParentNode(const buffPtr: PKDT13DE_Vec; NodePtr: PKDT13DE_Node): PKDT13DE_Node;
var
Next: PKDT13DE_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT13DE_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT13DE_Node; const buffPtr: PKDT13DE_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT13DE_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT13DE_Vec; const p1, p2: PKDT13DE_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT13DE_Vec);
var
i, j: NativeInt;
p, t: PKDT13DE_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT13DE_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT13DE_Node(NearestNodes[0]);
end;
end;
function TKDT13DE.Search(const buff: TKDT13DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT13DE_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT13DE.Search(const buff: TKDT13DE_Vec; var SearchedDistanceMin: Double): PKDT13DE_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT13DE.Search(const buff: TKDT13DE_Vec): PKDT13DE_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT13DE.SearchToken(const buff: TKDT13DE_Vec): TPascalString;
var
p: PKDT13DE_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT13DE.Search(const inBuff: TKDT13DE_DynamicVecBuffer; var OutBuff: TKDT13DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT13DE_DynamicVecBuffer;
outBuffPtr: PKDT13DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT13DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT13DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT13DE_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT13DE.Search(const inBuff: TKDT13DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT13DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT13DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT13DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT13DE_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT13DE.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT13DE_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT13DE_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT13DE.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT13DE_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT13DE_Vec)) <> SizeOf(TKDT13DE_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT13DE.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT13DE.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT13DE.PrintNodeTree(const NodePtr: PKDT13DE_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT13DE_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT13DE.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT13DE.Vec(const s: SystemString): TKDT13DE_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT13DE_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT13DE_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT13DE.Vec(const v: TKDT13DE_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT13DE_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT13DE.Distance(const v1, v2: TKDT13DE_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT13DE_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT13DE.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT13DE_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT13DE.Test;
var
TKDT13DE_Test: TKDT13DE;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT13DE_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT13DE_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT13DE_Test := TKDT13DE.Create;
n.Append('...');
SetLength(TKDT13DE_Test.TestBuff, 1000);
for i := 0 to length(TKDT13DE_Test.TestBuff) - 1 do
for j := 0 to KDT13DE_Axis - 1 do
TKDT13DE_Test.TestBuff[i][j] := i * KDT13DE_Axis + j;
{$IFDEF FPC}
TKDT13DE_Test.BuildKDTreeM(length(TKDT13DE_Test.TestBuff), nil, @TKDT13DE_Test.Test_BuildM);
{$ELSE FPC}
TKDT13DE_Test.BuildKDTreeM(length(TKDT13DE_Test.TestBuff), nil, TKDT13DE_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT13DE_Test.SaveToStream(m64);
m64.Position := 0;
TKDT13DE_Test.LoadFromStream(m64);
for i := 0 to length(TKDT13DE_Test.TestBuff) - 1 do
begin
p := TKDT13DE_Test.Search(TKDT13DE_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT13DE_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT13DE_Test.TestBuff));
TKDT13DE_Test.Search(TKDT13DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT13DE_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT13DE_Test.Clear;
{ kMean test }
TKDT13DE_Test.BuildKDTreeWithCluster(TKDT13DE_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT13DE_Test.Search(TKDT13DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT13DE_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT13DE_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT13DE_Test);
DoStatus(n);
n := '';
end;
function TKDT14DE.InternalBuildKdTree(const KDSourceBufferPtr: PKDT14DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT14DE_Node;
function SortCompare(const p1, p2: PKDT14DE_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT14DE_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT14DE_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT14DE_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT14DE_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT14DE.GetData(const Index: NativeInt): PKDT14DE_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT14DE.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT14DE.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT14DE.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT14DE_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT14DE.StoreBuffPtr: PKDT14DE_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT14DE.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT14DE_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT14DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT14DE.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT14DE_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT14DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT14DE.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT14DE_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT14DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT14DE.BuildKDTreeWithCluster(const inBuff: TKDT14DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT14DE_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT14DE_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT14DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT14DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT14DE.BuildKDTreeWithCluster(const inBuff: TKDT14DE_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT14DE.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT14DE_BuildCall);
var
TempStoreBuff: TKDT14DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT14DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT14DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT14DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT14DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT14DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT14DE.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT14DE_BuildMethod);
var
TempStoreBuff: TKDT14DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT14DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT14DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT14DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT14DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT14DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT14DE.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT14DE_BuildProc);
var
TempStoreBuff: TKDT14DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT14DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT14DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT14DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT14DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT14DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT14DE.Search(const buff: TKDT14DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT14DE_Node;
var
NearestNeighbour: PKDT14DE_Node;
function FindParentNode(const buffPtr: PKDT14DE_Vec; NodePtr: PKDT14DE_Node): PKDT14DE_Node;
var
Next: PKDT14DE_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT14DE_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT14DE_Node; const buffPtr: PKDT14DE_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT14DE_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT14DE_Vec; const p1, p2: PKDT14DE_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT14DE_Vec);
var
i, j: NativeInt;
p, t: PKDT14DE_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT14DE_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT14DE_Node(NearestNodes[0]);
end;
end;
function TKDT14DE.Search(const buff: TKDT14DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT14DE_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT14DE.Search(const buff: TKDT14DE_Vec; var SearchedDistanceMin: Double): PKDT14DE_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT14DE.Search(const buff: TKDT14DE_Vec): PKDT14DE_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT14DE.SearchToken(const buff: TKDT14DE_Vec): TPascalString;
var
p: PKDT14DE_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT14DE.Search(const inBuff: TKDT14DE_DynamicVecBuffer; var OutBuff: TKDT14DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT14DE_DynamicVecBuffer;
outBuffPtr: PKDT14DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT14DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT14DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT14DE_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT14DE.Search(const inBuff: TKDT14DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT14DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT14DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT14DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT14DE_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT14DE.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT14DE_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT14DE_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT14DE.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT14DE_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT14DE_Vec)) <> SizeOf(TKDT14DE_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT14DE.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT14DE.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT14DE.PrintNodeTree(const NodePtr: PKDT14DE_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT14DE_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT14DE.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT14DE.Vec(const s: SystemString): TKDT14DE_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT14DE_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT14DE_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT14DE.Vec(const v: TKDT14DE_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT14DE_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT14DE.Distance(const v1, v2: TKDT14DE_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT14DE_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT14DE.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT14DE_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT14DE.Test;
var
TKDT14DE_Test: TKDT14DE;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT14DE_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT14DE_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT14DE_Test := TKDT14DE.Create;
n.Append('...');
SetLength(TKDT14DE_Test.TestBuff, 1000);
for i := 0 to length(TKDT14DE_Test.TestBuff) - 1 do
for j := 0 to KDT14DE_Axis - 1 do
TKDT14DE_Test.TestBuff[i][j] := i * KDT14DE_Axis + j;
{$IFDEF FPC}
TKDT14DE_Test.BuildKDTreeM(length(TKDT14DE_Test.TestBuff), nil, @TKDT14DE_Test.Test_BuildM);
{$ELSE FPC}
TKDT14DE_Test.BuildKDTreeM(length(TKDT14DE_Test.TestBuff), nil, TKDT14DE_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT14DE_Test.SaveToStream(m64);
m64.Position := 0;
TKDT14DE_Test.LoadFromStream(m64);
for i := 0 to length(TKDT14DE_Test.TestBuff) - 1 do
begin
p := TKDT14DE_Test.Search(TKDT14DE_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT14DE_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT14DE_Test.TestBuff));
TKDT14DE_Test.Search(TKDT14DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT14DE_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT14DE_Test.Clear;
{ kMean test }
TKDT14DE_Test.BuildKDTreeWithCluster(TKDT14DE_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT14DE_Test.Search(TKDT14DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT14DE_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT14DE_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT14DE_Test);
DoStatus(n);
n := '';
end;
function TKDT15DE.InternalBuildKdTree(const KDSourceBufferPtr: PKDT15DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT15DE_Node;
function SortCompare(const p1, p2: PKDT15DE_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT15DE_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT15DE_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT15DE_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT15DE_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT15DE.GetData(const Index: NativeInt): PKDT15DE_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT15DE.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT15DE.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT15DE.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT15DE_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT15DE.StoreBuffPtr: PKDT15DE_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT15DE.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT15DE_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT15DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT15DE.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT15DE_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT15DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT15DE.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT15DE_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT15DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT15DE.BuildKDTreeWithCluster(const inBuff: TKDT15DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT15DE_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT15DE_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT15DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT15DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT15DE.BuildKDTreeWithCluster(const inBuff: TKDT15DE_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT15DE.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT15DE_BuildCall);
var
TempStoreBuff: TKDT15DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT15DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT15DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT15DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT15DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT15DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT15DE.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT15DE_BuildMethod);
var
TempStoreBuff: TKDT15DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT15DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT15DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT15DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT15DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT15DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT15DE.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT15DE_BuildProc);
var
TempStoreBuff: TKDT15DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT15DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT15DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT15DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT15DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT15DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT15DE.Search(const buff: TKDT15DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT15DE_Node;
var
NearestNeighbour: PKDT15DE_Node;
function FindParentNode(const buffPtr: PKDT15DE_Vec; NodePtr: PKDT15DE_Node): PKDT15DE_Node;
var
Next: PKDT15DE_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT15DE_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT15DE_Node; const buffPtr: PKDT15DE_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT15DE_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT15DE_Vec; const p1, p2: PKDT15DE_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT15DE_Vec);
var
i, j: NativeInt;
p, t: PKDT15DE_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT15DE_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT15DE_Node(NearestNodes[0]);
end;
end;
function TKDT15DE.Search(const buff: TKDT15DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT15DE_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT15DE.Search(const buff: TKDT15DE_Vec; var SearchedDistanceMin: Double): PKDT15DE_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT15DE.Search(const buff: TKDT15DE_Vec): PKDT15DE_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT15DE.SearchToken(const buff: TKDT15DE_Vec): TPascalString;
var
p: PKDT15DE_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT15DE.Search(const inBuff: TKDT15DE_DynamicVecBuffer; var OutBuff: TKDT15DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT15DE_DynamicVecBuffer;
outBuffPtr: PKDT15DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT15DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT15DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT15DE_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT15DE.Search(const inBuff: TKDT15DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT15DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT15DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT15DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT15DE_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT15DE.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT15DE_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT15DE_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT15DE.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT15DE_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT15DE_Vec)) <> SizeOf(TKDT15DE_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT15DE.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT15DE.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT15DE.PrintNodeTree(const NodePtr: PKDT15DE_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT15DE_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT15DE.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT15DE.Vec(const s: SystemString): TKDT15DE_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT15DE_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT15DE_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT15DE.Vec(const v: TKDT15DE_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT15DE_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT15DE.Distance(const v1, v2: TKDT15DE_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT15DE_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT15DE.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT15DE_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT15DE.Test;
var
TKDT15DE_Test: TKDT15DE;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT15DE_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT15DE_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT15DE_Test := TKDT15DE.Create;
n.Append('...');
SetLength(TKDT15DE_Test.TestBuff, 1000);
for i := 0 to length(TKDT15DE_Test.TestBuff) - 1 do
for j := 0 to KDT15DE_Axis - 1 do
TKDT15DE_Test.TestBuff[i][j] := i * KDT15DE_Axis + j;
{$IFDEF FPC}
TKDT15DE_Test.BuildKDTreeM(length(TKDT15DE_Test.TestBuff), nil, @TKDT15DE_Test.Test_BuildM);
{$ELSE FPC}
TKDT15DE_Test.BuildKDTreeM(length(TKDT15DE_Test.TestBuff), nil, TKDT15DE_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT15DE_Test.SaveToStream(m64);
m64.Position := 0;
TKDT15DE_Test.LoadFromStream(m64);
for i := 0 to length(TKDT15DE_Test.TestBuff) - 1 do
begin
p := TKDT15DE_Test.Search(TKDT15DE_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT15DE_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT15DE_Test.TestBuff));
TKDT15DE_Test.Search(TKDT15DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT15DE_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT15DE_Test.Clear;
{ kMean test }
TKDT15DE_Test.BuildKDTreeWithCluster(TKDT15DE_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT15DE_Test.Search(TKDT15DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT15DE_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT15DE_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT15DE_Test);
DoStatus(n);
n := '';
end;
function TKDT16DE.InternalBuildKdTree(const KDSourceBufferPtr: PKDT16DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT16DE_Node;
function SortCompare(const p1, p2: PKDT16DE_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT16DE_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT16DE_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT16DE_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT16DE_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT16DE.GetData(const Index: NativeInt): PKDT16DE_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT16DE.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT16DE.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT16DE.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT16DE_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT16DE.StoreBuffPtr: PKDT16DE_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT16DE.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT16DE_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT16DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT16DE.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT16DE_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT16DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT16DE.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT16DE_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT16DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT16DE.BuildKDTreeWithCluster(const inBuff: TKDT16DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT16DE_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT16DE_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT16DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT16DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT16DE.BuildKDTreeWithCluster(const inBuff: TKDT16DE_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT16DE.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT16DE_BuildCall);
var
TempStoreBuff: TKDT16DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT16DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT16DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT16DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT16DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT16DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT16DE.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT16DE_BuildMethod);
var
TempStoreBuff: TKDT16DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT16DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT16DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT16DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT16DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT16DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT16DE.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT16DE_BuildProc);
var
TempStoreBuff: TKDT16DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT16DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT16DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT16DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT16DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT16DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT16DE.Search(const buff: TKDT16DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT16DE_Node;
var
NearestNeighbour: PKDT16DE_Node;
function FindParentNode(const buffPtr: PKDT16DE_Vec; NodePtr: PKDT16DE_Node): PKDT16DE_Node;
var
Next: PKDT16DE_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT16DE_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT16DE_Node; const buffPtr: PKDT16DE_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT16DE_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT16DE_Vec; const p1, p2: PKDT16DE_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT16DE_Vec);
var
i, j: NativeInt;
p, t: PKDT16DE_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT16DE_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT16DE_Node(NearestNodes[0]);
end;
end;
function TKDT16DE.Search(const buff: TKDT16DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT16DE_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT16DE.Search(const buff: TKDT16DE_Vec; var SearchedDistanceMin: Double): PKDT16DE_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT16DE.Search(const buff: TKDT16DE_Vec): PKDT16DE_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT16DE.SearchToken(const buff: TKDT16DE_Vec): TPascalString;
var
p: PKDT16DE_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT16DE.Search(const inBuff: TKDT16DE_DynamicVecBuffer; var OutBuff: TKDT16DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT16DE_DynamicVecBuffer;
outBuffPtr: PKDT16DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT16DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT16DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT16DE_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT16DE.Search(const inBuff: TKDT16DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT16DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT16DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT16DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT16DE_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT16DE.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT16DE_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT16DE_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT16DE.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT16DE_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT16DE_Vec)) <> SizeOf(TKDT16DE_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT16DE.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT16DE.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT16DE.PrintNodeTree(const NodePtr: PKDT16DE_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT16DE_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT16DE.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT16DE.Vec(const s: SystemString): TKDT16DE_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT16DE_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT16DE_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT16DE.Vec(const v: TKDT16DE_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT16DE_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT16DE.Distance(const v1, v2: TKDT16DE_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT16DE_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT16DE.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT16DE_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT16DE.Test;
var
TKDT16DE_Test: TKDT16DE;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT16DE_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT16DE_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT16DE_Test := TKDT16DE.Create;
n.Append('...');
SetLength(TKDT16DE_Test.TestBuff, 1000);
for i := 0 to length(TKDT16DE_Test.TestBuff) - 1 do
for j := 0 to KDT16DE_Axis - 1 do
TKDT16DE_Test.TestBuff[i][j] := i * KDT16DE_Axis + j;
{$IFDEF FPC}
TKDT16DE_Test.BuildKDTreeM(length(TKDT16DE_Test.TestBuff), nil, @TKDT16DE_Test.Test_BuildM);
{$ELSE FPC}
TKDT16DE_Test.BuildKDTreeM(length(TKDT16DE_Test.TestBuff), nil, TKDT16DE_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT16DE_Test.SaveToStream(m64);
m64.Position := 0;
TKDT16DE_Test.LoadFromStream(m64);
for i := 0 to length(TKDT16DE_Test.TestBuff) - 1 do
begin
p := TKDT16DE_Test.Search(TKDT16DE_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT16DE_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT16DE_Test.TestBuff));
TKDT16DE_Test.Search(TKDT16DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT16DE_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT16DE_Test.Clear;
{ kMean test }
TKDT16DE_Test.BuildKDTreeWithCluster(TKDT16DE_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT16DE_Test.Search(TKDT16DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT16DE_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT16DE_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT16DE_Test);
DoStatus(n);
n := '';
end;
function TKDT17DE.InternalBuildKdTree(const KDSourceBufferPtr: PKDT17DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT17DE_Node;
function SortCompare(const p1, p2: PKDT17DE_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT17DE_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT17DE_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT17DE_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT17DE_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT17DE.GetData(const Index: NativeInt): PKDT17DE_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT17DE.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT17DE.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT17DE.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT17DE_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT17DE.StoreBuffPtr: PKDT17DE_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT17DE.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT17DE_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT17DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT17DE.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT17DE_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT17DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT17DE.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT17DE_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT17DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT17DE.BuildKDTreeWithCluster(const inBuff: TKDT17DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT17DE_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT17DE_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT17DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT17DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT17DE.BuildKDTreeWithCluster(const inBuff: TKDT17DE_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT17DE.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT17DE_BuildCall);
var
TempStoreBuff: TKDT17DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT17DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT17DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT17DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT17DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT17DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT17DE.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT17DE_BuildMethod);
var
TempStoreBuff: TKDT17DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT17DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT17DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT17DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT17DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT17DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT17DE.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT17DE_BuildProc);
var
TempStoreBuff: TKDT17DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT17DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT17DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT17DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT17DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT17DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT17DE.Search(const buff: TKDT17DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT17DE_Node;
var
NearestNeighbour: PKDT17DE_Node;
function FindParentNode(const buffPtr: PKDT17DE_Vec; NodePtr: PKDT17DE_Node): PKDT17DE_Node;
var
Next: PKDT17DE_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT17DE_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT17DE_Node; const buffPtr: PKDT17DE_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT17DE_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT17DE_Vec; const p1, p2: PKDT17DE_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT17DE_Vec);
var
i, j: NativeInt;
p, t: PKDT17DE_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT17DE_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT17DE_Node(NearestNodes[0]);
end;
end;
function TKDT17DE.Search(const buff: TKDT17DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT17DE_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT17DE.Search(const buff: TKDT17DE_Vec; var SearchedDistanceMin: Double): PKDT17DE_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT17DE.Search(const buff: TKDT17DE_Vec): PKDT17DE_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT17DE.SearchToken(const buff: TKDT17DE_Vec): TPascalString;
var
p: PKDT17DE_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT17DE.Search(const inBuff: TKDT17DE_DynamicVecBuffer; var OutBuff: TKDT17DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT17DE_DynamicVecBuffer;
outBuffPtr: PKDT17DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT17DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT17DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT17DE_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT17DE.Search(const inBuff: TKDT17DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT17DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT17DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT17DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT17DE_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT17DE.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT17DE_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT17DE_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT17DE.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT17DE_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT17DE_Vec)) <> SizeOf(TKDT17DE_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT17DE.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT17DE.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT17DE.PrintNodeTree(const NodePtr: PKDT17DE_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT17DE_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT17DE.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT17DE.Vec(const s: SystemString): TKDT17DE_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT17DE_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT17DE_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT17DE.Vec(const v: TKDT17DE_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT17DE_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT17DE.Distance(const v1, v2: TKDT17DE_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT17DE_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT17DE.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT17DE_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT17DE.Test;
var
TKDT17DE_Test: TKDT17DE;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT17DE_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT17DE_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT17DE_Test := TKDT17DE.Create;
n.Append('...');
SetLength(TKDT17DE_Test.TestBuff, 1000);
for i := 0 to length(TKDT17DE_Test.TestBuff) - 1 do
for j := 0 to KDT17DE_Axis - 1 do
TKDT17DE_Test.TestBuff[i][j] := i * KDT17DE_Axis + j;
{$IFDEF FPC}
TKDT17DE_Test.BuildKDTreeM(length(TKDT17DE_Test.TestBuff), nil, @TKDT17DE_Test.Test_BuildM);
{$ELSE FPC}
TKDT17DE_Test.BuildKDTreeM(length(TKDT17DE_Test.TestBuff), nil, TKDT17DE_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT17DE_Test.SaveToStream(m64);
m64.Position := 0;
TKDT17DE_Test.LoadFromStream(m64);
for i := 0 to length(TKDT17DE_Test.TestBuff) - 1 do
begin
p := TKDT17DE_Test.Search(TKDT17DE_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT17DE_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT17DE_Test.TestBuff));
TKDT17DE_Test.Search(TKDT17DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT17DE_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT17DE_Test.Clear;
{ kMean test }
TKDT17DE_Test.BuildKDTreeWithCluster(TKDT17DE_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT17DE_Test.Search(TKDT17DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT17DE_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT17DE_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT17DE_Test);
DoStatus(n);
n := '';
end;
function TKDT18DE.InternalBuildKdTree(const KDSourceBufferPtr: PKDT18DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT18DE_Node;
function SortCompare(const p1, p2: PKDT18DE_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT18DE_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT18DE_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT18DE_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT18DE_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT18DE.GetData(const Index: NativeInt): PKDT18DE_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT18DE.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT18DE.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT18DE.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT18DE_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT18DE.StoreBuffPtr: PKDT18DE_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT18DE.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT18DE_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT18DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT18DE.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT18DE_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT18DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT18DE.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT18DE_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT18DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT18DE.BuildKDTreeWithCluster(const inBuff: TKDT18DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT18DE_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT18DE_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT18DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT18DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT18DE.BuildKDTreeWithCluster(const inBuff: TKDT18DE_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT18DE.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT18DE_BuildCall);
var
TempStoreBuff: TKDT18DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT18DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT18DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT18DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT18DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT18DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT18DE.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT18DE_BuildMethod);
var
TempStoreBuff: TKDT18DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT18DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT18DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT18DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT18DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT18DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT18DE.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT18DE_BuildProc);
var
TempStoreBuff: TKDT18DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT18DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT18DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT18DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT18DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT18DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT18DE.Search(const buff: TKDT18DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT18DE_Node;
var
NearestNeighbour: PKDT18DE_Node;
function FindParentNode(const buffPtr: PKDT18DE_Vec; NodePtr: PKDT18DE_Node): PKDT18DE_Node;
var
Next: PKDT18DE_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT18DE_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT18DE_Node; const buffPtr: PKDT18DE_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT18DE_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT18DE_Vec; const p1, p2: PKDT18DE_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT18DE_Vec);
var
i, j: NativeInt;
p, t: PKDT18DE_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT18DE_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT18DE_Node(NearestNodes[0]);
end;
end;
function TKDT18DE.Search(const buff: TKDT18DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT18DE_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT18DE.Search(const buff: TKDT18DE_Vec; var SearchedDistanceMin: Double): PKDT18DE_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT18DE.Search(const buff: TKDT18DE_Vec): PKDT18DE_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT18DE.SearchToken(const buff: TKDT18DE_Vec): TPascalString;
var
p: PKDT18DE_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT18DE.Search(const inBuff: TKDT18DE_DynamicVecBuffer; var OutBuff: TKDT18DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT18DE_DynamicVecBuffer;
outBuffPtr: PKDT18DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT18DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT18DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT18DE_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT18DE.Search(const inBuff: TKDT18DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT18DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT18DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT18DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT18DE_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT18DE.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT18DE_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT18DE_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT18DE.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT18DE_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT18DE_Vec)) <> SizeOf(TKDT18DE_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT18DE.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT18DE.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT18DE.PrintNodeTree(const NodePtr: PKDT18DE_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT18DE_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT18DE.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT18DE.Vec(const s: SystemString): TKDT18DE_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT18DE_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT18DE_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT18DE.Vec(const v: TKDT18DE_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT18DE_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT18DE.Distance(const v1, v2: TKDT18DE_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT18DE_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT18DE.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT18DE_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT18DE.Test;
var
TKDT18DE_Test: TKDT18DE;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT18DE_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT18DE_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT18DE_Test := TKDT18DE.Create;
n.Append('...');
SetLength(TKDT18DE_Test.TestBuff, 1000);
for i := 0 to length(TKDT18DE_Test.TestBuff) - 1 do
for j := 0 to KDT18DE_Axis - 1 do
TKDT18DE_Test.TestBuff[i][j] := i * KDT18DE_Axis + j;
{$IFDEF FPC}
TKDT18DE_Test.BuildKDTreeM(length(TKDT18DE_Test.TestBuff), nil, @TKDT18DE_Test.Test_BuildM);
{$ELSE FPC}
TKDT18DE_Test.BuildKDTreeM(length(TKDT18DE_Test.TestBuff), nil, TKDT18DE_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT18DE_Test.SaveToStream(m64);
m64.Position := 0;
TKDT18DE_Test.LoadFromStream(m64);
for i := 0 to length(TKDT18DE_Test.TestBuff) - 1 do
begin
p := TKDT18DE_Test.Search(TKDT18DE_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT18DE_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT18DE_Test.TestBuff));
TKDT18DE_Test.Search(TKDT18DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT18DE_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT18DE_Test.Clear;
{ kMean test }
TKDT18DE_Test.BuildKDTreeWithCluster(TKDT18DE_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT18DE_Test.Search(TKDT18DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT18DE_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT18DE_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT18DE_Test);
DoStatus(n);
n := '';
end;
function TKDT19DE.InternalBuildKdTree(const KDSourceBufferPtr: PKDT19DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT19DE_Node;
function SortCompare(const p1, p2: PKDT19DE_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT19DE_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT19DE_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT19DE_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT19DE_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT19DE.GetData(const Index: NativeInt): PKDT19DE_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT19DE.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT19DE.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT19DE.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT19DE_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT19DE.StoreBuffPtr: PKDT19DE_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT19DE.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT19DE_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT19DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT19DE.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT19DE_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT19DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT19DE.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT19DE_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT19DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT19DE.BuildKDTreeWithCluster(const inBuff: TKDT19DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT19DE_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT19DE_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT19DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT19DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT19DE.BuildKDTreeWithCluster(const inBuff: TKDT19DE_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT19DE.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT19DE_BuildCall);
var
TempStoreBuff: TKDT19DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT19DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT19DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT19DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT19DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT19DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT19DE.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT19DE_BuildMethod);
var
TempStoreBuff: TKDT19DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT19DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT19DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT19DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT19DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT19DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT19DE.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT19DE_BuildProc);
var
TempStoreBuff: TKDT19DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT19DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT19DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT19DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT19DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT19DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT19DE.Search(const buff: TKDT19DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT19DE_Node;
var
NearestNeighbour: PKDT19DE_Node;
function FindParentNode(const buffPtr: PKDT19DE_Vec; NodePtr: PKDT19DE_Node): PKDT19DE_Node;
var
Next: PKDT19DE_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT19DE_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT19DE_Node; const buffPtr: PKDT19DE_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT19DE_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT19DE_Vec; const p1, p2: PKDT19DE_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT19DE_Vec);
var
i, j: NativeInt;
p, t: PKDT19DE_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT19DE_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT19DE_Node(NearestNodes[0]);
end;
end;
function TKDT19DE.Search(const buff: TKDT19DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT19DE_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT19DE.Search(const buff: TKDT19DE_Vec; var SearchedDistanceMin: Double): PKDT19DE_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT19DE.Search(const buff: TKDT19DE_Vec): PKDT19DE_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT19DE.SearchToken(const buff: TKDT19DE_Vec): TPascalString;
var
p: PKDT19DE_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT19DE.Search(const inBuff: TKDT19DE_DynamicVecBuffer; var OutBuff: TKDT19DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT19DE_DynamicVecBuffer;
outBuffPtr: PKDT19DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT19DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT19DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT19DE_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT19DE.Search(const inBuff: TKDT19DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT19DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT19DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT19DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT19DE_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT19DE.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT19DE_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT19DE_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT19DE.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT19DE_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT19DE_Vec)) <> SizeOf(TKDT19DE_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT19DE.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT19DE.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT19DE.PrintNodeTree(const NodePtr: PKDT19DE_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT19DE_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT19DE.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT19DE.Vec(const s: SystemString): TKDT19DE_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT19DE_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT19DE_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT19DE.Vec(const v: TKDT19DE_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT19DE_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT19DE.Distance(const v1, v2: TKDT19DE_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT19DE_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT19DE.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT19DE_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT19DE.Test;
var
TKDT19DE_Test: TKDT19DE;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT19DE_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT19DE_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT19DE_Test := TKDT19DE.Create;
n.Append('...');
SetLength(TKDT19DE_Test.TestBuff, 1000);
for i := 0 to length(TKDT19DE_Test.TestBuff) - 1 do
for j := 0 to KDT19DE_Axis - 1 do
TKDT19DE_Test.TestBuff[i][j] := i * KDT19DE_Axis + j;
{$IFDEF FPC}
TKDT19DE_Test.BuildKDTreeM(length(TKDT19DE_Test.TestBuff), nil, @TKDT19DE_Test.Test_BuildM);
{$ELSE FPC}
TKDT19DE_Test.BuildKDTreeM(length(TKDT19DE_Test.TestBuff), nil, TKDT19DE_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT19DE_Test.SaveToStream(m64);
m64.Position := 0;
TKDT19DE_Test.LoadFromStream(m64);
for i := 0 to length(TKDT19DE_Test.TestBuff) - 1 do
begin
p := TKDT19DE_Test.Search(TKDT19DE_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT19DE_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT19DE_Test.TestBuff));
TKDT19DE_Test.Search(TKDT19DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT19DE_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT19DE_Test.Clear;
{ kMean test }
TKDT19DE_Test.BuildKDTreeWithCluster(TKDT19DE_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT19DE_Test.Search(TKDT19DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT19DE_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT19DE_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT19DE_Test);
DoStatus(n);
n := '';
end;
function TKDT20DE.InternalBuildKdTree(const KDSourceBufferPtr: PKDT20DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT20DE_Node;
function SortCompare(const p1, p2: PKDT20DE_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT20DE_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT20DE_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT20DE_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT20DE_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT20DE.GetData(const Index: NativeInt): PKDT20DE_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT20DE.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT20DE.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT20DE.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT20DE_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT20DE.StoreBuffPtr: PKDT20DE_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT20DE.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT20DE_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT20DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT20DE.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT20DE_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT20DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT20DE.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT20DE_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT20DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT20DE.BuildKDTreeWithCluster(const inBuff: TKDT20DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT20DE_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT20DE_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT20DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT20DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT20DE.BuildKDTreeWithCluster(const inBuff: TKDT20DE_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT20DE.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT20DE_BuildCall);
var
TempStoreBuff: TKDT20DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT20DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT20DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT20DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT20DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT20DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT20DE.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT20DE_BuildMethod);
var
TempStoreBuff: TKDT20DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT20DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT20DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT20DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT20DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT20DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT20DE.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT20DE_BuildProc);
var
TempStoreBuff: TKDT20DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT20DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT20DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT20DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT20DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT20DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT20DE.Search(const buff: TKDT20DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT20DE_Node;
var
NearestNeighbour: PKDT20DE_Node;
function FindParentNode(const buffPtr: PKDT20DE_Vec; NodePtr: PKDT20DE_Node): PKDT20DE_Node;
var
Next: PKDT20DE_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT20DE_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT20DE_Node; const buffPtr: PKDT20DE_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT20DE_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT20DE_Vec; const p1, p2: PKDT20DE_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT20DE_Vec);
var
i, j: NativeInt;
p, t: PKDT20DE_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT20DE_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT20DE_Node(NearestNodes[0]);
end;
end;
function TKDT20DE.Search(const buff: TKDT20DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT20DE_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT20DE.Search(const buff: TKDT20DE_Vec; var SearchedDistanceMin: Double): PKDT20DE_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT20DE.Search(const buff: TKDT20DE_Vec): PKDT20DE_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT20DE.SearchToken(const buff: TKDT20DE_Vec): TPascalString;
var
p: PKDT20DE_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT20DE.Search(const inBuff: TKDT20DE_DynamicVecBuffer; var OutBuff: TKDT20DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT20DE_DynamicVecBuffer;
outBuffPtr: PKDT20DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT20DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT20DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT20DE_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT20DE.Search(const inBuff: TKDT20DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT20DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT20DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT20DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT20DE_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT20DE.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT20DE_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT20DE_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT20DE.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT20DE_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT20DE_Vec)) <> SizeOf(TKDT20DE_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT20DE.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT20DE.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT20DE.PrintNodeTree(const NodePtr: PKDT20DE_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT20DE_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT20DE.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT20DE.Vec(const s: SystemString): TKDT20DE_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT20DE_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT20DE_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT20DE.Vec(const v: TKDT20DE_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT20DE_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT20DE.Distance(const v1, v2: TKDT20DE_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT20DE_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT20DE.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT20DE_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT20DE.Test;
var
TKDT20DE_Test: TKDT20DE;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT20DE_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT20DE_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT20DE_Test := TKDT20DE.Create;
n.Append('...');
SetLength(TKDT20DE_Test.TestBuff, 1000);
for i := 0 to length(TKDT20DE_Test.TestBuff) - 1 do
for j := 0 to KDT20DE_Axis - 1 do
TKDT20DE_Test.TestBuff[i][j] := i * KDT20DE_Axis + j;
{$IFDEF FPC}
TKDT20DE_Test.BuildKDTreeM(length(TKDT20DE_Test.TestBuff), nil, @TKDT20DE_Test.Test_BuildM);
{$ELSE FPC}
TKDT20DE_Test.BuildKDTreeM(length(TKDT20DE_Test.TestBuff), nil, TKDT20DE_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT20DE_Test.SaveToStream(m64);
m64.Position := 0;
TKDT20DE_Test.LoadFromStream(m64);
for i := 0 to length(TKDT20DE_Test.TestBuff) - 1 do
begin
p := TKDT20DE_Test.Search(TKDT20DE_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT20DE_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT20DE_Test.TestBuff));
TKDT20DE_Test.Search(TKDT20DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT20DE_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT20DE_Test.Clear;
{ kMean test }
TKDT20DE_Test.BuildKDTreeWithCluster(TKDT20DE_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT20DE_Test.Search(TKDT20DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT20DE_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT20DE_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT20DE_Test);
DoStatus(n);
n := '';
end;
function TKDT21DE.InternalBuildKdTree(const KDSourceBufferPtr: PKDT21DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT21DE_Node;
function SortCompare(const p1, p2: PKDT21DE_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT21DE_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT21DE_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT21DE_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT21DE_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT21DE.GetData(const Index: NativeInt): PKDT21DE_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT21DE.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT21DE.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT21DE.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT21DE_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT21DE.StoreBuffPtr: PKDT21DE_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT21DE.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT21DE_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT21DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT21DE.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT21DE_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT21DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT21DE.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT21DE_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT21DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT21DE.BuildKDTreeWithCluster(const inBuff: TKDT21DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT21DE_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT21DE_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT21DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT21DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT21DE.BuildKDTreeWithCluster(const inBuff: TKDT21DE_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT21DE.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT21DE_BuildCall);
var
TempStoreBuff: TKDT21DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT21DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT21DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT21DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT21DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT21DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT21DE.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT21DE_BuildMethod);
var
TempStoreBuff: TKDT21DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT21DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT21DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT21DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT21DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT21DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT21DE.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT21DE_BuildProc);
var
TempStoreBuff: TKDT21DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT21DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT21DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT21DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT21DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT21DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT21DE.Search(const buff: TKDT21DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT21DE_Node;
var
NearestNeighbour: PKDT21DE_Node;
function FindParentNode(const buffPtr: PKDT21DE_Vec; NodePtr: PKDT21DE_Node): PKDT21DE_Node;
var
Next: PKDT21DE_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT21DE_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT21DE_Node; const buffPtr: PKDT21DE_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT21DE_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT21DE_Vec; const p1, p2: PKDT21DE_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT21DE_Vec);
var
i, j: NativeInt;
p, t: PKDT21DE_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT21DE_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT21DE_Node(NearestNodes[0]);
end;
end;
function TKDT21DE.Search(const buff: TKDT21DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT21DE_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT21DE.Search(const buff: TKDT21DE_Vec; var SearchedDistanceMin: Double): PKDT21DE_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT21DE.Search(const buff: TKDT21DE_Vec): PKDT21DE_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT21DE.SearchToken(const buff: TKDT21DE_Vec): TPascalString;
var
p: PKDT21DE_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT21DE.Search(const inBuff: TKDT21DE_DynamicVecBuffer; var OutBuff: TKDT21DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT21DE_DynamicVecBuffer;
outBuffPtr: PKDT21DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT21DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT21DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT21DE_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT21DE.Search(const inBuff: TKDT21DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT21DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT21DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT21DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT21DE_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT21DE.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT21DE_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT21DE_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT21DE.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT21DE_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT21DE_Vec)) <> SizeOf(TKDT21DE_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT21DE.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT21DE.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT21DE.PrintNodeTree(const NodePtr: PKDT21DE_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT21DE_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT21DE.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT21DE.Vec(const s: SystemString): TKDT21DE_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT21DE_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT21DE_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT21DE.Vec(const v: TKDT21DE_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT21DE_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT21DE.Distance(const v1, v2: TKDT21DE_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT21DE_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT21DE.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT21DE_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT21DE.Test;
var
TKDT21DE_Test: TKDT21DE;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT21DE_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT21DE_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT21DE_Test := TKDT21DE.Create;
n.Append('...');
SetLength(TKDT21DE_Test.TestBuff, 1000);
for i := 0 to length(TKDT21DE_Test.TestBuff) - 1 do
for j := 0 to KDT21DE_Axis - 1 do
TKDT21DE_Test.TestBuff[i][j] := i * KDT21DE_Axis + j;
{$IFDEF FPC}
TKDT21DE_Test.BuildKDTreeM(length(TKDT21DE_Test.TestBuff), nil, @TKDT21DE_Test.Test_BuildM);
{$ELSE FPC}
TKDT21DE_Test.BuildKDTreeM(length(TKDT21DE_Test.TestBuff), nil, TKDT21DE_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT21DE_Test.SaveToStream(m64);
m64.Position := 0;
TKDT21DE_Test.LoadFromStream(m64);
for i := 0 to length(TKDT21DE_Test.TestBuff) - 1 do
begin
p := TKDT21DE_Test.Search(TKDT21DE_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT21DE_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT21DE_Test.TestBuff));
TKDT21DE_Test.Search(TKDT21DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT21DE_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT21DE_Test.Clear;
{ kMean test }
TKDT21DE_Test.BuildKDTreeWithCluster(TKDT21DE_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT21DE_Test.Search(TKDT21DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT21DE_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT21DE_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT21DE_Test);
DoStatus(n);
n := '';
end;
function TKDT22DE.InternalBuildKdTree(const KDSourceBufferPtr: PKDT22DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT22DE_Node;
function SortCompare(const p1, p2: PKDT22DE_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT22DE_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT22DE_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT22DE_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT22DE_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT22DE.GetData(const Index: NativeInt): PKDT22DE_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT22DE.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT22DE.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT22DE.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT22DE_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT22DE.StoreBuffPtr: PKDT22DE_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT22DE.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT22DE_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT22DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT22DE.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT22DE_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT22DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT22DE.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT22DE_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT22DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT22DE.BuildKDTreeWithCluster(const inBuff: TKDT22DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT22DE_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT22DE_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT22DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT22DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT22DE.BuildKDTreeWithCluster(const inBuff: TKDT22DE_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT22DE.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT22DE_BuildCall);
var
TempStoreBuff: TKDT22DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT22DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT22DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT22DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT22DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT22DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT22DE.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT22DE_BuildMethod);
var
TempStoreBuff: TKDT22DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT22DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT22DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT22DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT22DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT22DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT22DE.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT22DE_BuildProc);
var
TempStoreBuff: TKDT22DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT22DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT22DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT22DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT22DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT22DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT22DE.Search(const buff: TKDT22DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT22DE_Node;
var
NearestNeighbour: PKDT22DE_Node;
function FindParentNode(const buffPtr: PKDT22DE_Vec; NodePtr: PKDT22DE_Node): PKDT22DE_Node;
var
Next: PKDT22DE_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT22DE_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT22DE_Node; const buffPtr: PKDT22DE_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT22DE_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT22DE_Vec; const p1, p2: PKDT22DE_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT22DE_Vec);
var
i, j: NativeInt;
p, t: PKDT22DE_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT22DE_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT22DE_Node(NearestNodes[0]);
end;
end;
function TKDT22DE.Search(const buff: TKDT22DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT22DE_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT22DE.Search(const buff: TKDT22DE_Vec; var SearchedDistanceMin: Double): PKDT22DE_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT22DE.Search(const buff: TKDT22DE_Vec): PKDT22DE_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT22DE.SearchToken(const buff: TKDT22DE_Vec): TPascalString;
var
p: PKDT22DE_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT22DE.Search(const inBuff: TKDT22DE_DynamicVecBuffer; var OutBuff: TKDT22DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT22DE_DynamicVecBuffer;
outBuffPtr: PKDT22DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT22DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT22DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT22DE_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT22DE.Search(const inBuff: TKDT22DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT22DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT22DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT22DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT22DE_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT22DE.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT22DE_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT22DE_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT22DE.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT22DE_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT22DE_Vec)) <> SizeOf(TKDT22DE_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT22DE.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT22DE.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT22DE.PrintNodeTree(const NodePtr: PKDT22DE_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT22DE_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT22DE.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT22DE.Vec(const s: SystemString): TKDT22DE_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT22DE_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT22DE_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT22DE.Vec(const v: TKDT22DE_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT22DE_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT22DE.Distance(const v1, v2: TKDT22DE_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT22DE_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT22DE.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT22DE_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT22DE.Test;
var
TKDT22DE_Test: TKDT22DE;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT22DE_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT22DE_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT22DE_Test := TKDT22DE.Create;
n.Append('...');
SetLength(TKDT22DE_Test.TestBuff, 1000);
for i := 0 to length(TKDT22DE_Test.TestBuff) - 1 do
for j := 0 to KDT22DE_Axis - 1 do
TKDT22DE_Test.TestBuff[i][j] := i * KDT22DE_Axis + j;
{$IFDEF FPC}
TKDT22DE_Test.BuildKDTreeM(length(TKDT22DE_Test.TestBuff), nil, @TKDT22DE_Test.Test_BuildM);
{$ELSE FPC}
TKDT22DE_Test.BuildKDTreeM(length(TKDT22DE_Test.TestBuff), nil, TKDT22DE_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT22DE_Test.SaveToStream(m64);
m64.Position := 0;
TKDT22DE_Test.LoadFromStream(m64);
for i := 0 to length(TKDT22DE_Test.TestBuff) - 1 do
begin
p := TKDT22DE_Test.Search(TKDT22DE_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT22DE_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT22DE_Test.TestBuff));
TKDT22DE_Test.Search(TKDT22DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT22DE_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT22DE_Test.Clear;
{ kMean test }
TKDT22DE_Test.BuildKDTreeWithCluster(TKDT22DE_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT22DE_Test.Search(TKDT22DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT22DE_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT22DE_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT22DE_Test);
DoStatus(n);
n := '';
end;
function TKDT23DE.InternalBuildKdTree(const KDSourceBufferPtr: PKDT23DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT23DE_Node;
function SortCompare(const p1, p2: PKDT23DE_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT23DE_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT23DE_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT23DE_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT23DE_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT23DE.GetData(const Index: NativeInt): PKDT23DE_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT23DE.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT23DE.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT23DE.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT23DE_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT23DE.StoreBuffPtr: PKDT23DE_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT23DE.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT23DE_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT23DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT23DE.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT23DE_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT23DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT23DE.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT23DE_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT23DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT23DE.BuildKDTreeWithCluster(const inBuff: TKDT23DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT23DE_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT23DE_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT23DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT23DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT23DE.BuildKDTreeWithCluster(const inBuff: TKDT23DE_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT23DE.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT23DE_BuildCall);
var
TempStoreBuff: TKDT23DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT23DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT23DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT23DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT23DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT23DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT23DE.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT23DE_BuildMethod);
var
TempStoreBuff: TKDT23DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT23DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT23DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT23DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT23DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT23DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT23DE.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT23DE_BuildProc);
var
TempStoreBuff: TKDT23DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT23DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT23DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT23DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT23DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT23DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT23DE.Search(const buff: TKDT23DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT23DE_Node;
var
NearestNeighbour: PKDT23DE_Node;
function FindParentNode(const buffPtr: PKDT23DE_Vec; NodePtr: PKDT23DE_Node): PKDT23DE_Node;
var
Next: PKDT23DE_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT23DE_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT23DE_Node; const buffPtr: PKDT23DE_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT23DE_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT23DE_Vec; const p1, p2: PKDT23DE_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT23DE_Vec);
var
i, j: NativeInt;
p, t: PKDT23DE_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT23DE_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT23DE_Node(NearestNodes[0]);
end;
end;
function TKDT23DE.Search(const buff: TKDT23DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT23DE_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT23DE.Search(const buff: TKDT23DE_Vec; var SearchedDistanceMin: Double): PKDT23DE_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT23DE.Search(const buff: TKDT23DE_Vec): PKDT23DE_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT23DE.SearchToken(const buff: TKDT23DE_Vec): TPascalString;
var
p: PKDT23DE_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT23DE.Search(const inBuff: TKDT23DE_DynamicVecBuffer; var OutBuff: TKDT23DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT23DE_DynamicVecBuffer;
outBuffPtr: PKDT23DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT23DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT23DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT23DE_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT23DE.Search(const inBuff: TKDT23DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT23DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT23DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT23DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT23DE_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT23DE.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT23DE_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT23DE_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT23DE.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT23DE_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT23DE_Vec)) <> SizeOf(TKDT23DE_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT23DE.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT23DE.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT23DE.PrintNodeTree(const NodePtr: PKDT23DE_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT23DE_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT23DE.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT23DE.Vec(const s: SystemString): TKDT23DE_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT23DE_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT23DE_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT23DE.Vec(const v: TKDT23DE_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT23DE_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT23DE.Distance(const v1, v2: TKDT23DE_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT23DE_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT23DE.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT23DE_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT23DE.Test;
var
TKDT23DE_Test: TKDT23DE;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT23DE_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT23DE_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT23DE_Test := TKDT23DE.Create;
n.Append('...');
SetLength(TKDT23DE_Test.TestBuff, 1000);
for i := 0 to length(TKDT23DE_Test.TestBuff) - 1 do
for j := 0 to KDT23DE_Axis - 1 do
TKDT23DE_Test.TestBuff[i][j] := i * KDT23DE_Axis + j;
{$IFDEF FPC}
TKDT23DE_Test.BuildKDTreeM(length(TKDT23DE_Test.TestBuff), nil, @TKDT23DE_Test.Test_BuildM);
{$ELSE FPC}
TKDT23DE_Test.BuildKDTreeM(length(TKDT23DE_Test.TestBuff), nil, TKDT23DE_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT23DE_Test.SaveToStream(m64);
m64.Position := 0;
TKDT23DE_Test.LoadFromStream(m64);
for i := 0 to length(TKDT23DE_Test.TestBuff) - 1 do
begin
p := TKDT23DE_Test.Search(TKDT23DE_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT23DE_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT23DE_Test.TestBuff));
TKDT23DE_Test.Search(TKDT23DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT23DE_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT23DE_Test.Clear;
{ kMean test }
TKDT23DE_Test.BuildKDTreeWithCluster(TKDT23DE_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT23DE_Test.Search(TKDT23DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT23DE_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT23DE_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT23DE_Test);
DoStatus(n);
n := '';
end;
function TKDT24DE.InternalBuildKdTree(const KDSourceBufferPtr: PKDT24DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT24DE_Node;
function SortCompare(const p1, p2: PKDT24DE_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT24DE_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT24DE_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT24DE_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT24DE_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT24DE.GetData(const Index: NativeInt): PKDT24DE_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT24DE.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT24DE.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT24DE.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT24DE_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT24DE.StoreBuffPtr: PKDT24DE_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT24DE.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT24DE_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT24DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT24DE.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT24DE_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT24DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT24DE.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT24DE_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT24DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT24DE.BuildKDTreeWithCluster(const inBuff: TKDT24DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT24DE_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT24DE_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT24DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT24DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT24DE.BuildKDTreeWithCluster(const inBuff: TKDT24DE_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT24DE.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT24DE_BuildCall);
var
TempStoreBuff: TKDT24DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT24DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT24DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT24DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT24DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT24DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT24DE.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT24DE_BuildMethod);
var
TempStoreBuff: TKDT24DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT24DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT24DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT24DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT24DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT24DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT24DE.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT24DE_BuildProc);
var
TempStoreBuff: TKDT24DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT24DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT24DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT24DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT24DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT24DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT24DE.Search(const buff: TKDT24DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT24DE_Node;
var
NearestNeighbour: PKDT24DE_Node;
function FindParentNode(const buffPtr: PKDT24DE_Vec; NodePtr: PKDT24DE_Node): PKDT24DE_Node;
var
Next: PKDT24DE_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT24DE_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT24DE_Node; const buffPtr: PKDT24DE_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT24DE_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT24DE_Vec; const p1, p2: PKDT24DE_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT24DE_Vec);
var
i, j: NativeInt;
p, t: PKDT24DE_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT24DE_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT24DE_Node(NearestNodes[0]);
end;
end;
function TKDT24DE.Search(const buff: TKDT24DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT24DE_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT24DE.Search(const buff: TKDT24DE_Vec; var SearchedDistanceMin: Double): PKDT24DE_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT24DE.Search(const buff: TKDT24DE_Vec): PKDT24DE_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT24DE.SearchToken(const buff: TKDT24DE_Vec): TPascalString;
var
p: PKDT24DE_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT24DE.Search(const inBuff: TKDT24DE_DynamicVecBuffer; var OutBuff: TKDT24DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT24DE_DynamicVecBuffer;
outBuffPtr: PKDT24DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT24DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT24DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT24DE_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT24DE.Search(const inBuff: TKDT24DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT24DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT24DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT24DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT24DE_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT24DE.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT24DE_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT24DE_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT24DE.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT24DE_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT24DE_Vec)) <> SizeOf(TKDT24DE_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT24DE.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT24DE.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT24DE.PrintNodeTree(const NodePtr: PKDT24DE_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT24DE_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT24DE.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT24DE.Vec(const s: SystemString): TKDT24DE_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT24DE_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT24DE_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT24DE.Vec(const v: TKDT24DE_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT24DE_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT24DE.Distance(const v1, v2: TKDT24DE_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT24DE_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT24DE.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT24DE_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT24DE.Test;
var
TKDT24DE_Test: TKDT24DE;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT24DE_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT24DE_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT24DE_Test := TKDT24DE.Create;
n.Append('...');
SetLength(TKDT24DE_Test.TestBuff, 1000);
for i := 0 to length(TKDT24DE_Test.TestBuff) - 1 do
for j := 0 to KDT24DE_Axis - 1 do
TKDT24DE_Test.TestBuff[i][j] := i * KDT24DE_Axis + j;
{$IFDEF FPC}
TKDT24DE_Test.BuildKDTreeM(length(TKDT24DE_Test.TestBuff), nil, @TKDT24DE_Test.Test_BuildM);
{$ELSE FPC}
TKDT24DE_Test.BuildKDTreeM(length(TKDT24DE_Test.TestBuff), nil, TKDT24DE_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT24DE_Test.SaveToStream(m64);
m64.Position := 0;
TKDT24DE_Test.LoadFromStream(m64);
for i := 0 to length(TKDT24DE_Test.TestBuff) - 1 do
begin
p := TKDT24DE_Test.Search(TKDT24DE_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT24DE_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT24DE_Test.TestBuff));
TKDT24DE_Test.Search(TKDT24DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT24DE_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT24DE_Test.Clear;
{ kMean test }
TKDT24DE_Test.BuildKDTreeWithCluster(TKDT24DE_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT24DE_Test.Search(TKDT24DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT24DE_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT24DE_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT24DE_Test);
DoStatus(n);
n := '';
end;
function TKDT48DE.InternalBuildKdTree(const KDSourceBufferPtr: PKDT48DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT48DE_Node;
function SortCompare(const p1, p2: PKDT48DE_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT48DE_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT48DE_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT48DE_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT48DE_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT48DE.GetData(const Index: NativeInt): PKDT48DE_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT48DE.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT48DE.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT48DE.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT48DE_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT48DE.StoreBuffPtr: PKDT48DE_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT48DE.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT48DE_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT48DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT48DE.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT48DE_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT48DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT48DE.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT48DE_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT48DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT48DE.BuildKDTreeWithCluster(const inBuff: TKDT48DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT48DE_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT48DE_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT48DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT48DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT48DE.BuildKDTreeWithCluster(const inBuff: TKDT48DE_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT48DE.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT48DE_BuildCall);
var
TempStoreBuff: TKDT48DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT48DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT48DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT48DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT48DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT48DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT48DE.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT48DE_BuildMethod);
var
TempStoreBuff: TKDT48DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT48DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT48DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT48DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT48DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT48DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT48DE.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT48DE_BuildProc);
var
TempStoreBuff: TKDT48DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT48DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT48DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT48DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT48DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT48DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT48DE.Search(const buff: TKDT48DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT48DE_Node;
var
NearestNeighbour: PKDT48DE_Node;
function FindParentNode(const buffPtr: PKDT48DE_Vec; NodePtr: PKDT48DE_Node): PKDT48DE_Node;
var
Next: PKDT48DE_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT48DE_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT48DE_Node; const buffPtr: PKDT48DE_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT48DE_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT48DE_Vec; const p1, p2: PKDT48DE_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT48DE_Vec);
var
i, j: NativeInt;
p, t: PKDT48DE_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT48DE_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT48DE_Node(NearestNodes[0]);
end;
end;
function TKDT48DE.Search(const buff: TKDT48DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT48DE_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT48DE.Search(const buff: TKDT48DE_Vec; var SearchedDistanceMin: Double): PKDT48DE_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT48DE.Search(const buff: TKDT48DE_Vec): PKDT48DE_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT48DE.SearchToken(const buff: TKDT48DE_Vec): TPascalString;
var
p: PKDT48DE_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT48DE.Search(const inBuff: TKDT48DE_DynamicVecBuffer; var OutBuff: TKDT48DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT48DE_DynamicVecBuffer;
outBuffPtr: PKDT48DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT48DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT48DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT48DE_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT48DE.Search(const inBuff: TKDT48DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT48DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT48DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT48DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT48DE_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT48DE.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT48DE_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT48DE_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT48DE.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT48DE_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT48DE_Vec)) <> SizeOf(TKDT48DE_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT48DE.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT48DE.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT48DE.PrintNodeTree(const NodePtr: PKDT48DE_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT48DE_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT48DE.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT48DE.Vec(const s: SystemString): TKDT48DE_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT48DE_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT48DE_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT48DE.Vec(const v: TKDT48DE_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT48DE_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT48DE.Distance(const v1, v2: TKDT48DE_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT48DE_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT48DE.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT48DE_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT48DE.Test;
var
TKDT48DE_Test: TKDT48DE;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT48DE_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT48DE_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT48DE_Test := TKDT48DE.Create;
n.Append('...');
SetLength(TKDT48DE_Test.TestBuff, 1000);
for i := 0 to length(TKDT48DE_Test.TestBuff) - 1 do
for j := 0 to KDT48DE_Axis - 1 do
TKDT48DE_Test.TestBuff[i][j] := i * KDT48DE_Axis + j;
{$IFDEF FPC}
TKDT48DE_Test.BuildKDTreeM(length(TKDT48DE_Test.TestBuff), nil, @TKDT48DE_Test.Test_BuildM);
{$ELSE FPC}
TKDT48DE_Test.BuildKDTreeM(length(TKDT48DE_Test.TestBuff), nil, TKDT48DE_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT48DE_Test.SaveToStream(m64);
m64.Position := 0;
TKDT48DE_Test.LoadFromStream(m64);
for i := 0 to length(TKDT48DE_Test.TestBuff) - 1 do
begin
p := TKDT48DE_Test.Search(TKDT48DE_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT48DE_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT48DE_Test.TestBuff));
TKDT48DE_Test.Search(TKDT48DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT48DE_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT48DE_Test.Clear;
{ kMean test }
TKDT48DE_Test.BuildKDTreeWithCluster(TKDT48DE_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT48DE_Test.Search(TKDT48DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT48DE_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT48DE_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT48DE_Test);
DoStatus(n);
n := '';
end;
function TKDT52DE.InternalBuildKdTree(const KDSourceBufferPtr: PKDT52DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT52DE_Node;
function SortCompare(const p1, p2: PKDT52DE_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT52DE_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT52DE_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT52DE_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT52DE_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT52DE.GetData(const Index: NativeInt): PKDT52DE_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT52DE.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT52DE.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT52DE.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT52DE_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT52DE.StoreBuffPtr: PKDT52DE_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT52DE.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT52DE_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT52DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT52DE.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT52DE_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT52DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT52DE.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT52DE_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT52DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT52DE.BuildKDTreeWithCluster(const inBuff: TKDT52DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT52DE_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT52DE_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT52DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT52DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT52DE.BuildKDTreeWithCluster(const inBuff: TKDT52DE_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT52DE.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT52DE_BuildCall);
var
TempStoreBuff: TKDT52DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT52DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT52DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT52DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT52DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT52DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT52DE.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT52DE_BuildMethod);
var
TempStoreBuff: TKDT52DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT52DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT52DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT52DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT52DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT52DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT52DE.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT52DE_BuildProc);
var
TempStoreBuff: TKDT52DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT52DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT52DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT52DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT52DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT52DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT52DE.Search(const buff: TKDT52DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT52DE_Node;
var
NearestNeighbour: PKDT52DE_Node;
function FindParentNode(const buffPtr: PKDT52DE_Vec; NodePtr: PKDT52DE_Node): PKDT52DE_Node;
var
Next: PKDT52DE_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT52DE_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT52DE_Node; const buffPtr: PKDT52DE_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT52DE_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT52DE_Vec; const p1, p2: PKDT52DE_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT52DE_Vec);
var
i, j: NativeInt;
p, t: PKDT52DE_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT52DE_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT52DE_Node(NearestNodes[0]);
end;
end;
function TKDT52DE.Search(const buff: TKDT52DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT52DE_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT52DE.Search(const buff: TKDT52DE_Vec; var SearchedDistanceMin: Double): PKDT52DE_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT52DE.Search(const buff: TKDT52DE_Vec): PKDT52DE_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT52DE.SearchToken(const buff: TKDT52DE_Vec): TPascalString;
var
p: PKDT52DE_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT52DE.Search(const inBuff: TKDT52DE_DynamicVecBuffer; var OutBuff: TKDT52DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT52DE_DynamicVecBuffer;
outBuffPtr: PKDT52DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT52DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT52DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT52DE_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT52DE.Search(const inBuff: TKDT52DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT52DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT52DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT52DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT52DE_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT52DE.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT52DE_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT52DE_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT52DE.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT52DE_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT52DE_Vec)) <> SizeOf(TKDT52DE_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT52DE.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT52DE.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT52DE.PrintNodeTree(const NodePtr: PKDT52DE_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT52DE_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT52DE.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT52DE.Vec(const s: SystemString): TKDT52DE_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT52DE_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT52DE_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT52DE.Vec(const v: TKDT52DE_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT52DE_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT52DE.Distance(const v1, v2: TKDT52DE_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT52DE_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT52DE.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT52DE_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT52DE.Test;
var
TKDT52DE_Test: TKDT52DE;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT52DE_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT52DE_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT52DE_Test := TKDT52DE.Create;
n.Append('...');
SetLength(TKDT52DE_Test.TestBuff, 1000);
for i := 0 to length(TKDT52DE_Test.TestBuff) - 1 do
for j := 0 to KDT52DE_Axis - 1 do
TKDT52DE_Test.TestBuff[i][j] := i * KDT52DE_Axis + j;
{$IFDEF FPC}
TKDT52DE_Test.BuildKDTreeM(length(TKDT52DE_Test.TestBuff), nil, @TKDT52DE_Test.Test_BuildM);
{$ELSE FPC}
TKDT52DE_Test.BuildKDTreeM(length(TKDT52DE_Test.TestBuff), nil, TKDT52DE_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT52DE_Test.SaveToStream(m64);
m64.Position := 0;
TKDT52DE_Test.LoadFromStream(m64);
for i := 0 to length(TKDT52DE_Test.TestBuff) - 1 do
begin
p := TKDT52DE_Test.Search(TKDT52DE_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT52DE_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT52DE_Test.TestBuff));
TKDT52DE_Test.Search(TKDT52DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT52DE_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT52DE_Test.Clear;
{ kMean test }
TKDT52DE_Test.BuildKDTreeWithCluster(TKDT52DE_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT52DE_Test.Search(TKDT52DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT52DE_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT52DE_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT52DE_Test);
DoStatus(n);
n := '';
end;
function TKDT64DE.InternalBuildKdTree(const KDSourceBufferPtr: PKDT64DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT64DE_Node;
function SortCompare(const p1, p2: PKDT64DE_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT64DE_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT64DE_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT64DE_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT64DE_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT64DE.GetData(const Index: NativeInt): PKDT64DE_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT64DE.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT64DE.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT64DE.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT64DE_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT64DE.StoreBuffPtr: PKDT64DE_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT64DE.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT64DE_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT64DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT64DE.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT64DE_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT64DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT64DE.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT64DE_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT64DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT64DE.BuildKDTreeWithCluster(const inBuff: TKDT64DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT64DE_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT64DE_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT64DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT64DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT64DE.BuildKDTreeWithCluster(const inBuff: TKDT64DE_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT64DE.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT64DE_BuildCall);
var
TempStoreBuff: TKDT64DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT64DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT64DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT64DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT64DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT64DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT64DE.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT64DE_BuildMethod);
var
TempStoreBuff: TKDT64DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT64DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT64DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT64DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT64DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT64DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT64DE.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT64DE_BuildProc);
var
TempStoreBuff: TKDT64DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT64DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT64DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT64DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT64DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT64DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT64DE.Search(const buff: TKDT64DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT64DE_Node;
var
NearestNeighbour: PKDT64DE_Node;
function FindParentNode(const buffPtr: PKDT64DE_Vec; NodePtr: PKDT64DE_Node): PKDT64DE_Node;
var
Next: PKDT64DE_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT64DE_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT64DE_Node; const buffPtr: PKDT64DE_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT64DE_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT64DE_Vec; const p1, p2: PKDT64DE_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT64DE_Vec);
var
i, j: NativeInt;
p, t: PKDT64DE_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT64DE_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT64DE_Node(NearestNodes[0]);
end;
end;
function TKDT64DE.Search(const buff: TKDT64DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT64DE_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT64DE.Search(const buff: TKDT64DE_Vec; var SearchedDistanceMin: Double): PKDT64DE_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT64DE.Search(const buff: TKDT64DE_Vec): PKDT64DE_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT64DE.SearchToken(const buff: TKDT64DE_Vec): TPascalString;
var
p: PKDT64DE_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT64DE.Search(const inBuff: TKDT64DE_DynamicVecBuffer; var OutBuff: TKDT64DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT64DE_DynamicVecBuffer;
outBuffPtr: PKDT64DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT64DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT64DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT64DE_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT64DE.Search(const inBuff: TKDT64DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT64DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT64DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT64DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT64DE_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT64DE.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT64DE_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT64DE_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT64DE.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT64DE_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT64DE_Vec)) <> SizeOf(TKDT64DE_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT64DE.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT64DE.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT64DE.PrintNodeTree(const NodePtr: PKDT64DE_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT64DE_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT64DE.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT64DE.Vec(const s: SystemString): TKDT64DE_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT64DE_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT64DE_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT64DE.Vec(const v: TKDT64DE_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT64DE_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT64DE.Distance(const v1, v2: TKDT64DE_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT64DE_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT64DE.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT64DE_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT64DE.Test;
var
TKDT64DE_Test: TKDT64DE;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT64DE_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT64DE_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT64DE_Test := TKDT64DE.Create;
n.Append('...');
SetLength(TKDT64DE_Test.TestBuff, 1000);
for i := 0 to length(TKDT64DE_Test.TestBuff) - 1 do
for j := 0 to KDT64DE_Axis - 1 do
TKDT64DE_Test.TestBuff[i][j] := i * KDT64DE_Axis + j;
{$IFDEF FPC}
TKDT64DE_Test.BuildKDTreeM(length(TKDT64DE_Test.TestBuff), nil, @TKDT64DE_Test.Test_BuildM);
{$ELSE FPC}
TKDT64DE_Test.BuildKDTreeM(length(TKDT64DE_Test.TestBuff), nil, TKDT64DE_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT64DE_Test.SaveToStream(m64);
m64.Position := 0;
TKDT64DE_Test.LoadFromStream(m64);
for i := 0 to length(TKDT64DE_Test.TestBuff) - 1 do
begin
p := TKDT64DE_Test.Search(TKDT64DE_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT64DE_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT64DE_Test.TestBuff));
TKDT64DE_Test.Search(TKDT64DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT64DE_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT64DE_Test.Clear;
{ kMean test }
TKDT64DE_Test.BuildKDTreeWithCluster(TKDT64DE_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT64DE_Test.Search(TKDT64DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT64DE_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT64DE_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT64DE_Test);
DoStatus(n);
n := '';
end;
function TKDT96DE.InternalBuildKdTree(const KDSourceBufferPtr: PKDT96DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT96DE_Node;
function SortCompare(const p1, p2: PKDT96DE_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT96DE_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT96DE_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT96DE_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT96DE_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT96DE.GetData(const Index: NativeInt): PKDT96DE_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT96DE.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT96DE.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT96DE.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT96DE_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT96DE.StoreBuffPtr: PKDT96DE_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT96DE.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT96DE_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT96DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT96DE.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT96DE_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT96DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT96DE.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT96DE_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT96DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT96DE.BuildKDTreeWithCluster(const inBuff: TKDT96DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT96DE_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT96DE_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT96DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT96DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT96DE.BuildKDTreeWithCluster(const inBuff: TKDT96DE_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT96DE.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT96DE_BuildCall);
var
TempStoreBuff: TKDT96DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT96DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT96DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT96DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT96DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT96DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT96DE.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT96DE_BuildMethod);
var
TempStoreBuff: TKDT96DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT96DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT96DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT96DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT96DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT96DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT96DE.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT96DE_BuildProc);
var
TempStoreBuff: TKDT96DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT96DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT96DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT96DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT96DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT96DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT96DE.Search(const buff: TKDT96DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT96DE_Node;
var
NearestNeighbour: PKDT96DE_Node;
function FindParentNode(const buffPtr: PKDT96DE_Vec; NodePtr: PKDT96DE_Node): PKDT96DE_Node;
var
Next: PKDT96DE_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT96DE_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT96DE_Node; const buffPtr: PKDT96DE_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT96DE_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT96DE_Vec; const p1, p2: PKDT96DE_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT96DE_Vec);
var
i, j: NativeInt;
p, t: PKDT96DE_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT96DE_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT96DE_Node(NearestNodes[0]);
end;
end;
function TKDT96DE.Search(const buff: TKDT96DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT96DE_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT96DE.Search(const buff: TKDT96DE_Vec; var SearchedDistanceMin: Double): PKDT96DE_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT96DE.Search(const buff: TKDT96DE_Vec): PKDT96DE_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT96DE.SearchToken(const buff: TKDT96DE_Vec): TPascalString;
var
p: PKDT96DE_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT96DE.Search(const inBuff: TKDT96DE_DynamicVecBuffer; var OutBuff: TKDT96DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT96DE_DynamicVecBuffer;
outBuffPtr: PKDT96DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT96DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT96DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT96DE_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT96DE.Search(const inBuff: TKDT96DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT96DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT96DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT96DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT96DE_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT96DE.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT96DE_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT96DE_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT96DE.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT96DE_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT96DE_Vec)) <> SizeOf(TKDT96DE_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT96DE.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT96DE.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT96DE.PrintNodeTree(const NodePtr: PKDT96DE_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT96DE_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT96DE.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT96DE.Vec(const s: SystemString): TKDT96DE_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT96DE_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT96DE_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT96DE.Vec(const v: TKDT96DE_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT96DE_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT96DE.Distance(const v1, v2: TKDT96DE_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT96DE_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT96DE.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT96DE_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT96DE.Test;
var
TKDT96DE_Test: TKDT96DE;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT96DE_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT96DE_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT96DE_Test := TKDT96DE.Create;
n.Append('...');
SetLength(TKDT96DE_Test.TestBuff, 1000);
for i := 0 to length(TKDT96DE_Test.TestBuff) - 1 do
for j := 0 to KDT96DE_Axis - 1 do
TKDT96DE_Test.TestBuff[i][j] := i * KDT96DE_Axis + j;
{$IFDEF FPC}
TKDT96DE_Test.BuildKDTreeM(length(TKDT96DE_Test.TestBuff), nil, @TKDT96DE_Test.Test_BuildM);
{$ELSE FPC}
TKDT96DE_Test.BuildKDTreeM(length(TKDT96DE_Test.TestBuff), nil, TKDT96DE_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT96DE_Test.SaveToStream(m64);
m64.Position := 0;
TKDT96DE_Test.LoadFromStream(m64);
for i := 0 to length(TKDT96DE_Test.TestBuff) - 1 do
begin
p := TKDT96DE_Test.Search(TKDT96DE_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT96DE_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT96DE_Test.TestBuff));
TKDT96DE_Test.Search(TKDT96DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT96DE_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT96DE_Test.Clear;
{ kMean test }
TKDT96DE_Test.BuildKDTreeWithCluster(TKDT96DE_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT96DE_Test.Search(TKDT96DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT96DE_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT96DE_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT96DE_Test);
DoStatus(n);
n := '';
end;
function TKDT128DE.InternalBuildKdTree(const KDSourceBufferPtr: PKDT128DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT128DE_Node;
function SortCompare(const p1, p2: PKDT128DE_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT128DE_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT128DE_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT128DE_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT128DE_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT128DE.GetData(const Index: NativeInt): PKDT128DE_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT128DE.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT128DE.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT128DE.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT128DE_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT128DE.StoreBuffPtr: PKDT128DE_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT128DE.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT128DE_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT128DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT128DE.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT128DE_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT128DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT128DE.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT128DE_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT128DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT128DE.BuildKDTreeWithCluster(const inBuff: TKDT128DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT128DE_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT128DE_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT128DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT128DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT128DE.BuildKDTreeWithCluster(const inBuff: TKDT128DE_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT128DE.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT128DE_BuildCall);
var
TempStoreBuff: TKDT128DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT128DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT128DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT128DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT128DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT128DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT128DE.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT128DE_BuildMethod);
var
TempStoreBuff: TKDT128DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT128DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT128DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT128DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT128DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT128DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT128DE.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT128DE_BuildProc);
var
TempStoreBuff: TKDT128DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT128DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT128DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT128DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT128DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT128DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT128DE.Search(const buff: TKDT128DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT128DE_Node;
var
NearestNeighbour: PKDT128DE_Node;
function FindParentNode(const buffPtr: PKDT128DE_Vec; NodePtr: PKDT128DE_Node): PKDT128DE_Node;
var
Next: PKDT128DE_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT128DE_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT128DE_Node; const buffPtr: PKDT128DE_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT128DE_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT128DE_Vec; const p1, p2: PKDT128DE_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT128DE_Vec);
var
i, j: NativeInt;
p, t: PKDT128DE_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT128DE_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT128DE_Node(NearestNodes[0]);
end;
end;
function TKDT128DE.Search(const buff: TKDT128DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT128DE_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT128DE.Search(const buff: TKDT128DE_Vec; var SearchedDistanceMin: Double): PKDT128DE_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT128DE.Search(const buff: TKDT128DE_Vec): PKDT128DE_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT128DE.SearchToken(const buff: TKDT128DE_Vec): TPascalString;
var
p: PKDT128DE_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT128DE.Search(const inBuff: TKDT128DE_DynamicVecBuffer; var OutBuff: TKDT128DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT128DE_DynamicVecBuffer;
outBuffPtr: PKDT128DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT128DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT128DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT128DE_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT128DE.Search(const inBuff: TKDT128DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT128DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT128DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT128DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT128DE_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT128DE.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT128DE_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT128DE_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT128DE.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT128DE_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT128DE_Vec)) <> SizeOf(TKDT128DE_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT128DE.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT128DE.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT128DE.PrintNodeTree(const NodePtr: PKDT128DE_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT128DE_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT128DE.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT128DE.Vec(const s: SystemString): TKDT128DE_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT128DE_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT128DE_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT128DE.Vec(const v: TKDT128DE_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT128DE_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT128DE.Distance(const v1, v2: TKDT128DE_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT128DE_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT128DE.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT128DE_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT128DE.Test;
var
TKDT128DE_Test: TKDT128DE;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT128DE_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT128DE_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT128DE_Test := TKDT128DE.Create;
n.Append('...');
SetLength(TKDT128DE_Test.TestBuff, 1000);
for i := 0 to length(TKDT128DE_Test.TestBuff) - 1 do
for j := 0 to KDT128DE_Axis - 1 do
TKDT128DE_Test.TestBuff[i][j] := i * KDT128DE_Axis + j;
{$IFDEF FPC}
TKDT128DE_Test.BuildKDTreeM(length(TKDT128DE_Test.TestBuff), nil, @TKDT128DE_Test.Test_BuildM);
{$ELSE FPC}
TKDT128DE_Test.BuildKDTreeM(length(TKDT128DE_Test.TestBuff), nil, TKDT128DE_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT128DE_Test.SaveToStream(m64);
m64.Position := 0;
TKDT128DE_Test.LoadFromStream(m64);
for i := 0 to length(TKDT128DE_Test.TestBuff) - 1 do
begin
p := TKDT128DE_Test.Search(TKDT128DE_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT128DE_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT128DE_Test.TestBuff));
TKDT128DE_Test.Search(TKDT128DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT128DE_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT128DE_Test.Clear;
{ kMean test }
TKDT128DE_Test.BuildKDTreeWithCluster(TKDT128DE_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT128DE_Test.Search(TKDT128DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT128DE_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT128DE_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT128DE_Test);
DoStatus(n);
n := '';
end;
function TKDT156DE.InternalBuildKdTree(const KDSourceBufferPtr: PKDT156DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT156DE_Node;
function SortCompare(const p1, p2: PKDT156DE_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT156DE_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT156DE_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT156DE_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT156DE_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT156DE.GetData(const Index: NativeInt): PKDT156DE_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT156DE.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT156DE.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT156DE.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT156DE_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT156DE.StoreBuffPtr: PKDT156DE_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT156DE.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT156DE_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT156DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT156DE.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT156DE_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT156DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT156DE.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT156DE_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT156DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT156DE.BuildKDTreeWithCluster(const inBuff: TKDT156DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT156DE_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT156DE_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT156DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT156DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT156DE.BuildKDTreeWithCluster(const inBuff: TKDT156DE_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT156DE.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT156DE_BuildCall);
var
TempStoreBuff: TKDT156DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT156DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT156DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT156DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT156DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT156DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT156DE.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT156DE_BuildMethod);
var
TempStoreBuff: TKDT156DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT156DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT156DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT156DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT156DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT156DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT156DE.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT156DE_BuildProc);
var
TempStoreBuff: TKDT156DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT156DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT156DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT156DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT156DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT156DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT156DE.Search(const buff: TKDT156DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT156DE_Node;
var
NearestNeighbour: PKDT156DE_Node;
function FindParentNode(const buffPtr: PKDT156DE_Vec; NodePtr: PKDT156DE_Node): PKDT156DE_Node;
var
Next: PKDT156DE_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT156DE_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT156DE_Node; const buffPtr: PKDT156DE_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT156DE_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT156DE_Vec; const p1, p2: PKDT156DE_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT156DE_Vec);
var
i, j: NativeInt;
p, t: PKDT156DE_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT156DE_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT156DE_Node(NearestNodes[0]);
end;
end;
function TKDT156DE.Search(const buff: TKDT156DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT156DE_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT156DE.Search(const buff: TKDT156DE_Vec; var SearchedDistanceMin: Double): PKDT156DE_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT156DE.Search(const buff: TKDT156DE_Vec): PKDT156DE_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT156DE.SearchToken(const buff: TKDT156DE_Vec): TPascalString;
var
p: PKDT156DE_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT156DE.Search(const inBuff: TKDT156DE_DynamicVecBuffer; var OutBuff: TKDT156DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT156DE_DynamicVecBuffer;
outBuffPtr: PKDT156DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT156DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT156DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT156DE_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT156DE.Search(const inBuff: TKDT156DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT156DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT156DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT156DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT156DE_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT156DE.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT156DE_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT156DE_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT156DE.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT156DE_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT156DE_Vec)) <> SizeOf(TKDT156DE_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT156DE.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT156DE.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT156DE.PrintNodeTree(const NodePtr: PKDT156DE_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT156DE_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT156DE.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT156DE.Vec(const s: SystemString): TKDT156DE_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT156DE_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT156DE_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT156DE.Vec(const v: TKDT156DE_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT156DE_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT156DE.Distance(const v1, v2: TKDT156DE_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT156DE_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT156DE.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT156DE_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT156DE.Test;
var
TKDT156DE_Test: TKDT156DE;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT156DE_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT156DE_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT156DE_Test := TKDT156DE.Create;
n.Append('...');
SetLength(TKDT156DE_Test.TestBuff, 1000);
for i := 0 to length(TKDT156DE_Test.TestBuff) - 1 do
for j := 0 to KDT156DE_Axis - 1 do
TKDT156DE_Test.TestBuff[i][j] := i * KDT156DE_Axis + j;
{$IFDEF FPC}
TKDT156DE_Test.BuildKDTreeM(length(TKDT156DE_Test.TestBuff), nil, @TKDT156DE_Test.Test_BuildM);
{$ELSE FPC}
TKDT156DE_Test.BuildKDTreeM(length(TKDT156DE_Test.TestBuff), nil, TKDT156DE_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT156DE_Test.SaveToStream(m64);
m64.Position := 0;
TKDT156DE_Test.LoadFromStream(m64);
for i := 0 to length(TKDT156DE_Test.TestBuff) - 1 do
begin
p := TKDT156DE_Test.Search(TKDT156DE_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT156DE_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT156DE_Test.TestBuff));
TKDT156DE_Test.Search(TKDT156DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT156DE_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT156DE_Test.Clear;
{ kMean test }
TKDT156DE_Test.BuildKDTreeWithCluster(TKDT156DE_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT156DE_Test.Search(TKDT156DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT156DE_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT156DE_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT156DE_Test);
DoStatus(n);
n := '';
end;
function TKDT192DE.InternalBuildKdTree(const KDSourceBufferPtr: PKDT192DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT192DE_Node;
function SortCompare(const p1, p2: PKDT192DE_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT192DE_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT192DE_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT192DE_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT192DE_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT192DE.GetData(const Index: NativeInt): PKDT192DE_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT192DE.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT192DE.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT192DE.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT192DE_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT192DE.StoreBuffPtr: PKDT192DE_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT192DE.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT192DE_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT192DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT192DE.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT192DE_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT192DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT192DE.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT192DE_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT192DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT192DE.BuildKDTreeWithCluster(const inBuff: TKDT192DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT192DE_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT192DE_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT192DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT192DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT192DE.BuildKDTreeWithCluster(const inBuff: TKDT192DE_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT192DE.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT192DE_BuildCall);
var
TempStoreBuff: TKDT192DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT192DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT192DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT192DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT192DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT192DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT192DE.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT192DE_BuildMethod);
var
TempStoreBuff: TKDT192DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT192DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT192DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT192DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT192DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT192DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT192DE.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT192DE_BuildProc);
var
TempStoreBuff: TKDT192DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT192DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT192DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT192DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT192DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT192DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT192DE.Search(const buff: TKDT192DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT192DE_Node;
var
NearestNeighbour: PKDT192DE_Node;
function FindParentNode(const buffPtr: PKDT192DE_Vec; NodePtr: PKDT192DE_Node): PKDT192DE_Node;
var
Next: PKDT192DE_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT192DE_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT192DE_Node; const buffPtr: PKDT192DE_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT192DE_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT192DE_Vec; const p1, p2: PKDT192DE_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT192DE_Vec);
var
i, j: NativeInt;
p, t: PKDT192DE_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT192DE_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT192DE_Node(NearestNodes[0]);
end;
end;
function TKDT192DE.Search(const buff: TKDT192DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT192DE_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT192DE.Search(const buff: TKDT192DE_Vec; var SearchedDistanceMin: Double): PKDT192DE_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT192DE.Search(const buff: TKDT192DE_Vec): PKDT192DE_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT192DE.SearchToken(const buff: TKDT192DE_Vec): TPascalString;
var
p: PKDT192DE_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT192DE.Search(const inBuff: TKDT192DE_DynamicVecBuffer; var OutBuff: TKDT192DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT192DE_DynamicVecBuffer;
outBuffPtr: PKDT192DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT192DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT192DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT192DE_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT192DE.Search(const inBuff: TKDT192DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT192DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT192DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT192DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT192DE_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT192DE.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT192DE_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT192DE_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT192DE.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT192DE_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT192DE_Vec)) <> SizeOf(TKDT192DE_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT192DE.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT192DE.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT192DE.PrintNodeTree(const NodePtr: PKDT192DE_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT192DE_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT192DE.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT192DE.Vec(const s: SystemString): TKDT192DE_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT192DE_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT192DE_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT192DE.Vec(const v: TKDT192DE_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT192DE_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT192DE.Distance(const v1, v2: TKDT192DE_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT192DE_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT192DE.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT192DE_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT192DE.Test;
var
TKDT192DE_Test: TKDT192DE;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT192DE_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT192DE_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT192DE_Test := TKDT192DE.Create;
n.Append('...');
SetLength(TKDT192DE_Test.TestBuff, 1000);
for i := 0 to length(TKDT192DE_Test.TestBuff) - 1 do
for j := 0 to KDT192DE_Axis - 1 do
TKDT192DE_Test.TestBuff[i][j] := i * KDT192DE_Axis + j;
{$IFDEF FPC}
TKDT192DE_Test.BuildKDTreeM(length(TKDT192DE_Test.TestBuff), nil, @TKDT192DE_Test.Test_BuildM);
{$ELSE FPC}
TKDT192DE_Test.BuildKDTreeM(length(TKDT192DE_Test.TestBuff), nil, TKDT192DE_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT192DE_Test.SaveToStream(m64);
m64.Position := 0;
TKDT192DE_Test.LoadFromStream(m64);
for i := 0 to length(TKDT192DE_Test.TestBuff) - 1 do
begin
p := TKDT192DE_Test.Search(TKDT192DE_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT192DE_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT192DE_Test.TestBuff));
TKDT192DE_Test.Search(TKDT192DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT192DE_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT192DE_Test.Clear;
{ kMean test }
TKDT192DE_Test.BuildKDTreeWithCluster(TKDT192DE_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT192DE_Test.Search(TKDT192DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT192DE_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT192DE_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT192DE_Test);
DoStatus(n);
n := '';
end;
function TKDT256DE.InternalBuildKdTree(const KDSourceBufferPtr: PKDT256DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT256DE_Node;
function SortCompare(const p1, p2: PKDT256DE_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT256DE_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT256DE_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT256DE_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT256DE_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT256DE.GetData(const Index: NativeInt): PKDT256DE_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT256DE.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT256DE.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT256DE.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT256DE_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT256DE.StoreBuffPtr: PKDT256DE_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT256DE.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT256DE_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT256DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT256DE.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT256DE_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT256DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT256DE.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT256DE_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT256DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT256DE.BuildKDTreeWithCluster(const inBuff: TKDT256DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT256DE_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT256DE_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT256DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT256DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT256DE.BuildKDTreeWithCluster(const inBuff: TKDT256DE_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT256DE.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT256DE_BuildCall);
var
TempStoreBuff: TKDT256DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT256DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT256DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT256DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT256DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT256DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT256DE.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT256DE_BuildMethod);
var
TempStoreBuff: TKDT256DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT256DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT256DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT256DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT256DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT256DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT256DE.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT256DE_BuildProc);
var
TempStoreBuff: TKDT256DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT256DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT256DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT256DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT256DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT256DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT256DE.Search(const buff: TKDT256DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT256DE_Node;
var
NearestNeighbour: PKDT256DE_Node;
function FindParentNode(const buffPtr: PKDT256DE_Vec; NodePtr: PKDT256DE_Node): PKDT256DE_Node;
var
Next: PKDT256DE_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT256DE_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT256DE_Node; const buffPtr: PKDT256DE_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT256DE_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT256DE_Vec; const p1, p2: PKDT256DE_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT256DE_Vec);
var
i, j: NativeInt;
p, t: PKDT256DE_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT256DE_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT256DE_Node(NearestNodes[0]);
end;
end;
function TKDT256DE.Search(const buff: TKDT256DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT256DE_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT256DE.Search(const buff: TKDT256DE_Vec; var SearchedDistanceMin: Double): PKDT256DE_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT256DE.Search(const buff: TKDT256DE_Vec): PKDT256DE_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT256DE.SearchToken(const buff: TKDT256DE_Vec): TPascalString;
var
p: PKDT256DE_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT256DE.Search(const inBuff: TKDT256DE_DynamicVecBuffer; var OutBuff: TKDT256DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT256DE_DynamicVecBuffer;
outBuffPtr: PKDT256DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT256DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT256DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT256DE_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT256DE.Search(const inBuff: TKDT256DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT256DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT256DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT256DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT256DE_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT256DE.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT256DE_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT256DE_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT256DE.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT256DE_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT256DE_Vec)) <> SizeOf(TKDT256DE_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT256DE.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT256DE.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT256DE.PrintNodeTree(const NodePtr: PKDT256DE_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT256DE_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT256DE.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT256DE.Vec(const s: SystemString): TKDT256DE_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT256DE_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT256DE_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT256DE.Vec(const v: TKDT256DE_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT256DE_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT256DE.Distance(const v1, v2: TKDT256DE_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT256DE_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT256DE.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT256DE_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT256DE.Test;
var
TKDT256DE_Test: TKDT256DE;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT256DE_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT256DE_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT256DE_Test := TKDT256DE.Create;
n.Append('...');
SetLength(TKDT256DE_Test.TestBuff, 1000);
for i := 0 to length(TKDT256DE_Test.TestBuff) - 1 do
for j := 0 to KDT256DE_Axis - 1 do
TKDT256DE_Test.TestBuff[i][j] := i * KDT256DE_Axis + j;
{$IFDEF FPC}
TKDT256DE_Test.BuildKDTreeM(length(TKDT256DE_Test.TestBuff), nil, @TKDT256DE_Test.Test_BuildM);
{$ELSE FPC}
TKDT256DE_Test.BuildKDTreeM(length(TKDT256DE_Test.TestBuff), nil, TKDT256DE_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT256DE_Test.SaveToStream(m64);
m64.Position := 0;
TKDT256DE_Test.LoadFromStream(m64);
for i := 0 to length(TKDT256DE_Test.TestBuff) - 1 do
begin
p := TKDT256DE_Test.Search(TKDT256DE_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT256DE_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT256DE_Test.TestBuff));
TKDT256DE_Test.Search(TKDT256DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT256DE_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT256DE_Test.Clear;
{ kMean test }
TKDT256DE_Test.BuildKDTreeWithCluster(TKDT256DE_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT256DE_Test.Search(TKDT256DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT256DE_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT256DE_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT256DE_Test);
DoStatus(n);
n := '';
end;
function TKDT384DE.InternalBuildKdTree(const KDSourceBufferPtr: PKDT384DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT384DE_Node;
function SortCompare(const p1, p2: PKDT384DE_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT384DE_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT384DE_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT384DE_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT384DE_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT384DE.GetData(const Index: NativeInt): PKDT384DE_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT384DE.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT384DE.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT384DE.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT384DE_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT384DE.StoreBuffPtr: PKDT384DE_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT384DE.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT384DE_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT384DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT384DE.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT384DE_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT384DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT384DE.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT384DE_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT384DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT384DE.BuildKDTreeWithCluster(const inBuff: TKDT384DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT384DE_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT384DE_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT384DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT384DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT384DE.BuildKDTreeWithCluster(const inBuff: TKDT384DE_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT384DE.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT384DE_BuildCall);
var
TempStoreBuff: TKDT384DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT384DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT384DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT384DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT384DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT384DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT384DE.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT384DE_BuildMethod);
var
TempStoreBuff: TKDT384DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT384DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT384DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT384DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT384DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT384DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT384DE.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT384DE_BuildProc);
var
TempStoreBuff: TKDT384DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT384DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT384DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT384DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT384DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT384DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT384DE.Search(const buff: TKDT384DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT384DE_Node;
var
NearestNeighbour: PKDT384DE_Node;
function FindParentNode(const buffPtr: PKDT384DE_Vec; NodePtr: PKDT384DE_Node): PKDT384DE_Node;
var
Next: PKDT384DE_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT384DE_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT384DE_Node; const buffPtr: PKDT384DE_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT384DE_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT384DE_Vec; const p1, p2: PKDT384DE_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT384DE_Vec);
var
i, j: NativeInt;
p, t: PKDT384DE_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT384DE_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT384DE_Node(NearestNodes[0]);
end;
end;
function TKDT384DE.Search(const buff: TKDT384DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT384DE_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT384DE.Search(const buff: TKDT384DE_Vec; var SearchedDistanceMin: Double): PKDT384DE_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT384DE.Search(const buff: TKDT384DE_Vec): PKDT384DE_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT384DE.SearchToken(const buff: TKDT384DE_Vec): TPascalString;
var
p: PKDT384DE_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT384DE.Search(const inBuff: TKDT384DE_DynamicVecBuffer; var OutBuff: TKDT384DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT384DE_DynamicVecBuffer;
outBuffPtr: PKDT384DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT384DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT384DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT384DE_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT384DE.Search(const inBuff: TKDT384DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT384DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT384DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT384DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT384DE_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT384DE.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT384DE_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT384DE_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT384DE.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT384DE_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT384DE_Vec)) <> SizeOf(TKDT384DE_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT384DE.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT384DE.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT384DE.PrintNodeTree(const NodePtr: PKDT384DE_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT384DE_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT384DE.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT384DE.Vec(const s: SystemString): TKDT384DE_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT384DE_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT384DE_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT384DE.Vec(const v: TKDT384DE_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT384DE_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT384DE.Distance(const v1, v2: TKDT384DE_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT384DE_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT384DE.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT384DE_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT384DE.Test;
var
TKDT384DE_Test: TKDT384DE;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT384DE_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT384DE_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT384DE_Test := TKDT384DE.Create;
n.Append('...');
SetLength(TKDT384DE_Test.TestBuff, 1000);
for i := 0 to length(TKDT384DE_Test.TestBuff) - 1 do
for j := 0 to KDT384DE_Axis - 1 do
TKDT384DE_Test.TestBuff[i][j] := i * KDT384DE_Axis + j;
{$IFDEF FPC}
TKDT384DE_Test.BuildKDTreeM(length(TKDT384DE_Test.TestBuff), nil, @TKDT384DE_Test.Test_BuildM);
{$ELSE FPC}
TKDT384DE_Test.BuildKDTreeM(length(TKDT384DE_Test.TestBuff), nil, TKDT384DE_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT384DE_Test.SaveToStream(m64);
m64.Position := 0;
TKDT384DE_Test.LoadFromStream(m64);
for i := 0 to length(TKDT384DE_Test.TestBuff) - 1 do
begin
p := TKDT384DE_Test.Search(TKDT384DE_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT384DE_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT384DE_Test.TestBuff));
TKDT384DE_Test.Search(TKDT384DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT384DE_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT384DE_Test.Clear;
{ kMean test }
TKDT384DE_Test.BuildKDTreeWithCluster(TKDT384DE_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT384DE_Test.Search(TKDT384DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT384DE_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT384DE_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT384DE_Test);
DoStatus(n);
n := '';
end;
function TKDT512DE.InternalBuildKdTree(const KDSourceBufferPtr: PKDT512DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT512DE_Node;
function SortCompare(const p1, p2: PKDT512DE_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT512DE_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT512DE_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT512DE_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT512DE_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT512DE.GetData(const Index: NativeInt): PKDT512DE_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT512DE.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT512DE.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT512DE.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT512DE_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT512DE.StoreBuffPtr: PKDT512DE_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT512DE.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT512DE_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT512DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT512DE.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT512DE_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT512DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT512DE.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT512DE_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT512DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT512DE.BuildKDTreeWithCluster(const inBuff: TKDT512DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT512DE_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT512DE_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT512DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT512DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT512DE.BuildKDTreeWithCluster(const inBuff: TKDT512DE_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT512DE.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT512DE_BuildCall);
var
TempStoreBuff: TKDT512DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT512DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT512DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT512DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT512DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT512DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT512DE.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT512DE_BuildMethod);
var
TempStoreBuff: TKDT512DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT512DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT512DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT512DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT512DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT512DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT512DE.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT512DE_BuildProc);
var
TempStoreBuff: TKDT512DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT512DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT512DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT512DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT512DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT512DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT512DE.Search(const buff: TKDT512DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT512DE_Node;
var
NearestNeighbour: PKDT512DE_Node;
function FindParentNode(const buffPtr: PKDT512DE_Vec; NodePtr: PKDT512DE_Node): PKDT512DE_Node;
var
Next: PKDT512DE_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT512DE_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT512DE_Node; const buffPtr: PKDT512DE_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT512DE_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT512DE_Vec; const p1, p2: PKDT512DE_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT512DE_Vec);
var
i, j: NativeInt;
p, t: PKDT512DE_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT512DE_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT512DE_Node(NearestNodes[0]);
end;
end;
function TKDT512DE.Search(const buff: TKDT512DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT512DE_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT512DE.Search(const buff: TKDT512DE_Vec; var SearchedDistanceMin: Double): PKDT512DE_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT512DE.Search(const buff: TKDT512DE_Vec): PKDT512DE_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT512DE.SearchToken(const buff: TKDT512DE_Vec): TPascalString;
var
p: PKDT512DE_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT512DE.Search(const inBuff: TKDT512DE_DynamicVecBuffer; var OutBuff: TKDT512DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT512DE_DynamicVecBuffer;
outBuffPtr: PKDT512DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT512DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT512DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT512DE_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT512DE.Search(const inBuff: TKDT512DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT512DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT512DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT512DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT512DE_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT512DE.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT512DE_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT512DE_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT512DE.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT512DE_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT512DE_Vec)) <> SizeOf(TKDT512DE_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT512DE.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT512DE.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT512DE.PrintNodeTree(const NodePtr: PKDT512DE_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT512DE_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT512DE.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT512DE.Vec(const s: SystemString): TKDT512DE_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT512DE_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT512DE_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT512DE.Vec(const v: TKDT512DE_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT512DE_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT512DE.Distance(const v1, v2: TKDT512DE_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT512DE_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT512DE.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT512DE_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT512DE.Test;
var
TKDT512DE_Test: TKDT512DE;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT512DE_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT512DE_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT512DE_Test := TKDT512DE.Create;
n.Append('...');
SetLength(TKDT512DE_Test.TestBuff, 1000);
for i := 0 to length(TKDT512DE_Test.TestBuff) - 1 do
for j := 0 to KDT512DE_Axis - 1 do
TKDT512DE_Test.TestBuff[i][j] := i * KDT512DE_Axis + j;
{$IFDEF FPC}
TKDT512DE_Test.BuildKDTreeM(length(TKDT512DE_Test.TestBuff), nil, @TKDT512DE_Test.Test_BuildM);
{$ELSE FPC}
TKDT512DE_Test.BuildKDTreeM(length(TKDT512DE_Test.TestBuff), nil, TKDT512DE_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT512DE_Test.SaveToStream(m64);
m64.Position := 0;
TKDT512DE_Test.LoadFromStream(m64);
for i := 0 to length(TKDT512DE_Test.TestBuff) - 1 do
begin
p := TKDT512DE_Test.Search(TKDT512DE_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT512DE_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT512DE_Test.TestBuff));
TKDT512DE_Test.Search(TKDT512DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT512DE_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT512DE_Test.Clear;
{ kMean test }
TKDT512DE_Test.BuildKDTreeWithCluster(TKDT512DE_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT512DE_Test.Search(TKDT512DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT512DE_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT512DE_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT512DE_Test);
DoStatus(n);
n := '';
end;
function TKDT800DE.InternalBuildKdTree(const KDSourceBufferPtr: PKDT800DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT800DE_Node;
function SortCompare(const p1, p2: PKDT800DE_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT800DE_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT800DE_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT800DE_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT800DE_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT800DE.GetData(const Index: NativeInt): PKDT800DE_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT800DE.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT800DE.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT800DE.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT800DE_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT800DE.StoreBuffPtr: PKDT800DE_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT800DE.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT800DE_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT800DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT800DE.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT800DE_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT800DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT800DE.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT800DE_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT800DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT800DE.BuildKDTreeWithCluster(const inBuff: TKDT800DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT800DE_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT800DE_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT800DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT800DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT800DE.BuildKDTreeWithCluster(const inBuff: TKDT800DE_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT800DE.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT800DE_BuildCall);
var
TempStoreBuff: TKDT800DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT800DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT800DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT800DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT800DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT800DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT800DE.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT800DE_BuildMethod);
var
TempStoreBuff: TKDT800DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT800DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT800DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT800DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT800DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT800DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT800DE.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT800DE_BuildProc);
var
TempStoreBuff: TKDT800DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT800DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT800DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT800DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT800DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT800DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT800DE.Search(const buff: TKDT800DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT800DE_Node;
var
NearestNeighbour: PKDT800DE_Node;
function FindParentNode(const buffPtr: PKDT800DE_Vec; NodePtr: PKDT800DE_Node): PKDT800DE_Node;
var
Next: PKDT800DE_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT800DE_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT800DE_Node; const buffPtr: PKDT800DE_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT800DE_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT800DE_Vec; const p1, p2: PKDT800DE_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT800DE_Vec);
var
i, j: NativeInt;
p, t: PKDT800DE_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT800DE_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT800DE_Node(NearestNodes[0]);
end;
end;
function TKDT800DE.Search(const buff: TKDT800DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT800DE_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT800DE.Search(const buff: TKDT800DE_Vec; var SearchedDistanceMin: Double): PKDT800DE_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT800DE.Search(const buff: TKDT800DE_Vec): PKDT800DE_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT800DE.SearchToken(const buff: TKDT800DE_Vec): TPascalString;
var
p: PKDT800DE_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT800DE.Search(const inBuff: TKDT800DE_DynamicVecBuffer; var OutBuff: TKDT800DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT800DE_DynamicVecBuffer;
outBuffPtr: PKDT800DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT800DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT800DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT800DE_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT800DE.Search(const inBuff: TKDT800DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT800DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT800DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT800DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT800DE_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT800DE.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT800DE_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT800DE_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT800DE.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT800DE_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT800DE_Vec)) <> SizeOf(TKDT800DE_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT800DE.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT800DE.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT800DE.PrintNodeTree(const NodePtr: PKDT800DE_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT800DE_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT800DE.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT800DE.Vec(const s: SystemString): TKDT800DE_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT800DE_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT800DE_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT800DE.Vec(const v: TKDT800DE_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT800DE_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT800DE.Distance(const v1, v2: TKDT800DE_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT800DE_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT800DE.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT800DE_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT800DE.Test;
var
TKDT800DE_Test: TKDT800DE;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT800DE_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT800DE_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT800DE_Test := TKDT800DE.Create;
n.Append('...');
SetLength(TKDT800DE_Test.TestBuff, 1000);
for i := 0 to length(TKDT800DE_Test.TestBuff) - 1 do
for j := 0 to KDT800DE_Axis - 1 do
TKDT800DE_Test.TestBuff[i][j] := i * KDT800DE_Axis + j;
{$IFDEF FPC}
TKDT800DE_Test.BuildKDTreeM(length(TKDT800DE_Test.TestBuff), nil, @TKDT800DE_Test.Test_BuildM);
{$ELSE FPC}
TKDT800DE_Test.BuildKDTreeM(length(TKDT800DE_Test.TestBuff), nil, TKDT800DE_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT800DE_Test.SaveToStream(m64);
m64.Position := 0;
TKDT800DE_Test.LoadFromStream(m64);
for i := 0 to length(TKDT800DE_Test.TestBuff) - 1 do
begin
p := TKDT800DE_Test.Search(TKDT800DE_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT800DE_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT800DE_Test.TestBuff));
TKDT800DE_Test.Search(TKDT800DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT800DE_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT800DE_Test.Clear;
{ kMean test }
TKDT800DE_Test.BuildKDTreeWithCluster(TKDT800DE_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT800DE_Test.Search(TKDT800DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT800DE_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT800DE_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT800DE_Test);
DoStatus(n);
n := '';
end;
function TKDT1024DE.InternalBuildKdTree(const KDSourceBufferPtr: PKDT1024DE_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT1024DE_Node;
function SortCompare(const p1, p2: PKDT1024DE_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT1024DE_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT1024DE_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT1024DE_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT1024DE_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT1024DE.GetData(const Index: NativeInt): PKDT1024DE_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT1024DE.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT1024DE.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT1024DE.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT1024DE_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT1024DE.StoreBuffPtr: PKDT1024DE_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT1024DE.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1024DE_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT1024DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT1024DE.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1024DE_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT1024DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT1024DE.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1024DE_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT1024DE_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT1024DE.BuildKDTreeWithCluster(const inBuff: TKDT1024DE_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT1024DE_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT1024DE_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT1024DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT1024DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT1024DE.BuildKDTreeWithCluster(const inBuff: TKDT1024DE_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT1024DE.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1024DE_BuildCall);
var
TempStoreBuff: TKDT1024DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT1024DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT1024DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT1024DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT1024DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT1024DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT1024DE.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1024DE_BuildMethod);
var
TempStoreBuff: TKDT1024DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT1024DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT1024DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT1024DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT1024DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT1024DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT1024DE.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1024DE_BuildProc);
var
TempStoreBuff: TKDT1024DE_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT1024DE_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT1024DE_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT1024DE_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT1024DE_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT1024DE_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT1024DE.Search(const buff: TKDT1024DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT1024DE_Node;
var
NearestNeighbour: PKDT1024DE_Node;
function FindParentNode(const buffPtr: PKDT1024DE_Vec; NodePtr: PKDT1024DE_Node): PKDT1024DE_Node;
var
Next: PKDT1024DE_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT1024DE_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT1024DE_Node; const buffPtr: PKDT1024DE_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT1024DE_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT1024DE_Vec; const p1, p2: PKDT1024DE_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT1024DE_Vec);
var
i, j: NativeInt;
p, t: PKDT1024DE_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT1024DE_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT1024DE_Node(NearestNodes[0]);
end;
end;
function TKDT1024DE.Search(const buff: TKDT1024DE_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT1024DE_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT1024DE.Search(const buff: TKDT1024DE_Vec; var SearchedDistanceMin: Double): PKDT1024DE_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT1024DE.Search(const buff: TKDT1024DE_Vec): PKDT1024DE_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT1024DE.SearchToken(const buff: TKDT1024DE_Vec): TPascalString;
var
p: PKDT1024DE_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT1024DE.Search(const inBuff: TKDT1024DE_DynamicVecBuffer; var OutBuff: TKDT1024DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT1024DE_DynamicVecBuffer;
outBuffPtr: PKDT1024DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT1024DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT1024DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT1024DE_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT1024DE.Search(const inBuff: TKDT1024DE_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT1024DE_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT1024DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT1024DE_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT1024DE_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT1024DE.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT1024DE_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT1024DE_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT1024DE.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT1024DE_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT1024DE_Vec)) <> SizeOf(TKDT1024DE_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT1024DE.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT1024DE.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT1024DE.PrintNodeTree(const NodePtr: PKDT1024DE_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT1024DE_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT1024DE.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT1024DE.Vec(const s: SystemString): TKDT1024DE_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT1024DE_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT1024DE_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT1024DE.Vec(const v: TKDT1024DE_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT1024DE_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT1024DE.Distance(const v1, v2: TKDT1024DE_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT1024DE_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT1024DE.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT1024DE_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT1024DE.Test;
var
TKDT1024DE_Test: TKDT1024DE;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT1024DE_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT1024DE_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT1024DE_Test := TKDT1024DE.Create;
n.Append('...');
SetLength(TKDT1024DE_Test.TestBuff, 1000);
for i := 0 to length(TKDT1024DE_Test.TestBuff) - 1 do
for j := 0 to KDT1024DE_Axis - 1 do
TKDT1024DE_Test.TestBuff[i][j] := i * KDT1024DE_Axis + j;
{$IFDEF FPC}
TKDT1024DE_Test.BuildKDTreeM(length(TKDT1024DE_Test.TestBuff), nil, @TKDT1024DE_Test.Test_BuildM);
{$ELSE FPC}
TKDT1024DE_Test.BuildKDTreeM(length(TKDT1024DE_Test.TestBuff), nil, TKDT1024DE_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT1024DE_Test.SaveToStream(m64);
m64.Position := 0;
TKDT1024DE_Test.LoadFromStream(m64);
for i := 0 to length(TKDT1024DE_Test.TestBuff) - 1 do
begin
p := TKDT1024DE_Test.Search(TKDT1024DE_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT1024DE_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT1024DE_Test.TestBuff));
TKDT1024DE_Test.Search(TKDT1024DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT1024DE_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT1024DE_Test.Clear;
{ kMean test }
TKDT1024DE_Test.BuildKDTreeWithCluster(TKDT1024DE_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT1024DE_Test.Search(TKDT1024DE_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT1024DE_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT1024DE_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT1024DE_Test);
DoStatus(n);
n := '';
end;
procedure Test_All;
begin
TKDT1DE.Test();
TKDT2DE.Test();
TKDT3DE.Test();
TKDT4DE.Test();
TKDT5DE.Test();
TKDT6DE.Test();
TKDT7DE.Test();
TKDT8DE.Test();
TKDT9DE.Test();
TKDT10DE.Test();
TKDT11DE.Test();
TKDT12DE.Test();
TKDT13DE.Test();
TKDT14DE.Test();
TKDT15DE.Test();
TKDT16DE.Test();
TKDT17DE.Test();
TKDT18DE.Test();
TKDT19DE.Test();
TKDT20DE.Test();
TKDT21DE.Test();
TKDT22DE.Test();
TKDT23DE.Test();
TKDT24DE.Test();
TKDT48DE.Test();
TKDT52DE.Test();
TKDT64DE.Test();
TKDT96DE.Test();
TKDT128DE.Test();
TKDT156DE.Test();
TKDT192DE.Test();
TKDT256DE.Test();
TKDT384DE.Test();
TKDT512DE.Test();
TKDT800DE.Test();
TKDT1024DE.Test();
end;
initialization
finalization
end.
|
object DlgProperties: TDlgProperties
Left = 8
Top = 8
ActiveControl = cbPort
BorderIcons = [biSystemMenu]
BorderStyle = bsDialog
Caption = 'Options'
ClientHeight = 371
ClientWidth = 568
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
OldCreateOrder = True
Position = poScreenCenter
Scaled = False
OnCreate = FormCreate
DesignSize = (
568
371)
PixelsPerInch = 96
TextHeight = 13
object OkButton: TButton
Left = 403
Top = 338
Width = 75
Height = 25
Anchors = [akRight, akBottom]
Cancel = True
Caption = 'OK'
Default = True
ModalResult = 1
TabOrder = 1
end
object CancelButton: TButton
Left = 485
Top = 338
Width = 75
Height = 25
Anchors = [akRight, akBottom]
Cancel = True
Caption = 'Cancel'
ModalResult = 2
TabOrder = 2
end
object PageControl1: TPageControl
Left = 9
Top = 8
Width = 551
Height = 323
ActivePage = TabConnection
Anchors = [akLeft, akTop, akRight, akBottom]
TabOrder = 0
object TabConnection: TTabSheet
Caption = '&Connection'
DesignSize = (
543
295)
object GroupBox1: TGroupBox
Left = 8
Top = 3
Width = 526
Height = 281
Anchors = [akLeft, akTop, akRight, akBottom]
TabOrder = 0
DesignSize = (
526
281)
object Label1: TLabel
Left = 8
Top = 17
Width = 24
Height = 13
Caption = '&Port:'
FocusControl = cbPort
end
object Label2: TLabel
Left = 8
Top = 78
Width = 62
Height = 13
Caption = '&Search Path:'
FocusControl = edPath
end
object Label3: TLabel
Left = 8
Top = 48
Width = 61
Height = 13
Caption = '&Default URL:'
FocusControl = edDefault
end
object Label6: TLabel
Left = 8
Top = 109
Width = 47
Height = 13
Caption = '&UDP Port:'
FocusControl = cbUDPPort
end
object Label7: TLabel
Left = 8
Top = 140
Width = 43
Height = 13
Caption = '&Browser:'
FocusControl = cbUDPPort
end
object cbPort: TEdit
Left = 88
Top = 13
Width = 65
Height = 21
TabOrder = 1
Text = 'cbPort'
OnKeyPress = NumericKeyPress
end
object cbActiveAtStartup: TCheckBox
Left = 185
Top = 16
Width = 144
Height = 17
Caption = '&Activate at Startup'
TabOrder = 2
end
object edDefault: TEdit
Left = 88
Top = 45
Width = 424
Height = 21
Anchors = [akLeft, akTop, akRight]
TabOrder = 3
Text = 'edDefault'
end
object edPath: TEdit
Left = 88
Top = 75
Width = 424
Height = 21
Anchors = [akLeft, akTop, akRight]
TabOrder = 4
Text = 'edPath'
end
object cbUDPPort: TEdit
Left = 88
Top = 105
Width = 65
Height = 21
TabOrder = 0
Text = 'cbPort'
OnKeyPress = NumericKeyPress
end
object edBrowser: TEdit
Left = 88
Top = 136
Width = 217
Height = 21
TabOrder = 5
Text = 'mozilla'
end
end
end
object TabLog: TTabSheet
Caption = '&Log'
ImageIndex = 1
DesignSize = (
543
295)
object GroupBox2: TGroupBox
Left = 8
Top = 8
Width = 527
Height = 196
Anchors = [akLeft, akTop, akRight, akBottom]
Caption = '&Show in Log'
TabOrder = 0
DesignSize = (
527
196)
inline LogColSettingsFrame: TLogColSettingsFrame
Left = 9
Top = 24
Width = 508
Height = 156
Anchors = [akLeft, akTop, akRight, akBottom]
TabOrder = 0
TabStop = True
ExplicitLeft = 9
ExplicitTop = 24
ExplicitWidth = 508
ExplicitHeight = 156
inherited lvColumns: TListView
Width = 508
Height = 156
ExplicitWidth = 508
ExplicitHeight = 156
end
end
end
object GroupBox6: TGroupBox
Left = 8
Top = 212
Width = 527
Height = 73
Anchors = [akLeft, akRight, akBottom]
Caption = ' Log S&ize '
TabOrder = 1
DesignSize = (
527
73)
object Label4: TLabel
Left = 10
Top = 21
Width = 60
Height = 13
Anchors = [akLeft, akBottom]
Caption = 'Ma&x Events:'
FocusControl = edLogMax
end
object Label5: TLabel
Left = 11
Top = 45
Width = 137
Height = 13
Anchors = [akLeft, akBottom]
Caption = '&Delete when max exceeded:'
FocusControl = edLogDelete
end
object edLogMax: TEdit
Left = 85
Top = 17
Width = 41
Height = 21
Anchors = [akLeft, akBottom]
TabOrder = 0
OnKeyPress = NumericKeyPress
end
object edLogDelete: TEdit
Left = 173
Top = 41
Width = 41
Height = 21
Anchors = [akLeft, akBottom]
TabOrder = 1
OnKeyPress = NumericKeyPress
end
end
end
end
end
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Vcl.CmAdmCtl;
{$HPPEMIT LEGACYHPP}
interface
uses Winapi.Windows, Winapi.ActiveX, System.Classes, Vcl.Graphics, Vcl.OleServer, Vcl.OleCtrls, System.Win.StdVCL, Winapi.COMAdmin;
type
CoCOMAdminCatalog = class
class function Create: ICOMAdminCatalog;
end;
TCOMAdminCatalogCollection = class;
TCOMAdminCatalog = class(TOleServer)
private
FIntf: ICOMAdminCatalog;
function GetDefaultInterface: ICOMAdminCatalog;
protected
procedure InitServerData; override;
public
{ TOleServer }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Connect; override;
procedure ConnectTo(svrIntf: ICOMAdminCatalog);
procedure Disconnect; override;
{ICOMAdminCatalog }
function GetCollection(const bstrCollName: WideString):
TCOMAdminCatalogCollection;
function ICOMAdminCatalog_Connect(const bstrConnectString: WideString):
TCOMAdminCatalogCollection;
function Get_MajorVersion: Integer;
function Get_MinorVersion: Integer;
function GetCollectionByQuery(const bstrCollName: WideString;
var aQuery: PSafeArray):
TCOMAdminCatalogCollection;
procedure ImportComponent(const bstrApplIdOrName: WideString;
const bstrCLSIDOrProgId: WideString);
procedure InstallComponent(const bstrApplIdOrName: WideString;
const bstrDLL: WideString;
const bstrTLB: WideString;
const bstrPSDLL: WideString);
procedure ShutdownApplication(const bstrApplIdOrName: WideString);
procedure ExportApplication(const bstrApplIdOrName: WideString;
const bstrApplicationFile: WideString;
lOptions: Integer);
procedure InstallApplication(const bstrApplicationFile: WideString;
const bstrDestinationDirectory: WideString;
lOptions: Integer;const bstrUserId: WideString;
const bstrPassword: WideString;
const bstrRSN: WideString);
procedure StopRouter;
procedure RefreshRouter;
procedure StartRouter;
procedure InstallMultipleComponents(const bstrApplIdOrName: WideString;
var varFileNames: PSafeArray;
var varCLSIDS: PSafeArray);
procedure GetMultipleComponentsInfo(const bstrApplIdOrName: WideString;
var varFileNames: PSafeArray;
out varCLSIDS: PSafeArray;
out varClassNames: PSafeArray;
out varFileFlags: PSafeArray;
out varComponentFlags: PSafeArray);
procedure RefreshComponents;
procedure BackupREGDB(const bstrBackupFilePath: WideString);
procedure RestoreREGDB(const bstrBackupFilePath: WideString);
procedure QueryApplicationFile(const bstrApplicationFile: WideString;
out bstrApplicationName: WideString;
out bstrApplicationDescription: WideString;
out bHasUsers: WordBool;
out bIsProxy: WordBool;
out varFileNames: PSafeArray);
procedure StartApplication(const bstrApplIdOrName: WideString);
function ServiceCheck(lService: Integer): Integer;
procedure InstallMultipleEventClasses(const bstrApplIdOrName: WideString;
var varFileNames: PSafeArray;
var varCLSIDS: PSafeArray);
procedure InstallEventClass(const bstrApplIdOrName: WideString;
const bstrDLL: WideString;
const bstrTLB: WideString;
const bstrPSDLL: WideString);
procedure GetEventClassesForIID(const bstrIID: WideString;
out varCLSIDS: PSafeArray;
out varProgIDs: PSafeArray;
out varDescriptions: PSafeArray);
{ properties }
property DefaultInterface: ICOMAdminCatalog read GetDefaultInterface;
property MajorVersion: Integer read Get_MajorVersion;
property MinorVersion: Integer read Get_MinorVersion;
end;
CoCOMAdminCatalogObject = class
class function Create: ICatalogObject;
end;
TCOMAdminCatalogObject = class(TOleServer)
private
FIntf: ICatalogObject;
function GetDefaultInterface: ICatalogObject;
protected
procedure InitServerData; override;
public
{ TOleServer }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Connect; override;
procedure ConnectTo(svrIntf: ICatalogObject);
procedure Disconnect; override;
{ ICatalogObject }
function Get_Value(const bstrPropName: WideString): OleVariant;
procedure Set_Value(const bstrPropName: WideString; retval: OleVariant);
function Get_Key: OleVariant;
function Get_Name: OleVariant;
function IsPropertyReadOnly(const bstrPropName: WideString): WordBool;
function Get_Valid: WordBool;
function IsPropertyWriteOnly(const bstrPropName: WideString): WordBool;
property Value[const bstrPropName: WideString]: OleVariant read Get_Value
write Set_Value;
property DefaultInterface: ICatalogObject read GetDefaultInterface;
property Key: OleVariant read Get_Key;
property Name: OleVariant read Get_Name;
property Valid: WordBool read Get_Valid;
end;
CoCOMAdminCatalogCollection = class
class function Create: ICatalogCollection;
end;
TCOMAdminCatalogCollection = class(TOleServer)
private
FIntf: ICatalogCollection;
function GetDefaultInterface: ICatalogCollection;
protected
procedure InitServerData; override;
public
{ TOleServer }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Connect; override;
procedure ConnectTo(svrIntf: ICatalogCollection);
procedure Disconnect; override;
{ ICatalogCollection }
function Get_Item(lIndex: Integer): TCOMAdminCatalogObject;
function Get_Count: Integer;
procedure Remove(lIndex: Integer);
function Add: TCOMAdminCatalogObject;
procedure Populate;
function SaveChanges: Integer;
function GetCollection(const bstrCollName: WideString;
varObjectKey: OleVariant):
TCOMAdminCatalogCollection;
function Get_Name: OleVariant;
function Get_AddEnabled: WordBool;
function Get_RemoveEnabled: WordBool;
function GetUtilInterface: IDispatch;
function Get_DataStoreMajorVersion: Integer;
function Get_DataStoreMinorVersion: Integer;
procedure PopulateByKey(aKeys: PSafeArray);
procedure PopulateByQuery(const bstrQueryString: WideString;
lQueryType: Integer);
{ properties }
property DefaultInterface: ICatalogCollection read GetDefaultInterface;
property Count: Integer read Get_Count;
property Name: OleVariant read Get_Name;
property AddEnabled: WordBool read Get_AddEnabled;
property RemoveEnabled: WordBool read Get_RemoveEnabled;
property DataStoreMajorVersion: Integer read Get_DataStoreMajorVersion;
property DataStoreMinorVersion: Integer read Get_DataStoreMinorVersion;
end;
implementation
uses System.Win.ComObj;
class function CoCOMAdminCatalog.Create: ICOMAdminCatalog;
begin
Result := CreateComObject(CLASS_COMAdminCatalog) as ICOMAdminCatalog;
end;
procedure TCOMAdminCatalog.InitServerData;
const
CServerData: TServerData = (
ClassID: '{F618C514-DFB8-11D1-A2CF-00805FC79235}';
IntfIID: '{DD662187-DFC2-11D1-A2CF-00805FC79235}';
EventIID: '';
LicenseKey: nil;
Version: 500);
begin
ServerData := @CServerData;
end;
procedure TCOMAdminCatalog.Connect;
var
punk: IUnknown;
begin
if FIntf = nil then
begin
punk := GetServer;
Fintf:= punk as ICOMAdminCatalog;
end;
end;
procedure TCOMAdminCatalog.ConnectTo(svrIntf: ICOMAdminCatalog);
begin
Disconnect;
FIntf := svrIntf;
end;
procedure TCOMAdminCatalog.DisConnect;
begin
if Fintf <> nil then
begin
FIntf := nil;
end;
end;
function TCOMAdminCatalog.GetDefaultInterface: ICOMAdminCatalog;
begin
if FIntf = nil then
Connect;
Result := FIntf;
end;
constructor TCOMAdminCatalog.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
end;
destructor TCOMAdminCatalog.Destroy;
begin
inherited Destroy;
end;
function TCOMAdminCatalog.Get_MajorVersion: Integer;
begin
Result := DefaultInterface.Get_MajorVersion;
end;
function TCOMAdminCatalog.Get_MinorVersion: Integer;
begin
Result := DefaultInterface.Get_MinorVersion;
end;
function TCOMAdminCatalog.GetCollection(const bstrCollName: WideString):
TCOMAdminCatalogCollection;
begin
Result := TCOMAdminCatalogCollection.Create(Self);
Result.ConnectTo(DefaultInterface.GetCollection(bstrCollName) as
ICatalogCollection);
end;
function TCOMAdminCatalog.ICOMAdminCatalog_Connect(
const bstrConnectString: WideString): TCOMAdminCatalogCollection;
begin
Result := TCOMAdminCatalogCollection.Create(Self);
Result.ConnectTo(DefaultInterface.Connect(bstrConnectString) as ICatalogCollection);
end;
function TCOMAdminCatalog.GetCollectionByQuery(const bstrCollName: WideString;
var aQuery: PSafeArray):
TCOMAdminCatalogCollection;
begin
Result := TCOMAdminCatalogCollection.Create(Self);
Result.ConnectTo(DefaultInterface.GetCollectionByQuery(bstrCollName, aQuery) as ICatalogCollection);
end;
procedure TCOMAdminCatalog.ImportComponent(const bstrApplIdOrName: WideString;
const bstrCLSIDOrProgId: WideString);
begin
DefaultInterface.ImportComponent(bstrApplIdOrName, bstrCLSIDOrProgId);
end;
procedure TCOMAdminCatalog.InstallComponent(const bstrApplIdOrName: WideString;
const bstrDLL: WideString; const bstrTLB: WideString;
const bstrPSDLL: WideString);
begin
DefaultInterface.InstallComponent(bstrApplIdOrName, bstrDLL, bstrTLB, bstrPSDLL);
end;
procedure TCOMAdminCatalog.ShutdownApplication(const bstrApplIdOrName: WideString);
begin
DefaultInterface.ShutdownApplication(bstrApplIdOrName);
end;
procedure TCOMAdminCatalog.ExportApplication(const bstrApplIdOrName: WideString;
const bstrApplicationFile: WideString;
lOptions: Integer);
begin
DefaultInterface.ExportApplication(bstrApplIdOrName, bstrApplicationFile, lOptions);
end;
procedure TCOMAdminCatalog.InstallApplication(const bstrApplicationFile: WideString;
const bstrDestinationDirectory: WideString;
lOptions: Integer; const bstrUserId: WideString;
const bstrPassword: WideString;
const bstrRSN: WideString);
begin
DefaultInterface.InstallApplication(bstrApplicationFile, bstrDestinationDirectory, lOptions,
bstrUserId, bstrPassword, bstrRSN);
end;
procedure TCOMAdminCatalog.StopRouter;
begin
DefaultInterface.StopRouter;
end;
procedure TCOMAdminCatalog.RefreshRouter;
begin
DefaultInterface.RefreshRouter;
end;
procedure TCOMAdminCatalog.StartRouter;
begin
DefaultInterface.StartRouter;
end;
procedure TCOMAdminCatalog.InstallMultipleComponents(const bstrApplIdOrName: WideString;
var varFileNames: PSafeArray;
var varCLSIDS: PSafeArray);
begin
DefaultInterface.InstallMultipleComponents(bstrApplIdOrName, varFileNames, varCLSIDS);
end;
procedure TCOMAdminCatalog.GetMultipleComponentsInfo(const bstrApplIdOrName: WideString;
var varFileNames: PSafeArray;
out varCLSIDS: PSafeArray;
out varClassNames: PSafeArray;
out varFileFlags: PSafeArray;
out varComponentFlags: PSafeArray);
begin
DefaultInterface.GetMultipleComponentsInfo(bstrApplIdOrName, varFileNames, varCLSIDS,
varClassNames, varFileFlags, varComponentFlags);
end;
procedure TCOMAdminCatalog.RefreshComponents;
begin
DefaultInterface.RefreshComponents;
end;
procedure TCOMAdminCatalog.BackupREGDB(const bstrBackupFilePath: WideString);
begin
DefaultInterface.BackupREGDB(bstrBackupFilePath);
end;
procedure TCOMAdminCatalog.RestoreREGDB(const bstrBackupFilePath: WideString);
begin
DefaultInterface.RestoreREGDB(bstrBackupFilePath);
end;
procedure TCOMAdminCatalog.QueryApplicationFile(const bstrApplicationFile: WideString;
out bstrApplicationName: WideString;
out bstrApplicationDescription: WideString;
out bHasUsers: WordBool; out bIsProxy: WordBool;
out varFileNames: PSafeArray);
begin
DefaultInterface.QueryApplicationFile(bstrApplicationFile, bstrApplicationName,
bstrApplicationDescription, bHasUsers, bIsProxy,
varFileNames);
end;
procedure TCOMAdminCatalog.StartApplication(const bstrApplIdOrName: WideString);
begin
DefaultInterface.StartApplication(bstrApplIdOrName);
end;
function TCOMAdminCatalog.ServiceCheck(lService: Integer): Integer;
begin
Result := DefaultInterface.ServiceCheck(lService);
end;
procedure TCOMAdminCatalog.InstallMultipleEventClasses(const bstrApplIdOrName: WideString;
var varFileNames: PSafeArray;
var varCLSIDS: PSafeArray);
begin
DefaultInterface.InstallMultipleEventClasses(bstrApplIdOrName, varFileNames, varCLSIDS);
end;
procedure TCOMAdminCatalog.InstallEventClass(const bstrApplIdOrName: WideString;
const bstrDLL: WideString; const bstrTLB: WideString;
const bstrPSDLL: WideString);
begin
DefaultInterface.InstallEventClass(bstrApplIdOrName, bstrDLL, bstrTLB, bstrPSDLL);
end;
procedure TCOMAdminCatalog.GetEventClassesForIID(const bstrIID: WideString;
out varCLSIDS: PSafeArray;
out varProgIDs: PSafeArray;
out varDescriptions: PSafeArray);
begin
DefaultInterface.GetEventClassesForIID(bstrIID, varCLSIDS, varProgIDs, varDescriptions);
end;
class function CoCOMAdminCatalogObject.Create: ICatalogObject;
begin
Result := CreateComObject(CLASS_COMAdminCatalogObject) as ICatalogObject;
end;
procedure TCOMAdminCatalogObject.InitServerData;
const
CServerData: TServerData = (
ClassID: '{F618C515-DFB8-11D1-A2CF-00805FC79235}';
IntfIID: '{6EB22871-8A19-11D0-81B6-00A0C9231C29}';
EventIID: '';
LicenseKey: nil;
Version: 500);
begin
ServerData := @CServerData;
end;
procedure TCOMAdminCatalogObject.Connect;
var
punk: IUnknown;
begin
if FIntf = nil then
begin
punk := GetServer;
Fintf:= punk as ICatalogObject;
end;
end;
procedure TCOMAdminCatalogObject.ConnectTo(svrIntf: ICatalogObject);
begin
Disconnect;
FIntf := svrIntf;
end;
procedure TCOMAdminCatalogObject.DisConnect;
begin
if Fintf <> nil then
begin
FIntf := nil;
end;
end;
function TCOMAdminCatalogObject.GetDefaultInterface: ICatalogObject;
begin
if FIntf = nil then
Connect;
Assert(FIntf <> nil, 'DefaultInterface is NULL. Component is not connected to Server. You must call ''Connect'' or ''ConnectTo'' before this operation');
Result := FIntf;
end;
constructor TCOMAdminCatalogObject.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
end;
destructor TCOMAdminCatalogObject.Destroy;
begin
inherited Destroy;
end;
function TCOMAdminCatalogObject.Get_Value(const bstrPropName: WideString): OleVariant;
begin
Result := DefaultInterface.Get_Value(bstrPropName);
end;
procedure TCOMAdminCatalogObject.Set_Value(const bstrPropName: WideString; retval: OleVariant);
begin
DefaultInterface.Set_Value(bstrPropName, retval);
end;
function TCOMAdminCatalogObject.Get_Key: OleVariant;
begin
Result := DefaultInterface.Get_Key;
end;
function TCOMAdminCatalogObject.Get_Name: OleVariant;
begin
Result := DefaultInterface.Get_Name;
end;
function TCOMAdminCatalogObject.Get_Valid: WordBool;
begin
Result := DefaultInterface.Get_Valid;
end;
function TCOMAdminCatalogObject.IsPropertyReadOnly(const bstrPropName: WideString): WordBool;
begin
Result := DefaultInterface.IsPropertyReadOnly(bstrPropName);
end;
function TCOMAdminCatalogObject.IsPropertyWriteOnly(const bstrPropName: WideString): WordBool;
begin
Result := DefaultInterface.IsPropertyWriteOnly(bstrPropName);
end;
class function CoCOMAdminCatalogCollection.Create: ICatalogCollection;
begin
Result := CreateComObject(CLASS_COMAdminCatalogCollection) as ICatalogCollection;
end;
procedure TCOMAdminCatalogCollection.InitServerData;
const
CServerData: TServerData = (
ClassID: '{F618C516-DFB8-11D1-A2CF-00805FC79235}';
IntfIID: '{6EB22872-8A19-11D0-81B6-00A0C9231C29}';
EventIID: '';
LicenseKey: nil;
Version: 500);
begin
ServerData := @CServerData;
end;
procedure TCOMAdminCatalogCollection.Connect;
var
punk: IUnknown;
begin
if FIntf = nil then
begin
punk := GetServer;
Fintf:= punk as ICatalogCollection;
end;
end;
procedure TCOMAdminCatalogCollection.ConnectTo(svrIntf: ICatalogCollection);
begin
Disconnect;
FIntf := svrIntf;
end;
procedure TCOMAdminCatalogCollection.DisConnect;
begin
if Fintf <> nil then
begin
FIntf := nil;
end;
end;
function TCOMAdminCatalogCollection.GetDefaultInterface: ICatalogCollection;
begin
if FIntf = nil then
Connect;
Assert(FIntf <> nil, 'DefaultInterface is NULL. Component is not connected to Server. You must call ''Connect'' or ''ConnectTo'' before this operation');
Result := FIntf;
end;
constructor TCOMAdminCatalogCollection.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
end;
destructor TCOMAdminCatalogCollection.Destroy;
begin
inherited Destroy;
end;
function TCOMAdminCatalogCollection.Get_Item(lIndex: Integer): TCOMAdminCatalogObject;
begin
Result := TCOMAdminCatalogObject.Create(Self);
Result.ConnectTo( DefaultInterface.Get_Item(lIndex) as ICatalogObject);
end;
function TCOMAdminCatalogCollection.Get_Count: Integer;
begin
Result := DefaultInterface.Get_Count;
end;
function TCOMAdminCatalogCollection.Get_Name: OleVariant;
begin
Result := DefaultInterface.Get_Name;
end;
function TCOMAdminCatalogCollection.Get_AddEnabled: WordBool;
begin
Result := DefaultInterface.Get_AddEnabled;
end;
function TCOMAdminCatalogCollection.Get_RemoveEnabled: WordBool;
begin
Result := DefaultInterface.Get_RemoveEnabled;
end;
function TCOMAdminCatalogCollection.Get_DataStoreMajorVersion: Integer;
begin
Result := DefaultInterface.Get_DataStoreMajorVersion;
end;
function TCOMAdminCatalogCollection.Get_DataStoreMinorVersion: Integer;
begin
Result := DefaultInterface.Get_DataStoreMinorVersion;
end;
procedure TCOMAdminCatalogCollection.Remove(lIndex: Integer);
begin
DefaultInterface.Remove(lIndex);
end;
function TCOMAdminCatalogCollection.Add: TCOMAdminCatalogObject;
begin
Result := TCOMAdminCatalogObject.Create(Self);
Result.ConnectTo( DefaultInterface.Add() as ICatalogObject);
end;
procedure TCOMAdminCatalogCollection.Populate;
begin
DefaultInterface.Populate;
end;
function TCOMAdminCatalogCollection.SaveChanges: Integer;
begin
Result := DefaultInterface.SaveChanges;
end;
function TCOMAdminCatalogCollection.GetCollection(const bstrCollName: WideString;
varObjectKey: OleVariant):
TCOMAdminCatalogCollection;
begin
Result := TCOMAdminCatalogCollection.Create(Self);
Result.ConnectTo( DefaultInterface.GetCollection(bstrCollName, varObjectKey)
as ICatalogCollection);
end;
function TCOMAdminCatalogCollection.GetUtilInterface: IDispatch;
begin
Result := DefaultInterface.GetUtilInterface;
end;
procedure TCOMAdminCatalogCollection.PopulateByKey(aKeys: PSafeArray);
begin
DefaultInterface.PopulateByKey(aKeys);
end;
procedure TCOMAdminCatalogCollection.PopulateByQuery(const bstrQueryString: WideString;
lQueryType: Integer);
begin
DefaultInterface.PopulateByQuery(bstrQueryString, lQueryType);
end;
end.
|
unit WebServer.HTTPCore;
interface
uses
System.SysUtils,
System.Types,
System.Classes,
System.Threading,
System.Net.Socket,
System.Generics.Collections,
System.SyncObjs,
WebServer.HTTPConnectedClient,
App.IHandlerCore,
Net.ConnectedClient,
WebServer.HTTPServer,
WebServer.HTTPTypes;
type
TWebServer = class
private
Server: THTTPServer;
FHandler: IBaseHandler;
Request: String;
NeedDestroySelf: Boolean;
procedure Handle(From: THTTPConnectedClient; AData: TBytes);
procedure NewConHandle(SocketIP: String);
procedure DiscClientHandle(SocketIP: String);
procedure DeleteConnectedClient(AID: integer);
function GetServerStatus: boolean;
function GetFreeArraySell: integer;
public
ConnectedClients: TArray<THTTPConnectedClient>;
constructor Create(const AHandler: IBaseHandler);
property ServerStarted: boolean read GetServerStatus;
property Handler: IBaseHandler read FHandler write FHandler;
property DestroyNetCore: Boolean write NeedDestroySelf;
// function DoApiRequest(Request: TRequest; Response: TResponse): Boolean;
procedure Start;
procedure Stop;
function IsActive: Boolean;
destructor Destroy; override;
end;
implementation
{ TWebServer }
constructor TWebServer.Create(const AHandler: IBaseHandler);
var
id: integer;
begin
Request := '';
NeedDestroySelf := False;
SetLength(ConnectedClients, 0);
Server := THTTPServer.Create;
FHandler := AHandler;
Server.AcceptHandle := (
procedure(ConnectedCli: THTTPConnectedClient)
begin
ConnectedCli.Handle := Handle;
id := GetFreeArraySell;
ConnectedCli.IdInArray := id;
ConnectedCli.AfterDisconnect := DeleteConnectedClient;
ConnectedClients[id] := ConnectedCli;
end);
Server.NewConnectHandle := NewConHandle;
end;
procedure TWebServer.DeleteConnectedClient(AID: integer);
begin
DiscClientHandle(ConnectedClients[AID].GetSocketIP);
ConnectedClients[AID] := nil;
end;
destructor TWebServer.Destroy;
begin
Server.Free;
Server := nil;
SetLength(ConnectedClients, 0);
FHandler := nil;
end;
procedure TWebServer.DiscClientHandle(SocketIP: String);
begin
FHandler.HandleDisconnectClient(SocketIP);
end;
function TWebServer.GetFreeArraySell: integer;
var
i, len: integer;
begin
len := Length(ConnectedClients);
Result := len;
for i := 0 to len - 1 do
if (ConnectedClients[i] = nil) then
begin
Result := i;
exit;
end;
SetLength(ConnectedClients, len + 1);
end;
function TWebServer.GetServerStatus: boolean;
begin
GetServerStatus := Server.isActive;
end;
procedure TWebServer.Handle(From: THTTPConnectedClient; AData: TBytes);
var
Request: TRequest;
Response: TResponse;
begin
try
Request := TRequest.Create(AData);
FHandler.HandleReceiveHTTPData(From, AData);
Response := TResponse.Create(Request);
From.SendMessage(Response.ByteAnswer);
From.Disconnect;
finally
if Assigned(Request) then
Request.Free;
if Assigned(Response) then
Response.Free;
end;
end;
function TWebServer.IsActive: Boolean;
begin
Result := Server.isActive;
end;
procedure TWebServer.NewConHandle(SocketIP: String);
begin
FHandler.HandleConnectClient(SocketIP);
end;
procedure TWebServer.Start;
begin
Server.Start;
end;
procedure TWebServer.Stop;
var
i: integer;
begin
for i := 0 to Length(ConnectedClients) - 1 do
if (ConnectedClients[i] <> nil) then
ConnectedClients[i].Disconnect;
Server.Stop;
if NeedDestroySelf then
Self.Free;
end;
end.
|
{ Copyright (C) 1998-2018, written by Shkolnik Mike, Scalabium
E-Mail: mshkolnik@scalabium.com
mshkolnik@yahoo.com
WEB: http://www.scalabium.com
This component allow rescale all controls on form
according a PixelsPerInch change between design- and run-time
of you application.
}
unit SMScale;
interface
{$I SMVersion.inc}
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls;
type
{$IFDEF SM_ADD_ComponentPlatformsAttribute}
[ComponentPlatformsAttribute(pidWin32 or pidWin64)]
{$ENDIF}
TSMScaler = class(TComponent)
private
FDesignedPPI: Integer;
FScaleFactor: Integer;
FOnBeforeRescale: TNotifyEvent;
FOnAfterRescale: TNotifyEvent;
protected
public
constructor Create (AOwner: TComponent); override;
procedure Loaded; override;
procedure Execute;
published
property DesignedPPI: Integer read FDesignedPPI write FDesignedPPI;
property ScaleFactor: Integer read FScaleFactor write FScaleFactor;
property OnBeforeRescale: TNotifyEvent read FOnBeforeRescale write FOnBeforeRescale;
property OnAfterRescale: TNotifyEvent read FOnAfterRescale write FOnAfterRescale;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('SMComponents', [TSMScaler]);
end;
constructor TSMScaler.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FDesignedPPI := Screen.PixelsPerInch;
FScaleFactor := 100;
end;
procedure TSMScaler.Loaded;
begin
inherited Loaded;
if not (csDesigning in ComponentState) then
Execute
end;
type THackForm = class(TCustomForm);
procedure TSMScaler.Execute;
var frmParent: THackForm;
curPPI: Integer;
begin
curPPI := Screen.PixelsPerInch;
if (curPPI > DesignedPPI) or (FScaleFactor <> 100) then
begin
frmParent := THackForm(Owner);
if Assigned(frmParent) then
begin
if Assigned(FOnBeforeRescale) then
FOnBeforeRescale(Self);
with frmParent do
begin
AutoScroll := False;
ChangeScale(Trunc((DesignedPPI/curPPI)*FScaleFactor), 100);
end;
if Assigned(FOnAfterRescale) then
FOnAfterRescale(Self);
end;
end;
end;
end.
|
unit ucadTransDxControls;
interface
uses
SysUtils,
classes,
ufmTranslator;
type
TdxBarTranslator = class ( TcadCompTranslator )
function Translate(const aObj: TObject; var Translated:boolean):boolean; override;
class function Supports(const aObj: TObject): Boolean; override;
end;
TdxBarItemTranslator = class ( TcadCompTranslator )
function Translate(const aObj: TObject; var Translated:boolean):boolean; override;
class function Supports(const aObj: TObject): Boolean; override;
end;
{TdxSideBarTranslator = class ( TcadCompTranslator )
function Translate(const aObj: TObject; var Translated:boolean):boolean; override;
class function Supports(const aObj: TObject): Boolean; override;
end;}
TdxStatusBarTranslator = class ( TcadCompTranslator )
function Translate(const aObj: TObject; var Translated:boolean):boolean; override;
class function Supports(const aObj: TObject): Boolean; override;
end;
TdxCustomDockControlTranslator = class ( TcadCompTranslator )
function Translate(const aObj: TObject; var Translated:boolean):boolean; override;
class function Supports(const aObj: TObject): Boolean; override;
end;
TdxCustomLayoutControlTranslator = class ( TcadCompTranslator )
function Translate(const aObj: TObject; var Translated:boolean):boolean; override;
class function Supports(const aObj: TObject): Boolean; override;
end;
TdxBarListItemTranslator = class ( TcadCompTranslator )
function Translate(const aObj: TObject; var Translated:boolean):boolean; override;
class function Supports(const aObj: TObject): Boolean; override;
end;
TdxBarImageComboTranslator = class ( TcadCompTranslator )
function Translate(const aObj: TObject; var Translated:boolean):boolean; override;
class function Supports(const aObj: TObject): Boolean; override;
end;
TdxLayoutItemTranslator = class ( TcadCompTranslator )
function Translate(const aObj: TObject; var Translated:boolean):boolean; override;
class function Supports(const aObj: TObject): Boolean; override;
end;
TdxNavBarItemTranslator = class ( TcadCompTranslator )
function Translate(const aObj: TObject; var Translated:boolean):boolean; override;
class function Supports(const aObj: TObject): Boolean; override;
end;
TcxGridDBCardViewRowTranslator = class ( TcadCompTranslator )
function Translate(const aObj: TObject; var Translated:boolean):boolean; override;
class function Supports(const aObj: TObject): Boolean; override;
end;
implementation
uses
dxbar, dxStatusBar, dxDockControl, dxLayoutControl, dxBarExtItems,
cxGridDBCardView, dxLayoutContainer, dxNavBarCollns;
// -----------------------------------------------------------------------------
class function TdxBarTranslator.Supports(const aObj: TObject): Boolean;
begin
Result := aObj.InheritsFrom(TdxBar);
end;
function TdxBarTranslator.Translate(const aObj: TObject; var Translated:boolean):boolean;
begin
result := true;
Translated := false;
if sametext(copy(TComponent(aObj).name, 1, 7),'NoXlate') then exit;
with TdxBar(aObj) do
Caption := TranslateProp(aObj, GetOwnerClassName(aObj), Name, 'Caption', Caption, Translated);
end;
// -----------------------------------------------------------------------------
class function TdxBarItemTranslator.Supports(const aObj: TObject): Boolean;
begin
Result := aObj.InheritsFrom(TdxBarItem);
end;
function TdxBarItemTranslator.Translate(const aObj: TObject; var Translated:boolean):boolean;
begin
result := true;
Translated := false;
if sametext(copy(TComponent(aObj).name, 1, 7),'NoXlate') then exit;
with TdxBarItem(aObj) do
Caption := TranslateProp(aObj, GetOwnerClassName(aObj), Name, 'Caption', Caption, Translated);
end;
// -----------------------------------------------------------------------------
{
class function TdxSideBarTranslator.Supports(const aObj: TObject): Boolean;
begin
Result := aObj.InheritsFrom(TdxSideBar);
end;
function TdxSideBarTranslator.Translate(const aObj: TObject; var Translated:boolean):boolean;
var
gr, i: integer;
begin
result := true;
Translated := false;
if sametext(copy(TComponent(aObj).name, 1, 7),'NoXlate') then exit;
with TdxSideBar(aObj) do
for gr:=0 to GroupCount-1 do begin
Groups[gr].Caption := TranslateProp(aObj, GetOwnerClassName(aObj),
TComponent(aObj).Name + '.Group['+inttostr(gr)+'].'+Groups[gr].ClassName,
'Caption', Groups[gr].Caption, Translated);
with Groups[gr] do
for i:=0 to ItemCount -1 do begin
Items[i].Caption := TranslateProp(aObj, GetOwnerClassName(aObj),
TComponent(aObj).Name + '.Group['+inttostr(gr)+'].Items['+inttostr(i)+'].'+Items[i].ClassName,
'Caption', Items[i].Caption, Translated);
end;
end;
end;
}
// -----------------------------------------------------------------------------
class function TdxStatusBarTranslator.Supports(const aObj: TObject): Boolean;
begin
Result := aObj.InheritsFrom(TdxStatusBar);
end;
function TdxStatusBarTranslator.Translate(const aObj: TObject; var Translated:boolean):boolean;
var
i: integer;
begin
result := true;
Translated := false;
if sametext(copy(TComponent(aObj).name, 1, 7),'NoXlate') then exit;
with TdxStatusBar(aObj) do
for i:=0 to Panels.Count-1 do begin
Panels[i].Text := TranslateProp(aObj, GetOwnerClassName(aObj),
TComponent(aObj).Name + '.Panels['+inttostr(i)+'].'+Panels[i].ClassName,
'Text', Panels[i].Text, Translated);
end;
end;
// -----------------------------------------------------------------------------
class function TdxCustomDockControlTranslator.Supports(const aObj: TObject): Boolean;
begin
Result := aObj.InheritsFrom(TdxCustomDockControl);
end;
function TdxCustomDockControlTranslator.Translate(const aObj: TObject; var Translated:boolean):boolean;
begin
result := true;
Translated := false;
if sametext(copy(TComponent(aObj).name, 1, 7),'NoXlate') then exit;
with TdxCustomDockControl(aObj) do
Caption := TranslateProp(aObj, GetOwnerClassName(aObj), Name, 'Caption', Caption, Translated);
end;
// -----------------------------------------------------------------------------
class function TdxCustomLayoutControlTranslator.Supports(const aObj: TObject): Boolean;
begin
Result := aObj.InheritsFrom(TdxCustomLayoutControl);
end;
function TdxCustomLayoutControlTranslator.Translate(const aObj: TObject; var Translated:boolean):boolean;
var
i: integer;
begin
result := true;
Translated := false;
if sametext(copy(TComponent(aObj).name, 1, 7),'NoXlate') then exit;
with TdxCustomLayoutControl(aObj) do begin
for i:=0 to AbsoluteItemCount-1 do
with AbsoluteItems[i] do begin
Caption := TranslateProp(aObj, GetOwnerClassName(aObj), Name, 'Caption', Caption, Translated);
Hint := TranslateProp(aObj, GetOwnerClassName(aObj), Name, 'Hint', Hint, Translated);
end;
end;
end;
// -----------------------------------------------------------------------------
class function TdxBarListItemTranslator.Supports(const aObj: TObject): Boolean;
begin
Result := aObj.InheritsFrom(TdxBarListItem);
end;
function TdxBarListItemTranslator.Translate(const aObj: TObject; var Translated:boolean):boolean;
var
i: integer;
begin
result := true;
Translated := false;
if sametext(copy(TComponent(aObj).name, 1, 7),'NoXlate') then exit;
with TdxBarListItem(aObj) do begin
Caption := TranslateProp(aObj, GetOwnerClassName(aObj), Name, 'Caption', Caption, Translated);
Hint := TranslateProp(aObj, GetOwnerClassName(aObj), Name, 'Hint', Hint, Translated);
for i:=0 to Items.Count-1 do
Items[i] := TranslateProp(aObj, GetOwnerClassName(aObj),
TComponent(aObj).Name, 'Items['+inttostr(i)+']', Items[i], Translated);
end;
end;
// -----------------------------------------------------------------------------
class function TdxBarImageComboTranslator.Supports(const aObj: TObject): Boolean;
begin
Result := aObj.InheritsFrom(TdxBarImageCombo);
end;
function TdxBarImageComboTranslator.Translate(const aObj: TObject; var Translated:boolean):boolean;
var
i: integer;
begin
result := true;
Translated := false;
if sametext(copy(TComponent(aObj).name, 1, 7),'NoXlate') then exit;
with TdxBarImageCombo(aObj) do begin
Caption := TranslateProp(aObj, GetOwnerClassName(aObj), Name, 'Caption', Caption, Translated);
Hint := TranslateProp(aObj, GetOwnerClassName(aObj), Name, 'Hint', Hint, Translated);
for i:=0 to Items.Count-1 do
Items[i] := TranslateProp(aObj, GetOwnerClassName(aObj),
TComponent(aObj).Name, 'Items['+inttostr(i)+']', Items[i], Translated);
end;
end;
// -----------------------------------------------------------------------------
{ TdxLayoutItemTranslator }
class function TdxLayoutItemTranslator.Supports(const aObj: TObject): Boolean;
begin
Result := aObj.InheritsFrom(TdxLayoutItem);
end;
function TdxLayoutItemTranslator.Translate(const aObj: TObject;
var Translated: boolean): boolean;
begin
result := true;
Translated := false;
if sametext(copy(TComponent(aObj).name, 1, 7),'NoXlate') then exit;
with TdxLayoutItem(aObj) do begin
Caption := TranslateProp(aObj, GetOwnerClassName(aObj), Name, 'Caption', Caption, Translated);
end;
end;
{ TdxNavBarItemTranslator }
class function TdxNavBarItemTranslator.Supports(const aObj: TObject): Boolean;
begin
Result := aObj.InheritsFrom(TdxNavBarItem);
end;
function TdxNavBarItemTranslator.Translate(const aObj: TObject;
var Translated: boolean): boolean;
begin
result := true;
Translated := false;
if sametext(copy(TComponent(aObj).name, 1, 7),'NoXlate') then exit;
with TdxNavBarItem(aObj) do begin
Caption := TranslateProp(aObj, GetOwnerClassName(aObj), Name, 'Caption', Caption, Translated);
Hint := TranslateProp(aObj, GetOwnerClassName(aObj), Name, 'Hint', Hint, Translated);
end;
end;
{ TcxGridDBCardViewRowTranslator }
class function TcxGridDBCardViewRowTranslator.Supports(
const aObj: TObject): Boolean;
begin
Result := aObj.InheritsFrom(TcxGridDBCardViewRow);
end;
function TcxGridDBCardViewRowTranslator.Translate(const aObj: TObject;
var Translated: boolean): boolean;
begin
result := true;
Translated := false;
if sametext(copy(TComponent(aObj).name, 1, 7),'NoXlate') then exit;
with TcxGridDBCardViewRow(aObj) do begin
Caption := TranslateProp(aObj, GetOwnerClassName(aObj), Name, 'Caption', Caption, Translated);
end;
end;
initialization
RegisterTranslators([ TdxBarTranslator, TdxBarItemTranslator, {TdxSideBarTranslator,}
TdxStatusBarTranslator, TdxCustomDockControlTranslator, TdxBarItemTranslator,
TdxCustomLayoutControlTranslator, TdxBarListItemTranslator,
TdxBarImageComboTranslator, TdxLayoutItemTranslator, TdxNavBarItemTranslator,
TcxGridDBCardViewRowTranslator ]);
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2014-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit System.Win.Bluetooth;
interface
uses
System.SysUtils, System.Bluetooth;
{$SCOPEDENUMS ON}
{$DEFINE BLUETOOTH_CLASSIC}
{$DEFINE BLUETOOTH_LE}
type
{$IFDEF BLUETOOTH_CLASSIC}
TPlatformBluetoothClassicManager = class(TBluetoothManager)
protected
class function GetBluetoothManager: TBluetoothManager; override;
end;
{$ENDIF BLUETOOTH_CLASSIC}
{$IFDEF BLUETOOTH_LE}
TPlatformBluetoothLEManager = class(TBluetoothLEManager)
protected
class function GetBluetoothManager: TBluetoothLEManager; override;
end;
{$ENDIF BLUETOOTH_LE}
implementation
uses
Winapi.Windows, Winapi.Winsock2, System.Types, System.Generics.Collections,
System.SyncObjs, WinApi.Bluetooth,
{$IFDEF BLUETOOTH_LE}
WinApi.BluetoothLE,
{$ENDIF BLUETOOTH_LE}
System.Win.BluetoothWinRT,
System.NetConsts, System.Classes, Winapi.Messages;
const
SBluetoothMACAddressFormat = '%0.2X:%0.2X:%0.2X:%0.2X:%0.2X:%0.2X'; // Do not translate
type
{$IFDEF BLUETOOTH_CLASSIC}
// --------------------------------------------------------------------- //
// Bluetooth Classic
// --------------------------------------------------------------------- //
TWinBluetoothAdapter = class;
TWinBluetoothManager = class(TPlatformBluetoothClassicManager)
private
FClassicAdapter: TBluetoothAdapter;
protected
function GetAdapterState: TBluetoothAdapterState;
function GetConnectionState: TBluetoothConnectionState; override;
function DoGetClassicAdapter: TBluetoothAdapter; override;
function DoEnableBluetooth: Boolean; override;
public
destructor Destroy; override;
end;
TWinBluetoothAdapter = class(TBluetoothAdapter)
private type
TThreadTimer = class(TThread)
private
FTimeout: Cardinal;
FOnTimer: TDiscoverableEndEvent;
FEvent: TEvent;
procedure Cancel;
public
constructor Create(const AEvent: TDiscoverableEndEvent; Timeout: Cardinal); overload;
destructor Destroy; override;
procedure Execute; override;
end;
TDiscoverThread = class(TThread)
private
FAdapter: TWinBluetoothAdapter;
FTimeout: Cardinal;
Cancelled: Boolean;
protected
procedure Execute; override;
public
constructor Create(const AnAdapter: TWinBluetoothAdapter; Timeout: Cardinal);
procedure Cancel;
end;
private
FTimer: TThreadTimer;
FState: TBluetoothAdapterState;
FDiscoverThread: TDiscoverThread;
FPairedDevices: TBluetoothDeviceList;
function GetBthAddress: TBluetoothAddress;
procedure GetDevicesByParam(const AList:TBluetoothDeviceList; AType: string; Timeout: Cardinal = 0);
protected
FRadioHandle: THandle;
function GetAdapterName: string; override;
procedure SetAdapterName(const Value: string); override;
function GetAddress: System.Bluetooth.TBluetoothMacAddress; override;
function GetPairedDevices: TBluetoothDeviceList; override;
procedure DoDiscoverableEnd(const Sender: TObject); override;
procedure DoStartDiscoverable(Timeout: Cardinal); override;
procedure DoStartDiscovery(Timeout: Cardinal); override;
procedure DoCancelDiscovery; override;
function DoPair(const ADevice: TBluetoothDevice): Boolean; override;
function DoUnPair(const ADevice: TBluetoothDevice): Boolean; override;
function GetScanMode: TBluetoothScanMode; override;
function GetState: TBluetoothAdapterState; override;
function DoCreateServerSocket(const AName: string; const AUUID: TGUID; Secure: Boolean): TBluetoothServerSocket; override;
public
constructor Create(const AManager: TBluetoothManager; const ARadioHandle: THandle);
destructor Destroy; override;
end;
TWinBluetoothDevice = class(TBluetoothDevice)
protected
FDeviceInfo: TBluetoothDeviceInfo;
FAdapter: TWinBluetoothAdapter;
FType: TBluetoothType;
function GetAddress: TBluetoothMacAddress; override;
function GetDeviceName: string; override;
function GetPaired: Boolean; override;
function GetState: TBluetoothDeviceState; override;
function GetBluetoothType: TBluetoothType; override;
function GetClassDevice: Integer; override;
function GetClassDeviceMajor: Integer; override;
function DoGetServices: TBluetoothServiceList; override;
function DoCreateClientSocket(const AUUID: TGUID; Secure: Boolean): TBluetoothSocket; override;
public
constructor Create(const AnAdapter: TWinBluetoothAdapter; const ADeviceInfo: TBluetoothDeviceInfo);
end;
TWinBluetoothServerSocket = class(TBluetoothServerSocket)
protected
FListenSocket: TSocket;
FWSAService: TWsaQuerySet;
FCsAddr: TCsAddrInfo;
FAddressBth: TSockAddrBth;
FSecured: Boolean;
function DoAccept(Timeout: Cardinal = 0): TBluetoothSocket; override;
procedure DoClose; override;
public
constructor Create(const AName: string; const AUUID: TGUID; Secure: Boolean; const MACAddress: string);
destructor Destroy; override;
end;
TWinBluetoothSocket = class(TBluetoothSocket)
private
FClientSocket: TSocket;
FGUIDService: TGUID;
FAddress: TBluetoothAddress;
FConnected: Boolean;
FSecure: Boolean;
FLastReadTimeout: Cardinal;
class constructor Create;
class destructor Destroy;
protected
function GetConnected: Boolean; override;
procedure DoClose; override;
procedure DoConnect; override;
function DoReceiveData(ATimeout: Cardinal): TBytes; override;
procedure DoSendData(const AData: TBytes); override;
constructor Create(const ASocket: TSocket; const AnAddress: TBluetoothAddress; const AUUID: TGUID; Secure: Boolean);
destructor Destroy; override;
end;
{$ENDIF BLUETOOTH_CLASSIC}
{$IFDEF BLUETOOTH_LE}
// --------------------------------------------------------------------- //
// Bluetooth LE
// --------------------------------------------------------------------- //
// --------------------------------------------------------------------- //
// Required API from SetupAPI.h for LE
// --------------------------------------------------------------------- //
{$IFDEF WIN32}
{$ALIGN OFF}
{$ENDIF}
type
HDEVINFO = Pointer;
{$EXTERNALSYM HDEVINFO}
SP_DEVICE_INTERFACE_DATA = record
cbSize: Cardinal;
InterfaceClassGuid: TGUID;
Flags: Cardinal;
Reserved: ULONG_PTR;
end;
_SP_DEVICE_INTERFACE_DATA = SP_DEVICE_INTERFACE_DATA;
{$EXTERNALSYM SP_DEVICE_INTERFACE_DATA}
PSP_DEVICE_INTERFACE_DATA = ^SP_DEVICE_INTERFACE_DATA;
{$EXTERNALSYM PSP_DEVICE_INTERFACE_DATA}
SP_DEVICE_INTERFACE_DETAIL_DATA = record
cbSize: Cardinal;
DevicePath: array [0..0] of Char;
end;
_SP_DEVICE_INTERFACE_DETAIL_DATA = SP_DEVICE_INTERFACE_DETAIL_DATA;
{$EXTERNALSYM SP_DEVICE_INTERFACE_DETAIL_DATA}
PSP_DEVICE_INTERFACE_DETAIL_DATA = ^SP_DEVICE_INTERFACE_DETAIL_DATA;
{$EXTERNALSYM PSP_DEVICE_INTERFACE_DETAIL_DATA}
SP_DEVINFO_DATA = record
cbSize: Cardinal;
ClassGuid: TGUID;
DevInst: Cardinal;
Reserved: ULONG_PTR;
end;
{$EXTERNALSYM SP_DEVINFO_DATA}
PSP_DEVINFO_DATA = ^SP_DEVINFO_DATA;
{$EXTERNALSYM PSP_DEVINFO_DATA}
DEVPROPTYPE = ULONG;
{$EXTERNALSYM DEVPROPTYPE}
PDEVPROPTYPE = ^DEVPROPTYPE;
DEVPROPKEY = record
fmtid: TGUID;
pid: ULONG;
end;
{$EXTERNALSYM DEVPROPKEY}
PDEVPROPKEY = ^DEVPROPKEY;
{$IFDEF WIN32}
{$ALIGN ON}
{$ENDIF}
TCancelConnectionFunction = function (hDevice: THandle; Flags: Cardinal): HRESULT; stdcall;
const
DIGCF_DEFAULT = $00000001; // only valid with DIGCF_DEVICEINTERFACE
{$EXTERNALSYM DIGCF_DEFAULT}
DIGCF_PRESENT = $00000002;
{$EXTERNALSYM DIGCF_PRESENT}
DIGCF_ALLCLASSES = $00000004;
{$EXTERNALSYM DIGCF_ALLCLASSES}
DIGCF_PROFILE = $00000008;
{$EXTERNALSYM DIGCF_PROFILE}
DIGCF_DEVICEINTERFACE = $00000010;
{$EXTERNALSYM DIGCF_DEVICEINTERFACE}
SetupApiModuleName = 'SetupApi.dll';
DN_DEVICE_DISCONNECTED = $02;
DEVPKEY_Device_FriendlyName: DEVPROPKEY = (
fmtid: '{A45C254E-DF1C-4EFD-8020-67D146A850E0}'; pid: 14);
{$EXTERNALSYM DEVPKEY_Device_FriendlyName}
DEVPKEY_Device_LocationInfo: DEVPROPKEY = (
fmtid: '{A45C254E-DF1C-4EFD-8020-67D146A850E0}'; pid: 15);
{$EXTERNALSYM DEVPKEY_Device_LocationInfo}
DEVPKEY_Device_LocationPaths: DEVPROPKEY = (
fmtid: '{A45C254E-DF1C-4EFD-8020-67D146A850E0}'; pid: 37);
{$EXTERNALSYM DEVPKEY_Device_LocationPaths}
DEVPKEY_Device_DevNodeStatus: DEVPROPKEY = (
fmtid:'{4340A6C5-93FA-4706-972C-7B648008A5A7}'; pid: 2);
{$WARN SYMBOL_PLATFORM OFF}
function SetupDiGetClassDevs(ClassGuid: PGUID; const Enumerator: PWideChar;
hwndParent: HWND; Flags: Cardinal): HDEVINFO; stdcall; external SetupApiModuleName name 'SetupDiGetClassDevsW' delayed;
{$EXTERNALSYM SetupDiGetClassDevs}
function SetupDiEnumDeviceInterfaces(DeviceInfoSet: HDEVINFO; DeviceInfoData: Pointer; const InterfaceClassGuid: PGUID;
MemberIndex: Cardinal;
var DeviceInterfaceData: SP_DEVICE_INTERFACE_DATA): BOOL; stdcall; external SetupApiModuleName name 'SetupDiEnumDeviceInterfaces' delayed;
{$EXTERNALSYM SetupDiEnumDeviceInterfaces}
function SetupDiGetDeviceInterfaceDetail(DeviceInfoSet: HDEVINFO;
var DeviceInterfaceData: SP_DEVICE_INTERFACE_DATA;
DeviceInterfaceDetailData: PSP_DEVICE_INTERFACE_DETAIL_DATA;
DeviceInterfaceDetailDataSize: Cardinal; RequiredSize: PCardinal;
Device: PSP_DEVINFO_DATA): BOOL; stdcall; external SetupApiModuleName name 'SetupDiGetDeviceInterfaceDetailW' delayed;
{$EXTERNALSYM SetupDiGetDeviceInterfaceDetail}
function SetupDiDestroyDeviceInfoList(
DeviceInfoSet: HDEVINFO): BOOL; stdcall; external SetupApiModuleName name 'SetupDiDestroyDeviceInfoList' delayed;
{$EXTERNALSYM SetupDiDestroyDeviceInfoList}
function SetupDiGetDeviceInterfaceProperty(
DeviceInfoSet: HDEVINFO;
var DeviceInterfaceData: SP_DEVICE_INTERFACE_DATA;
PropertyKey: PDEVPROPKEY;
PropertyType: PDEVPROPTYPE;
PropertyBuffer: PByte;
PropertyBufferSize: LongWord;
RequiredSize: PLongWord;
Flags: LongWord
): BOOL; stdcall; external SetupApiModuleName name 'SetupDiGetDeviceInterfacePropertyW' delayed;
{$EXTERNALSYM SetupDiGetDeviceInterfaceProperty}
function SetupDiEnumDeviceInfo(DeviceInfoSet: HDEVINFO;
MemberIndex: Cardinal; var DeviceInfoData: SP_DEVINFO_DATA): BOOL; stdcall; external SetupApiModuleName name 'SetupDiEnumDeviceInfo' delayed;
{$EXTERNALSYM SetupDiEnumDeviceInfo}
function SetupDiGetDeviceProperty(
DeviceInfoSet: HDEVINFO;
var DeviceInfoData: SP_DEVINFO_DATA;
PropertyKey: PDEVPROPKEY;
var PropertyType: DEVPROPTYPE;
PropertyBuffer: PByte;
PropertyBufferSize: Cardinal;
RequiredSize: PCardinal;
Flags: Cardinal
): BOOL; stdcall; external SetupApiModuleName name 'SetupDiGetDevicePropertyW' delayed;
{$EXTERNALSYM SetupDiGetDeviceProperty}
{$WARN SYMBOL_PLATFORM DEFAULT}
function GetApiFunction(const DLLName: string; const FunctionName: string): FARPROC;
var
Handle: THandle;
begin
Handle := SafeLoadLibrary(DLLName);
if Handle <= HINSTANCE_ERROR then
raise Exception.CreateFmt('%s: %s', [SysErrorMessage(GetLastError), DLLName]);
try
Result := GetProcAddress(Handle, PChar(FunctionName));
finally
FreeLibrary(Handle);
end;
end;
// --------------------------------------------------------------------- //
// End API from SetupAPI.h
// --------------------------------------------------------------------- //
// --------------------------------------------------------------------- //
// --------------------------------------------------------------------- //
// Required from Dbt.h for LE
// --------------------------------------------------------------------- //
type
PDevBroadcastHandle = ^DEV_BROADCAST_HANDLE;
DEV_BROADCAST_HANDLE = record
dbch_size: DWORD;
dbch_devicetype: DWORD;
dbch_reserved: DWORD;
dbch_handle: THandle;
dbch_hdevnotify: Pointer;
dbch_eventguid: TGUID;
dbch_nameoffset: Long;
dbch_data: array [0..0] of Byte;
dbcc_name: Char;
end;
TDevBroadcastHandle = DEV_BROADCAST_HANDLE;
const
DBT_DEVTYP_HANDLE = $00000006;
DBT_CUSTOMEVENT = $8006;
// --------------------------------------------------------------------- //
// End from Dbt.h
// --------------------------------------------------------------------- //
// --------------------------------------------------------------------- //
type
TWinBluetoothLEManager = class(TPlatformBluetoothLEManager)
private
FLEAdapter: TBluetoothLEAdapter;
protected
function GetAdapterState: TBluetoothAdapterState;
function GetConnectionState: TBluetoothConnectionState; override;
function DoGetAdapter: TBluetoothLEAdapter; override;
// LE Fucntionality
function DoGetGattServer: TBluetoothGattServer; override;
function DoGetSupportsGattClient: Boolean; override;
function DoGetSupportsGattServer: Boolean; override;
function DoEnableBluetooth: Boolean; override;
public
destructor Destroy; override;
end;
TWinBluetoothLEAdapter = class(TBluetoothLEAdapter)
private
FRadioInfo: TBluetoothRadioInfo;
FHardwareDeviceInfo: HDEVINFO;
FCancelConnectionFunction: TCancelConnectionFunction;
FWinHandle: HWND;
FNotificationHandle: Pointer;
procedure WndProc(var Msg: TMessage);
procedure RegisterBTChangeNotification;
procedure UnregisterBTChangeNotification;
procedure ChangeBTDeviceConnectionStatus(ABthAddress: BTH_ADDR; AConnected: Boolean);
function GetRadioInfo: TBluetoothRadioInfo;
procedure GetBLEDevices;
protected
function GetAdapterName: string; override;
procedure SetAdapterName(const Value: string); override;
function GetAddress: System.Bluetooth.TBluetoothMacAddress; override;
function DoStartDiscovery(Timeout: Cardinal; const AFilterUUIDList: TBluetoothUUIDsList = nil;
const ABluetoothLEScanFilterList: TBluetoothLEScanFilterList = nil): Boolean; override;
function DoStartDiscoveryRaw(const ABluetoothLEScanFilterList: TBluetoothLEScanFilterList = nil; Refresh: Boolean = True): Boolean; override;
procedure DoCancelDiscovery; override;
function GetScanMode: TBluetoothScanMode; override;
function GetState: TBluetoothAdapterState; override;
public
constructor Create(const AManager: TBluetoothLEManager);
destructor Destroy; override;
end;
TWinBluetoothLEDevice = class(TBluetoothLEDevice)
private
FLEAdapter: TWinBluetoothLEAdapter;
protected
FLEDeviceHandle: THandle;
FDeviceName: string;
FDevicePath: string;
FMacAddress: TBluetoothMacAddress;
FReliableWriteContext: TBthLeGattReliableWriteContext;
FDeviceInfo: SP_DEVINFO_DATA;
function DoCreateAdvertiseData: TBluetoothLEAdvertiseData; override;
function RegisterNotification(const ACharacteristic: TBluetoothGattCharacteristic): Boolean;
function UnregisterNotification(const ACharacteristic: TBluetoothGattCharacteristic): Boolean;
function GetAddress: TBluetoothMacAddress; override;
function GetDeviceName: string; override;
function GetBluetoothType: TBluetoothType; override;
function GetIdentifier: string; override;
function GetIsConnected: Boolean; override;
procedure DoAbortReliableWrite; override;
function DoBeginReliableWrite: Boolean; override;
function DoExecuteReliableWrite: Boolean; override;
function DoDiscoverServices: Boolean; override;
function DoReadCharacteristic(const ACharacteristic: TBluetoothGattCharacteristic): Boolean; override;
function DoReadDescriptor(const ADescriptor: TBluetoothGattDescriptor): Boolean; override;
function DoWriteCharacteristic(const ACharacteristic: TBluetoothGattCharacteristic): Boolean; override;
function DoWriteDescriptor(const ADescriptor: TBluetoothGattDescriptor): Boolean; override;
function DoReadRemoteRSSI: Boolean; override;
function DoSetCharacteristicNotification(const ACharacteristic: TBluetoothGattCharacteristic;
Enable: Boolean): Boolean; override;
function DoDisconnect: Boolean; override;
function DoConnect: Boolean; override;
public
class function ExtractMacAddres(const APath: string): TBluetoothMacAddress; static;
constructor Create(const AName, APath: string; const ALEAdapter: TWinBluetoothLEAdapter; AutoConnect: Boolean);
destructor Destroy; override;
end;
TWinBluetoothGattService = class(TBluetoothGattService)
private
function GetServiceHandle: THandle;
function GetHandle: THandle;
property ServiceHandle: THandle read GetHandle;
protected
FDevice: TWinBluetoothLEDevice;
FLEDeviceHandle: THandle;
FServiceHandle: THandle;
FGattService: TBthLeGattService;
FType: TBluetoothServiceType;
function GetServiceUUID: TBluetoothUUID; override;
function GetServiceType: TBluetoothServiceType; override;
function DoGetCharacteristics: TBluetoothGattCharacteristicList; override;
function DoGetIncludedServices: TBluetoothGattServiceList; override;
function DoCreateCharacteristic(const AUuid: TBluetoothUUID; APropertyFlags: TBluetoothPropertyFlags;
const ADescription: string): TBluetoothGattCharacteristic; override;
function DoCreateIncludedService(const AnUUID: TBluetoothUUID; AType: TBluetoothServiceType): TBluetoothGattService; override;
// Add the previously created Services and characteristics...
function DoAddIncludedService(const AService: TBluetoothGattService): Boolean; override;
function DoAddCharacteristic(const ACharacteristic: TBluetoothGattCharacteristic): Boolean; override;
public
constructor Create(const ADevice: TWinBluetoothLEDevice; const AGattService: TBthLeGattService; AType: TBluetoothServiceType);
destructor Destroy; override;
end;
TWinBluetoothGattCharacteristic = class(TBluetoothGattCharacteristic)
private
function UpdateValueFromDevice: TBluetoothGattStatus;
function SetValueToDevice: TBluetoothGattStatus;
procedure ValueChangeEvent(EventOutParameter: Pointer);
protected
FLEDeviceHandle: THandle;
FGattService: TBthLeGattService;
FGattCharacteristic: TBthLeGattCharacteristic;
PValue: PBthLeGattCharacteristicValue;
FValueChangeEventHandle: TBluetoothGattEventHandle;
function ServiceHandle: THandle; inline;
function GetUUID: TBluetoothUUID; override;
function GetProperties: TBluetoothPropertyFlags; override;
function DoAddDescriptor(const ADescriptor: TBluetoothGattDescriptor): Boolean; override;
function DoGetDescriptors: TBluetoothGattDescriptorList; override;
function DoCreateDescriptor(const AUUID: TBluetoothUUID): TBluetoothGattDescriptor; override;
function DoGetValue: TBytes; override;
procedure DoSetValue(const AValue: TBytes); override;
public
constructor Create(const AService: TWinBluetoothGattService; const AGattCharacteristic: TBthLeGattCharacteristic);
destructor Destroy; override;
end;
TWinBluetoothGattDescriptor = class(TBluetoothGattDescriptor)
private
function UpdateValueFromDevice: TBluetoothGattStatus;
function SetValueToDevice: TBluetoothGattStatus;
procedure CheckCreateValue;
protected
PValue: PBthLeGattDescriptorValue;
FGattDescriptor: TBthLeGattDescriptor;
// Characteristic Extended Properties
function DoGetReliableWrite: Boolean; override;
function DoGetWritableAuxiliaries: Boolean; override;
// Characteristic User Description
function DoGetUserDescription: string; override;
procedure DoSetUserDescription(const Value: string); override;
// Client Characteristic Configuration
procedure DoSetNotification(const Value: Boolean); override;
function DoGetNotification: Boolean; override;
procedure DoSetIndication(const Value: Boolean); override;
function DoGetIndication: Boolean; override;
// Server Characteristic Configuration
function DoGetBroadcasts: Boolean; override;
procedure DoSetBroadcasts(const Value: Boolean); override;
//Characteristic Presentation Format
function DoGetFormat: TBluetoothGattFormatType; override;
function DoGetExponent: ShortInt; override;
function DoGetFormatUnit: TBluetoothUUID; override;
function DoGetValue: TBytes; override;
procedure DoSetValue(const AValue: TBytes); override;
function GetUUID: TBluetoothUUID; override;
public
constructor Create(const ACharacteristic: TWinBluetoothGattCharacteristic; const AGattDescriptor: TBthLeGattDescriptor);
destructor Destroy; override;
end;
function TBthLeUuidToUUID(const Uuid: TBthLeUuid): TBluetoothUUID; inline;
var
TempGuuid: TBluetoothUUID;
begin
if Uuid.IsShortUuid then
begin
TempGuuid := BTH_LE_ATT_BLUETOOTH_BASE_GUID;
Inc(TempGuuid.D1, Uuid.ShortUuid);
Result := TempGuuid;
end
else
Result := Uuid.LongUuid;
end;
function BLEUuidToString(Uuid: TBthLeUuid): string; inline;
begin
Result := TBthLeUuidToUUID(Uuid).ToString;
end;
function ErrorToStatus(AnError: HRESULT): TBluetoothGattStatus;
begin
case Cardinal(AnError) of
S_OK:
Result := TBluetoothGattStatus.Success;
E_BLUETOOTH_ATT_READ_NOT_PERMITTED:
Result := TBluetoothGattStatus.ReadNotPermitted;
E_BLUETOOTH_ATT_WRITE_NOT_PERMITTED:
Result := TBluetoothGattStatus.WriteNotPermitted;
E_BLUETOOTH_ATT_INSUFFICIENT_AUTHENTICATION:
Result := TBluetoothGattStatus.InsufficientAutentication;
E_BLUETOOTH_ATT_ATTRIBUTE_NOT_FOUND:
Result := TBluetoothGattStatus.RequestNotSupported;
E_BLUETOOTH_ATT_INVALID_OFFSET:
Result := TBluetoothGattStatus.InvalidOffset;
E_BLUETOOTH_ATT_INVALID_ATTRIBUTE_VALUE_LENGTH:
Result := TBluetoothGattStatus.InvalidAttributeLength;
E_BLUETOOTH_ATT_INSUFFICIENT_ENCRYPTION:
Result := TBluetoothGattStatus.InsufficientEncryption;
else
Result := TBluetoothGattStatus.Failure;
end;
end;
function CheckOSVersionForGattClient: Boolean;
begin
Result := TOSVersion.Check(6, 2);
end;
function CheckOSVersionForGattServer: Boolean;
begin
Result := False;
end;
{$ENDIF BLUETOOTH_LE}
function BthAddressToString(const AnAddress: TBluetoothAddress): string; inline;
begin
Result := Format(SBluetoothMACAddressFormat, [AnAddress.rgBytes[5], AnAddress.rgBytes[4],
AnAddress.rgBytes[3], AnAddress.rgBytes[2], AnAddress.rgBytes[1], AnAddress.rgBytes[0]]);
end;
{$IFDEF BLUETOOTH_CLASSIC}
{ TPlatformBluetoothClassicManager }
class function TPlatformBluetoothClassicManager.GetBluetoothManager: TBluetoothManager;
begin
Result := TWinBluetoothManager.Create;
end;
{ TWinBluetoothManager }
function TWinBluetoothManager.GetAdapterState: TBluetoothAdapterState;
var
btfrp: TBlueToothFindRadioParams;
hRadio: THandle;
hFind: HBLUETOOTH_RADIO_FIND;
begin
FillChar(btfrp, SizeOf(btfrp), 0);
btfrp.dwSize := SizeOf(btfrp);
hFind := BluetoothFindFirstRadio(btfrp, hRadio);
if hFind <> 0 then
begin
Result := TBluetoothAdapterState.&On;
if FClassicAdapter = nil then
FClassicAdapter := TWinBluetoothAdapter.Create(Self, hRadio);
BluetoothFindRadioClose(hFind);
end
else
Result := TBluetoothAdapterState.Off;
end;
function TWinBluetoothManager.DoGetClassicAdapter: TBluetoothAdapter;
begin
if GetAdapterState = TBluetoothAdapterState.Off then
begin
FClassicAdapter.Free;
FClassicAdapter := nil;
end;
Result := FClassicAdapter;
end;
function TWinBluetoothManager.GetConnectionState: TBluetoothConnectionState;
begin
if GetAdapterState = TBluetoothAdapterState.&On then
Result := TBluetoothConnectionState.Connected
else
Result := TBluetoothConnectionState.Disconnected;
end;
destructor TWinBluetoothManager.Destroy;
begin
FClassicAdapter.Free;
inherited;
end;
function TWinBluetoothManager.DoEnableBluetooth: Boolean;
begin
Result := False;
end;
{ TWinBluetoothAdapter }
constructor TWinBluetoothAdapter.Create(const AManager: TBluetoothManager; const ARadioHandle: THandle);
begin
inherited Create(AManager);
FPairedDevices := TBluetoothDeviceList.Create;
FRadioHandle := ARadioHandle;
FState := TBluetoothAdapterState.&On;
end;
destructor TWinBluetoothAdapter.Destroy;
begin
if FRadioHandle <> 0 then
CloseHandle(FRadioHandle);
FPairedDevices.Free;
FDiscoverThread.Free;
inherited;
end;
function TWinBluetoothAdapter.GetAdapterName: string;
var
LRadioInfo: TBluetoothRadioInfo;
Res: DWORD;
begin
Result := '';
FillChar(LRadioInfo, SizeOf(LRadioInfo), 0);
LRadioInfo.dwSize := SizeOf(LRadioInfo);
Res := BluetoothGetRadioInfo(FRadioHandle, LRadioInfo);
if Res = ERROR_SUCCESS then
Result := LRadioInfo.szName;
end;
function TWinBluetoothAdapter.GetAddress: System.Bluetooth.TBluetoothMacAddress;
var
LAddress: TBluetoothAddress;
begin
Result := '00:00:00:00:00:00';
LAddress := GetBthAddress;
if LAddress.ullLong <> BLUETOOTH_NULL_ADDRESS.ullLong then
Result := BthAddressToString(LAddress);
end;
function TWinBluetoothAdapter.GetBthAddress: TBluetoothAddress;
var
LRadioInfo: TBluetoothRadioInfo;
begin
Result := BLUETOOTH_NULL_ADDRESS;
LRadioInfo.dwSize := SizeOf(LRadioInfo);
if BluetoothGetRadioInfo(FRadioHandle, LRadioInfo) = ERROR_SUCCESS then
Result := LRadioInfo.address;
end;
procedure TWinBluetoothAdapter.GetDevicesByParam(const AList: TBluetoothDeviceList; AType: string; Timeout: Cardinal);
var
LSearchParams: TBluetoothDeviceSearchParams;
LDeviceInfo: TBluetoothDeviceInfo;
LBluetoothDevice: TBluetoothDeviceFind;
begin
inherited;
FillChar(LSearchParams, SizeOf(LSearchParams), 0);
LSearchParams.dwSize := SizeOf(LSearchParams);
LSearchParams.hRadio := FRadioHandle;
if AType = 'PairedDevices' then // do not translate
begin
LSearchParams.fReturnAuthenticated := True;
LSearchParams.fReturnRemembered := False;
LSearchParams.fReturnUnknown := False;
LSearchParams.fReturnConnected := False;
LSearchParams.fIssueInquiry := False;
LSearchParams.cTimeoutMultiplier := 0;
end
else if AType = 'DiscoverDevices' then // do not translate
begin
LSearchParams.fReturnAuthenticated := False;
LSearchParams.fReturnRemembered := False;
LSearchParams.fReturnUnknown := True;
LSearchParams.fReturnConnected := False;
LSearchParams.fIssueInquiry := True;
LSearchParams.cTimeoutMultiplier := Trunc((Timeout div 1000) / 1.28);
end;
AList.Clear;
FillChar(LDeviceInfo, SizeOf(LDeviceInfo), 0);
LDeviceInfo.dwSize := SizeOf(LDeviceInfo);
LBluetoothDevice := BluetoothFindFirstDevice(LSearchParams, LDeviceInfo);
while LBluetoothDevice <> 0 do
begin
if BluetoothGetDeviceInfo(FRadioHandle, LDeviceInfo) <> ERROR_SUCCESS then
raise EBluetoothSocketException.CreateFmt(SBluetoothDeviceInfoError, [GetLastError, SysErrorMessage(GetLastError)]);
AList.Add(TWinBluetoothDevice.Create(Self, LDeviceInfo));
FillChar(LDeviceInfo, SizeOf(LDeviceInfo), 0);
LDeviceInfo.dwSize := SizeOf(LDeviceInfo);
if BluetoothFindNextDevice(LBluetoothDevice, LDeviceInfo) = BOOL(False) then
Break;
end;
if LBluetoothDevice <> 0 then
BluetoothFindDeviceClose(LBluetoothDevice);
end;
function TWinBluetoothAdapter.GetPairedDevices: TBluetoothDeviceList;
begin
Result := FPairedDevices;
GetDevicesByParam(FPairedDevices, 'PairedDevices'); // Do not translate
end;
function TWinBluetoothAdapter.GetScanMode: TBluetoothScanMode;
begin
if BluetoothIsDiscoverable(FRadioHandle) then
Result := TBluetoothScanMode.Discoverable
else if BluetoothIsConnectable(FRadioHandle) then
Result := TBluetoothScanMode.Connectable
else
Result := TBluetoothScanMode.None;
end;
function TWinBluetoothAdapter.GetState: TBluetoothAdapterState;
begin
Result := FState;
end;
function TWinBluetoothAdapter.DoPair(const ADevice: TBluetoothDevice): Boolean;
begin
Result := BluetoothAuthenticateDeviceEx(0 , FRadioHandle, TWinBluetoothDevice(ADevice).FDeviceInfo, nil,
MITMProtectionRequiredGeneralBonding) = ERROR_SUCCESS;
end;
procedure TWinBluetoothAdapter.SetAdapterName(const Value: string);
begin
inherited;
raise EBluetoothAdapterException.Create(SBluetoothNotImplemented);
end;
procedure TWinBluetoothAdapter.DoStartDiscoverable(Timeout: Cardinal);
begin
inherited;
BluetoothEnableDiscovery(FRadioHandle, TRUE);
FTimer := TThreadTimer.Create(DoDiscoverableEnd, Timeout);
FTimer.Start;
end;
procedure TWinBluetoothAdapter.DoStartDiscovery(Timeout: Cardinal);
begin
inherited;
if FState = TBluetoothAdapterState.&On then
begin
FState := TBluetoothAdapterState.Discovering;
if FDiscoverThread <> nil then
FreeAndNil(FDiscoverThread);
if FDiscoverThread = nil then
begin
FDiscoverThread := TDiscoverThread.Create(Self, Timeout);
FDiscoverThread.Start;
end;
end;
end;
function TWinBluetoothAdapter.DoUnPair(const ADevice: TBluetoothDevice): Boolean;
begin
Result := BluetoothRemoveDevice(TWinBluetoothDevice(ADevice).FDeviceInfo.Address) = ERROR_SUCCESS;
end;
procedure TWinBluetoothAdapter.DoCancelDiscovery;
begin
inherited;
if FDiscoverThread <> nil then
FDiscoverThread.Cancel;
end;
function TWinBluetoothAdapter.DoCreateServerSocket(const AName: string; const AUUID: TGUID;
Secure: Boolean): TBluetoothServerSocket;
begin
Result := TWinBluetoothServerSocket.Create(AName, AUUID, Secure, BthAddressToString(GetBthAddress));
end;
procedure TWinBluetoothAdapter.DoDiscoverableEnd(const Sender: TObject);
begin
BluetoothEnableDiscovery(FRadioHandle, FALSE);
inherited DoDiscoverableEnd(Self);
end;
{ TWinBluetoothDevice }
constructor TWinBluetoothDevice.Create(const AnAdapter: TWinBluetoothAdapter; const ADeviceInfo: TBluetoothDeviceInfo);
begin
inherited Create;
FType := TBluetoothType.Classic;
FDeviceInfo := ADeviceInfo;
FAdapter := AnAdapter;
end;
function TWinBluetoothDevice.DoCreateClientSocket(const AUUID: TGUID; Secure: Boolean): TBluetoothSocket;
begin
Result := TWinBluetoothSocket.Create(INVALID_SOCKET, FDeviceInfo.Address, AUUID, Secure);
end;
function SdpCallBack(uAttribId: ULONG; pValueStream: LPBYTE; cbStreamSize: ULONG; pvParam: LPVOID): BOOL; stdcall;
procedure CreateGUID16(var Guuid: TBluetoothUUID; PData: PByte); inline;
begin
Guuid := Bluetooth_Base_UUID;
Guuid.D1 := (PData[0] shl 8) or PData[1];
end;
procedure CreateGUID128(var Guuid: TBluetoothUUID; PData: PByte); inline;
begin
Guuid := TGUID.Create(PData^, TEndian.Big);
end;
function GetSDPName(element: TSdpElementData): string;
var
Buffer: TBytes;
begin
SetLength(Buffer, element.&string.length);
if element.&string.length > 0 then
Move(element.&string.value^, Buffer[0], element.&string.length);
Result := TEncoding.UTF8.GetString(Buffer);
end;
type
PBluetoothService = ^TBluetoothService;
const // constants from bluetooth/sdp.h in android
SDP_UUID16 = $19;
SDP_UUID128 = $1C;
var
LPService: PBluetoothService;
element: TSdpElementData;
PData: PByteArray;
begin
LPService := pvParam;
// uAttribId 1 -> Service GUUID
if (uAttribId = 1) and (BluetoothSdpGetElementData(pValueStream, cbStreamSize, element) = ERROR_SUCCESS) and
(element.&type = SDP_TYPE_SEQUENCE) then
begin
PData := PByteArray(element.sequence.value + 2);
case PData[0] of
SDP_UUID16: CreateGUID16(LPService.UUID, @PData[1]);
SDP_UUID128: CreateGUID128(LPService.UUID, @PData[1]);
end;
end // uAttribId 256 -> Service Name
else if (uAttribId = 256) and (BluetoothSdpGetElementData(pValueStream, cbStreamSize, element) = ERROR_SUCCESS) and
(element.&type = SDP_TYPE_STRING) then
LPService.Name := GetSDPName(element);
Result := True;
end;
function TWinBluetoothDevice.DoGetServices: TBluetoothServiceList;
var
QuerySet: WSAQUERYSET;
PResults: LPWSAQUERYSET;
Flags: DWORD;
HLookup: THandle;
Buffer: TBytes;
BufferLen: DWORD;
Res: Integer;
LService: TBluetoothService;
begin
FServiceList.Clear;
Result := FServiceList;
FillChar(QuerySet, SizeOf(QuerySet), 0);
QuerySet.dwSize := SizeOf(QuerySet);
QuerySet.lpServiceClassId := @L2CAP_PROTOCOL_UUID;
QuerySet.dwNameSpace := NS_BTH;
QuerySet.lpszContext := LPWSTR(Address);
Flags := LUP_FLUSHCACHE or LUP_RETURN_ALL;
if WSALookupServiceBegin(@QuerySet, Flags, HLookup) = 0 then
begin
SetLength(Buffer, 2048);
PResults := @Buffer[0];
Res := 0;
while Res = 0 do
begin
BufferLen := 2048;
Res := WSALookupServiceNext(HLookup, Flags, BufferLen, PResults);
if Res <> 0 then
if WSAGetLastError = WSA_E_NO_MORE then
Break
else
raise EBluetoothDeviceException.CreateFmt(SBluetoothServiceListError, [WSAGetLastError, SysErrorMessage(WSAGetLastError)]);
if PResults.lpBlob <> nil then
begin
LService.UUID := GUID_NULL;
BluetoothSdpEnumAttributes(PResults.lpBlob.pBlobData, PResults.lpBlob.cbSize, SdpCallBack, @LService);
if LService.UUID <> GUID_NULL then
if LService.Name = '' then
LService.Name := TPlatformBluetoothClassicManager.GetKnownServiceName(LService.UUID);
FServiceList.Add(LService);
end;
end;
WSALookupServiceEnd(HLookup);
end;
end;
function TWinBluetoothDevice.GetAddress: TBluetoothMacAddress;
begin
Result := Format(SBluetoothMACAddressFormat, [FDeviceInfo.address.rgBytes[5], FDeviceInfo.address.rgBytes[4],
FDeviceInfo.address.rgBytes[3], FDeviceInfo.address.rgBytes[2], FDeviceInfo.address.rgBytes[1], FDeviceInfo.address.rgBytes[0]]);
end;
function TWinBluetoothDevice.GetBluetoothType: TBluetoothType;
begin
Result := TBluetoothType.Classic;
end;
function TWinBluetoothDevice.GetClassDevice: Integer;
begin
Result := 256 * GET_COD_MAJOR(FDeviceInfo.ulClassofDevice) + 4 * GET_COD_MINOR(FDeviceInfo.ulClassofDevice);
end;
function TWinBluetoothDevice.GetClassDeviceMajor: Integer;
begin
Result := 256 * GET_COD_MAJOR(FDeviceInfo.ulClassofDevice);
end;
function TWinBluetoothDevice.GetDeviceName: string;
begin
Result := FDeviceInfo.szName;
if Result = '' then
if BluetoothGetDeviceInfo(FAdapter.FRadioHandle, FDeviceInfo) <> ERROR_SUCCESS then
raise EBluetoothDeviceException.CreateFmt(SBluetoothDeviceInfoError, [GetLastError, SysErrorMessage(GetLastError)]);
Result := FDeviceInfo.szName;
end;
function TWinBluetoothDevice.GetPaired: Boolean;
begin
Result := FDeviceInfo.fAuthenticated = True;
end;
function TWinBluetoothDevice.GetState: TBluetoothDeviceState;
begin
if FDeviceInfo.fConnected then
Result := TBluetoothDeviceState.Connected
else if FDeviceInfo.fAuthenticated then
Result := TBluetoothDeviceState.Paired
else
Result := TBluetoothDeviceState.None;
end;
{ TWinBluetoothAdapter.TThreadTimer }
procedure TWinBluetoothAdapter.TThreadTimer.Cancel;
begin
Terminate;
if Assigned(FOnTimer) then
begin
FOnTimer := nil;
FEvent.SetEvent;
end;
end;
constructor TWinBluetoothAdapter.TThreadTimer.Create(const AEvent: TDiscoverableEndEvent; Timeout: Cardinal);
begin
inherited Create(True);
FOnTimer := AEvent;
FTimeout := Timeout;
FEvent := TEvent.Create;
end;
destructor TWinBluetoothAdapter.TThreadTimer.Destroy;
begin
Cancel;
FEvent.Free;
inherited;
end;
procedure TWinBluetoothAdapter.TThreadTimer.Execute;
begin
inherited;
FEvent.WaitFor(FTimeout);
if not Terminated and Assigned(FOnTimer) then
try
FOnTimer(nil);
except
Synchronize(procedure
begin
if Assigned(System.Classes.ApplicationHandleException) then
System.Classes.ApplicationHandleException(Self)
else
raise;
end);
end;
end;
{ TWinBluetoothAdapter.TDiscoverThread }
procedure TWinBluetoothAdapter.TDiscoverThread.Cancel;
begin
Cancelled := True;
end;
constructor TWinBluetoothAdapter.TDiscoverThread.Create(const AnAdapter: TWinBluetoothAdapter; Timeout: Cardinal);
begin
inherited Create(True);
FAdapter := AnAdapter;
Cancelled := False;
FTimeout := Timeout;
end;
procedure TWinBluetoothAdapter.TDiscoverThread.Execute;
begin
inherited;
FAdapter.GetDevicesByParam(FAdapter.FManager.LastDiscoveredDevices, 'DiscoverDevices', FTimeout);
FAdapter.FState := TBluetoothAdapterState.&On;
if not Cancelled and not Terminated then
try
FAdapter.DoDiscoveryEnd(FAdapter, FAdapter.FManager.LastDiscoveredDevices);
except
Synchronize(procedure
begin
if Assigned(System.Classes.ApplicationHandleException) then
System.Classes.ApplicationHandleException(Self)
else
raise;
end);
end;
end;
{ TWinBluetoothServerSocket }
destructor TWinBluetoothServerSocket.Destroy;
begin
Close;
inherited;
end;
function TWinBluetoothServerSocket.DoAccept(Timeout: Cardinal): TBluetoothSocket;
var
ClientSocket: TSocket;
fds: fd_set;
tv: timeval;
res: Integer;
begin
inherited;
if Timeout = 0 then
begin
ClientSocket := Winapi.Winsock2.accept(FListenSocket, nil, nil);
if ClientSocket = INVALID_SOCKET then
begin
closesocket(FListenSocket);
raise EBluetoothSocketException.Create(SBluetoothAcceptError);
end;
Result := TWinBluetoothSocket.Create(ClientSocket, BLUETOOTH_NULL_ADDRESS, GUID_NULL, FSecured);
end
else
begin
FD_ZERO(fds);
_FD_SET(FListenSocket, fds);
tv.tv_sec := Timeout div 1000;
tv.tv_usec := (Timeout mod 1000) * 1000;
res := select(FListenSocket+1, @fds, nil, nil, @tv);
if res <> SOCKET_ERROR then
begin
if FD_ISSET(FListenSocket, fds) then
begin
ClientSocket := Winapi.Winsock2.accept(FListenSocket, nil, nil);
if ClientSocket = INVALID_SOCKET then
begin
closesocket(FListenSocket);
raise EBluetoothSocketException.Create(SBluetoothAcceptError);
end;
Result := TWinBluetoothSocket.Create(ClientSocket, BLUETOOTH_NULL_ADDRESS, GUID_NULL, FSecured);
end
else
Result := nil; { Timeout }
end
else
begin
closesocket(FListenSocket);
raise EBluetoothSocketException.Create(SBluetoothAcceptError);
end;
end;
end;
procedure TWinBluetoothServerSocket.DoClose;
begin
inherited;
closesocket(FListenSocket);
WSASetService(@FWSAService, RNRSERVICE_DELETE, 0);
end;
constructor TWinBluetoothServerSocket.Create(const AName: string; const AUUID: TGUID; Secure: Boolean; const MACAddress: string);
function FindWSAService(const MACAddress: string; const AGUID: TGUID): Boolean;
var
QuerySet: WSAQUERYSET;
PResults: LPWSAQUERYSET;
Flags: DWORD;
HLookup: THandle;
Buffer: TBytes;
BufferLen: DWORD;
Res: Integer;
LService: TBluetoothService;
begin
Result := False;
FillChar(QuerySet, SizeOf(QuerySet), 0);
QuerySet.dwSize := SizeOf(QuerySet);
QuerySet.lpServiceClassId := @L2CAP_PROTOCOL_UUID;
QuerySet.dwNameSpace := NS_BTH;
QuerySet.lpszContext := LPWSTR(MACAddress);
Flags := LUP_FLUSHCACHE or LUP_RETURN_ALL;
if WSALookupServiceBegin(@QuerySet, Flags, HLookup) = 0 then
begin
SetLength(Buffer, 2048);
PResults := @Buffer[0];
Res := 0;
while Res = 0 do
begin
BufferLen := 2048;
Res := WSALookupServiceNext(HLookup, Flags, BufferLen, PResults);
if Res <> 0 then
if WSAGetLastError = WSA_E_NO_MORE then
Break
else
raise EBluetoothSocketException.CreateFmt(SBluetoothWSALookupError, [WSAGetLastError, SysErrorMessage(WSAGetLastError)]);
if PResults.lpBlob <> nil then
begin
LService.UUID := GUID_NULL;
BluetoothSdpEnumAttributes(PResults.lpBlob.pBlobData, PResults.lpBlob.cbSize, SdpCallBack, @LService);
if LService.UUID = AGUID then
begin
Result := True;
Break;
end;
end;
end;
WSALookupServiceEnd(HLookup);
end
else
raise EBluetoothSocketException.CreateFmt(SBluetoothWSALookupError, [WSAGetLastError, SysErrorMessage(WSAGetLastError)]);
end;
var
PAddress: PSockAddr;
AddrLen: Integer;
Value: Cardinal;
begin
inherited Create;
FSecured := Secure;
if FindWSAService(MACAddress, AUUID) then
raise EBluetoothSocketException.Create(SBluetoothUsedGUIDError);
FListenSocket := socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM);
if FListenSocket = INVALID_SOCKET then
raise EBluetoothSocketException.Create(SBluetoothCreateSocketError);
FillChar(FAddressBth, SizeOf(FAddressBth), 0);
FAddressBth.addressFamily := AF_BTH;
FAddressBth.port := BT_PORT_ANY;
FAddressBth.serviceClassId := GUID_NULL;
PAddress := @FAddressBth;
if bind(FListenSocket, PAddress^, Sizeof(TSockAddrBth)) <> 0 then
raise EBluetoothSocketException.CreateFmt(SBluetoothServerSocket, [SysErrorMessage(WSAGetLastError)]);
AddrLen := SizeOf(TSockAddrBth);
if getsockname(FListenSocket, PAddress^, AddrLen) = SOCKET_ERROR then
raise EBluetoothSocketException.CreateFmt(SBluetoothServerSocket, [SysErrorMessage(WSAGetLastError)]);
if Secure then
begin
Value := 1;
AddrLen := SizeOf(Value);
if setsockopt(FListenSocket, SOL_RFCOMM, Integer(SO_BTH_AUTHENTICATE), MarshaledAString(@Value), AddrLen) = SOCKET_ERROR then
raise EBluetoothSocketException.CreateFmt(SBluetoothServerSocket, [SysErrorMessage(WSAGetLastError)]);
AddrLen := SizeOf(Value);
if setsockopt(FListenSocket, SOL_RFCOMM, SO_BTH_ENCRYPT, MarshaledAString(@Value), AddrLen) = SOCKET_ERROR then
raise EBluetoothSocketException.CreateFmt(SBluetoothServerSocket, [SysErrorMessage(WSAGetLastError)]);
end;
FillChar(FCsAddr, SizeOf(FCsAddr), 0);
FCsAddr.LocalAddr.iSockaddrLength := SizeOf(TSockAddrBth);
FCsAddr.LocalAddr.lpSockaddr := LPSOCKADDR(PAddress);
FCsAddr.RemoteAddr.iSockaddrLength := SizeOf(TSockAddrBth);
FCsAddr.RemoteAddr.lpSockaddr := LPSOCKADDR(PAddress);
FCsAddr.iSocketType := SOCK_STREAM;
FCsAddr.iProtocol := BTHPROTO_RFCOMM;
FillChar(FWSAService, SizeOf(FWSAService), 0);
FWSAService.dwSize := SizeOf(FWSAService);
FWSAService.lpServiceClassId := @AUUID;
FWSAService.lpszServiceInstanceName := PWideChar(AName);
FWSAService.dwNumberOfCsAddrs := 1;
FWSAService.dwNameSpace := NS_BTH;
FWSAService.lpcsaBuffer := @FCsAddr;
if WSASetService(@FWSAService, RNRSERVICE_REGISTER, 0) = SOCKET_ERROR then
raise EBluetoothSocketException.CreateFmt(SBluetoothServiceError, [WSAGetLastError, SysErrorMessage(WSAGetLastError)]);
if listen(FListenSocket, 4) = SOCKET_ERROR then
raise EBluetoothSocketException.CreateFmt(SBluetoothServerSocket, [SysErrorMessage(WSAGetLastError)]);
end;
{ TWinBluetoothSocket }
constructor TWinBluetoothSocket.Create(const ASocket: TSocket; const AnAddress: TBluetoothAddress; const AUUID: TGUID; Secure: Boolean);
var
time: Cardinal;
begin
inherited Create;
FGUIDService := AUUID;
FClientSocket := ASocket;
FConnected := False;
FSecure := Secure;
FAddress := AnAddress;
FLastReadTimeout := 0;
if FGUIDService = GUID_NULL then
FConnected := True;
if FClientSocket <> INVALID_SOCKET then
begin
Case TBluetoothManager.SocketTimeout of
0: time := 1;
INFINITE: time := 0;
else
time := TBluetoothManager.SocketTimeout;
end;
if setsockopt(FClientSocket, SOL_SOCKET, SO_RCVTIMEO, MarshaledAString(@time), SizeOf(time)) = SOCKET_ERROR then
raise EBluetoothSocketException.CreateFmt(SBluetoothRCVTIMEOError, [SysErrorMessage(WSAGetLastError)]);
FConnected := True;
FLastReadTimeout := TBluetoothManager.SocketTimeout;
end;
end;
class constructor TWinBluetoothSocket.Create;
var
LWsData: TWSAData;
begin
if WSAStartup(MAKEWORD(2, 2), LWsData) <> 0 then
raise EBluetoothSocketException.Create(SBluetoothWisockInitError);
end;
destructor TWinBluetoothSocket.Destroy;
begin
Close;
inherited;
end;
class destructor TWinBluetoothSocket.Destroy;
begin
if WSACleanup <> 0 then
raise EBluetoothSocketException.Create(SBluetoothWisockCleanupError);
end;
procedure TWinBluetoothSocket.DoClose;
begin
inherited;
if FConnected then
begin
closesocket(FClientSocket);
FConnected := False;
FClientSocket := INVALID_SOCKET;
end;
end;
procedure TWinBluetoothSocket.DoConnect;
var
LClientService: TSockAddrBth;
PService: PSockAddr;
AddrLen: Integer;
Value: Cardinal;
Error: Integer;
time: Cardinal;
begin
inherited;
if not FConnected and (FGUIDService <> GUID_NULL) then
begin
FLastReadTimeout := 0;
if FClientSocket <> INVALID_SOCKET then
closesocket(FClientSocket);
FClientSocket := socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM);
if FClientSocket = INVALID_SOCKET then
raise EBluetoothSocketException.Create(SBluetoothClientsocketError);
Case TBluetoothManager.SocketTimeout of
0: time := 1;
INFINITE: time := 0;
else
time := TBluetoothManager.SocketTimeout;
end;
if setsockopt(FClientSocket, SOL_SOCKET, SO_RCVTIMEO, MarshaledAString(@time), SizeOf(time)) = SOCKET_ERROR then
raise EBluetoothSocketException.CreateFmt(SBluetoothRCVTIMEOError, [SysErrorMessage(WSAGetLastError)]);
if FSecure then
begin
Value := 1;
AddrLen := SizeOf(Value);
if setsockopt(FClientSocket, SOL_RFCOMM, Integer(SO_BTH_AUTHENTICATE), MarshaledAString(@Value), AddrLen) = SOCKET_ERROR then
raise EBluetoothSocketException.CreateFmt(SBluetoothSetSockOptError, [SysErrorMessage(WSAGetLastError)]);
AddrLen := SizeOf(Value);
if setsockopt(FClientSocket, SOL_RFCOMM, SO_BTH_ENCRYPT, MarshaledAString(@Value), AddrLen) = SOCKET_ERROR then
raise EBluetoothSocketException.CreateFmt(SBluetoothSetSockOptError, [SysErrorMessage(WSAGetLastError)]);
end;
FillChar(LClientService, SizeOf(LClientService), 0);
LClientService.addressFamily := AF_BTH;
LClientService.btAddr := FAddress.ullLong;
LClientService.serviceClassId := FGUIDService;
PService := @LClientService;
if Winapi.Winsock2.connect(FClientSocket, PService^, SizeOf(LClientService)) = SOCKET_ERROR then
begin
Error := WSAGetLastError;
Close;
raise EBluetoothSocketException.CreateFmt(SBluetoothClientConnectError, [Error, SysErrorMessage(Error)]);
end;
FConnected := True;
FLastReadTimeout := TBluetoothManager.SocketTimeout;
end;
end;
function TWinBluetoothSocket.DoReceiveData(ATimeout: Cardinal): TBytes;
const
BuffLen = 4096;
var
Received: Integer;
Readed: Integer;
Error: Integer;
time: Cardinal;
begin
if not FConnected then
raise EBluetoothSocketException.Create(SBluetoothRFChannelClosed);
if FLastReadTimeout <> ATimeout then
begin
Case ATimeout of
0: time := 1;
INFINITE: time := 0;
else
time := ATimeout;
end;
if setsockopt(FClientSocket, SOL_SOCKET, SO_RCVTIMEO, MarshaledAString(@time), SizeOf(time)) = SOCKET_ERROR then
raise EBluetoothSocketException.CreateFmt(SBluetoothRCVTIMEOError, [SysErrorMessage(WSAGetLastError)]);
FLastReadTimeout := ATimeout;
end;
Readed := 0;
repeat
SetLength(Result, Readed + BuffLen);
Received := Winapi.Winsock2.recv(FClientSocket, Result[Readed], BuffLen, 0);
if Received = SOCKET_ERROR then
begin
Error := WSAGetLastError;
if Error = WSAETIMEDOUT then
Break
else
begin
Close;
raise EBluetoothSocketException.Create(SBluetoothRFChannelClosed);
end;
end;
Readed := Readed + Received;
until Received < BuffLen;
if (Readed = 0) and (Received = 0) then
begin
DoClose;
raise EBluetoothSocketException.Create(SBluetoothRFChannelClosed);
end;
SetLength(Result, Readed);
end;
procedure TWinBluetoothSocket.DoSendData(const AData: TBytes);
var
Error: Integer;
DataLen: Integer;
Sent: Integer;
begin
inherited;
if not FConnected then
raise EBluetoothSocketException.Create(SBluetoothCanNotSendData);
Sent := 0;
DataLen := Length(AData);
repeat
Sent := Sent + Winapi.Winsock2.send(FClientSocket, AData[Sent], DataLen - Sent, 0);
if Sent = SOCKET_ERROR then
begin
Error := WSAGetLastError;
Close;
raise EBluetoothSocketException.CreateFmt(SBluetoothSendDataError, [Error, SysErrorMessage(Error)]);
end;
until Sent >= DataLen;
end;
function TWinBluetoothSocket.GetConnected: Boolean;
begin
Result := FConnected;
end;
{$ENDIF BLUETOOTH_CLASSIC}
{$IFDEF BLUETOOTH_LE}
{ TPlatformBluetoothLEManager }
class function TPlatformBluetoothLEManager.GetBluetoothManager: TBluetoothLEManager;
begin
if TOSVersion.Check(10) then
Result := TPlatformWinRTBluetoothLEManager.GetBluetoothManager
else
Result := TWinBluetoothLEManager.Create;
end;
{ TWinBluetoothLEManager }
function TWinBluetoothLEManager.DoGetGattServer: TBluetoothGattServer;
begin
{ Gatt Server not supported on Windows Platform }
raise EBluetoothManagerException.Create(SBluetoothNotImplemented);
Result := nil;
end;
function TWinBluetoothLEManager.GetAdapterState: TBluetoothAdapterState;
var
btfrp: TBlueToothFindRadioParams;
hRadio: THandle;
hFind: HBLUETOOTH_RADIO_FIND;
begin
FillChar(btfrp, SizeOf(btfrp), 0);
btfrp.dwSize := SizeOf(btfrp);
hFind := BluetoothFindFirstRadio(btfrp, hRadio);
if hFind <> 0 then
begin
Result := TBluetoothAdapterState.&On;
if FLEAdapter = nil then
FLEAdapter := TWinBluetoothLEAdapter.Create(Self);
BluetoothFindRadioClose(hFind);
end
else
Result := TBluetoothAdapterState.Off;
end;
function TWinBluetoothLEManager.DoGetAdapter: TBluetoothLEAdapter;
begin
if GetAdapterState = TBluetoothAdapterState.Off then
FLEAdapter := nil;
Result := FLEAdapter;
end;
function TWinBluetoothLEManager.DoGetSupportsGattClient: Boolean;
begin
Result := CheckOSVersionForGattClient;
end;
function TWinBluetoothLEManager.DoGetSupportsGattServer: Boolean;
begin
Result := CheckOSVersionForGattServer;
end;
function TWinBluetoothLEManager.GetConnectionState: TBluetoothConnectionState;
begin
if GetAdapterState = TBluetoothAdapterState.&On then
Result := TBluetoothConnectionState.Connected
else
Result := TBluetoothConnectionState.Disconnected;
end;
destructor TWinBluetoothLEManager.Destroy;
begin
FLEAdapter.Free;
inherited;
end;
function TWinBluetoothLEManager.DoEnableBluetooth: Boolean;
begin
Result := False;
end;
{ TWinBluetoothLEAdapter }
procedure TWinBluetoothLEAdapter.ChangeBTDeviceConnectionStatus(ABthAddress: BTH_ADDR; AConnected: Boolean);
var
I: Integer;
ADevAddress: string;
ADevice: TBluetoothLEDevice;
begin
ADevAddress := BthAddressToString(TBluetoothAddress(ABthAddress));
for I := 0 to FManager.AllDiscoveredDevices.Count - 1 do
begin
if FManager.AllDiscoveredDevices[I].Address = ADevAddress then
begin
ADevice := FManager.AllDiscoveredDevices[I];
if AConnected and Assigned(ADevice.OnConnect) then
ADevice.OnConnect(ADevice)
else if (not AConnected) and Assigned(ADevice.OnDisconnect) then
ADevice.OnDisconnect(ADevice);
Exit;
end;
end;
end;
constructor TWinBluetoothLEAdapter.Create(const AManager: TBluetoothLEManager);
begin
inherited;
FRadioInfo := GetRadioInfo;
FCancelConnectionFunction := GetApiFunction(bthapile, 'BthpGATTCloseSession');
FWinHandle := AllocateHWnd(WndProc);
RegisterBTChangeNotification;
end;
destructor TWinBluetoothLEAdapter.Destroy;
begin
if FHardwareDeviceInfo <> nil then
SetupDiDestroyDeviceInfoList(FHardwareDeviceInfo);
UnregisterBTChangeNotification;
DeallocateHWnd(FWinHandle);
inherited;
end;
procedure TWinBluetoothLEAdapter.GetBLEDevices;
var
deviceInterfaceData: SP_DEVICE_INTERFACE_DATA;
deviceInterfaceDetailData: PSP_DEVICE_INTERFACE_DETAIL_DATA;
DeviceInfo: SP_DEVINFO_DATA;
requiredLength: Cardinal;
err: Cardinal;
I: Integer;
Path: string;
PropertyBuffer: TBytes;
PropertyType: DEVPROPTYPE;
DeviceName: string;
LTWinBluetoothLEDevice: TWinBluetoothLEDevice;
begin
if FHardwareDeviceInfo <> nil then
SetupDiDestroyDeviceInfoList(FHardwareDeviceInfo);
deviceInterfaceDetailData := PSP_DEVICE_INTERFACE_DETAIL_DATA(GetMemory(1024));
try
FHardwareDeviceInfo := SetupDiGetClassDevs(@GUID_BLUETOOTHLE_DEVICE_INTERFACE, nil, 0, DIGCF_PRESENT or DIGCF_DEVICEINTERFACE);
if THandle(FHardwareDeviceInfo) = INVALID_HANDLE_VALUE then
raise EBluetoothLEAdapterException.CreateFmt(SBluetoothLEGetDevicesError, [GetLastError, SysErrorMessage(GetLastError)]);
SetLength(PropertyBuffer, 1024);
I := 0;
while True do
begin
DeviceInfo.cbSize := SizeOf(SP_DEVINFO_DATA);
if SetupDiEnumDeviceInfo(FHardwareDeviceInfo, I, DeviceInfo) = FALSE then
begin
err := GetLastError;
if err <> ERROR_NO_MORE_ITEMS then
raise EBluetoothLEAdapterException.CreateFmt(SBluetoothLEGetDevicesError, [GetLastError, SysErrorMessage(GetLastError)]);
Break;
end;
if SetupDiGetDeviceProperty(FHardwareDeviceInfo, DeviceInfo, @DEVPKEY_Device_FriendlyName,
PropertyType, @PropertyBuffer[0], 1024, @requiredLength, 0) = FALSE then
raise EBluetoothLEAdapterException.CreateFmt(SBluetoothLEGetDevicesError, [GetLastError, SysErrorMessage(GetLastError)]);
DeviceName := TEncoding.Unicode.GetString(PropertyBuffer, 0, requiredLength - 1);
FillChar(deviceInterfaceData, SizeOf(deviceInterfaceData), 0);
deviceInterfaceData.cbSize := SizeOf(deviceInterfaceData);
if SetupDiEnumDeviceInterfaces(FHardwareDeviceInfo, nil,
@GUID_BLUETOOTHLE_DEVICE_INTERFACE, I, deviceInterfaceData) = FALSE then
begin
err := GetLastError;
if err <> ERROR_NO_MORE_ITEMS then
raise EBluetoothLEAdapterException.CreateFmt(SBluetoothLEGetDevicesError, [GetLastError, SysErrorMessage(GetLastError)]);
Break;
end;
FillChar(deviceInterfaceDetailData^, 1024, 0);
deviceInterfaceDetailData.cbSize := SizeOf(SP_DEVICE_INTERFACE_DETAIL_DATA) ;
if SetupDiGetDeviceInterfaceDetail (FHardwareDeviceInfo, deviceInterfaceData,
deviceInterfaceDetailData, 1024, @requiredLength, nil) = FALSE then
raise EBluetoothLEAdapterException.CreateFmt(SBluetoothLEGetDevicesError, [GetLastError, SysErrorMessage(GetLastError)]);
Path := PChar(@deviceInterfaceDetailData.DevicePath[0]);
LTWinBluetoothLEDevice := TWinBluetoothLEDevice(TWinBluetoothLEManager.GetDeviceInList(TWinBluetoothLEDevice.ExtractMacAddres(Path),
FManager.AllDiscoveredDevices));
{ RSSI not supported on windows }
{ Advertise Data not supported on windows }
if LTWinBluetoothLEDevice = nil then
begin
LTWinBluetoothLEDevice := TWinBluetoothLEDevice.Create(DeviceName, Path, Self, False);
LTWinBluetoothLEDevice.FDeviceInfo := DeviceInfo;
DoDeviceDiscovered(LTWinBluetoothLEDevice, True, nil);
end
else
DoDeviceDiscovered(LTWinBluetoothLEDevice, False, nil);
Inc(I);
end;
finally
FreeMemory(deviceInterfaceDetailData);
end;
end;
function TWinBluetoothLEAdapter.DoStartDiscovery(Timeout: Cardinal; const AFilterUUIDList: TBluetoothUUIDsList;
const ABluetoothLEScanFilterList: TBluetoothLEScanFilterList): Boolean;
begin
GetBLEDevices;
TWinBluetoothLEManager(FManager).DoDiscoveryEnd(Self, nil);
Result := True;
end;
function TWinBluetoothLEAdapter.DoStartDiscoveryRaw(const ABluetoothLEScanFilterList: TBluetoothLEScanFilterList; Refresh: Boolean): Boolean;
begin
raise EBluetoothAdapterException.Create(SBluetoothNotImplemented);
end;
function TWinBluetoothLEAdapter.GetAdapterName: string;
begin
Result := FRadioInfo.szName;
end;
function TWinBluetoothLEAdapter.GetAddress: System.Bluetooth.TBluetoothMacAddress;
var
LAddress: TBluetoothAddress;
begin
Result := '00:00:00:00:00:00'; // Do not translate
LAddress := FRadioInfo.address;
if LAddress.ullLong <> BLUETOOTH_NULL_ADDRESS.ullLong then
Result := BthAddressToString(LAddress);
end;
function TWinBluetoothLEAdapter.GetRadioInfo: TBluetoothRadioInfo;
var
btfrp: TBlueToothFindRadioParams;
hRadio: THandle;
hFind: HBLUETOOTH_RADIO_FIND;
begin
FillChar(btfrp, SizeOf(btfrp), 0);
btfrp.dwSize := SizeOf(btfrp);
hFind := BluetoothFindFirstRadio(btfrp, hRadio);
if hFind <> 0 then
begin
Result.dwSize := SizeOf(TBluetoothRadioInfo);
BluetoothGetRadioInfo(hRadio, Result);
BluetoothFindRadioClose(hFind);
end;
end;
function TWinBluetoothLEAdapter.GetScanMode: TBluetoothScanMode;
begin
Result := Default(TBluetoothScanMode);
end;
function TWinBluetoothLEAdapter.GetState: TBluetoothAdapterState;
begin
Result := Default(TBluetoothAdapterState);
end;
procedure TWinBluetoothLEAdapter.RegisterBTChangeNotification;
var
btfrp: TBlueToothFindRadioParams;
hRadio: THandle;
hFind: HBLUETOOTH_RADIO_FIND;
LNotificationFilter: TDevBroadcastHandle;
begin
FillChar(btfrp, SizeOf(btfrp), 0);
btfrp.dwSize := SizeOf(btfrp);
hFind := BluetoothFindFirstRadio(btfrp, hRadio);
if (hFind <> 0) and (FWinHandle <> INVALID_HANDLE_VALUE) then
begin
BluetoothFindRadioClose(hFind);
ZeroMemory(@LNotificationFilter, SizeOf(LNotificationFilter));
LNotificationFilter.dbch_size:= SizeOf(LNotificationFilter);
LNotificationFilter.dbch_devicetype := DBT_DEVTYP_HANDLE;
LNotificationFilter.dbch_handle := hRadio;
FNotificationHandle := RegisterDeviceNotification(FWinHandle, @LNotificationFilter, DEVICE_NOTIFY_WINDOW_HANDLE);
end
end;
procedure TWinBluetoothLEAdapter.SetAdapterName(const Value: string);
begin
raise EBluetoothAdapterException.Create(SBluetoothNotImplemented);
end;
procedure TWinBluetoothLEAdapter.UnregisterBTChangeNotification;
begin
if Assigned(FNotificationHandle) then
UnregisterDeviceNotification(FNotificationHandle);
end;
procedure TWinBluetoothLEAdapter.WndProc(var Msg: TMessage);
var
pHciEventInfo: PBTH_HCI_EVENT_INFO;
begin
if (Msg.Msg = WM_DEVICECHANGE) and (Msg.WParam = DBT_CUSTOMEVENT) and
(PDevBroadcastHandle(Msg.LParam).dbch_eventguid = GUID_BLUETOOTH_HCI_EVENT) then
begin
pHciEventInfo := PBTH_HCI_EVENT_INFO(@PDevBroadcastHandle(Msg.LParam).dbch_data);
if (pHciEventInfo.connectionType = HCI_CONNECTION_TYPE_LE) then
ChangeBTDeviceConnectionStatus(pHciEventInfo.bthAddress, pHciEventInfo.connected <> 0);
end
else
Msg.Result := DefWindowProc(FWinHandle, Msg.Msg, Msg.wParam, Msg.lParam);
end;
procedure TWinBluetoothLEAdapter.DoCancelDiscovery;
begin
inherited;
{ Makes no sense in windows }
end;
{ TWinBluetoothGattClient }
constructor TWinBluetoothLEDevice.Create(const AName, APath: string; const ALEAdapter: TWinBluetoothLEAdapter; AutoConnect: Boolean);
begin
inherited Create(AutoConnect);
FDeviceName := AName;
FDevicePath := APath;
FMacAddress := ExtractMacAddres(APath);
FLEAdapter := ALEAdapter;
FLEDeviceHandle := CreateFile(PWideChar(FDevicePath), GENERIC_READ or GENERIC_WRITE, 0, nil, OPEN_EXISTING, 0, 0);
if FLEDeviceHandle = INVALID_HANDLE_VALUE then
FLEDeviceHandle := CreateFile(PWideChar(FDevicePath), GENERIC_READ, 0, nil, OPEN_EXISTING, 0, 0);
if FLEDeviceHandle = INVALID_HANDLE_VALUE then
raise EBluetoothLEDeviceException.CreateFmt(SBluetoothLEDeviceHandleError, [Error, SysErrorMessage(Error)]);
FPaired := True;
end;
destructor TWinBluetoothLEDevice.Destroy;
begin
if FReliableWriteContext <> 0 then
BluetoothGATTAbortReliableWrite(FLEDeviceHandle, FReliableWriteContext, BLUETOOTH_GATT_FLAG_NONE);
DoDisconnect;
CloseHandle(FLEDeviceHandle);
inherited;
end;
procedure TWinBluetoothLEDevice.DoAbortReliableWrite;
begin
BluetoothGATTAbortReliableWrite(FLEDeviceHandle, FReliableWriteContext, BLUETOOTH_GATT_FLAG_NONE);
FReliableWriteContext := 0;
end;
function TWinBluetoothLEDevice.DoBeginReliableWrite: Boolean;
var
Res: HRESULT;
begin
Res := BluetoothGATTBeginReliableWrite(FLEDeviceHandle, FReliableWriteContext, BLUETOOTH_GATT_FLAG_NONE);
Result := S_OK = HResultCode(res);
end;
function TWinBluetoothLEDevice.DoDiscoverServices: Boolean;
var
Res: HRESULT;
ServiceBufferCount: Word;
Services: array of TBthLeGattService;
I: Integer;
begin
Result := True;
FServices.Clear;
Res := BluetoothGATTGetServices(FLEDeviceHandle, 0, nil, ServiceBufferCount, BLUETOOTH_GATT_FLAG_NONE);
if HResultCode(res) <> ERROR_MORE_DATA then
raise EBluetoothLEServiceException.CreateFmt(SBluetoothLEGattServiceError, [res,res, GetLastError, SysErrorMessage(GetLastError)]);
SetLength(Services, ServiceBufferCount);
Fillchar(Services[0], ServiceBufferCount * SizeOf(TBthLeGattService), 0);
Res := BluetoothGATTGetServices(FLEDeviceHandle, serviceBufferCount, @Services[0], serviceBufferCount, BLUETOOTH_GATT_FLAG_NONE);
if S_OK <> HResultCode(res) then
raise EBluetoothLEServiceException.CreateFmt(SBluetoothLEGattServiceError, [GetLastError, SysErrorMessage(GetLastError)]);
for I := 0 to serviceBufferCount - 1 do
FServices.Add(TWinBluetoothGattService.Create(Self, Services[I], TBluetoothServiceType.Primary));
DoOnServicesDiscovered(Self, FServices);
end;
function TWinBluetoothLEDevice.DoExecuteReliableWrite: Boolean;
var
Res: HRESULT;
begin
Res := BluetoothGATTEndReliableWrite(FLEDeviceHandle, FReliableWriteContext, BLUETOOTH_GATT_FLAG_NONE);
Result := S_OK = HResultCode(res);
FReliableWriteContext := 0;
end;
function TWinBluetoothLEDevice.DoReadCharacteristic(const ACharacteristic: TBluetoothGattCharacteristic): Boolean;
begin
TThread.CreateAnonymousThread(procedure
begin
DoOnCharacteristicRead(ACharacteristic, TWinBluetoothGattCharacteristic(ACharacteristic).UpdateValueFromDevice);
end).Start;
Result := True;
end;
function TWinBluetoothLEDevice.DoReadDescriptor(const ADescriptor: TBluetoothGattDescriptor): Boolean;
begin
TThread.CreateAnonymousThread(procedure
begin
DoOnDescriptorRead(ADescriptor,
TWinBluetoothGattDescriptor(ADescriptor).UpdateValueFromDevice);
end).Start;
Result := True;
end;
function TWinBluetoothLEDevice.DoReadRemoteRSSI: Boolean;
begin
{ Not supported on windows }
Result := False;
end;
procedure NotificationCallback(EventType: TBthLeGattEventType; EventOutParameter: Pointer; Context: Pointer); stdcall;
begin
TWinBluetoothGattCharacteristic(Context).ValueChangeEvent(EventOutParameter);
end;
function TWinBluetoothLEDevice.DoConnect: Boolean;
begin
{ Not supported on windows }
Result := False;
end;
function TWinBluetoothLEDevice.DoCreateAdvertiseData: TBluetoothLEAdvertiseData;
begin
{ BluetoothLEAdvertiseData not supported on Windows Platform }
Result := nil;
end;
function TWinBluetoothLEDevice.RegisterNotification(const ACharacteristic: TBluetoothGattCharacteristic): Boolean;
var
Reg: TBluetoothGattValueChangedEventRegistration;
Res: HRESULT;
begin
Result := False;
if ACharacteristic.Properties * [TBluetoothProperty.Notify, TBluetoothProperty.Indicate] <> [] then
begin
Reg.NumCharacteristics := 1;
Reg.Characteristics[0] := TWinBluetoothGattCharacteristic(ACharacteristic).FGattCharacteristic;
Res := BluetoothGATTRegisterEvent(TWinBluetoothGattCharacteristic(ACharacteristic).ServiceHandle,
TBthLeGattEventType.CharacteristicValueChangedEvent, @Reg, @NotificationCallback, Pointer(ACharacteristic),
TWinBluetoothGattCharacteristic(ACharacteristic).FValueChangeEventHandle, BLUETOOTH_GATT_FLAG_NONE);
Result := S_OK = HResultCode(Res);
{$IFDEF AUTOREFCOUNT}
if Result then
ACharacteristic.__ObjAddRef;
{$ENDIF}
end;
end;
function TWinBluetoothLEDevice.UnregisterNotification(const ACharacteristic: TBluetoothGattCharacteristic): Boolean;
var
Res: HRESULT;
LHandle: TBluetoothGattEventHandle;
begin
Result := False;
LHandle := TWinBluetoothGattCharacteristic(ACharacteristic).FValueChangeEventHandle;
if LHandle <> 0 then
begin
Res := BluetoothGATTUnregisterEvent(LHandle, BLUETOOTH_GATT_FLAG_NONE);
Result := S_OK = HResultCode(Res);
TWinBluetoothGattCharacteristic(ACharacteristic).FValueChangeEventHandle := 0;
{$IFDEF AUTOREFCOUNT}
ACharacteristic.__ObjRelease;
{$ENDIF}
end;
end;
function TWinBluetoothLEDevice.DoSetCharacteristicNotification(const ACharacteristic: TBluetoothGattCharacteristic;
Enable: Boolean): Boolean;
const
Desc_Configuration: TBluetoothUUID = '{00002902-0000-1000-8000-00805F9B34FB}';
var
LDesc: TBluetoothGattDescriptor;
begin
if Enable then
Result := RegisterNotification(ACharacteristic)
else
Result := UnregisterNotification(ACharacteristic);
if Result then
begin
LDesc := ACharacteristic.GetDescriptor(Desc_Configuration);
if LDesc <> nil then
begin
if TBluetoothProperty.Notify in ACharacteristic.Properties then
LDesc.Notification := Enable
else
LDesc.Indication := Enable;
WriteDescriptor(LDesc);
end;
end;
end;
function TWinBluetoothLEDevice.DoWriteCharacteristic(const ACharacteristic: TBluetoothGattCharacteristic): Boolean;
begin
TThread.CreateAnonymousThread(procedure
begin
DoOnCharacteristicWrite(ACharacteristic, TWinBluetoothGattCharacteristic(ACharacteristic).SetValueToDevice);
end).Start;
Result := True;
end;
function TWinBluetoothLEDevice.DoWriteDescriptor(const ADescriptor: TBluetoothGattDescriptor): Boolean;
begin
TThread.CreateAnonymousThread(procedure
begin
DoOnDescriptorWrite(ADescriptor, TWinBluetoothGattDescriptor(ADescriptor).SetValueToDevice);
end).Start;
Result := True;
end;
class function TWinBluetoothLEDevice.ExtractMacAddres(const APath: string): TBluetoothMacAddress;
var
Temp: string;
begin
Temp := APath.ToUpper;
Result := Temp.Substring(Temp.IndexOf('#DEV_') + 5, 12); // Do not translate
Result.Insert(2,':');
Result.Insert(5,':');
Result.Insert(8,':');
Result.Insert(11,':');
Result.Insert(14,':');
end;
function TWinBluetoothLEDevice.GetAddress: TBluetoothMacAddress;
begin
Result := FMacAddress;
end;
function TWinBluetoothLEDevice.GetBluetoothType: TBluetoothType;
begin
Result := TBluetoothType.LE;
end;
function TWinBluetoothLEDevice.GetDeviceName: string;
begin
Result := FDeviceName;
end;
function TWinBluetoothLEDevice.GetIdentifier: string;
begin
Result := GetAddress;
end;
function TWinBluetoothLEDevice.GetIsConnected: Boolean;
var
PropertyBuffer: TBytes;
PropertyType: DEVPROPTYPE;
begin
Result := False;
SetLength(PropertyBuffer, 4);
if SetupDiGetDeviceProperty(FLEAdapter.FHardwareDeviceInfo, FDeviceInfo, @DEVPKEY_Device_DevNodeStatus,
PropertyType, @PropertyBuffer[0], 4, nil, 0) = FALSE then
raise EBluetoothLEDeviceException.CreateFmt(SBluetoothLEGetDevicesError, [GetLastError, SysErrorMessage(GetLastError)]);
if (PropertyBuffer[3] and DN_DEVICE_DISCONNECTED) = 0 then
Result := True;
end;
function TWinBluetoothLEDevice.DoDisconnect: Boolean;
begin
if Assigned(FLEAdapter.FCancelConnectionFunction) then
Result := S_OK = FLEAdapter.FCancelConnectionFunction(FLEDeviceHandle, BLUETOOTH_GATT_FLAG_NONE)
else
Result := False;
end;
{ TWinBluetoothGattCharacteristic }
constructor TWinBluetoothGattCharacteristic.Create(const AService: TWinBluetoothGattService;
const AGattCharacteristic: TBthLeGattCharacteristic);
begin
inherited Create(AService);
FLEDeviceHandle := AService.FLEDeviceHandle;
FGattService := AService.FGattService;
FGattCharacteristic := AGattCharacteristic;
end;
destructor TWinBluetoothGattCharacteristic.Destroy;
begin
if PValue <> nil then
FreeMemory(PValue);
if FValueChangeEventHandle <> 0 then
BluetoothGATTUnregisterEvent(FValueChangeEventHandle, BLUETOOTH_GATT_FLAG_NONE);
inherited;
end;
function TWinBluetoothGattCharacteristic.DoAddDescriptor(const ADescriptor: TBluetoothGattDescriptor): Boolean;
begin
Result := False;
end;
function TWinBluetoothGattCharacteristic.DoCreateDescriptor(const AUUID: TBluetoothUUID): TBluetoothGattDescriptor;
begin
raise EBluetoothLECharacteristicException.Create(SBluetoothNotImplemented);
Result := nil;
end;
function TWinBluetoothGattCharacteristic.DoGetDescriptors: TBluetoothGattDescriptorList;
var
res: HRESULT;
DescriptorBufferCount: Word;
Descriptors: array of TBthLeGattDescriptor;
I: Integer;
begin
Result := FDescriptors;
FDescriptors.Clear;
BluetoothGATTGetDescriptors(FLEDeviceHandle, FGattCharacteristic, 0, nil, DescriptorBufferCount, BLUETOOTH_GATT_FLAG_NONE);
if DescriptorBufferCount > 0 then
begin
SetLength(Descriptors, DescriptorBufferCount);
Fillchar(Descriptors[0], DescriptorBufferCount * SizeOf(TBthLeGattDescriptor), 0);
res := BluetoothGATTGetDescriptors(FLEDeviceHandle, FGattCharacteristic, DescriptorBufferCount, @Descriptors[0],
DescriptorBufferCount, BLUETOOTH_GATT_FLAG_NONE);
if S_OK <> HResultCode(res) then
raise EBluetoothLECharacteristicException.CreateFmt(SBluetoothLEGattServiceError, [GetLastError, SysErrorMessage(GetLastError)]);
for I := 0 to DescriptorBufferCount - 1 do
FDescriptors.Add(TWinBluetoothGattDescriptor.Create(Self, Descriptors[I]));
end;
end;
procedure TWinBluetoothGattDescriptor.CheckCreateValue;
begin
if PValue = nil then
begin
PValue := GetMemory(SizeOf(TBthLeGattDescriptorValue));
FillChar(PValue^, SizeOf(TBthLeGattDescriptorValue), 0);
PValue.DescriptorType := TBthLeGattDescriptorType(Ord(Kind) - 1);
PValue.DescriptorUuid := FGattDescriptor.DescriptorUuid;
end;
end;
function TWinBluetoothGattCharacteristic.DoGetValue: TBytes;
begin
if (PValue = nil) or (PValue.DataSize = 0) then
SetLength(Result, 0)
else
begin
SetLength(Result, PValue.DataSize);
Move(PValue.Data, Result[0], PValue.DataSize);
end;
end;
function TWinBluetoothGattCharacteristic.ServiceHandle: THandle;
begin
Result := TWinBluetoothGattService(FService).ServiceHandle;
end;
procedure TWinBluetoothGattCharacteristic.DoSetValue(const AValue: TBytes);
begin
if (PValue <> nil) and (Length(AValue) <> Integer(PValue.DataSize)) then
begin
FreeMemory(PValue);
PValue := nil;
end;
if PValue = nil then
begin
PValue := GetMemory(SizeOf(TBthLeGattCharacteristicValue) + Length(AValue));
PValue.DataSize := Length(AValue);
end;
if Length(AValue) > 0 then
Move(AValue[0], PValue.Data, Length(AValue));
end;
function TWinBluetoothGattCharacteristic.GetProperties: TBluetoothPropertyFlags;
begin
Result := [];
if FGattCharacteristic.IsBroadcastable then
Include(Result, TBluetoothProperty.Broadcast);
if FGattCharacteristic.IsReadable then
Include(Result, TBluetoothProperty.Read);
if FGattCharacteristic.IsWritable then
Include(Result, TBluetoothProperty.Write);
if FGattCharacteristic.IsWritableWithoutResponse then
Include(Result, TBluetoothProperty.WriteNoResponse);
if FGattCharacteristic.IsSignedWritable then
Include(Result, TBluetoothProperty.SignedWrite);
if FGattCharacteristic.IsNotifiable then
Include(Result, TBluetoothProperty.Notify);
if FGattCharacteristic.IsIndicatable then
Include(Result, TBluetoothProperty.Indicate);
end;
function TWinBluetoothGattCharacteristic.GetUUID: TBluetoothUUID;
begin
Result := TBthLeUuidToUUID(FGattCharacteristic.CharacteristicUuid);
end;
function TWinBluetoothGattCharacteristic.SetValueToDevice: TBluetoothGattStatus;
var
Flags: Cardinal;
begin
if FGattCharacteristic.IsWritableWithoutResponse then
Flags := BLUETOOTH_GATT_FLAG_WRITE_WITHOUT_RESPONSE
else
Flags := BLUETOOTH_GATT_FLAG_NONE;
Result := ErrorToStatus(BluetoothGATTSetCharacteristicValue(TWinBluetoothGattService(FService).ServiceHandle,
FGattCharacteristic, PValue, TWinBluetoothGattService(FService).FDevice.FReliableWriteContext, Flags));
end;
function TWinBluetoothGattCharacteristic.UpdateValueFromDevice: TBluetoothGattStatus;
var
Res: HRESULT;
Buffer: PBthLeGattCharacteristicValue;
function GetCharacteristicValue(out ABuffer: PBthLeGattCharacteristicValue): HRESULT;
var
LBufferSize: Word;
begin
Result := BluetoothGATTGetCharacteristicValue(TWinBluetoothGattService(FService).ServiceHandle, FGattCharacteristic, 0, nil, @LBufferSize, BLUETOOTH_GATT_FLAG_NONE);
if LBufferSize > 0 then
begin
ABuffer := GetMemory(LBufferSize);
try
Result := BluetoothGATTGetCharacteristicValue(TWinBluetoothGattService(FService).ServiceHandle, FGattCharacteristic, LBufferSize, ABuffer, nil, BLUETOOTH_GATT_FLAG_FORCE_READ_FROM_DEVICE);
if S_OK = HResultCode(Result) then
begin
if PValue <> nil then
FreeMemory(PValue);
PValue := ABuffer;
end
else
FreeMemory(ABuffer);
except
FreeMemory(ABuffer);
raise
end;
end;
end;
begin
Result := TBluetoothGattStatus.Success;
Res := GetCharacteristicValue(Buffer);
if HResultCode(Res) = ERROR_INVALID_USER_BUFFER then
Res := GetCharacteristicValue(Buffer);
if S_OK <> HResultCode(Res) then
Result := ErrorToStatus(Res)
end;
procedure TWinBluetoothGattCharacteristic.ValueChangeEvent(EventOutParameter: Pointer);
var
ValueChanged: PBluetoothGattValueChangedEvent;
Buffer: TBytes;
begin
TMonitor.Enter(Self);
try
ValueChanged := PBluetoothGattValueChangedEvent(EventOutParameter);
SetLength(Buffer, ValueChanged.CharacteristicValue.DataSize);
if ValueChanged.CharacteristicValue.DataSize > 0 then
Move(ValueChanged.CharacteristicValue.Data, Buffer[0], ValueChanged.CharacteristicValue.DataSize);
SetValue(Buffer);
TWinBluetoothGattService(FService).FDevice.DoOnCharacteristicRead(Self, TBluetoothGattStatus.Success);
finally
TMonitor.Exit(Self);
end;
end;
{ TWinBluetoothGattService }
constructor TWinBluetoothGattService.Create(const ADevice: TWinBluetoothLEDevice;const AGattService: TBthLeGattService;
AType: TBluetoothServiceType);
begin
inherited Create(TGUID.Empty, AType);
FDevice := ADevice;
FLEDeviceHandle := ADevice.FLEDeviceHandle;
FGattService := AGattService;
FType := AType;
FServiceHandle := INVALID_HANDLE_VALUE;
end;
destructor TWinBluetoothGattService.Destroy;
begin
CloseHandle(FServiceHandle);
inherited;
end;
function TWinBluetoothGattService.DoGetCharacteristics: TBluetoothGattCharacteristicList;
var
res: HRESULT;
CharacteristicsBufferCount: Word;
Characteristics: array of TBthLeGattCharacteristic;
I: Integer;
begin
Result := FCharacteristics;
FCharacteristics.Clear;
BluetoothGATTGetCharacteristics(FLEDeviceHandle, @FGattService, 0, nil, CharacteristicsBufferCount, BLUETOOTH_GATT_FLAG_NONE);
if CharacteristicsBufferCount > 0 then
begin
SetLength(Characteristics, CharacteristicsBufferCount);
Fillchar(Characteristics[0], CharacteristicsBufferCount * SizeOf(TBthLeGattService), 0);
res := BluetoothGATTGetCharacteristics(FLEDeviceHandle, @FGattService, CharacteristicsBufferCount, @Characteristics[0],
CharacteristicsBufferCount, BLUETOOTH_GATT_FLAG_NONE);
if S_OK <> HResultCode(res) then
raise EBluetoothServiceException.CreateFmt(SBluetoothLEGattIncludedServicesError, [GetLastError, SysErrorMessage(GetLastError)]);
for I := 0 to CharacteristicsBufferCount - 1 do
FCharacteristics.Add(TWinBluetoothGattCharacteristic.Create(Self, Characteristics[I]));
end;
end;
function TWinBluetoothGattService.DoGetIncludedServices: TBluetoothGattServiceList;
var
res: HRESULT;
serviceBufferCount: Word;
Services: array of TBthLeGattService;
I: Integer;
begin
Result := FIncludedServices;
FIncludedServices.Clear;
BluetoothGATTGetIncludedServices(FLEDeviceHandle, @FGattService, 0, nil, serviceBufferCount, BLUETOOTH_GATT_FLAG_NONE);
if serviceBufferCount > 0 then
begin
SetLength(Services, serviceBufferCount);
Fillchar(Services[0], serviceBufferCount * SizeOf(TBthLeGattService), 0);
res := BluetoothGATTGetIncludedServices(FLEDeviceHandle, @FGattService, serviceBufferCount, @Services[0],
serviceBufferCount, BLUETOOTH_GATT_FLAG_NONE);
if S_OK <> HResultCode(res) then
raise EBluetoothServiceException.CreateFmt(SBluetoothLEGattIncludedServicesError, [GetLastError, SysErrorMessage(GetLastError)]);
for I := 0 to serviceBufferCount - 1 do
FIncludedServices.Add(TWinBluetoothGattService.Create(FDevice, Services[I], TBluetoothServiceType.Primary));
end;
end;
function TWinBluetoothGattService.DoAddIncludedService(const AService: TBluetoothGattService): Boolean;
begin
raise EBluetoothServiceException.Create(SBluetoothNotImplemented);
Result := False;
end;
function TWinBluetoothGattService.DoAddCharacteristic(const ACharacteristic: TBluetoothGattCharacteristic): Boolean;
begin
raise EBluetoothServiceException.Create(SBluetoothNotImplemented);
Result := False;
end;
function TWinBluetoothGattService.DoCreateCharacteristic(const AUuid: TBluetoothUUID; APropertyFlags: TBluetoothPropertyFlags;
const ADescription: string): TBluetoothGattCharacteristic;
begin
raise EBluetoothServiceException.Create(SBluetoothNotImplemented);
Result := nil;
end;
function TWinBluetoothGattService.DoCreateIncludedService(const AnUUID: TBluetoothUUID; AType: TBluetoothServiceType): TBluetoothGattService;
begin
raise EBluetoothServiceException.Create(SBluetoothNotImplemented);
Result := nil;
end;
function TWinBluetoothGattService.GetHandle: THandle;
begin
if FServiceHandle = INVALID_HANDLE_VALUE then
FServiceHandle := GetServiceHandle;
Result := FServiceHandle;
end;
function TWinBluetoothGattService.GetServiceHandle: THandle;
var
hardwareDeviceInfo: HDEVINFO;
deviceInterfaceData: SP_DEVICE_INTERFACE_DATA;
deviceInterfaceDetailData: PSP_DEVICE_INTERFACE_DETAIL_DATA;
requiredLength: Cardinal;
err: Cardinal;
I: Integer;
Path: string;
LGUID: TGUID;
LMac: string;
begin
LMac := FDevice.FMacAddress;
LMac := LMac.Replace(':', '');
Result := INVALID_HANDLE_VALUE;
deviceInterfaceDetailData := PSP_DEVICE_INTERFACE_DETAIL_DATA(GetMemory(1024));
try
LGUID := UUID;
hardwareDeviceInfo := SetupDiGetClassDevs(@LGUID, nil, 0, DIGCF_PRESENT or DIGCF_DEVICEINTERFACE);
if THandle(hardwareDeviceInfo) = INVALID_HANDLE_VALUE then
raise Exception.CreateFmt(SBluetoothLEGetServicesHandle, [GetLastError, SysErrorMessage(GetLastError)]);
I := 0;
while True do
begin
FillChar(deviceInterfaceData, SizeOf(deviceInterfaceData), 0);
deviceInterfaceData.cbSize := SizeOf(deviceInterfaceData);
if SetupDiEnumDeviceInterfaces(hardwareDeviceInfo, nil,
@LGUID, I, deviceInterfaceData) = FALSE then
begin
err := GetLastError;
if err <> ERROR_NO_MORE_ITEMS then
raise Exception.CreateFmt(SBluetoothLEGetServicesHandle, [GetLastError, SysErrorMessage(GetLastError)]);
Break;
end;
FillChar(deviceInterfaceDetailData^, 1024, 0);
deviceInterfaceDetailData.cbSize := SizeOf(SP_DEVICE_INTERFACE_DETAIL_DATA) ;
if SetupDiGetDeviceInterfaceDetail (hardwareDeviceInfo, deviceInterfaceData,
deviceInterfaceDetailData, 1024, @requiredLength, nil) = FALSE then
raise Exception.CreateFmt(SBluetoothLEGetServicesHandle, [GetLastError, SysErrorMessage(GetLastError)]);
Path := PChar(@deviceInterfaceDetailData.DevicePath[0]);
if Path.ToUpper.Contains(LMac) then
begin
Result := CreateFile(PWideChar(Path), GENERIC_READ or GENERIC_WRITE, FILE_SHARE_READ or FILE_SHARE_WRITE, nil,
OPEN_EXISTING, 0, 0);
if Result = INVALID_HANDLE_VALUE then
Result := CreateFile(PWideChar(Path), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, 0, 0);
Break;
end;
Inc(I);
end;
finally
FreeMemory(deviceInterfaceDetailData);
end;
SetupDiDestroyDeviceInfoList(hardwareDeviceInfo);
end;
function TWinBluetoothGattService.GetServiceType: TBluetoothServiceType;
begin
Result := FType;
end;
function TWinBluetoothGattService.GetServiceUUID: TBluetoothUUID;
begin
Result := TBthLeUuidToUUID(FGattService.ServiceUuid);
end;
{ TWinBluetoothGattDescriptor }
constructor TWinBluetoothGattDescriptor.Create(const ACharacteristic: TWinBluetoothGattCharacteristic; const AGattDescriptor: TBthLeGattDescriptor);
begin
inherited Create(ACharacteristic);
FGattDescriptor := AGattDescriptor;
end;
destructor TWinBluetoothGattDescriptor.Destroy;
begin
if PValue <> nil then
FreeMemory(PValue);
inherited;
end;
function TWinBluetoothGattDescriptor.DoGetBroadcasts: Boolean;
begin
if PValue = nil then
Result := False
else
Result := PValue.DescriptorInfo.IsBroadcast;
end;
function TWinBluetoothGattDescriptor.DoGetExponent: ShortInt;
begin
if PValue = nil then
Result := 0
else
Result := PValue.DescriptorInfo.Exponent;
end;
function TWinBluetoothGattDescriptor.DoGetFormat: TBluetoothGattFormatType;
begin
if PValue = nil then
Result := TBluetoothGattFormatType.Reserved
else
Result := TBluetoothGattFormatType(PValue.DescriptorInfo.Format);
end;
function TWinBluetoothGattDescriptor.DoGetFormatUnit: TBluetoothUUID;
begin
if PValue = nil then
Result := TGUID.Empty
else
Result := TBthLeUuidToUUID(PValue.DescriptorInfo.&Unit);
end;
function TWinBluetoothGattDescriptor.DoGetIndication: Boolean;
begin
if PValue = nil then
Result := False
else
Result := PValue.DescriptorInfo.IsSubscribeToIndication;
end;
function TWinBluetoothGattDescriptor.DoGetNotification: Boolean;
begin
if PValue = nil then
Result := False
else
Result := PValue.DescriptorInfo.IsSubscribeToNotification;
end;
function TWinBluetoothGattDescriptor.DoGetReliableWrite: Boolean;
begin
if PValue = nil then
Result := False
else
Result := PValue.DescriptorInfo.IsReliableWriteEnabled;
end;
function TWinBluetoothGattDescriptor.DoGetUserDescription: string;
var
B: TBytes;
begin
if (PValue = nil) or (PValue.DataSize = 0) then
Result := ''
else
begin
SetLength(B, PValue.DataSize);
Move(PValue.Data, B[0], PValue.DataSize);
Result := TEncoding.UTF8.GetString(B);
end;
end;
function TWinBluetoothGattDescriptor.DoGetValue: TBytes;
begin
if (PValue = nil) or (PValue.DataSize = 0) then
SetLength(Result, 0)
else
begin
SetLength(Result, PValue.DataSize);
Move(PValue.Data, Result[0], PValue.DataSize);
end;
end;
function TWinBluetoothGattDescriptor.DoGetWritableAuxiliaries: Boolean;
begin
if PValue = nil then
Result := False
else
Result := PValue.DescriptorInfo.IsAuxiliariesWritable;
end;
procedure TWinBluetoothGattDescriptor.DoSetBroadcasts(const Value: Boolean);
begin
inherited;
CheckCreateValue;
PValue.DescriptorInfo.IsBroadcast := Value;
end;
procedure TWinBluetoothGattDescriptor.DoSetIndication(const Value: Boolean);
begin
inherited;
CheckCreateValue;
PValue.DescriptorInfo.IsSubscribeToIndication := Value;
end;
procedure TWinBluetoothGattDescriptor.DoSetNotification(const Value: Boolean);
begin
inherited;
CheckCreateValue;
PValue.DescriptorInfo.IsSubscribeToNotification := Value;
end;
procedure TWinBluetoothGattDescriptor.DoSetUserDescription(const Value: string);
begin
inherited;
CheckCreateValue;
DoSetValue(TEncoding.UTF8.GetBytes(Value));
end;
procedure TWinBluetoothGattDescriptor.DoSetValue(const AValue: TBytes);
begin
CheckCreateValue;
PValue := ReallocMemory(PValue, SizeOf(TBthLeGattDescriptorValue) + Length(AValue));
PValue.DataSize := Length(AValue);
if PValue.DataSize > 0 then
Move(AValue[0], PValue.Data, Length(AValue));
end;
function TWinBluetoothGattDescriptor.GetUUID: TBluetoothUUID;
begin
Result := TBthLeUuidToUUID(FGattDescriptor.DescriptorUuid);
end;
function TWinBluetoothGattDescriptor.SetValueToDevice: TBluetoothGattStatus;
var
res: HRESULT;
begin
Result := TBluetoothGattStatus.Success;
res := BluetoothGATTSetDescriptorValue(TWinBluetoothGattCharacteristic(FCharacteristic).ServiceHandle, FGattDescriptor, PValue, BLUETOOTH_GATT_FLAG_NONE);
if S_OK <> HResultCode(res) then
Result := ErrorToStatus(res);
end;
function TWinBluetoothGattDescriptor.UpdateValueFromDevice: TBluetoothGattStatus;
var
res: HRESULT;
BufferSize: Word;
Buffer: PBthLeGattDescriptorValue;
begin
Result := TBluetoothGattStatus.Success;
res := BluetoothGATTGetDescriptorValue(TWinBluetoothGattCharacteristic(FCharacteristic).ServiceHandle, FGattDescriptor, 0, nil, @BufferSize, BLUETOOTH_GATT_FLAG_NONE);
if HResultCode(res) <> ERROR_MORE_DATA then
Result := ErrorToStatus(res);
if BufferSize > 0 then
begin
Buffer := GetMemory(BufferSize);
try
res := BluetoothGATTGetDescriptorValue(TWinBluetoothGattCharacteristic(FCharacteristic).ServiceHandle, FGattDescriptor, BufferSize, Buffer, nil, BLUETOOTH_GATT_FLAG_FORCE_READ_FROM_DEVICE);
if S_OK <> HResultCode(res) then
Result := ErrorToStatus(res)
else
begin
if PValue <> nil then
FreeMemory(PValue);
PValue := Buffer;
end;
except
FreeMemory(Buffer);
raise;
end;
end;
end;
{$ENDIF BLUETOOTH_LE}
end.
|
unit GoogleSpeakU;
interface
uses
System.Classes, System.SysUtils, System.Threading, VCL.Forms, VCL.MPlayer, VCL.Controls, LanguagesU;
{$M+}
type
TGoogleSpeak = class(TComponent)
private
MediaPlayer0: TMediaPlayer;
MediaPlayer1: TMediaPlayer;
CurrentMediaPlayer: TMediaPlayer;
NextMediaPlayer: TMediaPlayer;
FUseCache: Boolean;
FDownloadFolder: string;
FBuffer: TStringlist;
FLanguage: TLanguage;
procedure SayFirst;
procedure SayNext;
published
property Language: TLanguage read FLanguage write FLanguage;
public
constructor Create(AOwner: TWinControl; AUseCache: Boolean = True; aLanguageCode: string = 'da'); reintroduce;
destructor Destroy; override;
function DownloadFile(aText: String; aLanguage: string): IFuture<string>; overload;
function DownloadFile(aText: String; aLanguage: TLanguage = nil): IFuture<string>; overload;
procedure Say(aText: String; aLanguage: TLanguage = nil); overload;
procedure Say(aText: String; aLanguageCode: string); overload;
end;
implementation
uses
System.Types, System.IOUtils,
IdURI, UrlMon, System.Hash, EventDispatcher;
{ TGoogleSpeak }
constructor TGoogleSpeak.Create(AOwner: TWinControl; AUseCache: Boolean; aLanguageCode: string);
function ConstructMediaPlayer: TMediaPlayer;
begin
Result := TMediaPlayer.Create(Self);
Result.OnNotify := TNotifyEventDispatcher.Construct(Result,
procedure(Sender: TObject)
begin
SayNext;
end);
Result.Parent := AOwner;
Result.Visible := False;
end;
begin
inherited Create(AOwner);
FUseCache := AUseCache;
FDownloadFolder := ExtractFilePath(ParamStr(0)) + 'Cache\';
ForceDirectories(FDownloadFolder);
MediaPlayer0 := ConstructMediaPlayer;
MediaPlayer1 := ConstructMediaPlayer;
FBuffer := TStringlist.Create;
FLanguage := TLanguages.FromCode(aLanguageCode);
end;
destructor TGoogleSpeak.Destroy;
begin
FBuffer.Free;
if not FUseCache then
TDirectory.Delete(FDownloadFolder);
inherited;
end;
function TGoogleSpeak.DownloadFile(aText: String; aLanguage: string): IFuture<string>;
var
Url: String;
begin
if aLanguage = '' then
aLanguage := FLanguage.Code;
Url := 'https://translate.googleapis.com/translate_tts?ie=UTF-8&q=' + TIdURI.PathEncode(aText) + '&tl=' + aLanguage + '&total=1&idx=0&textlen=' + aText.Length.ToString + '&client=gtx';
Result := TTask.Future<string>(
function: string
begin
Result := FDownloadFolder + THashMD5.GetHashString((aLanguage + ' ' + aText).ToUpper) + '.mp3';
if (FUseCache and TFile.Exists(Result)) then
exit;
URLDownloadToFile(nil, pchar(Url), pchar(Result), 0, nil);
end).Start;
end;
function TGoogleSpeak.DownloadFile(aText: String; aLanguage: TLanguage): IFuture<string>;
begin
if aLanguage = nil then
aLanguage := FLanguage;
Result := DownloadFile(aText, aLanguage.Code);
end;
procedure TGoogleSpeak.Say(aText: String; aLanguage: TLanguage = nil);
begin
if aLanguage = nil then
aLanguage := FLanguage;
FBuffer.AddObject(aText, aLanguage);
if (CurrentMediaPlayer = nil) or (not(CurrentMediaPlayer.Mode in [TMPModes.mpPlaying, TMPModes.mpSeeking, TMPModes.mpPaused])) then
SayNext;
end;
procedure TGoogleSpeak.Say(aText, aLanguageCode: string);
begin
Say(aText, TLanguages.FromCode(aLanguageCode));
end;
procedure TGoogleSpeak.SayFirst;
begin
if FBuffer.Count = 0 then
exit;
CurrentMediaPlayer := MediaPlayer0;
NextMediaPlayer := MediaPlayer1;
CurrentMediaPlayer.FileName := DownloadFile(FBuffer[0], TLanguage(FBuffer.Objects[0])).Value;
CurrentMediaPlayer.Open;
CurrentMediaPlayer.Play;
FBuffer.Delete(0);
if FBuffer.Count = 0 then
exit;
NextMediaPlayer.FileName := DownloadFile(FBuffer[0], TLanguage(FBuffer.Objects[0])).Value;
NextMediaPlayer.Open;
FBuffer.Delete(0);
end;
procedure TGoogleSpeak.SayNext;
begin
if CurrentMediaPlayer = nil then
begin
SayFirst;
exit;
end;
if NextMediaPlayer.FileName <> '' then
begin
CurrentMediaPlayer := NextMediaPlayer;
if CurrentMediaPlayer.FileName <> '' then
CurrentMediaPlayer.Play;
end;
if FBuffer.Count = 0 then
begin
CurrentMediaPlayer.FileName := '';
exit;
end;
if NextMediaPlayer.FileName = '' then
begin
CurrentMediaPlayer.FileName := DownloadFile(FBuffer[0], TLanguage(FBuffer.Objects[0])).Value;
CurrentMediaPlayer.Open;
CurrentMediaPlayer.Play;
FBuffer.Delete(0);
exit;
end;
if FBuffer.Count = 0 then
begin
CurrentMediaPlayer.FileName := '';
exit;
end;
if NextMediaPlayer = MediaPlayer0 then
NextMediaPlayer := MediaPlayer1
else
NextMediaPlayer := MediaPlayer0;
NextMediaPlayer.FileName := DownloadFile(FBuffer[0], TLanguage(FBuffer.Objects[0])).Value;
FBuffer.Delete(0);
NextMediaPlayer.Open;
end;
end.
|
unit UnMenuView;
interface
uses
// VCL
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, JvExControls, JvButton, JvTransparentButton, ExtCtrls, StdCtrls, Vcl.Buttons,
// JEDI
JvExExtCtrls, JvExtComponent, JvPanel,
// helsonsant
Util;
type
TMenuItemView = class(TJvPanel)
private
FLegenda: TLabel;
FDescricao: TLabel;
FAoClicar: TNotifyEvent;
protected
procedure Destacar(Sender: TObject);
procedure RemoverDestaque(Sender: TObject);
public
function AoClicar(const EventoParaExecutarAoClicar: TNotifyEvent): TMenuItemView;
function Descricao(const Descricao: string): TMenuItemView;
function Legenda(const Legenda: string): TMenuItemView;
function Montar: TMenuItemView;
end;
TMenuView = class(TForm)
pnlDesktop: TPanel;
pnlTitle: TPanel;
btnFechar: TSpeedButton;
pnlCaption: TPanel;
pnlFooter: TPanel;
lblMensagem: TLabel;
pnlOpcoes: TJvPanel;
procedure btnFecharClick(Sender: TObject);
private
FOpcoes: TStringList;
FResposta: string;
protected
function ShowModalDimmed(Form: TForm; Centered: Boolean = true): TModalResult;
public
property Resposta: string read FResposta;
function AdicionarOpcao(const Opcao, Legenda: string;
const Descricao: string = ''): TMenuView;
function Exibir: string;
function Legenda(const Legenda: string): TMenuView;
function Mensagem(const Mensagem: string): TMenuView;
published
procedure ProcessarSelecaoDeOpcao(Sender: TObject);
end;
implementation
{$R *.dfm}
{ TMenuView }
function TMenuView.AdicionarOpcao(const Opcao, Legenda: string;
const Descricao: string = ''): TMenuView;
var
_menuItem: TMenuItemView;
begin
if Self.FOpcoes = nil then
Self.FOpcoes := TStringList.Create;
_menuItem := TMenuItemView.Create(Self.pnlOpcoes)
.Legenda(Legenda)
.Descricao(Descricao)
.AoClicar(Self.ProcessarSelecaoDeOpcao)
.Montar;
_menuItem.Parent := Self.pnlOpcoes;
_menuItem.Align := altop;
Self.FOpcoes.AddObject(Opcao, _menuItem);
Result := Self;
end;
function TMenuView.Exibir: string;
begin
Self.ShowModalDimmed(Self);
Result := Self.FResposta;
end;
function TMenuView.Legenda(const Legenda: string): TMenuView;
begin
Self.pnlCaption.Caption := Legenda;
Result := Self;
end;
function TMenuView.Mensagem(const Mensagem: string): TMenuView;
begin
Self.lblMensagem.Caption := ' ' + Mensagem;
Result := Self;
end;
procedure TMenuView.ProcessarSelecaoDeOpcao(Sender: TObject);
var
_indice: Integer;
_opcao: TMenuItemView;
begin
if Sender is TLabel then
_opcao := (TLabel(Sender).Parent as TMenuItemView)
else
_opcao := (Sender as TMenuItemView);
_indice := Self.FOpcoes.IndexOfObject(_opcao);
if _indice <> -1 then
Self.FResposta := Self.FOpcoes[_indice]
else
Self.FResposta := '';
Self.ModalResult := mrOk;
end;
function TMenuView.ShowModalDimmed(Form: TForm; Centered: Boolean): TModalResult;
var
Back: TForm;
begin
Back := TForm.Create(nil);
try
Back.Position := poDesigned;
Back.BorderStyle := bsNone;
Back.AlphaBlend := true;
Back.AlphaBlendValue := 192;
Back.Color := clBlack;
Back.SetBounds(0, 0, Screen.Width, Screen.Height);
Back.Show;
if Centered then begin
Form.Left := (Back.ClientWidth - Form.Width) div 2;
Form.Top := (Back.ClientHeight - Form.Height) div 2;
end;
Result := Form.ShowModal;
finally
Back.Free;
end;
end;
{ TMenuItemView }
function TMenuItemView.AoClicar(
const EventoParaExecutarAoClicar: TNotifyEvent): TMenuItemView;
begin
Self.FAoClicar := EventoParaExecutarAoClicar;
Self.FLegenda.OnClick := EventoParaExecutarAoClicar;
Self.FDescricao.OnClick := EventoParaExecutarAoClicar;
Self.OnClick := EventoParaExecutarAoClicar;
Result := Self;
end;
function TMenuItemView.Descricao(const Descricao: string): TMenuItemView;
begin
if Self.FDescricao = nil then
begin
Self.FDescricao := TLabel.Create(Self);
Self.FDescricao.Align := alClient;
Self.FDescricao.Font.Name := 'Segoe UI';
Self.FDescricao.Font.Size := 12;
Self.FDescricao.Font.Color := clGray;
Self.FDescricao.Font.Style := [];
Self.FDescricao.Parent := Self;
end;
Self.FDescricao.Caption := Descricao;
Result := Self;
end;
function TMenuItemView.Legenda(const Legenda: string): TMenuItemView;
begin
if Self.FLegenda = nil then
begin
Self.FLegenda := TLabel.Create(Self);
Self.FLegenda.Align := alTop;
Self.FLegenda.Font.Name := 'Segoe UI';
Self.FLegenda.Font.Size := 14;
Self.FLegenda.Font.Color := clTeal;
Self.FLegenda.Font.Style := [fsBold];
Self.FLegenda.Parent := Self;
end;
Self.FLegenda.Caption := Legenda;
Result := Self;
end;
function TMenuItemView.Montar: TMenuItemView;
begin
Self.BevelOuter := bvNone;
Self.BorderStyle := bsSingle;
Self.BorderWidth := 5;
Self.Color := clWhite;
Self.Height := 80;
Self.OnMouseEnter := Destacar;
Self.OnMouseLeave := RemoverDestaque;
Result := Self;
end;
procedure TMenuView.btnFecharClick(Sender: TObject);
begin
Self.ModalResult := mrCancel;
end;
procedure TMenuItemView.Destacar(Sender: TObject);
begin
if TJvPanel(Sender).Color = clWhite then
TJvPanel(Sender).Color := $00F0FFBB;
end;
procedure TMenuItemView.RemoverDestaque(Sender: TObject);
begin
if not (TJvPanel(Sender).Color = clWhite) then
TJvPanel(Sender).Color := clWhite;
end;
end.
|
unit NtUtils.Sections;
interface
uses
Winapi.WinNt, Ntapi.ntmmapi, NtUtils.Exceptions, NtUtils.Objects,
DelphiUtils.AutoObject;
// Create a section
function NtxCreateSection(out hxSection: IHandle; hFile: THandle;
MaximumSize: UInt64; PageProtection: Cardinal; AllocationAttributes:
Cardinal = SEC_COMMIT; ObjectName: String = ''; RootDirectory: THandle = 0;
HandleAttributes: Cardinal = 0): TNtxStatus;
// Open a section
function NtxOpenSection(out hxSection: IHandle; DesiredAccess: TAccessMask;
ObjectName: String; RootDirectory: THandle = 0; HandleAttributes
: Cardinal = 0): TNtxStatus;
// Map a section
function NtxMapViewOfSection(hSection: THandle; hProcess: THandle; var Memory:
TMemory; Protection: Cardinal; SectionOffset: UInt64 = 0) : TNtxStatus;
// Unmap a section
function NtxUnmapViewOfSection(hProcess: THandle; Address: Pointer): TNtxStatus;
type
NtxSection = class
// Query fixed-size information
class function Query<T>(hSection: THandle;
InfoClass: TSectionInformationClass; out Buffer: T): TNtxStatus; static;
end;
// A local section with reference counting
TLocalAutoSection = class(TCustomAutoMemory, IMemory)
destructor Destroy; override;
end;
// Map a section locally
function NtxMapViewOfSectionLocal(hSection: THandle; out MappedMemory: IMemory;
Protection: Cardinal): TNtxStatus;
// Map an image as a file using a read-only section
function RtlxMapReadonlyFile(out hxSection: IHandle; FileName: String;
out MappedMemory: IMemory): TNtxStatus;
// Map a known dll as an image
function RtlxMapKnownDll(out hxSection: IHandle; DllName: String;
WoW64: Boolean; out MappedMemory: IMemory): TNtxStatus;
// Map a system dll (tries known dlls first, than falls back to reading a file)
function RtlxMapSystemDll(out hxSection: IHandle; DllName: String; WoW64:
Boolean; out MappedMemory: IMemory; out MappedAsImage: Boolean): TNtxStatus;
implementation
uses
Ntapi.ntdef, Ntapi.ntioapi, Ntapi.ntpsapi, NtUtils.Access.Expected,
NtUtils.Files, NtUtils.Environment;
function NtxCreateSection(out hxSection: IHandle; hFile: THandle;
MaximumSize: UInt64; PageProtection, AllocationAttributes: Cardinal;
ObjectName: String; RootDirectory: THandle; HandleAttributes: Cardinal)
: TNtxStatus;
var
hSection: THandle;
ObjAttr: TObjectAttributes;
NameStr: UNICODE_STRING;
pSize: PUInt64;
begin
if ObjectName <> '' then
begin
NameStr.FromString(ObjectName);
InitializeObjectAttributes(ObjAttr, @NameStr, HandleAttributes,
RootDirectory);
end
else
InitializeObjectAttributes(ObjAttr, nil, HandleAttributes);
if MaximumSize <> 0 then
pSize := @MaximumSize
else
pSize := nil;
// TODO: Expected file handle access
Result.Location := 'NtCreateSection';
Result.Status := NtCreateSection(hSection, SECTION_ALL_ACCESS, @ObjAttr,
pSize, PageProtection, AllocationAttributes, hFile);
if Result.IsSuccess then
hxSection := TAutoHandle.Capture(hSection);
end;
function NtxOpenSection(out hxSection: IHandle; DesiredAccess: TAccessMask;
ObjectName: String; RootDirectory: THandle; HandleAttributes: Cardinal):
TNtxStatus;
var
hSection: THandle;
ObjAttr: TObjectAttributes;
NameStr: UNICODE_STRING;
begin
NameStr.FromString(ObjectName);
InitializeObjectAttributes(ObjAttr, @NameStr, HandleAttributes,
RootDirectory);
Result.Location := 'NtOpenSection';
Result.LastCall.CallType := lcOpenCall;
Result.LastCall.AccessMask := DesiredAccess;
Result.LastCall.AccessMaskType := @SectionAccessType;
Result.Status := NtOpenSection(hSection, DesiredAccess, ObjAttr);
if Result.IsSuccess then
hxSection := TAutoHandle.Capture(hSection);
end;
function NtxMapViewOfSection(hSection: THandle; hProcess: THandle; var Memory:
TMemory; Protection: Cardinal; SectionOffset: UInt64) : TNtxStatus;
begin
Result.Location := 'NtMapViewOfSection';
RtlxComputeSectionMapAccess(Result.LastCall, Protection);
Result.LastCall.Expects(PROCESS_VM_OPERATION, @ProcessAccessType);
Result.Status := NtMapViewOfSection(hSection, hProcess, Memory.Address, 0, 0,
@SectionOffset, Memory.Size, ViewUnmap, 0, Protection);
end;
function NtxUnmapViewOfSection(hProcess: THandle; Address: Pointer): TNtxStatus;
begin
Result.Location := 'NtUnmapViewOfSection';
Result.LastCall.Expects(PROCESS_VM_OPERATION, @ProcessAccessType);
Result.Status := NtUnmapViewOfSection(hProcess, Address);
end;
class function NtxSection.Query<T>(hSection: THandle;
InfoClass: TSectionInformationClass; out Buffer: T): TNtxStatus;
begin
Result.Location := 'NtQuerySection';
Result.LastCall.CallType := lcQuerySetCall;
Result.LastCall.InfoClass := Cardinal(InfoClass);
Result.LastCall.InfoClassType := TypeInfo(TSectionInformationClass);
Result.LastCall.Expects(SECTION_QUERY, @SectionAccessType);
Result.Status := NtQuerySection(hSection, InfoClass, @Buffer, SizeOf(Buffer),
nil);
end;
destructor TLocalAutoSection.Destroy;
begin
if FAutoRelease then
NtxUnmapViewOfSection(NtCurrentProcess, FAddress);
inherited;
end;
function NtxMapViewOfSectionLocal(hSection: THandle; out MappedMemory: IMemory;
Protection: Cardinal): TNtxStatus;
var
Memory: TMemory;
begin
Memory.Address := nil;
Memory.Size := 0;
Result := NtxMapViewOfSection(hSection, NtCurrentProcess, Memory, Protection);
if Result.IsSuccess then
MappedMemory := TLocalAutoSection.Capture(Memory);
end;
function RtlxMapReadonlyFile(out hxSection: IHandle; FileName: String;
out MappedMemory: IMemory): TNtxStatus;
var
hxFile: IHandle;
begin
// Open the file
Result := NtxOpenFile(hxFile, FILE_READ_DATA, FileName);
if not Result.IsSuccess then
Exit;
// Create a section, baked by this file
Result := NtxCreateSection(hxSection, hxFile.Handle, 0, PAGE_READONLY);
if not Result.IsSuccess then
Exit;
// Map the section
Result := NtxMapViewOfSectionLocal(hxSection.Handle, MappedMemory,
PAGE_READONLY);
end;
function RtlxMapKnownDll(out hxSection: IHandle; DllName: String;
WoW64: Boolean; out MappedMemory: IMemory): TNtxStatus;
begin
if Wow64 then
DllName := '\KnownDlls32\' + DllName
else
DllName := '\KnownDlls\' + DllName;
// Open a known-dll section
Result := NtxOpenSection(hxSection, SECTION_MAP_READ or SECTION_QUERY,
DllName);
if not Result.IsSuccess then
Exit;
// Map it
Result := NtxMapViewOfSectionLocal(hxSection.Handle, MappedMemory,
PAGE_READONLY);
end;
function RtlxMapSystemDll(out hxSection: IHandle; DllName: String; WoW64:
Boolean; out MappedMemory: IMemory; out MappedAsImage: Boolean): TNtxStatus;
begin
// Try known dlls first
Result := RtlxMapKnownDll(hxSection, DllName, WoW64, MappedMemory);
if Result.IsSuccess then
MappedAsImage := True
else
begin
// There is no such known dll, read the file from the disk
MappedAsImage := False;
if WoW64 then
DllName := '%SystemRoot%\SysWoW64\' + DllName
else
DllName := '%SystemRoot%\System32\' + DllName;
// Expan system root
Result := RtlxExpandStringVar(DllName);
// Convert the path to NT format
if Result.IsSuccess then
Result := RtlxDosPathToNtPathVar(DllName);
// Map the file
if Result.IsSuccess then
Result := RtlxMapReadonlyFile(hxSection, DllName, MappedMemory);
end;
end;
end.
|
unit ComandaAplicacao;
interface
uses
StdCtrls, ExtCtrls, Classes, DBClient, Controls, SysUtils, DB,
{ Fluente }
Util, UnComandaModelo, SearchUtil, UnAplicacao, Pagamentos,
UnAbrirComandaView, UnComandaView, UnDividirView, UnLancarCreditoView,
UnLancarDebitoView, UnLancarDinheiroView, UnPagamentosView, UnComandaPrint;
type
{ Operações de Comanda }
OperacoesDeComanda = (ocmdAbrirComanda, ocmdCarregarComanda, ocmdFecharConta);
TComandaAplicacao = class(TAplicacao, IResposta)
private
FComandaModelo: TComandaModelo;
FConfiguracaoAplicacao: TConfiguracaoAplicacao;
FDivisao: string;
FOnChangeModel: TNotifyEvent;
protected
procedure AlterarCliente;
procedure Dividir;
procedure ExibirComanda;
procedure ExibirPagamentos;
function FecharConta: Boolean;
procedure Imprimir(const Observacoes: string = '');
procedure LancarDinheiro;
procedure LancarCredito;
procedure LancarDebito;
public
function AtivarAplicacao: TAplicacao; override;
procedure Responder(const Chamada: TChamada);
function Descarregar: TAplicacao; override;
function Preparar(const ConfiguracaoAplicacao: TConfiguracaoAplicacao = nil): TAplicacao; override;
published
property Divisao: string read FDivisao write FDivisao;
property OnChangeModel: TNotifyEvent read FOnChangeModel write FOnChangeModel;
end;
function RetornarOperacaoDeComanda(
const OperacaoDeComanda: Integer): OperacoesDeComanda;
implementation
{ TComandaController }
procedure TComandaAplicacao.Dividir;
var
_dividirView: TDividirView;
begin
if Self.FComandaModelo.DataSet.FieldByName('coma_saldo').AsFloat > 0 then
begin
_dividirView := TDividirView.Create(nil)
.Modelo(Self.FComandaModelo)
.Preparar;
try
_dividirView.ShowModal;
finally
_dividirView.Descarregar;
FreeAndNil(_dividirView);
end;
end
else
TMessages.MensagemErro('Não há saldo para dividir!');
end;
procedure TComandaAplicacao.LancarDinheiro;
var
_lancarDinheiroView: ITela;
begin
Self.FComandaModelo.Parametros.Gravar('total',
Self.FComandaModelo.DataSet.FieldByName('COMA_SALDO').AsFloat);
_lancarDinheiroView := TLancarDinheiroView.Create(nil)
.Modelo(Self.FComandaModelo)
.Preparar;
try
_lancarDinheiroView.ExibirTela;
finally
_lancarDinheiroView.Descarregar;
end;
end;
procedure TComandaAplicacao.LancarCredito;
var
_lancarCreditoView: TLancarCreditoView;
begin
Self.FComandaModelo.Parametros.Gravar('total',
Self.FComandaModelo.DataSet.FieldByName('COMA_SALDO').AsFloat);
_lancarCreditoView := TLancarCreditoView.Create(nil)
.Modelo(Self.FComandaModelo)
.Preparar;
try
_lancarCreditoView.ShowModal;
finally
_lancarCreditoView.Descarregar;
FreeAndNil(_lancarCreditoView);
end;
end;
procedure TComandaAplicacao.LancarDebito;
var
_lancarDebito: TLancarDebitoView;
begin
Self.FComandaModelo.Parametros.Gravar('total',
Self.FComandaModelo.DataSet.FieldByName('COMA_SALDO').AsFloat);
_lancarDebito := TLancarDebitoView.Create(nil)
.Modelo(Self.FComandaModelo)
.Preparar;
try
_lancarDebito.ShowModal;
finally
_lancarDebito.Descarregar;
FreeAndNil(_lancarDebito);
end;
end;
procedure TComandaAplicacao.ExibirPagamentos;
var
_dataSet: TDataSet;
_pagamentos: ITela;
_valorTotal: Real;
begin
_dataSet := Self.FComandaModelo.DataSet('comap');
if _dataSet.FieldByName('VALOR_TOTAL').AsString <> '' then
begin
_valorTotal := StrToFloat(_dataSet.FieldByName('VALOR_TOTAL').AsString);
Self.FComandaModelo.Parametros
.Gravar('total', _valorTotal)
.Gravar('datasource', 'mcx');
_pagamentos := TPagamentosView.Create(nil)
.Modelo(Self.FComandaModelo)
.Preparar;
try
_pagamentos.ExibirTela
finally
_pagamentos.Descarregar;
end;
end
else
TMessages.Mensagem('Nenhum pagamento efetuado!');
end;
function TComandaAplicacao.FecharConta: Boolean;
var
_valorTotal, _saldo: Real;
_dataSet: TDataSet;
begin
Result := False;
_dataSet := Self.FComandaModelo.DataSet;
if _dataSet.FieldByName('coma_total').AsString = '' then
_valorTotal := 0
else
_valorTotal := _dataSet.FieldByName('coma_total').AsCurrency;
_saldo := _dataSet.FieldByName('coma_saldo').AsFloat;
if _valorTotal > 0 then
begin
if (_saldo = 0) or
TMessages.Confirma('Fechar comanda com SALDO A PAGAR?') then
begin
Self.FComandaModelo.FecharComanda;
Result := True;
end
else
TMessages.MensagemErro('Não foi possível fechar Conta!');
end
else
TMessages.MensagemErro('Não é possível fechar conta sem consumo!');
end;
procedure TComandaAplicacao.AlterarCliente;
var
_dataSet: TDataSet;
begin
_dataSet := Self.FComandaModelo.DataSet;
if not (_dataSet.State in [dsEdit, dsInsert]) then
begin
if _dataSet.RecordCount > 0 then
begin
_dataSet.Edit;
end
else
begin
_dataSet.Append;
end;
end;
_dataSet.FieldByName('cl_oid').AsString := Self.FComandaModelo.Parametros.Ler('cl_oid').ComoTexto;
_dataSet.FieldByName('cl_cod').AsString := Self.FComandaModelo.Parametros.Ler('cl_cod').ComoTexto;
_dataSet.FieldByName('coma_cliente').AsString := _dataSet.FieldByName('cl_cod').AsString;
_dataSet.Post;
Self.FComandaModelo.SalvarComanda;
end;
function TComandaAplicacao.AtivarAplicacao: TAplicacao;
var
_eventoAntesDeAtivar, _eventoAposDesativar: TNotifyEvent;
_operacao: OperacoesDeComanda;
_abrirComandaView: TAbrirComandaView;
_chaveComanda: string;
begin
_operacao := RetornarOperacaoDeComanda(Self.FConfiguracaoAplicacao.ObterParametros.Ler('operacao').ComoInteiro);
_eventoAntesDeAtivar := Self.FConfiguracaoAplicacao.EventoParaExecutarAntesDeAtivar;
_eventoAposDesativar := Self.FConfiguracaoAplicacao.EventoParaExecutarAposDesativar;
if _operacao = ocmdAbrirComanda then
begin
_abrirComandaView := TAbrirComandaView
.Create(Self.FComandaModelo)
.Preparar;
try
if _abrirComandaView.ShowModal() = mrOk then
begin
_chaveComanda := Self.FComandaModelo.Parametros.Ler('mesa').ComoTexto;
if _chaveComanda <> '' then
Self.FComandaModelo
.LimparComanda
.AbrirComandaParaMesa(_chaveComanda)
else
begin
_chaveComanda := Self.FComandaModelo.Parametros.Ler('cl_cod').ComoTexto;
Self.FComandaModelo
.LimparComanda
.AbrirComandaParaCliente(_chaveComanda);
end;
if Assigned(_eventoAntesDeAtivar) then
_eventoAntesDeAtivar(Self.FComandaModelo);
Self.ExibirComanda();
if Assigned(_eventoAposDesativar) then
_eventoAposDesativar(Self.FComandaModelo);
end;
finally
FreeAndNil(_abrirComandaView);
end;
end
else
begin
Self.FComandaModelo.CarregarComanda(Self.FConfiguracaoAplicacao.ObterParametros.Ler('oid').ComoTexto);
if Assigned(_eventoAntesDeAtivar) then
_eventoAntesDeAtivar(Self.FComandaModelo);
if _operacao = ocmdCarregarComanda then
Self.ExibirComanda
else
Self.FecharConta;
if Assigned(_eventoAposDesativar) then
_eventoAposDesativar(Self.FComandaModelo);
end;
Result := Self;
end;
function TComandaAplicacao.Descarregar: TAplicacao;
begin
Result := Self;
end;
function TComandaAplicacao.Preparar(
const ConfiguracaoAplicacao: TConfiguracaoAplicacao = nil): TAplicacao;
begin
Self.FComandaModelo :=
(Self.FFabricaDeModelos.ObterModelo('ComandaModelo') as TComandaModelo);
Self.FConfiguracaoAplicacao := ConfiguracaoAplicacao;
Result := Self;
end;
procedure TComandaAplicacao.Responder(const Chamada: TChamada);
var
_eventoAntesDaChamada, _eventoAposChamar: TNotifyEvent;
_acao: AcoesDeComanda;
begin
_acao := RetornarAcaoDeComanda(Chamada.ObterParametros.Ler('acao').ComoInteiro);
_eventoAntesDaChamada := Chamada.EventoParaExecutarAntesDeChamar;
_eventoAposChamar := Chamada.EventoParaExecutarAposChamar;
if Assigned(_eventoAntesDaChamada) then
_eventoAntesDaChamada(Self);
case _acao of
acmdImprimir: Self.Imprimir(Chamada.ObterParametros.Ler('obs').ComoTexto);
acmdDividir: Self.Dividir;
acmdLancarPagamentoCartaoDeDebito: Self.LancarDebito;
acmdLancarPagamentoCartaoDeCredito: Self.LancarCredito;
acmdLancarPagamentoDinheiro: Self.LancarDinheiro;
acmdExibirPagamentos: Self.ExibirPagamentos;
acmdFecharConta: Self.FecharConta;
acmdAlterarCliente: Self.AlterarCliente;
end;
if Assigned(_eventoAposChamar) then
_eventoAposChamar(Self);
end;
procedure TComandaAplicacao.ExibirComanda;
var
_comandaView: ITela;
begin
try
_comandaView := TComandaView.Create(nil)
.Controlador(Self)
.Modelo(Self.FComandaModelo)
.Preparar;
_comandaView.ExibirTela;
finally
_comandaView.Descarregar;
end;
end;
function RetornarOperacaoDeComanda(const OperacaoDeComanda: Integer): OperacoesDeComanda;
begin
if OperacaoDeComanda = 0 then
Result := ocmdAbrirComanda
else
if OperacaoDeComanda = 1 then
Result := ocmdCarregarComanda
else
Result := ocmdFecharConta;
end;
procedure TComandaAplicacao.Imprimir(const Observacoes: string = '');
var
_colunas: Integer;
_impressora: TComandaPrint;
_linhaSimples, _linhaDupla: string;
_dataSet, _dsIngredientes: TClientDataSet;
begin
_dataSet := Self.FComandaModelo.DataSet;
_colunas := 40;
_linhaSimples := StringOfChar('-', _colunas);
_linhaDupla := StringOfChar('=', _colunas);
// Imprime cabecalho
_impressora := TComandaPrint.Create
.DispositivoParaImpressao(ddiTela)
.DefinirLarguraDaImpressaoEmCaracteres(_colunas)
.AlinharAEsquerda
.Preparar
.IniciarImpressao
.ImprimirLinha('BAR MERCEARIA E LANCH PIRATEI LTDA ME')
.ImprimirLinha(_linhaSimples)
.ImprimirLinha('AV.JOSE MARIA M OLIVEIRA, 583')
.ImprimirLinha('CNPJ: 52.274.420/0001-60')
.ImprimirLinha('Vila Norma - Salto - SP - CEP 13327-300')
.ImprimirLinha(_linhaDupla)
.ImprimirLinha('Fone: 4028-1010')
.ImprimirLinha(_linhaSimples)
.ImprimirLinha(FormatDateTime('dd/mm/yy hh:nn', NOW) + ' DOC: ' +
_dataSet.FieldByName('coma_comanda').AsString)
.ImprimirLinha(_linhaSimples)
.ImprimirLinha('')
.ImprimirLinha('Qtde. Descrição Unit. Vl.Tot')
.ImprimirLinha(_linhaSimples);
// Imprime itens
_dataSet := Self.FComandaModelo.DataSet('comai');
_dataSet.First;
while not _dataSet.Eof do
begin
_impressora
.ImprimirLinha(
Format('%4.0f', [_dataSet.FieldByName('comai_qtde').AsFloat]) + ' ' +
Copy(_dataSet.FieldByName('pro_des').AsString, 1, 25) + ' ' +
Format('%4.2f', [_dataSet.FieldByName('comai_unit').AsFloat]) + ' ' +
Format('%6.2f', [_dataSet.FieldByName('comai_qtde').AsFloat * _dataSet.FieldByName('comai_unit').AsFloat])
);
_dsIngredientes := Self.FComandaModelo.DataSet('comaie');
if _dsIngredientes.RecordCount > 0 then
begin
_dsIngredientes.First;
while not _dsIngredientes.Eof do
begin
_impressora.ImprimirLinha(' * * * SEM ' +
_dsIngredientes.FieldByName('comaie_des').AsString + ' * * *');
_dsIngredientes.Next;
end
end;
_dataSet.Next;
end;
_impressora.ImprimirLinha(_linhaSimples);
// Imprime rodape
_dataSet := Self.FComandaModelo.DataSet;
_impressora.ImprimirLinha('Total Bruto R$ ' + StringOfChar(' ', 16) +
Format('%9.2f', [_dataSet.FieldByName('coma_total').AsFloat])
);
if Observacoes <> '' then
begin
_impressora.ImprimirLinha(_linhaSimples);
_impressora.ImprimirLinha(Observacoes);
_impressora.ImprimirLinha(_linhaSimples);
end;
_impressora.ImprimirLinha(_linhaSimples);
_impressora.FinalizarImpressao;
end;
initialization
RegisterClass(TComandaAplicacao);
end.
|
unit mGridPanelFrame;
{
================================================================================
*
* Application: CPRS - CoverSheet
* Developer: doma.user@domain.ext
* Site: Salt Lake City ISC
* Date: 2015-12-04
*
* Description: Inherited from TFrame. This display panel is the bare
* minimum for a grid panel for use within the CPRS
* application.
*
* Notes: This frame is a base object and heavily inherited from.
* ABSOLUTELY NO CHANGES SHOULD BE MADE WITHOUT FIRST
* CONFERRING WITH THE CPRS DEVELOPMENT TEAM ABOUT POSSIBLE
* RAMIFICATIONS WITH DESCENDANT FRAMES.
*
================================================================================
}
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
System.UITypes,
System.ImageList,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.Menus,
Vcl.StdCtrls,
Vcl.ExtCtrls,
Vcl.Buttons,
Vcl.ImgList,
iCoverSheetIntf,
iGridPanelIntf;
type
TfraGridPanelFrame = class(TFrame, IGridPanelControl, IGridPanelFrame, ICPRS508)
pnlMain: TPanel;
pnlHeader: TPanel;
lblTitle: TLabel;
pnlWorkspace: TPanel;
pmn: TPopupMenu;
pmnExpandCollapse: TMenuItem;
pmnRefresh: TMenuItem;
pmnCustomize: TMenuItem;
pmnShowError: TMenuItem;
sbtnExpandCollapse: TSpeedButton;
sbtnRefresh: TSpeedButton;
pnlVertHeader: TPanel;
img: TImage;
private
fGridPanelDisplay: IGridPanelDisplay;
fCollapsed: boolean;
fAllowCollapse: TGridPanelCollapse;
fAllowRefresh: boolean;
fAllowCustomize: boolean;
fLoadError: boolean;
fLoadErrorMessage: string;
fScreenReaderActive: boolean;
{ Prevents auto free when RefCount = 0 }
function _AddRef: integer; stdcall;
function _Release: integer; stdcall;
protected
{ Getters and Setters }
function getAllowCollapse: TGridPanelCollapse; virtual;
function getAllowCustomize: boolean; virtual;
function getAllowRefresh: boolean; virtual;
function getBackgroundColor: TColor; virtual; final;
function getCollapsed: boolean; virtual;
function getGridPanelDisplay: IGridPanelDisplay; virtual; final;
function getTitleFontColor: TColor; virtual; final;
function getTitleFontBold: boolean; virtual; final;
function getTitle: string; virtual;
function getLoadError: boolean;
function getLoadErrorMessage: string;
procedure setAllowCollapse(const aValue: TGridPanelCollapse); virtual;
procedure setAllowCustomize(const aValue: boolean); virtual;
procedure setAllowRefresh(const aValue: boolean); virtual;
procedure setBackgroundColor(const aValue: TColor); virtual; final;
procedure setGridPanelDisplay(const aValue: IGridPanelDisplay); virtual; final;
procedure setTitleFontColor(const aValue: TColor); virtual; final;
procedure setTitleFontBold(const aValue: boolean); virtual; final;
procedure setTitle(const aValue: string); virtual;
{ ICPRS508 implementation events }
procedure OnFocusFirstControl(Sender: TObject); virtual;
procedure OnSetFontSize(Sender: TObject; aNewSize: integer); virtual;
procedure OnSetScreenReaderStatus(Sender: TObject; aActive: boolean); virtual;
{ Component events }
procedure OnExpandCollapse(Sender: TObject); virtual;
procedure OnCustomizeDisplay(Sender: TObject); virtual;
procedure OnLoadError(Sender: TObject; E: Exception); virtual;
procedure OnPopupMenu(Sender: TObject); virtual;
procedure OnPopupMenuInit(Sender: TObject); virtual;
procedure OnPopupMenuFree(Sender: TObject); virtual;
procedure OnRefreshDisplay(Sender: TObject); virtual;
procedure OnRefreshVerticalTitle(Sender: TObject); virtual;
procedure OnShowError(Sender: TObject); virtual;
{ Component methods }
procedure ClearLoadError;
public
{ Public declarations }
constructor Create(aOwner: TComponent); override;
destructor Destroy; override;
end;
implementation
{$R *.dfm}
uses
VAUtils;
{ TfraGridPanelFrame }
const
IMG_COLLAPSE = 'MGRIDPANELFRAME_COLLAPSE';
IMG_EXPAND = 'MGRIDPANELFRAME_EXPAND';
IMG_REFRESH = 'MGRIDPANELFRAME_REFRESH';
IMG_DELETE = 'MGRIDPANELFRAME_DELETE';
constructor TfraGridPanelFrame.Create(aOwner: TComponent);
begin
inherited Create(aOwner);
name := 'fra' + NewGUID;
fCollapsed := False;
fAllowCollapse := gpcNone;
fAllowRefresh := False;
fAllowCustomize := False;
sbtnExpandCollapse.OnClick := OnExpandCollapse;
sbtnExpandCollapse.Visible := fAllowCollapse in [gpcRow, gpcColumn];
sbtnExpandCollapse.Glyph.LoadFromResourceName(HInstance, IMG_COLLAPSE);
sbtnRefresh.OnClick := OnRefreshDisplay;
sbtnRefresh.Visible := fAllowRefresh;
sbtnRefresh.Glyph.LoadFromResourceName(HInstance, IMG_REFRESH);
{ Default settings according to the current Windows Pallet - SHOULD NOT BE CHANGED HERE, EVER!!!! }
pnlMain.Color := clActiveCaption;
lblTitle.Font.Color := clCaptionText;
lblTitle.Font.Style := [fsBold];
{ Call this so that descendant panels can customize the menu if needed }
OnPopupMenuInit(Self);
end;
destructor TfraGridPanelFrame.Destroy;
begin
OnPopupMenuFree(Self);
inherited;
end;
function TfraGridPanelFrame._AddRef: integer;
begin
Result := -1;
end;
function TfraGridPanelFrame._Release: integer;
begin
Result := -1;
end;
procedure TfraGridPanelFrame.ClearLoadError;
begin
pmnShowError.Visible := False;
fLoadError := False;
fLoadErrorMessage := '';
end;
procedure TfraGridPanelFrame.OnLoadError(Sender: TObject; E: Exception);
begin
pmnShowError.Visible := True;
fLoadError := True;
fLoadErrorMessage := Format('LoadError: [%s] - %s', [Sender.ClassName, E.Message]);
end;
procedure TfraGridPanelFrame.OnCustomizeDisplay(Sender: TObject);
begin
{ Virtual method for the descendants to implement if needed }
end;
procedure TfraGridPanelFrame.OnExpandCollapse(Sender: TObject);
var
aRow: integer;
aCol: integer;
begin
try
fCollapsed := not fCollapsed;
{ Find out where we are on the grid }
fGridPanelDisplay.FindControl(Self, aCol, aRow);
case fAllowCollapse of
gpcRow:
if fCollapsed then
begin
pnlWorkspace.Hide;
sbtnRefresh.Hide;
sbtnExpandCollapse.Glyph.LoadFromResourceName(HInstance, IMG_EXPAND);
pnlVertHeader.TabStop := true;
fGridPanelDisplay.CollapseRow(aRow);
pnlVertHeader.SetFocus;
end
else
begin
fGridPanelDisplay.ExpandRow(aRow);
pnlVertHeader.TabStop := false;
sbtnExpandCollapse.Glyph.LoadFromResourceName(HInstance, IMG_COLLAPSE);
if fAllowRefresh then
sbtnRefresh.Show;
pnlWorkspace.Show;
pnlWorkspace.SetFocus;
end;
gpcColumn:
if fCollapsed then
begin
pnlWorkspace.Hide;
sbtnRefresh.Hide;
pnlVertHeader.Visible := True;
OnRefreshVerticalTitle(Sender);
sbtnExpandCollapse.Glyph.LoadFromResourceName(HInstance, IMG_EXPAND);
pnlVertHeader.TabStop := True;
fGridPanelDisplay.CollapseColumn(aCol);
pnlVertHeader.SetFocus;
end
else
begin
fGridPanelDisplay.ExpandColumn(aCol);
pnlVertHeader.TabStop := false;
sbtnExpandCollapse.Glyph.LoadFromResourceName(HInstance, IMG_COLLAPSE);
if fAllowRefresh then
sbtnRefresh.Show;
pnlWorkspace.Show;
pnlWorkspace.SetFocus;
pnlVertHeader.Visible := false;
end;
end;
except
ShowMessage('Error in ExpandCollapseClick method.');
end;
end;
procedure TfraGridPanelFrame.OnPopupMenu(Sender: TObject);
begin
if fCollapsed then
pmnExpandCollapse.Caption := 'Expand'
else
pmnExpandCollapse.Caption := 'Collapse';
pmnExpandCollapse.Visible := fAllowCollapse in [gpcRow, gpcColumn];
pmnRefresh.Visible := fAllowRefresh;
pmnCustomize.Visible := fAllowCustomize;
pmnShowError.Visible := fLoadError;
end;
procedure TfraGridPanelFrame.OnPopupMenuFree(Sender: TObject);
begin
// Nothing needed here, the menu items are all owned properly by the frame.
end;
procedure TfraGridPanelFrame.OnPopupMenuInit(Sender: TObject);
begin
pmnExpandCollapse.OnClick := OnExpandCollapse;
pmnExpandCollapse.Visible := fAllowCollapse in [gpcRow, gpcColumn];
pmnRefresh.OnClick := OnRefreshDisplay;
pmnRefresh.Visible := fAllowRefresh;
pmnCustomize.OnClick := OnCustomizeDisplay;
pmnCustomize.Visible := fAllowCustomize;
pmnShowError.OnClick := OnShowError;
pmnShowError.Visible := False;
pmn.OnPopup := OnPopupMenu;
end;
procedure TfraGridPanelFrame.OnRefreshDisplay(Sender: TObject);
begin
{ Virtual method for the descendants to implement if needed }
end;
procedure TfraGridPanelFrame.OnRefreshVerticalTitle(Sender: TObject);
var
aStr: string;
X: integer;
Y: integer;
H: integer;
i: integer;
begin
if fCollapsed then
begin
img.Picture := nil;
img.Canvas.Brush.Color := pnlMain.Color;
img.Canvas.FillRect(Rect(0, 0, img.Width, img.Height));
img.Canvas.Font.Color := lblTitle.Font.Color;
img.Canvas.Font.Style := lblTitle.Font.Style;
Y := 0;
H := img.Canvas.TextHeight('|');
for i := 1 to Length(lblTitle.Caption) do
begin
aStr := Copy(lblTitle.Caption, i, 1);
X := (img.Width - img.Canvas.TextWidth(aStr)) div 2;
img.Canvas.TextOut(X, Y, aStr);
inc(Y, H);
if Y > (img.Height - H) then
Break;
end;
img.Repaint;
end;
end;
procedure TfraGridPanelFrame.OnFocusFirstControl(Sender: TObject);
begin
if pnlWorkspace.Visible and pnlWorkspace.Enabled then
pnlWorkspace.SetFocus;
end;
procedure TfraGridPanelFrame.OnSetFontSize(Sender: TObject; aNewSize: integer);
var
aComponent: TComponent;
aCPRS508: ICPRS508;
begin
Self.Font.Size := aNewSize;
lblTitle.Font.Size := aNewSize; { Bolded so ParentFont = False :( }
pnlHeader.Height := lblTitle.Canvas.TextHeight(lblTitle.Caption) + lblTitle.Margins.Top + lblTitle.Margins.Bottom; { So the big ole title displays properly }
{ Now walk any other items that may be ICPRS_508 implementors }
for aComponent in Self do
if Supports(aComponent, ICPRS508, aCPRS508) then
aCPRS508.OnSetFontSize(Self, aNewSize);
end;
procedure TfraGridPanelFrame.OnSetScreenReaderStatus(Sender: TObject; aActive: boolean);
begin
pnlWorkspace.TabStop := aActive; { Lets the ScreenReader stop here and read the caption }
fScreenReaderActive := aActive;
end;
procedure TfraGridPanelFrame.OnShowError(Sender: TObject);
begin
if fLoadError then
ShowMessage(fLoadErrorMessage)
else
ShowMessage('No load error message.');
end;
function TfraGridPanelFrame.getLoadError: boolean;
begin
Result := fLoadError;
end;
function TfraGridPanelFrame.getLoadErrorMessage: string;
begin
Result := fLoadErrorMessage;
end;
function TfraGridPanelFrame.getAllowCollapse: TGridPanelCollapse;
begin
Result := fAllowCollapse;
end;
function TfraGridPanelFrame.getAllowCustomize: boolean;
begin
Result := fAllowCustomize;
end;
function TfraGridPanelFrame.getAllowRefresh: boolean;
begin
Result := fAllowRefresh;
end;
function TfraGridPanelFrame.getBackgroundColor: TColor;
begin
Result := pnlMain.Color;
end;
function TfraGridPanelFrame.getCollapsed: boolean;
begin
Result := fCollapsed;
end;
function TfraGridPanelFrame.getGridPanelDisplay: IGridPanelDisplay;
begin
{
When a control is added through the AddControl Method of the ICPRSGridPanel
if it supports ICPRSGridPanelFrame fCPRSGridPanel will br set to the
ICPRSGridPanel that it is added to.
}
if fGridPanelDisplay <> nil then
fGridPanelDisplay.QueryInterface(IGridPanelDisplay, Result)
else
Result := nil;
end;
function TfraGridPanelFrame.getTitle: string;
begin
Result := lblTitle.Caption;
end;
function TfraGridPanelFrame.getTitleFontBold: boolean;
begin
Result := (fsBold in lblTitle.Font.Style);
end;
function TfraGridPanelFrame.getTitleFontColor: TColor;
begin
Result := lblTitle.Font.Color;
end;
procedure TfraGridPanelFrame.setAllowCollapse(const aValue: TGridPanelCollapse);
begin
fAllowCollapse := aValue;
case fAllowCollapse of
gpcNone:
begin
sbtnExpandCollapse.Visible := False;
sbtnExpandCollapse.Glyph := nil;
end;
gpcRow:
begin
if fCollapsed then
sbtnExpandCollapse.Glyph.LoadFromResourceName(HInstance, IMG_EXPAND)
else
sbtnExpandCollapse.Glyph.LoadFromResourceName(HInstance, IMG_COLLAPSE);
sbtnExpandCollapse.Visible := True;
end;
gpcColumn:
begin
if fCollapsed then
sbtnExpandCollapse.Glyph.LoadFromResourceName(HInstance, IMG_EXPAND)
else
sbtnExpandCollapse.Glyph.LoadFromResourceName(HInstance, IMG_COLLAPSE);
sbtnExpandCollapse.Visible := True;
end;
end;
end;
procedure TfraGridPanelFrame.setAllowCustomize(const aValue: boolean);
begin
fAllowCustomize := aValue;
end;
procedure TfraGridPanelFrame.setAllowRefresh(const aValue: boolean);
begin
fAllowRefresh := aValue;
sbtnRefresh.Visible := fAllowRefresh;
end;
procedure TfraGridPanelFrame.setBackgroundColor(const aValue: TColor);
begin
pnlMain.Color := aValue;
end;
procedure TfraGridPanelFrame.setGridPanelDisplay(const aValue: IGridPanelDisplay);
begin
if aValue <> nil then
aValue.QueryInterface(IGridPanelDisplay, fGridPanelDisplay)
else
fGridPanelDisplay := nil;
end;
procedure TfraGridPanelFrame.setTitle(const aValue: string);
begin
lblTitle.Caption := aValue;
{
Set pnlWorkspace.Caption as the lblTitle.Caption so when
ScreenReader taps in it will have something to say.
}
pnlWorkspace.Caption := aValue;
pnlVertHeader.Caption := aValue + ' minimized';
end;
procedure TfraGridPanelFrame.setTitleFontBold(const aValue: boolean);
begin
if aValue and not(fsBold in lblTitle.Font.Style) then
lblTitle.Font.Style := lblTitle.Font.Style + [fsBold]
else
lblTitle.Font.Style := lblTitle.Font.Style - [fsBold];
end;
procedure TfraGridPanelFrame.setTitleFontColor(const aValue: TColor);
begin
lblTitle.Font.Color := aValue;
end;
end.
|
//Copyright 2009-2010 by Victor Derevyanko, dvpublic0@gmail.com
//http://code.google.com/p/dvsrc/
//http://derevyanko.blogspot.com/2009/02/hardware-id-diskid32-delphi.html
//{$Id$}
unit crtdll_wrapper;
// This file is a part of DiskID for Delphi
// Original code of DiskID can be taken here:
// http://www.winsim.com/diskid32/diskid32.html
// The code was ported from C++ to Delphi by Victor Derevyanko, dvpublic0@gmail.com
// If you find any error please send me bugreport by email. Thanks in advance.
// The translation was donated by efaktum (http://www.efaktum.dk).
interface
function isspace(ch: AnsiChar): Boolean;
function isalpha(ch: AnsiChar): Boolean;
function tolower(ch: AnsiChar): AnsiChar;
function isprint(ch: AnsiChar): Boolean;
function isalnum(ch: AnsiChar): Boolean;
implementation
//Use crtdll.dll for compartibility with Win95
//Use msvcrt.dll if you need compilation for x64 or compartibility with Win95 is not required.
function crt_isspace(ch: Integer): Integer; cdecl; external 'msvcrt.dll' name 'isspace';
function crt_isalpha(ch: Integer): Integer; cdecl; external 'msvcrt.dll' name 'isalpha';
function crt_tolower(ch: Integer): Integer; cdecl; external 'msvcrt.dll' name 'tolower';
function crt_isprint(ch: Integer): Integer; cdecl; external 'msvcrt.dll' name 'isprint';
function crt_isalnum(ch: Integer): Integer; cdecl; external 'msvcrt.dll' name 'isalnum';
function isspace(ch: AnsiChar): Boolean;
begin
Result := crt_isspace(Ord(ch)) <> 0;
end;
function isalpha(ch: AnsiChar): Boolean;
begin
Result := crt_isalpha(Ord(ch)) <> 0;
end;
function tolower(ch: AnsiChar): AnsiChar;
begin
Result := AnsiChar(Chr(crt_tolower(Ord(ch))));
end;
function isprint(ch: AnsiChar): Boolean;
begin
Result := crt_isprint(Ord(ch)) <> 0;
end;
function isalnum(ch: AnsiChar): Boolean;
begin
Result := crt_isalnum(Ord(ch)) <> 0;
end;
end.
|
unit uValidation;
interface
uses
System.Rtti, System.TypInfo,
System.SysUtils, System.Classes;
type
ValidationAttribute = class(TCustomAttribute)
private
function GetCustomMessage: string; virtual;
public
function Validate(AValue: TValue): Boolean; virtual;
property CustomMessage: string read GetCustomMessage;
end;
ValidTypesAttribute = class(ValidationAttribute)
private
FTypeKinds: TTypeKinds;
FCustomMessage: string;
function GetCustomMessage: string; override;
public
constructor Create(const ATypeKinds: TTypeKinds); overload;
function Validate(AValue: TValue): Boolean; override;
end;
[ValidTypesAttribute([tkInteger, tkChar, tkEnumeration, tkFloat, tkString,
tkSet, tkClass, tkWChar, tkLString, tkWString, tkVariant, tkArray, tkInt64,
tkDynArray, tkUString])]
MandatoryAttribute = class(ValidationAttribute)
private
function GetCustomMessage: string; override;
public
function Validate(AValue: TValue): Boolean; override;
end;
IPAddressAttribute = class(ValidationAttribute)
private
function GetCustomMessage: string; override;
public
function Validate(AValue: TValue): Boolean; override;
end;
RangeAttribute = class(ValidationAttribute)
private
FMin: Integer;
FMax: Integer;
function GetCustomMessage: string; override;
public
constructor Create(const AMin: Integer; const AMax: Integer);
function Validate(AValue: TValue): Boolean; override;
end;
TAttributeTransformDirection = (tdForward, tdBackward);
TransformAttribute = class(TCustomAttribute)
public
function RunTransform(const AValue: TValue; out OutValue: TValue;
ADirection: TAttributeTransformDirection): Boolean; overload;
end;
EncryptedAttribute = class(TransformAttribute)
public
function RunTransform(const AValue: TValue; out OutValue: TValue;
ADirection: TAttributeTransformDirection; const AKey: string): Boolean; overload;
end;
{ classe para validação }
TValidateObject = class
public
class function TryValidate(AClass: TObject;
AValidationResult: TStrings = nil): Boolean;
class function TryTransform(AClass: TObject;
ADirection: TAttributeTransformDirection): Boolean; overload;
class function TryTransform(AClass: TObject;
ADirection: TAttributeTransformDirection; const AKey: string): Boolean; overload;
end;
implementation
uses
DATA.DBXEncryption,
IdCoderMIME,
System.RegularExpressions;
{ ValidationAttribute }
function ValidationAttribute.GetCustomMessage: string;
begin
Result := EmptyStr;
end;
function ValidationAttribute.Validate(AValue: TValue): Boolean;
begin
Result := False;
end;
{ MandatoryAttribute }
function MandatoryAttribute.GetCustomMessage: string;
begin
Result := 'Este membro está vazio';
end;
function MandatoryAttribute.Validate(AValue: TValue): Boolean;
begin
// Result := False;
// case AValue.Kind of
// tkUnknown:
// ;
// tkInteger:
// Result := (AValue.AsInteger <> 0);
// tkEnumeration:
// ;
// tkFloat:
// ;
// tkString, tkWChar, tkLString, tkWString, tkUString, tkChar:
// Result := (AValue.AsString <> EmptyStr);
// tkSet:
// ;
// tkClass:
// ;
// tkMethod:
// ;
// tkVariant:
// ;
// tkArray:
// ;
// tkRecord:
// ;
// tkInterface:
// ;
// tkInt64:
// ;
// tkDynArray:
// ;
// tkClassRef:
// ;
// tkPointer:
// ;
// tkProcedure:
// ;
// end;
Result := (AValue.AsString <> EmptyStr);
end;
{ TValidateObject }
class function TValidateObject.TryTransform(AClass: TObject;
ADirection: TAttributeTransformDirection): Boolean;
var
LContext: TRttiContext;
LType: TRttiType;
LAttr: TCustomAttribute;
LProp: TRttiProperty;
LOutValue: TValue;
begin
Result := True;
{ recupera o tipo da classe do objeto enviado }
LType := LContext.GetType(AClass.ClassInfo);
{ percorre aas propriedades }
for LProp in LType.GetProperties do
if LProp.ClassNameIs('TRttiInstancePropertyEx') then
begin
{ recupera os atributos das propriedades }
for LAttr in LProp.GetAttributes do
begin
{ se for um atributo de transformação }
if LAttr is TransformAttribute then
begin
{ executa a validação }
if TransformAttribute(LAttr).RunTransform(LProp.GetValue(AClass),
LOutValue, ADirection) then
begin
LProp.SetValue(AClass, LOutValue);
end
else
begin
{ não passou na validação }
Result := False;
end;
end;
end;
end;
end;
class function TValidateObject.TryTransform(AClass: TObject;
ADirection: TAttributeTransformDirection; const AKey: string): Boolean;
var
LContext: TRttiContext;
LType: TRttiType;
LAttr: TCustomAttribute;
LProp: TRttiProperty;
LOutValue: TValue;
begin
Result := True;
{ recupera o tipo da classe do objeto enviado }
LType := LContext.GetType(AClass.ClassInfo);
{ percorre aas propriedades }
for LProp in LType.GetProperties do
if LProp.ClassNameIs('TRttiInstancePropertyEx') then
begin
{ recupera os atributos das propriedades }
for LAttr in LProp.GetAttributes do
begin
{ se for um atributo de transformação }
if LAttr is TransformAttribute then
begin
{ executa a validação }
if EncryptedAttribute(LAttr).RunTransform(LProp.GetValue(AClass),
LOutValue, ADirection, AKey) then
begin
LProp.SetValue(AClass, LOutValue);
end
else
begin
{ não passou na validação }
Result := False;
end;
end;
end;
end;
end;
class function TValidateObject.TryValidate(AClass: TObject;
AValidationResult: TStrings): Boolean;
var
LContext: TRttiContext;
LType, LTypeAttribute: TRttiType;
LAttr, LInnerAttribute: TCustomAttribute;
LProp: TRttiProperty;
LMessage: string;
LInnerValPassed: Boolean;
begin
Result := True;
{ recupera o tipo da classe do objeto enviado }
LType := LContext.GetType(AClass.ClassInfo);
{ percorre aas propriedades }
for LProp in LType.GetProperties do
if LProp.ClassNameIs('TRttiInstancePropertyEx') then
begin
{ recupera os atributos das propriedades }
for LAttr in LProp.GetAttributes do
begin
LInnerValPassed := True;
LTypeAttribute := LContext.GetType(LAttr.ClassInfo);
for LInnerAttribute in LTypeAttribute.GetAttributes do
begin
if LInnerAttribute is ValidationAttribute then
begin
if not ValidationAttribute(LInnerAttribute)
.Validate(LProp.GetValue(AClass)) then
begin
Result := False;
LMessage :=
Format('A validação %S falhou no atributo %S da propriedade %S.%S (Hint: %S)',
[LInnerAttribute.ClassName, LAttr.ClassName, AClass.ClassName,
LProp.Name, ValidationAttribute(LInnerAttribute).CustomMessage])
+ sLineBreak;
if AValidationResult <> nil then
begin
AValidationResult.Add(LMessage);
end;
end;
end;
end;
if LInnerValPassed then
begin
{ se for um atributo de validação }
if LAttr is ValidationAttribute then
begin
{ executa a validação }
if not ValidationAttribute(LAttr).Validate(LProp.GetValue(AClass))
then
begin
{ não passou na validação }
Result := False;
{ recupera a mensagem }
LMessage :=
Format('A validação %S falhou na propriedade %S.%S (Hint: %S)',
[LAttr.ClassName, AClass.ClassName, LProp.Name,
ValidationAttribute(LAttr).CustomMessage]);
{ vetifica se existe algum objeto para retorno da mensagem }
if AValidationResult <> nil then
begin
AValidationResult.Add(LMessage);
end;
end;
end;
end;
end;
end;
end;
{ IPAddressAttribute }
function IPAddressAttribute.GetCustomMessage: string;
begin
Result := 'Este endereço IP não é válido.';
end;
function IPAddressAttribute.Validate(AValue: TValue): Boolean;
begin
{ máscara de IP V4 }
Result := TRegEx.IsMatch(AValue.AsString,
'\b' + '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.' +
'(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.' +
'(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.' +
'(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b');
end;
{ RangeAttribute }
constructor RangeAttribute.Create(const AMin, AMax: Integer);
begin
inherited Create;
FMin := AMin;
FMax := AMax;
end;
function RangeAttribute.GetCustomMessage: string;
begin
Result := Format('Os valores devem estar entre [%d - %d]', [FMin, FMax]);
end;
function RangeAttribute.Validate(AValue: TValue): Boolean;
begin
Result := ((AValue.AsInteger >= FMin) and (AValue.AsInteger <= FMax));
end;
{ ValidTypesAttribute }
constructor ValidTypesAttribute.Create(const ATypeKinds: TTypeKinds);
begin
FTypeKinds := ATypeKinds;
FCustomMessage := 'Você deve passar um tipo válido para esta propriedade.';
end;
function ValidTypesAttribute.GetCustomMessage: string;
var
LKind: TTypeKind;
begin
Result := EmptyStr;
if FTypeKinds <> [] then
begin
for LKind in FTypeKinds do
begin
if Result <> '' then
begin
Result := Result + ', ';
end;
Result := Result + TRttiEnumerationType.GetName<TTypeKind>(LKind);
end;
Result := FCustomMessage + '[' + Result + ']';
end
else
begin
Result := FCustomMessage;
end;
end;
function ValidTypesAttribute.Validate(AValue: TValue): Boolean;
begin
Result := (AValue.Kind in FTypeKinds);
end;
{ TransformAttribute }
function TransformAttribute.RunTransform(const AValue: TValue;
out OutValue: TValue; ADirection: TAttributeTransformDirection): Boolean;
begin
Result := True;
OutValue := AValue;
end;
{ EncryptedAttribute }
function EncryptedAttribute.RunTransform(const AValue: TValue;
out OutValue: TValue; ADirection: TAttributeTransformDirection;
const AKey: string): Boolean;
var
LCypher: TPC1Cypher;
LCont: Integer;
LData: TArray<Byte>;
LStream: TMemoryStream;
begin
{ encryption }
if (ADirection = tdForward) then
begin
{ recupera e trata a string }
LData := TEncoding.UTF8.GetBytes(AValue.AsString);
{ cria o objeto para encriptar }
LCypher := TPC1Cypher.Create(AKey);
try
{ percorre o dado }
for LCont := 0 to Length(LData) - 1 do
begin
{ encripta }
LData[LCont] := LCypher.Cypher(LData[LCont]);
end;
finally
LCypher.Free;
end;
{ codifica a string encritada }
LStream := TMemoryStream.Create;
try
LStream.WriteData(LData, Length(LData));
LStream.Position := 0;
OutValue := TValue.From<string>(TIdEncoderMIME.EncodeStream(LStream));
finally
LStream.Free;
end;
end
{ decryption }
else
begin
{ recupera o valor }
LStream := TMemoryStream.Create;
try
TIdDecoderMIME.DecodeStream(AValue.AsString, LStream);
SetLength(LData, LStream.Size);
LStream.Position := 0;
LStream.ReadBuffer(LData[0], Length(LData));
finally
LStream.Free;
end;
{ desencripta }
LCypher := TPC1Cypher.Create(AKey);
try
for LCont := 0 to Length(LData) - 1 do
begin
LData[LCont] := LCypher.Decypher(LData[LCont]);
end;
finally
LCypher.Free;
end;
OutValue := TEncoding.UTF8.GetString(LData);
end;
Result := True;
end;
end.
|
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$HPPEMIT LINKUNIT}
unit Data.DBXInterbaseReadOnlyMetaData;
interface
uses
Data.DBXMetaDataReader,
Data.DBXMetaDataCommandFactory;
type
TDBXInterbaseMetaDataCommandFactory = class(TDBXMetaDataCommandFactory)
public
function CreateMetaDataReader: TDBXMetaDataReader; override;
end;
implementation
uses
Data.DBXInterbaseMetaDataReader;
function TDBXInterbaseMetaDataCommandFactory.CreateMetaDataReader: TDBXMetaDataReader;
begin
Result := TDBXInterbaseMetaDataReader.Create;
end;
initialization
TDBXMetaDataCommandFactory.RegisterMetaDataCommandFactory(TDBXInterbaseMetaDataCommandFactory);
finalization
TDBXMetaDataCommandFactory.UnRegisterMetaDataCommandFactory(TDBXInterbaseMetaDataCommandFactory);
end.
|
unit ORClasses;
interface
uses
SysUtils, System.Types, Classes, Controls, ComCtrls, ExtCtrls, StdCtrls, Forms, ORFn;
type
TNotifyProc = procedure(Sender: TObject);
TORNotifyList = class(TObject)
private
FCode: TList;
FData: TList;
protected
function GetItems(index: integer): TNotifyEvent;
procedure SetItems(index: integer; const Value: TNotifyEvent);
function GetIsProc(index: integer): boolean;
function GetProcs(index: integer): TNotifyProc;
procedure SetProcs(index: integer; const Value: TNotifyProc);
public
constructor Create;
destructor Destroy; override;
function IndexOf(const NotifyProc: TNotifyEvent): integer; overload;
function IndexOf(const NotifyProc: TNotifyProc): integer; overload;
procedure Add(const NotifyProc: TNotifyEvent); overload;
procedure Add(const NotifyProc: TNotifyProc); overload;
procedure Clear;
function Count: integer;
procedure Delete(index: integer);
procedure Remove(const NotifyProc: TNotifyEvent); overload;
procedure Remove(const NotifyProc: TNotifyProc); overload;
procedure Notify(Sender: TObject);
property Items[index: integer]: TNotifyEvent read GetItems write SetItems; default;
property Procs[index: integer]: TNotifyProc read GetProcs write SetProcs;
property IsProc[index: integer]: boolean read GetIsProc;
end;
TCanNotifyEvent = procedure(Sender: TObject; var CanNotify: boolean) of object;
IORNotifier = interface(IUnknown)
function GetOnNotify: TCanNotifyEvent;
procedure SetOnNotify(Value: TCanNotifyEvent);
procedure BeginUpdate;
procedure EndUpdate(DoNotify: boolean = FALSE);
procedure NotifyWhenChanged(Event: TNotifyEvent); overload;
procedure NotifyWhenChanged(Event: TNotifyProc); overload;
procedure RemoveNotify(Event: TNotifyEvent); overload;
procedure RemoveNotify(Event: TNotifyProc); overload;
procedure Notify; overload;
procedure Notify(Sender: TObject); overload;
function NotifyMethod: TNotifyEvent;
property OnNotify: TCanNotifyEvent read GetOnNotify Write SetOnNotify;
end;
TORNotifier = class(TInterfacedObject, IORNotifier)
private
FNotifyList: TORNotifyList;
FUpdateCount: integer;
FOwner: TObject;
FOnNotify: TCanNotifyEvent;
protected
procedure DoNotify(Sender: TObject);
public
constructor Create(Owner: TObject = nil; SingleInstance: boolean = FALSE);
destructor Destroy; override;
function GetOnNotify: TCanNotifyEvent;
procedure SetOnNotify(Value: TCanNotifyEvent);
procedure BeginUpdate;
procedure EndUpdate(DoNotify: boolean = FALSE);
procedure NotifyWhenChanged(Event: TNotifyEvent); overload;
procedure NotifyWhenChanged(Event: TNotifyProc); overload;
procedure RemoveNotify(Event: TNotifyEvent); overload;
procedure RemoveNotify(Event: TNotifyProc); overload;
procedure Notify; overload;
procedure Notify(Sender: TObject); overload;
function NotifyMethod: TNotifyEvent;
property OnNotify: TCanNotifyEvent read GetOnNotify Write SetOnNotify;
end;
TORStringList = class(TStringList, IORNotifier)
private
FNotifier: IORNotifier;
protected
function GetNotifier: IORNotifier;
procedure Changed; override;
public
destructor Destroy; override;
procedure KillObjects;
// IndexOfPiece starts looking at StartIdx+1
function CaseInsensitiveIndexOfPiece(Value: string; Delim: Char = '^';
PieceNum: integer = 1;
StartIdx: integer = -1): integer;
function IndexOfPiece(Value: string; Delim: Char = '^';
PieceNum: integer = 1;
StartIdx: integer = -1): integer;
function IndexOfPieces(const Values: array of string; const Delim: Char;
const Pieces: array of integer;
StartIdx: integer = -1): integer; overload;
function IndexOfPieces(const Values: array of string): integer; overload;
function IndexOfPieces(const Values: array of string; StartIdx: integer): integer; overload;
function PiecesEqual(const Index: integer;
const Values: array of string): boolean; overload;
function PiecesEqual(const Index: integer;
const Values: array of string;
const Pieces: array of integer): boolean; overload;
function PiecesEqual(const Index: integer;
const Values: array of string;
const Pieces: array of integer;
const Delim: Char): boolean; overload;
procedure SetStrPiece(Index, PieceNum: integer; Delim: Char; const NewValue: string); overload;
procedure SetStrPiece(Index, PieceNum: integer; const NewValue: string); overload;
procedure SortByPiece(PieceNum: integer; Delim: Char = '^');
procedure SortByPieces(Pieces: array of integer; Delim: Char = '^');
procedure RemoveDuplicates(CaseSensitive: boolean = TRUE);
property Notifier: IORNotifier read GetNotifier implements IORNotifier;
end;
{ Do NOT add ANTHING to the ORExposed Classes except to change the scope
of a property. If you do, existing code could generate Access Violations }
TORExposedCustomEdit = class(TCustomEdit)
public
property ReadOnly;
end;
TORExposedAnimate = class(TAnimate)
public
property OnMouseUp;
property OnMouseDown;
end;
TORExposedControl = class(TControl)
public
property Font;
property Text;
end;
{ AddToNotifyWhenCreated allows you to add an event handler before the object that
calls that event handler is created. This only works when there is only one
instance of a given object created (like TPatient or TEncounter). For an object
to make use of this feature, it must call ObjectCreated in the constructor,
which will return the TORNotifyList that was created for that object. }
procedure AddToNotifyWhenCreated(ProcToAdd: TNotifyEvent; CreatedClass: TClass); overload;
procedure AddToNotifyWhenCreated(ProcToAdd: TNotifyProc; CreatedClass: TClass); overload;
procedure ObjectCreated(CreatedClass: TClass; var NotifyList: TORNotifyList);
type
TORInterfaceList = class(TList)
private
function GetItem(Index: Integer): IUnknown;
procedure SetItem(Index: Integer; const Value: IUnknown);
protected
procedure Notify(Ptr: Pointer; Action: TListNotification); override;
public
function Add(Item: IUnknown): Integer;
function Extract(Item: IUnknown): IUnknown;
function First: IUnknown;
function IndexOf(Item: IUnknown): Integer;
procedure Insert(Index: Integer; Item: IUnknown);
function Last: IUnknown;
function Remove(Item: IUnknown): Integer;
property Items[Index: Integer]: IUnknown read GetItem write SetItem; default;
end;
implementation
var
NotifyLists: TStringList = nil;
function IndexOfClass(CreatedClass: TClass): integer;
begin
if(not assigned(NotifyLists)) then
NotifyLists := TStringList.Create;
Result := NotifyLists.IndexOf(CreatedClass.ClassName);
if(Result < 0) then
Result := NotifyLists.AddObject(CreatedClass.ClassName, TORNotifyList.Create);
end;
procedure AddToNotifyWhenCreated(ProcToAdd: TNotifyEvent; CreatedClass: TClass); overload;
var
idx: integer;
begin
idx := IndexOfClass(CreatedClass);
TORNotifyList(NotifyLists.Objects[idx]).Add(ProcToAdd);
end;
procedure AddToNotifyWhenCreated(ProcToAdd: TNotifyProc; CreatedClass: TClass); overload;
var
idx: integer;
begin
idx := IndexOfClass(CreatedClass);
TORNotifyList(NotifyLists.Objects[idx]).Add(ProcToAdd);
end;
procedure ObjectCreated(CreatedClass: TClass; var NotifyList: TORNotifyList);
var
idx: integer;
begin
if(assigned(NotifyLists)) then
begin
idx := IndexOfClass(CreatedClass);
if(idx < 0) then
NotifyList := nil
else
begin
NotifyList := (NotifyLists.Objects[idx] as TORNotifyList);
NotifyLists.Delete(idx);
if(NotifyLists.Count <= 0) then
KillObj(@NotifyLists);
end;
end;
end;
{ TORNotifyList }
constructor TORNotifyList.Create;
begin
inherited;
FCode := TList.Create;
FData := TList.Create;
end;
destructor TORNotifyList.Destroy;
begin
KillObj(@FCode);
KillObj(@FData);
inherited
end;
function TORNotifyList.IndexOf(const NotifyProc: TNotifyEvent): integer;
var
m: TMethod;
begin
if(assigned(NotifyProc) and (FCode.Count > 0)) then
begin
m := TMethod(NotifyProc);
Result := 0;
while((Result < FCode.Count) and ((FCode[Result] <> m.Code) or
(FData[Result] <> m.Data))) do inc(Result);
if Result >= FCode.Count then Result := -1;
end
else
Result := -1;
end;
procedure TORNotifyList.Add(const NotifyProc: TNotifyEvent);
var
m: TMethod;
begin
if(assigned(NotifyProc) and (IndexOf(NotifyProc) < 0)) then
begin
m := TMethod(NotifyProc);
FCode.Add(m.Code);
FData.Add(m.Data);
end;
end;
procedure TORNotifyList.Remove(const NotifyProc: TNotifyEvent);
var
idx: integer;
begin
idx := IndexOf(NotifyProc);
if(idx >= 0) then
begin
FCode.Delete(idx);
FData.Delete(idx);
end;
end;
function TORNotifyList.GetItems(index: integer): TNotifyEvent;
begin
TMethod(Result).Code := FCode[index];
TMethod(Result).Data := FData[index];
end;
procedure TORNotifyList.SetItems(index: integer; const Value: TNotifyEvent);
begin
FCode[index] := TMethod(Value).Code;
FData[index] := TMethod(Value).Data;
end;
procedure TORNotifyList.Notify(Sender: TObject);
var
i: integer;
evnt: TNotifyEvent;
proc: TNotifyProc;
begin
for i := 0 to FCode.Count-1 do
begin
if(FData[i] = nil) then
begin
proc := FCode[i];
if(assigned(proc)) then proc(Sender);
end
else
begin
TMethod(evnt).Code := FCode[i];
TMethod(evnt).Data := FData[i];
if(assigned(evnt)) then evnt(Sender);
end;
end;
end;
procedure TORNotifyList.Clear;
begin
FCode.Clear;
FData.Clear;
end;
function TORNotifyList.Count: integer;
begin
Result := FCode.Count;
end;
procedure TORNotifyList.Delete(index: integer);
begin
FCode.Delete(index);
FData.Delete(index);
end;
procedure TORNotifyList.Add(const NotifyProc: TNotifyProc);
begin
if(assigned(NotifyProc) and (IndexOf(NotifyProc) < 0)) then
begin
FCode.Add(@NotifyProc);
FData.Add(nil);
end;
end;
function TORNotifyList.IndexOf(const NotifyProc: TNotifyProc): integer;
var
prt: ^TNotifyProc;
begin
prt := @NotifyProc;
if(assigned(NotifyProc) and (FCode.Count > 0)) then
begin
Result := 0;
while((Result < FCode.Count) and ((FCode[Result] <> prt) or
(FData[Result] <> nil))) do inc(Result);
if Result >= FCode.Count then Result := -1;
end
else
Result := -1;
end;
procedure TORNotifyList.Remove(const NotifyProc: TNotifyProc);
var
idx: integer;
begin
idx := IndexOf(NotifyProc);
if(idx >= 0) then
begin
FCode.Delete(idx);
FData.Delete(idx);
end;
end;
function TORNotifyList.GetIsProc(index: integer): boolean;
begin
Result := (not assigned(FData[index]));
end;
function TORNotifyList.GetProcs(index: integer): TNotifyProc;
begin
Result := FCode[index];
end;
procedure TORNotifyList.SetProcs(index: integer; const Value: TNotifyProc);
begin
FCode[index] := @Value;
FData[index] := nil;
end;
{ TORNotifier }
constructor TORNotifier.Create(Owner: TObject = nil; SingleInstance: boolean = FALSE);
begin
FOwner := Owner;
if(assigned(Owner) and SingleInstance) then
ObjectCreated(Owner.ClassType, FNotifyList);
end;
destructor TORNotifier.Destroy;
begin
KillObj(@FNotifyList);
inherited;
end;
procedure TORNotifier.BeginUpdate;
begin
inc(FUpdateCount);
end;
procedure TORNotifier.EndUpdate(DoNotify: boolean = FALSE);
begin
if(FUpdateCount > 0) then
begin
dec(FUpdateCount);
if(DoNotify and (FUpdateCount = 0)) then Notify(FOwner);
end;
end;
procedure TORNotifier.Notify(Sender: TObject);
begin
if((FUpdateCount = 0) and assigned(FNotifyList) and (FNotifyList.Count > 0)) then
DoNotify(Sender);
end;
procedure TORNotifier.Notify;
begin
if((FUpdateCount = 0) and assigned(FNotifyList) and (FNotifyList.Count > 0)) then
DoNotify(FOwner);
end;
procedure TORNotifier.NotifyWhenChanged(Event: TNotifyEvent);
begin
if(not assigned(FNotifyList)) then
FNotifyList := TORNotifyList.Create;
FNotifyList.Add(Event);
end;
procedure TORNotifier.NotifyWhenChanged(Event: TNotifyProc);
begin
if(not assigned(FNotifyList)) then
FNotifyList := TORNotifyList.Create;
FNotifyList.Add(Event);
end;
procedure TORNotifier.RemoveNotify(Event: TNotifyEvent);
begin
if(assigned(FNotifyList)) then
FNotifyList.Remove(Event);
end;
procedure TORNotifier.RemoveNotify(Event: TNotifyProc);
begin
if(assigned(FNotifyList)) then
FNotifyList.Remove(Event);
end;
function TORNotifier.NotifyMethod: TNotifyEvent;
begin
Result := Notify;
end;
function TORNotifier.GetOnNotify: TCanNotifyEvent;
begin
Result := FOnNotify;
end;
procedure TORNotifier.SetOnNotify(Value: TCanNotifyEvent);
begin
FOnNotify := Value;
end;
procedure TORNotifier.DoNotify(Sender: TObject);
var
CanNotify: boolean;
begin
CanNotify := TRUE;
if(assigned(FOnNotify)) then
FOnNotify(Sender, CanNotify);
if(CanNotify) then
FNotifyList.Notify(Sender);
end;
{ TORStringList }
destructor TORStringList.Destroy;
begin
FNotifier := nil; // Frees instance
inherited;
end;
procedure TORStringList.Changed;
var
OldEvnt: TNotifyEvent;
begin
{ We redirect the OnChange event handler, rather than calling
FNotifyList.Notify directly, because inherited may not call
OnChange, and we don't have access to the private variables
inherited uses to determine if OnChange should be called }
if(assigned(FNotifier)) then
begin
OldEvnt := OnChange;
try
OnChange := FNotifier.NotifyMethod;
inherited; // Conditionally Calls FNotifier.Notify
finally
OnChange := OldEvnt;
end;
end;
inherited; // Conditionally Calls the old OnChange event handler
end;
function TORStringList.IndexOfPiece(Value: string; Delim: Char;
PieceNum: integer;
StartIdx: integer): integer;
begin
Result := StartIdx;
inc(Result);
while((Result >= 0) and (Result < Count) and
(Piece(Strings[Result], Delim, PieceNum) <> Value)) do
inc(Result);
if(Result < 0) or (Result >= Count) then Result := -1;
end;
function TORStringList.IndexOfPieces(const Values: array of string; const Delim: Char;
const Pieces: array of integer;
StartIdx: integer = -1): integer;
var
Done: boolean;
begin
Result := StartIdx;
repeat
inc(Result);
if(Result >= 0) and (Result < Count) then
Done := PiecesEqual(Result, Values, Pieces, Delim)
else
Done := TRUE;
until(Done);
if(Result < 0) or (Result >= Count) then Result := -1;
end;
function TORStringList.IndexOfPieces(const Values: array of string): integer;
begin
Result := IndexOfPieces(Values, U, [], -1);
end;
function TORStringList.IndexOfPieces(const Values: array of string;
StartIdx: integer): integer;
begin
Result := IndexOfPieces(Values, U, [], StartIdx);
end;
function TORStringList.GetNotifier: IORNotifier;
begin
if(not assigned(FNotifier)) then
FNotifier := TORNotifier.Create(Self);
Result := FNotifier;
end;
procedure TORStringList.KillObjects;
var
i: integer;
begin
for i := 0 to Count-1 do
begin
if(assigned(Objects[i])) then
begin
Objects[i].Free;
Objects[i] := nil;
end;
end;
end;
function TORStringList.PiecesEqual(const Index: integer;
const Values: array of string): boolean;
begin
Result := PiecesEqual(Index, Values, [], U);
end;
function TORStringList.PiecesEqual(const Index: integer;
const Values: array of string;
const Pieces: array of integer): boolean;
begin
Result := PiecesEqual(Index, Values, Pieces, U);
end;
function TORStringList.PiecesEqual(const Index: integer;
const Values: array of string;
const Pieces: array of integer;
const Delim: Char): boolean;
var
i, cnt, p: integer;
begin
cnt := 0;
Result := TRUE;
for i := low(Values) to high(Values) do
begin
inc(cnt);
if(i >= low(Pieces)) and (i <= high(Pieces)) then
p := Pieces[i]
else
p := cnt;
if(Piece(Strings[Index], Delim, p) <> Values[i]) then
begin
Result := FALSE;
break;
end;
end;
end;
procedure TORStringList.SortByPiece(PieceNum: integer; Delim: Char = '^');
begin
SortByPieces([PieceNum], Delim);
end;
procedure TORStringList.RemoveDuplicates(CaseSensitive: boolean = TRUE);
var
i: integer;
Kill: boolean;
begin
i := 1;
while (i < Count) do
begin
if(CaseSensitive) then
Kill := (Strings[i] = Strings[i-1])
else
Kill := (CompareText(Strings[i],Strings[i-1]) = 0);
if(Kill) then
Delete(i)
else
inc(i);
end;
end;
function TORStringList.CaseInsensitiveIndexOfPiece(Value: string; Delim: Char = '^';
PieceNum: integer = 1; StartIdx: integer = -1): integer;
begin
Result := StartIdx;
inc(Result);
while((Result >= 0) and (Result < Count) and
(CompareText(Piece(Strings[Result], Delim, PieceNum), Value) <> 0)) do
inc(Result);
if(Result < 0) or (Result >= Count) then Result := -1;
end;
procedure TORStringList.SortByPieces(Pieces: array of integer;
Delim: Char = '^');
procedure QSort(L, R: Integer);
var
I, J: Integer;
P: string;
begin
repeat
I := L;
J := R;
P := Strings[(L + R) shr 1];
repeat
while ComparePieces(Strings[I], P, Pieces, Delim, TRUE) < 0 do Inc(I);
while ComparePieces(Strings[J], P, Pieces, Delim, TRUE) > 0 do Dec(J);
if I <= J then
begin
Exchange(I, J);
Inc(I);
Dec(J);
end;
until I > J;
if L < J then QSort(L, J);
L := I;
until I >= R;
end;
begin
if not Sorted and (Count > 1) then
begin
Changing;
QSort(0, Count - 1);
Changed;
end;
end;
procedure TORStringList.SetStrPiece(Index, PieceNum: integer; Delim: Char;
const NewValue: string);
var
tmp: string;
begin
tmp := Strings[Index];
ORFn.SetPiece(tmp,Delim,PieceNum,NewValue);
Strings[Index] := tmp;
end;
procedure TORStringList.SetStrPiece(Index, PieceNum: integer;
const NewValue: string);
begin
SetStrPiece(Index, PieceNum, '^', NewValue);
end;
{ TORInterfaceList }
function TORInterfaceList.Add(Item: IUnknown): Integer;
begin
Result := inherited Add(Pointer(Item));
end;
function TORInterfaceList.Extract(Item: IUnknown): IUnknown;
begin
Result := IUnknown(inherited Extract(Pointer(Item)));
end;
function TORInterfaceList.First: IUnknown;
begin
Result := IUnknown(inherited First);
end;
function TORInterfaceList.GetItem(Index: Integer): IUnknown;
begin
Result := IUnknown(inherited Get(Index));
end;
function TORInterfaceList.IndexOf(Item: IUnknown): Integer;
begin
Result := inherited IndexOf(Pointer(Item));
end;
procedure TORInterfaceList.Insert(Index: Integer; Item: IUnknown);
begin
inherited Insert(Index, Pointer(Item));
end;
function TORInterfaceList.Last: IUnknown;
begin
Result := IUnknown(inherited Last);
end;
procedure TORInterfaceList.Notify(Ptr: Pointer; Action: TListNotification);
begin
case Action of
lnAdded: IUnknown(Ptr)._AddRef;
lnDeleted, lnExtracted: IUnknown(Ptr)._Release;
end;
end;
function TORInterfaceList.Remove(Item: IUnknown): Integer;
begin
Result := inherited Remove(Pointer(Item));
end;
procedure TORInterfaceList.SetItem(Index: Integer; const Value: IUnknown);
begin
inherited Put(Index, Pointer(Value));
end;
initialization
finalization
KillObj(@NotifyLists, TRUE);
end. |
unit FMain;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
System.IOUtils,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.StdCtrls,
Google.API;
type
TFormMain = class(TForm)
GroupBoxRequest: TGroupBox;
LabelOAuthScope: TLabel;
LabelUrl: TLabel;
LabelRequest: TLabel;
ButtonPost: TButton;
EditOAuthScope: TEdit;
EditUrl: TEdit;
MemoRequestContent: TMemo;
GroupBoxResponse: TGroupBox;
MemoResponseHeaders: TMemo;
MemoResponseContent: TMemo;
LabelResponseContent: TLabel;
LabelResponseHeaders: TLabel;
EditServiceAccount: TEdit;
LabelServiceAccount: TLabel;
ButtonBrowse: TButton;
LabelPEM: TLabel;
EditPEM: TEdit;
OpenDialog1: TOpenDialog;
procedure ButtonPostClick(Sender: TObject);
procedure ButtonBrowseClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FormMain: TFormMain;
implementation
{$R *.dfm}
procedure TFormMain.ButtonBrowseClick(Sender: TObject);
begin
if OpenDialog1.Execute then
EditPEM.Text := OpenDialog1.FileName;
end;
procedure TFormMain.ButtonPostClick(Sender: TObject);
var
Google: TgoGoogle;
ResponseHeaders, ResponseContent: String;
begin
Google := TgoGoogle.Create;
try
Google.OAuthScope := EditOAuthScope.Text;
Google.ServiceAccount := EditServiceAccount.Text;
Google.PrivateKey := TFile.ReadAllText(EditPEM.Text);
if Google.Post(EditUrl.Text, MemoRequestContent.Text,
ResponseHeaders, ResponseContent, 30000) = 200 then
begin
MemoResponseHeaders.Text := ResponseHeaders;
MemoResponseContent.Text := ResponseContent;
end;
finally
Google.Free;
end;
end;
end.
|
unit fpeMakerNoteNikon;
{$IFDEF FPC}
{$MODE DELPHI}
//{$mode objfpc}{$H+}
{$ENDIF}
interface
uses
Classes, SysUtils,
fpeGlobal, fpeTags, fpeExifReadWrite;
type
TNikonMakerNoteReader = class(TMakerNoteReader)
protected
function AddTag(AStream: TStream; const AIFDRecord: TIFDRecord;
const AData: TBytes; AParent: TTagID): Integer; override;
procedure GetTagDefs(AStream: TStream); override;
function Prepare(AStream: TStream): Boolean; override;
end;
TNikonCropHiSpeedTag = class(TIntegerTag)
public
function GetAsString: String; override;
end;
TNikonLensTypeTag = class(TIntegerTag)
public
function GetAsString: string; override;
end;
TNikonLensTag = class(TFloatTag)
public
function GetAsString: string; override;
end;
TNikonShootingModeTag = class(TIntegerTag)
public
function GetAsString: String; override;
end;
TNikonNEFBitDepthTag = class(TIntegerTag)
public
function GetAsString: String; override;
end;
implementation
uses
Math,
fpeStrConsts, fpeUtils, fpeExifData;
resourcestring
rsNikonActiveDLightingLkUp = '0:Off,1:Low,3:Normal,5:High,7:Extra High,'+
'8:Extra High 1,9:Extra High 2,10:Extra High 3,11:Extra High 4,65535:Auto';
rsNikonAFAreaMode = '0:Single Area,1:Dynamic Area,2:Dynamic Area (closest subject),'+
'3:Group Dynamic,4:Single Area (wide),5:Dynamic Area (wide)';
rsNikonAFPoint = '0:Center,1:Top,2:Bottom,3:Mid-left,4:Mid-right,5:Upper-left,'+
'6:Upper-right,7:Lower-left,8:Lower-right,9:Far Left,10:Far Right';
rsNikonAFPointsInFocus = '0:(none),$7FF:All 11 points,1:Center,2:Top,4:Bottom,'+
'8:Mid-left,16:Mid-right,32:Upper-left,64:Upper-right,128:Lower-left,'+
'256:Lower-right,512:Far left,1024:Far right';
// To do: This is a bit-mask. Combinations should be calculated!
rsNikonColorModeLkup = '1:Color,2:Monochrome';
rsNikonColorSpaceLkup = '1:sRGB,2:Adobe RGB';
rsNikonConverterLkup = '0:Not used,1:Used';
rsNikonCropHiSpeedLkup = '0:Off,1:1.3x Crop,2:DX Crop,3:5/4 Crop,4:3/2 Crop,'+
'6:16/9 Crop,9:DX Movie Crop,11:FX Uncropped,12:DX Uncropped,17:1/1 Crop';
rsNikonCropHiSpeedMask = '%0:s (%1:dx%2:d cropped to %3:dx%4:d at pixel %5:d,%6:d)';
rsNikonDateDisplayFormat = '0:Y/M/D,1:M/D/Y,2:D/M/Y';
rsNikonFlashModeLkUp = '0:Did Not Fire,1:Fired, Manual,3:Not Ready,'+
'7:Fired External,8:Fired Commander Mode,9:Fired TTL Mode';
rsNikonHighISONoiseReductionLkUp = '0:Off,1:Minimal,2:Low,3:Medium Low,'+
'4:Normal,5:Medium High,6:High';
rsNikonImgAdjLkup = '0:Normal,1:Bright+,2:Bright-,3:Contrast+,4:Contrast-';
rsNikonISOLkup = '0:ISO80,2:ISO160,4:ISO320,5:ISO100';
rsNikonNEFCompressionLkUp = '1:Lossy (type 1),2: Uncompressed,3:Lossless,'+
'4:Lossy (type 2),5:Striped packed 12 bits,6:Uncompressed (reduced to 12 bit),'+
'7:Unpacked 12 bits,8:Small,9:Packed 12 bits';
rsNikonOffOn='-1:Off,1:On';
rsNikonQualityLkup = '1:Vga Basic,2:Vga Normal,3:Vga Fine,4:SXGA Basic,'+
'5:SXGA Normal,6:SXGA Fine,10:2 Mpixel Basic,11:2 Mpixel Normal,'+
'12:2 Mpixel Fine';
rsNikonRetoucheHistoryLkup = '0:None,3:B & W,4:Sepia,5:Trim,6:Small Picture,'+
'7:D-Lighting,8:Red Eye,9:Cyanotype,10:Sky Light,11:Warm Tone,'+
'12:Color Custom,13:Image Overlay,14:Red Intensifier,15:Green Intensifier,'+
'16:Blue Intensifier,17:Cross Screen,18:Quick Retouch,19:NEF Processing,'+
'23:Distortion Control,25:Fisheye,26:Straighten,29:Perspective Control,'+
'30:Color Outline,31:Soft Filter,32:Resize,33: Miniature Effect,'+
'34:Skin Softening,35:Selected Frame,37:Color Sketch,38:Selective Color,'+
'39:Glamour,40:Drawing,44:Pop,45:Toy Camera Effect 1,46:Toy Camera Effect 2,'+
'47:Cross Process (red),48:Cross Process (blue),49:Cross Process (green),'+
'50:Cross Process (yellow),51:Super Vivid,52:High-contrast Monochrome,'+
'53:High Key,54:Low Key';
rsNikonShutterModeLkUp = '0:Mechanical,16:Electronic,48:Electronic Front Curtain';
rsNikonVignetteControlLkUp = '0:Off,1:Low,3:Normal,5:High';
rsNikonVibrationReductionLkUp = '0:n/a,1:On,2:Off';
rsNikonVRModeLkUp = '0:Normal,1:On (1),2:Active,3:Sport';
rsNikonWhiteBalanceLkup = '0:Auto,1:Preset,2:Daylight,3:Incandescense,'+
'4:Fluorescence,5:Cloudy,6:SpeedLight';
const
M = DWord(TAGPARENT_MAKERNOTE);
// not tested
procedure BuildNikon1TagDefs(AList: TTagDefList);
begin
Assert(AList <> nil);
with AList do begin
AddUShortTag(M+$0002, 'FamilyID');
AddUShortTag(M+$0003, 'Quality', 1, '', rsNikonQualityLkup);
AddUShortTag(M+$0004, 'ColorMode', 1, '', rsNikonColorModeLkup);
AddUShortTag(M+$0005, 'ImageAdjustment', 1, '', rsNikonImgAdjLkup);
AddUShortTag(M+$0006, 'ISOSpeed', 1, '', rsNikonISOLkup);
AddUShortTag(M+$0007, 'WhiteBalance', 1, '', rsNikonWhiteBalanceLkup);
AddUShortTag(M+$0008, 'Focus');
AddUShortTag(M+$000A, 'DigitalZoom');
AddUShortTag(M+$000B, 'Converter', 1, '', rsNikonConverterLkup);
end;
end;
{ for Nikon D1, E880, E885, E990, E995, E2500, E5000
Ref http://www.tawbaware.com/990exif.htm
https://sno.phy.queensu.ca/~phil/exiftool/TagNames/Nikon.html }
procedure BuildNikon2TagDefs(AList: TTagDefList);
begin
Assert(AList <> nil);
with AList do begin
AddBinaryTag (M+$0001, 'Version', 4, '', '', '', TVersionTag);
AddUShortTag (M+$0002, 'ISO', 2);
AddStringTag (M+$0003, 'ColorMode');
AddStringTag (M+$0004, 'Quality');
AddStringTag (M+$0005, 'WhiteBalance');
AddStringtag (M+$0006, 'ImageSharpening');
AddStringTag (M+$0007, 'FocusMode');
AddStringTag (M+$0008, 'FlashSetting');
AddStringTag (M+$0009, 'FlashType');
AddURationalTag(M+$000A, 'UNKNOWN');
AddStringTag (M+$000F, 'ISOSelection');
AddStringTag (M+$0080, 'ImageAdjustment');
AddStringTag (M+$0081, 'ToneComp');
AddStringTag (M+$0082, 'AuxiliaryLens');
AddURationalTag(M+$0085, 'ManualFocusDistance');
AddURationalTag(M+$0086, 'DigitalZoom');
AddBinaryTag (M+$0088, 'AFInfo');
AddStringTag (M+$008D, 'ColorHue');
AddStringTag (M+$008F, 'SceneMode');
AddStringTag (M+$0090, 'LightSource');
AddBinaryTag (M+$0010, 'DataDump');
end;
end;
// Ref.: https://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/Nikon.html
procedure BuildNikon3TagDefs(AList: TTagDefList);
begin
Assert(AList <> nil);
with AList do begin
// Tags in main MakerNote IFD
AddBinaryTag (M+$0001, 'Version', 4, '', '', '', TVersionTag);
AddUShortTag (M+$0002, 'ISO', 2);
AddStringTag (M+$0003, 'ColorMode');
AddStringTag (M+$0004, 'Quality');
AddStringTag (M+$0005, 'WhiteBalance');
AddStringtag (M+$0006, 'Sharpness');
AddStringTag (M+$0007, 'FocusMode');
AddStringTag (M+$0008, 'FlashSetting');
AddStringTag (M+$0009, 'FlashType');
AddURationalTag(M+$000A, 'UNKNOWN');
AddSShortTag (M+$000B, 'WhiteBalanceFineTune');
AddURationalTag(M+$000C, 'WB_RBLevels', 4);
AddBinaryTag (M+$000D, 'ProgramShift', 1);
AddBinaryTag (M+$000E, 'ExposureDifference', 1);
AddBinaryTag (M+$000F, 'ISOSelection');
AddBinaryTag (M+$0010, 'DataDump');
// ...
AddBinaryTag (M+$0012, 'FlashExposureComp', 4);
AddUShortTag (M+$0013, 'ISO Setting', 2);
AddUShortTag (M+$0016, 'ImageBoundary', 4);
AddBinaryTag (M+$0017, 'ExternalFlashExposureComp', 4);
AddBinaryTag (M+$0018, 'FlashExposureBracketValue', 4);
AddSRationalTag(M+$0019, 'ExposureBracketValue');
AddStringTag (M+$001A, 'ImageProcessing');
AddUShortTag (M+$001B, 'CropHiSpeed', 7, '', rsNikonCropHiSpeedLkUp, '', TNikonCropHiSpeedTag);
AddBinaryTag (M+$001C, 'ExposureTuning', 3);
AddStringTag (M+$001D, 'SerialNumber', 1, '', '', nil, true);
AddUShortTag (M+$001E, 'ColorSpace', 1, '', rsNikonColorSpaceLkUp);
AddBinaryTag (M+$001F, 'VRInfo', 8);
AddByteTag (M+$0020, 'ImageAuthentication', 1, '', rsOffOn);
// 21
AddUShortTag (M+$0022, 'ActiveD-Lighting', 1, '', rsNikonActiveDLightingLkUp);
AddBinaryTag (M+$0024, 'WorldTime');
//...
AddUShortTag (M+$002A, 'VignetteControl', 1, '', rsNikonVignetteControlLkUp);
//...
AddUShortTag (M+$0034, 'ShutterMode', 1, '', '', rsNikonShutterModeLkUp);
//..
AddULongTag (M+$0037, 'MechanicalShutterCount');
AddBinaryTag (M+$0039, 'LocationInfo');
//..
AddUShortTag (M+$003D, 'BlackLevel', 4);
AddUShortTag (M+$004F, 'ColorTemperatureAuto');
AddStringTag (M+$0080, 'ImageAdjustment');
AddStringTag (M+$0081, 'ToneComp');
AddStringTag (M+$0082, 'AuxiliaryLens');
AddByteTag (M+$0083, 'LensType', 1, '', '', '', TNikonLensTypeTag);
AddURationalTag(M+$0084, 'Lens', 4, '', '', '', TNikonLensTag);
AddURationalTag(M+$0085, 'ManualFocusDistance');
AddURationalTag(M+$0086, 'DigitalZoom');
AddByteTag (M+$0087, 'FlashMode', 1, '', rsNikonFlashModeLkUp);
AddBinaryTag (M+$0088, 'AFInfo', 4);
// ..
AddUShortTag (M+$0089, 'ShootingMode', 1, '', '', '', TNikonShootingModeTag);
AddBinaryTag (M+$008B, 'LensFStops', 4);
AddBinaryTag (M+$008C, 'ContrastCurve');
AddStringTag (M+$008D, 'ColorHude');
AddStringTag (M+$008F, 'SceneMode');
AddStringTag (M+$0090, 'LightSource');
AddSShortTag (M+$0092, 'HueAdjustment');
AddUShortTag (M+$0093, 'NEFCompression', 1, '', rsNikonNEFCompressionLkUp);
AddSShortTag (M+$0094, 'Saturation');
AddStringTag (M+$0095, 'NoiseReduction');
AddBinaryTag (M+$0097, 'NEFLinearizationTable');
AddUShortTag (M+$0099, 'RawImageCenter', 2);
AddURationalTag(M+$009A, 'SensorPixelSize', 2);
AddStringTag (M+$009C, 'SceneAssist');
AddUShortTag (M+$009E, 'RetoucheHistory', 10, '', rsNikonRetoucheHistoryLkup);
AddStringTag (M+$00A0, 'SerialNumber');
AddULongTag (M+$00A2, 'ImageDataSize');
AddULongTag (M+$00A5, 'ImageCount');
AddULongTag (M+$00A6, 'DeletedImageCount');
AddULongTag (M+$00A7, 'ShutterCount', 1, '', '', '', nil, true);
AddStringTag (M+$00A9, 'ImageOptimization');
AddStringTag (M+$00AA, 'Saturation');
AddStringTag (M+$00AB, 'VariProgram');
AddStringTag (M+$00AC, 'ImageStabilization');
AddStringTag (M+$00AD, 'AFResponse');
AddUShortTag (M+$00B1, 'HighISONoiseReduction', 1, '', rsNikonHighISONoiseReductionLkup);
AddStringTag (M+$00B3, 'ToningEffect');
AddBinaryTag (M+$00B6, 'PowerUpTime');
// ...
AddBinaryTag (M+$00B8, 'FileInfo');
AddBinaryTag (M+$00BB, 'RetoucheInfo');
AddBinaryTag (M+$00C3, 'BarometerInfo');
AddStringTag (M+$0E09, 'NikonCaptureVersion');
// ...
AddUShortTag (M+$0E22, 'NEFBitDepth', 4, '', '', '', TNikonNEFBitDepthTag);
// AddBinaryTag (M+$0103, 'CompressionValue', 1, '', rsCompressionLkUp);
end;
end;
//==============================================================================
// MakerNote reader
//==============================================================================
function TNikonMakerNoteReader.AddTag(AStream: TStream;
const AIFDRecord: TIFDRecord; const AData: TBytes; AParent: TTagID): Integer;
var
tagDef: TTagDef;
t: TTagID;
idx: Integer;
b: Byte;
w: Word;
r: TExifRational;
begin
Result := -1;
tagDef := FindTagDef(AIFDRecord.TagID or AParent);
if (tagDef = nil) then
exit;
Result := inherited AddTag(AStream, AIFDRecord, AData, AParent);
t := tagDef.TagID;
case tagDef.TagID of
TAGPARENT_MAKERNOTE+$001F: // VR info
if Length(AData) >= 8 then
with FImgInfo.ExifData do begin
AddMakerNoteStringTag(0, t, 'VRInfoVersion', AData, 4, '');
AddMakerNoteTag(4, t, 'VibrationReduction', AData[4], rsNikonVibrationReductionLkUp, '', ttUInt8);
AddMakerNoteTag(6, t, 'VRMode', AData[6], rsNikonVRModeLkUp, '', ttUInt8);
end;
TAGPARENT_MAKERNOTE+$0088:
if Length(AData) >= 4 then // AF Info
with FImgInfo.ExifData do begin
b := AData[0];
AddMakerNoteTag(0, t, 'AFAreaMode', b, rsNikonAFAreaMode, '', ttUInt8);
b := AData[1];
AddMakerNoteTag(1, t, 'AFPoint', b, rsNikonAFPoint, '', ttUInt8);
w := FixEndian16(PWord(@AData[2])^);
AddmakerNoteTag(2, t, 'AFPointsInFocus', w, rsNikonAFPointsInFocus, '', ttUInt16);
end;
TAGPARENT_MAKERNOTE+$0024:
if Length(AData) >= 4 then // WorldTime
with FImgInfo.ExifData do begin
w := FixEndian16(PWord(@AData[0])^);
AddMakerNoteTag(0, t, 'TimeZone', Integer(w), '', '', ttSInt16);
AddMakerNoteTag(2, t, 'DaylightSavings', byte(AData[2]), rsNoYes, '', ttUInt8);
AddMakerNoteTag(3, t, 'DateDisplayFormat', byte(AData[3]), rsNikonDateDisplayformat, '', ttUInt8);
end;
TAGPARENT_MAKERNOTE+$00B8:
if Length(AData) >= 8 then
with FImgInfo.ExifData do begin
idx := 0;
AddMakerNoteStringTag(idx, t, 'FileInfoVersion', AData, 4);
inc(idx, 4);
w := FixEndian16(PWord(@AData[idx])^);
AddMakerNoteTag(idx, t, 'MemoryCardNumber', Integer(w), '', '', ttUInt16);
inc(idx, 2);
w := FixEndian16(PWord(@AData[idx])^);
AddMakerNoteTag(idx, t, 'DirectoryNumber', Integer(w), '', '', ttUInt16);
inc(idx, 2);
w := FixEndian16(PWord(@AData[idx])^);
AddMakerNoteTag(idx, t, 'FileNumber', Integer(w), '', '', ttUInt16);
end;
TAGPARENT_MAKERNOTE+$BB:
if Length(ADAta) >= 6 then
with FImgInfo.ExifData do begin
AddMakerNoteStringTag(0, t, 'RetouchInfoVersion', AData, 5);
AddMakerNoteTag(5, t, 'RetouchNEFProcessing', byte(AData[5]), '', rsNikonOffOn, ttSInt8);
end;
TAGPARENT_MAKERNOTE+$00C3:
if Length(AData) >= 10 then
with FImgInfo.ExifData do begin
idx := 0;
AddMakerNoteStringTag(idx, t, 'BarometerInfoVersion', AData, 6);
inc(idx, 6);
Move(AData[idx], r{%H-}, SizeOf(r));
r.Numerator := FixEndian32(r.Numerator);
r.Denominator := FixEndian32(r.Denominator);
AddMakerNoteTag(idx, t, 'Altitude', r.Numerator/r.Denominator, '', ttSRational);
end;
end;
end;
procedure TNikonMakerNoteReader.GetTagDefs(AStream: TStream);
var
b: TBytes; //array of byte;
tmp, tmp2: String;
p: Integer;
streamPos: Int64;
begin
if Uppercase(FMake) = 'NIKON CORPORATION' then begin
SetLength(b, 20);
streamPos := AStream.Position;
AStream.Read(b[0], 20);
AStream.Position := streamPos;
SetLength(tmp, 5);
Move(b[0], tmp[1], 5);
if (PosInBytes('Nikon'#00, b) = 0) and (
(PosInBytes('MM'#00#42#00#00#00#08, b) = 10) or
(PosInBytes('II'#42#00#08#00#00#00, b) = 10)
)
then
BuildNikon3TagDefs(FTagDefs)
else begin
p := Max(0, Pos(' ', FModel));
tmp2 := FModel[p+1];
if (FExifVersion > '0210') or
((FExifVersion = '') and (tmp2 = 'D') and (FImgFormat = ifTiff))
then
BuildNikon2TagDefs(FTagDefs)
else
if (tmp = 'Nikon') then
BuildNikon1TagDefs(FTagDefs)
else
BuildNikon2TagDefs(FTagDefs);
end;
end;
end;
function TNikonMakerNoteReader.Prepare(AStream: TStream): Boolean;
var
b: TBytes;
UCMake: String;
dw: DWord;
begin
Result := false;
UCMake := Uppercase(FMake);
if UCMake = 'NIKON CORPORATION' then begin
SetLength(b, 10);
AStream.Read(b[0], 10);
if PosInBytes('Nikon'#0{#$10#00#00}, b) = 0 then begin
// These MakerNotes are relative to the beginning of the MakerNote's
// TIFF header!
FStartPosition := AStream.Position;
AStream.Read(b[0], 4);
if PosInBytes('MM'#00#42, b) = 0 then
FBigEndian := true
else
if PosInBytes('II'#42#00, b) = 0 then
FBigEndian := false
else
exit;
dw := ReadDWord(AStream);
// dw := AStream.ReadDWord;
if FBigEndian then dw := BEToN(dw) else dw := LEToN(dw);
if dw = 8 then
Result := true;
// The stream is now at the beginning of the IFD structure used by
// the Nikon maker notes.
end;
end;
end;
//==============================================================================
// Special tags
//==============================================================================
function TNikonCropHiSpeedTag.GetAsString: String;
var
s: String;
intVal: TExifIntegerArray;
begin
if (FCount = 7) and (toDecodeValue in FOptions) then begin
intVal := AsIntegerArray;
s := Lookup(IntToStr(intVal[0]), FLkupTbl, @SameIntegerFunc);
Result := Format(rsNikonCropHiSpeedMask, [
s, intval[1], intVal[2], intVal[3], intVal[4], intVal[5], intVal[6]
]);
end else
Result := inherited;
end;
function TNikonLensTypeTag.GetAsString: String;
var
intVal: Integer;
begin
if (toDecodeValue in FOptions) then begin
Result := '';
intVal := AsInteger;
if intVal and 1 <> 0 then Result := Result + 'MF+';
if intVal and 2 <> 0 then Result := Result + 'D+';
if intVal and 4 <> 0 then Result := Result + 'G+';
if intVal and 8 <> 0 then Result := Result + 'VR+';
if intval and 16 <> 0 then Result := Result + '1+';
if intVal and 32 <> 0 then Result := Result + 'E+';
if Result <> '' then SetLength(Result, Length(Result)-1);
end else
Result := inherited;
end;
function TNikonLensTag.GetAsString: String;
var
values: TExifDoubleArray;
begin
values := AsFloatArray;
if (toDecodeValue in FOptions) and (Length(values) = 4) then
Result := Format('%g-%gmm f/%g-%g', [values[0], values[1], values[2], values[3]], fpExifFmtSettings)
else
Result := inherited;
end;
function TNikonShootingModetag.GetAsString: String;
var
intVal: Integer;
begin
if (toDecodeValue in FOptions) then begin
intVal := AsInteger;
if intVal = 0 then
Result := 'Single frame'
else begin
Result := '';
if intVal and 1 <> 0 then Result := Result + 'Continuous, ';
if intVal and 2 <> 0 then Result := Result + 'Delay, ';
if intVal and 4 <> 0 then Result := Result + 'PC Control, ';
if intVal and 8 <> 0 then Result := Result + 'Self-timer, ';
if intval and 16 <> 0 then Result := Result + 'Exposure bracketing, ';
if intVal and 32 <> 0 then Result := Result + 'Auto ISO, ';
if intVal and 64 <> 0 then Result := Result + 'White-balance bracketing, ';
if intVal and 128 <> 0 then Result := Result + 'IR control, ';
if intVal and 256 <> 0 then Result := Result + 'D-Lighting bracketing, ';
if Result <> '' then SetLength(Result, Length(Result)-2);
end;
end else
Result := inherited;
end;
function TNikonNEFBitDepthTag.GetAsString: String;
var
iVal: TExifIntegerArray;
i: Integer;
n: Integer;
begin
if (FCount = 4) and (toDecodeValue in FOptions) then begin
iVal := AsIntegerArray;
if iVal[0] = 0 then
Result := 'n/a (JPEG)'
else begin
Result := intToStr(iVal[0]);
n := 1;
for i:= Succ(Low(iVal)) to High(iVal) do
if iVal[i] = 0 then
break
else if iVal[i] = iVal[0] then
inc(n)
else begin
Result := inherited;
exit;
end;
Result := Result + ' x ' + IntToStr(n);
end;
end else
Result := inherited;
end;
initialization
RegisterMakerNoteReader(TNikonMakerNoteReader, 'Nikon Corporation;Nikon', '');
end.
|
{****************************************************}
{ TeeChart Pro }
{ Polynomic routines }
{ Copyright (c) 1995-2004 by David Berneda }
{****************************************************}
unit TeePoly;
{$I TeeDefs.inc}
interface
uses
Classes;
const
MaxPolyDegree = 20; { maximum number of polynomial degree }
type
Float = {$IFDEF CLR}Double{$ELSE}Extended{$ENDIF};
TDegreeVector = Array[1..MaxPolyDegree] of Float;
TPolyMatrix = Array[1..MaxPolyDegree,1..MaxPolyDegree] of Float;
TVector = Array of Float;
Function CalcFitting( PolyDegree:Integer; const Answer:TDegreeVector; const XWert:Float):Float;
Procedure PolyFitting( NumPoints:Integer; PolyDegree:Integer;
const X,Y:TVector; var Answer:TDegreeVector);
Procedure SetVectorValue(Const V:TVector; Index:Integer; Const Value:Float);
Function GetVectorValue(Const V:TVector; Index:Integer):Float;
implementation
Uses {$IFNDEF CLR}
SysUtils,
{$ENDIF}
TeeProCo;
// GAUSSIAN POLYNOMICAL FITTING:
Function GetVectorValue(Const V:TVector; Index:Integer):Float;
Begin
result:=V[Index];
end;
Procedure SetVectorValue(Const V:TVector; Index:Integer; Const Value:Float);
begin
V[Index]:=Value;
end;
Function GaussianFitting( NumDegree:Integer;
Var M:TPolyMatrix;
Var Y,X:TDegreeVector;
Const Error:Float):Float;
var i : Integer;
j : Integer;
k : Integer;
MaxIndex : Integer;
Change : Integer;
MaxEl : Float;
Temp : Float;
Wert : Float;
begin
Change:=0;
for i:=1 to NumDegree-1 do
begin
MaxIndex:=i;
MaxEl:=Abs(M[i,i]);
for j:=i+1 to NumDegree do
if Abs(M[j,i]) > MaxEl then
begin
MaxEl:=Abs(M[j,i]);
MaxIndex:=j;
end;
if MaxIndex <> i then
begin
for j:=i to NumDegree do
begin
Temp:=M[i,j];
M[i,j]:=M[MaxIndex,j];
M[MaxIndex,j]:=Temp;
end;
Temp:=Y[i];
Y[i]:=Y[MaxIndex];
Y[MaxIndex]:=Temp;
Inc(Change);
end;
if Abs(M[i,i]) < Error then
Begin
result:=0;
exit;
end;
for j:=i+1 to NumDegree do
begin
Wert:=M[j,i]/M[i,i];
for k:=i+1 to NumDegree do M[j,k]:=M[j,k]-Wert*M[i,k];
Y[j]:=Y[j]-Wert*Y[i];
end;
end;
if Abs(M[NumDegree,NumDegree])< Error then
Begin
Result:=0;
Exit;
end;
Result:=1;
for i:=NumDegree DownTo 1 do
begin
Wert:=0;
for j:=i+1 to NumDegree do Wert:=Wert + M[i,j]*X[j];
X[i]:=(Y[i]-Wert)/M[i,i];
result:=result*M[i,i];
end;
if Odd(Change) then result:=-result;
end;
Procedure FKT(PolyDegree:Integer; Const xarg:Float; Var PHI:TDegreeVector);
var t : Integer;
begin
PHI[1]:=1;
for t:=2 to PolyDegree do PHI[t]:=PHI[t-1]*xarg;
end;
Function CalcFitting( PolyDegree:Integer;
Const Answer:TDegreeVector;
Const xwert:Float):Float;
var PHI : TDegreeVector;
t : Integer;
begin
result:=0;
FKT(PolyDegree,xwert,PHI);
for t:=1 to PolyDegree do result:=result+Answer[t]*PHI[t];
end;
Procedure PolyFitting( NumPoints:Integer; PolyDegree:Integer; const X,Y:TVector;
var Answer:TDegreeVector);
var t : Integer;
tt : Integer;
l : Integer;
PHI : TDegreeVector;
B : TDegreeVector;
F : Array[1..MaxPolyDegree] of TVector;
M : TPolyMatrix;
begin
for t:=1 to PolyDegree do F[t]:=nil;
for t:=1 to PolyDegree do
Begin
SetLength(F[t],NumPoints+1);
for tt:=0 to NumPoints do F[t][tt]:=0;
end;
try
for t:=1 to NumPoints do { Prepare the approximation }
begin
FKT(PolyDegree,X[t],PHI);
for tt:=1 to PolyDegree do F[tt][t]:=PHI[tt];
end;
for tt:=1 to PolyDegree do { Build the matrix of the LinEqu. }
for t:=1 to PolyDegree do
begin
M[t,tt]:=0;
for l:=1 to NumPoints do
M[t,tt]:=M[t,tt]+F[t][l]*F[tt][l];
M[tt,t]:=M[t,tt];
end;
for t:=1 to PolyDegree do
begin
B[t]:=0;
for l:=1 to NumPoints do
B[t]:=B[t]+F[t][l]*Y[l];
end;
if GaussianFitting(PolyDegree,M,B,Answer,1.0e-15)=0 then
Raise Exception.Create(TeeMsg_FittingError);
finally
for t:=1 to PolyDegree do F[t]:=nil;
end;
end;
end.
|
unit uFuncionario;
interface
uses
uExceptions, System.SysUtils, uEnumFuncionario;
type
TFuncionario = class
private
FNome : String;
FSetor : tSetor;
FPermissao : tPermissao;
FNomeLider : String;
FDataInclusao : TDateTime;
function GetNome: string;
function GetNomeLider: string;
function GetPermissao: tPermissao;
function GetSetor: tSetor;
procedure SetNome(const Value: string);
procedure SetNomeLider(const Value: string);
procedure SetPermissao(const Value: tPermissao);
procedure SetSetor(const Value: tSetor);
function GetDataInc: TDateTime;
public
property Nome : string read GetNome write SetNome;
property Setor : tSetor read GetSetor write SetSetor;
property Permissao : tPermissao read GetPermissao write SetPermissao;
property NomeLider : string read GetNomeLider write SetNomeLider;
property DataInc : TDateTime read GetDataInc;
function ToString : string; override;
function SetorParaString: String;
function PermissaoParaString: String;
constructor Create;
end;
implementation
{ TFuncionario }
constructor TFuncionario.Create;
begin
FDataInclusao := Now;
end;
function TFuncionario.GetDataInc: TDateTime;
begin
Result := FDataInclusao;
end;
function TFuncionario.GetNome: string;
begin
Result := FNome;
end;
function TFuncionario.GetSetor: tSetor;
begin
Result := FSetor;
end;
function TFuncionario.GetPermissao: tPermissao;
begin
Result := FPermissao;
end;
function TFuncionario.GetNomeLider: string;
begin
Result := FNomeLider;
end;
function TFuncionario.PermissaoParaString: String;
begin
if FPermissao = tPermissao.tpVisualizar then
Result := 'Vizualizar';
if FPermissao = tPermissao.tpSupervisor then
Result := 'Supervisor';
if FPermissao = tPermissao.tpNormal then
Result := 'Normal';
end;
procedure TFuncionario.SetNome(const Value: string);
begin
if Value = '' then
raise ECampoObrigatorio.Create;
FNome := Value;
end;
procedure TFuncionario.SetSetor(const Value: tSetor);
begin
if Value = tsVazio then
raise ECampoObrigatorio.Create;
FSetor := Value;
end;
procedure TFuncionario.SetPermissao(const Value: tPermissao);
begin
if Value = tpVazio then
raise ECampoObrigatorio.Create;
FPermissao := Value;
end;
procedure TFuncionario.SetNomeLider(const Value: string);
begin
if Value = '' then
raise ECampoObrigatorio.Create;
FNomeLider := Value;
end;
function TFuncionario.ToString: string;
begin
Result := 'Nome: ' + FNome + sLineBreak
+ 'Nome do líder: ' + FNomeLider + sLineBreak
+ 'Setor: ' + SetorParaString + sLineBreak
+ 'Permissão: ' + PermissaoParaString + sLineBreak
+ 'Data de inclusão: ' + DateToStr(FDataInclusao);
end;
function TFuncionario.SetorParaString: String;
begin
if FSetor = tsTi then
Result := 'TI';
if FSetor = tsAdm then
Result := 'Administração';
if FSetor = tsFinanceiro then
Result := 'Financeiro';
if FSetor = tsLimpeza then
Result := 'Limpeza';
end;
end.
|
unit Component.SSDLabel.List;
interface
uses
SysUtils, Generics.Collections, Graphics,
Component.SSDLabel, Device.PhysicalDrive;
type
TSSDLabelList = class(TList<TSSDLabel>)
private
const
LabelPerLine = 8;
HorizontalPadding = 10;
VerticalPadding = 10;
function GetMaxHeight: Integer;
function GetMaxWidth: Integer;
procedure SetFirstLabelLeft(Index: Integer);
procedure SetFirstLabelTop(Index: Integer);
procedure SetGroupboxSize;
procedure SetLabelPosition;
procedure SetMidLabelLeft(Index: Integer);
procedure SetMidLabelTop(Index: Integer);
procedure SetSingleLabelLeft(Index: Integer);
procedure SetSingleLabelPosition(Index: Integer);
procedure SetSingleLabelTop(Index: Integer);
public
destructor Destroy; override;
procedure Delete(Index: Integer);
procedure Add(SSDLabel: TSSDLabel);
function IndexOf(Entry: TPhysicalDrive): Integer;
function IsExists(Entry: TPhysicalDrive): Boolean;
function IndexOfByPath(const Path: String): Integer;
function IsExistsByPath(const Path: String): Boolean;
end;
EIndexOfNotFound = class(Exception);
implementation
uses Form.Main;
procedure TSSDLabelList.Delete(Index: Integer);
begin
Self[Index].Free;
inherited Delete(Index);
SetLabelPosition;
SetGroupboxSize;
end;
procedure TSSDLabelList.Add(SSDLabel: TSSDLabel);
begin
inherited Add(SSDLabel);
SetLabelPosition;
SetGroupboxSize;
end;
function TSSDLabelList.GetMaxWidth: Integer;
var
CurrentEntry: TSSDLabel;
begin
if Self.Count = 0 then
exit(0);
result := 0;
for CurrentEntry in Self do
begin
CurrentEntry.Font.Style := [fsBold];
if result < CurrentEntry.Left + CurrentEntry.Width then
result := CurrentEntry.Left + CurrentEntry.Width;
CurrentEntry.Font.Style := [];
end;
end;
function TSSDLabelList.GetMaxHeight: Integer;
var
CurrentEntry: TSSDLabel;
begin
if Self.Count = 0 then
exit(0);
result := 0;
for CurrentEntry in Self do
begin
CurrentEntry.Font.Style := [fsBold];
if result < CurrentEntry.Top + CurrentEntry.Height then
result := CurrentEntry.Top + CurrentEntry.Height;
CurrentEntry.Font.Style := [];
end;
end;
procedure TSSDLabelList.SetGroupboxSize;
begin
fMain.gSSDSel.Width := GetMaxWidth + HorizontalPadding;
fMain.gSSDSel.Height := GetMaxHeight + VerticalPadding;
if fMain.gSSDSel.Left + fMain.gSSDSel.Width > fMain.ClientWidth then
fMain.gSSDSel.Left := fMain.ClientWidth - fMAin.gSSDSel.Width -
HorizontalPadding;
end;
procedure TSSDLabelList.SetLabelPosition;
var
CurrentLabel: Integer;
begin
for CurrentLabel := 0 to Count - 1 do
SetSingleLabelPosition(CurrentLabel);
end;
procedure TSSDLabelList.SetFirstLabelTop(Index: Integer);
begin
Self[Index].Top := VerticalPadding;
end;
procedure TSSDLabelList.SetFirstLabelLeft(Index: Integer);
begin
Self[Index].Left := HorizontalPadding;
end;
procedure TSSDLabelList.SetMidLabelTop(Index: Integer);
begin
Self[Index].Top := Self[Index - 1].Top + Self[Index - 1].Height +
VerticalPadding;
end;
procedure TSSDLabelList.SetMidLabelLeft(Index: Integer);
begin
Self[Index].Left :=
Self[Index - LabelPerLine].Left +
Self[Index - LabelPerLine].Width +
HorizontalPadding;
end;
procedure TSSDLabelList.SetSingleLabelTop(Index: Integer);
begin
if (Index mod LabelPerLine) = 0 then
SetFirstLabelTop(Index)
else
SetMidLabelTop(Index);
end;
procedure TSSDLabelList.SetSingleLabelLeft(Index: Integer);
begin
if (Index div LabelPerLine) = 0 then
SetFirstLabelLeft(Index)
else
SetMidLabelLeft(Index);
end;
procedure TSSDLabelList.SetSingleLabelPosition(Index: Integer);
begin
SetSingleLabelLeft(Index);
SetSingleLabelTop(Index);
end;
destructor TSSDLabelList.Destroy;
var
CurrentItem: Integer;
begin
for CurrentItem := 0 to Count - 1 do //FI:W528
Delete(0);
inherited;
end;
function TSSDLabelList.IndexOf(Entry: TPhysicalDrive): Integer;
var
CurrentEntry: Integer;
begin
for CurrentEntry := 0 to Count - 1 do
if Entry.IsPathEqual(
self[CurrentEntry].PhysicalDrive.GetPathOfFileAccessing) then
exit(CurrentEntry);
raise EIndexOfNotFound.Create('EIndexOfNotFound: This list does not contain' +
' that item');
end;
function TSSDLabelList.IsExists(Entry: TPhysicalDrive): Boolean;
begin
try
result := true;
IndexOf(Entry);
except
result := false;
end;
end;
function TSSDLabelList.IndexOfByPath(const Path: String): Integer;
var
CurrentEntry: Integer;
begin
for CurrentEntry := 0 to Count - 1 do
if Self[CurrentEntry].PhysicalDrive.GetPathOfFileAccessing = Path then
exit(CurrentEntry);
raise EIndexOfNotFound.Create('EIndexOfNotFound: This list does not contain' +
' that item');
end;
function TSSDLabelList.IsExistsByPath(const Path: String): Boolean;
begin
try
result := true;
IndexOfByPath(Path);
except
result := false;
end;
end;
end. |
{*******************************************************}
{ }
{ Delphi Runtime Library }
{ SOAP Support }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Soap.WSDLNode;
interface
uses
System.Classes, System.SysUtils, System.TypInfo, Soap.IntfInfo,
Soap.SOAPAttachIntf, Soap.WebNode, Soap.WSDLItems, Soap.WSDLIntf, Xml.XMLIntf;
type
{ To report errors loading WSDLs }
EWSDLLoadException = class(Exception)
end;
TWSDLView = class(TComponent)
private
FUserName: string;
FPassword: string;
FProxy: string;
FPortType: string;
FPort: string;
FOperation: string;
FService: string;
FWSDL: TWSDLItems;
FIWSDL: IXMLDocument;
procedure SetWSDL(Value: TWSDLItems);
procedure SetOperation(const Op: string);
function GetService: String;
function GetPort: String;
public
IntfInfo: PTypeInfo;
procedure Activate;
procedure SetDesignState(Designing: Boolean);
published
property PortType: string read FPortType write FPortType;
property Port: string read GetPort write FPort;
property Operation: string read FOperation write SetOperation;
property Service: string read GetService write FService;
property UserName: string read FUserName write FUserName;
property Password: string read FPassword write FPassword;
property Proxy: string read FProxy write FProxy;
property WSDL: TWSDLItems read FWSDL write SetWSDL;
end;
TWSDLClientNode = class(TComponent, IWebNode)
private
FWSDLView: TWSDLView;
FTransportNode: IWebNode;
procedure SetTransportNode(Value: IWebNode);
protected
function GetMimeBoundary: string;
procedure SetMimeBoundary(const Value: string);
function GetWebNodeOptions: WebNodeOptions;
procedure SetWebNodeOptions(Value: WebNodeOptions);
public
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure Execute(const DataMsg: string; Resp: TStream); overload;
procedure Execute(const Request: TStream; Response: TStream); overload;
function Execute(const Request: TStream): TStream; overload;
procedure BeforeExecute(const IntfMetaData: TIntfMetaData;
const MethodMetaData: TIntfMethEntry;
MethodIndex: Integer;
AttachHandler: IMimeAttachmentHandler);
published
property WSDLView: TWSDLView read FWSDLView write FWSDLView;
property TransportNode: IWebNode read FTransportNode write SetTransportNode;
end;
function ActivateWSDL(WSDL: TWSDLItems; const Name: string; const Password: string; const Proxy: string): Boolean;
implementation
uses
Soap.SOAPConst, Xml.xmldom;
{ ActivateWSDL }
function ActivateWSDL(WSDL: TWSDLItems; const Name: string; const Password: string; const Proxy: string): Boolean;
begin
Result := True;
try
if (not WSDL.Active) then
begin
WSDL.StreamLoader.UserName := Name;
WSDL.StreamLoader.Password := Password;
WSDL.StreamLoader.Proxy := Proxy;
WSDL.Load(WSDL.FileName);
end
except
on E: EDOMParseError do
raise EWSDLLoadException.CreateFmt(SWSDLError, [WSDL.Filename, E.Message]);
end;
end;
{ TWSDLClientNode }
function TWSDLClientNode.GetMimeBoundary: string;
begin
Result := '';
end;
procedure TWSDLClientNode.SetMimeBoundary(const Value: string);
begin
end;
function TWSDLClientNode.GetWebNodeOptions: WebNodeOptions;
begin
Result := FTransportNode.Options;
end;
procedure TWSDLClientNode.SetWebNodeOptions(Value: WebNodeOptions);
begin
FTransportNode.Options := Value;
end;
procedure TWSDLClientNode.Execute(const Request: TStream; Response: TStream);
begin
end;
procedure TWSDLClientNode.Execute(const DataMsg: String; Resp: TStream);
begin
end;
function TWSDLClientNode.Execute(const Request: TStream): TStream;
begin
Result := nil;
end;
procedure TWSDLClientNode.BeforeExecute(const IntfMetaData: TIntfMetaData;
const MethodMetaData: TIntfMethEntry;
MethodIndex: Integer;
AttachHandler: IMimeAttachmentHandler);
begin
end;
procedure TWSDLClientNode.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
if (Operation = opRemove) and AComponent.IsImplementorOf(FTransportNode) then
FTransportNode := nil;
end;
procedure TWSDLClientNode.SetTransportNode(Value: IWebNode);
begin
if Assigned(Value) then
begin
ReferenceInterface(FTransportNode, opRemove);
FTransportNode := Value;
ReferenceInterface(FTransportNode, opInsert);
end;
end;
{ TWSDLView }
procedure TWSDLView.SetDesignState(Designing: Boolean);
begin
SetDesigning(Designing);
end;
procedure TWSDLView.SetWSDL(Value: TWSDLItems);
begin
if Assigned(Value) then
begin
FWSDL := Value;
FIWSDL := Value as IXMLDocument;
end;
end;
procedure TWSDLView.Activate;
begin
if Assigned(FWSDL) then
begin
ActivateWSDL(FWSDL, UserName, Password, Proxy);
end;
end;
function TWSDLView.GetService: String;
var
List: TDOMStrings;
begin
Result := FService;
if Result = '' then
begin
{ See if we can deduce the Service - i.e. if there's only one }
if Assigned(FWSDL) and not (csDesigning in ComponentState) then
begin
Activate;
List := TDOMStrings.Create;
try
FWSDL.GetServices(List);
if List.Count = 1 then
FService := List.Strings[0];
Result := FService;
finally
List.Free;
end;
end;
end;
end;
function TWSDLView.GetPort: String;
var
List: TDOMStrings;
Svc: string;
begin
Result := FPort;
if Result = '' then
begin
{ See if we can deduce the Port - i.e. if there's only one }
if Assigned(FWSDL) and not (csDesigning in ComponentState) then
begin
Svc := Service;
if (Svc <> '') then
begin
List := TDOMStrings.Create;
try
FWSDL.GetPortsForService(Svc, List);
if List.Count = 1 then
FPort := List.Strings[0];
Result := FPort;
finally
List.Free;
end;
end;
end;
end;
end;
procedure TWSDLView.SetOperation(const Op: string);
begin
FOperation := Op;
end;
end.
|
unit MemoImpl1;
interface
uses
Windows, ActiveX, Classes, Controls, Graphics, Menus, Forms, StdCtrls,
ComServ, StdVCL, AXCtrls, DelCtrls_TLB;
type
TMemoX = class(TActiveXControl, IMemoX)
private
{ Private declarations }
FDelphiControl: TMemo;
FEvents: IMemoXEvents;
procedure ChangeEvent(Sender: TObject);
procedure ClickEvent(Sender: TObject);
procedure DblClickEvent(Sender: TObject);
procedure KeyPressEvent(Sender: TObject; var Key: Char);
protected
{ Protected declarations }
procedure DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); override;
procedure EventSinkChanged(const EventSink: IUnknown); override;
procedure InitializeControl; override;
function ClassNameIs(const Name: WideString): WordBool; safecall;
function DrawTextBiDiModeFlags(Flags: Integer): Integer; safecall;
function DrawTextBiDiModeFlagsReadingOnly: Integer; safecall;
function Get_Alignment: TxAlignment; safecall;
function Get_BiDiMode: TxBiDiMode; safecall;
function Get_BorderStyle: TxBorderStyle; safecall;
function Get_CanUndo: WordBool; safecall;
function Get_Color: OLE_COLOR; safecall;
function Get_Ctl3D: WordBool; safecall;
function Get_Cursor: Smallint; safecall;
function Get_DoubleBuffered: WordBool; safecall;
function Get_DragCursor: Smallint; safecall;
function Get_DragMode: TxDragMode; safecall;
function Get_Enabled: WordBool; safecall;
function Get_Font: IFontDisp; safecall;
function Get_HideSelection: WordBool; safecall;
function Get_ImeMode: TxImeMode; safecall;
function Get_ImeName: WideString; safecall;
function Get_Lines: IStrings; safecall;
function Get_MaxLength: Integer; safecall;
function Get_Modified: WordBool; safecall;
function Get_OEMConvert: WordBool; safecall;
function Get_ParentColor: WordBool; safecall;
function Get_ParentCtl3D: WordBool; safecall;
function Get_ParentFont: WordBool; safecall;
function Get_ReadOnly: WordBool; safecall;
function Get_ScrollBars: TxScrollStyle; safecall;
function Get_SelLength: Integer; safecall;
function Get_SelStart: Integer; safecall;
function Get_SelText: WideString; safecall;
function Get_Text: WideString; safecall;
function Get_Visible: WordBool; safecall;
function Get_WantReturns: WordBool; safecall;
function Get_WantTabs: WordBool; safecall;
function Get_WordWrap: WordBool; safecall;
function GetControlsAlignment: TxAlignment; safecall;
function IsRightToLeft: WordBool; safecall;
function UseRightToLeftAlignment: WordBool; safecall;
function UseRightToLeftReading: WordBool; safecall;
function UseRightToLeftScrollBar: WordBool; safecall;
procedure _Set_Font(const Value: IFontDisp); safecall;
procedure AboutBox; safecall;
procedure Clear; safecall;
procedure ClearSelection; safecall;
procedure ClearUndo; safecall;
procedure CopyToClipboard; safecall;
procedure CutToClipboard; safecall;
procedure FlipChildren(AllLevels: WordBool); safecall;
procedure InitiateAction; safecall;
procedure PasteFromClipboard; safecall;
procedure SelectAll; safecall;
procedure Set_Alignment(Value: TxAlignment); safecall;
procedure Set_BiDiMode(Value: TxBiDiMode); safecall;
procedure Set_BorderStyle(Value: TxBorderStyle); safecall;
procedure Set_Color(Value: OLE_COLOR); safecall;
procedure Set_Ctl3D(Value: WordBool); safecall;
procedure Set_Cursor(Value: Smallint); safecall;
procedure Set_DoubleBuffered(Value: WordBool); safecall;
procedure Set_DragCursor(Value: Smallint); safecall;
procedure Set_DragMode(Value: TxDragMode); safecall;
procedure Set_Enabled(Value: WordBool); safecall;
procedure Set_Font(const Value: IFontDisp); safecall;
procedure Set_HideSelection(Value: WordBool); safecall;
procedure Set_ImeMode(Value: TxImeMode); safecall;
procedure Set_ImeName(const Value: WideString); safecall;
procedure Set_Lines(const Value: IStrings); safecall;
procedure Set_MaxLength(Value: Integer); safecall;
procedure Set_Modified(Value: WordBool); safecall;
procedure Set_OEMConvert(Value: WordBool); safecall;
procedure Set_ParentColor(Value: WordBool); safecall;
procedure Set_ParentCtl3D(Value: WordBool); safecall;
procedure Set_ParentFont(Value: WordBool); safecall;
procedure Set_ReadOnly(Value: WordBool); safecall;
procedure Set_ScrollBars(Value: TxScrollStyle); safecall;
procedure Set_SelLength(Value: Integer); safecall;
procedure Set_SelStart(Value: Integer); safecall;
procedure Set_SelText(const Value: WideString); safecall;
procedure Set_Text(const Value: WideString); safecall;
procedure Set_Visible(Value: WordBool); safecall;
procedure Set_WantReturns(Value: WordBool); safecall;
procedure Set_WantTabs(Value: WordBool); safecall;
procedure Set_WordWrap(Value: WordBool); safecall;
procedure Undo; safecall;
end;
implementation
uses ComObj, About17;
{ TMemoX }
procedure TMemoX.DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage);
begin
{ Define property pages here. Property pages are defined by calling
DefinePropertyPage with the class id of the page. For example,
DefinePropertyPage(Class_MemoXPage); }
end;
procedure TMemoX.EventSinkChanged(const EventSink: IUnknown);
begin
FEvents := EventSink as IMemoXEvents;
end;
procedure TMemoX.InitializeControl;
begin
FDelphiControl := Control as TMemo;
FDelphiControl.OnChange := ChangeEvent;
FDelphiControl.OnClick := ClickEvent;
FDelphiControl.OnDblClick := DblClickEvent;
FDelphiControl.OnKeyPress := KeyPressEvent;
end;
function TMemoX.ClassNameIs(const Name: WideString): WordBool;
begin
Result := FDelphiControl.ClassNameIs(Name);
end;
function TMemoX.DrawTextBiDiModeFlags(Flags: Integer): Integer;
begin
Result := FDelphiControl.DrawTextBiDiModeFlags(Flags);
end;
function TMemoX.DrawTextBiDiModeFlagsReadingOnly: Integer;
begin
Result := FDelphiControl.DrawTextBiDiModeFlagsReadingOnly;
end;
function TMemoX.Get_Alignment: TxAlignment;
begin
Result := Ord(FDelphiControl.Alignment);
end;
function TMemoX.Get_BiDiMode: TxBiDiMode;
begin
Result := Ord(FDelphiControl.BiDiMode);
end;
function TMemoX.Get_BorderStyle: TxBorderStyle;
begin
Result := Ord(FDelphiControl.BorderStyle);
end;
function TMemoX.Get_CanUndo: WordBool;
begin
Result := FDelphiControl.CanUndo;
end;
function TMemoX.Get_Color: OLE_COLOR;
begin
Result := OLE_COLOR(FDelphiControl.Color);
end;
function TMemoX.Get_Ctl3D: WordBool;
begin
Result := FDelphiControl.Ctl3D;
end;
function TMemoX.Get_Cursor: Smallint;
begin
Result := Smallint(FDelphiControl.Cursor);
end;
function TMemoX.Get_DoubleBuffered: WordBool;
begin
Result := FDelphiControl.DoubleBuffered;
end;
function TMemoX.Get_DragCursor: Smallint;
begin
Result := Smallint(FDelphiControl.DragCursor);
end;
function TMemoX.Get_DragMode: TxDragMode;
begin
Result := Ord(FDelphiControl.DragMode);
end;
function TMemoX.Get_Enabled: WordBool;
begin
Result := FDelphiControl.Enabled;
end;
function TMemoX.Get_Font: IFontDisp;
begin
GetOleFont(FDelphiControl.Font, Result);
end;
function TMemoX.Get_HideSelection: WordBool;
begin
Result := FDelphiControl.HideSelection;
end;
function TMemoX.Get_ImeMode: TxImeMode;
begin
Result := Ord(FDelphiControl.ImeMode);
end;
function TMemoX.Get_ImeName: WideString;
begin
Result := WideString(FDelphiControl.ImeName);
end;
function TMemoX.Get_Lines: IStrings;
begin
GetOleStrings(FDelphiControl.Lines, Result);
end;
function TMemoX.Get_MaxLength: Integer;
begin
Result := FDelphiControl.MaxLength;
end;
function TMemoX.Get_Modified: WordBool;
begin
Result := FDelphiControl.Modified;
end;
function TMemoX.Get_OEMConvert: WordBool;
begin
Result := FDelphiControl.OEMConvert;
end;
function TMemoX.Get_ParentColor: WordBool;
begin
Result := FDelphiControl.ParentColor;
end;
function TMemoX.Get_ParentCtl3D: WordBool;
begin
Result := FDelphiControl.ParentCtl3D;
end;
function TMemoX.Get_ParentFont: WordBool;
begin
Result := FDelphiControl.ParentFont;
end;
function TMemoX.Get_ReadOnly: WordBool;
begin
Result := FDelphiControl.ReadOnly;
end;
function TMemoX.Get_ScrollBars: TxScrollStyle;
begin
Result := Ord(FDelphiControl.ScrollBars);
end;
function TMemoX.Get_SelLength: Integer;
begin
Result := FDelphiControl.SelLength;
end;
function TMemoX.Get_SelStart: Integer;
begin
Result := FDelphiControl.SelStart;
end;
function TMemoX.Get_SelText: WideString;
begin
Result := WideString(FDelphiControl.SelText);
end;
function TMemoX.Get_Text: WideString;
begin
Result := WideString(FDelphiControl.Text);
end;
function TMemoX.Get_Visible: WordBool;
begin
Result := FDelphiControl.Visible;
end;
function TMemoX.Get_WantReturns: WordBool;
begin
Result := FDelphiControl.WantReturns;
end;
function TMemoX.Get_WantTabs: WordBool;
begin
Result := FDelphiControl.WantTabs;
end;
function TMemoX.Get_WordWrap: WordBool;
begin
Result := FDelphiControl.WordWrap;
end;
function TMemoX.GetControlsAlignment: TxAlignment;
begin
Result := TxAlignment(FDelphiControl.GetControlsAlignment);
end;
function TMemoX.IsRightToLeft: WordBool;
begin
Result := FDelphiControl.IsRightToLeft;
end;
function TMemoX.UseRightToLeftAlignment: WordBool;
begin
Result := FDelphiControl.UseRightToLeftAlignment;
end;
function TMemoX.UseRightToLeftReading: WordBool;
begin
Result := FDelphiControl.UseRightToLeftReading;
end;
function TMemoX.UseRightToLeftScrollBar: WordBool;
begin
Result := FDelphiControl.UseRightToLeftScrollBar;
end;
procedure TMemoX._Set_Font(const Value: IFontDisp);
begin
SetOleFont(FDelphiControl.Font, Value);
end;
procedure TMemoX.AboutBox;
begin
ShowMemoXAbout;
end;
procedure TMemoX.Clear;
begin
FDelphiControl.Clear;
end;
procedure TMemoX.ClearSelection;
begin
FDelphiControl.ClearSelection;
end;
procedure TMemoX.ClearUndo;
begin
FDelphiControl.ClearUndo;
end;
procedure TMemoX.CopyToClipboard;
begin
FDelphiControl.CopyToClipboard;
end;
procedure TMemoX.CutToClipboard;
begin
FDelphiControl.CutToClipboard;
end;
procedure TMemoX.FlipChildren(AllLevels: WordBool);
begin
FDelphiControl.FlipChildren(AllLevels);
end;
procedure TMemoX.InitiateAction;
begin
FDelphiControl.InitiateAction;
end;
procedure TMemoX.PasteFromClipboard;
begin
FDelphiControl.PasteFromClipboard;
end;
procedure TMemoX.SelectAll;
begin
FDelphiControl.SelectAll;
end;
procedure TMemoX.Set_Alignment(Value: TxAlignment);
begin
FDelphiControl.Alignment := TAlignment(Value);
end;
procedure TMemoX.Set_BiDiMode(Value: TxBiDiMode);
begin
FDelphiControl.BiDiMode := TBiDiMode(Value);
end;
procedure TMemoX.Set_BorderStyle(Value: TxBorderStyle);
begin
FDelphiControl.BorderStyle := TBorderStyle(Value);
end;
procedure TMemoX.Set_Color(Value: OLE_COLOR);
begin
FDelphiControl.Color := TColor(Value);
end;
procedure TMemoX.Set_Ctl3D(Value: WordBool);
begin
FDelphiControl.Ctl3D := Value;
end;
procedure TMemoX.Set_Cursor(Value: Smallint);
begin
FDelphiControl.Cursor := TCursor(Value);
end;
procedure TMemoX.Set_DoubleBuffered(Value: WordBool);
begin
FDelphiControl.DoubleBuffered := Value;
end;
procedure TMemoX.Set_DragCursor(Value: Smallint);
begin
FDelphiControl.DragCursor := TCursor(Value);
end;
procedure TMemoX.Set_DragMode(Value: TxDragMode);
begin
FDelphiControl.DragMode := TDragMode(Value);
end;
procedure TMemoX.Set_Enabled(Value: WordBool);
begin
FDelphiControl.Enabled := Value;
end;
procedure TMemoX.Set_Font(const Value: IFontDisp);
begin
SetOleFont(FDelphiControl.Font, Value);
end;
procedure TMemoX.Set_HideSelection(Value: WordBool);
begin
FDelphiControl.HideSelection := Value;
end;
procedure TMemoX.Set_ImeMode(Value: TxImeMode);
begin
FDelphiControl.ImeMode := TImeMode(Value);
end;
procedure TMemoX.Set_ImeName(const Value: WideString);
begin
FDelphiControl.ImeName := TImeName(Value);
end;
procedure TMemoX.Set_Lines(const Value: IStrings);
begin
SetOleStrings(FDelphiControl.Lines, Value);
end;
procedure TMemoX.Set_MaxLength(Value: Integer);
begin
FDelphiControl.MaxLength := Value;
end;
procedure TMemoX.Set_Modified(Value: WordBool);
begin
FDelphiControl.Modified := Value;
end;
procedure TMemoX.Set_OEMConvert(Value: WordBool);
begin
FDelphiControl.OEMConvert := Value;
end;
procedure TMemoX.Set_ParentColor(Value: WordBool);
begin
FDelphiControl.ParentColor := Value;
end;
procedure TMemoX.Set_ParentCtl3D(Value: WordBool);
begin
FDelphiControl.ParentCtl3D := Value;
end;
procedure TMemoX.Set_ParentFont(Value: WordBool);
begin
FDelphiControl.ParentFont := Value;
end;
procedure TMemoX.Set_ReadOnly(Value: WordBool);
begin
FDelphiControl.ReadOnly := Value;
end;
procedure TMemoX.Set_ScrollBars(Value: TxScrollStyle);
begin
FDelphiControl.ScrollBars := TScrollStyle(Value);
end;
procedure TMemoX.Set_SelLength(Value: Integer);
begin
FDelphiControl.SelLength := Value;
end;
procedure TMemoX.Set_SelStart(Value: Integer);
begin
FDelphiControl.SelStart := Value;
end;
procedure TMemoX.Set_SelText(const Value: WideString);
begin
FDelphiControl.SelText := String(Value);
end;
procedure TMemoX.Set_Text(const Value: WideString);
begin
FDelphiControl.Text := TCaption(Value);
end;
procedure TMemoX.Set_Visible(Value: WordBool);
begin
FDelphiControl.Visible := Value;
end;
procedure TMemoX.Set_WantReturns(Value: WordBool);
begin
FDelphiControl.WantReturns := Value;
end;
procedure TMemoX.Set_WantTabs(Value: WordBool);
begin
FDelphiControl.WantTabs := Value;
end;
procedure TMemoX.Set_WordWrap(Value: WordBool);
begin
FDelphiControl.WordWrap := Value;
end;
procedure TMemoX.Undo;
begin
FDelphiControl.Undo;
end;
procedure TMemoX.ChangeEvent(Sender: TObject);
begin
if FEvents <> nil then FEvents.OnChange;
end;
procedure TMemoX.ClickEvent(Sender: TObject);
begin
if FEvents <> nil then FEvents.OnClick;
end;
procedure TMemoX.DblClickEvent(Sender: TObject);
begin
if FEvents <> nil then FEvents.OnDblClick;
end;
procedure TMemoX.KeyPressEvent(Sender: TObject; var Key: Char);
var
TempKey: Smallint;
begin
TempKey := Smallint(Key);
if FEvents <> nil then FEvents.OnKeyPress(TempKey);
Key := Char(TempKey);
end;
initialization
TActiveXControlFactory.Create(
ComServer,
TMemoX,
TMemo,
Class_MemoX,
17,
'{695CDB59-02E5-11D2-B20D-00C04FA368D4}',
0,
tmApartment);
end.
|
{*******************************************************}
{ }
{ Delphi Runtime Library }
{ }
{ File: MLang.h }
{ Copyright (c) Microsoft Corporation }
{ All Rights Reserved. }
{ }
{ Translator: Embarcadero Technologies, Inc. }
{ Copyright(c) 2014-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Winapi.MLang;
{$ALIGN 4}
{$HPPEMIT ''}
{$HPPEMIT '#include <MLang.h>' }
{$HPPEMIT ''}
interface
uses Winapi.Windows, Winapi.ActiveX;
const
SID_IMLangStringBufW = '{D24ACD21-BA72-11D0-B188-00AA0038C969}';
SID_IMLangStringBufA = '{D24ACD23-BA72-11D0-B188-00AA0038C969}';
SID_IMLangString = '{C04D65CE-B70D-11D0-B188-00AA0038C969}';
SID_IMLangStringWStr = '{C04D65D0-B70D-11D0-B188-00AA0038C969}';
SID_IMLangStringAStr = '{C04D65D2-B70D-11D0-B188-00AA0038C969}';
SID_IMLangLineBreakConsole = '{F5BE2EE1-BFD7-11D0-B188-00AA0038C969}';
SID_IEnumCodePage = '{275c23e3-3747-11d0-9fea-00aa003f8646}';
SID_IEnumRfc1766 = '{3dc39d1d-c030-11d0-b81b-00c04fc9b31f}';
SID_IEnumScript = '{AE5F1430-388B-11d2-8380-00C04F8F5DA1}';
SID_IMLangConvertCharset = '{d66d6f98-cdaa-11d0-b822-00c04fc9b31f}';
SID_IMultiLanguage = '{275c23e1-3747-11d0-9fea-00aa003f8646}';
SID_IMultiLanguage2 = '{DCCFC164-2B38-11d2-B7EC-00C04F8F5D9A}';
SID_IMLangCodePages = '{359F3443-BD4A-11D0-B188-00AA0038C969}';
SID_IMLangFontLink = '{359F3441-BD4A-11D0-B188-00AA0038C969}';
SID_IMLangFontLink2 = '{DCCFC162-2B38-11d2-B7EC-00C04F8F5D9A}';
SID_IMultiLanguage3 = '{4e5868ab-b157-4623-9acc-6a1d9caebe04}';
IID_IMLangStringBufW: TGUID = '{D24ACD21-BA72-11D0-B188-00AA0038C969}';
IID_IMLangStringBufA: TGUID = '{D24ACD23-BA72-11D0-B188-00AA0038C969}';
IID_IMLangString: TGUID = '{C04D65CE-B70D-11D0-B188-00AA0038C969}';
IID_IMLangStringWStr: TGUID = '{C04D65D0-B70D-11D0-B188-00AA0038C969}';
IID_IMLangStringAStr: TGUID = '{C04D65D2-B70D-11D0-B188-00AA0038C969}';
IID_IMLangLineBreakConsole: TGUID = '{F5BE2EE1-BFD7-11D0-B188-00AA0038C969}';
IID_IEnumCodePage: TGUID = '{275C23E3-3747-11D0-9FEA-00AA003F8646}';
IID_IEnumRfc1766: TGUID = '{3DC39D1D-C030-11D0-B81B-00C04FC9B31F}';
IID_IEnumScript: TGUID = '{AE5F1430-388B-11D2-8380-00C04F8F5DA1}';
IID_IMLangConvertCharset: TGUID = '{D66D6F98-CDAA-11D0-B822-00C04FC9B31F}';
IID_IMultiLanguage: TGUID = '{275C23E1-3747-11D0-9FEA-00AA003F8646}';
IID_IMultiLanguage2: TGUID = '{DCCFC164-2B38-11D2-B7EC-00C04F8F5D9A}';
IID_IMLangCodePages: TGUID = '{359F3443-BD4A-11D0-B188-00AA0038C969}';
IID_IMLangFontLink: TGUID = '{359F3441-BD4A-11D0-B188-00AA0038C969}';
IID_IMLangFontLink2: TGUID = '{DCCFC162-2B38-11D2-B7EC-00C04F8F5D9A}';
IID_IMultiLanguage3: TGUID = '{4E5868AB-B157-4623-9ACC-6A1D9CAEBE04}';
type
// *********************************************************************//
// Interface: IMLangStringBufW
// Flags: (0)
// GUID: {D24ACD21-BA72-11D0-B188-00AA0038C969}
// *********************************************************************//
{$HPPEMIT 'DECLARE_DINTERFACE_TYPE(IMLangStringBufW);'}
IMLangStringBufW = interface(IUnknown)
[SID_IMLangStringBufW]
function GetStatus(out plFlags: Integer; out pcchBuf: Integer): HResult; stdcall;
function LockBuf(cchOffset: Integer; cchMaxLock: Integer; out ppszBuf: PWideChar;
out pcchBuf: Integer): HResult; stdcall;
function UnlockBuf(pszBuf: PWord; cchOffset: Integer; cchWrite: Integer): HResult; stdcall;
function Insert(cchOffset: Integer; cchMaxInsert: Integer; out pcchActual: Integer)
: HResult; stdcall;
function Delete(cchOffset: Integer; cchDelete: Integer): HResult; stdcall;
end;
// *********************************************************************//
// Interface: IMLangStringBufA
// Flags: (0)
// GUID: {D24ACD23-BA72-11D0-B188-00AA0038C969}
// *********************************************************************//
{$HPPEMIT 'DECLARE_DINTERFACE_TYPE(IMLangStringBufA);'}
IMLangStringBufA = interface(IUnknown)
[SID_IMLangStringBufA]
function GetStatus(out plFlags: Integer; out pcchBuf: Integer): HResult; stdcall;
function LockBuf(cchOffset: Integer; cchMaxLock: Integer; out ppszBuf: PAnsiChar;
out pcchBuf: Integer): HResult; stdcall;
function UnlockBuf(pszBuf: PByte; cchOffset: Integer; cchWrite: Integer)
: HResult; stdcall;
function Insert(cchOffset: Integer; cchMaxInsert: Integer; out pcchActual: Integer)
: HResult; stdcall;
function Delete(cchOffset: Integer; cchDelete: Integer): HResult; stdcall;
end;
// *********************************************************************//
// Interface: IMLangString
// Flags: (0)
// GUID: {C04D65CE-B70D-11D0-B188-00AA0038C969}
// *********************************************************************//
{$HPPEMIT 'DECLARE_DINTERFACE_TYPE(IMLangString);'}
IMLangString = interface(IUnknown)
[SID_IMLangString]
function Sync(fNoAccess: Integer): HResult; stdcall;
function GetLength(out plLen: Integer): HResult; stdcall;
function SetMLStr(lDestPos: Integer; lDestLen: Integer; const pSrcMLStr: IUnknown;
lSrcPos: Integer; lSrcLen: Integer): HResult; stdcall;
function GetMLStr(lSrcPos: Integer; lSrcLen: Integer; const pUnkOuter: IUnknown;
dwClsContext: LongWord; var piid: TGUID; out ppDestMLStr: IUnknown; out plDestPos: Integer;
out plDestLen: Integer): HResult; stdcall;
end;
// *********************************************************************//
// Interface: IMLangStringWStr
// Flags: (0)
// GUID: {C04D65D0-B70D-11D0-B188-00AA0038C969}
// *********************************************************************//
{$HPPEMIT 'DECLARE_DINTERFACE_TYPE(IMLangStringWStr);'}
IMLangStringWStr = interface(IMLangString)
[SID_IMLangStringWStr]
function SetWStr(lDestPos: Integer; lDestLen: Integer; pszSrc: PWideChar; cchSrc: Integer;
out pcchActual: Integer; out plActualLen: Integer): HResult; stdcall;
function SetStrBufW(lDestPos: Integer; lDestLen: Integer; const pSrcBuf: IMLangStringBufW;
out pcchActual: Integer; out plActualLen: Integer): HResult; stdcall;
function GetWStr(lSrcPos: Integer; lSrcLen: Integer; pszDest: PWideChar; cchDest: Integer;
out pcchActual: Integer; out plActualLen: Integer): HResult; stdcall;
function GetStrBufW(lSrcPos: Integer; lSrcMaxLen: Integer; out ppDestBuf: IMLangStringBufW;
out plDestLen: Integer): HResult; stdcall;
function LockWStr(lSrcPos: Integer; lSrcLen: Integer; lFlags: Integer; cchRequest: Integer;
out ppszDest: PWideChar; out pcchDest: Integer; out plDestLen: Integer): HResult; stdcall;
function UnlockWStr(pszSrc: PWideChar; cchSrc: Integer; out pcchActual: Integer;
out plActualLen: Integer): HResult; stdcall;
function SetLocale(lDestPos: Integer; lDestLen: Integer; locale: LongWord): HResult; stdcall;
function GetLocale(lSrcPos: Integer; lSrcMaxLen: Integer; out plocale: LongWord;
out plLocalePos: Integer; out plLocaleLen: Integer): HResult; stdcall;
end;
// *********************************************************************//
// Interface: IMLangStringAStr
// Flags: (0)
// GUID: {C04D65D2-B70D-11D0-B188-00AA0038C969}
// *********************************************************************//
{$HPPEMIT 'DECLARE_DINTERFACE_TYPE(IMLangStringAStr);'}
IMLangStringAStr = interface(IMLangString)
[SID_IMLangStringAStr]
function SetAStr(lDestPos: Integer; lDestLen: Integer; uCodePage: UINT; pszSrc: PAnsiChar;
cchSrc: Integer; out pcchActual: Integer; out plActualLen: Integer): HResult; stdcall;
function SetStrBufA(lDestPos: Integer; lDestLen: Integer; uCodePage: UINT;
const pSrcBuf: IMLangStringBufA; out pcchActual: Integer; out plActualLen: Integer)
: HResult; stdcall;
function GetAStr(lSrcPos: Integer; lSrcLen: Integer; uCodePageIn: UINT;
out puCodePageOut: UINT; pszDest: PAnsiChar; cchDest: Integer; out pcchActual: Integer;
out plActualLen: Integer): HResult; stdcall;
function GetStrBufA(lSrcPos: Integer; lSrcMaxLen: Integer; out puDestCodePage: UINT;
out ppDestBuf: IMLangStringBufA; out plDestLen: Integer): HResult; stdcall;
function LockAStr(lSrcPos: Integer; lSrcLen: Integer; lFlags: Integer; uCodePageIn: UINT;
cchRequest: Integer; out puCodePageOut: UINT; out ppszDest: PAnsiChar;
out pcchDest: Integer; out plDestLen: Integer): HResult; stdcall;
function UnlockAStr(pszSrc: PAnsiChar; cchSrc: Integer; out pcchActual: Integer;
out plActualLen: Integer): HResult; stdcall;
function SetLocale(lDestPos: Integer; lDestLen: Integer; locale: LongWord): HResult; stdcall;
function GetLocale(lSrcPos: Integer; lSrcMaxLen: Integer; out plocale: LongWord;
out plLocalePos: Integer; out plLocaleLen: Integer): HResult; stdcall;
end;
// *********************************************************************//
// Interface: IMLangLineBreakConsole
// Flags: (0)
// GUID: {F5BE2EE1-BFD7-11D0-B188-00AA0038C969}
// *********************************************************************//
{$HPPEMIT 'DECLARE_DINTERFACE_TYPE(IMLangLineBreakConsole);'}
IMLangLineBreakConsole = interface(IUnknown)
[SID_IMLangLineBreakConsole]
function BreakLineML(const pSrcMLStr: IMLangString; lSrcPos: Integer; lSrcLen: Integer;
cMinColumns: Integer; cMaxColumns: Integer; out plLineLen: Integer; out plSkipLen: Integer)
: HResult; stdcall;
function BreakLineW(locale: LongWord; pszSrc: PWideChar; cchSrc: Integer; cMaxColumns: Integer;
out pcchLine: Integer; out pcchSkip: Integer): HResult; stdcall;
function BreakLineA(locale: LongWord; uCodePage: UINT; pszSrc: PAnsiChar; cchSrc: Integer;
cMaxColumns: Integer; out pcchLine: Integer; out pcchSkip: Integer): HResult; stdcall;
end;
const
MAX_MIMECP_NAME = 64 ;
{$EXTERNALSYM MAX_MIMECP_NAME}
MAX_MIMECSET_NAME = 50 ;
{$EXTERNALSYM MAX_MIMECSET_NAME}
MAX_MIMEFACE_NAME = 32 ;
{$EXTERNALSYM MAX_MIMEFACE_NAME}
MIMECONTF_MAILNEWS = $00000001;
{$EXTERNALSYM MIMECONTF_MAILNEWS}
MIMECONTF_BROWSER = $00000002;
{$EXTERNALSYM MIMECONTF_BROWSER}
MIMECONTF_MINIMAL = $00000004;
{$EXTERNALSYM MIMECONTF_MINIMAL}
MIMECONTF_IMPORT = $00000008;
{$EXTERNALSYM MIMECONTF_IMPORT}
MIMECONTF_SAVABLE_MAILNEWS = $00000100;
{$EXTERNALSYM MIMECONTF_SAVABLE_MAILNEWS}
MIMECONTF_SAVABLE_BROWSER = $00000200;
{$EXTERNALSYM MIMECONTF_SAVABLE_BROWSER}
MIMECONTF_EXPORT = $00000400;
{$EXTERNALSYM MIMECONTF_EXPORT}
MIMECONTF_PRIVCONVERTER = $00010000;
{$EXTERNALSYM MIMECONTF_PRIVCONVERTER}
MIMECONTF_VALID = $00020000;
{$EXTERNALSYM MIMECONTF_VALID}
MIMECONTF_VALID_NLS = $00040000;
{$EXTERNALSYM MIMECONTF_VALID_NLS}
MIMECONTF_MIME_IE4 = $10000000;
{$EXTERNALSYM MIMECONTF_MIME_IE4}
MIMECONTF_MIME_LATEST = $20000000;
{$EXTERNALSYM MIMECONTF_MIME_LATEST}
MIMECONTF_MIME_REGISTRY = $40000000;
{$EXTERNALSYM MIMECONTF_MIME_REGISTRY}
type
PMimeCPInfo = ^TMimeCPInfo;
tagMIMECPINFO = record
dwFlags: DWORD;
uiCodePage: UINT;
uiFamilyCodePage: UINT;
wszDescription: packed array[0..MAX_MIMECP_NAME-1] of WCHAR;
wszWebCharset: packed array[0..MAX_MIMECSET_NAME-1] of WCHAR;
wszHeaderCharset: packed array[0..MAX_MIMECSET_NAME-1] of WCHAR;
wszBodyCharset: packed array[0..MAX_MIMECSET_NAME-1] of WCHAR;
wszFixedWidthFont: packed array[0..MAX_MIMEFACE_NAME-1] of WCHAR;
wszProportionalFont: packed array[0..MAX_MIMEFACE_NAME-1] of WCHAR;
bGDICharset: BYTE;
end;
{$EXTERNALSYM tagMIMECPINFO}
TMimeCPInfo = tagMIMECPINFO;
MIMECPINFO = tagMIMECPINFO;
{$EXTERNALSYM MIMECPINFO}
PMimeCsetInfo = ^TMimeCsetInfo;
tagMIMECSETINFO = record
uiCodePage: UINT;
uiInternetEncoding: UINT;
wszCharset: packed array[0..49] of WCHAR;
end;
{$EXTERNALSYM MIMECSETINFO}
TMimeCsetInfo = tagMIMECSETINFO;
MIMECSETINFO = tagMIMECSETINFO;
{$EXTERNALSYM tagMIMECSETINFO}
// *********************************************************************//
// Interface: IEnumCodePage
// Flags: (0)
// GUID: {275C23E3-3747-11D0-9FEA-00AA003F8646}
// *********************************************************************//
{$HPPEMIT 'DECLARE_DINTERFACE_TYPE(IEnumCodePage);'}
IEnumCodePage = interface(IUnknown)
[SID_IEnumCodePage]
function Clone(out ppEnum: IEnumCodePage): HResult; stdcall;
function Next(celt: LongWord; out rgelt: tagMIMECPINFO; out pceltFetched: LongWord)
: HResult; stdcall;
function Reset: HResult; stdcall;
function Skip(celt: LongWord): HResult; stdcall;
end;
const
MAX_RFC1766_NAME = 6 ;
{$EXTERNALSYM MAX_RFC1766_NAME}
MAX_LOCALE_NAME = 32 ;
{$EXTERNALSYM MAX_LOCALE_NAME}
type
PRFC1766Info = ^TRFC1766Info;
tagRFC1766INFO = record
lcid: LCID;
wszRfc1766: packed array[0..MAX_RFC1766_NAME-1] of WCHAR;
wszLocaleName: packed array[0..MAX_LOCALE_NAME-1] of WCHAR;
end;
{$EXTERNALSYM tagRFC1766INFO}
TRFC1766Info = tagRFC1766INFO;
RFC1766INFO = tagRFC1766INFO;
{$EXTERNALSYM RFC1766INFO}
// *********************************************************************//
// Interface: IEnumRfc1766
// Flags: (0)
// GUID: {3DC39D1D-C030-11D0-B81B-00C04FC9B31F}
// *********************************************************************//
{$HPPEMIT 'DECLARE_DINTERFACE_TYPE(IEnumRfc1766);'}
IEnumRfc1766 = interface(IUnknown)
[SID_IEnumRfc1766]
function Clone(out ppEnum: IEnumRfc1766): HResult; stdcall;
function Next(celt: LongWord; out rgelt: tagRFC1766INFO; out pceltFetched: LongWord)
: HResult; stdcall;
function Reset: HResult; stdcall;
function Skip(celt: LongWord): HResult; stdcall;
end;
const
MAX_SCRIPT_NAME = 48 ;
{$EXTERNALSYM MAX_SCRIPT_NAME}
type
SCRIPT_ID = BYTE;
{$EXTERNALSYM SCRIPT_ID}
TScriptID = SCRIPT_ID;
SCRIPT_IDS = int64;
{$EXTERNALSYM SCRIPT_IDS}
TScriptIDs = SCRIPT_IDS;
const
sidDefault = 0;
sidMerge = SIDDEFAULT + 1;
sidAsciiSym = SIDMERGE + 1;
sidAsciiLatin = SIDASCIISYM + 1;
sidLatin = SIDASCIILATIN + 1;
sidGreek = SIDLATIN + 1;
sidCyrillic = SIDGREEK + 1;
sidArmenian = SIDCYRILLIC + 1;
sidHebrew = SIDARMENIAN + 1;
sidArabic = SIDHEBREW + 1;
sidDevanagari = SIDARABIC + 1;
sidBengali = SIDDEVANAGARI + 1;
sidGurmukhi = SIDBENGALI + 1;
sidGujarati = SIDGURMUKHI + 1;
sidOriya = SIDGUJARATI + 1;
sidTamil = SIDORIYA + 1;
sidTelugu = SIDTAMIL + 1;
sidKannada = SIDTELUGU + 1;
sidMalayalam = SIDKANNADA + 1;
sidThai = SIDMALAYALAM + 1;
sidLao = SIDTHAI + 1;
sidTibetan = SIDLAO + 1;
sidGeorgian = SIDTIBETAN + 1;
sidHangul = SIDGEORGIAN + 1;
sidKana = SIDHANGUL + 1;
sidBopomofo = SIDKANA + 1;
sidHan = SIDBOPOMOFO + 1;
sidEthiopic = SIDHAN + 1;
sidCanSyllabic = SIDETHIOPIC + 1;
sidCherokee = SIDCANSYLLABIC + 1;
sidYi = SIDCHEROKEE + 1;
sidBraille = SIDYI + 1;
sidRunic = SIDBRAILLE + 1;
sidOgham = SIDRUNIC + 1;
sidSinhala = SIDOGHAM + 1;
sidSyriac = SIDSINHALA + 1;
sidBurmese = SIDSYRIAC + 1;
sidKhmer = SIDBURMESE + 1;
sidThaana = SIDKHMER + 1;
sidMongolian = SIDTHAANA + 1;
sidUserDefined = SIDMONGOLIAN + 1;
sidLim = SIDUSERDEFINED + 1;
sidFEFirst = SIDHANGUL;
sidFELast = SIDHAN;
type
tagSCRIPTINFO = record
ScriptId: TScriptID;
uiCodePage: UINT;
wszDescription: packed array[0..MAX_SCRIPT_NAME-1] of WCHAR;
wszFixedWidthFont: packed array[0..MAX_MIMEFACE_NAME-1] of WCHAR;
wszProportionalFont: packed array[0..MAX_MIMEFACE_NAME-1] of WCHAR;
end;
{$EXTERNALSYM tagSCRIPTINFO}
TScriptInfo = tagSCRIPTINFO;
SCRIPTINFO = tagSCRIPTINFO;
{$EXTERNALSYM SCRIPTINFO}
// *********************************************************************//
// Interface: IEnumScript
// Flags: (0)
// GUID: {AE5F1430-388B-11D2-8380-00C04F8F5DA1}
// *********************************************************************//
{$HPPEMIT 'DECLARE_DINTERFACE_TYPE(IEnumScript);'}
IEnumScript = interface(IUnknown)
[SID_IEnumScript]
function Clone(out ppEnum: IEnumScript): HResult; stdcall;
function Next(celt: LongWord; out rgelt: tagSCRIPTINFO; out pceltFetched: LongWord)
: HResult; stdcall;
function Reset: HResult; stdcall;
function Skip(celt: LongWord): HResult; stdcall;
end;
const
MLCONVCHARF_AUTODETECT = 1;
MLCONVCHARF_ENTITIZE = 2;
MLCONVCHARF_NCR_ENTITIZE = 2;
MLCONVCHARF_NAME_ENTITIZE = 4;
MLCONVCHARF_USEDEFCHAR = 8;
MLCONVCHARF_NOBESTFITCHARS = 16;
MLCONVCHARF_DETECTJPN = 32;
MLDETECTF_MAILNEWS = $1;
MLDETECTF_BROWSER = $2;
MLDETECTF_VALID = $4;
MLDETECTF_VALID_NLS = $8;
MLDETECTF_PRESERVE_ORDER = $10;
MLDETECTF_PREFERRED_ONLY = $20;
MLDETECTF_FILTER_SPECIALCHAR = $40;
MLDETECTF_EURO_UTF8 = $80;
type
// *********************************************************************//
// Interface: IMLangConvertCharset
// Flags: (0)
// GUID: {D66D6F98-CDAA-11D0-B822-00C04FC9B31F}
// *********************************************************************//
{$HPPEMIT 'DECLARE_DINTERFACE_TYPE(IMLangConvertCharset);'}
IMLangConvertCharset = interface(IUnknown)
[SID_IMLangConvertCharset]
function Initialize(uiSrcCodePage: UINT; uiDstCodePage: UINT; dwProperty: LongWord)
: HResult; stdcall;
function GetSourceCodePage(out puiSrcCodePage: UINT): HResult; stdcall;
function GetDestinationCodePage(out puiDstCodePage: UINT): HResult; stdcall;
function GetProperty(out pdwProperty: LongWord): HResult; stdcall;
function DoConversion(pSrcStr: Pointer; pcSrcSize: PUINT; pDstStr: Pointer;
var pcDstSize: UINT): HResult; stdcall;
function DoConversionToUnicode(pSrcStr: Pointer; pcSrcSize: PUINT; pDstStr: PWideChar;
var pcDstSize: UINT): HResult; stdcall;
function DoConversionFromUnicode(pSrcStr: PWideChar; pcSrcSize: PUINT;
pDstStr: Pointer; var pcDstSize: UINT): HResult; stdcall;
end;
// *********************************************************************//
// Interface: IMultiLanguage
// Flags: (0)
// GUID: {275C23E1-3747-11D0-9FEA-00AA003F8646}
// *********************************************************************//
{$HPPEMIT 'DECLARE_DINTERFACE_TYPE(IMultiLanguage);'}
IMultiLanguage = interface(IUnknown)
[SID_IMultiLanguage]
function GetNumberOfCodePageInfo(out pcCodePage: UINT): HResult; stdcall;
function GetCodePageInfo(uiCodePage: UINT; out pCodePageInfo: tagMIMECPINFO)
: HResult; stdcall;
function GetFamilyCodePage(uiCodePage: UINT; out puiFamilyCodePage: UINT)
: HResult; stdcall;
function EnumCodePages(grfFlags: LongWord; out ppEnumCodePage: IEnumCodePage): HResult; stdcall;
function GetCharsetInfo(const Charset: WideString; out pCharsetInfo: tagMIMECSETINFO)
: HResult; stdcall;
function IsConvertible(dwSrcEncoding: LongWord; dwDstEncoding: LongWord): HResult; stdcall;
function ConvertString(var pdwMode: LongWord; dwSrcEncoding: LongWord; dwDstEncoding: LongWord;
pSrcStr: Pointer; pcSrcSize: PUINT; pDstStr: Pointer; var pcDstSize: UINT)
: HResult; stdcall;
function ConvertStringToUnicode(var pdwMode: LongWord; dwEncoding: LongWord;
pSrcStr: Pointer; pcSrcSize: PUINT; pDstStr: PWideChar; var pcDstSize: UINT)
: HResult; stdcall;
function ConvertStringFromUnicode(var pdwMode: LongWord; dwEncoding: LongWord;
pSrcStr: PWideChar; pcSrcSize: PUINT; pDstStr: Pointer; var pcDstSize: UINT)
: HResult; stdcall;
function ConvertStringReset: HResult; stdcall;
function GetRfc1766FromLcid(locale: LongWord; out pbstrRfc1766: WideString): HResult; stdcall;
function GetLcidFromRfc1766(out plocale: LongWord; const bstrRfc1766: WideString)
: HResult; stdcall;
function EnumRfc1766(out ppEnumRfc1766: IEnumRfc1766): HResult; stdcall;
function GetRfc1766Info(locale: LongWord; out pRfc1766Info: tagRFC1766INFO): HResult; stdcall;
function CreateConvertCharset(uiSrcCodePage: UINT; uiDstCodePage: UINT;
dwProperty: LongWord; out ppMLangConvertCharset: IMLangConvertCharset): HResult; stdcall;
end;
{ dwfIODControl definitions for ValidateCodePageEx() }
const
CPIOD_PEEK = $40000000;
{$EXTERNALSYM CPIOD_PEEK}
CPIOD_FORCE_PROMPT = $80000000;
{$EXTERNALSYM CPIOD_FORCE_PROMPT}
MLDETECTCP_NONE = 0;
MLDETECTCP_7BIT = 1;
MLDETECTCP_8BIT = 2;
MLDETECTCP_DBCS = 4;
MLDETECTCP_HTML = 8;
MLDETECTCP_NUMBER = 16;
type
PDetectEncodingInfo = ^TDetectEncodingInfo;
tagDetectEncodingInfo = record
nLangID: UInt32;
nCodePage: UInt32;
nDocPercent: Int32;
nConfidence: Int32
end;
{$EXTERNALSYM tagDetectEncodingInfo}
TDetectEncodingInfo = tagDetectEncodingInfo;
DetectEncodingInfo = tagDetectEncodingInfo;
{$EXTERNALSYM DetectEncodingInfo}
const
SCRIPTCONTF_FIXED_FONT = $1;
SCRIPTCONTF_PROPORTIONAL_FONT = $2;
SCRIPTCONTF_SCRIPT_USER = $10000;
SCRIPTCONTF_SCRIPT_HIDE = $20000;
SCRIPTCONTF_SCRIPT_SYSTEM = $40000;
type
PScriptFontInfo = ^TScriptFontInfo;
tagSCRIPFONTINFO = record
scripts: TScriptIDs;
wszFont: packed array[0..31] of WCHAR;
end;
{$EXTERNALSYM tagSCRIPFONTINFO}
TScriptFontInfo = tagSCRIPFONTINFO;
SCRIPTFONTINFO = tagSCRIPFONTINFO;
{$EXTERNALSYM SCRIPTFONTINFO}
// *********************************************************************//
// Interface: IMultiLanguage2
// Flags: (0)
// GUID: {DCCFC164-2B38-11D2-B7EC-00C04F8F5D9A}
// *********************************************************************//
{$HPPEMIT 'DECLARE_DINTERFACE_TYPE(IMultiLanguage2);'}
IMultiLanguage2 = interface(IUnknown)
[SID_IMultiLanguage2]
function GetNumberOfCodePageInfo(out pcCodePage: UINT): HResult; stdcall;
function GetCodePageInfo(uiCodePage: UINT; LangId: Word; out pCodePageInfo: tagMIMECPINFO)
: HResult; stdcall;
function GetFamilyCodePage(uiCodePage: UINT; out puiFamilyCodePage: UINT)
: HResult; stdcall;
function EnumCodePages(grfFlags: LongWord; LangId: Word; out ppEnumCodePage: IEnumCodePage)
: HResult; stdcall;
function GetCharsetInfo(const Charset: WideString; out pCharsetInfo: tagMIMECSETINFO)
: HResult; stdcall;
function IsConvertible(dwSrcEncoding: LongWord; dwDstEncoding: LongWord): HResult; stdcall;
function ConvertString(var pdwMode: LongWord; dwSrcEncoding: LongWord; dwDstEncoding: LongWord;
pSrcStr: Pointer; pcSrcSize: PUINT; pDstStr: Pointer; var pcDstSize: UINT)
: HResult; stdcall;
function ConvertStringToUnicode(var pdwMode: LongWord; dwEncoding: LongWord;
pSrcStr: Pointer; pcSrcSize: PUINT; pDstStr: PWideChar; var pcDstSize: UINT)
: HResult; stdcall;
function ConvertStringFromUnicode(var pdwMode: LongWord; dwEncoding: LongWord;
pSrcStr: PWideChar; pcSrcSize: PUINT; pDstStr: Pointer; var pcDstSize: UINT)
: HResult; stdcall;
function ConvertStringReset: HResult; stdcall;
function GetRfc1766FromLcid(locale: LongWord; out pbstrRfc1766: WideString): HResult; stdcall;
function GetLcidFromRfc1766(out plocale: LongWord; const bstrRfc1766: WideString)
: HResult; stdcall;
function EnumRfc1766(LangId: Word; out ppEnumRfc1766: IEnumRfc1766): HResult; stdcall;
function GetRfc1766Info(locale: LongWord; LangId: Word; out pRfc1766Info: tagRFC1766INFO)
: HResult; stdcall;
function CreateConvertCharset(uiSrcCodePage: UINT; uiDstCodePage: UINT;
dwProperty: LongWord; out ppMLangConvertCharset: IMLangConvertCharset): HResult; stdcall;
function ConvertStringInIStream(var pdwMode: LongWord; dwFlag: LongWord; lpFallBack: PWideChar;
dwSrcEncoding: LongWord; dwDstEncoding: LongWord; const [ref] pstmIn: IStream;
const [ref] pstmOut: IStream): HResult; stdcall;
function ConvertStringToUnicodeEx(var pdwMode: LongWord; dwEncoding: LongWord;
pSrcStr: Pointer; pcSrcSize: PUINT; pDstStr: PWideChar; var pcDstSize: UINT;
dwFlag: LongWord; lpFallBack: PWideChar): HResult; stdcall;
function ConvertStringFromUnicodeEx(var pdwMode: LongWord; dwEncoding: LongWord;
pSrcStr: PWideChar; pcSrcSize: PUINT; pDstStr: Pointer; var pcDstSize: UINT;
dwFlag: LongWord; lpFallBack: PWideChar): HResult; stdcall;
function DetectCodepageInIStream(dwFlag: LongWord; dwPrefWinCodePage: LongWord;
const [ref] pstmIn: IStream; lpEncoding: PDetectEncodingInfo; var pnScores: Integer)
: HResult; stdcall;
function DetectInputCodepage(dwFlag: LongWord; dwPrefWinCodePage: LongWord;
pSrcStr: Pointer; var pcSrcSize: Integer; lpEncoding: PDetectEncodingInfo;
var pnScores: Integer): HResult; stdcall;
function ValidateCodePage(uiCodePage: UINT; hwnd: HWND): HResult; stdcall;
function GetCodePageDescription(uiCodePage: UINT; lcid: LongWord; lpWideCharStr: PWideChar;
cchWideChar: Integer): HResult; stdcall;
function IsCodePageInstallable(uiCodePage: UINT): HResult; stdcall;
function SetMimeDBSource(dwSource: UINT): HResult; stdcall;
function GetNumberOfScripts(out pnScripts: UINT): HResult; stdcall;
function EnumScripts(dwFlags: LongWord; LangId: Word; out ppEnumScript: IEnumScript)
: HResult; stdcall;
function ValidateCodePageEx(uiCodePage: UINT; hwnd: HWND;
dwfIODControl: LongWord): HResult; stdcall;
end;
// *********************************************************************//
// Interface: IMLangCodePages
// Flags: (0)
// GUID: {359F3443-BD4A-11D0-B188-00AA0038C969}
// *********************************************************************//
{$HPPEMIT 'DECLARE_DINTERFACE_TYPE(IMLangCodePages);'}
IMLangCodePages = interface(IUnknown)
[SID_IMLangCodePages]
function GetCharCodePages(chSrc: WideChar; out pdwCodePages: LongWord): HResult; stdcall;
function GetStrCodePages(pszSrc: PWideChar; cchSrc: Integer; dwPriorityCodePages: LongWord;
out pdwCodePages: LongWord; out pcchCodePages: Integer): HResult; stdcall;
function CodePageToCodePages(uCodePage: UINT; out pdwCodePages: LongWord): HResult; stdcall;
function CodePagesToCodePage(dwCodePages: LongWord; uDefaultCodePage: UINT;
out puCodePage: UINT): HResult; stdcall;
end;
// *********************************************************************//
// Interface: IMLangFontLink
// Flags: (0)
// GUID: {359F3441-BD4A-11D0-B188-00AA0038C969}
// *********************************************************************//
{$HPPEMIT 'DECLARE_DINTERFACE_TYPE(IMLangFontLink);'}
IMLangFontLink = interface(IMLangCodePages)
[SID_IMLangFontLink]
function GetFontCodePages(hDC: HDC; hFont: HFONT;
out pdwCodePages: LongWord): HResult; stdcall;
function MapFont(hDC: HDC; dwCodePages: LongWord;
hSrcFont: HFONT; out phDestFont: HFONT): HResult; stdcall;
function ReleaseFont(hFont: HFONT): HResult; stdcall;
function ResetFontMapping: HResult; stdcall;
end;
PUnicodeRange = ^TUnicodeRange;
tagUNICODERANGE = record
wcFrom: WCHAR;
wcTo: WCHAR;
end;
{$EXTERNALSYM tagUNICODERANGE}
TUnicodeRange = tagUNICODERANGE;
UNICODERANGE = tagUNICODERANGE;
{$EXTERNALSYM UNICODERANGE}
// *********************************************************************//
// Interface: IMLangFontLink2
// Flags: (0)
// GUID: {DCCFC162-2B38-11D2-B7EC-00C04F8F5D9A}
// *********************************************************************//
{$HPPEMIT 'DECLARE_DINTERFACE_TYPE(IMLangFontLink2);'}
IMLangFontLink2 = interface(IMLangCodePages)
[SID_IMLangFontLink2]
function GetFontCodePages(hDC: HDC; hFont: HFONT;
out pdwCodePages: LongWord): HResult; stdcall;
function ReleaseFont(hFont: HFONT): HResult; stdcall;
function ResetFontMapping: HResult; stdcall;
function MapFont(hDC: HDC; dwCodePages: LongWord; chSrc: WideChar;
out pFont: HFONT): HResult; stdcall;
function GetFontUnicodeRanges(hDC: HDC; var puiRanges: UINT;
pUranges: PUnicodeRange): HResult; stdcall;
function GetScriptFontInfo(sid: Byte; dwFlags: LongWord; var puiFonts: UINT;
pScriptFont: PScriptFontInfo): HResult; stdcall;
function CodePageToScriptID(uiCodePage: UINT; out pSid: Byte): HResult; stdcall;
end;
// *********************************************************************//
// Interface: IMultiLanguage3
// Flags: (0)
// GUID: {4E5868AB-B157-4623-9ACC-6A1D9CAEBE04}
// *********************************************************************//
{$HPPEMIT 'DECLARE_DINTERFACE_TYPE(IMultiLanguage3);'}
IMultiLanguage3 = interface(IMultiLanguage2)
[SID_IMultiLanguage3]
function DetectOutboundCodePage(dwFlags: LongWord; lpWideCharStr: PWideChar;
cchWideChar: UINT; puiPreferredCodePages: PUINT; nPreferredCodePages: UINT;
puiDetectedCodePages: PUINT; var pnDetectedCodePages: UINT; lpSpecialChar: PWideChar)
: HResult; stdcall;
function DetectOutboundCodePageInIStream(dwFlags: LongWord; const [ref] pStrIn: IStream;
puiPreferredCodePages: PUINT; nPreferredCodePages: UINT;
puiDetectedCodePages: PUINT; var pnDetectedCodePages: UINT; lpSpecialChar: PWideChar)
: HResult; stdcall;
end;
const
MLSTR_READ = 1;
MLSTR_WRITE = 2;
CLSID_CMLangString: TGUID = '{C04D65CF-B70D-11D0-B188-00AA0038C969}';
{$EXTERNALSYM CLSID_CMLangString}
CLSID_CMLangConvertCharset: TGUID = '{d66d6f99-cdaa-11d0-b822-00c04fc9b31f}';
{$EXTERNALSYM CLSID_CMLangConvertCharset}
CLSID_CMultiLanguage: TGUID = '{275c23e2-3747-11d0-9fea-00aa003f8646}';
{$EXTERNALSYM CLSID_CMultiLanguage}
{ APIs prototypes }
function LcidToRfc1766(Local: LCID; ptszRfc1766: LPWSTR; iMaxLength: integer):LongInt; stdcall;
{$EXTERNALSYM LcidToRfc1766}
function LcidToRfc1766A(Local: LCID; ptszRfc1766: LPSTR; iMaxLength: integer):LongInt; stdcall;
{$EXTERNALSYM LcidToRfc1766A}
function LcidToRfc1766W(Local: LCID; ptszRfc1766: LPWSTR; iMaxLength: integer):LongInt; stdcall;
{$EXTERNALSYM LcidToRfc1766W}
function Rfc1766ToLcid(out pLocale:LCID; ptszRfc1766: LPCWSTR):LongInt; stdcall;
{$EXTERNALSYM Rfc1766ToLcid}
function Rfc1766ToLcidA(out pLocale:LCID; ptszRfc1766: LPCSTR):LongInt; stdcall;
{$EXTERNALSYM Rfc1766ToLcidA}
function Rfc1766ToLcidW(out pLocale:LCID; ptszRfc1766: LPCWSTR):LongInt; stdcall;
{$EXTERNALSYM Rfc1766ToLcidW}
function IsConvertINetStringAvailable(dwSrcEncoding: DWORD;
dwDstEncoding: DWORD):LongInt; stdcall;
{$EXTERNALSYM IsConvertINetStringAvailable}
function ConvertINetString(lpdwMode: LPDWORD; dwSrcEncoding: DWORD;
dwDstEncoding: DWORD; lpSrcStr: LPCSTR; lpnSrcSize: PINT; lpDstStr: LPSTR;
lpnDstSize: PINT):LongInt; stdcall;
{$EXTERNALSYM ConvertINetString}
function ConvertINetMultiByteToUnicode( lpdwMode: LPDWORD; dwEncoding: DWORD;
lpSrcStr: LPCSTR; lpnMultiCharCount: PINT; lpDstStr: LPWSTR;
lpnWideCharCount: PINT):LongInt; stdcall;
{$EXTERNALSYM ConvertINetMultiByteToUnicode}
function ConvertINetUnicodeToMultiByte(lpdwMode: LPDWORD; dwEncoding: DWORD;
lpSrcStr: LPCWSTR; lpnWideCharCount: PINT; lpDstStr: LPSTR;
lpnMultiCharCount: PINT):LongInt; stdcall;
{$EXTERNALSYM ConvertINetUnicodeToMultiByte}
type
// *********************************************************************//
// Declaration of CoClasses defined in Type Library
// (NOTE: Here we map each CoClass to its Default Interface)
// *********************************************************************//
CMLangString = IMLangString;
CMLangConvertCharset = IMLangConvertCharset;
CMultiLanguage = IMultiLanguage;
// *********************************************************************//
// The Class CoCMLangString provides a Create and CreateRemote method to
// create instances of the default interface IMLangString exposed by
// the CoClass CMLangString. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoCMLangString = class
class function Create: IMLangString;
class function CreateRemote(const MachineName: string): IMLangString;
end;
// *********************************************************************//
// The Class CoCMLangConvertCharset provides a Create and CreateRemote method to
// create instances of the default interface IMLangConvertCharset exposed by
// the CoClass CMLangConvertCharset. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoCMLangConvertCharset = class
class function Create: IMLangConvertCharset;
class function CreateRemote(const MachineName: string): IMLangConvertCharset;
end;
// *********************************************************************//
// The Class CoCMultiLanguage provides a Create and CreateRemote method to
// create instances of the default interface IMultiLanguage exposed by
// the CoClass CMultiLanguage. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoCMultiLanguage = class
class function Create: IMultiLanguage;
class function CreateRemote(const MachineName: string): IMultiLanguage;
end;
CoCMultiLanguage2 = class
class function Create: IMultiLanguage2;
class function CreateRemote(const MachineName: string): IMultiLanguage2;
end;
CoCMultiLanguage3 = class
class function Create: IMultiLanguage3;
class function CreateRemote(const MachineName: string): IMultiLanguage3;
end;
implementation
uses System.Win.ComObj;
const
ModName = 'MLANG.DLL';
function ConvertINetMultiByteToUnicode; external ModName name 'ConvertINetMultiByteToUnicode';
function ConvertINetString; external ModName name 'ConvertINetString';
function ConvertINetUnicodeToMultiByte; external ModName name 'ConvertINetUnicodeToMultiByte';
function IsConvertINetStringAvailable; external ModName name 'IsConvertINetStringAvailable';
function LcidToRfc1766; external ModName name 'LcidToRfc1766W';
function LcidToRfc1766A; external ModName name 'LcidToRfc1766A';
function LcidToRfc1766W; external ModName name 'LcidToRfc1766W';
function Rfc1766ToLcid; external ModName name 'Rfc1766ToLcidW';
function Rfc1766ToLcidA; external ModName name 'Rfc1766ToLcidA';
function Rfc1766ToLcidW; external ModName name 'Rfc1766ToLcidW';
class function CoCMLangString.Create: IMLangString;
begin
Result := CreateComObject(CLSID_CMLangString) as IMLangString;
end;
class function CoCMLangString.CreateRemote(const MachineName: string): IMLangString;
begin
Result := CreateRemoteComObject(MachineName, CLSID_CMLangString) as IMLangString;
end;
class function CoCMLangConvertCharset.Create: IMLangConvertCharset;
begin
Result := CreateComObject(CLSID_CMLangConvertCharset) as IMLangConvertCharset;
end;
class function CoCMLangConvertCharset.CreateRemote(const MachineName: string): IMLangConvertCharset;
begin
Result := CreateRemoteComObject(MachineName, CLSID_CMLangConvertCharset) as IMLangConvertCharset;
end;
class function CoCMultiLanguage.Create: IMultiLanguage;
begin
Result := CreateComObject(CLSID_CMultiLanguage) as IMultiLanguage;
end;
class function CoCMultiLanguage.CreateRemote(const MachineName: string): IMultiLanguage;
begin
Result := CreateRemoteComObject(MachineName, CLSID_CMultiLanguage) as IMultiLanguage;
end;
class function CoCMultiLanguage2.Create: IMultiLanguage2;
begin
Result := CreateComObject(CLSID_CMultiLanguage) as IMultiLanguage2;
end;
class function CoCMultiLanguage2.CreateRemote(const MachineName: string): IMultiLanguage2;
begin
Result := CreateRemoteComObject(MachineName, CLSID_CMultiLanguage) as IMultiLanguage2;
end;
class function CoCMultiLanguage3.Create: IMultiLanguage3;
begin
Result := CreateComObject(CLSID_CMultiLanguage) as IMultiLanguage3;
end;
class function CoCMultiLanguage3.CreateRemote(const MachineName: string): IMultiLanguage3;
begin
Result := CreateRemoteComObject(MachineName, CLSID_CMultiLanguage) as IMultiLanguage3;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.