text
stringlengths
14
6.51M
unit Common; interface uses SysUtils, ActiveX, Winsock, Classes; const strEncryptCode : String = 'VZHLEPDQKYMGSOJX'; type StringArray = array of string; function Split(const Source: string; ASplit: string): StringArray; function SplitToStringList(const Source: string; ASplit: string): TStrings; overload; function SplitToStringList(const Source: string; ASplit: string; Strings: TStrings): TStrings; overload; function toArr(const Source: string): StringArray; //字符串变为一个数组 function toStringList(const Source: string): TStrings; //字符串变为一个数组 function StrToUniCode(text: string): string; function UnicodeToStr(text: string): string; procedure CompletStr(var text: string; Lengths: Integer); // 用0填充text为指定长度 function CheckNum(const V: string): Boolean; //验证是否是数子 function CreateOnlyId: string; //产生唯一序列号 function CompletWeight(text: string; LengthInt, LengthFloat: Integer): string; //格式化重量输出 function GetIPAddr: string; //获取ip地址 function FormatDouble(Source: Double; Format: string): Double; //四舍五入数字 function RandomStr(): string; //随机取得4位a到z之间字符串 function BooleanToStr(va: boolean): string; function Encrypt(Source: string): string; //解密 function Decrypt(Source: string): string; //加密 implementation function Encrypt(Source: string): string; var i, n, j: Integer; strTmp: string; chrTmp: Char; begin // strEncryptCode := 'VZHLEPDQKYMGSOJX'; Result := ''; n := Length(Source); if (n <= 0) or (n >= 100) then Exit; // 限制 // 生成2位长度 if n < 10 then Result := '0' + IntToStr(n) // 长度 else Result := IntToStr(n); // 生成 00+AABBCCDD.... for i := 1 to n do begin chrTmp := Source[i]; strTmp := IntToHex(Ord(ChrTmp), 2); Result := Result + strTmp; end; n := Length(Result); strTmp := Copy(Result, n, 1); Delete(Result, n, 1); Result := strTmp + Result; // 最后一个字符放到第一个字符 strTmp := ''; // for i := 1 to n do // 替换 begin case Result[i] of '0'..'9': strTmp := strTmp + strEncryptCode[StrToInt(Result[i]) + 1]; 'A'..'F', 'a'..'f': begin j := Ord(UpperCase(Result[i])[1]) - 54; //(-55+1)//91; strTmp := strTmp + strEncryptCode[j]; end; end; end; Result := strTmp; end; function Decrypt(Source: string): string; var i, n, j, k: Integer; strTmp, strTmp1: string; //chrTmp: Char; begin Result := ''; n := Length(Source); if n <= 4 then Exit; j := -1; strTmp := ''; for i := 1 to n do begin StrTmp := Source[i]; j := Pos(strTmp, strEncryptCode) - 1; if j < 0 then break; //if j>9 then j := j + 54; Result := Result + IntToHex(j, 1); end; if j < 0 then // 出错 begin Result := ''; Exit; end; strTmp := Copy(Result, 1, 1); Delete(Result, 1, 1); Result := Result + strTmp; strTmp := Copy(Result, 1, 2); try k := StrToInt(strTmp); except Result := ''; Exit; end; if k > ((n - 2) div 2) then // 较验长度 begin Result := ''; Exit; end; n := k; strTmp := ''; for i := 1 to n do begin strTmp1 := Copy(Result, i * 2 + 1, 2); j := 0; for k := 1 to 2 do begin case strTmp1[k] of '0'..'9': j := j * 16 + StrToInt(strTmp1[k]); 'A'..'F', 'a'..'f': begin j := j * 16 + Ord(UpperCase(strTmp1[k])[1]) - 55; //91 end; end; end; strTmp := strTmp + Chr(j); end; Result := strTmp; end; function FormatDouble(Source: Double; Format: string): Double; var Temp: string; begin Temp := FormatFloat(Format, Source); Result := StrtoFloat(Temp); end; function Split(const Source: string; ASplit: string): StringArray; var AStr: string; rArray: StringArray; I: Integer; begin if Source = '' then Exit; AStr := Source; I := pos(ASplit, Source); Setlength(rArray, 0); while I <> 0 do begin Setlength(rArray, Length(rArray) + 1); rArray[Length(rArray) - 1] := copy(AStr, 0, I - 1); Delete(AStr, 1, I + Length(ASplit) - 1); I := pos(ASplit, AStr); end; Setlength(rArray, Length(rArray) + 1); rArray[Length(rArray) - 1] := AStr; Result := rArray; end; function SplitToStringList(const Source: string; ASplit: string): TStrings; var rArray: StringArray; Roles: TStrings; I: Integer; begin rArray := Split(Source, ASplit); Roles := TStringList.Create; for I := 0 to Length(rArray) - 1 do begin if rArray[I] = '' then Continue; if Roles.IndexOf(rArray[I]) = -1 then Roles.Add(rArray[I]); end; Result := Roles; end; function SplitToStringList(const Source: string; ASplit: string; Strings: TStrings): TStrings; var rArray: StringArray; I: Integer; begin rArray := Split(Source, ASplit); for I := 0 to Length(rArray) - 1 do begin Strings.Add(rArray[I]); end; Result := Strings; end; function StrToUniCode(text: string): string; var I, len: Integer; cur: Integer; t: string; ws: WideString; begin Result := ''; ws := text; len := Length(ws); I := 1; Result := '\u'; while I <= len do begin cur := Ord(ws[I]); FmtStr(t, '%4.4X', [cur]); Result := Result + t; if I <> len then Result := Result + '\u'; Inc(I); end; end; // 恢复 function UnicodeToStr(text: string): string; var I, len: Integer; ws: WideString; begin ws := ''; I := 1; len := Length(text); while I < len do begin ws := ws + Widechar(StrToInt('$' + copy(text, I, 4))); I := I + 4; end; Result := ws; end; procedure CompletStr(var text: string; Lengths: Integer); // 用0填充text为指定长度 var L, I: Integer; begin L := Lengths - Length(text); for I := 0 to L - 1 do begin text := '0' + text; end; end; function CreateOnlyId: string; //产生唯一序列号 var AGuid: TGuid; begin if CoCreateGuid(AGuid) = s_OK then begin Result := Split(Split(GUIDToString(AGuid), '{')[1], '}')[0]; end; end; function CheckNum(const V: string): Boolean; var Temp: Double; begin Result := false; try Temp := StrtoFloat(V); Result := true; except end; end; function CompletWeight(text: string; LengthInt, LengthFloat: Integer): string; //格式化重量输出 var SA: StringArray; L, I: Integer; begin SA := Split(text, '.'); L := LengthInt - Length(SA[0]); text := SA[0]; for I := 0 to L - 1 do begin text := '0' + text; end; text := text + '.'; if Length(SA) = 2 then begin L := LengthFloat - Length(SA[1]); text := text + SA[1]; end else begin L := LengthFloat; end; for I := 0 to L - 1 do begin text := text + '0'; end; Result := text; end; function toArr(const Source: string): StringArray; //字符串变为一个数组 var rArray: StringArray; I: Integer; begin for I := 1 to Length(Source) do begin SetLength(rArray, Length(rArray) + 1); rArray[Length(rArray) - 1] := Copy(Source, I, 1); end; Result := rArray; end; function toStringList(const Source: string): TStrings; //字符串变为一个数组 var a:TStrings; I:Integer; begin a:=TStringList.Create; for I := 1 to Length(Source) do begin a.Add(Copy(Source, I, 1)) end; Result := a; end; function GetIPAddr: string; //获取ip地址 type TaPInAddr = array[0..10] of PInAddr; PaPInAddr = ^TaPInAddr; var phe: PHostEnt; pptr: PaPInAddr; Buffer: array[0..63] of char; I: Integer; GInitData: TWSADATA; begin WSAStartup($101, GInitData); Result := ''; GetHostName(Buffer, SizeOf(Buffer)); phe := GetHostByName(buffer); if phe = nil then Exit; pptr := PaPInAddr(Phe^.h_addr_list); I := 0; while pptr^[I] <> nil do begin result := StrPas(inet_ntoa(pptr^[I]^)); Inc(I); end; WSACleanup; end; function RandomStr(): string; var PicName: string; I: Integer; begin Randomize; for I := 1 to 4 do PicName := PicName + chr(97 + random(26)); RandomStr := PicName; end; function BooleanToStr(va: boolean): string; begin if va then Result := 'true' else Result := 'false'; end; end.
unit util_utf8; interface uses Windows; type UTF8String = AnsiString; function AnsiToWide(const S: AnsiString): WideString; function WideToUTF8(const WS: WideString): UTF8String; function AnsiToUTF8(const S: AnsiString): UTF8String; function UTF8ToWide(const US: UTF8String): WideString; function WideToAnsi(const WS: WideString): AnsiString; function UTF8ToAnsi(const S: UTF8String): AnsiString; implementation function AnsiToWide(const S: AnsiString): WideString; var len: integer; ws: WideString; begin Result:=''; if (Length(S) = 0) then exit; len:=MultiByteToWideChar(CP_ACP, 0, PChar(s), -1, nil, 0); SetLength(ws, len); MultiByteToWideChar(CP_ACP, 0, PChar(s), -1, PWideChar(ws), len); Result:=ws; end; function WideToUTF8(const WS: WideString): UTF8String; var len: integer; us: UTF8String; begin Result:=''; if (Length(WS) = 0) then exit; len:=WideCharToMultiByte(CP_UTF8, 0, PWideChar(WS), -1, nil, 0, nil, nil); SetLength(us, len); WideCharToMultiByte(CP_UTF8, 0, PWideChar(WS), -1, PChar(us), len, nil, nil); Result:=us; end; function AnsiToUTF8(const S: AnsiString): UTF8String; begin Result:=WideToUTF8(AnsiToWide(S)); end; function UTF8ToWide(const US: UTF8String): WideString; var len: integer; ws: WideString; begin Result:=''; if (Length(US) = 0) then exit; len:=MultiByteToWideChar(CP_UTF8, 0, PChar(US), -1, nil, 0); SetLength(ws, len); MultiByteToWideChar(CP_UTF8, 0, PChar(US), -1, PWideChar(ws), len); Result:=ws; end; function WideToAnsi(const WS: WideString): AnsiString; var len: integer; s: AnsiString; begin Result:=''; if (Length(WS) = 0) then exit; len:=WideCharToMultiByte(CP_ACP, 0, PWideChar(WS), -1, nil, 0, nil, nil); SetLength(s, len); WideCharToMultiByte(CP_ACP, 0, PWideChar(WS), -1, PChar(s), len, nil, nil); Result:=s; end; function UTF8ToAnsi(const S: UTF8String): AnsiString; begin Result:=WideToAnsi(UTF8ToWide(S)); end; end.
unit Grijjy.FBSDK.Android; { Provides class abstraction for the Facebook SDK libraries for Android } interface uses System.SysUtils, System.Messaging, FMX.Platform, Androidapi.JNI, Androidapi.JNI.App, Androidapi.JNIBridge, Androidapi.JNI.JavaTypes, Androidapi.JNI.Os, Androidapi.JNI.GraphicsContentViewText, Grijjy.FBSDK.Android.API; type TgoFacebookSDK = class private FCallbackManager: JCallbackManager; FLoginManager: JLoginManager; private type TFacebookCallback = class(TJavaLocal, JFacebookCallback) private [weak] FImplementation: TgoFacebookSDK; public procedure onCancel; cdecl; procedure onError(P1: JFacebookException); cdecl; { Login } procedure onSuccess(P1: JObject); cdecl; public constructor Create(const AImplementation: TgoFacebookSDK); end; private FFacebookCallback: TFacebookCallback; procedure HandleActivityMessage(const Sender: TObject; const M: TMessage); procedure ApplicationEventHandler(const Sender: TObject; const Msg: TMessage); private type { Graph Requests } TFacebookGraphRequestHandler = class(TJavaLocal, JGraphRequest_CallbackClass, JGraphRequest_Callback) private FImplementation: TgoFacebookSDK; public procedure onCompleted(P1: JGraphResponse); cdecl; public constructor Create(const AImplementation: TgoFacebookSDK); end; private FFacebookGraphRequestHandler: TFacebookGraphRequestHandler; public { Login } procedure LogInWithReadPermissions(const APermissions: TArray<String>); function CurrentAccessToken: String; function CurrentUserId: String; public { Graph Requests } procedure GraphPath(const APath: String); public constructor Create; destructor Destroy; override; end; var FacebookSDK: TgoFacebookSDK; implementation uses System.Types, System.UITypes, System.Classes, Androidapi.Helpers, Grijjy.FBSDK.Types; { Helpers } function _StringsToJArrayList(const AStrings: TArray<String>): JArrayList; var S: JString; AString: String; begin Result := TJArrayList.JavaClass.init(Length(AStrings)); for AString in AStrings do begin S := StringToJString(AString); Result.add(S); end; end; function _JSetToStrings(const ASet: JSet): TArray<String>; var Iterator: JIterator; Index: Integer; S: JString; begin SetLength(Result, ASet.size); Index := 0; Iterator := ASet.iterator; while Iterator.hasNext do begin S := TJString.Wrap((Iterator.next as ILocalObject).GetObjectID); if S <> nil then begin Result[Index] := JStringToString(S); Inc(Index); end; end; end; function IsFacebookIntent(const AIntent: JIntent): Boolean; var Extras: JBundle; ExtrasArray: TJavaObjectArray<AndroidApi.JNI.JavaTypes.JObject>; begin Extras := AIntent.getExtras; if Extras <> nil then begin ExtrasArray := Extras.KeySet.toArray; if ExtrasArray.Length > 0 then Result := JStringToString(ExtrasArray.Items[0].toString) = 'com.facebook.LoginFragment:Result' else Result := False; end else Result := False; end; { TgoFacebookSDK.TFacebookCallback } constructor TgoFacebookSDK.TFacebookCallback.Create( const AImplementation: TgoFacebookSDK); begin Assert(Assigned(AImplementation)); inherited Create; FImplementation := AImplementation; end; procedure TgoFacebookSDK.HandleActivityMessage(const Sender: TObject; const M: TMessage); begin if M is TMessageResultNotification then begin TMessageManager.DefaultManager.Unsubscribe(TMessageResultNotification, HandleActivityMessage); FCallbackManager.onActivityResult(TMessageResultNotification(M).RequestCode, TMessageResultNotification(M).ResultCode, TMessageResultNotification(M).Value); end; end; procedure TgoFacebookSDK.TFacebookCallback.onCancel; var LoginResult: TFacebookLoginResult; LoginResultMessage: TFacebookLoginResultMessage; begin LoginResult.Initialize; LoginResult.IsCancelled := True; LoginResultMessage := TFacebookLoginResultMessage.Create(LoginResult); TMessageManager.DefaultManager.SendMessage(Self, LoginResultMessage); end; procedure TgoFacebookSDK.TFacebookCallback.onError(P1: JFacebookException); var LoginResult: TFacebookLoginResult; LoginResultMessage: TFacebookLoginResultMessage; begin LoginResult.Initialize; if P1 <> nil then LoginResult.ErrorDesc := JStringToString(P1.toString); LoginResultMessage := TFacebookLoginResultMessage.Create(LoginResult); TMessageManager.DefaultManager.SendMessage(Self, LoginResultMessage); end; procedure TgoFacebookSDK.TFacebookCallback.onSuccess(P1: JObject); var _LoginResult: JLoginResult; Token: JAccessToken; LoginResult: TFacebookLoginResult; LoginResultMessage: TFacebookLoginResultMessage; begin _LoginResult := TJLoginResult.Wrap((P1 as ILocalObject).GetObjectID); LoginResult.Initialize; LoginResult.Result := True; LoginResult.GrantedPermissions := _JSetToStrings(_LoginResult.getRecentlyGrantedPermissions); Token := _LoginResult.getAccessToken; if Token <> nil then begin LoginResult.Token := JStringToString(Token.GetToken); if Token.getUserId <> nil then LoginResult.UserID := JStringToString(Token.getUserId); end; LoginResultMessage := TFacebookLoginResultMessage.Create(LoginResult); TMessageManager.DefaultManager.SendMessage(Self, LoginResultMessage); end; { TgoFacebookSDK.TFacebookGraphRequestHandler } constructor TgoFacebookSDK.TFacebookGraphRequestHandler.Create( const AImplementation: TgoFacebookSDK); begin Assert(Assigned(AImplementation)); inherited Create; FImplementation := AImplementation; end; procedure TgoFacebookSDK.TFacebookGraphRequestHandler.onCompleted( P1: JGraphResponse); var GraphResult: TFacebookGraphResult; GraphResultMessage: TFacebookGraphResultMessage; begin GraphResult.Initialize; GraphResult.Json := JStringToString(P1.getRawResponse); GraphResult.Result := True; GraphResultMessage := TFacebookGraphResultMessage.Create(GraphResult); TMessageManager.DefaultManager.SendMessage(Self, GraphResultMessage); end; { TgoFacebookSDK } constructor TgoFacebookSDK.Create; begin // TJFacebookSdk.JavaClass.sdkInitialize(TAndroidHelper.Context.getApplicationContext); { no longer needed since Facebook SDK 4.19 } TMessageManager.DefaultManager.SubscribeToMessage(TApplicationEventMessage, ApplicationEventHandler); end; destructor TgoFacebookSDK.Destroy; begin inherited; TMessageManager.DefaultManager.Unsubscribe(TApplicationEventMessage, ApplicationEventHandler); end; procedure TgoFacebookSDK.ApplicationEventHandler(const Sender: TObject; const Msg: TMessage); begin Assert(Assigned(Msg)); Assert(Msg is TApplicationEventMessage); case TApplicationEventMessage(Msg).Value.Event of TApplicationEvent.WillBecomeForeground: TJAppEventsLogger.JavaClass.activateApp(TAndroidHelper.Context.getApplicationContext); TApplicationEvent.EnteredBackground: TJAppEventsLogger.JavaClass.deactivateApp(TAndroidHelper.Context.getApplicationContext); end; end; procedure TgoFacebookSDK.LogInWithReadPermissions(const APermissions: TArray<String>); var ArrayList: JArrayList; Collection: JCollection; begin TMessageManager.DefaultManager.SubscribeToMessage(TMessageResultNotification, HandleActivityMessage); FCallbackManager := TJCallbackManager_Factory.JavaClass.create; FFacebookCallback := TFacebookCallback.Create(Self); FLoginManager := TJLoginManager.Create; FLoginManager.registerCallback(FCallbackManager, FFacebookCallback); ArrayList := _StringsToJArrayList(APermissions); Collection := TJCollection.Wrap((ArrayList as ILocalObject).GetObjectID); FLoginManager.logInWithReadPermissions(TAndroidHelper.Activity, Collection); end; function TgoFacebookSDK.CurrentAccessToken: String; var Token: JAccessToken; begin Token := TJAccessToken.JavaClass.getCurrentAccessToken; if Token = nil then Result := '' else Result := JStringToString(Token.GetToken); end; function TgoFacebookSDK.CurrentUserId: String; var Token: JAccessToken; begin Token := TJAccessToken.JavaClass.getCurrentAccessToken; if Token = nil then Result := '' else Result := JStringToString(Token.getUserId); end; procedure TgoFacebookSDK.GraphPath(const APath: String); var Token: JAccessToken; Bundle: JBundle; Path, Name, Value: JString; GraphRequest: JGraphRequest; Pos1, Pos2: Integer; begin if FFacebookGraphRequestHandler = nil then FFacebookGraphRequestHandler := TFacebookGraphRequestHandler.Create(Self); Token := TJAccessToken.JavaClass.getCurrentAccessToken; if Token <> nil then begin Bundle := TJBundle.JavaClass.init; { parse path into strings } Pos1 := APath.IndexOf('?'); if Pos1 >= 0 then begin Path := StringToJString('/' + APath.Substring(0, Pos1)); Pos2 := APath.IndexOf('=', Pos1); if Pos2 >= 0 then begin Name := StringToJString(APath.Substring(Pos1 + 1, Pos2 - Pos1 - 1)); Value := StringToJString(APath.Substring(Pos2 + 1)); end; end else Path := StringToJString('/' + APath); Bundle.putString(Name, Value); { TODO: handle more complex requests } GraphRequest := TJGraphRequest.JavaClass.init(Token, Path, Bundle, TJHttpMethod.JavaClass.GET, FFacebookGraphRequestHandler); GraphRequest.executeAsync; end; end; initialization FacebookSDK := TgoFacebookSDK.Create; finalization FacebookSDK.Free; end.
{Из последовательности символов, записанной в текстовом файле, построить бинарное дерево поиска. Распечатать все листья дерева} program NumTree; type Elem = char; BTree = ^Uz; Uz = record data: Elem; left, right: BTree; end; procedure AddElem(var root: BTree; el: Elem);//добавление элемента в дерево begin if root=nil then begin new(root); root^.data:=el; root^.left:=nil; root^.right:=nil; end else begin if el>root^.data then AddElem(root^.right,el) else if el<root^.data then AddElem(root^.left,el); end; end; procedure CreatTree(var BinT: BTree; DF: TextFile);//запись элементов в дерево var n: Elem; begin while not Eof(DF) do begin Readln(DF, n); AddElem(BinT,n); end; end; Procedure PrintTree(root:BTree; h: integer);//печать дерева begin if root=nil then exit; PrintTree(Root^.right, h+1); for var i := 1 to h do write(#9); writeln(Root^.data); PrintTree(Root^.left, h+1); end; var BinTreeF: BTree; Fl: TextFile; h: integer; begin BinTreeF:=nil; h:=0; Assign(Fl, 'data.txt'); //связывает файловую переменную с файлом на диске Reset(Fl); //открытие текстового файла для чтения CreatTree(BinTreeF, Fl); writeln('Дерево: '); PrintTree(BinTreeF,h); end.
unit EditRatePriceFrm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DB, DBClient, StdCtrls, DBCtrls, Mask, RzEdit, RzDBEdit, RzButton, RzLabel, ExtCtrls,CommonLIB, RzPanel; type TfrmEditRatePrice = class(TForm) RzPanel1: TRzPanel; RzLabel1: TRzLabel; RzLabel3: TRzLabel; RzLabel2: TRzLabel; btnSave: TRzBitBtn; btnCancel: TRzBitBtn; RzDBEdit17: TRzDBEdit; RzDBEdit1: TRzDBEdit; DBCheckBox1: TDBCheckBox; RzDBEdit2: TRzDBEdit; cdsRatePrice: TClientDataSet; dsRatePrice: TDataSource; RzLabel4: TRzLabel; RzDBEdit3: TRzDBEdit; procedure btnCancelClick(Sender: TObject); procedure btnSaveClick(Sender: TObject); private FAppParameter: TDLLParameter; FRatePriceCode: integer; procedure SetAppParameter(const Value: TDLLParameter); procedure SetRatePriceCode(const Value: integer); { Private declarations } public { Public declarations } property AppParameter : TDLLParameter read FAppParameter write SetAppParameter; property RatePriceCode:integer read FRatePriceCode write SetRatePriceCode; end; var frmEditRatePrice: TfrmEditRatePrice; implementation uses STDLIB, STK_LIB, CdeLIB; {$R *.dfm} procedure TfrmEditRatePrice.btnCancelClick(Sender: TObject); begin Close; end; procedure TfrmEditRatePrice.SetAppParameter(const Value: TDLLParameter); begin FAppParameter := Value; end; procedure TfrmEditRatePrice.SetRatePriceCode(const Value: integer); begin FRatePriceCode := Value; cdsRatePrice.Data:=GetDataSet('select * from ICMTTRA1 where RA1COD='+IntToStr(FRatePriceCode)); end; procedure TfrmEditRatePrice.btnSaveClick(Sender: TObject); var IsNew : boolean; begin if cdsRatePrice.State in [dsinsert] then begin IsNew := true; cdsRatePrice.FieldByName('RA1COD').AsInteger :=getCdeRun('SETTING','RUNNING','RA1COD','CDENM1'); if cdsRatePrice.FieldByName('RA1ACT').IsNull then cdsRatePrice.FieldByName('RA1ACT').AsString:='A'; setEntryUSRDT(cdsRatePrice,FAppParameter.UserID); setSystemCMP(cdsRatePrice,FAppParameter.Company,FAppParameter.Branch,FAppParameter.Department,FAppParameter.Section); end; if cdsRatePrice.State in [dsinsert,dsedit] then setModifyUSRDT(cdsRatePrice,FAppParameter.UserID); if cdsRatePrice.State in [dsedit,dsinsert] then cdsRatePrice.Post; if cdsRatePrice.ChangeCount>0 then begin UpdateDataset(cdsRatePrice,'select * from ICMTTRA1 where RA1COD='+IntToStr(FRatePriceCode)) ; if IsNew then setCdeRun('SETTING','RUNNING','RA1COD','CDENM1'); end; FRatePriceCode:= cdsRatePrice.FieldByName('RA1COD').AsInteger; Close; end; end.
(*----------------------------------------------------------------------------* * Direct3D sample from DirectX 9.0 SDK December 2006 * * Delphi adaptation by Alexey Barkovoy (e-mail: directx@clootie.ru) * * * * Supported compilers: Delphi 5,6,7,9; FreePascal 2.0 * * * * Latest version can be downloaded from: * * http://www.clootie.ru * * http://sourceforge.net/projects/delphi-dx9sdk * *----------------------------------------------------------------------------* * $Id: DepthOfFieldUnit.pas,v 1.16 2007/02/05 22:21:05 clootie Exp $ *----------------------------------------------------------------------------*) //-------------------------------------------------------------------------------------- // File: DepthOfField.cpp // // Starting point for new Direct3D applications // // Copyright (c) Microsoft Corporation. All rights reserved. //-------------------------------------------------------------------------------------- {$I DirectX.inc} unit DepthOfFieldUnit; interface uses Windows, SysUtils, DXTypes, Direct3D9, D3DX9, DXUT, DXUTcore, DXUTenum, DXUTmisc, DXUTgui, DXUTmesh, DXUTSettingsDlg; {.$DEFINE DEBUG_VS} // Uncomment this line to debug vertex shaders {.$DEFINE DEBUG_PS} // Uncomment this line to debug pixel shaders //-------------------------------------------------------------------------------------- // Vertex format //-------------------------------------------------------------------------------------- type TVertex = record pos: TD3DXVector4; clr: DWORD; tex1: TD3DXVector2; tex2: TD3DXVector2; tex3: TD3DXVector2; tex4: TD3DXVector2; tex5: TD3DXVector2; tex6: TD3DXVector2; // static const DWORD FVF; end; const TVertex_FVF = D3DFVF_XYZRHW or D3DFVF_DIFFUSE or D3DFVF_TEX6; //-------------------------------------------------------------------------------------- // Global variables //-------------------------------------------------------------------------------------- var g_pFont: ID3DXFont; // Font for drawing text g_pTextSprite: ID3DXSprite; // Sprite for batching draw text calls g_Camera: CFirstPersonCamera; // A model viewing camera g_bShowHelp: Boolean = True; // If true, it renders the UI control text g_DialogResourceManager: CDXUTDialogResourceManager; // manager for shared resources of dialogs g_SettingsDlg: CD3DSettingsDlg; // Device settings dialog g_HUD: CDXUTDialog; // dialog for standard controls g_SampleUI: CDXUTDialog; // dialog for sample specific controls g_Vertex: array[0..3] of TVertex; g_pFullScreenTexture: IDirect3DTexture9; g_pRenderToSurface: ID3DXRenderToSurface; g_pFullScreenTextureSurf: IDirect3DSurface9; g_pScene1Mesh: ID3DXMesh; g_pScene1MeshTexture: IDirect3DTexture9; g_pScene2Mesh: ID3DXMesh; g_pScene2MeshTexture: IDirect3DTexture9; g_nCurrentScene: Integer; g_pEffect: ID3DXEffect; g_vFocalPlane: TD3DXVector4; g_fChangeTime: Double; g_nShowMode: Integer; g_dwBackgroundColor: DWORD; g_ViewportFB: TD3DViewport9; g_ViewportOffscreen: TD3DViewport9; g_fBlurConst: Single; g_TechniqueIndex: DWORD; g_hFocalPlane: TD3DXHandle; g_hWorld: TD3DXHandle; g_hWorldView: TD3DXHandle; g_hWorldViewProjection: TD3DXHandle; g_hMeshTexture: TD3DXHandle; g_hTechWorldWithBlurFactor: TD3DXHandle; g_hTechShowBlurFactor: TD3DXHandle; g_hTechShowUnmodified: TD3DXHandle; g_hTech: array[0..4] of TD3DXHandle; g_TechniqueNames: array[0..2] of PAnsiChar = ( 'UsePS20ThirteenLookups', 'UsePS20SevenLookups', 'UsePS20SixTexcoords' ); const g_TechniqueCount = High(g_TechniqueNames)+1; //-------------------------------------------------------------------------------------- // UI control IDs //-------------------------------------------------------------------------------------- const IDC_TOGGLEFULLSCREEN = 1; IDC_TOGGLEREF = 3; IDC_CHANGEDEVICE = 4; IDC_CHANGE_SCENE = 5; IDC_CHANGE_TECHNIQUE = 6; IDC_SHOW_BLUR = 7; IDC_CHANGE_BLUR = 8; IDC_CHANGE_FOCAL = 9; IDC_CHANGE_BLUR_STATIC = 10; IDC_SHOW_UNBLURRED = 11; IDC_SHOW_NORMAL = 12; IDC_CHANGE_FOCAL_STATIC = 13; //-------------------------------------------------------------------------------------- // Forward declarations //-------------------------------------------------------------------------------------- function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall; function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall; function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall; function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall; procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall; procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall; function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall; procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall; procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall; procedure OnLostDevice(pUserContext: Pointer); stdcall; procedure OnDestroyDevice(pUserContext: Pointer); stdcall; procedure InitApp; function LoadMesh(pd3dDevice: IDirect3DDevice9; strFileName: PWideChar; out ppMesh: ID3DXMesh): HRESULT; procedure RenderText; procedure SetupQuad(const pBackBufferSurfaceDesc: TD3DSurfaceDesc); function UpdateTechniqueSpecificVariables(const pBackBufferSurfaceDesc: TD3DSurfaceDesc): HRESULT; procedure CreateCustomDXUTobjects; procedure DestroyCustomDXUTobjects; implementation uses StrSafe; //-------------------------------------------------------------------------------------- // Initialize the app //-------------------------------------------------------------------------------------- procedure InitApp; var iY: Integer; sz: array[0..99] of WideChar; begin g_pFont := nil; g_pFullScreenTexture := nil; g_pFullScreenTextureSurf := nil; g_pRenderToSurface := nil; g_pEffect := nil; g_vFocalPlane := D3DXVector4(0.0, 0.0, 1.0, -2.5); g_fChangeTime := 0.0; g_pScene1Mesh := nil; g_pScene1MeshTexture := nil; g_pScene2Mesh := nil; g_pScene2MeshTexture := nil; g_nCurrentScene := 1; g_nShowMode := 0; g_bShowHelp := True; g_dwBackgroundColor := $00003F3F; g_fBlurConst := 4.0; g_TechniqueIndex := 0; g_hFocalPlane := nil; g_hWorld := nil; g_hWorldView := nil; g_hWorldViewProjection := nil; g_hMeshTexture := nil; g_hTechWorldWithBlurFactor := nil; g_hTechShowBlurFactor := nil; g_hTechShowUnmodified := nil; ZeroMemory(@g_hTech, SizeOf(g_hTech)); // Initialize dialogs g_SettingsDlg.Init(g_DialogResourceManager); g_HUD.Init(g_DialogResourceManager); g_SampleUI.Init(g_DialogResourceManager); g_HUD.SetCallback(OnGUIEvent); iY := 10; g_HUD.AddButton(IDC_TOGGLEFULLSCREEN, 'Toggle full screen', 35, iY, 125, 22); Inc(iY, 24); g_HUD.AddButton(IDC_TOGGLEREF, 'Toggle REF (F3)', 35, iY, 125, 22); Inc(iY, 24); g_HUD.AddButton(IDC_CHANGEDEVICE, 'Change device (F2)', 35, iY, 125, 22, VK_F2); g_SampleUI.SetCallback(OnGUIEvent); iY := 10; g_SampleUI.AddButton(IDC_CHANGE_SCENE, 'Change Scene', 35, iY, 125, 22, Ord('P')); Inc(iY, 24); g_SampleUI.AddButton(IDC_CHANGE_TECHNIQUE, 'Change Technique', 35, iY, 125, 22, Ord('N')); Inc(iY, 24); g_SampleUI.AddRadioButton(IDC_SHOW_NORMAL, 1, 'Show Normal', 35, iY, 125, 22, True); Inc(iY, 24); g_SampleUI.AddRadioButton(IDC_SHOW_BLUR, 1, 'Show Blur Factor', 35, iY, 125, 22); Inc(iY, 24); g_SampleUI.AddRadioButton(IDC_SHOW_UNBLURRED, 1, 'Show Unblurred', 35, iY, 125, 22); Inc(iY, 24); StringCchFormat(sz, 100, 'Focal Distance: %0.2f'#0, [-g_vFocalPlane.w]); sz[99] := #0; Inc(iY, 24); g_SampleUI.AddStatic(IDC_CHANGE_FOCAL_STATIC, sz, 35, iY, 125, 22 ); Inc(iY, 24); g_SampleUI.AddSlider(IDC_CHANGE_FOCAL, 50, iY, 100, 22, 0, 100, Trunc(-g_vFocalPlane.w*10.0)); Inc(iY, 24); StringCchFormat(sz, 100, 'Blur Factor: %0.2f'#0, [g_fBlurConst]); sz[99] := #0; Inc(iY, 24); g_SampleUI.AddStatic(IDC_CHANGE_BLUR_STATIC, sz, 35, iY, 125, 22 ); Inc(iY, 24); g_SampleUI.AddSlider(IDC_CHANGE_BLUR, 50, iY, 100, 22, 0, 100, Trunc(g_fBlurConst*10.0)); end; //-------------------------------------------------------------------------------------- // Called during device initialization, this code checks the device for some // minimum set of capabilities, and rejects those that don't pass by returning false. //-------------------------------------------------------------------------------------- function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall; var pD3D: IDirect3D9; begin Result:= False; // Skip backbuffer formats that don't support alpha blending pD3D := DXUTGetD3DObject; if FAILED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType, AdapterFormat, D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, D3DRTYPE_TEXTURE, BackBufferFormat)) then Exit; // Must support pixel shader 2.0 if (pCaps.PixelShaderVersion < D3DPS_VERSION(2, 0)) then Exit; Result:= True; end; //-------------------------------------------------------------------------------------- // This callback function is called immediately before a device is created to allow the // application to modify the device settings. The supplied pDeviceSettings parameter // contains the settings that the framework has selected for the new device, and the // application can make any desired changes directly to this structure. Note however that // DXUT will not correct invalid device settings so care must be taken // to return valid device settings, otherwise IDirect3D9::CreateDevice() will fail. //-------------------------------------------------------------------------------------- {static} var s_bFirstTime: Boolean = True; function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall; begin // If device doesn't support HW T&L or doesn't support 1.1 vertex shaders in HW // then switch to SWVP. if (pCaps.DevCaps and D3DDEVCAPS_HWTRANSFORMANDLIGHT = 0) or (pCaps.VertexShaderVersion < D3DVS_VERSION(1,1)) then pDeviceSettings.BehaviorFlags := D3DCREATE_SOFTWARE_VERTEXPROCESSING; // Debugging vertex shaders requires either REF or software vertex processing // and debugging pixel shaders requires REF. {$IFDEF DEBUG_VS} if (pDeviceSettings.DeviceType <> D3DDEVTYPE_REF) then with pDeviceSettings do begin BehaviorFlags := BehaviorFlags and not D3DCREATE_HARDWARE_VERTEXPROCESSING; BehaviorFlags := BehaviorFlags and not D3DCREATE_PUREDEVICE; BehaviorFlags := BehaviorFlags or D3DCREATE_SOFTWARE_VERTEXPROCESSING; end; {$ENDIF} {$IFDEF DEBUG_PS} pDeviceSettings.DeviceType := D3DDEVTYPE_REF; {$ENDIF} // For the first device created if its a REF device, optionally display a warning dialog box if s_bFirstTime then begin s_bFirstTime := False; if (pDeviceSettings.DeviceType = D3DDEVTYPE_REF) then DXUTDisplaySwitchingToREFWarning; end; Result:= True; end; //-------------------------------------------------------------------------------------- // This callback function will be called immediately after the Direct3D device has been // created, which will happen during application initialization and windowed/full screen // toggles. This is the best location to create D3DPOOL_MANAGED resources since these // resources need to be reloaded whenever the device is destroyed. Resources created // here should be released in the OnDestroyDevice callback. //-------------------------------------------------------------------------------------- function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall; var str: array[0..MAX_PATH-1] of WideChar; dwShaderFlags: DWORD; begin Result:= g_DialogResourceManager.OnCreateDevice(pd3dDevice); if V_Failed(Result) then Exit; Result:= g_SettingsDlg.OnCreateDevice(pd3dDevice); if V_Failed(Result) then Exit; // Initialize the font Result:= D3DXCreateFont(pd3dDevice, 15, 0, FW_BOLD, 1, False, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH or FF_DONTCARE, 'Arial', g_pFont); if V_Failed(Result) then Exit; // Load the meshs Result:= LoadMesh(pd3dDevice, 'tiger\tiger.x', g_pScene1Mesh); if V_Failed(Result) then Exit; Result:= LoadMesh(pd3dDevice, 'misc\sphere.x', g_pScene2Mesh); if V_Failed(Result) then Exit; // Load the mesh textures Result:= DXUTFindDXSDKMediaFile(str, MAX_PATH, 'tiger\tiger.bmp'); if V_Failed(Result) then Exit; Result:= D3DXCreateTextureFromFileW(pd3dDevice, str, g_pScene1MeshTexture); if V_Failed(Result) then Exit; Result:= DXUTFindDXSDKMediaFile(str, MAX_PATH, 'earth\earth.bmp'); if V_Failed(Result) then Exit; Result:= D3DXCreateTextureFromFileW(pd3dDevice, str, g_pScene2MeshTexture); if V_Failed(Result) then Exit; // Define DEBUG_VS and/or DEBUG_PS to debug vertex and/or pixel shaders with the // shader debugger. Debugging vertex shaders requires either REF or software vertex // processing, and debugging pixel shaders requires REF. The // D3DXSHADER_FORCE_*_SOFTWARE_NOOPT flag improves the debug experience in the // shader debugger. It enables source level debugging, prevents instruction // reordering, prevents dead code elimination, and forces the compiler to compile // against the next higher available software target, which ensures that the // unoptimized shaders do not exceed the shader model limitations. Setting these // flags will cause slower rendering since the shaders will be unoptimized and // forced into software. See the DirectX documentation for more information about // using the shader debugger. dwShaderFlags := D3DXFX_NOT_CLONEABLE; {$IFDEF DEBUG} // Set the D3DXSHADER_DEBUG flag to embed debug information in the shaders. // Setting this flag improves the shader debugging experience, but still allows // the shaders to be optimized and to run exactly the way they will run in // the release configuration of this program. dwShaderFlags := dwShaderFlags or D3DXSHADER_DEBUG; {$ENDIF} {$IFDEF DEBUG_VS} dwShaderFlags := dwShaderFlags or D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT; {$ENDIF} {$IFDEF DEBUG_PS} dwShaderFlags := dwShaderFlags or D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT; {$ENDIF} // Read the D3DX effect file // If this fails, there should be debug output as to // they the .fx file failed to compile Result:= DXUTFindDXSDKMediaFile(str, MAX_PATH, 'DepthOfField.fx'); if V_Failed(Result) then Exit; Result:= D3DXCreateEffectFromFileW(pd3dDevice, str, nil, nil, dwShaderFlags, nil, g_pEffect, nil); if V_Failed(Result) then Exit; Result:= S_OK; end; //-------------------------------------------------------------------------------------- // This function loads the mesh and ensures the mesh has normals; it also optimizes the // mesh for the graphics card's vertex cache, which improves performance by organizing // the internal triangle list for less cache misses. //-------------------------------------------------------------------------------------- function LoadMesh(pd3dDevice: IDirect3DDevice9; strFileName: PWideChar; out ppMesh: ID3DXMesh): HRESULT; var pMesh: ID3DXMesh; str: array[0..MAX_PATH-1] of WideChar; rgdwAdjacency: PDWORD; pTempMesh: ID3DXMesh; begin // Load the mesh with D3DX and get back a ID3DXMesh*. For this // sample we'll ignore the X file's embedded materials since we know // exactly the model we're loading. See the mesh samples such as // "OptimizedMesh" for a more generic mesh loading example. Result := DXUTFindDXSDKMediaFile(str, MAX_PATH, strFileName); if V_Failed(Result) then Exit; Result := D3DXLoadMeshFromXW(str, D3DXMESH_MANAGED, pd3dDevice, nil, nil, nil, nil, pMesh); if V_Failed(Result) then Exit; // rgdwAdjacency := nil; // Make sure there are normals which are required for lighting if (pMesh.GetFVF and D3DFVF_NORMAL = 0) then begin Result := V(pMesh.CloneMeshFVF(pMesh.GetOptions, pMesh.GetFVF or D3DFVF_NORMAL, pd3dDevice, pTempMesh)); if Failed(Result) then Exit; Result := V(D3DXComputeNormals(pTempMesh, nil)); if Failed(Result) then Exit; SAFE_RELEASE(pMesh); pMesh := pTempMesh; end; // Optimize the mesh for this graphics card's vertex cache // so when rendering the mesh's triangle list the vertices will // cache hit more often so it won't have to re-execute the vertex shader // on those vertices so it will improve perf. try GetMem(rgdwAdjacency, SizeOf(DWORD)*pMesh.GetNumFaces*3); V(pMesh.GenerateAdjacency(1e-6,rgdwAdjacency)); V(pMesh.OptimizeInplace(D3DXMESHOPT_VERTEXCACHE, rgdwAdjacency, nil, nil, nil)); FreeMem(rgdwAdjacency); ppMesh := pMesh; Result:= S_OK; except on EOutOfMemory do Result:= E_OUTOFMEMORY; end; end; //-------------------------------------------------------------------------------------- // This callback function will be called immediately after the Direct3D device has been // reset, which will happen after a lost device scenario. This is the best location to // create D3DPOOL_DEFAULT resources since these resources need to be reloaded whenever // the device is lost. Resources created here should be released in the OnLostDevice // callback. //-------------------------------------------------------------------------------------- function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall; var fAspectRatio: Single; vecEye: TD3DXVector3; vecAt: TD3DXVector3; desc: TD3DSurfaceDesc; colorWhite: TD3DXColor; colorBlack: TD3DXColor; colorAmbient: TD3DXColor; i: Integer; OriginalTechnique: DWORD; hTech: TD3DXHandle; begin Result:= g_DialogResourceManager.OnResetDevice; if V_Failed(Result) then Exit; Result:= g_SettingsDlg.OnResetDevice; if V_Failed(Result) then Exit; Result:= S_OK; if (g_pFont <> nil) then Result := g_pFont.OnResetDevice; if V_Failed(Result) then Exit; if (g_pEffect <> nil) then Result:= g_pEffect.OnResetDevice; if V_Failed(Result) then Exit; // Setup the camera with view & projection matrix vecEye := D3DXVector3(1.3, 1.1, -3.3); vecAt := D3DXVector3(0.75, 0.9, -2.5); g_Camera.SetViewParams( vecEye, vecAt); fAspectRatio := pBackBufferSurfaceDesc.Width / pBackBufferSurfaceDesc.Height; g_Camera.SetProjParams(D3DXToRadian(60.0), fAspectRatio, 0.5, 100.0); pd3dDevice.GetViewport(g_ViewportFB); // Backbuffer viewport is identical to frontbuffer, except starting at 0, 0 g_ViewportOffscreen := g_ViewportFB; g_ViewportOffscreen.X := 0; g_ViewportOffscreen.Y := 0; // Create fullscreen renders target texture Result := D3DXCreateTexture(pd3dDevice, pBackBufferSurfaceDesc.Width, pBackBufferSurfaceDesc.Height, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, g_pFullScreenTexture); if FAILED(Result) then begin // Fallback to a non-RT texture Result:= D3DXCreateTexture(pd3dDevice, pBackBufferSurfaceDesc.Width, pBackBufferSurfaceDesc.Height, 1, 0, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, g_pFullScreenTexture); if V_Failed(Result) then Exit; end; g_pFullScreenTexture.GetSurfaceLevel(0, g_pFullScreenTextureSurf); g_pFullScreenTextureSurf.GetDesc(desc); // Create a ID3DXRenderToSurface to help render to a texture on cards // that don't support render targets Result:= D3DXCreateRenderToSurface(pd3dDevice, desc.Width, desc.Height, desc.Format, True, D3DFMT_D16, g_pRenderToSurface); if V_Failed(Result) then Exit; // clear the surface alpha to 0 so that it does not bleed into a "blurry" background // this is possible because of the avoidance of blurring in a non-blurred texel if SUCCEEDED(g_pRenderToSurface.BeginScene(g_pFullScreenTextureSurf, nil)) then begin pd3dDevice.Clear(0, nil, D3DCLEAR_TARGET, $00, 1.0, 0); g_pRenderToSurface.EndScene(0); end; colorWhite := D3DXColor(1.0, 1.0, 1.0, 1.0); colorBlack := D3DXCOLOR(0.0, 0.0, 0.0, 1.0); colorAmbient := D3DXColor(0.25, 0.25, 0.25, 1.0); // Get D3DXHANDLEs to the parameters/techniques that are set every frame so // D3DX doesn't spend time doing string compares. Doing this likely won't affect // the perf of this simple sample but it should be done in complex engine. g_hFocalPlane := g_pEffect.GetParameterByName(nil, 'vFocalPlane'); g_hWorld := g_pEffect.GetParameterByName(nil, 'mWorld'); g_hWorldView := g_pEffect.GetParameterByName(nil, 'mWorldView'); g_hWorldViewProjection := g_pEffect.GetParameterByName(nil, 'mWorldViewProjection'); g_hMeshTexture := g_pEffect.GetParameterByName(nil, 'MeshTexture'); g_hTechWorldWithBlurFactor := g_pEffect.GetTechniqueByName('WorldWithBlurFactor'); g_hTechShowBlurFactor := g_pEffect.GetTechniqueByName('ShowBlurFactor'); g_hTechShowUnmodified := g_pEffect.GetTechniqueByName('ShowUnmodified'); for i := 0 to g_TechniqueCount do g_hTech[i] := g_pEffect.GetTechniqueByName(g_TechniqueNames[i]); // Set the vars in the effect that doesn't change each frame Result:= g_pEffect.SetVector('MaterialAmbientColor', PD3DXVector4(@colorAmbient)^); if V_Failed(Result) then Exit; Result:= g_pEffect.SetVector('MaterialDiffuseColor', PD3DXVector4(@colorWhite)^); if V_Failed(Result) then Exit; Result:= g_pEffect.SetTexture('RenderTargetTexture', g_pFullScreenTexture); if V_Failed(Result) then Exit; // Check if the current technique is valid for the new device/settings // Start from the current technique, increment until we find one we can use. OriginalTechnique := g_TechniqueIndex; repeat hTech := g_pEffect.GetTechniqueByName(g_TechniqueNames[g_TechniqueIndex]); if SUCCEEDED(g_pEffect.ValidateTechnique(hTech)) then Break; Inc(g_TechniqueIndex); if (g_TechniqueIndex = g_TechniqueCount) then g_TechniqueIndex := 0; until (OriginalTechnique = g_TechniqueIndex); // while( OriginalTechnique <> g_TechniqueIndex); Result:= UpdateTechniqueSpecificVariables(pBackBufferSurfaceDesc); if V_Failed(Result) then Exit; g_HUD.SetLocation(pBackBufferSurfaceDesc.Width-170, 0); g_HUD.SetSize(170, 170); g_SampleUI.SetLocation(pBackBufferSurfaceDesc.Width-170, pBackBufferSurfaceDesc.Height-300); g_SampleUI.SetSize(170, 250); Result:= S_OK; end; //-------------------------------------------------------------------------------------- // Certain parameters need to be specified for specific techniques //-------------------------------------------------------------------------------------- function UpdateTechniqueSpecificVariables(const pBackBufferSurfaceDesc: TD3DSurfaceDesc): HRESULT; var strInputArrayName, strOutputArrayName: PChar; nNumKernelEntries: Integer; hAnnotation: TD3DXHandle; hTech: TD3DXHandle; aKernel, aKernel2: PD3DXVector2; desc: TD3DSurfaceDesc; fWidthMod: Single; fHeightMod: Single; iEntry: Integer; begin // Create the post-process quad and set the texcoords based on the blur factor SetupQuad(pBackBufferSurfaceDesc); // Get the handle to the current technique hTech := g_pEffect.GetTechniqueByName(g_TechniqueNames[g_TechniqueIndex]); if(hTech = nil) then begin Result := S_FALSE; // This will happen if the technique doesn't have this annotation Exit; end; // Get the value of the annotation int named "NumKernelEntries" inside the technique hAnnotation := g_pEffect.GetAnnotationByName(hTech, 'NumKernelEntries'); if (hAnnotation = nil) then // This will happen if the technique doesn't have this annotation begin Result:= S_FALSE; Exit; end; Result:= g_pEffect.GetInt(hAnnotation, nNumKernelEntries); if V_Failed(Result) then Exit; // Get the value of the annotation string named "KernelInputArray" inside the technique hAnnotation := g_pEffect.GetAnnotationByName(hTech, 'KernelInputArray'); if (hAnnotation = nil) then // This will happen if the technique doesn't have this annotation begin Result:= S_FALSE; Exit; end; Result:= g_pEffect.GetString(hAnnotation, strInputArrayName); if V_Failed(Result) then Exit; // Get the value of the annotation string named "KernelOutputArray" inside the technique hAnnotation := g_pEffect.GetAnnotationByName(hTech, 'KernelOutputArray'); if (hAnnotation = nil) then // This will happen if the technique doesn't have this annotation begin Result:= S_FALSE; Exit; end; Result := g_pEffect.GetString(hAnnotation, strOutputArrayName); if V_Failed(Result) then Exit; // Create a array to store the input array try GetMem(aKernel, SizeOf(TD3DXVector2)*nNumKernelEntries); except Result:= E_OUTOFMEMORY; Exit; end; // Get the input array Result:= g_pEffect.GetValue(TD3DXHandle(strInputArrayName), aKernel, SizeOf(TD3DXVector2)*nNumKernelEntries); if V_Failed(Result) then Exit; // Get the size of the texture g_pFullScreenTextureSurf.GetDesc(desc); // Calculate the scale factor to convert the input array to screen space fWidthMod := g_fBlurConst / desc.Width ; fHeightMod := g_fBlurConst / desc.Height; // Scale the effect's kernel from pixel space to tex coord space // In pixel space 1 unit = one pixel and in tex coord 1 unit = width/height of texture aKernel2:= aKernel; for iEntry := 0 to nNumKernelEntries - 1 do begin aKernel2.x := aKernel.x * fWidthMod; aKernel2.y := aKernel.y * fHeightMod; Inc(aKernel2); end; // Pass the updated array values to the effect file Result:= g_pEffect.SetValue(TD3DXHandle(strOutputArrayName), aKernel, SizeOf(TD3DXVector2)*nNumKernelEntries); if V_Failed(Result) then Exit; FreeMem(aKernel); Result:= S_OK; end; //-------------------------------------------------------------------------------------- // Sets up a quad to render the fullscreen render target to the backbuffer // so it can run a fullscreen pixel shader pass that blurs based // on the depth of the objects. It set the texcoords based on the blur factor //-------------------------------------------------------------------------------------- procedure SetupQuad(const pBackBufferSurfaceDesc: TD3DSurfaceDesc); var desc: TD3DSurfaceDesc; fWidth5, fHeight5, fHalf, fOffOne, fOffTwo, fTexWidth1, fTexHeight1, fWidthMod, fHeightMod : Single; begin g_pFullScreenTextureSurf.GetDesc(desc); fWidth5 := pBackBufferSurfaceDesc.Width - 0.5; fHeight5 := pBackBufferSurfaceDesc.Height - 0.5; fHalf := g_fBlurConst; fOffOne := fHalf * 0.5; fOffTwo := fOffOne * sqrt(3.0); fTexWidth1 := pBackBufferSurfaceDesc.Width / desc.Width; fTexHeight1 := pBackBufferSurfaceDesc.Height / desc.Height; fWidthMod := 1.0 / desc.Width ; fHeightMod := 1.0 / desc.Height; // Create vertex buffer. // g_Vertex[0].tex1 == full texture coverage // g_Vertex[0].tex2 == full texture coverage, but shifted y by -fHalf*fHeightMod // g_Vertex[0].tex3 == full texture coverage, but shifted x by -fOffTwo*fWidthMod & y by -fOffOne*fHeightMod // g_Vertex[0].tex4 == full texture coverage, but shifted x by +fOffTwo*fWidthMod & y by -fOffOne*fHeightMod // g_Vertex[0].tex5 == full texture coverage, but shifted x by -fOffTwo*fWidthMod & y by +fOffOne*fHeightMod // g_Vertex[0].tex6 == full texture coverage, but shifted x by +fOffTwo*fWidthMod & y by +fOffOne*fHeightMod g_Vertex[0].pos := D3DXVector4(fWidth5, -0.5, 0.0, 1.0); g_Vertex[0].clr := D3DXColorToDWord(D3DXColor(0.5, 0.5, 0.5, 0.66666)); g_Vertex[0].tex1 := D3DXVector2(fTexWidth1, 0.0); g_Vertex[0].tex2 := D3DXVector2(fTexWidth1, 0.0 - fHalf*fHeightMod); g_Vertex[0].tex3 := D3DXVector2(fTexWidth1 - fOffTwo*fWidthMod, 0.0 - fOffOne*fHeightMod); g_Vertex[0].tex4 := D3DXVector2(fTexWidth1 + fOffTwo*fWidthMod, 0.0 - fOffOne*fHeightMod); g_Vertex[0].tex5 := D3DXVector2(fTexWidth1 - fOffTwo*fWidthMod, 0.0 + fOffOne*fHeightMod); g_Vertex[0].tex6 := D3DXVector2(fTexWidth1 + fOffTwo*fWidthMod, 0.0 + fOffOne*fHeightMod); g_Vertex[1].pos := D3DXVector4(fWidth5, fHeight5, 0.0, 1.0); g_Vertex[1].clr := D3DXColorToDWord(D3DXColor(0.5, 0.5, 0.5, 0.66666)); g_Vertex[1].tex1 := D3DXVector2(fTexWidth1, fTexHeight1); g_Vertex[1].tex2 := D3DXVector2(fTexWidth1, fTexHeight1 - fHalf*fHeightMod); g_Vertex[1].tex3 := D3DXVector2(fTexWidth1 - fOffTwo*fWidthMod, fTexHeight1 - fOffOne*fHeightMod); g_Vertex[1].tex4 := D3DXVector2(fTexWidth1 + fOffTwo*fWidthMod, fTexHeight1 - fOffOne*fHeightMod); g_Vertex[1].tex5 := D3DXVector2(fTexWidth1 - fOffTwo*fWidthMod, fTexHeight1 + fOffOne*fHeightMod); g_Vertex[1].tex6 := D3DXVector2(fTexWidth1 + fOffTwo*fWidthMod, fTexHeight1 + fOffOne*fHeightMod); g_Vertex[2].pos := D3DXVector4(-0.5, -0.5, 0.0, 1.0); g_Vertex[2].clr := D3DXColorToDWord(D3DXColor(0.5, 0.5, 0.5, 0.66666)); g_Vertex[2].tex1 := D3DXVector2(0.0, 0.0); g_Vertex[2].tex2 := D3DXVector2(0.0, 0.0 - fHalf*fHeightMod); g_Vertex[2].tex3 := D3DXVector2(0.0 - fOffTwo*fWidthMod, 0.0 - fOffOne*fHeightMod); g_Vertex[2].tex4 := D3DXVector2(0.0 + fOffTwo*fWidthMod, 0.0 - fOffOne*fHeightMod); g_Vertex[2].tex5 := D3DXVector2(0.0 - fOffTwo*fWidthMod, 0.0 + fOffOne*fHeightMod); g_Vertex[2].tex6 := D3DXVector2(0.0 + fOffTwo*fWidthMod, 0.0 + fOffOne*fHeightMod); g_Vertex[3].pos := D3DXVector4(-0.5, fHeight5, 0.0, 1.0); g_Vertex[3].clr := D3DXColorToDWord(D3DXColor(0.5, 0.5, 0.5, 0.66666)); g_Vertex[3].tex1 := D3DXVector2(0.0, fTexHeight1); g_Vertex[3].tex2 := D3DXVector2(0.0, fTexHeight1 - fHalf*fHeightMod); g_Vertex[3].tex3 := D3DXVector2(0.0 - fOffTwo*fWidthMod, fTexHeight1 - fOffOne*fHeightMod); g_Vertex[3].tex4 := D3DXVector2(0.0 + fOffTwo*fWidthMod, fTexHeight1 - fOffOne*fHeightMod); g_Vertex[3].tex5 := D3DXVector2(0.0 + fOffTwo*fWidthMod, fTexHeight1 + fOffOne*fHeightMod); g_Vertex[3].tex6 := D3DXVector2(0.0 - fOffTwo*fWidthMod, fTexHeight1 + fOffOne*fHeightMod); end; //-------------------------------------------------------------------------------------- // This callback function will be called once at the beginning of every frame. This is the // best location for your application to handle updates to the scene, but is not // intended to contain actual rendering calls, which should instead be placed in the // OnFrameRender callback. //-------------------------------------------------------------------------------------- procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall; begin // Update the camera's position based on user input g_Camera.FrameMove(fElapsedTime); end; //-------------------------------------------------------------------------------------- // This callback function will be called at the end of every frame to perform all the // rendering calls for the scene, and it will also be called if the window needs to be // repainted. After this function has returned, DXUT will call // IDirect3DDevice9::Present to display the contents of the next buffer in the swap chain //-------------------------------------------------------------------------------------- procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall; var iPass, cPasses: Integer; matWorld: TD3DXMatrixA16; matView: TD3DXMatrixA16; matProj: TD3DXMatrixA16; matViewProj: TD3DXMatrixA16; pSceneMesh: ID3DXMesh; nNumObjectsInScene: Integer; mScene2WorldPos: array[0..2] of TD3DXVector3; iObject: Integer; matRot, matPos: TD3DXMatrixA16; matWorldViewProj, matWorldView: TD3DXMatrixA16; begin // If the settings dialog is being shown, then // render it instead of rendering the app's scene if g_SettingsDlg.Active then begin g_SettingsDlg.OnRender(fElapsedTime); Exit; end; // First render the world on the rendertarget g_pFullScreenTexture. if SUCCEEDED(g_pRenderToSurface.BeginScene(g_pFullScreenTextureSurf, @g_ViewportOffscreen)) then begin V(pd3dDevice.Clear(0, nil, D3DCLEAR_TARGET or D3DCLEAR_ZBUFFER, g_dwBackgroundColor, 1.0, 0)); // Get the view & projection matrix from camera matView := g_Camera.GetViewMatrix^; matProj := g_Camera.GetProjMatrix^; D3DXMatrixMultiply(matViewProj, matView, matProj); // Update focal plane g_pEffect.SetVector(g_hFocalPlane, g_vFocalPlane); // Set world render technique V(g_pEffect.SetTechnique(g_hTechWorldWithBlurFactor)); // Set the mesh texture if (g_nCurrentScene = 1) then begin V(g_pEffect.SetTexture(g_hMeshTexture, g_pScene1MeshTexture)); pSceneMesh := g_pScene1Mesh; nNumObjectsInScene := 25; end else begin V(g_pEffect.SetTexture(g_hMeshTexture, g_pScene2MeshTexture)); pSceneMesh := g_pScene2Mesh; nNumObjectsInScene := 3; end; mScene2WorldPos[0]:= D3DXVector3(-0.5,-0.5,-0.5); mScene2WorldPos[1]:= D3DXVector3(1.0, 1.0, 2.0); mScene2WorldPos[2]:= D3DXVector3(3.0, 3.0, 5.0); for iObject:= 0 to nNumObjectsInScene - 1 do begin // setup the world matrix for the current world if (g_nCurrentScene = 1) then begin D3DXMatrixTranslation(matWorld, -(iObject mod 5)*1.0, 0.0, (iObject / 5)*3.0); end else begin D3DXMatrixRotationY(matRot, fTime * 0.66666); D3DXMatrixTranslation(matPos, mScene2WorldPos[iObject].x, mScene2WorldPos[iObject].y, mScene2WorldPos[iObject].z); D3DXMatrixMultiply(matWorld, matRot, matPos); end; // Update effect vars D3DXMatrixMultiply(matWorldViewProj, matWorld, matViewProj); D3DXMatrixMultiply(matWorldView, matWorld, matView); V(g_pEffect.SetMatrix(g_hWorld, matWorld)); V(g_pEffect.SetMatrix(g_hWorldView, matWorldView)); V(g_pEffect.SetMatrix(g_hWorldViewProjection, matWorldViewProj)); // Draw the mesh on the rendertarget V(g_pEffect._Begin(@cPasses, 0)); for iPass := 0 to cPasses - 1 do begin V(g_pEffect.BeginPass(iPass)); V(pSceneMesh.DrawSubset(0)); V(g_pEffect.EndPass); end; V(g_pEffect._End); end; V(g_pRenderToSurface.EndScene(0)); end; // Clear the backbuffer V(pd3dDevice.Clear(0, nil, D3DCLEAR_TARGET, $00000000, 1.0, 0)); // Begin the scene, rendering to the backbuffer if SUCCEEDED(pd3dDevice.BeginScene) then begin pd3dDevice.SetViewport(g_ViewportFB); // Set the post process technique case g_nShowMode of 0: V(g_pEffect.SetTechnique(g_hTech[g_TechniqueIndex])); 1: V(g_pEffect.SetTechnique(g_hTechShowBlurFactor)); 2: V(g_pEffect.SetTechnique(g_hTechShowUnmodified)); end; // Render the fullscreen quad on to the backbuffer V(g_pEffect._Begin(@cPasses, 0)); for iPass := 0 to cPasses - 1 do begin V(g_pEffect.BeginPass(iPass)); V(pd3dDevice.SetFVF(TVertex_FVF)); V(pd3dDevice.DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, g_Vertex, SizeOf(TVertex))); V(g_pEffect.EndPass); end; V(g_pEffect._End); V(g_HUD.OnRender(fElapsedTime)); V(g_SampleUI.OnRender(fElapsedTime)); // Render the text RenderText; // End the scene. pd3dDevice.EndScene; end; end; //-------------------------------------------------------------------------------------- // Render the help and statistics text. This function uses the ID3DXFont interface for // efficient text rendering. //-------------------------------------------------------------------------------------- procedure RenderText; var txtHelper: CDXUTTextHelper; pd3dsdBackBuffer: PD3DSurfaceDesc; begin // The helper object simply helps keep track of text position, and color // and then it calls pFont->DrawText( g_pSprite, strMsg, -1, &rc, DT_NOCLIP, g_clr ); // If NULL is passed in as the sprite object, then it will work however the // pFont->DrawText() will not be batched together. Batching calls will improves performance. txtHelper := CDXUTTextHelper.Create(g_pFont, g_pTextSprite, 15); // Output statistics txtHelper._Begin; txtHelper.SetInsertionPos(5, 5); txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 0.0, 1.0)); txtHelper.DrawTextLine(DXUTGetFrameStats); txtHelper.DrawTextLine(DXUTGetDeviceStats); txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 1.0, 1.0)); case g_nShowMode of 0: txtHelper.DrawFormattedTextLine('Technique: %S', [g_TechniqueNames[g_TechniqueIndex]]); 1: txtHelper.DrawTextLine('Technique: ShowBlurFactor'); 2: txtHelper.DrawTextLine('Technique: ShowUnmodified'); end; txtHelper.DrawFormattedTextLine('Focal Plane: (%0.1f,%0.1f,%0.1f,%0.1f)', [g_vFocalPlane.x, g_vFocalPlane.y, g_vFocalPlane.z, g_vFocalPlane.w]); // Draw help if g_bShowHelp then begin pd3dsdBackBuffer := DXUTGetBackBufferSurfaceDesc; txtHelper.SetInsertionPos(2, pd3dsdBackBuffer.Height-15*6); txtHelper.SetForegroundColor(D3DXColor(1.0, 0.75, 0.0, 1.0)); txtHelper.DrawTextLine('Controls (F1 to hide):'); txtHelper.SetInsertionPos(20, pd3dsdBackBuffer.Height-15*5); txtHelper.DrawTextLine('Look: Left drag mouse'#10+ 'Move: A,W,S,D or Arrow Keys'#10+ 'Move up/down: Q,E or PgUp,PgDn'#10+ 'Reset camera: Home'#10); end else begin txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 1.0, 1.0)); txtHelper.DrawTextLine('Press F1 for help'); end; txtHelper._End; txtHelper.Free; end; //-------------------------------------------------------------------------------------- // Before handling window messages, the sample framework passes incoming windows // messages to the application through this callback function. If the application sets // *pbNoFurtherProcessing to TRUE, then the sample framework will not process this message. //-------------------------------------------------------------------------------------- function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall; begin Result:= 0; // Always allow dialog resource manager calls to handle global messages // so GUI state is updated correctly pbNoFurtherProcessing := g_DialogResourceManager.MsgProc(hWnd, uMsg, wParam, lParam); if pbNoFurtherProcessing then Exit; if g_SettingsDlg.IsActive then begin g_SettingsDlg.MsgProc(hWnd, uMsg, wParam, lParam); Exit; end; // Give the dialogs a chance to handle the message first pbNoFurtherProcessing := g_HUD.MsgProc(hWnd, uMsg, wParam, lParam); if pbNoFurtherProcessing then Exit; pbNoFurtherProcessing := g_SampleUI.MsgProc(hWnd, uMsg, wParam, lParam); if pbNoFurtherProcessing then Exit; // Pass all remaining windows messages to camera so it can respond to user input g_Camera.HandleMessages(hWnd, uMsg, wParam, lParam); end; //-------------------------------------------------------------------------------------- // As a convenience, DXUT inspects the incoming windows messages for // keystroke messages and decodes the message parameters to pass relevant keyboard // messages to the application. The framework does not remove the underlying keystroke // messages, which are still passed to the application's MsgProc callback. //-------------------------------------------------------------------------------------- procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall; begin if bKeyDown then begin case nChar of VK_F1: g_bShowHelp := not g_bShowHelp; end; end; end; //-------------------------------------------------------------------------------------- // Handles the GUI events //-------------------------------------------------------------------------------------- procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall; var OriginalTechnique: DWORD; hTech: TD3DXHandle; sz: array[0..99] of WideChar; begin case nControlID of IDC_TOGGLEFULLSCREEN: DXUTToggleFullScreen; IDC_TOGGLEREF: DXUTToggleREF; IDC_CHANGEDEVICE: with g_SettingsDlg do Active := not Active; IDC_CHANGE_TECHNIQUE: begin OriginalTechnique := g_TechniqueIndex; repeat Inc(g_TechniqueIndex); if (g_TechniqueIndex = g_TechniqueCount) then g_TechniqueIndex := 0; hTech := g_pEffect.GetTechniqueByName(g_TechniqueNames[g_TechniqueIndex]); if SUCCEEDED(g_pEffect.ValidateTechnique(hTech)) then Break; until (OriginalTechnique = g_TechniqueIndex); UpdateTechniqueSpecificVariables(DXUTGetBackBufferSurfaceDesc^); end; IDC_CHANGE_SCENE: begin g_nCurrentScene := g_nCurrentScene mod 2; Inc(g_nCurrentScene); case g_nCurrentScene of 1: begin // D3DXVECTOR3 vecEye(0.75f, 0.8, -2.3); // D3DXVECTOR3 vecAt (0.2f, 0.75, -1.5); g_Camera.SetViewParams(D3DXVector3(0.75, 0.8, -2.3), D3DXVector3(0.2, 0.75, -1.5)); end; 2: begin // D3DXVECTOR3 vecEye(0.0, 0.0, -3.0); // D3DXVECTOR3 vecAt (0.0, 0.0, 0.0); g_Camera.SetViewParams(D3DXVector3(0.0, 0.0, -3.0), D3DXVector3(0.0, 0.0, 0.0)); end; end; end; IDC_CHANGE_FOCAL: begin g_vFocalPlane.w := -g_SampleUI.GetSlider(IDC_CHANGE_FOCAL).Value / 10.0; StringCchFormat(sz, 100, 'Focal Distance: %0.2f', [-g_vFocalPlane.w]); g_SampleUI.GetStatic(IDC_CHANGE_FOCAL_STATIC).Text := sz; UpdateTechniqueSpecificVariables(DXUTGetBackBufferSurfaceDesc^); end; IDC_SHOW_NORMAL: g_nShowMode := 0; IDC_SHOW_BLUR: g_nShowMode := 1; IDC_SHOW_UNBLURRED: g_nShowMode := 2; IDC_CHANGE_BLUR: begin g_fBlurConst := g_SampleUI.GetSlider(IDC_CHANGE_BLUR).Value / 10.0; StringCchFormat(sz, 100, 'Blur Factor: %0.2f', [g_fBlurConst]); g_SampleUI.GetStatic(IDC_CHANGE_BLUR_STATIC).Text := sz; UpdateTechniqueSpecificVariables(DXUTGetBackBufferSurfaceDesc^); end; end; end; //-------------------------------------------------------------------------------------- // This callback function will be called immediately after the Direct3D device has // entered a lost state and before IDirect3DDevice9::Reset is called. Resources created // in the OnResetDevice callback should be released here, which generally includes all // D3DPOOL_DEFAULT resources. See the "Lost Devices" section of the documentation for // information about lost devices. //-------------------------------------------------------------------------------------- procedure OnLostDevice(pUserContext: Pointer); stdcall; begin g_DialogResourceManager.OnLostDevice; g_SettingsDlg.OnLostDevice; if (g_pFont <> nil) then g_pFont.OnLostDevice; if (g_pEffect <> nil) then g_pEffect.OnLostDevice; SAFE_RELEASE(g_pTextSprite); SAFE_RELEASE(g_pFullScreenTextureSurf); SAFE_RELEASE(g_pFullScreenTexture); SAFE_RELEASE(g_pRenderToSurface); end; //-------------------------------------------------------------------------------------- // This callback function will be called immediately after the Direct3D device has // been destroyed, which generally happens as a result of application termination or // windowed/full screen toggles. Resources created in the OnCreateDevice callback // should be released here, which generally includes all D3DPOOL_MANAGED resources. //-------------------------------------------------------------------------------------- procedure OnDestroyDevice(pUserContext: Pointer); stdcall; begin g_DialogResourceManager.OnDestroyDevice; g_SettingsDlg.OnDestroyDevice; SAFE_RELEASE(g_pEffect); SAFE_RELEASE(g_pFont); SAFE_RELEASE(g_pFullScreenTextureSurf); SAFE_RELEASE(g_pFullScreenTexture); SAFE_RELEASE(g_pRenderToSurface); SAFE_RELEASE(g_pScene1Mesh); SAFE_RELEASE(g_pScene1MeshTexture); SAFE_RELEASE(g_pScene2Mesh); SAFE_RELEASE(g_pScene2MeshTexture); end; procedure CreateCustomDXUTobjects; begin g_DialogResourceManager:= CDXUTDialogResourceManager.Create; // manager for shared resources of dialogs g_SettingsDlg:= CD3DSettingsDlg.Create; // Device settings dialog g_Camera:= CFirstPersonCamera.Create; g_HUD:= CDXUTDialog.Create; g_SampleUI:= CDXUTDialog.Create; end; procedure DestroyCustomDXUTobjects; begin FreeAndNil(g_DialogResourceManager); FreeAndNil(g_SettingsDlg); FreeAndNil(g_Camera); FreeAndNil(g_HUD); FreeAndNil(g_SampleUI); end; end.
unit Mt3dmsRctWriterUnit; interface uses CustomModflowWriterUnit, ModflowPackageSelectionUnit, Forms, PhastModelUnit; type TMt3dmsRctWriter = class(TCustomModflowWriter) private ISOTHM: Integer; IREACT: Integer; IGETSC: Integer; procedure WriteDataSet1; procedure WriteDataSet2A; procedure WriteDataSet2B; procedure WriteDataSet2C; procedure WriteDataSet3; procedure WriteDataSet4; procedure WriteDataSet5; procedure WriteDataSet6; protected class function Extension: string; override; public Constructor Create(AModel: TCustomModel; EvaluationType: TEvaluationType); override; procedure WriteFile(const AFileName: string); end; implementation uses frmProgressUnit, ModflowUnitNumbers, DataSetUnit, SysUtils, Mt3dmsChemSpeciesUnit, GoPhastTypes; resourcestring StrSInTheMT3DMSRCT = '%s in the MT3DMS RCT package'; StrRHOBLayerD = 'Data Set 2A: RHOB Layer: %d'; StrPRSITY2LayerD = 'Data Set 2B: PRSITY2 Layer: %d'; StrWritingMT3DMSRCTP = 'Writing MT3DMS RCT Package input.'; // StrWritingDataSet1 = ' Writing Data Set 1.'; StrWritingDataSet2A = ' Writing Data Set 2A.'; StrWritingDataSet2B = ' Writing Data Set 2B.'; StrWritingDataSet2C = ' Writing Data Set 2C.'; // StrWritingDataSet3 = ' Writing Data Set 3.'; // StrWritingDataSet4 = ' Writing Data Set 4.'; // StrWritingDataSet5 = ' Writing Data Set 5.'; // StrWritingDataSet6 = ' Writing Data Set 6.'; { TMt3dmsRctWriter } constructor TMt3dmsRctWriter.Create(AModel: TCustomModel; EvaluationType: TEvaluationType); begin inherited; FArrayWritingFormat := awfMt3dms; end; class function TMt3dmsRctWriter.Extension: string; begin result := '.rct'; end; procedure TMt3dmsRctWriter.WriteDataSet1; var ChemPkg: TMt3dmsChemReaction; IRCTOP: Integer; begin ChemPkg := Model.ModflowPackages.Mt3dmsChemReact; ISOTHM := Ord(ChemPkg.SorptionChoice); case ChemPkg.KineticChoice of kcNone: IREACT := 0; kcFirstOrder: IREACT := 1; kcZeroOrder: IREACT := 100; else Assert(False); end; IRCTOP := 2; IGETSC := Ord(ChemPkg.OtherInitialConcChoice); WriteI10Integer(ISOTHM, Format(StrSInTheMT3DMSRCT, ['ISOTHM'])); WriteI10Integer(IREACT, Format(StrSInTheMT3DMSRCT, ['IREACT'])); WriteI10Integer(IRCTOP, Format(StrSInTheMT3DMSRCT, ['IRCTOP'])); WriteI10Integer(IGETSC, Format(StrSInTheMT3DMSRCT, ['IGETSC'])); WriteString(' # Data Set 1: ISOTHM IREACT IRCTOP IGETSC'); NewLine; end; procedure TMt3dmsRctWriter.WriteDataSet2A; var LayerIndex: Integer; DataArray: TDataArray; begin if ISOTHM in [1,2,3,4,6] then begin DataArray := Model.DataArrayManager.GetDataSetByName(rsBulkDensity); DataArray.Initialize; for LayerIndex := 0 to Model.ModflowGrid.LayerCount - 1 do begin if Model.IsLayerSimulated(LayerIndex) then begin WriteArray(DataArray, LayerIndex, Format(StrRHOBLayerD, [Model.DataSetLayerToModflowLayer(LayerIndex)]), StrNoValueAssigned, 'RHOB'); end; end; end; end; procedure TMt3dmsRctWriter.WriteDataSet2B; var LayerIndex: Integer; DataArray: TDataArray; begin if ISOTHM in [5,6] then begin DataArray := Model.DataArrayManager.GetDataSetByName(rsImmobPorosity); DataArray.Initialize; for LayerIndex := 0 to Model.ModflowGrid.LayerCount - 1 do begin if Model.IsLayerSimulated(LayerIndex) then begin WriteArray(DataArray, LayerIndex, Format(StrPRSITY2LayerD, [Model.DataSetLayerToModflowLayer(LayerIndex)]), StrNoValueAssigned, 'PRSITY2'); end; end; end; end; procedure TMt3dmsRctWriter.WriteDataSet2C; var SpeciesIndex: Integer; Item: TChemSpeciesItem; procedure WriteSorbedInitialConc; var LayerIndex: Integer; DataArray: TDataArray; begin DataArray := Model.DataArrayManager.GetDataSetByName( Item.SorbOrImmobInitialConcDataArrayName); DataArray.Initialize; for LayerIndex := 0 to Model.ModflowGrid.LayerCount - 1 do begin if Model.IsLayerSimulated(LayerIndex) then begin WriteArray(DataArray, LayerIndex, Format('Data Set: 2C: SRCONC: %0:s, Layer: %1:d', [Item.Name, Model.DataSetLayerToModflowLayer(LayerIndex)]), StrNoValueAssigned, 'SRCONC'); end; end; end; begin if IGETSC > 0 then begin for SpeciesIndex := 0 to Model.MobileComponents.Count - 1 do begin Item := Model.MobileComponents[SpeciesIndex]; WriteSorbedInitialConc; end; for SpeciesIndex := 0 to Model.ImmobileComponents.Count - 1 do begin Item := Model.ImmobileComponents[SpeciesIndex]; WriteSorbedInitialConc; end; end; end; procedure TMt3dmsRctWriter.WriteDataSet3; var SpeciesIndex: Integer; Item: TChemSpeciesItem; procedure WriteSP1; var LayerIndex: Integer; DataArray: TDataArray; begin DataArray := Model.DataArrayManager.GetDataSetByName( Item.FirstSorbParamDataArrayName); DataArray.Initialize; for LayerIndex := 0 to Model.ModflowGrid.LayerCount - 1 do begin if Model.IsLayerSimulated(LayerIndex) then begin WriteArray(DataArray, LayerIndex, Format('Data Set: 3: SP1: %0:s, Layer: %1:d', [Item.Name, Model.DataSetLayerToModflowLayer(LayerIndex)]), StrNoValueAssigned, 'SP1'); end; end; end; begin if ISOTHM > 0 then begin for SpeciesIndex := 0 to Model.MobileComponents.Count - 1 do begin Item := Model.MobileComponents[SpeciesIndex]; WriteSP1; end; for SpeciesIndex := 0 to Model.ImmobileComponents.Count - 1 do begin Item := Model.ImmobileComponents[SpeciesIndex]; WriteSP1; end; end; end; procedure TMt3dmsRctWriter.WriteDataSet4; var SpeciesIndex: Integer; Item: TChemSpeciesItem; procedure WriteSP2; var LayerIndex: Integer; DataArray: TDataArray; begin DataArray := Model.DataArrayManager.GetDataSetByName( Item.SecondSorbParamDataArrayName); DataArray.Initialize; for LayerIndex := 0 to Model.ModflowGrid.LayerCount - 1 do begin if Model.IsLayerSimulated(LayerIndex) then begin WriteArray(DataArray, LayerIndex, Format('Data Set: 4: SP2: %0:s, Layer: %1:d', [Item.Name, Model.DataSetLayerToModflowLayer(LayerIndex)]), StrNoValueAssigned, 'SP2'); end; end; end; begin if ISOTHM > 0 then begin for SpeciesIndex := 0 to Model.MobileComponents.Count - 1 do begin Item := Model.MobileComponents[SpeciesIndex]; WriteSP2; end; for SpeciesIndex := 0 to Model.ImmobileComponents.Count - 1 do begin Item := Model.ImmobileComponents[SpeciesIndex]; WriteSP2; end; end; end; procedure TMt3dmsRctWriter.WriteDataSet5; var SpeciesIndex: Integer; Item: TChemSpeciesItem; procedure WriteRC1; var LayerIndex: Integer; DataArray: TDataArray; begin DataArray := Model.DataArrayManager.GetDataSetByName( Item.ReactionRateDisolvedDataArrayName); DataArray.Initialize; for LayerIndex := 0 to Model.ModflowGrid.LayerCount - 1 do begin if Model.IsLayerSimulated(LayerIndex) then begin WriteArray(DataArray, LayerIndex, Format('Data Set: 5: RC1: %0:s, Layer: %1:d', [Item.Name, Model.DataSetLayerToModflowLayer(LayerIndex)]), StrNoValueAssigned, 'RC1'); end; end; end; begin if IREACT > 0 then begin for SpeciesIndex := 0 to Model.MobileComponents.Count - 1 do begin Item := Model.MobileComponents[SpeciesIndex]; WriteRC1; end; for SpeciesIndex := 0 to Model.ImmobileComponents.Count - 1 do begin Item := Model.ImmobileComponents[SpeciesIndex]; WriteRC1; end; end; end; procedure TMt3dmsRctWriter.WriteDataSet6; var SpeciesIndex: Integer; Item: TChemSpeciesItem; procedure WriteRC2; var LayerIndex: Integer; DataArray: TDataArray; begin DataArray := Model.DataArrayManager.GetDataSetByName( Item.ReactionRateSorbedDataArrayName); DataArray.Initialize; for LayerIndex := 0 to Model.ModflowGrid.LayerCount - 1 do begin if Model.IsLayerSimulated(LayerIndex) then begin WriteArray(DataArray, LayerIndex, Format('Data Set: 6: RC2: %0:s, Layer: %1:d', [Item.Name, Model.DataSetLayerToModflowLayer(LayerIndex)]), StrNoValueAssigned, 'RC2'); end; end; end; begin if IREACT > 0 then begin for SpeciesIndex := 0 to Model.MobileComponents.Count - 1 do begin Item := Model.MobileComponents[SpeciesIndex]; WriteRC2; end; for SpeciesIndex := 0 to Model.ImmobileComponents.Count - 1 do begin Item := Model.ImmobileComponents[SpeciesIndex]; WriteRC2; end; end; end; procedure TMt3dmsRctWriter.WriteFile(const AFileName: string); var NameOfFile: string; begin if not Model.ModflowPackages.Mt3dmsChemReact.IsSelected then begin Exit; end; // remove errors and warnings // frmErrorsAndWarnings.RemoveErrorGroup(Model, StrFileForTheInitial); if Model.PackageGeneratedExternally(StrRCT) then begin Exit; end; NameOfFile := FileName(AFileName); // write to MT3DMS name file. WriteToMt3dMsNameFile(StrRCT, Mt3dRct, NameOfFile, foInput, Model); // WriteToNameFile(StrBAS, Model.UnitNumbers.UnitNumber(StrBAS), // NameOfFile, foInput); // PackageGeneratedExternally needs to be updated for MT3DMS OpenFile(NameOfFile); try frmProgressMM.AddMessage(StrWritingMT3DMSRCTP); frmProgressMM.AddMessage(StrWritingDataSet1); WriteDataSet1; Application.ProcessMessages; if not frmProgressMM.ShouldContinue then begin Exit; end; frmProgressMM.AddMessage(StrWritingDataSet2A); WriteDataSet2A; Application.ProcessMessages; if not frmProgressMM.ShouldContinue then begin Exit; end; frmProgressMM.AddMessage(StrWritingDataSet2B); WriteDataSet2B; Application.ProcessMessages; if not frmProgressMM.ShouldContinue then begin Exit; end; frmProgressMM.AddMessage(StrWritingDataSet2C); WriteDataSet2C; Application.ProcessMessages; if not frmProgressMM.ShouldContinue then begin Exit; end; frmProgressMM.AddMessage(StrWritingDataSet3); WriteDataSet3; Application.ProcessMessages; if not frmProgressMM.ShouldContinue then begin Exit; end; frmProgressMM.AddMessage(StrWritingDataSet4); WriteDataSet4; Application.ProcessMessages; if not frmProgressMM.ShouldContinue then begin Exit; end; frmProgressMM.AddMessage(StrWritingDataSet5); WriteDataSet5; Application.ProcessMessages; if not frmProgressMM.ShouldContinue then begin Exit; end; frmProgressMM.AddMessage(StrWritingDataSet6); WriteDataSet6; Application.ProcessMessages; if not frmProgressMM.ShouldContinue then begin Exit; end; finally CloseFile; end; end; end.
unit uNomnFilter; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uResources, cxLookAndFeelPainters, StdCtrls, cxButtons, cxSpinEdit, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit, DB, FIBDataSet, pFIBDataSet, FR_Class, FR_DSet, FR_DBSet, cxCheckBox, FIBDatabase, pFIBDatabase, ibase, cxButtonEdit, uSpMatSch, uMatasVars, uMatasUtils, ActnList, GlobalSPR, cxGraphics, cxCustomData, cxStyles, cxTL, cxInplaceContainer, cxDBTL, cxTLData, ExtCtrls, cxCurrencyEdit, cxClasses, cxGridTableView, Buttons, FIBQuery, pFIBQuery, pFIBStoredProc, uPackageManager, DateUtils; function ShowNomnFilter(aOwner:TComponent; aDBHANDLE : TISC_DB_HANDLE; aID_SESSION:Int64; var aNomnList: string):boolean;stdcall; exports ShowNomnFilter; type TNomnFilterForm = class(TForm) WorkDatabase: TpFIBDatabase; WorkTransaction: TpFIBTransaction; Panel1: TPanel; cxDBTreeList1: TcxDBTreeList; AllGroupDataSource: TDataSource; AllGroupDataSet: TpFIBDataSet; cxDBTreeList1TYPE_RECORD: TcxDBTreeListColumn; cxDBTreeList1LINK_TO: TcxDBTreeListColumn; cxDBTreeList1ID_NOM: TcxDBTreeListColumn; cxDBTreeList1NAME: TcxDBTreeListColumn; StyleRepository: TcxStyleRepository; cxStyle1: TcxStyle; cxStyle2: TcxStyle; cxStyle3: TcxStyle; cxStyle4: TcxStyle; cxStyle5: TcxStyle; cxStyle6: TcxStyle; cxStyle7: TcxStyle; cxStyle8: TcxStyle; cxStyle9: TcxStyle; cxStyle10: TcxStyle; cxStyle11: TcxStyle; cxStyle12: TcxStyle; cxStyle13: TcxStyle; cxStyle14: TcxStyle; GridTableViewStyleSheetDevExpress: TcxGridTableViewStyleSheet; WorkStoredProc: TpFIBStoredProc; AddButton: TSpeedButton; DelButton: TSpeedButton; DelAllButton: TSpeedButton; ExitButton: TSpeedButton; AllGroupDataSetID_NOMN: TFIBBCDField; AllGroupDataSetLINK_TO: TFIBBCDField; AllGroupDataSetNAME: TFIBStringField; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure CancelButtonClick(Sender: TObject); procedure ActionCancelExecute(Sender: TObject); procedure AddButtonClick(Sender: TObject); procedure DelButtonClick(Sender: TObject); procedure ExitButtonClick(Sender: TObject); procedure DelAllButtonClick(Sender: TObject); private { Private declarations } DBHANDLE : TISC_DB_HANDLE; ID_USER : Int64; ID_SESSION:Integer;// содержит идентификатор сессии public { Public declarations } MatasMonth, MatasYear: Word; PERIOD: TDateTime; ID_SCH: integer; NomnList: string; constructor Create(aOwner:TComponent;aDBHANDLE : TISC_DB_HANDLE;aID_SESSION:Int64); end; var NomnFilterForm: TNomnFilterForm; implementation {$R *.dfm} function ShowNomnFilter(aOwner:TComponent; aDBHANDLE : TISC_DB_HANDLE; aID_SESSION:Int64; var aNomnList: string):boolean;stdcall; var form : TNomnFilterForm; begin form := TNomnFilterForm.Create(aOwner, aDBHANDLE, aID_SESSION); form.FormStyle:= fsNormal; form.ShowModal; aNomnList:=form.NomnList; if form.AllGroupDataSet.IsEmpty then Result:=false else Result:=true; form.Free; end; constructor TNomnFilterForm.Create(aOwner:TComponent;aDBHANDLE : TISC_DB_HANDLE;aID_SESSION:Int64); var dy, dm, dd: Word; begin inherited Create(aOwner); if Assigned(aDBHandle) then begin Self.WorkDatabase.Close; Self.DBHANDLE:= aDBHandle; Self.WorkDatabase.Handle:=aDBHANDLE; self.WorkDatabase.Open; ID_SESSION:=aID_SESSION; AllGroupDataSet.Close; AllGroupDataSet.ParamByName('ID_SESSION').Value :=ID_SESSION; AllGroupDataSet.CloseOpen(false); end; end; procedure TNomnFilterForm.FormClose(Sender: TObject; var Action: TCloseAction); var Str:String; begin if AllGroupDataSet.IsEmpty then exit; AllGroupDataSet.First; while (not AllGroupDataSet.Eof) and (Length(Str)<255) do begin Str:=Str + AllGroupDataSetNAME.AsString + ';'; AllGroupDataSet.Next; end; NomnList:=Str; end; procedure TNomnFilterForm.CancelButtonClick(Sender: TObject); begin Close; end; procedure TNomnFilterForm.ActionCancelExecute(Sender: TObject); begin Close; end; procedure TNomnFilterForm.AddButtonClick(Sender: TObject); var Res:Variant; TempID:Int64; sTempID: string; begin Res:=uPackageManager.LGetNomn(self, DBHandle, fsNormal, 0, 0, 0, 0, 0, 2, 1); if VarType(Res) <> varEmpty then begin sTempID:=Res[0]; TempID:=StrToInt64(sTempID); if (TempID=0) then Exit; try WorkTransaction.StartTransaction; WorkStoredProc.StoredProcName:='MAT_FILTER_ADD_NOMN_TREE'; WorkStoredProc.Prepare; WorkStoredProc.ParamByName('ID_OBJECT_NOMN').AsInt64:=TempID; WorkStoredProc.ParamByName('ID_SESSION').AsInt64:=ID_SESSION; WorkStoredProc.ExecProc; WorkStoredProc.Transaction.Commit; except on E : Exception do begin ShowMessage(E.Message); WorkStoredProc.Transaction.Rollback; Exit; end; end; AllGroupDataSet.CloseOpen(false); end; end; procedure TNomnFilterForm.DelButtonClick(Sender: TObject); var ID:Int64; Link:Int64; begin ID:=AllGroupDataSetID_NOMN.AsInt64; Link:=AllGroupDataSetLINK_TO.AsInt64; try WorkTransaction.StartTransaction; WorkStoredProc.StoredProcName:='MAT_DEL_FROM_TMP_FTR_RECORD'; WorkStoredProc.Prepare; WorkStoredProc.ParamByName('ID_NOMN').AsInt64:=ID; WorkStoredProc.ParamByName('ID_SESSION').AsInt64:=ID_SESSION; WorkStoredProc.ExecProc; WorkStoredProc.Transaction.Commit; except on E : Exception do begin ShowMessage(E.Message); WorkStoredProc.Transaction.Rollback; Exit; end; end; AllGroupDataSet.Close; AllGroupDataSet.ParamByName('ID_SESSION').Value :=ID_SESSION; AllGroupDataSet.CloseOpen(false); AllGroupDataSet.Locate('id_nom',Link,[]); end; procedure TNomnFilterForm.ExitButtonClick(Sender: TObject); begin Close(); end; procedure TNomnFilterForm.DelAllButtonClick(Sender: TObject); begin try WorkTransaction.StartTransaction; WorkStoredProc.StoredProcName:='MAT_DEL_FROM_TMP_FILTER'; WorkStoredProc.Prepare; WorkStoredProc.ParamByName('ID_SESSION').AsInt64:=ID_SESSION; WorkStoredProc.ExecProc; WorkStoredProc.Transaction.Commit; except on E : Exception do begin ShowMessage(E.Message); WorkStoredProc.Transaction.Rollback; Exit; end; end; end; end.
unit uAtributos; interface uses uInterfaces, uTypes; type TMVVMCustomAttribute = class(TCustomAttribute) end; ViewForVM = class(TMVVMCustomAttribute) strict private FVMInterface: TGUID; FVMClass: TViewModelClass; FInstanceType: EInstanceType; public constructor Create(AInterfaceID: TGUID; AVMClassType: TViewModelClass; const AInstanceType: EInstanceType = EInstanceType.itDefault); property VMInterface: TGUID read FVMInterface; property VMClass: TViewModelClass read FVMClass; property InstanceType: EInstanceType read FInstanceType; end; implementation { ViewForVM } constructor ViewForVM.Create(AInterfaceID: TGUID; AVMClassType: TViewModelClass; const AInstanceType: EInstanceType); begin FVMInterface := AInterfaceID; FVMClass := AVMClassType; FInstanceType:= AInstanceType; end; end.
unit uMainForm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Edit, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Layouts, FMX.ListBox, Androidapi.JNIBridge, Androidapi.JNI.Embarcadero, Androidapi.JNI.GraphicsContentViewText; type TMyReceiver = class(TJavaLocal, JFMXBroadcastReceiverListener) public constructor Create; procedure onReceive(context: JContext; intent: JIntent); cdecl; end; type TMainForm = class(TForm) ToolBar1: TToolBar; Label1: TLabel; ListBox1: TListBox; Button1: TButton; Button2: TButton; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } FMyListener: TMyReceiver; FBroadcastReceiver: JFMXBroadcastReceiver; public { Public declarations } end; var MainForm: TMainForm; implementation {$R *.fmx} uses Androidapi.Helpers, Androidapi.JNI.JavaTypes; procedure TMainForm.Button1Click(Sender: TObject); var LJIntent: JIntent; begin LJIntent := TJIntent.Create; LJIntent.setAction(StringToJString('com.barcode.sendBroadcastScan')); TAndroidHelper.context.sendBroadcast(LJIntent); end; procedure TMainForm.Button2Click(Sender: TObject); begin ListBox1.Items.Clear; end; procedure TMainForm.FormCreate(Sender: TObject); var Filter: JIntentFilter; begin FMyListener := TMyReceiver.Create; FBroadcastReceiver := TJFMXBroadcastReceiver.JavaClass.init(FMyListener); Filter := TJIntentFilter.JavaClass.init (StringToJString('com.barcode.sendBroadcast')); TAndroidHelper.context.getApplicationContext.registerReceiver (FBroadcastReceiver, Filter); end; procedure TMainForm.FormDestroy(Sender: TObject); begin TAndroidHelper.context.getApplicationContext.unregisterReceiver (FBroadcastReceiver); end; { TMyReceiver } constructor TMyReceiver.Create; begin inherited; end; procedure TMyReceiver.onReceive(context: JContext; intent: JIntent); var ldata: string; begin ldata := JStringToString (intent.getStringExtra(StringToJString('BARCODE'))).Trim; if not ldata.IsEmpty then MainForm.ListBox1.Items.Insert(0, ldata + ' - ' + FormatDateTime('hh:nn:ss', Now)); end; end.
unit ComponentTreeView; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, ImgList, TypInfo, Menus; type TComponentTreeFilterEvent = function(inObject: TObject): Boolean of object; // TComponentTreeForm = class(TForm) TreeView: TTreeView; ExplorerImages: TImageList; PopupMenu1: TPopupMenu; Delete1: TMenuItem; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure TreeViewGetImageIndex(Sender: TObject; Node: TTreeNode); procedure TreeViewClick(Sender: TObject); procedure TreeViewKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure Delete1Click(Sender: TObject); private FNodeCache: TList; FOnSelect: TNotifyEvent; FRoot: TComponent; FSelectCache: TPersistent; FTopCache: TPersistent; Locked: Boolean; FOnFilter: TComponentTreeFilterEvent; protected function GetSelected: TPersistent; procedure SetOnSelect(const Value: TNotifyEvent); procedure SetRoot(const Value: TComponent); procedure SetSelected(const Value: TPersistent); protected procedure AddCollectionItems(inNode: TTreeNode; inComponent: TComponent); procedure AddComponent(inNode: TTreeNode; inComponent: TComponent); procedure AddItem(inNode: TTreeNode; inComponent: TComponent); procedure AddItems(inNode: TTreeNode; inContainer: TComponent); procedure AddProp(inNode: TTreeNode; inObject: TObject; const inName: string); procedure AddPropInfo(inNode: TTreeNode; inComponent: TComponent; inInfo: PPropInfo); procedure BuildCache; procedure DesignChange(Sender: TObject); procedure ExpandIfCached(inNode: TTreeNode); function Filter(inObject: TObject): Boolean; function FindNode(inComponent: TPersistent): TTreeNode; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure Select; procedure SelectionChange(Sender: TObject); procedure SetCollectionItem(inNode: TTreeNode; inCollection: TCollection); procedure SetItem(inNode: TTreeNode; inComponent: TComponent); function ShouldAddComponent(inComponent: TComponent): Boolean; public procedure Delete(inComponent: TComponent); procedure Refresh; property Root: TComponent read FRoot write SetRoot; property Selected: TPersistent read GetSelected write SetSelected; property OnFilter: TComponentTreeFilterEvent read FOnFilter write FOnFilter; property OnSelect: TNotifyEvent read FOnSelect write SetOnSelect; end; var ComponentTreeForm: TComponentTreeForm; implementation uses DesignManager; {$R *.dfm} { TComponentTreeForm } procedure TComponentTreeForm.FormCreate(Sender: TObject); begin FNodeCache := TList.Create; DesignMgr.DesignObservers.Add(DesignChange); DesignMgr.SelectionObservers.Add(SelectionChange); end; procedure TComponentTreeForm.FormDestroy(Sender: TObject); begin FNodeCache.Free; end; procedure TComponentTreeForm.DesignChange(Sender: TObject); begin Root := DesignMgr.Container; end; procedure TComponentTreeForm.SelectionChange(Sender: TObject); begin Selected := TPersistent(DesignMgr.SelectedObject); end; procedure TComponentTreeForm.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (Operation = opRemove) and (AComponent = Root) then FRoot := nil; end; procedure TComponentTreeForm.SetRoot(const Value: TComponent); begin if (Value <> FRoot) then begin if FRoot <> nil then FRoot.RemoveFreeNotification(Self); FRoot := Value; if FRoot <> nil then FRoot.FreeNotification(Self); end; if not Locked then Refresh; end; procedure TComponentTreeForm.BuildCache; var i: Integer; begin FSelectCache := Selected; if TreeView.TopItem <> nil then FTopCache := TreeView.TopItem.Data else FTopCache := nil; FNodeCache.Clear; for i := 0 to Pred(TreeView.Items.Count) do if TreeView.Items[i].Expanded then FNodeCache.Add(TreeView.Items[i].Data); end; procedure TComponentTreeForm.Refresh; var n: TTreeNode; begin with TreeView do try Items.BeginUpdate; BuildCache; Items.Clear; if Root <> nil then AddItems(nil, Root); finally Items.EndUpdate; end; n := FindNode(FTopCache); if n <> nil then TreeView.TopItem := n; n := FindNode(FSelectCache); if n <> nil then TreeView.Selected := n; end; function TComponentTreeForm.Filter(inObject: TObject): Boolean; begin Result := DesignMgr.Filter(inObject); //Result := Assigned(OnFilter) and OnFilter(inObject); end; function TComponentTreeForm.ShouldAddComponent( inComponent: TComponent): Boolean; begin Result := (inComponent <> nil) and (inComponent.Name <> '') and not Filter(inComponent); end; procedure TComponentTreeForm.ExpandIfCached(inNode: TTreeNode); begin if FNodeCache.IndexOf(inNode.Data) >= 0 then inNode.Expanded := true; end; procedure TComponentTreeForm.SetItem(inNode: TTreeNode; inComponent: TComponent); begin inNode.Data := inComponent; AddCollectionItems(inNode, inComponent); //if inComponent is TComponent then // AddItems(inNode, TWinControl(inComponent)); AddItems(inNode, inComponent); ExpandIfCached(inNode); end; procedure TComponentTreeForm.AddItem(inNode: TTreeNode; inComponent: TComponent); begin if ShouldAddComponent(inComponent) then SetItem(TreeView.Items.AddChild(inNode, inComponent.Name), inComponent); end; procedure TComponentTreeForm.AddComponent(inNode: TTreeNode; inComponent: TComponent); begin if not (inComponent is TControl) then AddItem(inNode, inComponent); end; procedure TComponentTreeForm.AddItems(inNode: TTreeNode; inContainer: TComponent); var i: Integer; begin for i := 0 to Pred(inContainer.ComponentCount) do AddComponent(inNode, inContainer.Components[i]); if inContainer is TWinControl then with TWinControl(inContainer) do for i := 0 to Pred(ControlCount) do AddItem(inNode, Controls[i]); end; procedure TComponentTreeForm.SetCollectionItem(inNode: TTreeNode; inCollection: TCollection); var i: Integer; begin inNode.Data := inCollection; with inCollection do for i := 0 to Pred(Count) do TreeView.Items.AddChild(inNode, Items[i].DisplayName).Data := Items[i]; ExpandIfCached(inNode); end; procedure TComponentTreeForm.AddProp(inNode: TTreeNode; inObject: TObject; const inName: string); begin if (inObject is TCollection) and not Filter(inObject) then SetCollectionItem(TreeView.Items.AddChild(inNode, inName), TCollection(inObject)); end; procedure TComponentTreeForm.AddPropInfo(inNode: TTreeNode; inComponent: TComponent; inInfo: PPropInfo); begin if inInfo.PropType^.Kind = tkClass then AddProp(inNode, GetObjectProp(inComponent, inInfo), inInfo.Name); end; procedure TComponentTreeForm.AddCollectionItems(inNode: TTreeNode; inComponent: TComponent); var c, i: Integer; propList: PPropList; begin c := GetPropList(inComponent, propList); for i := 0 to Pred(c) do AddPropInfo(inNode, inComponent, propList[i]); end; procedure TComponentTreeForm.TreeViewGetImageIndex(Sender: TObject; Node: TTreeNode); var c: TComponent; begin c := TComponent(Node.Data); if (c is TWinControl) then Node.ImageIndex := 0 else if (c is TControl) then Node.ImageIndex := 1 else Node.ImageIndex := 2; Node.SelectedIndex := Node.ImageIndex; end; function TComponentTreeForm.GetSelected: TPersistent; begin if TreeView.Selected = nil then Result := nil else Result := TPersistent(TreeView.Selected.Data); end; function TComponentTreeForm.FindNode(inComponent: TPersistent): TTreeNode; var i: Integer; begin Result := nil; for i := 0 to Pred(TreeView.Items.Count) do if TreeView.Items[i].Data = inComponent then begin Result := TreeView.Items[i]; break; end; end; procedure TComponentTreeForm.Delete(inComponent: TComponent); var n: TTreeNode; begin n := FindNode(inComponent); if n <> nil then n.Free; end; procedure TComponentTreeForm.SetSelected(const Value: TPersistent); var n: TTreeNode; begin if not Locked then begin n := FindNode(Value); if n <> nil then TreeView.Select(n); end; end; procedure TComponentTreeForm.SetOnSelect(const Value: TNotifyEvent); begin FOnSelect := Value; end; procedure TComponentTreeForm.Select; begin if (Selected <> nil) and not Locked then try Locked := true; DesignMgr.ObjectSelected(Self, Selected); if Assigned(OnSelect) then OnSelect(Self); finally Locked := false; end; end; procedure TComponentTreeForm.TreeViewClick(Sender: TObject); begin Select; end; procedure TComponentTreeForm.TreeViewKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin Select; end; procedure TComponentTreeForm.Delete1Click(Sender: TObject); begin if (Selected <> nil) then begin Selected.Free; DesignMgr.DesignChange; end; end; end.
unit RectangularUnitControl; interface uses Math, TypeControl, UnitControl; type TRectangularUnit = class (TUnit) private FWidth: Double; FHeight: Double; function GetWidth: Double; function GetHeight: Double; public property Width: Double read GetWidth; property Height: Double read GetHeight; constructor Create(const AId: Int64; const AMass: Double; const AX: Double; const AY: Double; const ASpeedX: Double; const ASpeedY: Double; const AAngle: Double; const AAngularSpeed: Double; const AWidth: Double; const AHeight: Double); destructor Destroy; override; end; TRectangularUnitArray = array of TRectangularUnit; implementation function TRectangularUnit.GetWidth: Double; begin Result := FWidth; end; function TRectangularUnit.GetHeight: Double; begin Result := FHeight; end; constructor TRectangularUnit.Create(const AId: Int64; const AMass: Double; const AX: Double; const AY: Double; const ASpeedX: Double; const ASpeedY: Double; const AAngle: Double; const AAngularSpeed: Double; const AWidth: Double; const AHeight: Double); begin inherited Create(AId, AMass, AX, AY, ASpeedX, ASpeedY, AAngle, AAngularSpeed); FWidth := AWidth; FHeight := AHeight; end; destructor TRectangularUnit.Destroy; begin inherited; end; end.
{ StringOps Hotkey: Ctrl+R } unit UserScript; var frmSearch: TForm; sElementPath: String; bProperCase: Boolean; bSentenceCase: Boolean; bModify: Boolean; sQuerySearch: String; sQueryReplace: String; sQueryPrefix: String; sQuerySuffix: String; bCaseSensitive: Boolean; frmModalResult: TModalResult; lblModifyOptions: TLabel; edElementPath: TEdit; edQuerySearch: TEdit; edQueryReplace: TEdit; rbProperCase: TRadioButton; rbSentenceCase: TRadioButton; rbModify: TRadioButton; edQueryPrefix: TEdit; edQuerySuffix: TEdit; btnExecute: TButton; btnClose: TButton; function Initialize: Integer; begin ShowSearchForm; if frmSearch.ModalResult = mrCancel then exit; end; function Process(e: IInterface): Integer; var x: IInterface; i: Integer; sRecordID: String; sElementPathTemplate: String; begin if frmSearch.ModalResult = mrCancel then exit; sRecordID := GetEditValue(GetElement(e, 'Record Header\FormID')); if ContainsText(sElementPath, '[*]') then begin sElementPathTemplate := sElementPath; // set up first child element sElementPath := StringReplace(sElementPathTemplate, '[*]', '[0]', [rfReplaceAll]); x := GetElement(e, sElementPath); if not Assigned(x) or not IsEditable(x) then exit; i := 0; repeat ExecuteExecuteExecute(x); AddMessage('Processed: ' + sRecordID + ' @ ' + sElementPath); // set up next child element Inc(i); sElementPath := StringReplace(sElementPathTemplate, '[*]', '[' + IntToStr(i) + ']', [rfReplaceAll]); x := GetElement(e, sElementPath); until not Assigned(x) or not IsEditable(x); sElementPath := sElementPathTemplate; exit; end; x := GetElement(e, sElementPath); if not Assigned(x) or not IsEditable(x) then exit; ExecuteExecuteExecute(x); AddMessage('Processed: ' + sRecordID); end; function Finalize: Integer; begin frmSearch.Free; end; function ExecuteExecuteExecute(aElement: IInterface): Integer; var sHaystack: String; bMatchFound: Boolean; bAddPrefix: Boolean; bAddSuffix: Boolean; begin sHaystack := GetEditValue(aElement); if not (Length(sHaystack) > 0) then exit; if bProperCase then begin SetEditValue(aElement, ProperCase(sHaystack)); exit; end; if bSentenceCase then begin SetEditValue(aElement, SentenceCase(sHaystack)); exit; end; if not bModify then exit; if Length(sQuerySearch) > 0 then begin if bCaseSensitive then bMatchFound := ContainsStr(sHaystack, sQuerySearch) else bMatchFound := ContainsText(sHaystack, sQuerySearch); if bMatchFound then begin sHaystack := GetEditValue(aElement); if bCaseSensitive then sHaystack := StringReplace(sHaystack, sQuerySearch, sQueryReplace, [rfReplaceAll]) else sHaystack := StringReplace(sHaystack, sQuerySearch, sQueryReplace, [rfReplaceAll, rfIgnoreCase]); // handle special tokens sHaystack := StringReplace(sHaystack, '#13', #13, [rfReplaceAll]); sHaystack := StringReplace(sHaystack, '#10', #10, [rfReplaceAll]); sHaystack := StringReplace(sHaystack, '#9', #9, [rfReplaceAll]); SetEditValue(aElement, sHaystack); end; end; bAddPrefix := Length(sQueryPrefix) > 0; bAddSuffix := Length(sQuerySuffix) > 0; if bAddPrefix or bAddSuffix then begin // ensure we're working with latest haystack sHaystack := GetEditValue(aElement); // we don't care about prefix/suffix case sensitivity if bAddPrefix then if not StartsText(sQueryPrefix, sHayStack) then sHaystack := Insert(sQueryPrefix, sHaystack, 0); if bAddSuffix then if not EndsText(sQuerySuffix, sHaystack) then sHaystack := Insert(sQuerySuffix, sHaystack, Length(sHaystack) + 1); SetEditValue(aElement, sHaystack); end; end; function GetChar(const aText: String; aPosition: Integer): Char; begin Result := Copy(aText, aPosition, 1); end; procedure SetChar(var aText: String; aPosition: Integer; aChar: Char); var sHead, sTail: String; begin sHead := Copy(aText, 1, aPosition - 1); sTail := Copy(aText, aPosition + 1, Length(aText)); aText := sHead + aChar + sTail; end; function InStringList(const aText: String; const aList: TStringList): Boolean; begin Result := (aList.IndexOf(aText) <> -1); end; function SentenceCase(const aText: String): String; begin Result := ''; if aText <> '' then Result := UpCase(aText[1]) + Copy(LowerCase(aText), 2, Length(aText)); end; function ProperCase(const aText: String): String; var slResults: TStringList; slLowerCase: TStringList; slUpperCase: TStringList; i, dp: Integer; rs, tmp: String; begin slLowerCase := TStringList.Create; slUpperCase := TStringList.Create; slLowerCase.CommaText := ' a , an , the , and , but , or , nor , at , by , for , from , in , into , of , off , on , onto , out , over , up , with , to , as '; slUpperCase.CommaText := ' fx , npc '; slResults := TStringList.Create; slResults.Delimiter := ' '; slResults.DelimitedText := aText; for i := 0 to Pred(slResults.Count) do begin tmp := slResults[i]; tmp := SentenceCase(tmp); if InStringList(tmp, slLowerCase) and i <> 0 then tmp := LowerCase(tmp); if InStringList(tmp, slUpperCase) and i <> 0 then tmp := UpperCase(tmp); if GetChar(tmp, 1) = '(' then SetChar(tmp, 2, UpperCase(GetChar(tmp, 2))); if GetChar(tmp, 1) = '<' then SetChar(tmp, 2, UpperCase(GetChar(tmp, 2))); if GetChar(tmp, 1) = '=' then SetChar(tmp, 2, UpperCase(GetChar(tmp, 2))); if Pos('-', tmp) > 0 then begin dp := Pos('-', tmp); if GetChar(tmp, dp + 1) <> ' ' then SetChar(tmp, dp + 1, UpperCase(GetChar(tmp, dp + 1))); end; slResults[i] := tmp; end; Result := slResults.DelimitedText; slResults.Free; slLowerCase.Free; slUpperCase.Free; end; function GetElement(const aElement: IInterface; const aPath: String): IInterface; begin if Pos('[', aPath) > 0 then Result := ElementByIP(aElement, aPath) else if Pos('\', aPath) > 0 then Result := ElementByPath(aElement, aPath) else if CompareStr(aPath, Uppercase(aPath)) = 0 then Result := ElementBySignature(aElement, aPath) else Result := ElementByName(aElement, aPath); end; function ElementByIP(aElement: IInterface; aIndexedPath: String): IInterface; var i, index, startPos: Integer; path: TStringList; begin aIndexedPath := StringReplace(aIndexedPath, '/', '\', [rfReplaceAll]); path := TStringList.Create; path.Delimiter := '\'; path.StrictDelimiter := true; path.DelimitedText := aIndexedPath; for i := 0 to Pred(path.count) do begin startPos := Pos('[', path[i]); if not (startPos > 0) then begin aElement := ElementByPath(aElement, path[i]); continue; end; index := StrToInt(MidStr(path[i], startPos+1, Pos(']', path[i])-2)); aElement := ElementByIndex(aElement, index); end; Result := aElement; end; procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then btnClose.Click else if Key = VK_RETURN then btnExecute.Click; end; procedure btnExecuteClick(Sender: TObject); begin sElementPath := edElementPath.Text; sQuerySearch := edQuerySearch.Text; sQueryReplace := edQueryReplace.Text; sQueryPrefix := edQueryPrefix.Text; sQuerySuffix := edQuerySuffix.Text; bProperCase := rbProperCase.Checked; bSentenceCase := rbSentenceCase.Checked; bModify := rbModify.Checked; bCaseSensitive := CompareStr(sQuerySearch, LowerCase(sQueryReplace)) <> 0; end; procedure rbProperCaseClick(Sender: TObject); begin rbSentenceCase.Checked := False; rbModify.Checked := False; edQuerySearch.Enabled := False; edQueryReplace.Enabled := False; edQueryPrefix.Enabled := False; edQuerySuffix.Enabled := False; lblModifyOptions.Caption := 'Modify Options (disabled)'; end; procedure rbSentenceCaseClick(Sender: TObject); begin rbProperCase.Checked := False; rbModify.Checked := False; edQuerySearch.Enabled := False; edQueryReplace.Enabled := False; edQueryPrefix.Enabled := False; edQuerySuffix.Enabled := False; lblModifyOptions.Caption := 'Modify Options (disabled)'; end; procedure rbModifyClick(Sender: TObject); begin rbProperCase.Checked := False; rbSentenceCase.Checked := False; edQuerySearch.Enabled := True; edQueryReplace.Enabled := True; edQueryPrefix.Enabled := True; edQuerySuffix.Enabled := True; lblModifyOptions.Caption := 'Modify Options (enabled)'; end; procedure ShowSearchForm; var lblElementPath: TLabel; lblBatchOperation: TLabel; lblQuerySearch: TLabel; lblQueryReplace: TLabel; lblQueryPrefix: TLabel; lblQuerySuffix: TLabel; ini: TMemIniFile; iniDefaultElementPath: String; iniDefaultQuerySearch: String; iniDefaultQueryReplace: String; iniDefaultQueryPrefix: String; iniDefaultQuerySuffix: String; iniDefaultProperCase: Boolean; iniDefaultSentenceCase: Boolean; iniDefaultModify: Boolean; scaleFactor: Double; begin ini := TMemIniFile.Create(wbScriptsPath + 'StringOps.ini'); iniDefaultElementPath := ini.ReadString('Settings', 'ElementPath', 'FULL'); iniDefaultQuerySearch := ini.ReadString('Settings', 'QuerySearch', ''); iniDefaultQueryReplace := ini.ReadString('Settings', 'QueryReplace', ''); iniDefaultQueryPrefix := ini.ReadString('Settings', 'QueryPrefix', ''); iniDefaultQuerySuffix := ini.ReadString('Settings', 'QuerySuffix', ''); iniDefaultProperCase := ini.ReadBool('Settings', 'ProperCase', False); iniDefaultSentenceCase := ini.ReadBool('Settings', 'SentenceCase', False); iniDefaultModify := ini.ReadBool('Settings', 'Modify', True); scaleFactor := Screen.PixelsPerInch / 96; frmSearch := TForm.Create(nil); try lblElementPath := TLabel.Create(frmSearch); lblQuerySearch := TLabel.Create(frmSearch); lblQueryReplace := TLabel.Create(frmSearch); lblBatchOperation := TLabel.Create(frmSearch); lblModifyOptions := TLabel.Create(frmSearch); lblQueryPrefix := TLabel.Create(frmSearch); lblQuerySuffix := TLabel.Create(frmSearch); edElementPath := TEdit.Create(frmSearch); edQuerySearch := TEdit.Create(frmSearch); edQueryReplace := TEdit.Create(frmSearch); btnExecute := TButton.Create(frmSearch); btnClose := TButton.Create(frmSearch); rbProperCase := TRadioButton.Create(frmSearch); rbSentenceCase := TRadioButton.Create(frmSearch); rbModify := TRadioButton.Create(frmSearch); edQueryPrefix := TEdit.Create(frmSearch); edQuerySuffix := TEdit.Create(frmSearch); frmSearch.Name := 'frmSearch'; frmSearch.BorderStyle := bsDialog; frmSearch.Caption := 'StringOps by fireundubh'; frmSearch.ClientHeight := 284 * scaleFactor; frmSearch.ClientWidth := 274 * scaleFactor; frmSearch.Color := clBtnFace; frmSearch.KeyPreview := True; frmSearch.OnKeyDown := FormKeyDown; frmSearch.Position := poScreenCenter; lblElementPath.Name := 'lblElementPath'; lblElementPath.Parent := frmSearch; lblElementPath.Left := 16 * scaleFactor; lblElementPath.Top := 12 * scaleFactor; lblElementPath.Width := 63 * scaleFactor; lblElementPath.Height := 13 * scaleFactor; lblElementPath.Alignment := taRightJustify; lblElementPath.Caption := 'Element path'; lblQuerySearch.Name := 'lblQuerySearch'; lblQuerySearch.Parent := frmSearch; lblQuerySearch.Left := 32 * scaleFactor; lblQuerySearch.Top := 124 * scaleFactor; lblQuerySearch.Width := 47 * scaleFactor; lblQuerySearch.Height := 13 * scaleFactor; lblQuerySearch.Alignment := taRightJustify; lblQuerySearch.Caption := 'Find what'; lblQueryReplace.Name := 'lblQueryReplace'; lblQueryReplace.Parent := frmSearch; lblQueryReplace.Left := 18 * scaleFactor; lblQueryReplace.Top := 156 * scaleFactor; lblQueryReplace.Width := 61 * scaleFactor; lblQueryReplace.Height := 13 * scaleFactor; lblQueryReplace.Alignment := taRightJustify; lblQueryReplace.Caption := 'Replace with'; lblBatchOperation.Name := 'lblBatchOperation'; lblBatchOperation.Parent := frmSearch; lblBatchOperation.Left := 8 * scaleFactor; lblBatchOperation.Top := 40 * scaleFactor; lblBatchOperation.Width := 94 * scaleFactor; lblBatchOperation.Height := 13 * scaleFactor; lblBatchOperation.Caption := 'Select Operation'; lblModifyOptions.Name := 'lblModifyOptions'; lblModifyOptions.Parent := frmSearch; lblModifyOptions.Left := 8 * scaleFactor; lblModifyOptions.Top := 96 * scaleFactor; lblModifyOptions.Width := 159 * scaleFactor; lblModifyOptions.Height := 13 * scaleFactor; lblModifyOptions.Caption := 'Modify Options (enabled)'; lblQueryPrefix.Name := 'lblQueryPrefix'; lblQueryPrefix.Parent := frmSearch; lblQueryPrefix.Left := 29 * scaleFactor; lblQueryPrefix.Top := 187 * scaleFactor; lblQueryPrefix.Width := 50 * scaleFactor; lblQueryPrefix.Height := 13 * scaleFactor; lblQueryPrefix.Alignment := taRightJustify; lblQueryPrefix.Caption := 'Add prefix'; lblQuerySuffix.Name := 'lblQuerySuffix'; lblQuerySuffix.Parent := frmSearch; lblQuerySuffix.Left := 30 * scaleFactor; lblQuerySuffix.Top := 220 * scaleFactor; lblQuerySuffix.Width := 49 * scaleFactor; lblQuerySuffix.Height := 13 * scaleFactor; lblQuerySuffix.Alignment := taRightJustify; lblQuerySuffix.Caption := 'Add suffix'; edElementPath.Name := 'edElementPath'; edElementPath.Parent := frmSearch; edElementPath.Left := 85 * scaleFactor; edElementPath.Top := 8 * scaleFactor; edElementPath.Width := 180 * scaleFactor; edElementPath.Height := 21 * scaleFactor; edElementPath.TabOrder := 0; edElementPath.Text := iniDefaultElementPath; rbProperCase.Name := 'rbProperCase'; rbProperCase.Parent := frmSearch; rbProperCase.Left := 8 * scaleFactor; rbProperCase.Top := 60 * scaleFactor; rbProperCase.Width := 80 * scaleFactor; rbProperCase.Height := 17 * scaleFactor; rbProperCase.Caption := 'Proper Case'; rbProperCase.Checked := iniDefaultProperCase; rbProperCase.TabOrder := 1; rbProperCase.OnClick := rbProperCaseClick; rbSentenceCase.Name := 'rbSentenceCase'; rbSentenceCase.Parent := frmSearch; rbSentenceCase.Left := 102 * scaleFactor; rbSentenceCase.Top := 60 * scaleFactor; rbSentenceCase.Width := 91 * scaleFactor; rbSentenceCase.Height := 17 * scaleFactor; rbSentenceCase.Caption := 'Sentence Case'; rbSentenceCase.Checked := iniDefaultSentenceCase; rbSentenceCase.TabOrder := 2; rbSentenceCase.OnClick := rbSentenceCaseClick; rbModify.Name := 'rbModify'; rbModify.Parent := frmSearch; rbModify.Left := 210 * scaleFactor; rbModify.Top := 60 * scaleFactor; rbModify.Width := 49 * scaleFactor; rbModify.Height := 17 * scaleFactor; rbModify.Caption := 'Modify'; rbModify.Checked := iniDefaultModify; rbModify.TabOrder := 3; rbModify.OnClick := rbModifyClick; edQuerySearch.Name := 'edQuerySearch'; edQuerySearch.Parent := frmSearch; edQuerySearch.Left := 85 * scaleFactor; edQuerySearch.Top := 120 * scaleFactor; edQuerySearch.Width := 180 * scaleFactor; edQuerySearch.Height := 21 * scaleFactor; edQuerySearch.TabOrder := 4; edQuerySearch.Text := iniDefaultQuerySearch; edQueryReplace.Name := 'edQueryReplace'; edQueryReplace.Parent := frmSearch; edQueryReplace.Left := 85 * scaleFactor; edQueryReplace.Top := 152 * scaleFactor; edQueryReplace.Width := 180 * scaleFactor; edQueryReplace.Height := 21 * scaleFactor; edQueryReplace.TabOrder := 5; edQueryReplace.Text := iniDefaultQueryReplace; edQueryPrefix.Name := 'edQueryPrefix'; edQueryPrefix.Parent := frmSearch; edQueryPrefix.Left := 85 * scaleFactor; edQueryPrefix.Top := 184 * scaleFactor; edQueryPrefix.Width := 180 * scaleFactor; edQueryPrefix.Height := 21 * scaleFactor; edQueryPrefix.TabOrder := 6; edQueryPrefix.Text := iniDefaultQueryPrefix; edQuerySuffix.Name := 'edQuerySuffix'; edQuerySuffix.Parent := frmSearch; edQuerySuffix.Left := 85 * scaleFactor; edQuerySuffix.Top := 216 * scaleFactor; edQuerySuffix.Width := 180 * scaleFactor; edQuerySuffix.Height := 21 * scaleFactor; edQuerySuffix.TabOrder := 7; edQuerySuffix.Text := iniDefaultQuerySuffix; btnExecute.Name := 'btnExecute'; btnExecute.Parent := frmSearch; btnExecute.Left := 191 * scaleFactor; btnExecute.Top := 251 * scaleFactor; btnExecute.Width := 75 * scaleFactor; btnExecute.Height := 25 * scaleFactor; btnExecute.Caption := 'Execute'; btnExecute.TabOrder := 8; btnExecute.OnClick := btnExecuteClick; btnExecute.ModalResult := mrOk; btnClose.Name := 'btnClose'; btnClose.Parent := frmSearch; btnClose.Left := 110 * scaleFactor; btnClose.Top := 252 * scaleFactor; btnClose.Width := 75 * scaleFactor; btnClose.Height := 25 * scaleFactor; btnClose.Caption := 'Close'; btnClose.TabOrder := 9; btnClose.ModalResult := mrCancel; frmSearch.ShowModal; finally ini.WriteString('Settings', 'ElementPath', edElementPath.Text); ini.WriteString('Settings', 'QuerySearch', edQuerySearch.Text); ini.WriteString('Settings', 'QueryReplace', edQueryReplace.Text); ini.WriteString('Settings', 'QueryPrefix', edQueryPrefix.Text); ini.WriteString('Settings', 'QuerySuffix', edQuerySuffix.Text); ini.WriteBool('Settings', 'ProperCase', rbProperCase.Checked); ini.WriteBool('Settings', 'SentenceCase', rbSentenceCase.Checked); ini.WriteBool('Settings', 'Modify', rbModify.Checked); try ini.UpdateFile; except AddMessage('Cannot save settings, no write access to ' + ini.FileName); end; ini.Free; end; end; end.
unit cn_dt_Raport_Unit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ibase, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxCheckBox, cxTextEdit, cxCurrencyEdit, FIBQuery, pFIBQuery, pFIBStoredProc, FIBDataSet, pFIBDataSet, FIBDatabase, pFIBDatabase, dxBar, ImgList, ActnList, dxBarExtItems, dxStatusBar, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses, cxControls, cxGridCustomView, cxGrid, ExtCtrls, DM_Raport, cn_Common_Types, cn_Common_Funcs, cnConsts, frmDocs_AE_Unit, cn_Common_Messages,cnConsts_Messages, cn_Common_Loader, frmPfio_AE_Unit,frmAddAll_Unit, frxClass, frxDBSet, frxDesgn, frxExportPDF, frxExportXLS, frxExportHTML, frxExportRTF, StdCtrls; type TfrmRaport = class(TForm) Splitter1: TSplitter; Grid: TcxGrid; GridView: TcxGridDBTableView; GridLevel1: TcxGridLevel; Grid2: TcxGrid; Grid2View: TcxGridDBTableView; cxGridLevel1: TcxGridLevel; dxBarManager1: TdxBarManager; AddButton: TdxBarLargeButton; EditButton: TdxBarLargeButton; DeleteButton: TdxBarLargeButton; RefreshButton: TdxBarLargeButton; ExitButton: TdxBarLargeButton; SelectButton: TdxBarLargeButton; ViewButton: TdxBarLargeButton; AddPfioButton: TdxBarLargeButton; DeletePfioButton: TdxBarLargeButton; EditPfioButton: TdxBarLargeButton; AddListPfioButton: TdxBarLargeButton; dxBarLargeButton1: TdxBarLargeButton; Search_Button: TdxBarLargeButton; dxBarButton1: TdxBarButton; dxBarButton2: TdxBarButton; dxBarButton3: TdxBarButton; dxBarButton4: TdxBarButton; ActionList1: TActionList; AddAction: TAction; EditAction: TAction; DeleteAction: TAction; RefreshAction: TAction; ExitAction: TAction; ViewAction: TAction; LargeImages: TImageList; DisabledLargeImages: TImageList; PopupMenu1: TdxBarPopupMenu; PopupImageList: TImageList; dxBarPopupMenu1: TdxBarPopupMenu; NAME_DOCUM: TcxGridDBColumn; DATE_DOCUM: TcxGridDBColumn; FIO_Col: TcxGridDBColumn; Summa_Col: TcxGridDBColumn; Styles: TcxStyleRepository; BackGround: TcxStyle; FocusedRecord: TcxStyle; Header: TcxStyle; DesabledRecord: TcxStyle; cxStyle5: TcxStyle; cxStyle6: TcxStyle; cxStyle7: TcxStyle; cxStyle8: TcxStyle; cxStyle9: TcxStyle; cxStyle10: TcxStyle; cxStyle11: TcxStyle; cxStyle12: TcxStyle; cxStyle13: TcxStyle; cxStyle14: TcxStyle; cxStyle15: TcxStyle; cxStyle16: TcxStyle; cxStyle17: TcxStyle; cxStyle18: TcxStyle; cxStyle19: TcxStyle; cxStyle20: TcxStyle; Default_StyleSheet: TcxGridTableViewStyleSheet; DevExpress_Style: TcxGridTableViewStyleSheet; StatusBar: TdxStatusBar; Facul_Col: TcxGridDBColumn; KURS_Col: TcxGridDBColumn; Group_Col: TcxGridDBColumn; DATE_OPL_Col: TcxGridDBColumn; AddAllAvto_Btn: TdxBarLargeButton; PrintButton: TdxBarLargeButton; frxRTFExport1: TfrxRTFExport; frxHTMLExport1: TfrxHTMLExport; frxXLSExport1: TfrxXLSExport; frxPDFExport1: TfrxPDFExport; frxDesigner1: TfrxDesigner; frxDBDataset: TfrxDBDataset; DebugPrintAction: TAction; BarStatic: TdxBarStatic; frxReport: TfrxReport; ID_STATUS_col: TcxGridDBColumn; DeleteAll_Btn: TdxBarLargeButton; frxDBDataset2: TfrxDBDataset; procedure AddButtonClick(Sender: TObject); procedure AddPfioButtonClick(Sender: TObject); procedure EditButtonClick(Sender: TObject); procedure GridViewDblClick(Sender: TObject); procedure DeletePfioButtonClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure DeleteButtonClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure ExitButtonClick(Sender: TObject); procedure RefreshButtonClick(Sender: TObject); procedure AddListPfioButtonClick(Sender: TObject); procedure SelectButtonClick(Sender: TObject); procedure ViewButtonClick(Sender: TObject); procedure AddAllAvto_BtnClick(Sender: TObject); procedure DebugPrintActionExecute(Sender: TObject); procedure PrintButtonClick(Sender: TObject); procedure GridViewCustomDrawCell(Sender: TcxCustomGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean); procedure DeleteAll_BtnClick(Sender: TObject); private PLanguageIndex :byte; DM, DM_Detail_1: TDM_Rap; SpravMode: byte; // 1-отчисление, 2-восстановление // SelectSQL, MasterDetailSQl : string; Id_type_doc: int64; ID_STATUS_Proekt : int64; ID_STATUS_Vipolnen : int64; procedure FormIniLanguage(); public res: Variant; constructor Create(Parameter:TcnSimpleParamsEx); reintroduce; end; var designer_rep:Integer; implementation uses cxCalendar; {$R *.dfm} constructor TfrmRaport.Create(Parameter:TcnSimpleParamsEx); begin Screen.Cursor:=crHourGlass; inherited Create(Parameter.Owner); DM:=TDM_Rap.Create(Self); DM.DB.Handle:=Parameter.DB_Handle; designer_rep:=0; SpravMode := Parameter.TypeDoc; // оперделяю тип документа if SpravMode = 1 then // отчисление begin DM.ReadDataSet.SelectSQL.Text := 'select * from CN_GET_ID_TYPEDOC_OTCHISLENIE'; DM.ReadDataSet.Open; if DM.ReadDataSet['CN_ID_TYPEDOC_OTCHISLENIE'] = null then begin showmessage('Не заполнены системные параметры (CN_ID_TYPEDOC_OTCHISLENIE). Продолжение работы невозможно'); DM.ReadDataSet.Close; exit; end else Id_type_doc := DM.ReadDataSet['CN_ID_TYPEDOC_OTCHISLENIE']; end else // восстановление begin AddListPfioButton.Visible := ivNever; Summa_Col.Visible := false; DATE_OPL_Col.Visible := false; DM.ReadDataSet.SelectSQL.Text := 'select * from CN_GET_ID_TYPEDOC_VOSSTANOVL'; DM.ReadDataSet.Open; if DM.ReadDataSet['CN_ID_TYPEDOC_VOSSTANOVL'] = null then begin showmessage('Не заполнены системные параметры (CN_ID_TYPEDOC_VOSSTANOVL). Продолжение работы невозможно'); exit; DM.ReadDataSet.Close; end else Id_type_doc := DM.ReadDataSet['CN_ID_TYPEDOC_VOSSTANOVL']; end; DM.ReadDataSet.Close; // возможные статусы DM.ReadDataSet.SelectSQL.Text := 'select * from CN_GET_ID_RAP_STATUS_PROEKT'; DM.ReadDataSet.Open; if DM.ReadDataSet['CN_ID_RAP_STATUS_PROEKT'] = null then begin showmessage('Не заполнены системные параметры (CN_ID_RAP_STATUS_PROEKT). Продолжение работы невозможно'); DM.ReadDataSet.Close; exit; end else ID_STATUS_Proekt := DM.ReadDataSet['CN_ID_RAP_STATUS_PROEKT']; DM.ReadDataSet.Close; DM.ReadDataSet.SelectSQL.Text := 'select * from CN_GET_ID_RAP_STATUS_VIPOLNEN'; DM.ReadDataSet.Open; if DM.ReadDataSet['CN_ID_RAP_STATUS_VIPOLNEN'] = null then begin showmessage('Не заполнены системные параметры (CN_ID_RAP_STATUS_VIPOLNEN). Продолжение работы невозможно'); DM.ReadDataSet.Close; exit; end else ID_STATUS_Vipolnen := DM.ReadDataSet['CN_ID_RAP_STATUS_VIPOLNEN']; DM.ReadDataSet.Close; DM.DataSet.SQLs.SelectSQL.Text := 'select * from CN_DT_RAPORT_SELECT(' + inttostr(Id_type_doc) + ')'; DM.DataSet.Open; GridView.DataController.DataSource := DM.DataSource; DM_Detail_1:=TDM_Rap.Create(Self); DM_Detail_1.DataSet.SQLs.SelectSQL.Text := 'SELECT * FROM CN_DT_RAPORT_STUD_SELECT(?ID_DOCUM) order by NAME_FACUL, NAME_GROUP'; DM_Detail_1.DataSet.DataSource:= DM.DataSource; DM_Detail_1.DB.Handle:=Parameter.DB_Handle; DM_Detail_1.DataSet.Open; Grid2View.DataController.DataSource := DM_Detail_1.DataSource; FormIniLanguage; Screen.Cursor:=crDefault; end; procedure TfrmRaport.FormIniLanguage(); begin // индекс языка (1-укр, 2 - рус) PLanguageIndex:= cn_Common_Funcs.cnLanguageIndex(); if SpravMode = 1 then Caption := cnConsts.cn_Main_RaportOtchisl[PLanguageIndex] else Caption := cnConsts.cn_Main_RaportVotanovl[PLanguageIndex]; //названия кнопок AddButton.Caption := cnConsts.cn_InsertBtn_Caption[PLanguageIndex]; EditButton.Caption := cnConsts.cn_EditBtn_Caption[PLanguageIndex]; DeleteButton.Caption := cnConsts.cn_DeleteBtn_Caption[PLanguageIndex]; RefreshButton.Caption := cnConsts.cn_RefreshBtn_Caption[PLanguageIndex]; SelectButton.Caption := cnConsts.cn_Execution[PLanguageIndex]; ExitButton.Caption := cnConsts.cn_ExitBtn_Caption[PLanguageIndex]; ViewButton.Caption := cnConsts.cn_ViewShort_Caption[PLanguageIndex]; PrintButton.Caption:= cnConsts.cn_Print_Caption[PLanguageIndex]; DeleteAll_Btn.Hint:= cn_DelAll_Caption[PLanguageIndex]; //статусбар StatusBar.Panels[0].Text:= cnConsts.cn_InsertBtn_ShortCut[PLanguageIndex] + cnConsts.cn_InsertBtn_Caption[PLanguageIndex]; StatusBar.Panels[1].Text:= cnConsts.cn_EditBtn_ShortCut[PLanguageIndex] + cnConsts.cn_EditBtn_Caption[PLanguageIndex]; StatusBar.Panels[2].Text:= cnConsts.cn_DeleteBtn_ShortCut[PLanguageIndex] + cnConsts.cn_DeleteBtn_Caption[PLanguageIndex]; StatusBar.Panels[3].Text:= cnConsts.cn_RefreshBtn_ShortCut[PLanguageIndex] + cnConsts.cn_RefreshBtn_Caption[PLanguageIndex]; StatusBar.Panels[4].Text:= cnConsts.cn_EnterBtn_ShortCut[PLanguageIndex] + cnConsts.cn_SelectBtn_Caption[PLanguageIndex]; StatusBar.Panels[5].Text:= cnConsts.cn_ExitBtn_ShortCut[PLanguageIndex] + cnConsts.cn_ExitBtn_Caption[PLanguageIndex]; AddPfioButton.Caption := cn_InsertBtn_Caption[PLanguageIndex]; AddPfioButton.Hint := cn_InsertBtn_Caption[PLanguageIndex]; EditPfioButton.Caption := cn_EditBtn_Caption[PLanguageIndex]; EditPfioButton.Hint := cn_EditBtn_Caption[PLanguageIndex]; DeletePfioButton.Caption := cn_DeleteBtn_Caption[PLanguageIndex]; DeletePfioButton.Hint := cn_DeleteBtn_Caption[PLanguageIndex]; AddListPfioButton.Caption := cn_Add_List[PLanguageIndex]; AddListPfioButton.Hint := cn_Add_List[PLanguageIndex]; AddAllAvto_Btn.Hint := cn_RaportAvto[PLanguageIndex]; // grid's NAME_DOCUM.Caption := cn_Name_Column[PLanguageIndex]; DATE_DOCUM.Caption := cn_DateDoc_Pay[PLanguageIndex]; Facul_Col.Caption := cn_footer_Faculty[PLanguageIndex]; FIO_Col.Caption := cn_grid_FIO_Column[PLanguageIndex]; KURS_Col.Caption := cn_footer_Kurs[PLanguageIndex]; Group_Col.Caption := cn_footer_Group[PLanguageIndex]; Summa_Col.Caption := cn_Summa_Column[PLanguageIndex]; DATE_OPL_Col.Caption:= cn_Date_Opl_Column[PLanguageIndex]; end; procedure TfrmRaport.AddButtonClick(Sender: TObject); var ViewForm : TfrmDocs_AE; location : int64; begin ViewForm := TfrmDocs_AE.create(self, PLanguageIndex, DM.DB.Handle, false ); ViewForm.Caption := cn_InsertBtn_Caption[PLanguageIndex]; ViewForm.ID_STATUS := ID_STATUS_Proekt; ViewForm.ID_TYPE_DOCUM := Id_type_doc; DM.ReadDataSet.SelectSQL.Text := 'select * from CN_GET_RAPSTATUS_NAME_BY_ID (' + inttostr(ID_STATUS_Proekt) + ')'; DM.ReadDataSet.Open; ViewForm.Status_Edit.Text := DM.ReadDataSet['NAME']; DM.ReadDataSet.Close; DM.ReadDataSet.SelectSQL.Text := 'select * from CN_GET_TYPEDOCUM_NAME_BY_ID (' + inttostr(Id_type_doc) + ')'; DM.ReadDataSet.Open; ViewForm.TypeDocum_Edit.Text := DM.ReadDataSet['NAME']; DM.ReadDataSet.Close; if ViewForm.ShowModal = mrOk then begin with DM.StProc do begin try StoredProcName := 'CN_DT_RAPORT_INSERT'; Transaction.StartTransaction; ParamByName('NAME_DOCUM').AsString := ViewForm.Num_Doc_Edit.Text; ParamByName('DATE_DOCUM').AsDate := ViewForm.Date_Doc_Edit.Date; ParamByName('ID_STATUS').AsInt64 := ViewForm.ID_STATUS; ParamByName('ID_TYPE_DOCUM').AsInt64 := ViewForm.ID_TYPE_DOCUM; ParamByName('DATE_DEPT').AsDate := ViewForm.DateDept_Edit.Date; ParamByName('ORDER_DATE').AsDate := ViewForm.Order_Date_Edit.Date; ParamByName('ORDER_NUM').AsString := ViewForm.Order_Num_Edit.Text; Prepare; ExecProc; location := ParamByName('ID_DOCUM').AsInt64; Transaction.Commit; Close; except Transaction.Rollback; ShowMessage('Error in stored procedure CN_DT_RAPORT_INSERT'); exit; end; end; DM.DataSet.CloseOpen(true); DM.DataSet.Locate('ID_DOCUM',location,[] ); DM_Detail_1.DataSet.CloseOpen(true); end; end; procedure TfrmRaport.AddPfioButtonClick(Sender: TObject); var ViewForm : TfrmPfio_AE; id_pk_new : int64; begin if GridView.DataController.RecordCount = 0 then exit; if DM.DataSet['ID_STATUS'] = ID_STATUS_Vipolnen then begin showmessage(cn_NotChangeRaport[PLanguageIndex]); exit; end; ViewForm := TfrmPfio_AE.create(self,DM.DB.Handle, PLanguageIndex, Dm.DataSet['DATE_DEPT'], SpravMode); ViewForm.Caption := cn_InsertBtn_Caption[PLanguageIndex]; if ViewForm.ShowModal = mrOk then begin with DM.StProc do begin try StoredProcName := 'CN_DT_RAPORT_STUD_INSERT'; Transaction.StartTransaction; ParamByName('ID_DOCUM').AsInt64 := DM.DataSet['ID_DOCUM']; ParamByName('ID_DOG').AsInt64 := ViewForm.ID_DOG; ParamByName('ID_STUD').AsInt64 := ViewForm.ID_STUD; ParamByName('ID_GROUP').AsInt64 := ViewForm.ID_GROUP; ParamByName('ID_FACUL').AsInt64 := ViewForm.ID_FACUL; ParamByName('SUMMA').AsCurrency := ViewForm.SummaEdit.Value; ParamByName('KURS').AsShort := ViewForm.Kurs; ParamByName('DATE_OPL').AsDate := ViewForm.DateOpl; Prepare; ExecProc; id_pk_new := ParamByName('ID_PK').AsInt64; Transaction.Commit; Close; except Transaction.Rollback; ShowMessage('Error in stored procedure CN_DT_RAPORT_STUD_INSERT'); exit; end; end; DM_Detail_1.DataSet.CloseOpen(true); DM_Detail_1.DataSet.Locate('ID_PK',id_pk_new,[] ); end; end; procedure TfrmRaport.EditButtonClick(Sender: TObject); var ViewForm : TfrmDocs_AE; locateID : int64; begin if GridView.DataController.RecordCount = 0 then exit; if DM.DataSet['ID_STATUS'] = ID_STATUS_Vipolnen then begin showmessage(cn_NotChangeRaport[PLanguageIndex]); exit; end; ViewForm := TfrmDocs_AE.create(self, PLanguageIndex, DM.DB.Handle, false); ViewForm.Caption := cn_EditBtn_Caption[PLanguageIndex]; ViewForm.Num_Doc_Edit.Text := DM.DataSet['NAME_DOCUM']; ViewForm.Date_Doc_Edit.Date := DM.DataSet['DATE_DOCUM']; ViewForm.ID_STATUS := DM.DataSet['ID_STATUS']; ViewForm.ID_TYPE_DOCUM := DM.DataSet['ID_TYPE_DOCUM']; ViewForm.Status_Edit.Text := DM.DataSet['NAME_STATUS']; ViewForm.TypeDocum_Edit.Text := DM.DataSet['NAME_TYPE_DOCUM']; ViewForm.DateDept_Edit.Date := DM.DataSet['DATE_DEPT']; if DM.DataSet['ORDER_DATE'] <> null then ViewForm.Order_Date_Edit.Date:= DM.DataSet['ORDER_DATE']; if DM.DataSet['ORDER_NUM'] <> null then ViewForm.Order_Num_Edit.Text := DM.DataSet['ORDER_NUM']; if ViewForm.ShowModal = mrOk then begin with DM.StProc do begin try StoredProcName := 'CN_DT_RAPORT_UPDATE'; Transaction.StartTransaction; ParamByName('ID_DOCUM').AsInt64 := DM.Dataset['ID_DOCUM']; locateID := DM.Dataset['ID_DOCUM']; ParamByName('NAME_DOCUM').AsString := ViewForm.Num_Doc_Edit.Text; ParamByName('DATE_DOCUM').AsDate := ViewForm.Date_Doc_Edit.Date; ParamByName('ID_STATUS').AsInt64 := ViewForm.ID_STATUS; ParamByName('ID_TYPE_DOCUM').AsInt64:= ViewForm.ID_TYPE_DOCUM; ParamByName('DATE_DEPT').Asdate := ViewForm.DateDept_Edit.Date; ParamByName('ORDER_DATE').AsDate := ViewForm.Order_Date_Edit.Date; ParamByName('ORDER_NUM').AsString := ViewForm.Order_Num_Edit.Text; Prepare; ExecProc; Transaction.Commit; Close; except Transaction.Rollback; ShowMessage('Error in stored procedure CN_DT_RAPORT_UPDATE'); exit; end; end; DM.DataSet.CloseOpen(true); DM_Detail_1.DataSet.CloseOpen(true); DM.DataSet.Locate('ID_DOCUM',locateID, []); end; end; procedure TfrmRaport.GridViewDblClick(Sender: TObject); begin EditButtonClick(Sender); end; procedure TfrmRaport.DeletePfioButtonClick(Sender: TObject); var i: byte; begin if Grid2View.DataController.RecordCount = 0 then exit; if DM.DataSet['ID_STATUS'] = ID_STATUS_Vipolnen then begin showmessage(cn_NotChangeRaport[PLanguageIndex]); exit; end; i:= cn_Common_Messages.cnShowMessage(cnConsts.cn_Confirmation_Caption[PLanguageIndex], cnConsts_Messages.cn_warning_Delete[PLanguageIndex], mtConfirmation, [mbYes, mbNo]); if ((i = 7) or (i= 2)) then exit else begin with DM.StProc do try Transaction.StartTransaction; StoredProcName := 'CN_DT_RAPORT_STUD_DELETE'; Prepare; ParamByName('ID_PK').AsInt64 := DM_Detail_1.DataSet['ID_PK']; ExecProc; Transaction.Commit; except on E:Exception do begin cnShowMessage('Error in CN_DT_RAPORT_STUD_DELETE',e.Message,mtError,[mbOK]); Transaction.Rollback; end; end; DM_Detail_1.DataSet.CloseOpen(true); end; end; procedure TfrmRaport.FormShow(Sender: TObject); begin FormIniLanguage(); end; procedure TfrmRaport.DeleteButtonClick(Sender: TObject); var i: byte; begin if GridView.DataController.RecordCount = 0 then exit; if DM.DataSet['ID_STATUS'] = ID_STATUS_Vipolnen then begin showmessage(cn_NotChangeRaport[PLanguageIndex]); exit; end; if DM_Detail_1.DataSet.RecordCount > 0 then begin showmessage(cnConsts_Messages.cn_NonDeleteDependet[PLanguageIndex]); exit; end; i:= cn_Common_Messages.cnShowMessage(cnConsts.cn_Confirmation_Caption[PLanguageIndex], cnConsts_Messages.cn_warning_Delete[PLanguageIndex], mtConfirmation, [mbYes, mbNo]); if ((i = 7) or (i= 2)) then exit else begin with DM.StProc do try Transaction.StartTransaction; StoredProcName := 'CN_DT_RAPORT_DELETE'; Prepare; ParamByName('ID_DOCUM').AsInt64 := DM.DataSet['ID_DOCUM']; ExecProc; Transaction.Commit; except on E:Exception do begin Transaction.Rollback; end; end; DM.DataSet.CloseOpen(True); DM_Detail_1.DataSet.CloseOpen(True); end; end; procedure TfrmRaport.FormClose(Sender: TObject; var Action: TCloseAction); begin if FormStyle = fsMDIChild then action:=caFree else begin DM.Free; DM_Detail_1.Free; end; end; procedure TfrmRaport.ExitButtonClick(Sender: TObject); begin close; end; procedure TfrmRaport.RefreshButtonClick(Sender: TObject); begin DM.DataSet.CloseOpen(True); DM_Detail_1.DataSet.CloseOpen(True); end; procedure TfrmRaport.AddListPfioButtonClick(Sender: TObject); var AParameter:TcnSimpleParamsEx; res: Variant; cnt, i: integer; CnCalcOut : TCnCalcOut; cnCalcIn: TcnCalcIn; CnPayOut : TCnPayOut; cnPayIn: TcnPayIn; begin if GridView.DataController.RecordCount = 0 then exit; if DM.DataSet['ID_STATUS'] = ID_STATUS_Vipolnen then begin showmessage(cn_NotChangeRaport[PLanguageIndex]); exit; end; // вызов справочника AParameter:= TcnSimpleParamsEx.Create; AParameter.Owner:=self; AParameter.Db_Handle:= DM.DB.Handle; AParameter.Formstyle:=fsNormal; AParameter.WaitPakageOwner:=self; AParameter.ReturnMode := 'Multy'; Res:= null; Res:= RunFunctionFromPackage(AParameter, 'Contracts\cn_sp_ContractsList.bpl','ShowSPContractsList'); if VarArrayDimCount(res)>0 then begin cnt:=VarArrayHighBound(res,1)-VarArrayLowBound(res,1); for i:=0 to cnt do begin with DM.StProc do try // сначала рассчитываю сумму и дату оплаты // рассчитывается на дату. указанную в документе // cn_pay cnPayIn.Owner := self; cnPayIn.DB_Handle := DM.DB.Handle; cnPayIn.ID_STUD := res[i][1]; cnPayIn.BEG_CHECK := strtodate('01.01.1900'); cnPayIn.END_CHECK := Dm.DataSet['DATE_DEPT']; cnPayIn.DATE_PROV_CHECK := 1; cnPayIn.IS_DOC_GEN := 0; cnPayIn.IS_PROV_GEN := 0; cnPayIn.IS_SMET_GEN := 0; cnPayIn.NOFPROV := 1; cnPayIn.DIGNORDOCID := 1; CnPayOut := GetCnPay(cnPayIn); // cn_calc cnCalcIn.Owner := self; cnCalcIn.DB_Handle := DM.DB.Handle; cnCalcIn.ID_STUD := res[i][1]; cnCalcIn.BEG_CHECK := strtodate('01.01.1900'); cnCalcIn.END_CHECK := Dm.DataSet['DATE_DEPT']; cnCalcIn.CNUPLSUM := CnPayOut.CNSUMDOC; CnCalcOut := GetCnCalc(cnCalcIn); //далее вношу записи в базу Transaction.StartTransaction; StoredProcName := 'CN_DT_RAPORT_STUD_INSERT'; Prepare; ParamByName('ID_DOCUM').AsInt64 := DM.DataSet['ID_DOCUM']; ParamByName('ID_DOG').AsInt64 := res[i][0]; ParamByName('ID_STUD').AsInt64 := res[i][1]; ParamByName('ID_FACUL').AsInt64 := res[i][2]; ParamByName('ID_GROUP').AsInt64 := res[i][3]; if CnPayOut.CNUPLSUM > CnPayOut.CNSUMDOC then ParamByName('SUMMA').AsCurrency := CnCalcOut.CN_SNEED - CnPayOut.CNUPLSUM else ParamByName('SUMMA').AsCurrency := CnCalcOut.CN_SNEED - CnPayOut.CNSUMDOC; ParamByName('KURS').AsShort := res[i][4]; ParamByName('DATE_OPL').AsDate := CnCalcOut.CNDATEOPL; ExecProc; Transaction.Commit; except on E:Exception do begin cnShowMessage('Error in CN_DT_RAPORT_STUD_INSERT',e.Message,mtError,[mbOK]); Transaction.Rollback; end; end; end; DM_Detail_1.DataSet.CloseOpen(true); end; end; procedure TfrmRaport.SelectButtonClick(Sender: TObject); var i: integer; cnAnnulContractIn :TcnAnnulContractIn; ID_DOG_as_int, ID_STUD_as_int, CN_ORDERTYPE_OTCHISLENIE, CN_ORDERTYPE_VOSSTANOVL: int64; begin if DM.DataSet['ID_STATUS'] = ID_STATUS_Vipolnen then begin showmessage(cn_NotChangeRaport[PLanguageIndex]); exit; end; if Grid2View.DataController.RecordCount = 0 then exit; i:= cn_Common_Messages.cnShowMessage(cnConsts.cn_Confirmation_Caption[PLanguageIndex], cnConsts_Messages.cn_warning_Execute[PLanguageIndex], mtConfirmation, [mbYes, mbNo]); if ((i = 7) or (i= 2)) then exit; DM_Detail_1.DataSet.First; if SpravMode =1 then begin Dm.ReadDataSet.Close; Dm.ReadDataSet.SelectSQL.Clear; Dm.ReadDataSet.SelectSQL.Text := 'select CN_ORDERTYPE_OTCHISLENIE from CN_PUB_SYS_DATA_GET_ALL'; Dm.ReadDataSet.Open; CN_ORDERTYPE_OTCHISLENIE := Dm.ReadDataSet['CN_ORDERTYPE_OTCHISLENIE']; Dm.ReadDataSet.Close; for i:=0 to DM_Detail_1.DataSet.RecordCount-1 do begin ID_DOG_as_int := DM_Detail_1.DataSet['ID_DOG']; ID_STUD_as_int:= DM_Detail_1.DataSet['ID_STUD']; // определяю параметры для разрыва DM.ReadDataSet.SelectSQL.Text := 'select * from CN_ANNUL_CONTRACT_PREPARE(' + IntToStr(ID_DOG_as_int)+ ','+ IntToStr(ID_STUD_as_int)+ ')'; DM.ReadDataSet.Open; cnAnnulContractIn.Owner := self; cnAnnulContractIn.DB_Handle := Dm.DB.Handle; cnAnnulContractIn.ID_DOG_ROOT := DM.ReadDataSet['ID_DOG_ROOT']; cnAnnulContractIn.ID_DOG := DM_Detail_1.DataSet['ID_DOG']; cnAnnulContractIn.ID_STUD := DM_Detail_1.DataSet['ID_STUD']; cnAnnulContractIn.DATE_DISS := DM.DataSet['DATE_DEPT']; cnAnnulContractIn.ID_TYPE_DISS:= DM.ReadDataSet['CN_ID_TYPE_DISS_FOR_RAPORT']; cnAnnulContractIn.ORDER_DATE := DM.DataSet['ORDER_DATE']; cnAnnulContractIn.ORDER_NUM := DM.DataSet['ORDER_NUM']; cnAnnulContractIn.COMMENT := 'Авто розірвання за рапортом на відрахування'; cnAnnulContractIn.IS_COLLECT := DM.ReadDataSet['IS_COLLECT']; DM.ReadDataSet.close; // разрываю контракт DoAnnulContract(cnAnnulContractIn); // пишу приказ об отчислении with DM.StProc do begin try StoredProcName := 'CN_DT_ORDERS_INSERT'; Transaction.StartTransaction; Prepare; ParamByName('ID_ORDER').AsInt64 := CN_ORDERTYPE_OTCHISLENIE; ParamByName('ID_STUD').AsInt64 := DM_Detail_1.DataSet['ID_STUD']; ParamByName('DATE_ORDER').AsDate := DM.DataSet['ORDER_DATE']; ParamByName('NUM_ORDER').AsString := DM.DataSet['ORDER_NUM']; ParamByName('COMMENTS').AsString := 'автоматичне додавання наказу при роботі з рапортами на відрахування'; ExecProc; Transaction.Commit; Close; except Transaction.Rollback; ShowMessage('Error in stored procedure CN_DT_ORDERS_INSERT'); exit; end; end; DM_Detail_1.DataSet.Next; end; end else // восстановление begin Dm.ReadDataSet.Close; Dm.ReadDataSet.SelectSQL.Clear; Dm.ReadDataSet.SelectSQL.Text := 'select CN_ORDERTYPE_VOSSTANOVL from CN_PUB_SYS_DATA_GET_ALL'; Dm.ReadDataSet.Open; CN_ORDERTYPE_VOSSTANOVL := Dm.ReadDataSet['CN_ORDERTYPE_VOSSTANOVL']; Dm.ReadDataSet.Close; for i:=0 to DM_Detail_1.DataSet.RecordCount-1 do begin ID_DOG_as_int := DM_Detail_1.DataSet['ID_DOG']; ID_STUD_as_int:= DM_Detail_1.DataSet['ID_STUD']; // определяю параметры для восстановления DM.ReadDataSet.SelectSQL.Text := 'select * from CN_GET_ID_DOG_ROOT(' + IntToStr(ID_DOG_as_int)+ ','+ IntToStr(ID_STUD_as_int)+ ')'; DM.ReadDataSet.Open; with DM.StProc do begin try StoredProcName := 'CN_DT_CONTRACT_RECOVERY'; Transaction.StartTransaction; Prepare; ParamByName('ID_DOG_ROOT').AsInt64 := DM.ReadDataSet['ID_DOG_ROOT']; ParamByName('ID_DOG').AsInt64 := ID_DOG_as_int; ParamByName('ID_STUD').AsInt64 := ID_STUD_as_int; ExecProc; Transaction.Commit; Close; except Transaction.Rollback; ShowMessage('Error in stored procedure CN_DT_CONTRACT_RECOVERY'); exit; end; end; DM.ReadDataSet.close; // пишу приказ о восстановлении with DM.StProc do begin try StoredProcName := 'CN_DT_ORDERS_INSERT'; Transaction.StartTransaction; Prepare; ParamByName('ID_ORDER').AsInt64 := CN_ORDERTYPE_VOSSTANOVL; ParamByName('ID_STUD').AsInt64 := DM_Detail_1.DataSet['ID_STUD']; ParamByName('DATE_ORDER').AsDate := DM.DataSet['ORDER_DATE']; ParamByName('NUM_ORDER').AsString := DM.DataSet['ORDER_NUM']; ParamByName('COMMENTS').AsString := 'автоматичне додавання наказу при роботі з рапортами на відновлення'; ExecProc; Transaction.Commit; Close; except Transaction.Rollback; ShowMessage('Error in stored procedure CN_DT_ORDERS_INSERT'); exit; end; end; DM_Detail_1.DataSet.Next; end; end; with DM.StProc do begin try StoredProcName := 'CN_DT_RAPORT_UPT_VIPOLNEN'; Transaction.StartTransaction; ParamByName('ID_DOCUM').AsInt64 := DM.Dataset['ID_DOCUM']; ParamByName('ID_STATUS').AsInt64 := ID_STATUS_Vipolnen; Prepare; ExecProc; Transaction.Commit; Close; except Transaction.Rollback; ShowMessage('Error in stored procedure CN_DT_RAPORT_UPT_VIPOLNEN'); exit; end; end; DM.DataSet.CloseOpen(true); DM_Detail_1.DataSet.CloseOpen(true); end; procedure TfrmRaport.ViewButtonClick(Sender: TObject); var ViewForm :TfrmDocs_AE; begin if GridView.DataController.RecordCount = 0 then exit; ViewForm := TfrmDocs_AE.create(self, PLanguageIndex, DM.DB.Handle, true); ViewForm.Caption := cn_EditBtn_Caption[PLanguageIndex]; ViewForm.Num_Doc_Edit.Text := DM.DataSet['NAME_DOCUM']; ViewForm.Date_Doc_Edit.Date := DM.DataSet['DATE_DOCUM']; ViewForm.ID_STATUS := DM.DataSet['ID_STATUS']; ViewForm.ID_TYPE_DOCUM := DM.DataSet['ID_TYPE_DOCUM']; ViewForm.Status_Edit.Text := DM.DataSet['NAME_STATUS']; ViewForm.TypeDocum_Edit.Text := DM.DataSet['NAME_TYPE_DOCUM']; ViewForm.DateDept_Edit.Date := DM.DataSet['DATE_DEPT']; if DM.DataSet['ORDER_DATE'] <> null then ViewForm.Order_Date_Edit.Date:= DM.DataSet['ORDER_DATE']; if DM.DataSet['ORDER_NUM'] <> null then ViewForm.Order_Num_Edit.Text := DM.DataSet['ORDER_NUM']; ViewForm.ShowModal; end; procedure TfrmRaport.AddAllAvto_BtnClick(Sender: TObject); var ViewForm : TfrmAddAll; begin if GridView.DataController.RecordCount = 0 then exit; if DM.DataSet['ID_STATUS'] = ID_STATUS_Vipolnen then begin showmessage(cn_NotChangeRaport[PLanguageIndex]); exit; end; ViewForm := TfrmAddAll.Create(self,DM.DB.Handle, PLanguageIndex, Dm.DataSet['DATE_DEPT'], Dm.DataSet['ID_DOCUM'], SpravMode); ViewForm.Caption := cn_InsertBtn_Caption[PLanguageIndex]; ViewForm.DateDocumVosst := Dm.DataSet['DATE_DOCUM']; ViewForm.ShowModal; DM_Detail_1.DataSet.CloseOpen(true); ViewForm.Free; end; procedure TfrmRaport.DebugPrintActionExecute(Sender: TObject); begin if designer_rep=0 then begin designer_rep:=1; BarStatic.Caption:='Режим отладки отчетов'; end else begin designer_rep:=0; BarStatic.Caption:=''; end; end; procedure TfrmRaport.PrintButtonClick(Sender: TObject); var ID_NAMEREP : int64; begin frxReport.Clear; if SpravMode = 1 then frxReport.LoadFromFile(ExtractFilePath(Application.ExeName)+'Reports\Contracts\'+'cn_che_RaportOtchisl'+'.fr3') else frxReport.LoadFromFile(ExtractFilePath(Application.ExeName)+'Reports\Contracts\'+'cn_che_RaportVosstanovl'+'.fr3'); frxReport.Variables.Clear; Dm.ReadDataSet.Close; Dm.ReadDataSet.SelectSQL.Clear; Dm.ReadDataSet.SelectSQL.Text := 'select * from CN_FR_RAPORT_GET_ATRIBUTES'; Dm.ReadDataSet.Open; frxReport.Variables['CN_FR_UNIVER'] := ''''+ Dm.ReadDataSet['CN_FR_UNIVER'] +''''; frxReport.Variables['CN_FR_REKTOR'] := ''''+ Dm.ReadDataSet['CN_FR_REKTOR'] +''''; frxReport.Variables['CN_FR_UNIVER_NAME']:= ''''+ Dm.ReadDataSet['CN_FR_UNIVER_NAME']+''''; Dm.ReadDataSet.Close; frxReport.Variables['DATE_DOCUM']:= ''''+ datetostr(DM.DataSet['DATE_DOCUM'])+''''; Dm.ReadDataSet.Close; Dm.ReadDataSet.SelectSQL.Clear; Dm.ReadDataSet.SelectSQL.Text := 'select CN_NAMEZVIT_RAP_NA_OTCHISL from CN_PUB_SYS_DATA_GET_ALL'; Dm.ReadDataSet.Open; if Dm.ReadDataSet['CN_NAMEZVIT_RAP_NA_OTCHISL'] <> null then ID_NAMEREP := Dm.ReadDataSet['CN_NAMEZVIT_RAP_NA_OTCHISL']; Dm.ReadDataSet.Close; Dm.ReadDataSet.Close; Dm.ReadDataSet.SelectSQL.Clear; Dm.ReadDataSet.SelectSQL.Text := 'select * from CN_FR_GET_SIGNATURES(' + inttostr(ID_NAMEREP) + ')'; Dm.ReadDataSet.Open; Dm.ReadDataSet.FetchAll; frxDBDataset.DataSet := DM_Detail_1.DataSet; frxDBDataset2.DataSet := Dm.ReadDataSet; frxReport.PrepareReport(true); frxReport.ShowReport; if designer_rep=1 then begin frxReport.DesignReport; end; Dm.ReadDataSet.Close; end; procedure TfrmRaport.GridViewCustomDrawCell(Sender: TcxCustomGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean); var Arect:TRect; begin if ((AViewInfo.GridRecord.Values[2]= ID_STATUS_Vipolnen) and (not AViewInfo.GridRecord.Focused )) then begin Arect:=AViewInfo.Bounds; ACanvas.Canvas.Brush.Color:=$00AEA4DF; ACanvas.Canvas.FillRect(Arect); end; if ((AViewInfo.GridRecord.Values[2]= ID_STATUS_Vipolnen) and (AViewInfo.GridRecord.Focused )) then begin Arect:=AViewInfo.Bounds; ACanvas.Canvas.Brush.Color:=$007968CA; ACanvas.Canvas.FillRect(Arect); end; end; procedure TfrmRaport.DeleteAll_BtnClick(Sender: TObject); var i: byte; begin if Grid2View.DataController.RecordCount = 0 then exit; if DM.DataSet['ID_STATUS'] = ID_STATUS_Vipolnen then begin showmessage(cn_NotChangeRaport[PLanguageIndex]); exit; end; i:= cn_Common_Messages.cnShowMessage(cnConsts.cn_Confirmation_Caption[PLanguageIndex], cnConsts_Messages.cn_warning_Execute[PLanguageIndex], mtConfirmation, [mbYes, mbNo]); if ((i = 7) or (i= 2)) then exit else begin with DM.StProc do try Transaction.StartTransaction; StoredProcName := 'CN_DT_RAPORT_STUD_DELETE_ALL'; Prepare; ParamByName('ID_DOCUM').AsInt64 := DM.DataSet['ID_DOCUM']; ExecProc; Transaction.Commit; except on E:Exception do begin cnShowMessage('Error in CN_DT_RAPORT_STUD_DELETE_ALL',e.Message,mtError,[mbOK]); Transaction.Rollback; end; end; DM_Detail_1.DataSet.CloseOpen(true); end; end; end.
{ SuperMaximo GameLibrary : Audio unit by Max Foster License : http://creativecommons.org/licenses/by/3.0/ } unit Audio; {$mode objfpc}{$H+} interface //Initialise audio, with a specific number of audio channels procedure initAudio(channels : word = 16); procedure quitAudio; //Set a sound channel to simulate coming from a certain position in 3D space procedure soundPosition(channel : integer; angle : integer = 90; distance : integer = 0); //Set the music volume (0-100) procedure musicVolume(percentage : integer); procedure pauseMusic; procedure resumeMusic; procedure restartMusic; procedure stopMusic; procedure fadeMusic(time : longint);//Fade out the music within a time period implementation uses SDL_mixer, SoundClass; procedure initAudio(channels : word = 16); begin Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 4096); allocateSoundChannels(channels); end; procedure quitAudio; begin Mix_CloseAudio; end; procedure soundPosition(channel : integer; angle : integer = 90; distance : integer = 0); begin Mix_SetPosition(channel, angle, distance); end; procedure musicVolume(percentage : integer); begin Mix_VolumeMusic(round((MIX_MAX_VOLUME/100)*percentage)); end; procedure pauseMusic; begin Mix_PauseMusic(); end; procedure resumeMusic; begin Mix_ResumeMusic(); end; procedure restartMusic; begin Mix_RewindMusic(); end; procedure stopMusic; begin Mix_HaltMusic(); end; procedure fadeMusic(time : longint); begin Mix_FadeOutMusic(time); end; end.
unit EcranElevage; interface uses Variables; { Affichage de l'écran et appel des fonctions & procédures associées } procedure afficher(Joueur : TJoueur); { Vérifie l'état d'avancement d'une construction et met à jour les variables une fois celle-ci terminée. } procedure majConstruction(Joueur : TJoueur); { Vérifie l'état d'avancement de la croissance de l'élevage et met à jour les variables une fois celle-ci achevée } procedure majCroissance(Joueur : TJoueur); implementation uses GestionEcran, OptnAffichage, EcranTribu; { Lance la construction d'un bâtiment (Universite, CDR, Laboratoire, Enclos) } procedure construire(Joueur : TJoueur ; nomBatiment : String); var sommeNiveau : Integer; // Somme du niveau de chaque bâtiment begin { Si aucune construction n'est en cours } if getElevage(Joueur).construction = False then begin // Calcul de la somme du niveau de chaque bâtiment sommeNiveau := getUniversite(Joueur).niveau + getCDR(Joueur).niveau + getLaboratoire(Joueur).niveau + getEnclos(Joueur).niveau + getBibliotheque(Joueur).niveau + getArchives(Joueur).niveau; { Si la somme du niveau de chaque bâtiment est inférieure à la population } if (sommeNiveau < getElevage(Joueur).population) then begin // Université if nomBatiment = 'Universite' then begin { Si le bâtiment n'est pas déjà au niveau maximum } if (getUniversite(Joueur).niveau < getTribu(Joueur).niveauMax) then begin setElevage_construction(Joueur, True); setUniversite_construction(Joueur, True); setMessage('Construction lancée'); end else setMessage('Ce bâtiment est déjà au niveau maximum'); end; // Centre de recherches if nomBatiment = 'CDR' then begin { Si le bâtiment n'est pas déjà au niveau maximum } if (getCDR(Joueur).niveau < getTribu(Joueur).niveauMax) then begin setElevage_construction(Joueur, True); setCDR_construction(Joueur, True); setMessage('Construction lancée'); end else setMessage('Ce bâtiment est déjà au niveau maximum'); end; // Laboratoire if nomBatiment = 'Laboratoire' then begin { Si le bâtiment n'est pas déjà au niveau maximum } if (getLaboratoire(Joueur).niveau < getTribu(Joueur).niveauMax) then begin setElevage_construction(Joueur, True); setLaboratoire_construction(Joueur, True); setMessage('Construction lancée'); end else setMessage('Ce bâtiment est déjà au niveau maximum'); end; // Enclos if nomBatiment = 'Enclos' then begin { Si le bâtiment n'est pas déjà au niveau maximum } if (getEnclos(Joueur).niveau < getTribu(Joueur).niveauMax) then begin setElevage_construction(Joueur, True); setEnclos_construction(Joueur, True); setMessage('Construction lancée'); end else setMessage('Ce bâtiment est déjà au niveau maximum'); end; // Bibliothèque if nomBatiment = 'Bibliothèque' then begin { Si le bâtiment n'est pas déjà au niveau maximum } if (getBibliotheque(Joueur).niveau < getTribu(Joueur).niveauMax) then begin setElevage_construction(Joueur, True); setBibliotheque_construction(Joueur, True); setMessage('Construction lancée'); end else setMessage('Ce bâtiment est déjà au niveau maximum'); end; // Archives if nomBatiment = 'Archives' then begin { Si le bâtiment n'est pas déjà au niveau maximum } if (getArchives(Joueur).niveau < getTribu(Joueur).niveauMax) then begin setElevage_construction(Joueur, True); setArchives_construction(Joueur, True); setMessage('Construction lancée'); end else setMessage('Ce bâtiment est déjà au niveau maximum'); end; end else setMessage('Population insuffisante'); end else setMessage('Une construction est déjà en cours'); end; { Remet à 0 les variables liées à la construction } procedure reinitConstruction(Joueur : TJoueur); begin setElevage_construction(Joueur, False); setElevage_equationsResolues(Joueur, 0); setUniversite_construction(Joueur, False); setCDR_construction(Joueur, False); setLaboratoire_construction(Joueur, False); setEnclos_construction(Joueur, False); setBibliotheque_construction(Joueur, False); end; { Vérifie l'état d'avancement d'une construction et met à jour les variables une fois celle-ci terminée. } procedure majConstruction(Joueur : TJoueur); begin { Si une construction (encore indéterminée) est en cours } if getElevage(Joueur).construction = True then begin { On détermine d'abord quel bâtiment est en construction. Ensuite on regarde si le travail accumulé est suffisant pour passer au niveau supérieur. Dans le cas d'un passage au niveau supérieur, on met à jour le niveau du bâtiment et les bonus liés, et on réinitialise l'état de construction. } { Si la construction de l'UNIVERSITE est en cours } if getUniversite(Joueur).construction = True then begin { Si les équations résolues sont suffisantes pour passer au niveau suivant } if getElevage(Joueur).equationsResolues >= getUniversite(Joueur).PALIERS[getUniversite(Joueur).niveau+1] then begin setUniversite_niveau(Joueur, getUniversite(Joueur).niveau + 1 ); setElevage_savoirJourAbsolu(Joueur, getElevage(Joueur).savoirJourAbsolu + getUniversite(Joueur).BONUS[getUniversite(Joueur).niveau] ); setElevage_savoirJour(Joueur, round( getElevage(Joueur).savoirJourAbsolu * getElevage(Joueur).facteurBonheur )); reinitConstruction(Joueur); end; end; { Si la construction du LABORATOIRE est en cours } if getLaboratoire(Joueur).construction = True then begin { Si les équations résolues sont suffisantes pour passer au niveau suivant } if getElevage(Joueur).equationsResolues >= getLaboratoire(Joueur).PALIERS[getLaboratoire(Joueur).niveau+1] then begin setLaboratoire_niveau(Joueur, getLaboratoire(Joueur).niveau + 1 ); setElevage_equationsJour(Joueur, round(( getElevage(Joueur).population*10 + getLaboratoire(Joueur).BONUS[getLaboratoire(Joueur).niveau] + getCDR(Joueur).BONUS[getCDR(Joueur).niveau] ) * getElevage(Joueur).facteurBonheur) ); reinitConstruction(Joueur); end; end; { Si la construction du CDR est en cours } if getCDR(Joueur).construction = True then begin { Si les équations résolues sont suffisantes pour passer au niveau suivant } if getElevage(Joueur).equationsResolues >= getCDR(Joueur).PALIERS[getCDR(Joueur).niveau+1] then begin setCDR_niveau(Joueur, getCDR(Joueur).niveau + 1 ); setElevage_equationsJour(Joueur, round(( getElevage(Joueur).population*10 + getLaboratoire(Joueur).BONUS[getLaboratoire(Joueur).niveau] + getCDR(Joueur).BONUS[getCDR(Joueur).niveau] ) * getElevage(Joueur).facteurBonheur) ); reinitConstruction(Joueur); end; end; { Si la construction de l'ENCLOS est en cours } if getEnclos(Joueur).construction = True then begin { Si les équations résolues sont suffisantes pour passer au niveau suivant } if getElevage(Joueur).equationsResolues >= getEnclos(Joueur).PALIERS[getEnclos(Joueur).niveau+1] then begin setEnclos_niveau(Joueur, getEnclos(Joueur).niveau + 1 ); setTribu_ptsRecrutementJour(Joueur, getEnclos(Joueur).BONUS[getEnclos(Joueur).niveau]); reinitConstruction(Joueur); end; end; { Si la construction de la BIBLIOTHÈQUE est en cours } if getBibliotheque(Joueur).construction = True then begin { Si les équations résolues sont suffisantes pour passer au niveau suivant } if getElevage(Joueur).equationsResolues >= getBibliotheque(Joueur).PALIERS[getBibliotheque(Joueur).niveau+1] then begin setBibliotheque_niveau(Joueur, getBibliotheque(Joueur).niveau+1); // L'archétype ANALYSTE bénéficie d'un bonheur constant (100%) if getTribu(Joueur).archetype <> 'Géomètre' then begin setElevage_bonheur(Joueur, getBibliotheque(Joueur).BONUS[getBibliotheque(Joueur).niveau]); setElevage_facteurBonheur(Joueur, 1 - getElevage(Joueur).population/10 + getElevage(Joueur).bonheur/10); end; setElevage_savoirJourAbsolu(Joueur, getElevage(Joueur).savoirJourAbsolu + getUniversite(Joueur).BONUS[getUniversite(Joueur).niveau] ); setElevage_savoirJour(Joueur, round( getElevage(Joueur).savoirJourAbsolu * getElevage(Joueur).facteurBonheur )); setElevage_equationsJour(Joueur, round(( getElevage(Joueur).population*10 + getLaboratoire(Joueur).BONUS[getLaboratoire(Joueur).niveau] + getCDR(Joueur).BONUS[getCDR(Joueur).niveau] ) * getElevage(Joueur).facteurBonheur) ); reinitConstruction(Joueur); end; end; { Si la construction des ARCHIVES est en cours } if getArchives(Joueur).construction = True then begin { Si les équations résolues sont suffisantes pour passer au niveau suivant } if getElevage(Joueur).equationsResolues >= getArchives(Joueur).PALIERS[getArchives(Joueur).niveau+1] then begin setArchives_niveau(Joueur, getArchives(Joueur).niveau+1); setTribu_limDefaites(Joueur, getArchives(Joueur).BONUS[getArchives(Joueur).niveau]); reinitConstruction(Joueur); end; end; end; end; { Vérifie l'état d'avancement de la croissance de l'élevage et met à jour les variables une fois celle-ci achevée } procedure majCroissance(Joueur : TJoueur); begin { Calcul du savoir/j à partir du savoir/j absolu } setElevage_savoirJour(Joueur, round( ( getElevage(Joueur).savoirJourAbsolu - getElevage(Joueur).population*10 ) * getElevage(Joueur).facteurBonheur ) ); { Si le savoir acquis permet de croître en population } if getElevage(Joueur).savoirAcquis >= getElevage(Joueur).seuilCroissance then begin setElevage_savoirAcquis(Joueur, 0); setElevage_population(Joueur, getElevage(Joueur).population + 1); // L'archétype ANALYSTE bénéficie d'un bonheur constant (100%) if getTribu(Joueur).archetype <> 'Géomètre' then begin setElevage_facteurBonheur(Joueur, 1 - getElevage(Joueur).population/10 + getElevage(Joueur).bonheur/10); end; setElevage_savoirJour(Joueur, round( ( getElevage(Joueur).savoirJourAbsolu - getElevage(Joueur).population*10 ) * getElevage(Joueur).facteurBonheur ) ); setElevage_equationsJour(Joueur, round( ( getElevage(Joueur).population*10 + getLaboratoire(Joueur).BONUS[getLaboratoire(Joueur).niveau] + getCDR(Joueur).BONUS[getCDR(Joueur).niveau] ) * getElevage(Joueur).facteurBonheur ) ); setElevage_seuilCroissance(Joueur, getElevage(Joueur).population * getElevage(Joueur).facteurCroissance); end; { Permet de passer directement à une croissance nulle ; évite la division par 0 dans le calcul suivant } if getElevage(Joueur).savoirJour = 0 then setElevage_nbJourAvCroissance(Joueur, 0) else setElevage_nbJourAvCroissance(Joueur, ( getElevage(Joueur).seuilCroissance - getElevage(Joueur).savoirAcquis + ( getElevage(Joueur).seuilCroissance mod getElevage(Joueur).savoirJour)) div getElevage(Joueur).savoirJour ) end; { Affiche la liste des bâtiments construits aux coordonnées (x,y) } procedure afficherBatimentsConstruits(Joueur : TJoueur ; x,y : Integer); begin deplacerCurseurXY(x,y); write('Bâtiments construits :'); deplacerCurseurXY(x,y+1); write('¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯'); { On regarde simplement quel bâtiment est construit (niveau > 0) et on affiche son nom et son niveau. } // Université if getUniversite(Joueur).niveau > 0 then begin deplacerCurseurXY(x+2,y+2); write('- Université (niv ', getUniversite(Joueur).niveau,')'); end; // Centre de recherches if getCDR(Joueur).niveau > 0 then begin deplacerCurseurXY(x+2,y+3); write('- Centre de recherches (niv ', getCDR(Joueur).niveau,')'); end; // Laboratoire if getLaboratoire(Joueur).niveau > 0 then begin deplacerCurseurXY(x+2,y+4); write('- Laboratoire (niv ', getLaboratoire(Joueur).niveau,')'); end; // Enclos if getEnclos(Joueur).niveau > 0 then begin deplacerCurseurXY(x+2,y+5); write('- Enclos (niv ', getEnclos(Joueur).niveau,')'); end; // Bibliothèque if getBibliotheque(Joueur).niveau > 0 then begin deplacerCurseurXY(x+2,y+6); write('- Bibliothèque (niv ', getBibliotheque(Joueur).niveau,')'); end; // Archives if getArchives(Joueur).niveau > 0 then begin deplacerCurseurXY(x+2,y+7); write('- Archives (niv ', getArchives(Joueur).niveau,')'); end; end; { Affiche la liste des bonus accumulés aux coordonnées (x,y) } procedure afficherBonus(Joueur : TJoueur ; x,y : Integer); begin deplacerCurseurXY(x,y); write('Bonus accumulés :'); deplacerCurseurXY(x,y+1); write('¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯'); { Chaque bonus s'affiche en gris s'il est nul ou False et en vert s'il est positif ou True. } // Savoir/j deplacerCurseurXY(x+2,y+2); write('Savoir/j : '); if getUniversite(Joueur).BONUS[getUniversite(Joueur).niveau] = 0 then couleurTexte(8) else couleurTexte(10); write('+ ', getUniversite(Joueur).BONUS[getUniversite(Joueur).niveau]); couleurTexte(15); // Equations/j deplacerCurseurXY(x+2,y+3); write('Équations/j : '); if getCDR(Joueur).BONUS[getCDR(Joueur).niveau] + getLaboratoire(Joueur).BONUS[getLaboratoire(Joueur).niveau] = 0 then couleurTexte(8) else couleurTexte(10); write('+ ', getCDR(Joueur).BONUS[getCDR(Joueur).niveau] + getLaboratoire(Joueur).BONUS[getLaboratoire(Joueur).niveau]); couleurTexte(15); // Points de bonheur deplacerCurseurXY(x+2,y+4); write('Bonheur : '); if getBibliotheque(Joueur).BONUS[getBibliotheque(Joueur).niveau] = 0 then couleurTexte(8) else couleurTexte(10); write(getBibliotheque(Joueur).BONUS[getBibliotheque(Joueur).niveau], ' points'); couleurTexte(15); // Points de recrutement deplacerCurseurXY(x+2,y+5); write('Recrutement : '); if getEnclos(Joueur).BONUS[getEnclos(Joueur).niveau] = 0 then couleurTexte(8) else couleurTexte(10); write(getEnclos(Joueur).BONUS[getEnclos(Joueur).niveau], ' points'); couleurTexte(15); // Lamas deplacerCurseurXY(x+2,y+6); write('Lamas : '); if getEnclos(Joueur).niveau > 0 then begin couleurTexte(10); write('Déverouillés'); end else begin couleurtexte(8); write('Verouillés'); end; couleurtexte(15); // Alpagas deplacerCurseurXY(x+2,y+7); write('Alpagas : '); if getCDR(Joueur).niveau >= 1 then begin couleurTexte(10); write('Déverouillés'); end else begin couleurtexte(8); write('Verouillés'); end; couleurtexte(15); // Guanacos deplacerCurseurXY(x+2,y+8); write('Guanacos : '); if getCDR(Joueur).niveau >= 2 then begin couleurTexte(10); write('Déverouillés'); end else begin couleurtexte(8); write('Verouillés'); end; couleurtexte(15); end; { Récupère le choix du joueur et détermine l'action à effectuer } procedure choisir(Joueur : TJoueur); var choix : String; // Valeur entrée par la joueur begin { Déplace le curseur dans le cadre "Action" } deplacerCurseurXY(114,26); readln(choix); { Liste des choix disponibles } if (choix = '1') then begin construire(Joueur, 'Universite'); majConstruction(Joueur); afficher(Joueur); end; if (choix = '2') then begin construire(Joueur, 'CDR'); majConstruction(Joueur); afficher(Joueur); end; if (choix = '3') then begin construire(Joueur, 'Laboratoire'); majConstruction(Joueur); afficher(Joueur); end; if (choix = '4') then begin construire(Joueur, 'Enclos'); majConstruction(Joueur); afficher(Joueur); end; if (choix = '5') then begin construire(Joueur, 'Bibliothèque'); majConstruction(Joueur); afficher(Joueur); end; if (choix = '6') then begin construire(Joueur, 'Archives'); majConstruction(Joueur); afficher(Joueur); end; if (choix = '0') then begin EcranTribu.afficher(Joueur); end { Valeur saisie invalide } else begin setMessage('Action non reconnue'); afficher(Joueur); end; end; { Affichage de l'écran et appel des fonctions & procédures associées } procedure afficher(Joueur : TJoueur); begin effacerEcran(); { Partie supérieure de l'écran } afficherEntete(Joueur); dessinerCadreXY(0,6, 119,28, simple, 15,0); afficherTitre('ECRAN DE GESTION DE : ' + getElevage(Joueur).nom, 6); { Corps de l'écran } afficherElevage(Joueur, 4,10); afficherBatimentsConstruits(Joueur, 46,15); afficherBonus(Joueur, 84,15); { Choix disponibles } if getElevage(Joueur).construction = True then begin afficherAction(3,19, '1', 'Construire : Université', 'rouge'); afficherAction(3,20, '2', 'Construire : Centre de recherches', 'rouge'); afficherAction(3,21, '3', 'Construire : Laboratoire', 'rouge'); afficherAction(3,22, '4', 'Construire : Enclos', 'rouge'); afficherAction(3,23, '5', 'Construire : Bibliothèque', 'rouge'); afficherAction(3,24, '6', 'Construire : Archives', 'rouge'); end else begin if ( getUniversite(Joueur).niveau + getCDR(Joueur).niveau + getLaboratoire(Joueur).niveau + getEnclos(Joueur).niveau + getBibliotheque(Joueur).niveau + getArchives(Joueur).niveau ) < getElevage(Joueur).population then begin if (getUniversite(Joueur).niveau < getTribu(Joueur).niveauMax) then afficherAction(3,19, '1', 'Construire : Université', 'vert') else afficherAction(3,19, '1', 'Construire : Université', 'rouge'); if (getCDR(Joueur).niveau < getTribu(Joueur).niveauMax) then afficherAction(3,20, '2', 'Construire : Centre de recherches', 'vert') else afficherAction(3,20, '2', 'Construire : Centre de recherches', 'rouge'); if (getLaboratoire(Joueur).niveau < getTribu(Joueur).niveauMax) then afficherAction(3,21, '3', 'Construire : Laboratoire', 'vert') else afficherAction(3,21, '3', 'Construire : Laboratoire', 'rouge'); if (getEnclos(Joueur).niveau < getTribu(Joueur).niveauMax) then afficherAction(3,22, '4', 'Construire : Enclos', 'vert') else afficherAction(3,22, '4', 'Construire : Enclos', 'rouge'); if (getBibliotheque(Joueur).niveau < getTribu(Joueur).niveauMax) then afficherAction(3,23, '5', 'Construire : Bibliothèque', 'vert') else afficherAction(3,23, '5', 'Construire : Bibliothèque', 'rouge'); if (getArchives(Joueur).niveau < getTribu(Joueur).niveauMax) then afficherAction(3,24, '6', 'Construire : Archives', 'vert') else afficherAction(3,24, '6', 'Construire : Archives', 'rouge'); end; end; afficherAction(3,26, '0', 'Retour au menu', 'jaune'); { Partie inférieure de l'écran } afficherMessage(); afficherCadreAction(); choisir(Joueur); end; end.
unit UMySQLCheck; interface uses SysUtils, Ils.Logger, ZConnection, uADCompClient, Ils.MySql.Conf; function CheckTryRepairMySQL( const AConnection: TZConnection ): Boolean; overload; function CheckTryRepairMySQL( const AConnection: TADConnection ): Boolean; overload; implementation function CheckTryRepairMySQL( const AConnection: TZConnection ): Boolean; var DBInfo: string; begin DBInfo := 'СУБД ' + AConnection.HostName + ':' + IntToStr(AConnection.Port) + '@' + AConnection.Database + ' => '; Result := AConnection.Connected and AConnection.Ping(); if not Result then begin ToLog(DBInfo + 'обрыв связи, попытка восстановления'); try AConnection.Disconnect(); AConnection.Connect(); ToLog(DBInfo + 'восстановление связи успешно'); Result := True; except on Ex: Exception do ToLog(DBInfo + 'ошибка восстановления связи "' + Ex.ClassName + '":' + Ex.Message); end; end; end; function CheckTryRepairMySQL( const AConnection: TADConnection ): Boolean; var DBInfo: string; begin DBInfo := 'СУБД ' + AConnection.Params.Values['Server'] + ':' + AConnection.Params.Values['Port'] + '@' + AConnection.Params.Values['Database'] + ' => '; try Result := AConnection.Connected and AConnection.Ping(); except on Ex: Exception do begin ToLog(DBInfo + 'ошибка проверки связи "' + Ex.ClassName + '":' + Ex.Message); Result := False; end; end; if not Result then begin ToLog(DBInfo + 'обрыв связи, попытка восстановления'); try AConnection.Connected := False; AConnection.Connected := True; ToLog(DBInfo + 'восстановление связи успешно'); Result := True; except on Ex: Exception do ToLog(DBInfo + 'ошибка восстановления связи "' + Ex.ClassName + '":' + Ex.Message); end; end; end; end.
unit TimeLineBar; interface uses SysUtils, Classes, Controls, Types; type TTimeLineBar = class(TGraphicControl) // KeyFrameWidth private m_nCurrentLeft : Integer; m_nGraduationHeight : Integer; { Private declarations } protected { Protected declarations } procedure Paint; override; public { Public declarations } m_nRangeMin : Integer; m_nRangeMax : Integer; m_nGraduationWidth : Integer; procedure SetGraduationWidth(nWidth : Integer); procedure SetGraduationHeight(nHeight : Integer); procedure SetViewPort(nLeft : Integer); function GetViewPort(): Integer; function GetFrameX(nFrame : Integer) : Integer; function GetFrameByX(nX : Integer) : Integer; constructor Create(AOwner: TComponent); override; published { Published declarations } property Anchors; property OnClick; property OnMouseMove; property OnMouseUp; end; procedure Register; implementation constructor TTimeLineBar.Create(AOwner: TComponent); begin inherited Create(AOwner); m_nRangeMin := 0; m_nRangeMax := 1000; m_nGraduationHeight := 30; m_nCurrentLeft := 0; m_nGraduationWidth := 10; end; procedure Register; begin RegisterComponents('Samples', [TTimeLineBar]); end; procedure TTimeLineBar.SetGraduationWidth(nWidth : Integer); begin m_nGraduationWidth := nWidth; end; function TTimeLineBar.GetViewPort(): Integer; begin GetViewPort := m_nCurrentLeft; end; procedure TTimeLineBar.SetGraduationHeight(nHeight : Integer); begin m_nGraduationHeight := nHeight; end; procedure TTimeLineBar.SetViewPort(nLeft : Integer); begin if (nLeft < m_nRangeMin) then Exit; if (nLeft + Width > m_nRangeMax) then begin nLeft := m_nRangeMax - Width; if (nLeft < m_nRangeMin) then nLeft := m_nRangeMin; end; m_nCurrentLeft := nLeft; Paint(); end; function TTimeLineBar.GetFrameX(nFrame : Integer) : Integer; var nReturn : Integer; nStartFrame : Integer; begin nStartFrame := m_nCurrentLeft div m_nGraduationWidth; if nFrame < nStartFrame then nReturn := -1 else nReturn := nFrame * m_nGraduationWidth - m_nCurrentLeft; GetFrameX := nReturn; end; function TTimeLineBar.GetFrameByX(nX : Integer) : Integer; begin GetFrameByX := (m_nCurrentLeft + nX) div m_nGraduationWidth; end; procedure TTimeLineBar.Paint(); var nFrameInView : Integer; nFrameInRange : Integer; i : Integer; nHeight : Integer; PositionMark : String; PositionMarkWidth : Integer; nStartFrame : Integer; begin nFrameInRange := (m_nRangeMax - m_nCurrentLeft * m_nGraduationWidth) div m_nGraduationWidth; nFrameInView := Width div m_nGraduationWidth; Canvas.FillRect(ClientRect); Canvas.MoveTo(0, 0); Canvas.LineTo(Width, 0); nStartFrame := m_nCurrentLeft div m_nGraduationWidth; if nFrameInView > nFrameInRange then nFrameInView := nFrameInRange; for i := 0 to nFrameInView do begin if ((i + nStartFrame) mod 5 = 0) then begin nHeight := m_nGraduationHeight; PositionMark := Format('%d', [i + nStartFrame]); PositionMarkWidth := Canvas.TextWidth(PositionMark); Canvas.TextOut(i * m_nGraduationWidth + m_nGraduationWidth div 2 - PositionMarkWidth div 2, nHeight, PositionMark); end else nHeight := m_nGraduationHeight div 2; Canvas.MoveTo(i * m_nGraduationWidth + m_nGraduationWidth div 2, 0); Canvas.LineTo(i * m_nGraduationWidth + m_nGraduationWidth div 2, nHeight); end; end; end.
unit SDFATBootSectorPropertiesDlg; interface uses Classes, Controls, Dialogs, Forms, Graphics, Messages, SDFilesystem_FAT, SDUForms, StdCtrls, SysUtils, Variants, Windows; type TSDFATBootSectorPropertiesDialog = class (TSDUForm) Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; Label9: TLabel; Label10: TLabel; Label11: TLabel; Label12: TLabel; edOEMName: TEdit; edBytesPerSector: TEdit; edSectorsPerCluster: TEdit; edReservedSectorCount: TEdit; edFATCount: TEdit; edMaxRootEntries: TEdit; edTotalSectors: TEdit; edMediaDescriptor: TEdit; edSectorsPerFAT: TEdit; edSectorsPerTrack: TEdit; edNumberOfHeads: TEdit; edHiddenSectors: TEdit; pbClose: TButton; procedure pbCloseClick(Sender: TObject); procedure FormShow(Sender: TObject); PRIVATE { Private declarations } PUBLIC Filesystem: TSDFilesystem_FAT; end; implementation {$R *.dfm} procedure TSDFATBootSectorPropertiesDialog.pbCloseClick(Sender: TObject); begin Close(); end; procedure TSDFATBootSectorPropertiesDialog.FormShow(Sender: TObject); begin edOEMName.Text := Filesystem.OEMName; edBytesPerSector.Text := IntToStr(Filesystem.BytesPerSector); edSectorsPerCluster.Text := IntToStr(Filesystem.SectorsPerCluster); edReservedSectorCount.Text := IntToStr(Filesystem.ReservedSectorCount); edFATCount.Text := IntToStr(Filesystem.FATCount); edMaxRootEntries.Text := IntToStr(Filesystem.MaxRootEntries); edTotalSectors.Text := IntToStr(Filesystem.TotalSectors); edMediaDescriptor.Text := '0x' + inttohex(Filesystem.MediaDescriptor, 2); edSectorsPerFAT.Text := IntToStr(Filesystem.SectorsPerFAT); edSectorsPerTrack.Text := IntToStr(Filesystem.SectorsPerTrack); edNumberOfHeads.Text := IntToStr(Filesystem.NumberOfHeads); edHiddenSectors.Text := IntToStr(Filesystem.HiddenSectors); end; end.
unit UnitServices; interface uses StrUtils,Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, ImgList, Menus, UnitMain, sSkinProvider, UnitConexao; type TFormServices = class(TForm) StatusBar1: TStatusBar; AdvListView1: TListView; PopupMenu1: TPopupMenu; Atualizar1: TMenuItem; N1: TMenuItem; Iniciar1: TMenuItem; Parar1: TMenuItem; N2: TMenuItem; Instalar1: TMenuItem; Desinstalar1: TMenuItem; Editar1: TMenuItem; sSkinProvider1: TsSkinProvider; procedure AdvListView1ColumnClick(Sender: TObject; Column: TListColumn); procedure Atualizar1Click(Sender: TObject); procedure FormShow(Sender: TObject); procedure AdvListView1CustomDrawItem(Sender: TCustomListView; Item: TListItem; State: TCustomDrawState; var DefaultDraw: Boolean); procedure PopupMenu1Popup(Sender: TObject); procedure Iniciar1Click(Sender: TObject); procedure Parar1Click(Sender: TObject); procedure Desinstalar1Click(Sender: TObject); procedure Instalar1Click(Sender: TObject); procedure Editar1Click(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); private { Private declarations } Servidor: TConexaoNew; NomePC: string; LiberarForm: boolean; procedure WMCloseFree(var Message: TMessage); message WM_CLOSEFREE; procedure AtualizarIdioma; procedure WMAtualizarIdioma(var Message: TMessage); message WM_ATUALIZARIDIOMA; procedure CreateParams(var Params : TCreateParams); override; public { Public declarations } procedure OnRead(Recebido: String; ConAux: TConexaoNew); overload; constructor Create(aOwner: TComponent; ConAux: TConexaoNew); overload; end; var FormServices: TFormServices; implementation {$R *.dfm} uses DateUtils, ShellApi, UnitStrings, UnitConstantes, UnitServiceInstall, UnitCommonProcedures, CommCtrl, CustomIniFiles, AS_ShellUtils; //procedure WMAtualizarIdioma(var Message: TMessage); message WM_ATUALIZARIDIOMA; procedure TFormServices.WMAtualizarIdioma(var Message: TMessage); begin AtualizarIdioma; end; procedure TFormServices.WMCloseFree(var Message: TMessage); begin LiberarForm := True; Close; end; //Here's the implementation of CreateParams procedure TFormServices.CreateParams(var Params : TCreateParams); begin inherited CreateParams(Params); //Don't ever forget to do this!!! if FormMain.ControlCenter = True then Exit; Params.WndParent := GetDesktopWindow; end; var LastSortedColumn: TListColumn; Ascending: boolean; function SortByColumn(Item1, Item2: TListItem; Data: integer): integer; stdcall; var s1,s2: string; ex1,ex2: extended; num: integer; begin Result := 0; if Data = 0 then Result := AnsiCompareText(Item1.Caption, Item2.Caption) else Result := AnsiCompareText(Item1.SubItems[Data-1],Item2.SubItems[Data-1]); if not Ascending then Result := -Result; end; procedure TFormServices.AdvListView1ColumnClick(Sender: TObject; Column: TListColumn); var i: integer; begin Ascending := not Ascending; if Column <> LastSortedColumn then Ascending := not Ascending; for i := 0 to AdvListview1.Columns.Count -1 do AdvListview1.Column[i].ImageIndex := -1; LastSortedColumn := Column; AdvListview1.CustomSort(@SortByColumn, LastSortedColumn.Index); end; procedure TFormServices.AtualizarIdioma; begin AdvListView1.Column[0].Caption := traduzidos[250]; AdvListView1.Column[1].Caption := traduzidos[251]; AdvListView1.Column[2].Caption := traduzidos[252]; AdvListView1.Column[3].Caption := traduzidos[253]; AdvListView1.Column[4].Caption := traduzidos[254]; AdvListView1.Column[5].Caption := traduzidos[255]; Iniciar1.Caption := traduzidos[256]; Parar1.Caption := traduzidos[257]; Instalar1.Caption := traduzidos[258]; Atualizar1.Caption := traduzidos[192]; Desinstalar1.Caption := traduzidos[141]; Editar1.Caption := traduzidos[265]; end; constructor TFormServices.Create(aOwner: TComponent; ConAux: TConexaoNew); var TempStr: WideString; IniFile: TIniFile; begin inherited Create(aOwner); Servidor := ConAux; NomePC := Servidor.NomeDoServidor; TempStr := ExtractFilePath(ParamStr(0)) + 'Settings\'; ForceDirectories(TempStr); TempStr := TempStr + NomePC + '.ini'; if FileExists(TempStr) = True then try IniFile := TIniFile.Create(TempStr, IniFilePassword); Width := IniFile.ReadInteger('ServiceManager', 'Width', Width); Height := IniFile.ReadInteger('ServiceManager', 'Height', Height); Left := IniFile.ReadInteger('ServiceManager', 'Left', Left); Top := IniFile.ReadInteger('ServiceManager', 'Top', Top); AdvListView1.Column[0].Width := IniFile.ReadInteger('ServiceManager', 'LV1_0', AdvListView1.Column[0].Width); AdvListView1.Column[1].Width := IniFile.ReadInteger('ServiceManager', 'LV1_1', AdvListView1.Column[1].Width); AdvListView1.Column[2].Width := IniFile.ReadInteger('ServiceManager', 'LV1_2', AdvListView1.Column[2].Width); AdvListView1.Column[3].Width := IniFile.ReadInteger('ServiceManager', 'LV1_3', AdvListView1.Column[3].Width); AdvListView1.Column[4].Width := IniFile.ReadInteger('ServiceManager', 'LV1_4', AdvListView1.Column[4].Width); AdvListView1.Column[5].Width := IniFile.ReadInteger('ServiceManager', 'LV1_5', AdvListView1.Column[5].Width); IniFile.Free; except DeleteFile(TempStr); end; end; procedure TFormServices.Iniciar1Click(Sender: TObject); begin Servidor.EnviarString(INICIARSERVICO + '|' + AdvListView1.Selected.SubItems.Strings[0] + '|'); end; procedure TFormServices.Instalar1Click(Sender: TObject); var DisplayName: string; ServiceName: string; FileName: string; Desc: string; Startup: string; STartNow: string; Form: TFormServiceInstall; begin Form := TFormServiceInstall.create(application); try Form.Label1.Caption := AdvListView1.Column[0].Caption + ':'; Form.Label2.Caption := AdvListView1.Column[1].Caption + ':'; Form.Label3.Caption := AdvListView1.Column[4].Caption + ':'; Form.Label4.Caption := AdvListView1.Column[5].Caption + ':'; Form.Label5.Caption := AdvListView1.Column[3].Caption + ':'; Form.Caption := ''; Form.Edit2.Enabled := true; Form.CheckBox1.Enabled := true; Form.CheckBox1.Checked := true; Form.Edit1.Clear; Form.Edit2.Clear; Form.Edit3.Clear; Form.Edit4.Clear; Form.Combobox1.Items.Clear; Form.ComboBox1.Items.Add(traduzidos[261]); Form.ComboBox1.Items.Add(traduzidos[262]); Form.ComboBox1.Items.Add(traduzidos[263]); Form.Combobox1.ItemIndex := 0; Form.CheckBox1.Caption := traduzidos[264]; Form.BitBtn2.Caption := traduzidos[120]; if Form.ShowModal = mrok then begin DisplayName := Form.Edit1.Text; ServiceName := Form.Edit2.Text; FileName := Form.Edit3.Text; Desc := Form.Edit4.Text; Startup := IntToStr(Form.ComboBox1.ItemIndex + 2); // Automatic = 2; Manual = 3; Disabled = 4 STartNow := '0'; if Form.CheckBox1.Checked then StartNow := '1'; Servidor.EnviarString(INSTALARSERVICO + '|' + ServiceName + delimitadorComandos + DisplayName + delimitadorComandos + FileName + delimitadorComandos + Desc + delimitadorComandos + Startup + delimitadorComandos + STartNow + delimitadorComandos); end; finally Form.Release; Form := nil; end; end; procedure TFormServices.Parar1Click(Sender: TObject); begin Servidor.EnviarString(PARARSERVICO + '|' + AdvListView1.Selected.SubItems.Strings[0] + '|'); end; procedure TFormServices.Desinstalar1Click(Sender: TObject); begin if AdvListView1.SelCount <= 0 then Exit; if MessageBox(Handle, pchar(traduzidos[278] + '?'), pchar(NomeDoPrograma + ' ' + VersaoDoPrograma), MB_ICONQUESTION or MB_YESNO or MB_SYSTEMMODAL or MB_SETFOREGROUND or MB_TOPMOST) <> idYes then Exit; Servidor.EnviarString(REMOVERSERVICO + '|' + AdvListView1.Selected.SubItems.Strings[0] + '|'); end; procedure TFormServices.Editar1Click(Sender: TObject); var DisplayName: string; ServiceName: string; FileName: string; Desc: string; Startup: string; STartNow: string; Form: TFormServiceInstall; begin Form := TFormServiceInstall.create(application); try Form.Caption := ''; Form.Edit2.Enabled := false; Form.CheckBox1.Checked := false; Form.CheckBox1.Enabled := false; Form.Label1.Caption := AdvListView1.Column[0].Caption + ':'; Form.Label2.Caption := AdvListView1.Column[1].Caption + ':'; Form.Label3.Caption := AdvListView1.Column[4].Caption + ':'; Form.Label4.Caption := AdvListView1.Column[5].Caption + ':'; Form.Label5.Caption := AdvListView1.Column[3].Caption + ':'; Form.CheckBox1.Caption := traduzidos[264]; Form.BitBtn2.Caption := traduzidos[120]; Form.Edit1.Text := AdvListView1.Selected.Caption; Form.Edit2.Text := AdvListView1.Selected.SubItems.Strings[0]; Form.Edit3.Text := AdvListView1.Selected.SubItems.Strings[3]; Form.Edit4.Text := AdvListView1.Selected.SubItems.Strings[4]; Form.Combobox1.Items.Clear; Form.ComboBox1.Items.Add(traduzidos[261]); Form.ComboBox1.Items.Add(traduzidos[262]); Form.ComboBox1.Items.Add(traduzidos[263]); if AdvListView1.Selected.SubItems.Strings[2] = traduzidos[261] then Form.Combobox1.ItemIndex := 0 else if AdvListView1.Selected.SubItems.Strings[2] = traduzidos[262] then Form.Combobox1.ItemIndex := 1 else Form.Combobox1.ItemIndex := 2; if Form.ShowModal = mrOK then begin DisplayName := Form.Edit1.Text; ServiceName := Form.Edit2.Text; FileName := Form.Edit3.Text; Desc := Form.Edit4.Text; Startup := IntToStr(Form.ComboBox1.ItemIndex + 2); // Automatic = 2; Manual = 3; Disabled = 4 STartNow := '0'; Servidor.EnviarString(EDITARSERVICO + '|' + ServiceName + delimitadorComandos + DisplayName + delimitadorComandos + FileName + delimitadorComandos + Desc + delimitadorComandos + Startup + delimitadorComandos + STartNow + delimitadorComandos); end; finally Form.Release; Form := nil; end; end; procedure TFormServices.Atualizar1Click(Sender: TObject); begin Servidor.EnviarString(LISTADESERVICOS + '|'); StatusBar1.Panels.Items[0].Text := traduzidos[205]; end; procedure TFormServices.FormClose(Sender: TObject; var Action: TCloseAction); var TempStr: WideString; IniFile: TIniFile; begin if LiberarForm then Action := caFree; AdvListView1.Items.Clear; TempStr := ExtractFilePath(ParamStr(0)) + 'Settings\'; ForceDirectories(TempStr); TempStr := TempStr + NomePC + '.ini'; try IniFile := TIniFile.Create(TempStr, IniFilePassword); IniFile.WriteInteger('ServiceManager', 'Width', Width); IniFile.WriteInteger('ServiceManager', 'Height', Height); IniFile.WriteInteger('ServiceManager', 'Left', Left); IniFile.WriteInteger('ServiceManager', 'Top', Top); IniFile.WriteInteger('ServiceManager', 'LV1_0', AdvListView1.Column[0].Width); IniFile.WriteInteger('ServiceManager', 'LV1_1', AdvListView1.Column[1].Width); IniFile.WriteInteger('ServiceManager', 'LV1_2', AdvListView1.Column[2].Width); IniFile.WriteInteger('ServiceManager', 'LV1_3', AdvListView1.Column[3].Width); IniFile.WriteInteger('ServiceManager', 'LV1_4', AdvListView1.Column[4].Width); IniFile.WriteInteger('ServiceManager', 'LV1_5', AdvListView1.Column[5].Width); IniFile.Free; except DeleteFile(TempStr); end; end; procedure TFormServices.FormCreate(Sender: TObject); begin Self.Left := (screen.width - Self.width) div 2 ; Self.top := (screen.height - Self.height) div 2; if AdvListView1.Items.Count > 0 then AdvListView1.Items.Clear; end; procedure TFormServices.FormShow(Sender: TObject); begin AtualizarIdioma; Atualizar1Click(Atualizar1); end; procedure TFormServices.OnRead(Recebido: String; ConAux: TConexaoNew); var TempInt: Integer; Item: TListItem; TempStr: string; i: integer; Result: TSplit; begin if Copy(Recebido, 1, posex('|', Recebido) - 1) = LISTADESERVICOS then begin delete(Recebido, 1, posex('|', Recebido)); AdvListView1.Items.BeginUpdate; try if AdvListView1.Items.Count > 0 then AdvListView1.Items.Clear; while (recebido <> '') and (Visible = True) do begin TempStr := Copy(Recebido, 1, posex(#13#10, Recebido) - 1); delete(Recebido, 1, posex(#13#10, Recebido) + 1); Item := AdvListView1.Items.Add; Item.ImageIndex := 58; Result := SplitString(TempStr, delimitadorComandos); Item.Caption := Result[0]; Item.SubItems.Add(Result[1]); if Result[2] = '4' then Result[2] := traduzidos[259] else Result[2] := traduzidos[260]; Item.SubItems.Add(Result[2]); if Result[2] = traduzidos[260] then Item.Data := TObject(clGray); if Result[3] = '2' then Result[3] := traduzidos[261] else if Result[3] = '3' then Result[3] := traduzidos[262] else if Result[3] = '4' then Result[3] := traduzidos[263] else Result[3] := ''; Item.SubItems.Add(Result[3]); Item.SubItems.Add(Result[4]); Item.SubItems.Add(Result[5]); end; finally AdvListView1.Items.EndUpdate; end; StatusBar1.Panels.Items[0].Text := traduzidos[266]; end else if Copy(Recebido, 1, posex('|', Recebido) - 1) = INSTALARSERVICO then begin delete(Recebido, 1, posex('|', Recebido)); TempStr := Copy(Recebido, 1, posex(delimitadorComandos, Recebido) - 1); delete(Recebido, 1, posex(delimitadorComandos, Recebido) - 1); delete(Recebido, 1, length(delimitadorComandos)); if Copy(Recebido, 1, posex('|', Recebido) - 1) = 'T' then StatusBar1.Panels.Items[0].Text := traduzidos[267] + ' "' + tempstr + '" ' + traduzidos[268] else StatusBar1.Panels.Items[0].Text := traduzidos[267] + ' "' + tempstr + '" ' + traduzidos[269]; end else if Copy(Recebido, 1, posex('|', Recebido) - 1) = PARARSERVICO then begin delete(Recebido, 1, posex('|', Recebido)); TempStr := Copy(Recebido, 1, posex('|', Recebido) - 1); delete(Recebido, 1, posex('|', Recebido)); if Copy(Recebido, 1, posex('|', Recebido) - 1) = 'T' then StatusBar1.Panels.Items[0].Text := traduzidos[267] + ' "' + tempstr + '" ' + traduzidos[270] else StatusBar1.Panels.Items[0].Text := traduzidos[267] + ' "' + tempstr + '" ' + traduzidos[271]; end else if Copy(Recebido, 1, posex('|', Recebido) - 1) = INICIARSERVICO then begin delete(Recebido, 1, posex('|', Recebido)); TempStr := Copy(Recebido, 1, posex('|', Recebido) - 1); delete(Recebido, 1, posex('|', Recebido)); if Copy(Recebido, 1, posex('|', Recebido) - 1) = 'T' then StatusBar1.Panels.Items[0].Text := traduzidos[267] + ' "' + tempstr + '" ' + traduzidos[272] else StatusBar1.Panels.Items[0].Text := traduzidos[267] + ' "' + tempstr + '" ' + traduzidos[273]; end else if Copy(Recebido, 1, posex('|', Recebido) - 1) = REMOVERSERVICO then begin delete(Recebido, 1, posex('|', Recebido)); TempStr := Copy(Recebido, 1, posex('|', Recebido) - 1); delete(Recebido, 1, posex('|', Recebido)); if Copy(Recebido, 1, posex('|', Recebido) - 1) = 'T' then StatusBar1.Panels.Items[0].Text := traduzidos[267] + ' "' + tempstr + '" ' + traduzidos[274] else StatusBar1.Panels.Items[0].Text := traduzidos[267] + ' "' + tempstr + '" ' + traduzidos[275]; end else if Copy(Recebido, 1, posex('|', Recebido) - 1) = EDITARSERVICO then begin delete(Recebido, 1, posex('|', Recebido)); TempStr := Copy(Recebido, 1, posex(delimitadorComandos, Recebido) - 1); delete(Recebido, 1, posex(delimitadorComandos, Recebido) - 1); delete(Recebido, 1, length(delimitadorComandos)); if Copy(Recebido, 1, posex('|', Recebido) - 1) = 'T' then StatusBar1.Panels.Items[0].Text := traduzidos[267] + ' "' + tempstr + '" ' + traduzidos[276] else StatusBar1.Panels.Items[0].Text := traduzidos[267] + ' "' + tempstr + '" ' + traduzidos[277]; end else end; procedure TFormServices.AdvListView1CustomDrawItem(Sender: TCustomListView; Item: TListItem; State: TCustomDrawState; var DefaultDraw: Boolean); begin if Item.Data <> nil then Sender.Canvas.Font.Color := TColor(Item.Data); end; procedure TFormServices.PopupMenu1Popup(Sender: TObject); var i: integer; begin if AdvListView1.Selected = nil then begin for i := 0 to PopupMenu1.Items.Count - 1 do PopupMenu1.Items.Items[i].Enabled := false; Atualizar1.Enabled := true; end else for i := 0 to PopupMenu1.Items.Count - 1 do PopupMenu1.Items.Items[i].Enabled := true; end; end.
unit uClassAuditoria; interface type TAuditoria = class private FDataAtualizacao: TDateTime; FDataCadastro: TDateTime; FDataMovimento: TDateTime; FCodigoEmpresa: integer; procedure SetCodigoEmpresa(const Value: integer); procedure SetDataAtualizacao(const Value: TDateTime); procedure SetDataCadastro(const Value: TDateTime); procedure SetDataMovimento(const Value: TDateTime); published public property DataCadastro : TDateTime read FDataCadastro write SetDataCadastro; property DataAtualizacao : TDateTime read FDataAtualizacao write SetDataAtualizacao; property DataMovimento : TDateTime read FDataMovimento write SetDataMovimento; property CodigoEmpresa : integer read FCodigoEmpresa write SetCodigoEmpresa; end; implementation { TAuditoria } procedure TAuditoria.SetCodigoEmpresa(const Value: integer); begin FCodigoEmpresa := Value; end; procedure TAuditoria.SetDataAtualizacao(const Value: TDateTime); begin FDataAtualizacao := Value; end; procedure TAuditoria.SetDataCadastro(const Value: TDateTime); begin FDataCadastro := Value; end; procedure TAuditoria.SetDataMovimento(const Value: TDateTime); begin FDataMovimento := Value; end; end.
Unit Font; Interface Procedure Print_Char(Chr:Char); {gibt Zeichen auf Mode X aus} Procedure Print_String(Str:String); {gibt String auf Mode X aus} Procedure Scrl_Move; {bewegt sichtbaren Teil des Scrolly nach links} Procedure Scrl_Append; {h„ngt am rechten Bildrand neue Daten an Scrolly an} Var Scrl_Y:Word; {vertikale Position des Scrollys} Const Scrl_Anzahl=4; {Anzahl der in Scrl_Txt vorhandenen Strings} Scrl_Txt:Array [1..Scrl_Anzahl] of String = {Nur ein Demo-Text, der beliebig ver„ndert oder erg„nzt werden kann !} ('Hallo, dies ist Martins kleine Demo - total schlecht und eigentlich' +' einfach nur irgendwo abgeschrieben. Erstellt wurde sie am 21.3.1998,', +' um ca. 23.30 uhr. Gleich kommen noch ein paar lustige 3D - Scherzchen.' +' Gruesse gehen an Phylax, Buddy und an alle, die Lust haben, sich dieses ', ' anzutun. --------------------------- ', ' '+''); Implementation Uses ModeXLib; Const CharPos:Array[' '..'Z', 0..1] of Word= {Positionen und Breiten der einzelnen Zeichen, jeweils CPU-adressierte Bytes} ((71,4),(0,0),(0,0),(0,0),(0,0),(0,0), (0,0),(0,0),(0,0),(0,0),(0,0),(0,0), (1906,3),(1909,3),(1912,3),(1915,4), {,-./} (3600,5),(3605,3),(3608,5),(3613,5), {0..3} (3618,5),(3623,5),(3628,5),(3633,5), {4..7} (3638,5),(3643,5),(3648,3),(3651,3), {8..;} (3654,5),(3659,5),(3664,5),(3669,4), {<..?} (0,0),(0,5),(5,5),(10,5),(15,6),(21,5), {@..E} (26,4),(30,7),(37,5),(42,3),(45,4),(49,5),{F..K} (54,4),(58,8),(66,5),(1840,7),(1847,5), {L..P} (1852,7),(1859,5),(1864,4),(1868,4), {Q..T} (1872,5),(1877,6),(1883,8),(1891,5), {U..X} (1896,5),(1901,5)); {YZ} Var Cur_X, {gegenw„rtige x-} Cur_Y:Integer; {und y-Position des Cursors} Scrl_Number, {Nummer des gerade aktiven Scroll-Strings} Scrl_Pos, {Position innerhalb dieses Strings} Scrl_ChrPos:Word; {Position innerhalb des Zeichens} Procedure Print_Char(Chr:Char); {Gibt ein Zeichen auf Mode X Bildschirm aus und bewegt Cursor eine Position weiter} Begin Chr:=UpCase(Chr); {nur Groábuchstaben verwenden} If Chr in [' '..'Z'] Then Begin {ist das Zeichen im Zeichensatz ?, ja:} If 80- Cur_X < {noch genug Platz ?} CharPos[Chr,1] Then Begin Cur_X:=0; {nein, dann n„chste Zeile, x auf 0} Inc(Cur_Y,25); {und y eine Zeichenh”he weiter} End; Copy_Block(Cur_Y*80+Cur_X, 48000+Charpos[Chr,0], CharPos[Chr,1], 22); {Zeichen von Font-Position (aus CharPos-Tabelle) an Cursorposition (Cur_Y * 80 Byte pro Zeile + Cur_X) kopieren (H”he 22 Zeilen} Inc(Cur_X,CharPos[Chr,1]); {Cursor um Zeichenbreite bewegen} End; End; Procedure Print_String(Str:String); {gibt einen String auf Mode X Bildschirm aus, benutzt dazu Print_Char} Var i:Word; Begin For i:=1 to Length(Str) do {gesamten String an Print_Char schicken} Print_Char(Str[i]); End; Procedure Scrl_Move; {verschiebt einfach Bildinhalt an der Stelle des Scrollys um eine Position nach links, also 79 Bytes von x-Position 1 nach x-Position 0 kopieren} Begin Copy_Block(Scrl_y*80, Scrl_Y*80 +1, 79,22); End; Procedure Scrl_Append; Var Chr:Char; {aktueller Buchstabe} Begin Chr:=UpCase(Scrl_txt[Scrl_Number,Scrl_pos]); {Buchstaben holen, nur Groábuchstaben} If Chr in [' '..'Z'] Then Begin {ist das Zeichen im Zeichensatz ?, ja:} If CharPos[Chr,1] > 0 Then {nur vorhandene Zeichen darstellen} Copy_Block(Scrl_y*80+79, 48000+CharPos[Chr,0]+Scrl_ChrPos, 1, 22); {dann 1 Spalte aus Zeichensatz an rechten} {Bildschirmrand kopieren} Inc(Scrl_ChrPos); {und n„chste Spalte innerhalb des Zeichens} If Scrl_ChrPos >= CharPos[Chr,1] Then Begin Inc(Scrl_Pos); {wenn Zeichen fertig, n„chstes Zeichen} Scrl_ChrPos:=0; {und Spalte wieder auf 0} If Scrl_Pos > Length(Scrl_Txt[Scrl_Number]) Then Begin Inc(Scrl_Number); {wenn String fertig, n„chsten String} Scrl_Pos:=1; {Position wieder auf 0} If Scrl_Number > Scrl_Anzahl Then Begin Scrl_Number:=1; {wenn Text fertig, wieder von vorn} Scrl_Pos:=1; Scrl_ChrPos:=0; End; End; End; End; End; Begin Cur_X:=0; {Cursor auf linke obere Ecke} Cur_Y:=0; Scrl_Y:=50; {Default-Wert fr y-Position} Scrl_Number:=1; {Start mit String 1, Zeichen 1, Spalte 0} Scrl_Pos:=1; Scrl_ChrPos:=0; End.
unit Mailbox; interface uses Contnrs, Being; type TMail = class public ID : LongWord; SenderID : LongWord; SenderName: String; ReceiverID : LongWord; ReceiverName : String; SendTime : LongWord; Title : String; Content : String; Read : Boolean; end; TMailBox = class private fChanged : Boolean; fMails : Byte; fNewMails : Byte; //How many new mails? fBeing : TBeing; //Since we can't loop back refence... fMailList : TObjectList; function GetValue(Index : Integer) : TMail; public property Changed : Boolean read fChanged; property Mails : Byte read fMails; property NewMails : Byte read fNewMails; property Item[Index : Integer] : TMail read GetValue; procedure LoadMails; procedure Clear; function Get(const AMailID:LongWord):TMail; function Delete(const AMailID:LongWord):Boolean; function Send(const Receiver,Title,Content : String):Boolean; constructor Create(const ABeing:TBeing); destructor Destroy; override; end; implementation uses Main, SysUtils, DateUtils, Character, ZoneSend, PacketTypes, ZoneInterCommunication; function TMailBox.GetValue(Index : Integer) : TMail; begin Result := TMail(fMailList[Index]); end; procedure TMailBox.LoadMails; var AChara : TCharacter; begin if Changed then begin AChara := TCharacter(fBeing); TThreadLink(AChara.ClientInfo.Data).DatabaseLink.Mail.LoadMails( fMailList, AChara.ID, fMails, fNewMails ); fChanged := False; end; end; procedure TMailBox.Clear; begin fMailList.Clear; end; function TMailBox.Get(const AMailID:LongWord):TMail; var AChara : TCharacter; begin AChara := TCharacter(fBeing); Result := TThreadLink(AChara.ClientInfo.Data).DatabaseLink.Mail.Get( AChara.ID, AMailID ); fChanged := True; {Assume player reading an unread message} end; function TMailBox.Delete(const AMailID:LongWord):Boolean; var AChara : TCharacter; begin AChara := TCharacter(fBeing); Result := TThreadLink(AChara.ClientInfo.Data).DatabaseLink.Mail.Delete( AChara.ID, AMailID ); fChanged := True; end; function TMailBox.Send(const Receiver,Title,Content : String):Boolean; var AChara : TCharacter; Target : TCharacter; Mail : TMail; begin AChara := TCharacter(fBeing); Result := False; Target := TCharacter.Create(nil); Mail := TMail.Create; try Target.ID := 0; Target.Name := Receiver; TThreadLink(AChara.ClientInfo.Data).DatabaseLink.Character.Load(Target); if Target.ID > 0 then begin //Prevent send to yourself if Target.AccountID <> AChara.AccountID then begin Mail.SenderID := AChara.ID; Mail.SenderName := AChara.Name; Mail.ReceiverID := Target.ID; Mail.ReceiverName := Target.Name; Mail.Title := Title; Mail.Content := Content; Mail.SendTime := DateTimeToUnix(Now); TThreadLink(AChara.ClientInfo.Data).DatabaseLink.Mail.Add( Mail ); ZoneSendNotifyMail( MainProc.ZoneServer.ToInterTCPClient, Mail.ID ); Result := True; end; end; finally Target.Free; Mail.Free; end; end; constructor TMailBox.Create(const ABeing:TBeing); begin {Set to True so we can load a fresh copy} fChanged := True; fBeing := ABeing; fMailList := TObjectList.Create(True); end;{Create} destructor TMailBox.Destroy; begin fMailList.Free; end; end.
unit SQLGenerator; interface uses MetaData, System.SysUtils; function GetJoin(ATag: Integer): string; function GetSelectionJoin(ATag: Integer): string; function GetJoinWhere(Count: Integer; ATag: Integer; Params: string; Query: string): string; function GetSelectClause(ATag: Integer): string; function GetSelectJoinWhere(Count: Integer; ATag: Integer; Params: string; Query: string): string; function GetOrdered(State: TSort; ATag: Integer; Filter: string = ''; FieldName: string = ''): string; function GetInsert(Tag: Integer; Index: Integer; Count: Integer): string; function GetUpdate(Tag: Integer; Index: Integer): string; function SetGenerator(Max: Integer): string; implementation function GetJoin(ATag: Integer): String; var I: Integer; begin with TablesMetaData.Tables[ATag] do begin Result := TableName; for I := 0 to High(TableFields) do with TableFields[I] do if References <> Nil then begin Result := Result + ' LEFT JOIN ' + References.Table + ' ON ' + TableName + '.' + FieldName + ' = ' + References.Table + '.' + References.Field; end; end; end; function GetSelectClause(ATag: Integer): string; var I: Integer; FromQuery: string; begin Result := 'SELECT '; with TablesMetaData.Tables[ATag] do for I := 0 to High(TableFields) do with TableFields[I] do begin Result := Result + TableName + '.' + FieldName + ', '; if References <> Nil then Result := Result + References.Table + '.' + References.Name + ', '; end; Delete(Result, Length(Result) - 1, 2); end; function GetSelectionJoin(ATag: Integer): string; begin Result := GetSelectClause(ATag) + ' FROM ' + GetJoin(ATag); end; function GetSelectJoinWhere(Count: Integer; ATag: Integer; Params: string; Query: string): string; begin if Count = 0 then Result := GetSelectClause(ATag) + ' FROM ' + ' ' + GetJoin(ATag) + ' WHERE ' + Params + ':' + IntToStr(Count) else Result := Query + ' AND ' + Params + ':' + IntToStr(Count); end; function GetOrdered(State: TSort; ATag: Integer; Filter: string = ''; FieldName: string = ''): string; begin if Filter = '' then Result := GetSelectionJoin(ATag) else Result := Filter; case State of TSort(None): exit; Up: Result := Result + ' ORDER BY ' + FieldName; Down: Result := Result + ' ORDER BY ' + FieldName + ' DESC'; end; end; function GetJoinWhere(Count: Integer; ATag: Integer; Params: string; Query: string): string; begin if Count = 0 then Result := 'SELECT * FROM ' + ' ' + GetJoin(ATag) + ' WHERE ' + Params + ':' + IntToStr(Count) else Result := Query + ' AND ' + Params + ':' + IntToStr(Count); end; function GetInsert(Tag: Integer; Index: Integer; Count: Integer): string; var I: Integer; begin if TablesMetaData.Tables[Tag].TableFields[Index].References = Nil then begin Result := 'INSERT INTO ' + TablesMetaData.Tables[Tag].TableFields[Index] .References.Table + '(' + TablesMetaData.Tables[Tag].TableFields[0] .FieldName + ', ' + TablesMetaData.Tables[Tag].TableFields[Index] .References.Name + ') VALUES ( GEN_ID(GenNewID, 1)'; Result := Result + ', :0'; Result := Result + ');'; end else begin Result := 'INSERT INTO ' + TablesMetaData.Tables[Tag].TableName + ' VALUES ( GEN_ID(GenNewID, 1)'; for I := 0 to Count do Result := Result + ', :' + IntToStr(Index); Result := Result + ');'; end; end; function GetUpdate(Tag: Integer; Index: Integer): string; var I: Integer; begin { if TablesMetaData.Tables[Tag].TableFields[Index].References <> Nil then begin Result := 'UPDATE ' + TablesMetaData.Tables[Tag].TableFields[Index].References.Table + ' SET ' + TablesMetaData.Tables[Tag].TableFields[Index].References.Name + ' = :0 WHERE ' + TablesMetaData.Tables[Tag].TableFields[Index] .References.Name + ' = :1'; end else begin } if Index = 0 then Result := 'UPDATE ' + TablesMetaData.Tables[Tag].TableName + ' SET ' + TablesMetaData.Tables[Tag].TableFields[Index + 1] .FieldName + ' = :' + IntToStr(Index); if (Index > 0) and (Index < High(TablesMetaData.Tables[Tag].TableFields)) then Result := Result + ', ' + TablesMetaData.Tables[Tag].TableFields[Index + 1] .FieldName + ' = :' + IntToStr(Index); if Index = High(TablesMetaData.Tables[Tag].TableFields) then Result := ' WHERE ID = :' + IntToStr(Index); // end; end; function SetGenerator(Max: Integer): string; begin Result := 'SET GENERATOR GenNewID TO ' + IntToStr(Max); end; end.
unit eUsusario.View.Conexao.Interfaces; interface uses Data.DB; Type iConexao = interface ['{C274FEBB-916D-43DB-BF6E-790E3622270E}'] function Connection : TCustomConnection; end; iQuery = interface ['{733D3424-1A9A-4948-ADC6-6CEA4B6F4B7C}'] function SQL(Value : String) : iQuery; function DataSet : TDataSet; function Open(aSQL : String) : iQuery; end; iEntidade = interface ['{832976AC-317B-4656-8A19-F771D6D5C1E2}'] function Listar(Value : TDataSource) : iEntidade; procedure Open; end; implementation end.
(* Design and define a class hierarchy, using composition, and test it. The first object is a real number with a floating point. Its parameters are its value and format. Its methods are the constructor and a function, which determines the number of digits after the floating point. The second object is a set of numbers. Determine the average of the said numbers and the average number of digits in the fractional part of each number. *) uses Math, SysUtils; type FDigits = class(TObject) function fracDigits(): Real; virtual; abstract; end; type Float = class(FDigits) significand: Cardinal; // base: Cardinal; // base = 10; exponent: Integer; value: Real; constructor Create(significand: Cardinal; exponent: Integer); function fracDigits(): Real; override; end; constructor Float.Create(significand: Cardinal; exponent: Integer); begin self.significand := significand; self.exponent := exponent; self.value := significand * Power(10, exponent); end; function Float.fracDigits(): Real; begin if (exponent > 0) then Result := 0 else Result := Abs(exponent) end; type FloatArray = array of Float; type FloatSet = class(FDigits) values: FloatArray; function average(): Real; function fracDigits(): Real; override; end; function FloatSet.average(): Real; var sum: Real; var len: Integer; var i: Integer; begin len := Length(values); sum := 0; for i := 0 to len-1 do sum := sum + values[i].value; Result := sum / len; end; function FloatSet.fracDigits(): Real; var sum: Real; var len: Integer; var i: Integer; begin len := Length(values); sum := 0; for i := 0 to len-1 do sum := sum + values[i].fracDigits(); Result := sum / len; end; var f,g,h: Float; var fset: FloatSet; begin f := Float.Create(421234, -4); WriteLn('f value: ', f.value:4:4); WriteLn('frac digits: ', f.fracDigits():4:2); g := Float.Create(9, 0); h := Float.Create(112, -2); fset := FloatSet.Create(); SetLength(fset.values, 3); fset.values[0] := f; fset.values[1] := g; fset.values[2] := h; WriteLn('fset average: ', fset.average():4:2); WriteLn('fset average frac digits: ', fset.fracDigits():4:2); fset.Destroy(); f.Destroy(); g.Destroy(); h.Destroy(); end.
{ ============================================ Software Name : RFID_ACCESS ============================================ } { ******************************************** } { Written By WalWalWalides } { CopyRight © 2019 } { Email : WalWalWalides@gmail.com } { GitHub :https://github.com/walwalwalides } { ******************************************** } unit uUser; interface uses System.SysUtils, System.Generics.Collections, VCL.Graphics, System.iOUtils, System.UITypes, VCL.Dialogs; type {$METHODINFO ON} TUser = class private _Id: integer; _FirstName: string; _LastName: string; _UID: string; procedure SetFirstName(const Value: string); procedure SetId(const Value: integer); procedure SetLastName(const Value: string); procedure SetUID(const Value: string); { Private declarations } public { Public declarations } // Constructor Create; overload; Constructor Create(Const lastName: string;Const firstName: string;Const UID: string); Property id: integer read _Id write SetId; Property firstName: string read _FirstName write SetFirstName; Property lastName: string read _LastName write SetLastName; property UID: string read _UID write SetUID ; end; {$METHODINFO OFF} implementation Constructor TUser.Create(Const lastName: string;Const firstName: string;Const UID: string); begin Self._FirstName := firstName; Self._LastName := lastName; Self._UID := UID end; procedure TUser.SetFirstName(const Value: string); begin _FirstName := Value; end; procedure TUser.SetId(const Value: integer); begin _Id := Value; end; procedure TUser.SetLastName(const Value: string); begin _LastName := Value; end; procedure TUser.SetUID(const Value: string); begin _UID := Value; end; end.
//****************************************************************************** // Пакет для добавленя, изменения, удаления данных о свойствах людей // параметры: ID - идентификатор, если добавление, то идентификатор человека, иначе // идентификатор свойства человека. //****************************************************************************** unit PeopleWorkMode_Ctrl_MainForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, StdCtrls, cxButtons, cxCalendar, cxTextEdit, cxMaskEdit, cxContainer, cxEdit, cxLabel, ExtCtrls, cxControls, cxGroupBox,ZMessages, ZProc, Unit_ZGlobal_Consts, FIBQuery, pFIBQuery, pFIBStoredProc, FIBDatabase, pFIBDatabase, DB, FIBDataSet, pFIBDataSet, ZTypes, IBase, ActnList, PeopleWorkMode_Ctrl_DM, ComCtrls, Grids, IBDatabase, Ibexternals; type TFSp_People_WorkMode_Control = class(TForm) IdentificationBox: TcxGroupBox; PeopleLabel: TcxLabel; PeopleEdit: TcxMaskEdit; PeriodBox: TcxGroupBox; YesBtn: TcxButton; CancelBtn: TcxButton; Bevel1: TBevel; WorkModeLabel: TcxLabel; PropEdit: TcxLookupComboBox; DateBegLabel: TcxLabel; DateBeg: TcxDateEdit; DateEndLabel: TcxLabel; DateEnd: TcxDateEdit; Actions: TActionList; ActionYes: TAction; WorkDogLabel: TcxLabel; cxMaskEdit1: TcxMaskEdit; Panel1: TPanel; cxLabel1: TcxLabel; cxTextEdit1: TcxTextEdit; UpDown1: TUpDown; WorkModeGrid: TStringGrid; procedure CancelBtnClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ActionYesExecute(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure PropEditPropertiesEditValueChanged(Sender: TObject); procedure DateBegPropertiesEditValueChanged(Sender: TObject); procedure DateEndPropertiesEditValueChanged(Sender: TObject); procedure cxTextEdit1PropertiesEditValueChanged(Sender: TObject); procedure DateBegPropertiesChange(Sender: TObject); procedure DateEndPropertiesChange(Sender: TObject); procedure PropEditPropertiesChange(Sender: TObject); procedure PropEditPropertiesCloseUp(Sender: TObject); private Ins_Id_Man:LongWord; PParameter:TZPeopleWorkModeParameters; DM:TDMWorkMode_Ctrl; PLanguageIndex:Byte; pNumPredpr:integer; public constructor Create(AOwner: TComponent;DB_Handle:TISC_DB_HANDLE;AParameters:TZPeopleWorkModeParameters;Is_Grant: TZChildSystems);reintroduce; procedure UpdateGrid; property ID_Man:LongWord read Ins_Id_Man write Ins_Id_Man; property Parameter:TZPeopleWorkModeParameters read PParameter; end; implementation uses StrUtils; {$R *.dfm} constructor TFSp_People_WorkMode_Control.Create(AOwner: TComponent;DB_Handle:TISC_DB_HANDLE;AParameters:TZPeopleWorkModeParameters;Is_Grant: TZChildSystems); begin inherited Create(AOwner); PParameter := AParameters; DM := TDMWorkMode_Ctrl.Create(AOwner,DB_Handle,AParameters,Is_Grant); PLanguageIndex:=LanguageIndex; pNumPredpr := StrToInt(VarToStrDef(ValueFieldZSetup(DB_Handle,'NUM_PREDPR'),'1')); //****************************************************************************** PeopleLabel.Caption := LabelMan_Caption[PLanguageIndex]; WorkModeLabel.Caption := 'Режим праці'; WorkDogLabel.Caption := 'Трудовий договір'; DateBegLabel.Caption := LabelDateBeg_Caption[PLanguageIndex]+' - '; DateEndLabel.Caption := ' - '+AnsiLowerCase(LabelDateEnd_Caption[PLanguageIndex]); YesBtn.Caption := YesBtn_Caption[PLanguageIndex]; CancelBtn.Caption := CancelBtn_Caption[PLanguageIndex]; //****************************************************************************** PropEdit.Properties.ListFieldNames := 'NAME'; PropEdit.Properties.KeyFieldNames :='ID_WORK_MODE'; PropEdit.Properties.DataController.DataSource := DM.DSourceProp; //****************************************************************************** case PParameter.ControlFormStyle of zcfsInsert: begin DateBeg.Properties.MaxDate := VarToDateTime(DM.DSetData['PER_DATE_BEG']); DateBeg.Properties.MinDate := VarToDateTime(DM.DSetData['PER_DATE_END']); DateEnd.Properties.MaxDate := VarToDateTime(DM.DSetData['PER_DATE_BEG']); DateEnd.Properties.MinDate := VarToDateTime(DM.DSetData['PER_DATE_END']); cxMaskEdit1.Text :=DM.DSetData['NAME_POST']; Caption := 'Додати режим праці'; PeopleEdit.Text := VarToStr(DM.DSetData.FieldValues['TN'])+' - '+VarToStr(DM.DSetData.FieldValues['FIO']); DateBeg.Date := VarToDateTime(DM.DSetData['PER_DATE_BEG']); DateEnd.Date := VarToDateTime(DM.DSetData['PER_DATE_END']); end; zcfsUpdate: begin DateBeg.Properties.MaxDate := VarToDateTime(DM.DSetData['PER_DATE_BEG']); DateBeg.Properties.MinDate := VarToDateTime(DM.DSetData['PER_DATE_END']); DateEnd.Properties.MaxDate := VarToDateTime(DM.DSetData['PER_DATE_BEG']); DateEnd.Properties.MinDate := VarToDateTime(DM.DSetData['PER_DATE_END']); cxMaskEdit1.Text :=DM.DSetData['NAME_POST']; Caption := 'Змінити режим праці'; PeopleEdit.Text := VarToStr(DM.DSetData['FIO']); DateBeg.Date := AParameters.date_beg; DateEnd.Date := AParameters.date_end; PropEdit.EditValue := AParameters.id_workmode; UpDown1.Position := AParameters.SHIFT; cxTextEdit1.EditValue := AParameters.SHIFT; end; zcfsShowDetails: begin cxMaskEdit1.Text :=DM.DSetData['NAME_POST']; Caption := 'Інформація по режиму праці'; PeopleEdit.Text := VarToStr(DM.DSetData['FIO']); DateBeg.Date := AParameters.date_beg; DateEnd.Date := AParameters.date_end; PropEdit.EditValue := AParameters.id_workmode; PeriodBox.Enabled := False; YesBtn.Visible := False; CancelBtn.Caption := ExitBtn_Caption[PLanguageIndex]; end; end; end; procedure TFSp_People_WorkMode_Control.CancelBtnClick(Sender: TObject); begin ModalResult:=mrCancel; end; procedure TFSp_People_WorkMode_Control.FormCreate(Sender: TObject); begin if PParameter.ControlFormStyle = zcfsDelete then begin if ZShowMessage(ZPeopleWorkModeCtrl_Caption_Delete[PLanguageIndex],DeleteRecordQuestion_Text[PLanguageIndex],mtConfirmation,[mbYes,mbNo])=mrYes then begin with DM do try StoredProc.Database := DB; StoredProc.Transaction := WriteTransaction; StoredProc.Transaction.StartTransaction; StoredProc.StoredProcName := 'Z_PEOPLE_WORKMODE_DELETE'; StoredProc.Prepare; StoredProc.ParamByName('ID_PEOPLE_WORKMODE').AsInteger := PParameter.ID; StoredProc.ExecProc; StoredProc.Transaction.Commit; ModalResult:=mrYes; except on E:Exception do begin ZShowMessage(Error_Caption[PLanguageIndex],E.Message,mtError,[mbOK]); StoredProc.Transaction.Rollback; end; end end else ModalResult:=mrCancel; end; end; procedure TFSp_People_WorkMode_Control.ActionYesExecute(Sender: TObject); var ID:integer; begin if PropEdit.EditText = '' then begin ZShowMessage(Error_Caption[PLanguageIndex],ZeInputProp_Error_Text[PLanguageIndex],mtWarning,[mbOK]); PropEdit.SetFocus; end else begin if DateBeg.Date>DateEnd.Date then begin ZShowMessage(Error_Caption[PLanguageIndex],ZeInputTerms_ErrorText[PLanguageIndex],mtWarning,[mbOK]); DateBeg.SetFocus; end else begin case PParameter.ControlFormStyle of zcfsInsert: with DM do try StoredProc.Database := DB; StoredProc.Transaction := WriteTransaction; StoredProc.Transaction.StartTransaction; StoredProc.StoredProcName := 'Z_PEOPLE_WORKMODE_INSERT'; StoredProc.Prepare; StoredProc.ParamByName('ID_WORKMODE').AsInteger := PropEdit.EditValue; StoredProc.ParamByName('ID_WORK_DOG_MOVING').AsInteger := PParameter.rmoving; StoredProc.ParamByName('DATE_BEG').AsDate := DateBeg.Date; StoredProc.ParamByName('DATE_END').AsDate := DateEnd.Date; StoredProc.ParamByName('SHIFT').Value := cxTextEdit1.EditValue; StoredProc.ExecProc; ID:=StoredProc.ParamByName('ID_PEOPLE_WORKMODE').AsInteger; StoredProc.Transaction.Commit; PParameter.ID := ID; ModalResult:=mrYes; except on E:Exception do begin ZShowMessage(Error_Caption[PLanguageIndex],E.Message,mtError,[mbOK]); StoredProc.Transaction.Rollback; end; end; zcfsUpdate: with DM do try StoredProc.Database := DB; StoredProc.Transaction := WriteTransaction; StoredProc.Transaction.StartTransaction; StoredProc.StoredProcName := 'Z_PEOPLE_WORKMODE_UPDATE'; StoredProc.Prepare; StoredProc.ParamByName('ID_PEOPLE_WORKMODE').AsInteger := PParameter.ID; StoredProc.ParamByName('ID_WORKMODE').AsInteger := PropEdit.EditValue; StoredProc.ParamByName('DATE_BEG').AsDate := DateBeg.Date; StoredProc.ParamByName('DATE_END').AsDate := DateEnd.Date; StoredProc.ParamByName('SHIFT').Value := cxTextEdit1.EditValue; StoredProc.ExecProc; StoredProc.Transaction.Commit; ModalResult:=mrYes; except on E:Exception do begin ZShowMessage(Error_Caption[PLanguageIndex],E.Message,mtError,[mbOK]); StoredProc.Transaction.Rollback; end; end; end; end; end; end; procedure TFSp_People_WorkMode_Control.FormDestroy(Sender: TObject); begin if DM<>nil then DM.Destroy; end; procedure TFSp_People_WorkMode_Control.PropEditPropertiesEditValueChanged( Sender: TObject); begin UpdateGrid; end; procedure TFSp_People_WorkMode_Control.DateBegPropertiesEditValueChanged( Sender: TObject); begin UpdateGrid; end; procedure TFSp_People_WorkMode_Control.DateEndPropertiesEditValueChanged( Sender: TObject); begin UpdateGrid; end; procedure TFSp_People_WorkMode_Control.cxTextEdit1PropertiesEditValueChanged( Sender: TObject); begin UpdateGrid; end; procedure TFSp_People_WorkMode_Control.DateBegPropertiesChange( Sender: TObject); begin UpdateGrid; end; procedure TFSp_People_WorkMode_Control.DateEndPropertiesChange( Sender: TObject); begin UpdateGrid; end; procedure TFSp_People_WorkMode_Control.PropEditPropertiesChange( Sender: TObject); begin UpdateGrid; end; procedure TFSp_People_WorkMode_Control.PropEditPropertiesCloseUp( Sender: TObject); begin UpdateGrid; end; procedure TFSp_People_WorkMode_Control.UpdateGrid; var Trans:TIBTransaction; DBib:TIBDatabase; begin WorkModeGrid.RowCount:=1; WorkModeGrid.ColCount:=1; Trans:=TIBTransaction.Create(self); DBib:=TIBDatabase.Create(self); DBib.SQLDialect:=3; DBib.DefaultTransaction:=Trans; DBib.SetHandle(Ibexternals.pvoid(DM.DB.Handle)); Trans.StartTransaction; if (PropEdit.EditValue>0) then begin if (PParameter.ControlFormStyle=zcfsInsert) then DrawWorkModeEx(WorkModeGrid,Date, IncMonth(Date),PropEdit.EditValue,cxTextEdit1.EditValue, Trans) else DrawWorkModeEx(WorkModeGrid,DateBeg.EditValue, IncMonth(Date),PropEdit.EditValue,cxTextEdit1.EditValue, Trans); end; Trans.Free; Dbib.Free; end; end.
unit PE.Parser.Import; interface uses System.Generics.Collections, System.SysUtils, PE.Common, PE.Types, PE.Types.Imports, PE.Types.FileHeader, PE.Imports, PE.Imports.Func, PE.Imports.Lib, PE.Utils; type TPEImportParser = class(TPEParser) public function Parse: TParserResult; override; end; implementation uses PE.Types.Directories, PE.Image; { TPEImportParser } function TPEImportParser.Parse: TParserResult; type TImpDirs = TList<TImportDirectoryTable>; TILTs = TList<TImportLookupTable>; var dir: TImageDataDirectory; bIs32: boolean; dq: uint64; sizet: byte; IDir: TImportDirectoryTable; IATRVA: uint64; PATCHRVA: uint64; // place where loader will put new address IDirs: TImpDirs; ILT: TImportLookupTable; ILTs: TILTs; ImpFn: TPEImportFunction; Lib: TPEImportLibrary; PE: TPEImage; LibraryName: string; dwLeft: uint32; bEmptyLastDirFound: boolean; IDirNumber: integer; begin PE := TPEImage(FPE); result := PR_ERROR; IDirs := TImpDirs.Create; ILTs := TILTs.Create; try PE.Imports.Clear; bIs32 := PE.Is32bit; sizet := PE.ImageBits div 8; // If no imports, it's ok. if not PE.DataDirectories.Get(DDIR_IMPORT, @dir) then exit(PR_OK); if dir.IsEmpty then exit(PR_OK); // Seek import dir. if not PE.SeekRVA(dir.VirtualAddress) then exit; // Read import descriptors. dwLeft := dir.Size; bEmptyLastDirFound := false; while dwLeft >= sizeof(IDir) do begin // Read IDir. if not PE.ReadEx(@IDir, sizeof(IDir)) then exit; if IDir.IsEmpty then // it's last dir begin bEmptyLastDirFound := true; break; end; // Check RVA. if not(PE.RVAExists(IDir.NameRVA)) then begin PE.Msg.Write(SCategoryImports, 'Bad RVAs in directory. Imports are incorrect.'); exit; end; IDirs.Add(IDir); // add read dir dec(dwLeft, sizeof(IDir)); end; if IDirs.Count = 0 then begin PE.Msg.Write(SCategoryImports, 'No directories found.'); exit; end; if not bEmptyLastDirFound then begin PE.Msg.Write(SCategoryImports, 'No last (empty) directory found.'); end; // Parse import descriptors. IDirNumber := -1; for IDir in IDirs do begin inc(IDirNumber); ILTs.Clear; // Read library name. if (not PE.SeekRVA(IDir.NameRVA)) then begin PE.Msg.Write(SCategoryImports, 'Library name RVA not found (0x%x) for dir # %d.', [IDir.NameRVA, IDirNumber]); Continue; end; LibraryName := PE.ReadAnsiString; if LibraryName.IsEmpty then begin PE.Msg.Write(SCategoryImports, 'Library # %d has empty name.', [IDirNumber]); Continue; end; PATCHRVA := IDir.FirstThunk; if PATCHRVA = 0 then begin PE.Msg.Write(SCategoryImports, 'Library # %d (%s) has NULL patch RVA.', [IDirNumber, LibraryName]); break; end; if IDir.ImportAddressTable <> 0 then IATRVA := IDir.ImportAddressTable else IATRVA := IDir.ImportLookupTableRVA; if IATRVA = 0 then begin PE.Msg.Write(SCategoryImports, 'Library # %d (%s) has NULL IAT RVA.', [IDirNumber, LibraryName]); break; end; // Lib will be created just in time. Lib := nil; // Read IAT elements. while PE.SeekRVA(IATRVA) do begin if not PE.ReadWordEx(0, @dq) then begin // Failed to read word and not null yet reached. FreeAndNil(Lib); PE.Msg.Write(SCategoryImports, 'Bad directory # %d. Skipped.', [IDirNumber]); break; end; if dq = 0 then break; ILT.Create(dq, bIs32); ImpFn := TPEImportFunction.CreateEmpty; // By ordinal. if ILT.IsImportByOrdinal then begin ImpFn.Ordinal := ILT.OrdinalNumber; ImpFn.Name := ''; end // By name. else if PE.SeekRVA(ILT.HintNameTableRVA) then begin dq := 0; PE.ReadEx(@dq, 2); ImpFn.Name := PE.ReadAnsiString; end; if not assigned(Lib) then begin // Create lib once in loop. // Added after loop (if not discarded). Lib := TPEImportLibrary.Create(LibraryName, IDir.IsBound, True); Lib.TimeDateStamp := IDir.TimeDateStamp; Lib.IATRVA := IATRVA; end; Lib.Functions.Add(ImpFn); inc(IATRVA, sizet); // next item inc(PATCHRVA, sizet); end; // If lib is generated, add it. if assigned(Lib) then PE.Imports.Add(Lib); end; result := PR_OK; finally IDirs.Free; ILTs.Free; end; end; end.
unit InfluxDB.Core; interface uses System.SysUtils, System.Classes, System.StrUtils, System.Net.HttpClient, System.Net.HttpClientComponent, System.NetEncoding, System.Generics.Collections; type TRequestMethod = (GET, POST, PUT, DELETE, PATCH); TRequest = class abstract (TInterfacedObject) private FHeaders: TDictionary<String, String>; FQueryParams: TDictionary<String, String>; FMethod: TRequestMethod; FAccept: String; FContentType: String; FClient: TNetHTTPClient; FHttp: TNetHTTPRequest; protected function GetMethod: TRequestMethod; procedure SetMethod(const Value: TRequestMethod); function GetHeaders: TDictionary<String, String>; function GetQueryParams: TDictionary<String, String>; function EncodeQueryParams: String; function GetNetHTTPRequest: TNetHTTPRequest; procedure InitializeRequest; virtual; procedure BeforeExecute; virtual; function Execute(Command: TRequestMethod; Url: String; PostData: TStream = nil): IHTTPResponse; overload; function Execute(Url: String; PostData: TStream = nil): IHTTPResponse; overload; public constructor Create; destructor Destroy; override; function Get(Url: String): IHTTPResponse; function Delete(Url: String): IHTTPResponse; function Post(Url: String; Data: TStream): IHTTPResponse; overload; function Post(Url: String; Data: String): IHTTPResponse; overload; function Put(Url: String; Data: TStream): IHTTPResponse; overload; function Put(Url: String; Data: String): IHTTPResponse; overload; function Patch(Url: String; Data: TStream): IHTTPResponse; overload; function Patch(Url: String; Data: String): IHTTPResponse; overload; property Header: TDictionary<String, String> read GetHeaders; property QueryParams: TDictionary<String, String> read GetQueryParams; property Method: TRequestMethod read GetMethod write SetMethod; property Accept: String read FAccept write FAccept; property ContentType: String read FContentType write FContentType; end; const HTTP_USER_AGENT = 'InfluxDB Client 1.0'; implementation { TRequest } procedure TRequest.BeforeExecute; begin if not Assigned(FClient) then InitializeRequest; end; constructor TRequest.Create; begin FHeaders := TDictionary<String, String>.Create; FQueryParams := TDictionary<String, String>.Create; end; function TRequest.Delete(Url: String): IHTTPResponse; begin Result := Execute(TRequestMethod.DELETE, Url); end; destructor TRequest.Destroy; begin FQueryParams.Free; FHeaders.Free; if Assigned(FClient) then begin FClient.Free; FHttp.Free; end; inherited; end; function TRequest.Execute(Command: TRequestMethod; Url: String; PostData: TStream): IHTTPResponse; begin Self.Method := Command; Result := Execute(Url, PostData); end; function TRequest.EncodeQueryParams: String; var Param: TPair<String, String>; begin Result := ''; for Param in QueryParams do begin if Result <> '' then Result := Result + '&'; Result := Result + TNetEncoding.URL.Encode(Param.Key) + '=' + TNetEncoding.URL.Encode(Param.Value); end; end; procedure TRequest.InitializeRequest; begin FClient := TNetHTTPClient.Create(nil); FHttp := TNetHTTPRequest.Create(nil); FHttp.Client := FClient; FClient.UserAgent := HTTP_USER_AGENT; end; function TRequest.Execute(Url: String; PostData: TStream = nil): IHTTPResponse; var Param: TPair<String, String>; begin BeforeExecute; FClient.ContentType := ContentType; FClient.Accept := Accept; for Param in Header do FHttp.CustomHeaders[Param.Key] := Param.Value; if QueryParams.Count > 0 then begin Url := Url + IfThen(Pos('?', Url) > 0, '&', '?') + EncodeQueryParams; end; case FMethod of TRequestMethod.GET: Result := FHttp.Get(Url); TRequestMethod.POST: Result := FHttp.Post(Url, PostData); TRequestMethod.PUT: Result := FHttp.Put(Url, PostData); TRequestMethod.DELETE: Result := FHttp.Delete(Url); TRequestMethod.PATCH: Result := FHttp.Patch(Url, PostData); end; end; function TRequest.GetNetHTTPRequest: TNetHTTPRequest; begin Result := FHttp; end; function TRequest.Get(Url: String): IHTTPResponse; begin Result := Execute(TRequestMethod.GET, Url); end; function TRequest.GetHeaders: TDictionary<String, String>; begin Result := FHeaders; end; function TRequest.GetMethod: TRequestMethod; begin Result := FMethod; end; function TRequest.GetQueryParams: TDictionary<String, String>; begin Result := FQueryParams; end; function TRequest.Patch(Url: String; Data: TStream): IHTTPResponse; begin Result := Execute(TRequestMethod.PATCH, Url, Data); end; function TRequest.Patch(Url, Data: String): IHTTPResponse; var DataStream: TStringStream; begin DataStream := TStringStream.Create(Data, TEncoding.UTF8); Result := Patch(Url, DataStream); DataStream.Free; end; function TRequest.Post(Url, Data: String): IHTTPResponse; var DataStream: TStringStream; begin DataStream := TStringStream.Create(Data, TEncoding.UTF8); Result := Post(Url, DataStream); DataStream.Free; end; function TRequest.Put(Url, Data: String): IHTTPResponse; var DataStream: TStringStream; begin DataStream := TStringStream.Create(Data, TEncoding.UTF8); Result := Put(Url, DataStream); DataStream.Free; end; function TRequest.Post(Url: String; Data: TStream): IHTTPResponse; begin Result := Execute(TRequestMethod.POST, Url, Data); end; function TRequest.Put(Url: String; Data: TStream): IHTTPResponse; begin Result := Execute(TRequestMethod.PUT, Url, Data); end; procedure TRequest.SetMethod(const Value: TRequestMethod); begin FMethod := Value; end; end.
{ SuperMaximo GameLibrary : Graphical Asset class (sprites, models and gameObjects) unit by Max Foster License : http://creativecommons.org/licenses/by/3.0/ } unit GraphicalAssetClasses; {$mode objfpc}{$H+} interface uses SDL, dglOpenGL, Display, ShaderClass; type pSpriteDrawParams = ^tSpriteDrawParams; PSprite = ^TSprite; pkeyFrame = ^keyFrame; pbone = ^bone; ptriangle = ^triangle; pbox = ^box; PModel = ^TModel; PGameObject = ^TGameObject; customSpriteBufferFunctionType = procedure(buffer : PGLuint; sprite : PSprite; data : Pointer); customModelBufferFunctionType = procedure(buffer : PGLuint; sprite : PModel; data : Pointer); tSpriteDrawParams = record x, y, depth, rotation, xScale, yScale, alpha, frame : real; end; TSprite = object private image : PSDL_Surface; texture_ : array of GLuint; frames, vertices_, framerate_ : word; originX_, originY_ : integer; name_ : string; rect_ : SDL_Rect; vao_, vbo_ : GLuint; boundShader_ : PShader; customDrawFunction : customDrawFunctionType; procedure initBuffer; public //Create a sprite with the specified name, loaded from a file. 'imageX/Y' are the coordinates of where to start 'cutting out' the sprite //from the image provided, and 'imageWidth/Height' are the width and height of the new sprite. 'aniframes' is the number of frames that //the sprite has, if provided on a spritesheet, and 'framerate' lets you set the animation speed in frames per second. 'newOrignX/Y' is the //point on the sprite where it will pivot for rotation. 'customBufferFunction' allows you to pass a procedure pointer to your own sprite //buffering procedure for advanced usage and 'customData' allows you to pass a pointer to the data you want to access in your custom buffer //procedure constructor create(newName, fileName : string; imageX, imageY, imageWidth, imageHeight : integer; aniframes : integer = 1; framerate : word = 1; newOriginX : integer = 0; newOriginY : integer = 0; customBufferFunction : customSpriteBufferFunctionType = nil; customData : Pointer = nil); destructor destroy; function name : string; function frameCount : word; procedure setFramerate(newFramerate : word); function framerate : word; function rect : SDL_Rect; function originX : integer; function originY : integer; //Draws the sprite with the specified coordinates and transformations. 'alpha' is only for a convienience if you want to use it in a //custom draw procedure where you send the alpha value as a shader uniform. The frame is used when using spritesheets. You can override //the shader bound to the sprite or globally with 'shaderOverride' and override the drawing procedure with 'customDrawFunctionOverride' procedure draw(x, y, depth : real; rotation : real = 0.0; xScale : real = 1.0; yScale : real = 1.0; alpha : real = 1.0; frame : real = 1.0; shaderOverride : PShader = nil; customDrawFunctionOverride : customDrawFunctionType = nil); procedure draw(objectParam : PGameObject); //Draws the sprite from the details of a GameObject procedure defaultDraw(shaderToUse : PShader; params : pSpriteDrawParams); //The default drawing procedure for the sprite function width : integer; function height : integer; function surface : PSDL_Surface; function texture(frame : word) : GLuint; //Return the OpenGL texture ID for passing to OpenGL functions function vertices : word; //Bind a shader to be used with the sprite instead of using one that is globally bound with globalBindShader or 'Shader.bind' procedure bindShader(newShader : PShader); function boundShader : PShader; //Bind a custom draw procedure to be used when the sprite is drawn procedure bindCustomDrawFunction(newCustomDrawFunction : customDrawFunctionType); function boundCustomDrawFunction : customDrawFunctionType; //Returns the OpenGL Vertex Array Object contained in the Sprite function vao : GLuint; //Returns the OpenGL Vertex Buffer Object contained in the Sprite function vbo : GLuint; end; keyFrameData = record boneId : integer; xRot, yRot, zRot : real; end; keyFrame = record boneData : array of keyFrameData; step : word; end; normal = record x, y, z : real; end; vertex = record x, y, z : real; normal_ : normal; end; color = record r, g, b : real; end; material = record name, fileName : string; textureId : integer; hasTexture : boolean; ambientColor, diffuseColor, specularColor : color; shininess, alpha : real; end; triangle = record coords, texCoords : array[0..2] of vertex; mtlNum, boneId : integer; pBone_ : pbone; sharedCoord : array[0..2] of boolean; end; box = record x, y, z, l, w, h, xRot, yRot, zRot, rl, rw, rh : real; end; bone = record id, offset : integer; x, y, z, endX, endY, endZ, xRot, yRot, zRot : real; parent : pBone; child : array of pbone; triangles : array of ptriangle; hitbox : box; end; animation = record name : string; frames : array of keyFrame; end; TModel = object private name_ : string; triangles : array of triangle; materials : array of material; bones : array of pbone; animations : array of animation; vao, vbo, texture : GLuint; boundShader_ : PShader; loadedFromObj : boolean; framerate_ : word; //Has not been implemented procedure loadObj(path, fileName : string; customBufferFunction : customModelBufferFunctionType = nil; customData : Pointer = nil); //Load SuperMaximo* files procedure loadSmm(fileName : string); //SuperMaximo Model procedure loadSms(fileName : string); //SuperMaximo Skeleton procedure loadSma(fileName : string); //SuperMaximo Animation procedure loadSmo(path, fileName : string; customBufferFunction : customModelBufferFunctionType = nil; customData : Pointer = nil); //SuperMaximo Object //Buffer the vertex data for each file type procedure initBufferObj; procedure initBufferSmo; procedure drawObj(shaderToUse : PShader); function calculatePoints(nx, ny, nz : real; matrix : matrix4d) : normal; procedure calculateHitbox(pBone_ : pbone; matrix : matrix4d); procedure drawBone(pBone_ : pbone; shaderToUse : PShader; skipHitboxes : boolean = false); public //Loads a model, from the path and file name constructor create(newName, path, fileName : string; framerate : word = 60; customBufferFunction : customModelBufferFunctionType = nil; customData : Pointer = nil); destructor destroy; function name : string; //Draw the model using details from a GameObject. You can skip animation and hitbox orientation to save processing time //NOTE: The hitboxes probably don't work, and have actually been removed from the latest version of the library! procedure draw(objectParam : PGameObject; skipAnimation : boolean = false; skipHitboxes : boolean = false); //Bind a shader to be used when drawing the model instead of a globally bound one procedure bindShader(newShader : PShader); function boundShader : PShader; function animationId(searchName : string) : integer; //Return the ID of an animation with the specified name (-1 is returned on failure) procedure setFramerate(newFramerate : word); function framerate : word; end; TGameObject = object protected sprite_ : PSprite; model_ : PModel; hasModel_, interpolating_ : boolean; currentAnimationId, nextAnimationId : word; x_, y_, z_, xRotation_, yRotation_, zRotation_, xScale_, yScale_, zScale_, width_, height_, alpha_, xRotatedWidth_, yRotatedWidth_, zRotatedWidth_, xRotatedHeight_, yRotatedHeight_, zRotatedHeight_, originX, originY, frame_ : real; name_ : string; boundShader_ : PShader; customDrawFunction : customDrawFunctionType; fakeKeyFrame1, fakeKeyFrame2 : pkeyFrame; public //Create a GameObject at the specified coordinates with either a sprite or model bound to it constructor create(newName : string; destX, destY, destZ : real; newSprite : PSprite = nil; startFrame : word = 0); constructor create(newName : string; destX, destY, destZ : real; newModel : PModel = nil); destructor destroy; function name : string; procedure setSprite(newSprite : PSprite); function sprite : PSprite; procedure setModel(newModel : PModel); function model : PModel; function hasModel : boolean; //Bind a shader to be used when drawing instead of the globally bound one procedure bindShader(shader : PShader); function boundShader : PShader; //Bind a custom draw procedure to be used when drawing the object procedure bindCustomDrawFunction(newCustomDrawFunction : customDrawFunctionType); function boundCustomDrawFunction : customDrawFunctionType; procedure setPosition(xAmount, yAmount, zAmount : real; relative : boolean = false); function setX(amount : real; relative : boolean = false) : real; function setY(amount : real; relative : boolean = false) : real; function setZ(amount : real; relative : boolean = false) : real; function x : real; function y : real; function z : real; function width : real; function height : real; procedure calcZRotatedDimensions; procedure scale(xAmount, yAmount, zAmount : real; relative : boolean = false; recalculateDimensions : boolean = true); function xScale : real; function yScale : real; function zScale : real; //Rotate by an amount around each axis. Set 'recalculateDimensions' to recalculate sprite bounds for collisions procedure rotate(xAmount, yAmount, zAmount : real; relative : boolean = false; recalculateDimensions : boolean = true); function rotate(amount : real; relative : boolean = false; recalculateDimensions : boolean = true) : real; //2D rotation (i.e. around Z axis) function xRotation : real; function yRotation : real; function zRotation : real; function setAlpha(amount : real; relative : boolean = false) : real; function alpha : real; //Set and get the animation that the object is playing procedure setCurrentAnimation(animationId : word); function currentAnimation : word; procedure setFrame(newFrame : real; relative : boolean = false); function frame : real; procedure animate(start, finish : word; animationId : word = 0); //Animate between two particular frames //Interpolate between the frame of one animation and the frame of another animation, over a set time period in frames procedure setInterpolation(startFrame, animation1Id, endFrame, animation2Id, numFramesToTake : integer); procedure setInterpolation; //Stop interpolation function interpolating : boolean; procedure draw(skipAnimation : boolean = false; skipHitboxes : boolean = false); //2D collision detection for sprites function mouseOverBox : boolean; function roughMouseOverBox : boolean; function mouseOverCircle(extraX : real = 0; extraY : real = 0; extraZ : real = 0) : boolean; function boxCollision(other : PGameObject; allStages : boolean = true) : boolean; function roughBoxCollision(other : PGameObject) : boolean; function circleCollision(other : PGameObject; extraX1 : real = 0; extraY1 : real = 0; extraZ1 : real = 0; extraX2 : real = 0; extraY2 : real = 0; extraZ2 : real = 0) : boolean; //3D hitbox collision detection //NOTE: Does not work, and has been removed from newer versions of the library! function roughHitboxCollision(bone1, bone2 : pbone) : boolean; function hitBoxCollision(bone1, bone2 : pbone) : boolean; function roughModelCollision(other : PGameObject; hitboxId : integer = -1; hitboxOtherId : integer = -1) : boolean; function modelCollision(other : PGameObject; hitboxId : integer = -1; hitboxOtherId : integer = -1) : boolean; end; //Set a model to be in a particular pose from data in a keyframe procedure setKeyFrame(frame : pkeyFrame; model : PModel); function subtractNormal(operandNormal, subtractingNormal : normal) : normal; function subtractVertex(operandVertex, subtractingVertex : vertex) : vertex; //Get the surface normal of a triangle in 3D space function getSurfaceNormal(srcTriangle : ptriangle) : normal; //Initialise the variables in a box procedure initBox(dstBox : pbox); function sprite(searchName : string) : PSprite; function addSprite(newName, fileName : string; imageX, imageY, imageWidth, imageHeight : integer; aniframes : integer = 1; frameChangePerSecond : integer = 1; newOriginX : integer = 0; newOriginY : integer = 0; customBufferFunction : customSpriteBufferFunctionType = nil; customData : Pointer = nil) : PSprite; procedure destroySprite(searchName : string); procedure destroyAllSprites; function model(searchName : string) : PModel; function addModel(newName, path, fileName : string; framerate : word = 60; customBufferFunction : customModelBufferFunctionType = nil; customData : Pointer = nil) : PModel; procedure destroyModel(searchName : string); procedure destroyAllModels; function gameObject(searchName : string) : PGameObject; function addGameObject(newName : string; destX, destY, destZ : real; newSprite : PSprite = nil; startFrame : word = 0) : PGameObject; function addGameObject(newName : string; destX, destY, destZ : real; newModel : PModel = nil) : PGameObject; procedure destroyGameObject(searchName : string); procedure destroyAllGameObjects; implementation uses SysUtils, Classes, Math, SDL_image, Input; var allSprites : array['a'..'z'] of TList; allModels : array['a'..'z'] of TList; allGameObjects : array['a'..'z'] of TList; constructor TSprite.create(newName, fileName : string; imageX, imageY, imageWidth, imageHeight : integer; aniframes : integer = 1; framerate : word = 1; newOriginX : integer = 0; newOriginY : integer = 0; customBufferFunction : customSpriteBufferFunctionType = nil; customData : Pointer = nil); var textureFormat : GLenum; tempSurface : PSDL_Surface; tempRect : SDL_Rect; i, frame, row, numFrames : integer; begin name_ := newName; fileName := setDirSeparators(fileName); frames := aniFrames; framerate_ := framerate; rect_.x := imageX; rect_.y := imageY; rect_.w := imageWidth; rect_.h := imageHeight; originX_ := newOriginX; originY_ := newOriginY; customDrawFunction := nil; image := IMG_Load(pchar(fileName)); if (image = nil) then writeln('Could not load image ', fileName) else begin SDL_SetAlpha(image, 0, 0); if (image^.format^.BytesPerPixel = 4) then begin if (image^.format^.Rmask = $000000ff) then textureFormat := GL_RGBA else textureFormat := GL_BGRA; end else begin if (image^.format^.Rmask = $000000ff) then textureFormat := GL_RGB else textureFormat := GL_BGR; end; tempSurface := SDL_CreateRGBSurface(SDL_HWSURFACE, rect_.w, rect_.h, image^.format^.BitsPerPixel, image^.format^.Rmask, image^.format^.Gmask, image^.format^.Bmask, image^.format^.Amask); tempRect := rect_; for i := 0 to frames-1 do begin setLength(texture_, length(texture_)+1); glGenTextures(1, @texture_[i]); frame := i; row := 0; numFrames := image^.w div rect_.w; if (numFrames > 0) then begin while (frame-(row*numFrames) >= numFrames) do begin row += 1; frame -= numFrames; end end; tempRect.x := frame*rect_.w; tempRect.y := row*rect_.h; SDL_BlitSurface(image, @tempRect, tempSurface, nil); glBindTexture(GL_TEXTURE_RECTANGLE, texture_[i]); glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_RECTANGLE, 0, tempSurface^.format^.BytesPerPixel, rect_.w, rect_.h, 0, textureFormat, GL_UNSIGNED_BYTE, tempSurface^.pixels); end; SDL_FreeSurface(tempSurface); end; boundShader_ := nil; vertices_ := 6; if (vertexArrayObjectSupported) then begin glGenVertexArrays(1, @vao_); glBindVertexArray(vao_); end; if (customBufferFunction = nil) then initBuffer else customBufferFunction(@vbo_, @self, customData); if (vertexArrayObjectSupported) then glBindVertexArray(0); for i := 0 to 15 do glDisableVertexAttribArray(i); glBindTexture(GL_TEXTURE_RECTANGLE, 0); end; destructor TSprite.destroy; var i : integer; begin if (image <> nil) then begin SDL_FreeSurface(image); for i := 0 to frames-1 do glDeleteTextures(1, @texture_[i]); if (vertexArrayObjectSupported) then glDeleteVertexArrays(1, @vao_); glDeleteBuffers(1, @vbo_); end; end; procedure TSprite.initBuffer; var vertexArray : array[0..23] of GLfloat = (0.0, 1, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1, 0.0, 0.0, 1.0, 0.0, 1, 0.0, 1.0, 1, 1, 0.0, 1.0, 1, 0.0, 0.0, 1.0); begin vertexArray[1] := rect_.h; vertexArray[8] := rect_.w; vertexArray[13] := rect_.h; vertexArray[16] := rect_.w; vertexArray[17] := rect_.h; vertexArray[20] := rect_.w; glGenBuffers(1, @vbo_); glBindBuffer(GL_ARRAY_BUFFER, vbo_); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*length(vertexArray), @vertexArray, GL_STATIC_DRAW); if (vertexArrayObjectSupported) then begin glVertexAttribPointer(VERTEX_ATTRIBUTE, 4, GL_FLOAT, false, 0, nil); glEnableVertexAttribArray(VERTEX_ATTRIBUTE); end; glBindBuffer(GL_ARRAY_BUFFER, 0); end; function TSprite.name : string; begin result := name_; end; function TSprite.frameCount : word; begin result := frames; end; procedure TSprite.setFramerate(newFramerate : word); begin framerate_ := newFramerate; if (framerate_ = 0) then framerate_ := 1; end; function TSprite.framerate : word; begin result := framerate_; end; function TSprite.rect : SDL_Rect; begin result := rect_; end; function TSprite.originX : integer; begin result := originX_; end; function TSprite.originY : integer; begin result := originY_; end; procedure TSprite.draw(x, y, depth : real; rotation : real = 0.0; xScale : real = 1.0; yScale : real = 1.0; alpha : real = 1.0; frame : real = 1.0; shaderOverride : PShader = nil; customDrawFunctionOverride : customDrawFunctionType = nil); var shaderToUse : PShader; drawFunctionToUse : customDrawFunctionType; params : tSpriteDrawParams; begin if (shaderOverride <> nil) then shaderToUse := shaderOverride else if (boundShader_ <> nil) then shaderToUse := boundShader_ else shaderToUse := globalBoundShader; if (customDrawFunctionOverride <> nil) then drawFunctionToUse := customDrawFunctionOverride else if (customDrawFunction <> nil) then drawFunctionToUse := customDrawFunction else drawFunctionToUse := globalBoundCustomDrawFunction; params.x := x; params.y := y; params.depth := depth; params.rotation := rotation; params.xScale := xScale; params.yScale := yScale; params.alpha := alpha; params.frame := frame; if (drawFunctionToUse <> nil) then drawFunctionToUse(@self, shaderToUse, @params) else defaultDraw(shaderToUse, @params); if (globalBoundShader <> nil) then glUseProgram(globalBoundShader^.getProgram) else glUseProgram(0); end; procedure TSprite.draw(objectParam : PGameObject); begin draw(objectParam^.x_, objectParam^.y_, objectParam^.z_, objectParam^.zRotation_, objectParam^.xScale_, objectParam^.yScale_, objectParam^.alpha_, objectParam^.frame_, objectParam^.boundShader_, objectParam^.customDrawFunction); end; procedure TSprite.defaultDraw(shaderToUse : PShader; params : pSpriteDrawParams); var frameToUse : integer; begin if (shaderToUse <> nil) then begin while (params^.frame >= frames) do params^.frame -= 1; glActiveTexture(GL_TEXTURE0); frameToUse := round(params^.frame); while (frameToUse >= length(texture_)) do frameToUse -= 1; if (frameToUse < 0) then frameToUse := 0; glBindTexture(GL_TEXTURE_RECTANGLE, texture_[frameToUse]); pushMatrix; translateMatrix(params^.x-originX_, params^.y-originY_, params^.depth); translateMatrix(originX_, originY_, 0.0); rotateMatrix(params^.rotation, 0.0, 0.0, 1.0); scaleMatrix(params^.xScale, params^.yScale, 0.0); translateMatrix(-originX_, -originY_, 0.0); glUseProgram(shaderToUse^.getProgram); shaderToUse^.setUniform16(MODELVIEW_LOCATION, getMatrix(MODELVIEW_MATRIX)); shaderToUse^.setUniform16(PROJECTION_LOCATION, getMatrix(PROJECTION_MATRIX)); shaderToUse^.setUniform1(TEXSAMPLER_LOCATION, 0); if (vertexArrayObjectSupported) then begin glBindVertexArray(vao_); glBindBuffer(GL_ARRAY_BUFFER, vbo_); end else begin glBindBuffer(GL_ARRAY_BUFFER, vbo_); glVertexAttribPointer(VERTEX_ATTRIBUTE, 4, GL_FLOAT, false, 0, nil); glEnableVertexAttribArray(VERTEX_ATTRIBUTE); end; glDrawArrays(GL_TRIANGLES, 0, vertices_); glBindBuffer(GL_ARRAY_BUFFER, 0); if (vertexArrayObjectSupported) then glBindVertexArray(0) else glDisableVertexAttribArray(VERTEX_ATTRIBUTE); popMatrix; end; end; function TSprite.width : integer; begin result := rect_.w; end; function TSprite.height : integer; begin result := rect_.h end; function TSprite.surface : PSDL_Surface; begin result := image; end; function TSprite.texture(frame : word) : GLuint; begin if (frame >= frames) then frame := frames-1; result := texture_[frame]; end; function TSprite.vertices : word; begin result := vertices_; end; procedure TSprite.bindShader(newShader : PShader); begin boundShader_ := newShader; end; function TSprite.boundShader : PShader; begin result := boundShader_; end; procedure TSprite.bindCustomDrawFunction(newCustomDrawFunction : customDrawFunctionType); begin customDrawFunction := newCustomDrawFunction; end; function TSprite.boundCustomDrawFunction : customDrawFunctionType; begin result := customDrawFunction; end; function TSprite.vao : GLuint; begin result := vao_; end; function TSprite.vbo : GLuint; begin result := vbo_; end; constructor TModel.create(newName, path, fileName : string; framerate : word = 60; customBufferFunction : customModelBufferFunctionType = nil; customData : Pointer = nil); begin name_ := newName; path := setDirSeparators(path); boundShader_ := nil; framerate_ := framerate; if (lowerCase(rightStr(fileName, 3)) = 'smo') then loadSmo(path, fileName, customBufferFunction, customData) else if (lowerCase(rightStr(fileName, 3)) = 'obj') then loadObj(path, fileName, customBufferFunction, customData); end; destructor TModel.destroy; var i : integer; begin glDeleteTextures(1, @texture); if (length(bones) > 0) then begin for i := 0 to length(bones)-1 do dispose(bones[i]); end; glDeleteBuffers(1, @vbo); if (vertexArrayObjectSupported) then glDeleteVertexArrays(1, @vao); end; procedure TModel.loadObj(path, fileName : string; customBufferFunction : customModelBufferFunctionType = nil; customData : Pointer = nil); begin end; procedure TModel.loadSmm(fileName : string); var fileText : array of string; modelFile : text; tempStr : string; totalTriangles, totalMaterials, size : longword; newTriangle : triangle; i, j, null : integer; newMaterial : material; image : PSDL_Surface; textureFormat : GLenum; initialised : boolean; begin setLength(fileText, 0); assign(modelFile, fileName); reset(modelFile); repeat readln(modelFile, tempStr); while ((rightStr(tempStr, 1) = #13) or (rightStr(tempStr, 1) = #10)) do tempStr := leftStr(tempStr, length(tempStr)-1); setLength(fileText, length(fileText)+1); fileText[length(fileText)-1] := tempStr; until Eof(modelFile); close(modelFile); while (fileText[length(fileText)-1] = '') do setLength(fileText, length(fileText)-1); setLength(triangles, 0); totalTriangles := strToInt(fileText[0]); for i := 0 to totalTriangles-1 do begin for j := 0 to 2 do begin val(fileText[(i*32)+(j*6)+1], newTriangle.coords[j].x, null); val(fileText[(i*32)+(j*6)+2], newTriangle.coords[j].y, null); val(fileText[(i*32)+(j*6)+3], newTriangle.coords[j].z, null); val(fileText[(i*32)+(j*6)+4], newTriangle.coords[j].normal_.x, null); val(fileText[(i*32)+(j*6)+5], newTriangle.coords[j].normal_.y, null); val(fileText[(i*32)+(j*6)+6], newTriangle.coords[j].normal_.z, null); end; for j := 0 to 2 do begin val(fileText[(i*32)+(j*3)+19], newTriangle.texCoords[j].x, null); val(fileText[(i*32)+(j*3)+20], newTriangle.texCoords[j].y, null); val(fileText[(i*32)+(j*3)+21], newTriangle.texCoords[j].z, null); end; newTriangle.mtlNum := strToInt(fileText[(i*32)+28]); for j := 0 to 2 do begin if (strToInt(fileText[(i*32)+j+29]) = 1) then newTriangle.sharedCoord[j] := true else newTriangle.sharedCoord[j] := false; end; if (strToInt(fileText[(i*32)+32]) < 0) then newTriangle.pBone_ := nil else newTriangle.pBone_ := bones[strToInt(fileText[(i*32)+32])]; setLength(triangles, length(triangles)+1); triangles[length(triangles)-1] := newTriangle; end; setLength(materials, 0); totalTriangles *= 32; totalMaterials := strToInt(fileText[totalTriangles+1]); initialised := false; for i := 0 to totalMaterials-1 do begin newMaterial.name := fileText[totalTriangles+(i*14)+2]; newMaterial.fileName := setDirSeparators(fileText[totalTriangles+(i*14)+3]); val(fileText[totalTriangles+(i*14)+4], newMaterial.ambientColor.r, null); val(fileText[totalTriangles+(i*14)+5], newMaterial.ambientColor.g, null); val(fileText[totalTriangles+(i*14)+6], newMaterial.ambientColor.b, null); val(fileText[totalTriangles+(i*14)+7], newMaterial.diffuseColor.r, null); val(fileText[totalTriangles+(i*14)+8], newMaterial.diffuseColor.g, null); val(fileText[totalTriangles+(i*14)+9], newMaterial.diffuseColor.b, null); val(fileText[totalTriangles+(i*14)+10], newMaterial.specularColor.r, null); val(fileText[totalTriangles+(i*14)+11], newMaterial.specularColor.g, null); val(fileText[totalTriangles+(i*14)+12], newMaterial.specularColor.b, null); val(fileText[totalTriangles+(i*14)+13], newMaterial.shininess, null); val(fileText[totalTriangles+(i*14)+14], newMaterial.alpha); if (strToInt(fileText[totalTriangles+(i*14)+15]) = 1) then newMaterial.hasTexture := true else newMaterial.hasTexture := false; newMaterial.textureId := -1; if (newMaterial.hasTexture) then begin image := IMG_Load(pchar(newMaterial.fileName)); if (image = nil) then writeln('Could not load texture ', newMaterial.fileName) else begin if (image^.format^.BytesPerPixel = 4) then begin if (image^.format^.Rmask = $000000ff) then textureFormat := GL_RGBA else textureFormat := GL_BGRA; end else begin if (image^.format^.Rmask = $000000ff) then textureFormat := GL_RGB else textureFormat := GL_BGR; end; if (not initialised) then begin initialised := true; if (glSlVersion < 1.5) then begin glGenTextures(1, @texture); glBindTexture(GL_TEXTURE_2D, texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); glTexImage2D(GL_TEXTURE_2D, 0, image^.format^.BytesPerPixel, image^.w*totalMaterials, image^.h, 0, textureFormat, GL_UNSIGNED_BYTE, nil); end else begin glGenTextures(1, @texture); glBindTexture(GL_TEXTURE_2D_ARRAY, texture); glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_GENERATE_MIPMAP, GL_TRUE); glTexImage3D(GL_TEXTURE_2D_ARRAY, 0, image^.format^.BytesPerPixel, image^.w, image^.h, totalMaterials, 0, textureFormat, GL_UNSIGNED_BYTE, nil); end; end; if (glSlVersion < 1.5) then glTexSubImage2D(GL_TEXTURE_2D, 0, image^.w*i, 0, image^.w, image^.h, textureFormat, GL_UNSIGNED_BYTE, image^.pixels) else glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, i, image^.w, image^.h, 1, textureFormat, GL_UNSIGNED_BYTE, image^.pixels); SDL_FreeSurface(image); newMaterial.textureId := i; end; end; size := length(materials); setLength(materials, size+1); materials[size] := newMaterial; end; if (glSlVersion < 1.5) then glBindTexture(GL_TEXTURE_2D, 0) else glBindTexture(GL_TEXTURE_2D_ARRAY, 0); for i := 0 to length(triangles)-1 do begin if (triangles[i].pBone_ <> nil) then begin size := length(triangles[i].pBone_^.triangles); setLength(triangles[i].pBone_^.triangles, size+1); triangles[i].pBone_^.triangles[size] := @triangles[i]; end; end; end; procedure TModel.loadSms(fileName : string); var fileText : array of string; skeletonFile : text; tempStr : string; i, j, totalBones, null, size : integer; b : pbone; begin setLength(fileText, 0); assign(skeletonFile, fileName); reset(skeletonFile); repeat readln(skeletonFile, tempStr); while ((rightStr(tempStr, 1) = #13) or (rightStr(tempStr, 1) = #10)) do tempStr := leftStr(tempStr, length(tempStr)-1); setLength(fileText, length(fileText)+1); fileText[length(fileText)-1] := tempStr; until Eof(skeletonFile); close(skeletonFile); while (fileText[length(fileText)-1] = '') do setLength(fileText, length(fileText)-1); if (length(triangles) > 0) then for i := 0 to length(triangles)-1 do triangles[i].pBone_ := nil; if (length(bones) > 0) then for i := 0 to length(bones)-1 do dispose(bones[i]); setLength(bones, 0); totalBones := strToInt(fileText[0]); for i := 0 to totalBones-1 do begin setLength(bones, length(bones)+1); bones[i] := new(pbone); b := bones[i]; setLength(b^.triangles, 0); b^.id := strToInt(fileText[(i*17)+1]); val(fileText[(i*17)+2], b^.x, null); val(fileText[(i*17)+3], b^.y, null); val(fileText[(i*17)+4], b^.z, null); val(fileText[(i*17)+5], b^.endX, null); val(fileText[(i*17)+6], b^.endY, null); val(fileText[(i*17)+7], b^.endZ, null); if (strToInt(fileText[(i*17)+8]) > -1) then b^.parent := bones[strToInt(fileText[(i*17)+8])] else b^.parent := nil; initBox(@b^.hitbox); val(fileText[(i*17)+9], b^.hitbox.x, null); val(fileText[(i*17)+10], b^.hitbox.y, null); val(fileText[(i*17)+11], b^.hitbox.z, null); val(fileText[(i*17)+12], b^.hitbox.l, null); val(fileText[(i*17)+13], b^.hitbox.w, null); val(fileText[(i*17)+14], b^.hitbox.h, null); val(fileText[(i*17)+15], b^.hitbox.xRot, null); val(fileText[(i*17)+16], b^.hitbox.yRot, null); val(fileText[(i*17)+17], b^.hitbox.zRot, null); b^.hitBox.rl := b^.hitBox.l; b^.hitBox.rw := b^.hitBox.w; b^.hitBox.rh := b^.hitBox.h; end; for i := 0 to length(bones)-1 do begin for j := 0 to length(bones)-1 do if (bones[i] = bones[j]^.parent) then begin size := length(bones[i]^.child); setLength(bones[i]^.child, size+1); bones[i]^.child[size] := bones[j]; end; end; for i := 0 to length(triangles)-1 do begin if (triangles[i].boneId > -1) then triangles[i].pBone_ := bones[triangles[i].boneId] else triangles[i].pBone_ := nil; end; end; procedure TModel.loadSma(fileName : string); var fileText : array of string; animationFile : text; tempStr : string; i, j, totalFrames, line, totalBoneData, null, size : integer; newAnimation : animation; newFrame : keyFrame; newBoneData : keyFrameData; begin setLength(fileText, 0); assign(animationFile, fileName); reset(animationFile); repeat readln(animationFile, tempStr); while ((rightStr(tempStr, 1) = #13) or (rightStr(tempStr, 1) = #10)) do tempStr := leftStr(tempStr, length(tempStr)-1); setLength(fileText, length(fileText)+1); fileText[length(fileText)-1] := tempStr; until Eof(animationFile); close(animationFile); while (fileText[length(fileText)-1] = '') do setLength(fileText, length(fileText)-1); newAnimation.name := fileText[0]; totalFrames := strToInt(fileText[1]); line := 2; for i := 0 to totalFrames-1 do begin setLength(newFrame.boneData, 0); newFrame.step := strToInt(fileText[line]); line += 1; totalBoneData := strToInt(fileText[line]); line += 1; for j := 0 to totalBoneData-1 do begin newBoneData.boneId := strToInt(fileText[line]); line += 1; val(fileText[line], newBoneData.xRot, null); line += 1; val(fileText[line], newBoneData.yRot, null); line += 1; val(fileText[line], newBoneData.zRot, null); line += 1; size := length(newFrame.boneData); setLength(newFrame.boneData, size+1); newFrame.boneData[size] := newBoneData; end; size := length(newAnimation.frames); setLength(newAnimation.frames, size+1); newAnimation.frames[size] := newFrame; end; size := length(animations); setLength(animations, size+1); animations[size] := newAnimation; end; procedure TModel.loadSmo(path, fileName : string; customBufferFunction : customModelBufferFunctionType = nil; customData : Pointer = nil); var fileText : array of string; objectFile : text; tempStr : string; i : integer; begin setLength(fileText, 0); assign(objectFile, path+fileName); reset(objectFile); repeat readln(objectFile, tempStr); while ((rightStr(tempStr, 1) = #13) or (rightStr(tempStr, 1) = #10)) do tempStr := leftStr(tempStr, length(tempStr)-1); setLength(fileText, length(fileText)+1); fileText[length(fileText)-1] := tempStr; until Eof(objectFile); close(objectFile); while (fileText[length(fileText)-1] = '') do setLength(fileText, length(fileText)-1); loadSms(setDirSeparators(path+fileText[1])); loadSmm(setDirSeparators(path+fileText[0])); for i := 2 to length(fileText)-1 do loadSma(setDirSeparators(path+fileText[i])); if (customBufferFunction = nil) then initBufferSmo else customBufferFunction(@vbo, @self, customData); if (vertexArrayObjectSupported) then glBindVertexArray(0); for i := 0 to 15 do glDisableVertexAttribArray(i); loadedFromObj := false; end; procedure TModel.initBufferObj; var vertexArray : array of GLfloat; count, i : word; j : integer; begin setLength(vertexArray, length(triangles)*3*23); count := 0; for i := 0 to length(triangles)-1 do begin for j := 0 to 2 do begin vertexArray[count] := triangles[i].coords[j].x; count += 1; vertexArray[count] := triangles[i].coords[j].y; count += 1; vertexArray[count] := triangles[i].coords[j].z; count += 1; vertexArray[count] := 1.0; count += 1; vertexArray[count] := triangles[i].coords[j].normal_.x; count += 1; vertexArray[count] := triangles[i].coords[j].normal_.y; count += 1; vertexArray[count] := triangles[i].coords[j].normal_.z; count += 1; vertexArray[count] := materials[triangles[i].mtlNum].ambientColor.r; count += 1; vertexArray[count] := materials[triangles[i].mtlNum].ambientColor.g; count += 1; vertexArray[count] := materials[triangles[i].mtlNum].ambientColor.b; count += 1; vertexArray[count] := materials[triangles[i].mtlNum].diffuseColor.r; count += 1; vertexArray[count] := materials[triangles[i].mtlNum].diffuseColor.g; count += 1; vertexArray[count] := materials[triangles[i].mtlNum].diffuseColor.b; count += 1; vertexArray[count] := materials[triangles[i].mtlNum].specularColor.r; count += 1; vertexArray[count] := materials[triangles[i].mtlNum].specularColor.g; count += 1; vertexArray[count] := materials[triangles[i].mtlNum].specularColor.b; count += 1; vertexArray[count] := triangles[i].texCoords[j].x; count += 1; vertexArray[count] := triangles[i].texCoords[j].y; count += 1; vertexArray[count] := triangles[i].texCoords[j].z; count += 1; vertexArray[count] := triangles[i].mtlNum; count += 1; if (materials[triangles[i].mtlNum].hasTexture) then vertexArray[count] := 1.0 else vertexArray[count] := 0.0; count += 1; vertexArray[count] := materials[triangles[i].mtlNum].shininess; count += 1; vertexArray[count] := materials[triangles[i].mtlNum].alpha; count += 1; end; end; glGenBuffers(1, @vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*length(vertexArray), @vertexArray, GL_STATIC_DRAW); glVertexAttribPointer(VERTEX_ATTRIBUTE, 4, GL_FLOAT, false, sizeof(GLfloat)*23, nil); glVertexAttribPointer(NORMAL_ATTRIBUTE, 3, GL_FLOAT, false, sizeof(GLfloat)*23, PGLvoid(sizeof(GLfloat)*4)); glVertexAttribPointer(COLOR0_ATTRIBUTE, 3, GL_FLOAT, false, sizeof(GLfloat)*23, PGLvoid(sizeof(GLfloat)*7)); glVertexAttribPointer(COLOR1_ATTRIBUTE, 3, GL_FLOAT, false, sizeof(GLfloat)*23, PGLvoid(sizeof(GLfloat)*10)); glVertexAttribPointer(COLOR2_ATTRIBUTE, 3, GL_FLOAT, false, sizeof(GLfloat)*23, PGLvoid(sizeof(GLfloat)*13)); glVertexAttribPointer(TEXTURE0_ATTRIBUTE, 3, GL_FLOAT, false, sizeof(GLfloat)*23, PGLvoid(sizeof(GLfloat)*16)); glVertexAttribPointer(EXTRA0_ATTRIBUTE, 1, GL_FLOAT, false, sizeof(GLfloat)*23, PGLvoid(sizeof(GLfloat)*19)); glVertexAttribPointer(EXTRA1_ATTRIBUTE, 1, GL_FLOAT, false, sizeof(GLfloat)*23, PGLvoid(sizeof(GLfloat)*20)); glVertexAttribPointer(EXTRA2_ATTRIBUTE, 1, GL_FLOAT, false, sizeof(GLfloat)*23, PGLvoid(sizeof(GLfloat)*21)); glVertexAttribPointer(EXTRA3_ATTRIBUTE, 1, GL_FLOAT, false, sizeof(GLfloat)*23, PGLvoid(sizeof(GLfloat)*22)); glEnableVertexAttribArray(VERTEX_ATTRIBUTE); glEnableVertexAttribArray(NORMAL_ATTRIBUTE); glEnableVertexAttribArray(COLOR0_ATTRIBUTE); glEnableVertexAttribArray(COLOR1_ATTRIBUTE); glEnableVertexAttribArray(COLOR2_ATTRIBUTE); glEnableVertexAttribArray(TEXTURE0_ATTRIBUTE); glEnableVertexAttribArray(EXTRA0_ATTRIBUTE); glEnableVertexAttribArray(EXTRA1_ATTRIBUTE); glEnableVertexAttribArray(EXTRA2_ATTRIBUTE); glEnableVertexAttribArray(EXTRA3_ATTRIBUTE); glBindBuffer(GL_ARRAY_BUFFER, 0); end; procedure TModel.initBufferSmo; var vertexArray : array[0..50000] of GLfloat;//2069999 count, offset, i, j, k : integer; begin count := 0; for i := 0 to length(bones)-1 do begin count += length(bones[i]^.triangles)*3; end; if (vertexArrayObjectSupported) then begin glGenVertexArrays(1, @vao); glBindVertexArray(vao); end; glGenBuffers(1, @vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*count*23, nil, GL_STATIC_DRAW); offset := 0; for i := 0 to length(bones)-1 do begin bones[i]^.offset := offset; count := 0; if (length(bones[i]^.triangles) > 0) then begin for j := 0 to length(bones[i]^.triangles)-1 do begin for k := 0 to 2 do begin vertexArray[count] := bones[i]^.triangles[j]^.coords[k].x; count += 1; vertexArray[count] := bones[i]^.triangles[j]^.coords[k].y; count += 1; vertexArray[count] := bones[i]^.triangles[j]^.coords[k].z; count += 1; if (bones[i]^.triangles[j]^.sharedCoord[k]) then vertexArray[count] := 1.0 else vertexArray[count] := 0.0; count += 1; vertexArray[count] := bones[i]^.triangles[j]^.coords[k].normal_.x; count += 1; vertexArray[count] := bones[i]^.triangles[j]^.coords[k].normal_.y; count += 1; vertexArray[count] := bones[i]^.triangles[j]^.coords[k].normal_.z; count += 1; vertexArray[count] := materials[bones[i]^.triangles[j]^.mtlNum].ambientColor.r; count += 1; vertexArray[count] := materials[bones[i]^.triangles[j]^.mtlNum].ambientColor.g; count += 1; vertexArray[count] := materials[bones[i]^.triangles[j]^.mtlNum].ambientColor.b; count += 1; vertexArray[count] := materials[bones[i]^.triangles[j]^.mtlNum].diffuseColor.r; count += 1; vertexArray[count] := materials[bones[i]^.triangles[j]^.mtlNum].diffuseColor.g; count += 1; vertexArray[count] := materials[bones[i]^.triangles[j]^.mtlNum].diffuseColor.b; count += 1; vertexArray[count] := materials[bones[i]^.triangles[j]^.mtlNum].specularColor.r; count += 1; vertexArray[count] := materials[bones[i]^.triangles[j]^.mtlNum].specularColor.g; count += 1; vertexArray[count] := materials[bones[i]^.triangles[j]^.mtlNum].specularColor.b; count += 1; vertexArray[count] := bones[i]^.triangles[j]^.texCoords[k].x; count += 1; vertexArray[count] := bones[i]^.triangles[j]^.texCoords[k].y; count += 1; vertexArray[count] := bones[i]^.triangles[j]^.texCoords[k].z; count += 1; vertexArray[count] := bones[i]^.triangles[j]^.mtlNum; count += 1; if (materials[bones[i]^.triangles[j]^.mtlNum].hasTexture) then vertexArray[count] := 1.0 else vertexArray[count] := 0.0; count += 1; vertexArray[count] := materials[bones[i]^.triangles[j]^.mtlNum].shininess; count += 1; vertexArray[count] := materials[bones[i]^.triangles[j]^.mtlNum].alpha; count += 1; end; end; glBufferSubData(GL_ARRAY_BUFFER, sizeof(GLfloat)*offset*23, sizeof(GLfloat)*count, @vertexArray); offset += length(bones[i]^.triangles)*3; end; end; if (vertexArrayObjectSupported) then begin glVertexAttribPointer(VERTEX_ATTRIBUTE, 4, GL_FLOAT, false, sizeof(GLfloat)*23, nil); glVertexAttribPointer(NORMAL_ATTRIBUTE, 3, GL_FLOAT, false, sizeof(GLfloat)*23, PGLvoid(sizeof(GLfloat)*4)); glVertexAttribPointer(COLOR0_ATTRIBUTE, 3, GL_FLOAT, false, sizeof(GLfloat)*23, PGLvoid(sizeof(GLfloat)*7)); glVertexAttribPointer(COLOR1_ATTRIBUTE, 3, GL_FLOAT, false, sizeof(GLfloat)*23, PGLvoid(sizeof(GLfloat)*10)); glVertexAttribPointer(COLOR2_ATTRIBUTE, 3, GL_FLOAT, false, sizeof(GLfloat)*23, PGLvoid(sizeof(GLfloat)*13)); glVertexAttribPointer(TEXTURE0_ATTRIBUTE, 3, GL_FLOAT, false, sizeof(GLfloat)*23, PGLvoid(sizeof(GLfloat)*16)); glVertexAttribPointer(EXTRA0_ATTRIBUTE, 1, GL_FLOAT, false, sizeof(GLfloat)*23, PGLvoid(sizeof(GLfloat)*19)); glVertexAttribPointer(EXTRA1_ATTRIBUTE, 1, GL_FLOAT, false, sizeof(GLfloat)*23, PGLvoid(sizeof(GLfloat)*20)); glVertexAttribPointer(EXTRA2_ATTRIBUTE, 1, GL_FLOAT, false, sizeof(GLfloat)*23, PGLvoid(sizeof(GLfloat)*21)); glVertexAttribPointer(EXTRA3_ATTRIBUTE, 1, GL_FLOAT, false, sizeof(GLfloat)*23, PGLvoid(sizeof(GLfloat)*22)); glEnableVertexAttribArray(VERTEX_ATTRIBUTE); glEnableVertexAttribArray(NORMAL_ATTRIBUTE); glEnableVertexAttribArray(COLOR0_ATTRIBUTE); glEnableVertexAttribArray(COLOR1_ATTRIBUTE); glEnableVertexAttribArray(COLOR2_ATTRIBUTE); glEnableVertexAttribArray(TEXTURE0_ATTRIBUTE); glEnableVertexAttribArray(EXTRA0_ATTRIBUTE); glEnableVertexAttribArray(EXTRA1_ATTRIBUTE); glEnableVertexAttribArray(EXTRA2_ATTRIBUTE); glEnableVertexAttribArray(EXTRA3_ATTRIBUTE); end; glBindBuffer(GL_ARRAY_BUFFER, 0); if (vertexArrayObjectSupported) then glBindVertexArray(0); for i := 0 to 15 do glDisableVertexAttribArray(i); end; procedure TModel.drawObj(shaderToUse : PShader); begin shaderToUse^.setUniform16(MODELVIEW_LOCATION, getMatrix(MODELVIEW_MATRIX)); shaderToUse^.setUniform16(PROJECTION_LOCATION, getMatrix(PROJECTION_MATRIX)); glBindVertexArray(vao); glBindBuffer(GL_ARRAY_BUFFER, vbo); glDrawArrays(GL_TRIANGLES, 0, length(triangles)*3); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); end; function TModel.calculatePoints(nx, ny, nz : real; matrix : matrix4d) : normal; begin result.x := (nx*matrix[0])+(ny*matrix[4])+(nz*matrix[8])+matrix[12]; result.y := (nx*matrix[1])+(ny*matrix[5])+(nz*matrix[9])+matrix[13]; result.z := (nx*matrix[2])+(ny*matrix[6])+(nz*matrix[10])+matrix[14]; end; procedure TModel.calculateHitbox(pBone_ : pbone; matrix : matrix4d); var nx, ny, nz, lLowerBound, lUpperBound, wLowerBound, wUpperBound, hLowerBound, hUpperBound : real; point : array[0..7] of normal; i : integer; begin nx := 0.0; ny := -pBone_^.hitbox.h/2.0; nz := pBone_^.hitbox.w/2.0; point[0] := calculatePoints(nx, ny, nz, matrix); nx := 0.0; ny := pBone_^.hitbox.h/2.0; nz := pBone_^.hitbox.w/2.0; point[1] := calculatePoints(nx, ny, nz, matrix); nx := 0.0; ny := pBone_^.hitbox.h/2.0; nz := -pBone_^.hitbox.w/2.0; point[2] := calculatePoints(nx, ny, nz, matrix); nx := 0.0; ny := -pBone_^.hitbox.h/2.0; nz := -pBone_^.hitbox.w/2.0; point[3] := calculatePoints(nx, ny, nz, matrix); nx := pBone_^.hitbox.l; ny := -pBone_^.hitbox.h/2.0; nz := pBone_^.hitbox.w/2.0; point[4] := calculatePoints(nx, ny, nz, matrix); nx := pBone_^.hitbox.l; ny := pBone_^.hitbox.h/2.0; nz := pBone_^.hitbox.w/2.0; point[5] := calculatePoints(nx, ny, nz, matrix); nx := pBone_^.hitbox.l; ny := pBone_^.hitbox.h/2.0; nz := -pBone_^.hitbox.w/2.0; point[6] := calculatePoints(nx, ny, nz, matrix); nx := pBone_^.hitbox.l; ny := -pBone_^.hitbox.h/2.0; nz := -pBone_^.hitbox.w/2.0; point[7] := calculatePoints(nx, ny, nz, matrix); lLowerBound := point[0].x; lUpperBound := point[0].x; wLowerBound := point[0].z; wUpperBound := point[0].z; hLowerBound := point[0].y; hUpperBound := point[0].y; for i := 0 to 7 do begin if (point[i].x < lLowerBound) then lLowerBound := point[i].x else if (point[i].x > lUpperBound) then lUpperBound := point[i].x; if (point[i].z < wLowerBound) then wLowerBound := point[i].z else if (point[i].z > wUpperBound) then wUpperBound := point[i].z; if (point[i].y < hLowerBound) then hLowerBound := point[i].y else if (point[i].y > hUpperBound) then hUpperBound := point[i].y; end; pBone_^.hitbox.rl := lUpperBound-lLowerBound; pBone_^.hitbox.rw := wUpperBound-wLowerBound; pBone_^.hitbox.rh := hUpperBound-hLowerBound; end; procedure TModel.drawBone(pBone_ : pbone; shaderToUse : PShader; skipHitboxes : boolean = false); var modelMatrix, modelNormMatrix : matrix4d; i : integer; nx, ny, nz : real; begin pushMatrix; pushMatrix; copyMatrix(IDENTITY_MATRIX, MODELVIEW_MATRIX); translateMatrix(pBone_^.x, pBone_^.y, pBone_^.z); rotateMatrix(pBone_^.xRot, 1.0, 0.0, 0.0); rotateMatrix(pBone_^.yRot, 0.0, 1.0, 0.0); rotateMatrix(pBone_^.zRot, 0.0, 0.0, 1.0); translateMatrix(-pBone_^.x, -pBone_^.y, -pBone_^.z); modelMatrix := getMatrix(MODELVIEW_MATRIX); popMatrix; shaderToUse^.setUniform16(EXTRA0_LOCATION, getMatrix(MODELVIEW_MATRIX)); copyMatrix(multiplyMatrix(getMatrix(MODELVIEW_MATRIX), modelMatrix), MODELVIEW_MATRIX); shaderToUse^.setUniform16(MODELVIEW_LOCATION, getMatrix(MODELVIEW_MATRIX)); shaderToUse^.setUniform16(PROJECTION_LOCATION, getMatrix(PROJECTION_MATRIX)); glDrawArrays(GL_TRIANGLES, pBone_^.offset, length(pBone_^.triangles)*3); if (not skipHitboxes) then begin if (pBone_^.parent = nil) then begin pBone_^.hitbox.x := 0.0; pBone_^.hitbox.y := 0.0; pBone_^.hitbox.z := 0.0; end else begin pBone_^.hitbox.x := pBone_^.parent^.hitbox.x+pBone_^.parent^.endX; pBone_^.hitbox.y := pBone_^.parent^.hitbox.y+pBone_^.parent^.endY; pBone_^.hitbox.z := pBone_^.parent^.hitbox.z+pBone_^.parent^.endZ; end; nx := pBone_^.endX; ny := pBone_^.endY; nz := pBone_^.endZ; pBone_^.endX := (nx*modelNormMatrix[0])+(ny*modelNormMatrix[4])+(nz*modelNormMatrix[8])+modelNormMatrix[12]; pBone_^.endY := (nx*modelNormMatrix[1])+(ny*modelNormMatrix[5])+(nz*modelNormMatrix[9])+modelNormMatrix[13]; pBone_^.endZ := (nx*modelNormMatrix[2])+(ny*modelNormMatrix[6])+(nz*modelNormMatrix[10])+modelNormMatrix[14]; calculateHitbox(pBone_, modelNormMatrix); end; if (length(pBone_^.child) > 0) then for i := 0 to length(pBone_^.child)-1 do drawBone(pBone_^.child[i], shaderToUse, skipHitboxes); popMatrix; end; function TModel.name : string; begin result := name_; end; procedure TModel.draw(objectParam : PGameObject; skipAnimation : boolean = false; skipHitboxes : boolean = false); var shaderToUse : PShader; i, currentKeyFrame, stepDiff, size : integer; thisKeyFrame, nextKeyFrame : pkeyFrame; tempFrame, diff, diff1, diff2 : real; begin if (objectParam^.model_ = nil) then exit; if (objectParam^.boundShader <> nil) then shaderToUse := objectParam^.boundShader else if (boundShader_ <> nil) then shaderToUse := boundShader_ else shaderToUse := globalBoundShader; if (shaderToUse <> nil) then begin shaderToUse^.use; glActiveTexture(GL_TEXTURE0); if (glSlVersion < 1.5) then begin glBindTexture(GL_TEXTURE_2D, texture); shaderToUse^.setUniform1(TEXCOMPAT_LOCATION, length(materials)); end else glBindTexture(GL_TEXTURE_2D_ARRAY, texture); shaderToUse^.setUniform1(TEXSAMPLER_LOCATION, 0); setMatrix(MODELVIEW_MATRIX); pushMatrix; translateMatrix(objectParam^.x_, objectParam^.y_, objectParam^.z_); rotateMatrix(objectParam^.xRotation_, 1.0, 0.0, 0.0); rotateMatrix(objectParam^.yRotation_, 0.0, 1.0, 0.0); rotateMatrix(objectParam^.zRotation_, 0.0, 0.0, 1.0); scaleMatrix(objectParam^.xScale_, objectParam^.yScale_, objectParam^.zScale_); if (vertexArrayObjectSupported) then glBindVertexArray(vao); if (loadedFromObj) then drawObj(shaderToUse) else begin if (not skipAnimation) then begin if (length(animations) > 0) then begin if (length(animations[objectParam^.currentAnimationId].frames) > 1) then begin if (objectParam^.interpolating) then begin thisKeyFrame := objectParam^.fakeKeyFrame1; nextKeyFrame := objectParam^.fakeKeyFrame2; if (objectParam^.frame_ > nextKeyFrame^.step) then objectParam^.frame_ -= nextKeyFrame^.step else if (objectParam^.frame_ < 0) then objectParam^.frame_ := nextKeyFrame^.step+(objectParam^.frame_+1); end else begin currentKeyFrame := 0; size := length(animations[objectParam^.currentAnimationId].frames); while (objectParam^.frame_ > animations[objectParam^.currentAnimationId].frames[size-1].step) do objectParam^.frame_ -= animations[objectParam^.currentAnimationId].frames[size-1].step; while (objectParam^.frame_ > animations[objectParam^.currentAnimationId].frames[currentKeyFrame+1].step) do begin currentKeyFrame += 1; if (currentKeyFrame >= length(animations[objectParam^.currentAnimationId].frames)) then begin currentKeyFrame := 0; size := length(animations[objectParam^.currentAnimationId].frames); objectParam^.frame_ -= animations[objectParam^.currentAnimationId].frames[size-1].step; break; end; end; thisKeyFrame := @animations[objectParam^.currentAnimationId].frames[currentKeyFrame]; if (currentKeyFrame+1 < length(animations[objectParam^.currentAnimationId].frames)) then nextKeyFrame := @animations[objectParam^.currentAnimationId].frames[currentKeyFrame+1] else nextKeyFrame := @animations[objectParam^.currentAnimationId].frames[0]; end; tempFrame := objectParam^.frame_-thisKeyFrame^.step; stepDiff := nextKeyFrame^.step-thisKeyFrame^.step; for i := 0 to length(bones)-1 do begin diff1 := nextKeyFrame^.boneData[i].xRot-thisKeyFrame^.boneData[i].xRot; diff2 := 360-nextKeyFrame^.boneData[i].xRot; if (abs(diff1) < abs(diff2)) then diff := diff1 else diff := diff2; bones[thisKeyFrame^.boneData[i].boneId]^.xRot := thisKeyFrame^.boneData[i].xRot+((diff/stepDiff)*tempFrame); diff1 := nextKeyFrame^.boneData[i].yRot-thisKeyFrame^.boneData[i].yRot; diff2 := 360-nextKeyFrame^.boneData[i].yRot; if (abs(diff1) < abs(diff2)) then diff := diff1 else diff := diff2; bones[thisKeyFrame^.boneData[i].boneId]^.yRot := thisKeyFrame^.boneData[i].yRot+((diff/stepDiff)*tempFrame); diff1 := nextKeyFrame^.boneData[i].zRot-thisKeyFrame^.boneData[i].zRot; diff2 := 360-nextKeyFrame^.boneData[i].zRot; if (abs(diff1) < abs(diff2)) then diff := diff1 else diff := diff2; bones[thisKeyFrame^.boneData[i].boneId]^.zRot := thisKeyFrame^.boneData[i].zRot+((diff/stepDiff)*tempFrame); end; end; end; end; if (not vertexArrayObjectSupported) then begin glBindBuffer(GL_ARRAY_BUFFER, vbo); glVertexAttribPointer(VERTEX_ATTRIBUTE, 4, GL_FLOAT, false, sizeof(GLfloat)*23, nil); glVertexAttribPointer(NORMAL_ATTRIBUTE, 3, GL_FLOAT, false, sizeof(GLfloat)*23, PGLvoid(sizeof(GLfloat)*4)); glVertexAttribPointer(COLOR0_ATTRIBUTE, 3, GL_FLOAT, false, sizeof(GLfloat)*23, PGLvoid(sizeof(GLfloat)*7)); glVertexAttribPointer(COLOR1_ATTRIBUTE, 3, GL_FLOAT, false, sizeof(GLfloat)*23, PGLvoid(sizeof(GLfloat)*10)); glVertexAttribPointer(COLOR2_ATTRIBUTE, 3, GL_FLOAT, false, sizeof(GLfloat)*23, PGLvoid(sizeof(GLfloat)*13)); glVertexAttribPointer(TEXTURE0_ATTRIBUTE, 3, GL_FLOAT, false, sizeof(GLfloat)*23, PGLvoid(sizeof(GLfloat)*16)); glVertexAttribPointer(EXTRA0_ATTRIBUTE, 1, GL_FLOAT, false, sizeof(GLfloat)*23, PGLvoid(sizeof(GLfloat)*19)); glVertexAttribPointer(EXTRA1_ATTRIBUTE, 1, GL_FLOAT, false, sizeof(GLfloat)*23, PGLvoid(sizeof(GLfloat)*20)); glVertexAttribPointer(EXTRA2_ATTRIBUTE, 1, GL_FLOAT, false, sizeof(GLfloat)*23, PGLvoid(sizeof(GLfloat)*21)); glVertexAttribPointer(EXTRA3_ATTRIBUTE, 1, GL_FLOAT, false, sizeof(GLfloat)*23, PGLvoid(sizeof(GLfloat)*22)); glEnableVertexAttribArray(VERTEX_ATTRIBUTE); glEnableVertexAttribArray(NORMAL_ATTRIBUTE); glEnableVertexAttribArray(COLOR0_ATTRIBUTE); glEnableVertexAttribArray(COLOR1_ATTRIBUTE); glEnableVertexAttribArray(COLOR2_ATTRIBUTE); glEnableVertexAttribArray(TEXTURE0_ATTRIBUTE); glEnableVertexAttribArray(EXTRA0_ATTRIBUTE); glEnableVertexAttribArray(EXTRA1_ATTRIBUTE); glEnableVertexAttribArray(EXTRA2_ATTRIBUTE); glEnableVertexAttribArray(EXTRA3_ATTRIBUTE); end; drawBone(bones[0], shaderToUse, skipHitboxes); end; if (vertexArrayObjectSupported) then glBindVertexArray(0) else begin glDisableVertexAttribArray(VERTEX_ATTRIBUTE); glDisableVertexAttribArray(NORMAL_ATTRIBUTE); glDisableVertexAttribArray(COLOR0_ATTRIBUTE); glDisableVertexAttribArray(COLOR1_ATTRIBUTE); glDisableVertexAttribArray(COLOR2_ATTRIBUTE); glDisableVertexAttribArray(TEXTURE0_ATTRIBUTE); glDisableVertexAttribArray(EXTRA0_ATTRIBUTE); glDisableVertexAttribArray(EXTRA1_ATTRIBUTE); glDisableVertexAttribArray(EXTRA2_ATTRIBUTE); glDisableVertexAttribArray(EXTRA3_ATTRIBUTE); end; popMatrix; end; if (globalBoundShader <> nil) then glUseProgram(globalBoundShader()^.getProgram) else glUseProgram(0); end; procedure TModel.bindShader(newShader : PShader); begin boundShader_ := newShader; end; function TModel.boundShader : PShader; begin result := boundShader_; end; function TModel.animationId(searchName : string) : integer; var i : integer; begin result := -1; for i := 0 to length(animations)-1 do if (animations[i].name = searchName) then begin result := i; break; end; end; procedure TModel.setFramerate(newFramerate : word); begin framerate_ := newFramerate; end; function TModel.framerate : word; begin result := framerate_; end; constructor TGameObject.create(newName : string; destX, destY, destZ : real; newSprite : PSprite = nil; startFrame : word = 0); begin name_ := newName; x_ := destX; y_ := destY; z_ := destZ; sprite_ := newSprite; frame_ := startFrame; currentAnimationId := 0; nextAnimationId := 0; xRotation_ := 0; yRotation_ := 0; zRotation_ := 0; xScale_ := 1; yScale_ := 1; zScale_ := 1; alpha_ := 1; hasModel_ := false; if (sprite_ <> nil) then begin width_ := sprite_^.rect.w; height_ := sprite_^.rect.h; originX := sprite_^.originX; originY := sprite_^.originY; end; zRotatedWidth_ := width; zRotatedHeight_ := height; boundShader_ := nil; customDrawFunction := nil; fakeKeyFrame1 := nil; fakeKeyFrame2 := nil; interpolating_ := false; end; constructor TGameObject.create(newName : string; destX, destY, destZ : real; newModel : PModel = nil); begin name_ := newName; x_ := destX; y_ := destY; z_ := destZ; model_ := newModel; frame_ := 0; currentAnimationId := 0; nextAnimationId := 0; xRotation_ := 0; yRotation_ := 0; zRotation_ := 0; xScale_ := 1; yScale_ := 1; zScale_ := 1; alpha_ := 1; hasModel_ := true; boundShader_ := nil; customDrawFunction := nil; fakeKeyFrame1 := new(pkeyFrame); fakeKeyFrame2 := new(pkeyFrame); interpolating_ := false; end; destructor TGameObject.destroy; begin if (fakeKeyFrame1 <> nil) then dispose(fakeKeyFrame1); if (fakeKeyFrame2 <> nil) then dispose(fakeKeyFrame2); end; function TGameObject.name : string; begin result := name_; end; procedure TGameObject.setSprite(newSprite : PSprite); begin sprite_ := newSprite; if (sprite_ <> nil) then begin width_ := sprite_^.rect.w; height_ := sprite_^.rect.h; originX := sprite_^.originX; originY := sprite_^.originY; end; hasModel_ := false; if (fakeKeyFrame1 <> nil) then dispose(fakeKeyFrame1); if (fakeKeyFrame2 <> nil) then dispose(fakeKeyFrame2); end; function TGameObject.sprite : PSprite; begin result := sprite_; end; procedure TGameObject.setModel(newModel : PModel); begin model_ := newModel; hasModel_ := true; if (fakeKeyFrame1 <> nil) then fakeKeyFrame1 := new(pkeyFrame); if (fakeKeyFrame2 <> nil) then fakeKeyFrame2 := new(pkeyFrame); end; function TGameObject.model : PModel; begin result := model_; end; function TGameObject.hasModel : boolean; begin result := hasModel_; end; procedure TGameObject.bindShader(shader : PShader); begin boundShader_ := shader; end; function TGameObject.boundShader : PShader; begin result := boundShader_; end; procedure TGameObject.bindCustomDrawFunction(newCustomDrawFunction : customDrawFunctionType); begin customDrawFunction := newCustomDrawFunction; end; function TGameObject.boundCustomDrawFunction : customDrawFunctionType; begin result := customDrawFunction; end; procedure TGameObject.setPosition(xAmount, yAmount, zAmount : real; relative : boolean = false); begin if (relative) then begin x_ += xAmount*compensation; y_ += yAmount*compensation; z_ += zAmount*compensation; end else begin x_ := xAmount; y_ := yAmount; z_ := zAmount; end; end; function TGameObject.setX(amount : real; relative : boolean = false) : real; begin if (relative) then x_ += amount*compensation else x_ := amount; result := x_; end; function TGameObject.setY(amount : real; relative : boolean = false) : real; begin if (relative) then y_ += amount*compensation else y_ := amount; result := y_; end; function TGameObject.setZ(amount : real; relative : boolean = false) : real; begin if (relative) then z_ += amount*compensation else z_ := amount; result := z_; end; function TGameObject.x : real; begin result := x_; end; function TGameObject.y : real; begin result := y_; end; function TGameObject.z : real; begin result := z_; end; function TGameObject.width : real; begin result := width_; end; function TGameObject.height : real; begin result := height_; end; procedure TGameObject.calcZRotatedDimensions; var pointX, pointY : array[0..3] of real; i : integer; pointDist, angle, calc, wLowerBound, wUpperBound, hLowerBound, hUpperBound : real; begin if ((zRotation_ = 0.0) or (zRotation = 180.0)) then begin zRotatedWidth_ := width_; zRotatedHeight_ := height_; end else if ((zRotation_ = 90.0) or (zRotation_ = 270.0)) then begin zRotatedWidth_ := height_; zRotatedHeight_ := width_; end else begin pointX[0] := -originX; pointY[0] := -originY; pointX[1] := -originX; pointY[1] := -originY+height_; pointX[2] := -originX+width_; pointY[2] := -originY+height_; pointX[3] := -originX+width_; pointY[3] := -originY; for i := 0 to 3 do begin pointDist := sqrt((pointX[i]*pointX[i])+(pointY[i]*pointY[i])); angle := arctan2(pointY[i], pointX[i]); calc := angle-degToRad(zRotation_); pointX[i] := pointDist*cos(calc); pointY[i] := pointDist*sin(calc); end; wLowerBound := pointX[0]; wUpperBound := pointX[0]; hLowerBound := pointY[0]; hUpperBound := pointY[0]; for i := 0 to 3 do begin if (pointX[i] < wLowerBound) then wLowerBound := pointX[i]; if (pointX[i] > wUpperBound) then wUpperBound := pointX[i]; if (pointY[i] < hLowerBound) then hLowerBound := pointY[i]; if (pointY[i] > hUpperBound) then hUpperBound := pointY[i]; end; zRotatedWidth_ := wUpperBound-wLowerBound; zRotatedHeight_ := hUpperBound-hLowerBound; end; end; procedure TGameObject.scale(xAmount, yAmount, zAmount : real; relative : boolean = false; recalculateDimensions : boolean = true); begin if (relative) then begin xScale_ += xAmount*compensation; yScale_ += yAmount*compensation; zScale_ += zAmount*compensation; end else begin xScale_ := xAmount; yScale_ := yAmount; zScale_ := zAmount; end; width_ *= xScale_; height_ *= yScale_; originX *= xScale_; originY *= yScale_; if (recalculateDimensions) then calcZRotatedDimensions; end; function TGameObject.xScale : real; begin result := xScale_; end; function TGameObject.yScale : real; begin result := yScale_; end; function TGameObject.zScale : real; begin result := zScale_; end; procedure TGameObject.rotate(xAmount, yAmount, zAmount : real; relative : boolean = false; recalculateDimensions : boolean = true); begin if (relative) then begin xRotation_ += xAmount*compensation; yRotation_ += yAmount*compensation; zRotation_ += zAmount*compensation; end else begin xRotation_ := xAmount; yRotation_ := yAmount; zRotation_ := zAmount; end; if (xRotation_ >= 360.0) then xRotation_ -= 360.0 else if (xRotation_ < 0.0) then xRotation_ += 360.0; if (yRotation_ >= 360.0) then yRotation_ -= 360.0 else if (yRotation_ < 0.0) then yRotation_ += 360.0; if (zRotation_ >= 360.0) then zRotation_ -= 360.0 else if (zRotation_ < 0.0) then zRotation_ += 360.0; if (recalculateDimensions) then calcZRotatedDimensions; end; function TGameObject.rotate(amount : real; relative : boolean = false; recalculateDimensions : boolean = true) : real; begin if (relative) then zRotation_ += amount*compensation else zRotation_ := amount; if (zRotation_ >= 360.0) then zRotation_ -= 360.0 else if (zRotation_ < 0.0) then zRotation_ += 360.0; if (recalculateDimensions) then calcZRotatedDimensions; result := zRotation_; end; function TGameObject.xRotation : real; begin result := xRotation_; end; function TGameObject.yRotation : real; begin result := yRotation_; end; function TGameObject.zRotation : real; begin result := zRotation_; end; function TGameObject.setAlpha(amount : real; relative : boolean = false) : real; begin if (relative) then alpha_ += amount*compensation else alpha_ := amount; result := alpha_; end; function TGameObject.alpha : real; begin result := alpha_; end; procedure TGameObject.setCurrentAnimation(animationId : word); begin currentAnimationId := animationId; end; function TGameObject.currentAnimation : word; begin result := currentAnimationId; end; procedure TGameObject.setFrame(newFrame : real; relative : boolean = false); begin if (relative) then frame_ += newFrame*compensation else frame_ := newFrame; if (not hasModel_) then begin if (frame_ > sprite_^.frames) then frame_ := (frame_-1.0)-sprite_^.frames else if (frame_ < 0.0) then frame_ := sprite_^.frames+(frame_+1.0); end; end; function TGameObject.frame : real; begin result := frame_; end; procedure TGameObject.animate(start, finish : word; animationId : word = 0); begin if (hasModel_) then begin currentAnimationId := animationId; while (currentAnimationId >= length(model_^.animations)) do currentAnimationId -= length(model_^.animations); if (start < finish) then begin frame_ += compensation; if (frame_ > finish) then frame_ := start+((frame_-1.0)-finish); end else if (start > finish) then begin frame_ -= compensation; if (frame_ < 0.0) then frame_ := finish+(frame_+1.0) else if (frame_ < start) then frame_ := finish+((frame_-start)+1.0); end end else begin if (start < finish) then begin frame_ += compensation; if (frame_ > finish) then frame_ := start+((frame_-1.0)-finish) else if (frame_ > sprite_^.frames) then frame_ := start+((frame_-1.0)-sprite_^.frames); end else if (start > finish) then begin frame_ -= compensation; if (frame_ < 0.0) then frame_ := finish+(frame_+1.0) else if (frame_ < start) then frame_ := finish+((frame_-start)+1.0); end; end; end; procedure TGameObject.setInterpolation(startFrame, animation1Id, endFrame, animation2Id, numFramesToTake : integer); var i, animationId, currentKeyFrame, size, tempFrame, stepDiff, frameCount : integer; frameToUse : ^integer; fakeKeyFrame, thisKeyFrame, nextKeyFrame : pkeyFrame; diff, diff1, diff2 : real; begin if (hasModel_) then begin interpolating_ := true; fakeKeyFrame1^.step := 0; fakeKeyFrame1^.boneData := model_^.animations[animation1Id].frames[0].boneData; fakeKeyFrame2^.step := numFramesToTake-1; fakeKeyFrame2^.boneData := model_^.animations[animation2Id].frames[0].boneData; for frameCount := 0 to 1 do begin if (frameCount = 1) then begin frameToUse := @endFrame; fakeKeyFrame := fakeKeyFrame2; animationId := animation2Id; end else begin frameToUse := @startFrame; fakeKeyFrame := fakeKeyFrame1; animationId := animation1Id; end; currentKeyFrame := 0; while (frameToUse^ > model_^.animations[animationId].frames[currentKeyFrame+1].step) do begin currentKeyFrame += 1; if (currentKeyFrame >= length(model_^.animations[animationId].frames)) then begin currentKeyFrame := 0; size := length(model_^.animations[animationId].frames); frameToUse^ -= model_^.animations[animationId].frames[size-1].step; break; end; end; thisKeyFrame := @model_^.animations[animationId].frames[currentKeyFrame]; if (currentKeyFrame+1 < length(model_^.animations[animationId].frames)) then nextKeyFrame := @model_^.animations[animationId].frames[currentKeyFrame+1] else nextKeyFrame := @model_^.animations[animationId].frames[0]; tempFrame := frameToUse^-thisKeyFrame^.step; stepDiff := nextKeyFrame^.step-thisKeyFrame^.step; for i := 0 to length(model_^.bones)-1 do begin diff1 := nextKeyFrame^.boneData[i].xRot-thisKeyFrame^.boneData[i].xRot; diff2 := 360.0-nextKeyFrame^.boneData[i].xRot; if (abs(diff1) < abs(diff2)) then diff := diff1 else diff := diff2; fakeKeyFrame^.boneData[i].xRot := thisKeyFrame^.boneData[i].xRot+((diff/stepDiff)*tempFrame); diff1 := nextKeyFrame^.boneData[i].yRot-thisKeyFrame^.boneData[i].yRot; diff2 := 360-nextKeyFrame^.boneData[i].yRot; if (abs(diff1) < abs(diff2)) then diff := diff1 else diff := diff2; fakeKeyFrame^.boneData[i].yRot := thisKeyFrame^.boneData[i].yRot+((diff/stepDiff)*tempFrame); diff1 := nextKeyFrame^.boneData[i].zRot-thisKeyFrame^.boneData[i].zRot; diff2 := 360-nextKeyFrame^.boneData[i].zRot; if (abs(diff1) < abs(diff2)) then diff := diff1 else diff := diff2; fakeKeyFrame^.boneData[i].zRot := thisKeyFrame^.boneData[i].zRot+((diff/stepDiff)*tempFrame); end; end; end; end; procedure TGameObject.setInterpolation; begin interpolating_ := false; end; function TGameObject.interpolating : boolean; begin result := interpolating_; end; procedure TGameObject.draw(skipAnimation : boolean = false; skipHitboxes : boolean = false); begin if (hasModel_) then model_^.draw(@self, skipAnimation, skipHitboxes) else sprite_^.draw(@self); end; function TGameObject.mouseOverBox : boolean; var mouseX_, mouseY_, mouseXDist, mouseYDist, mouseDist, angle : real; begin result := false; if (not hasModel_) then begin if (zRotation_ <> 0.0) then begin mouseXDist := mouseX-x_; mouseYDist := mouseY-y_; mouseDist := sqrt((mouseXDist*mouseXDist)+(mouseYDist*mouseYDist)); angle := arctan2(mouseYDist, mouseXDist); mouseX_ := (mouseDist*cos(angle-degToRad(zRotation_)))+x_; mouseY_ := (mouseDist*sin(angle-degToRad(zRotation_)))+y_; end else begin mouseX_ := mouseX; mouseY_ := mouseY; end; if ((mouseX_ >= x_-originX) and (mouseX_ <= x_-originX+width_)) then begin if ((mouseY_ >= y_-originY) and (mouseY_ <= y_-originY+height_)) then result := true; end; end; end; function TGameObject.roughMouseOverBox : boolean; begin result := true; if (not hasModel_) then begin if (mouseX < x_-originX) then begin result := false; exit; end; if (mouseX > x_-originX+zRotatedWidth_) then begin result := false; exit; end; if (mouseY < y_-originY) then begin result := false; exit; end; if (mouseY > y_-originY+zRotatedHeight_) then begin result := false; exit; end; end else result := false; end; function TGameObject.mouseOverCircle(extraX : real = 0; extraY : real = 0; extraZ : real = 0) : boolean; var mouseXDist, mouseYDist, mouseDist : real; begin result := false; if (not hasModel_) then begin mouseXDist := mouseX-(x_+extraX); mouseYDist := mouseY-(y_+extraY); mouseDist := (mouseXDist*mouseXDist)+(mouseYDist*mouseYDist); if (mouseDist <= (width_/2)*(width_/2)) then result := true; end; end; function TGameObject.boxCollision(other : PGameObject; allStages : boolean = true) : boolean; var i : integer; pointX, pointY, tempPointX, tempPointY, tempPointDist, tempAngle, angle, calc, pointXDist, pointYDist, pointDist : real; begin result := false; if ((not hasModel_) and (not other^.hasModel_)) then begin for i := 0 to 3 do begin case i of 0: begin tempPointX := -other^.originX; tempPointY := -other^.originY; end; 1: begin tempPointX := -other^.originX; tempPointY := -other^.originY+other^.height_; end; 2: begin tempPointX := -other^.originX+other^.width_; tempPointY := -other^.originY+other^.height_; end; 3: begin tempPointX := -other^.originX+other^.width_; tempPointY := -other^.originY; end; end; if (other^.zRotation_ = 0.0) then begin tempPointX += other^.x_; tempPointY += other^.y_; end else begin tempPointDist := sqrt((tempPointX*tempPointX)+(tempPointY*tempPointY)); tempAngle := arctan2(tempPointY, tempPointX); calc := tempAngle-degToRad(other^.zRotation_); tempPointX := (tempPointDist*cos(calc))+other^.x_; tempPointY := (tempPointDist*sin(calc))+other^.y_; end; if (zRotation_ = 0.0) then begin pointX := tempPointX; pointY := tempPointY; end else begin pointXDist := tempPointX-x_; pointYDist := tempPointY-y_; pointDist := sqrt((pointXDist*pointXDist)+(pointYDist*pointYDist)); angle := arctan2(pointYDist, pointXDist); calc := angle-degToRad(zRotation_); pointX := (pointDist*cos(calc))+x_; pointY := (pointDist*sin(calc))+y_; end; if ((pointX >= x_-originX) and (pointX <= (x_-originX)+width_)) then begin if ((pointY >= y_-originY) and (pointY <= (y_-originY)+height_)) then begin result := true; exit; end; end; end; if (not allStages) then begin if ((other^.x_ >= x_-originX) and (other^.x_ <= (x_-originX)+width_)) then begin if ((other^.y_ >= y_-originY) and (other^.y_ <= (y_-originY)+height_)) then begin result := true; exit; end; end; result := false; exit; end; for i := 0 to 4 do begin if (i < 4) then begin case i of 0: begin tempPointX := -originX; tempPointY := -originY; end; 1: begin tempPointX := -originX; tempPointY := -originY+height_; end; 2: begin tempPointX := -originX+width_; tempPointY := -originY+height_; end; 3: begin tempPointX := -originX+width_; tempPointY := -originY; end; end; if (zRotation_ = 0.0) then begin tempPointX += x_; tempPointY += y_; end else begin tempPointDist := sqrt((tempPointX*tempPointX)+(tempPointY*tempPointY)); tempAngle := arctan2(tempPointY, tempPointX); calc := tempAngle-degToRad(zRotation_); tempPointX := (tempPointDist*cos(calc))+x_; tempPointY := (tempPointDist*sin(calc))+y_; end; if (other^.zRotation_ = 0.0) then begin pointX := tempPointX; pointY := tempPointY; end else begin pointXDist := tempPointX-other^.x_; pointYDist := tempPointY-other^.y_; pointDist := sqrt((pointXDist*pointXDist)+(pointYDist*pointYDist)); angle := arctan2(pointYDist, pointXDist); calc := angle-degToRad(other^.zRotation_); pointX := (pointDist*cos(calc))+other^.x_; pointY := (pointDist*sin(calc))+other^.y_; end; end else begin pointX := x_; pointY := y_; end; if ((pointX >= other^.x_-other^.originX) and (pointX <= (other^.x_-other^.originX)+other^.width_)) then begin if ((pointY >= other^.y_-other^.originY) and (pointY <= (other^.y_-other^.originY)+other^.height_)) then begin result := true; exit; end; end; end; end; end; function TGameObject.roughBoxCollision(other : PGameObject) : boolean; begin result := true; if ((not hasModel_) and (not other^.hasModel_)) then begin if (x_+zRotatedWidth_-originX < other^.x_-other^.originX) then begin result := false; exit; end; if (other^.x_+other^.zRotatedWidth_-other^.originX < x_-originX) then begin result := false; exit; end; if (y_+zRotatedHeight_-originY < other^.y_-other^.originY) then begin result := false; exit; end; if (other^.y_+other^.zRotatedHeight_-other^.originY < y_-originY) then begin result := false; exit; end; end else result := false; end; function TGameObject.circleCollision(other : PGameObject; extraX1 : real = 0; extraY1 : real = 0; extraZ1 : real = 0; extraX2 : real = 0; extraY2 : real = 0; extraZ2 : real = 0) : boolean; begin result := false; end; function TGameObject.roughHitboxCollision(bone1, bone2 : pbone) : boolean; begin if ((bone1 <> nil) and (bone2 <> nil)) then begin if (bone1^.hitbox.x+bone1^.hitbox.rl < bone2^.hitbox.x) then begin result := false; exit; end; if (bone2^.hitbox.x+bone2^.hitbox.rl < bone1^.hitbox.x) then begin result := false; exit; end; if (bone1^.hitbox.y+bone1^.hitbox.rh < bone2^.hitbox.y) then begin result := false; exit; end; if (bone2^.hitbox.y+bone2^.hitbox.rh < bone1^.hitbox.y) then begin result := false; exit; end; if (bone1^.hitbox.z+bone1^.hitbox.rw < bone2^.hitbox.z) then begin result := false; exit; end; if (bone2^.hitbox.z+bone2^.hitbox.rw < bone1^.hitbox.z) then begin result := false; exit; end; end; result := true; end; function TGameObject.hitBoxCollision(bone1, bone2 : pbone) : boolean; begin result := false; end; function TGameObject.roughModelCollision(other : PGameObject; hitboxId : integer = -1; hitboxOtherId : integer = -1) : boolean; var i, j : integer; begin if (hasModel_ and other^.hasModel_) then begin if (hitboxId < 0) then begin if (hitboxOtherId < 0) then begin for i := 0 to length(model_^.bones)-1 do begin for j := 0 to length(other^.model_^.bones)-1 do begin if (roughHitboxCollision(model_^.bones[i], other^.model_^.bones[j])) then begin result := true; exit; end; end; end; end else begin for i := 0 to length(model_^.bones)-1 do begin if (roughHitboxCollision(model_^.bones[i], other^.model_^.bones[hitboxOtherId])) then begin result := true; exit; end; end; end; end else begin if (hitboxOtherId < 0) then begin for i := 0 to length(other^.model_^.bones)-1 do begin if (roughHitboxCollision(model_^.bones[hitboxId], other^.model_^.bones[i])) then begin result := true; exit; end; end; end else begin if (roughHitboxCollision(model_^.bones[hitboxId], other^.model_^.bones[hitboxOtherId])) then begin result := true; exit; end; end; end; end; result := false; end; function TGameObject.modelCollision(other : PGameObject; hitboxId : integer = -1; hitboxOtherId : integer = -1) : boolean; begin result := false; end; procedure setKeyFrame(frame : pkeyFrame; model : PModel); var i : integer; begin for i := 0 to length(frame^.boneData)-1 do begin model^.bones[frame^.boneData[i].boneId]^.xRot := frame^.boneData[i].xRot; model^.bones[frame^.boneData[i].boneId]^.yRot := frame^.boneData[i].yRot; model^.bones[frame^.boneData[i].boneId]^.zRot := frame^.boneData[i].zRot; end; end; function subtractNormal(operandNormal, subtractingNormal : normal) : normal; begin result.x := operandNormal.x-subtractingNormal.x; result.y := operandNormal.y-subtractingNormal.y; result.z := operandNormal.z-subtractingNormal.z; end; function subtractVertex(operandVertex, subtractingVertex : vertex) : vertex; begin result.x := operandVertex.x-subtractingVertex.x; result.y := operandVertex.y-subtractingVertex.y; result.z := operandVertex.z-subtractingVertex.z; end; function getSurfaceNormal(srcTriangle : ptriangle) : normal; var u, v : vertex; normal_ : normal; len : real; begin u := subtractVertex(srcTriangle^.coords[1], srcTriangle^.coords[0]); v := subtractVertex(srcTriangle^.coords[2], srcTriangle^.coords[0]); normal_.x := (u.y*v.z)-(u.z*v.y); normal_.y := (u.z*v.x)-(u.x*v.z); normal_.z := (u.x*v.y)-(u.y*v.x); len := sqrt((normal_.x*normal_.x)+(normal_.y*normal_.y)+(normal_.z*normal_.z)); if (len = 0) then len := 1; normal_.x /= len; normal_.y /= len; normal_.z /= len; result := normal_; end; procedure initBox(dstBox : pbox); begin dstBox^.x := 0.0; dstBox^.y := 0.0; dstBox^.z := 0.0; dstBox^.l := 0.0; dstBox^.w := 0.0; dstBox^.h := 0.0; dstBox^.xRot := 0.0; dstBox^.yRot := 0.0; dstBox^.zRot := 0.0; end; function sprite(searchName : string) : PSprite; var letter : char; i : word; tempSprite : PSprite; begin letter := searchName[1]; result := nil; if (allSprites[letter].count > 0) then begin for i := 0 to allSprites[letter].count-1 do begin tempSprite := PSprite(allSprites[letter][i]); if (tempSprite^.name = searchName) then result := tempSprite; end; end; end; function addSprite(newName, fileName : string; imageX, imageY, imageWidth, imageHeight : integer; aniframes : integer = 1; frameChangePerSecond : integer = 1; newOriginX : integer = 0; newOriginY : integer = 0; customBufferFunction : customSpriteBufferFunctionType = nil; customData : Pointer = nil) : PSprite; var letter : char; begin letter := newName[1]; allSprites[letter].add(new(PSprite, create(newName, fileName, imageX, imageY, imageWidth, imageHeight, aniframes, frameChangePerSecond, newOriginX, newOriginY, customBufferFunction, customData))); result := allSprites[letter].last; end; procedure destroySprite(searchName : string); var letter : char; i : word; tempSprite : PSprite; begin letter := searchName[1]; if (allSprites[letter].count > 0) then begin for i := 0 to allSprites[letter].count-1 do begin tempSprite := PSprite(allSprites[letter][i]); if (tempSprite^.name = searchName) then begin dispose(tempSprite, destroy); allSprites[letter].delete(i); break; end; end; end; end; procedure destroyAllSprites; var i : char; j : integer; tempSprite : PSprite; begin for i := 'a' to 'z' do begin if (allSprites[i].count > 0) then begin for j := 0 to allSprites[i].count-1 do begin tempSprite := PSprite(allSprites[i][j]); dispose(tempSprite, destroy); end; allSprites[i].clear; end; end; end; function model(searchName : string) : PModel; var letter : char; i : word; tempModel : PModel; begin letter := searchName[1]; result := nil; if (allModels[letter].count > 0) then begin for i := 0 to allModels[letter].count-1 do begin tempModel := PModel(allModels[letter][i]); if (tempModel^.name = searchName) then result := tempModel; end; end; end; function addModel(newName, path, fileName : string; framerate : word = 60; customBufferFunction : customModelBufferFunctionType = nil; customData : Pointer = nil) : PModel; var letter : char; begin letter := newName[1]; allModels[letter].add(new(PModel, create(newName, path, fileName, framerate, customBufferFunction, customData))); result := allModels[letter].last; end; procedure destroyModel(searchName : string); var letter : char; i : word; tempModel : PModel; begin letter := searchName[1]; if (allModels[letter].count > 0) then begin for i := 0 to allModels[letter].count-1 do begin tempModel := PModel(allModels[letter][i]); if (tempModel^.name = searchName) then begin dispose(tempModel, destroy); allModels[letter].delete(i); break; end; end; end; end; procedure destroyAllModels; var i : char; j : integer; tempModel : PModel; begin for i := 'a' to 'z' do begin if (allModels[i].count > 0) then begin for j := 0 to allModels[i].count-1 do begin tempModel := PModel(allModels[i][j]); dispose(tempModel, destroy); end; allModels[i].clear; end; end; end; function gameObject(searchName : string) : PGameObject; var letter : char; i : word; tempGameObject : PGameObject; begin letter := searchName[1]; result := nil; if (allGameObjects[letter].count > 0) then begin for i := 0 to allGameObjects[letter].count-1 do begin tempGameObject := PGameObject(allGameObjects[letter][i]); if (tempGameObject^.name = searchName) then result := tempGameObject; end; end; end; function addGameObject(newName : string; destX, destY, destZ : real; newSprite : PSprite = nil; startFrame : word = 0) : PGameObject; var letter : char; begin letter := newName[1]; allGameObjects[letter].add(new(PGameObject, create(newName, destX, destY, destZ, newSprite, startFrame))); result := allGameObjects[letter].last; end; function addGameObject(newName : string; destX, destY, destZ : real; newModel : PModel = nil) : PGameObject; var letter : char; begin letter := newName[1]; allGameObjects[letter].add(new(PGameObject, create(newName, destX, destY, destZ, newModel))); result := allGameObjects[letter].last; end; procedure destroyGameObject(searchName : string); var letter : char; i : word; tempGameObject : PGameObject; begin letter := searchName[1]; if (allGameObjects[letter].count > 0) then begin for i := 0 to allGameObjects[letter].count-1 do begin tempGameObject := PGameObject(allGameObjects[letter][i]); if (tempGameObject^.name = searchName) then begin dispose(tempGameObject, destroy); allGameObjects[letter].delete(i); break; end; end; end; end; procedure destroyAllGameObjects; var i : char; j : integer; tempGameObject : PGameObject; begin for i := 'a' to 'z' do begin if (allGameObjects[i].count > 0) then begin for j := 0 to allGameObjects[i].count-1 do begin tempGameObject := PGameObject(allGameObjects[i][j]); dispose(tempGameObject, destroy); end; allGameObjects[i].clear; end; end; end; procedure initializeAllGraphicalAssets; var i : char; begin for i := 'a' to 'z' do begin allSprites[i] := TList.create; allModels[i] := TList.create; allGameObjects[i] := TList.create; end; end; procedure finalizeAllGraphicalAssets; var i : char; begin for i := 'a' to 'z' do begin allSprites[i].destroy; allModels[i].destroy; allGameObjects[i].destroy; end; end; initialization initializeAllGraphicalAssets; finalization finalizeAllGraphicalAssets; end.
namespace GLExample; interface uses rtl, GlHelper, OpenGL; type GL_Example_2 = class(IAppInterface) private // fTexture : Texture; shader : Shader; fVertexArray : VertexArray; FTexture1: Texture; FTexture2: Texture; FUniformOurTexture1: GLint; FUniformOurTexture2: GLint; public method initialize : Boolean; method Update(width, height : Integer; const ATotalTimeSec : Double := 0.3); method ChangeFillmode; end; implementation method GL_Example_2.initialize: Boolean; const { Each vertex consists of a 3-element position and 3-element color. } VERTICES: array of Single = [ // Positions // Texture Coords 0.5, 0.4, 0.0, 1.0, 1.0, // Top Right 0.5, -0.4, 0.0, 1.0, 0.0, // Bottom Right -0.5, -0.5, 0.0, 0.0, 0.0, // Bottom Left -0.5, 0.5, 0.0, 0.0, 1.0]; // Top Left const { The indices define a single triangle } INDICES: array of UInt16 = [0, 1, 3, 1,2,3]; Var VertexLayout : VertexLayout; begin shader := new Shader('texture.vs', 'texture.fs'); FUniformOurTexture1 := shader.GetUniformLocation('ourTexture1'); FUniformOurTexture2 := shader.GetUniformLocation('ourTexture2'); { Define layout of the attributes in the shader program. The shader program contains 2 attributes called "position" and "color". Both attributes are of type "vec3" and thus contain 3 floating-point values. } VertexLayout := new VertexLayout(shader._GetHandle) .Add('position', 3) .Add('texCoord', 2); { Create the vertex array } fVertexArray := new VertexArray(VertexLayout, VERTICES, INDICES); FTexture1 := new Texture('Tex1.JPG'); FTexture2 := new Texture('coral.jpg'); //FTexture2 := new Texture('gears.png'); result := true; end; method GL_Example_2.Update(width, height : Integer; const ATotalTimeSec : Double := 0.3); begin glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); shader.Use; { Bind Textures using texture units } glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, FTexture1.Id); glUniform1i(FUniformOurTexture1, 0); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, FTexture2.Id); glUniform1i(FUniformOurTexture2, 1); { Draw the rectangle } fVertexArray.Render; end; method GL_Example_2.ChangeFillmode; begin end; end.
unit uPhotoShareInterfaces; interface uses uMemory, Generics.Collections, Classes, SyncObjs, SysUtils, Graphics, uInternetUtils; const PHOTO_PROVIDER_FEATURE_ALBUMS = '{06213CD9-35C9-4FA8-B21D-4D7628347DEC}'; PHOTO_PROVIDER_FEATURE_PRIVATE_ITEMS = '{0D4C568C-C3E7-45DD-9E61-47D529480D0E}'; PHOTO_PROVIDER_FEATURE_DELETE = '{7258EB96-A9FE-4E63-8035-2F94680EC320}'; PHOTO_PROVIDER_ALBUM_PUBLIC = 1; PHOTO_PROVIDER_ALBUM_PROTECTED = 2; PHOTO_PROVIDER_ALBUM_PRIVATE = 3; type IPhotoServiceUserInfo = interface function GetUserAvatar(Bitmap: TBitmap): Boolean; function GetUserDisplayName: string; function GetHomeUrl: string; function GetAvailableSpace: Int64; property UserDisplayName: string read GetUserDisplayName; property HomeUrl: string read GetHomeUrl; property AvailableSpace: Int64 read GetAvailableSpace; end; IPhotoServiceItem = interface function GetName: string; function GetDescription: string; function GetDate: TDateTime; function GetUrl: string; function GetSize: Int64; function GetWidth: Integer; function GetHeight: Integer; function ExtractPreview(Image: TBitmap): Boolean; function Delete: Boolean; property Name: string read GetName; property Description: string read GetDescription; property Date: TDateTime read GetDate; property Url: string read GetUrl; property Size: Int64 read GetSize; property Width: Integer read GetWidth; property Height: Integer read GetHeight; end; IPhotoShareProvider = interface; IUploadProgress = interface procedure OnProgress(Sender: IPhotoShareProvider; Max, Position: Int64; var Cancel: Boolean); end; IPhotoServiceAlbum = interface function UploadItem(FileName, Name, Description: string; Date: TDateTime; ContentType: string; Stream: TStream; Progress: IUploadProgress; out Item: IPhotoServiceItem): Boolean; function GetAlbumID: string; function GetName: string; function GetDescription: string; function GetDate: TDateTime; function GetUrl: string; function GetAccess: Integer; function GetPreview(Bitmap: TBitmap; HttpContainer: THTTPRequestContainer = nil): Boolean; property AlbumID: string read GetAlbumID; property Name: string read GetName; property Description: string read GetDescription; property Date: TDateTime read GetDate; property Url: string read GetUrl; property Access: Integer read GetAccess; end; IPhotoShareProvider = interface function InitializeService: Boolean; function GetProviderName: string; function GetUserInfo(out Info: IPhotoServiceUserInfo): Boolean; function GetAlbumList(Albums: TList<IPhotoServiceAlbum>): Boolean; function CreateAlbum(Name, Description: string; Date: TDateTime; Access: Integer; out Album: IPhotoServiceAlbum): Boolean; function UploadPhoto(AlbumID, FileName, Name, Description: string; Date: TDateTime; ContentType: string; Stream: TStream; Progress: IUploadProgress; out Photo: IPhotoServiceItem): Boolean; function IsFeatureSupported(Feature: string): Boolean; function GetProviderImage(Bitmap: TBitmap): Boolean; function ChangeUser: Boolean; end; TPhotoShareManager = class(TObject) private FProviders: TList<IPhotoShareProvider>; FSync: TCriticalSection; public constructor Create; destructor Destroy; override; procedure RegisterProvider(Provider: IPhotoShareProvider); procedure FillProviders(Items: TList<IPhotoShareProvider>); end; function PhotoShareManager: TPhotoShareManager; function GetFileMIMEType(FileName: string): string; implementation var FPhotoShareManager: TPhotoShareManager = nil; function PhotoShareManager: TPhotoShareManager; begin if FPhotoShareManager = nil then FPhotoShareManager := TPhotoShareManager.Create; Result := FPhotoShareManager; end; { ---------------------- * video/3gpp * video/avi * video/quicktime * video/mp4 * video/mpeg * video/mpeg4 * video/msvideo * video/x-ms-asf * video/x-ms-wmv * video/x-msvideo } function GetFileMIMEType(FileName: string): string; var Ext: string; begin Ext := AnsiLowerCase(ExtractFileExt(FileName)); Result := 'video/' + StringReplace(Ext, '.', '', []); if (Ext = '.3gp2') or (Ext = '.3gpp') or (Ext = '.3gp') or (Ext = '.3g2') then Result := 'video/3gpp' else if (Ext = '.avi') then Result := 'video/avi' else if (Ext = '.mov') then Result := 'video/quicktime' else if (Ext = '.mp4') then Result := 'video/mp4' else if (Ext = '.mpeg') then Result := 'video/mpeg' else if (Ext = '.mpeg4') then Result := 'video/mpeg4' else if (Ext = '.asf') then Result := 'video/x-ms-asf' else if (Ext = '.wmv') then Result := 'video/x-ms-wmv'; end; { TPhotoShareManager } constructor TPhotoShareManager.Create; begin FProviders := TList<IPhotoShareProvider>.Create; FSync := TCriticalSection.Create; end; destructor TPhotoShareManager.Destroy; begin F(FProviders); F(FSync); inherited; end; procedure TPhotoShareManager.FillProviders(Items: TList<IPhotoShareProvider>); begin FSync.Enter; try Items.AddRange(FProviders); finally FSync.Leave; end; end; procedure TPhotoShareManager.RegisterProvider(Provider: IPhotoShareProvider); begin FSync.Enter; try FProviders.Add(Provider); finally FSync.Leave; end; end; initialization finalization F(FPhotoShareManager); end.
unit TpAnchor; interface uses Windows, Classes, Controls, StdCtrls, ExtCtrls, Graphics, Messages, SysUtils, Types, ThTag, ThAnchor, TpControls; type TTpAnchor = class(TThAnchor) private FClient: TComponent; protected procedure Tag(inTag: TThTag); override; public constructor Create(inClient: TComponent); public property Client: TComponent read FClient write FClient; end; implementation constructor TTpAnchor.Create(inClient: TComponent); begin inherited Create; Client := inClient; end; procedure TTpAnchor.Tag(inTag: TThTag); begin inherited; if Client <> nil then begin inTag.Add(tpClass, 'TTpAnchor'); inTag.Add('tpName', Client.Name + 'Anchor'); end; end; end.
(* Generates a grid based dungeon level *) unit grid_dungeon; {$mode objfpc}{$H+} interface uses globalutils, map; type coordinates = record x, y: smallint; end; var r, c, i, p, t, listLength, firstHalf, lastHalf: smallint; dungeonArray: array[1..globalutils.MAXROWS, 1..globalutils.MAXCOLUMNS] of char; totalRooms, roomSquare: smallint; (* start creating corridors once this rises above 1 *) roomCounter: smallint; (* Player starting position *) startX, startY: smallint; (* TESTING - Write dungeon to text file *) filename: ShortString; myfile: Text; (* Carve a horizontal tunnel *) procedure carveHorizontally(x1, x2, y: smallint); (* Carve a vertical tunnel *) procedure carveVertically(y1, y2, x: smallint); (* Carve corridor between rooms *) procedure createCorridor(fromX, fromY, toX, toY: smallint); (* Create a room *) procedure createRoom(gridNumber: smallint); (* Generate a dungeon *) procedure generate; (* sort room list in order from left to right *) procedure leftToRight; implementation procedure leftToRight; var i, j, n, tempX, tempY: smallint; begin n := length(globalutils.currentDgncentreList) - 1; for i := n downto 2 do for j := 0 to i - 1 do if globalutils.currentDgncentreList[j].x > globalutils.currentDgncentreList[j + 1].x then begin tempX := globalutils.currentDgncentreList[j].x; tempY := globalutils.currentDgncentreList[j].y; globalutils.currentDgncentreList[j].x := globalutils.currentDgncentreList[j + 1].x; globalutils.currentDgncentreList[j].y := globalutils.currentDgncentreList[j + 1].y; globalutils.currentDgncentreList[j + 1].x := tempX; globalutils.currentDgncentreList[j + 1].y := tempY; end; end; procedure carveHorizontally(x1, x2, y: smallint); var x: byte; begin if x1 < x2 then begin for x := x1 to x2 do dungeonArray[y][x] := '.'; end; if x1 > x2 then begin for x := x2 to x1 do dungeonArray[y][x] := '.'; end; end; procedure carveVertically(y1, y2, x: smallint); var y: byte; begin if y1 < y2 then begin for y := y1 to y2 do dungeonArray[y][x] := '.'; end; if y1 > y2 then begin for y := y2 to y1 do dungeonArray[y][x] := '.'; end; end; procedure createCorridor(fromX, fromY, toX, toY: smallint); var direction: byte; begin // flip a coin to decide whether to first go horizontally or vertically direction := Random(2); // horizontally first if direction = 1 then begin carveHorizontally(fromX, toX, fromY); carveVertically(fromY, toY, toX); end // vertically first else begin carveVertically(fromY, toY, toX); carveHorizontally(fromX, toX, fromY); end; end; procedure createRoom(gridNumber: smallint); var topLeftX, topLeftY, roomHeight, roomWidth, drawHeight, drawWidth, nudgeDown, nudgeAcross: smallint; begin // initialise variables topLeftX := 0; topLeftY := 0; roomHeight := 0; roomWidth := 0; drawHeight := 0; drawWidth := 0; // row 1 if (gridNumber >= 1) and (gridNumber <= 13) then begin topLeftX := (gridNumber * 5) - 3; topLeftY := 2; end; // row 2 if (gridNumber >= 14) and (gridNumber <= 26) then begin topLeftX := (gridNumber * 5) - 68; topLeftY := 8; end; // row 3 if (gridNumber >= 27) and (gridNumber <= 39) then begin topLeftX := (gridNumber * 5) - 133; topLeftY := 14; end; // row 4 if (gridNumber >= 40) and (gridNumber <= 52) then begin topLeftX := (gridNumber * 5) - 198; topLeftY := 20; end; // row 5 if (gridNumber >= 53) and (gridNumber <= 65) then begin topLeftX := (gridNumber * 5) - 263; topLeftY := 26; end; // row 6 if (gridNumber >= 66) and (gridNumber <= 78) then begin topLeftX := (gridNumber * 5) - 328; topLeftY := 32; end; (* Randomly select room dimensions between 2 - 5 tiles in height / width *) roomHeight := Random(2) + 3; roomWidth := Random(2) + 3; (* Change starting point of each room so they don't all start drawing from the top left corner *) case roomHeight of 2: nudgeDown := Random(0) + 2; 3: nudgeDown := Random(0) + 1; else nudgeDown := 0; end; case roomWidth of 2: nudgeAcross := Random(0) + 2; 3: nudgeAcross := Random(0) + 1; else nudgeAcross := 0; end; (* Save coordinates of the centre of the rooms *) listLength := Length(globalutils.currentDgncentreList); SetLength(globalutils.currentDgncentreList, listLength + 1); globalutils.currentDgncentreList[listLength].x := (topLeftX + nudgeAcross) + (roomWidth div 2); globalutils.currentDgncentreList[listLength].y := (topLeftY + nudgeDown) + (roomHeight div 2); (* Draw room within the grid square *) for drawHeight := 0 to roomHeight do begin for drawWidth := 0 to roomWidth do begin dungeonArray[(topLeftY + nudgeDown) + drawHeight][(topLeftX + nudgeAcross) + drawWidth] := '.'; end; end; end; procedure generate; begin roomCounter := 0; // initialise the array SetLength(globalutils.currentDgncentreList, 1); // fill map with walls for r := 1 to globalutils.MAXROWS do begin for c := 1 to globalutils.MAXCOLUMNS do begin dungeonArray[r][c] := '#'; end; end; // Random(Range End - Range Start) + Range Start; totalRooms := Random(10) + 20; // between 20 - 30 rooms for i := 1 to totalRooms do begin // randomly choose grid location from 1 to 78 roomSquare := Random(77) + 1; createRoom(roomSquare); Inc(roomCounter); end; leftToRight(); for i := 1 to (totalRooms - 1) do begin createCorridor(globalutils.currentDgncentreList[i].x, globalutils.currentDgncentreList[i].y, globalutils.currentDgncentreList[i + 1].x, globalutils.currentDgncentreList[i + 1].y); end; // connect random rooms so the map isn't totally linear // from the first half of the room list firstHalf := (totalRooms div 2); p := random(firstHalf - 1) + 1; t := random(firstHalf - 1) + 1; createCorridor(globalutils.currentDgncentreList[p].x, globalutils.currentDgncentreList[p].y, globalutils.currentDgncentreList[t].x, globalutils.currentDgncentreList[t].y); // from the second half of the room list lastHalf := (totalRooms - firstHalf); p := random(lastHalf) + firstHalf; t := random(lastHalf) + firstHalf; createCorridor(globalutils.currentDgncentreList[p].x, globalutils.currentDgncentreList[p].y, globalutils.currentDgncentreList[t].x, globalutils.currentDgncentreList[t].y); // set player start coordinates map.startX := globalutils.currentDgncentreList[1].x; map.startY := globalutils.currentDgncentreList[1].y; ///////////////////////////// // Write map to text file for testing //filename := 'output_grid_dungeon.txt'; //AssignFile(myfile, filename); //rewrite(myfile); //for r := 1 to MAXROWS do //begin // for c := 1 to MAXCOLUMNS do // begin // Write(myfile, dungeonArray[r][c]); // end; // Write(myfile, sLineBreak); //end; //closeFile(myfile); ////////////////////////////// // Copy array to main dungeon for r := 1 to globalutils.MAXROWS do begin for c := 1 to globalutils.MAXCOLUMNS do begin globalutils.dungeonArray[r][c] := dungeonArray[r][c]; end; end; (* Copy total rooms to main dungeon *) globalutils.currentDgnTotalRooms := totalRooms; (* Set flag for type of dungeon *) map.mapType := 1; end; end.
program questao15; { Autor: Hugo Deiró Data: 03/06/2012 - Este programa calcula o salário líquido de uma pessoa; } const INSS = 0.08; Sindicato = 0.05; IR = 0.11; var horas_trabalhadas : integer; valor_hora : real; begin write('Insira o número de horas trabalhadas no mês: '); readln(horas_trabalhadas); write('Insira o valor da hora de trabalho: '); readln(valor_hora); writeln; writeln('Salário Bruto = R$',(horas_trabalhadas*valor_hora):6:2); writeln('INSS = ',(horas_trabalhadas*valor_hora)*0.08:6:2); writeln('IR = ',(horas_trabalhadas*valor_hora)*0.11:6:2); writeln('Sindicato = ',(horas_trabalhadas*valor_hora)*0.05:6:2); writeln('Salário Líquido = R$',(horas_trabalhadas*valor_hora) - ((horas_trabalhadas*valor_hora)*0.24):6:2); end.
unit UnitFavs; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, sButton, Vcl.Buttons, sBitBtn, sEdit, sListBox, sCheckListBox, sSkinProvider; type TFavForm = class(TForm) sSkinProvider1: TsSkinProvider; FavList: TsCheckListBox; NewFavEdit: TsEdit; AddBtn: TsBitBtn; SaveBtn: TsButton; CancelBtn: TsButton; ClearBtn: TsButton; RemoveBtn: TsButton; UpBtn: TsButton; DownBtn: TsButton; DownloadBtn: TsButton; procedure CancelBtnClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure AddBtnClick(Sender: TObject); procedure SaveBtnClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure NewFavEditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure RemoveBtnClick(Sender: TObject); procedure ClearBtnClick(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure FavListClickCheck(Sender: TObject); procedure UpBtnClick(Sender: TObject); procedure DownBtnClick(Sender: TObject); procedure DownloadBtnClick(Sender: TObject); private { Private declarations } FEdited: Boolean; public { Public declarations } end; var FavForm: TFavForm; implementation {$R *.dfm} uses UnitMain; procedure TFavForm.AddBtnClick(Sender: TObject); begin if Length(NewFavEdit.Text) > 0 then begin NewFavEdit.Text := LowerCase(NewFavEdit.Text); FavList.Items.Add(NewFavEdit.Text); FavList.Checked[FavList.Items.Count - 1] := True; NewFavEdit.Text := ''; FEdited := True; end else begin Application.MessageBox('Please enter a user name.', 'Error', MB_ICONERROR); end; end; procedure TFavForm.CancelBtnClick(Sender: TObject); begin Self.Close; end; procedure TFavForm.ClearBtnClick(Sender: TObject); begin if ID_YES = Application.MessageBox('Clear the favourites? This cannot be reversed!', 'Clear', MB_ICONQUESTION or MB_YESNO) then begin FEdited := True; // delete fav file if FileExists(MainForm.FFavFilePath) then begin DeleteFile(MainForm.FFavFilePath); end; FavList.Items.Clear; end; end; procedure TFavForm.DownBtnClick(Sender: TObject); var I: Integer; begin I := Favlist.Items.Count - 2; while I >= 0 do begin if Favlist.Selected[I] then begin Favlist.Items.Exchange(I, I + 1); Favlist.Selected[I + 1] := True; end; Dec(I); end; end; procedure TFavForm.DownloadBtnClick(Sender: TObject); begin if FavList.ItemIndex > -1 then begin Self.Close; MainForm.UserNameEdit.Text := FavList.Items[FavList.ItemIndex]; MainForm.DownloadBtnClick(Self); end; end; procedure TFavForm.FavListClickCheck(Sender: TObject); begin FEdited := True; end; procedure TFavForm.FormClose(Sender: TObject; var Action: TCloseAction); begin FEdited := True; MainForm.Enabled := True; MainForm.BringToFront; end; procedure TFavForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); var LAnswer: integer; begin if FEdited then begin // ask user wheter they want to close the form LAnswer := Application.MessageBox('Some values are changed. Do you want to save them before you close this window?', 'Save', MB_ICONQUESTION or MB_YESNO); if ID_YES = LAnswer then begin // save then close SaveBtnClick(Self); CanClose := True; end else if ID_CANCEL = LAnswer then begin // dont close wtf CanClose := False; end else begin // close CanClose := True; end; end else begin // nothing's changed just close the form CanClose := True; end; end; procedure TFavForm.FormShow(Sender: TObject); var LFavFile: TStringList; I: Integer; LSplit: TStringList; begin FEdited := False; FavList.Items.Clear; if FileExists(MainForm.FFavFilePath) then begin LFavFile := TStringList.Create; LSplit := TStringList.Create; try LSplit.StrictDelimiter := True; LSplit.Delimiter := '|'; LFavFile.LoadFromFile(MainForm.FFavFilePath); for I := 0 to LFavFile.Count - 1 do begin LSplit.Clear; LSplit.DelimitedText := LFavFile[i]; if LSplit.Count = 2 then begin FavList.Items.Add(LSplit[0]); if LSplit[1] = '1' then begin FavList.Checked[FavList.Items.Count - 1] := True; end else begin FavList.Checked[FavList.Items.Count - 1] := false; end; end; end; finally LFavFile.Free; LSplit.Free; end; end; end; procedure TFavForm.NewFavEditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_RETURN then begin AddBtnClick(Self); end; end; procedure TFavForm.RemoveBtnClick(Sender: TObject); begin FavList.DeleteSelected; FEdited := true; end; procedure TFavForm.SaveBtnClick(Sender: TObject); var I: Integer; LTmpList: TStringList; begin if FavList.Items.Count > 0 then begin LTmpList := TStringList.Create; try for I := 0 to FavList.Items.Count - 1 do begin if FavList.Checked[i] then begin LTmpList.Add(FavList.Items[i] + '|1') end else begin LTmpList.Add(FavList.Items[i] + '|0') end; end; LTmpList.SaveToFile(MainForm.FFavFilePath, TEncoding.UTF8); finally LTmpList.Free; end; end else begin DeleteFile(MainForm.FFavFilePath) end; FEdited := False; Self.Close; end; procedure TFavForm.UpBtnClick(Sender: TObject); var I: Integer; begin I := 1; while I < Favlist.Items.Count do begin if Favlist.Selected[I] then begin Favlist.Items.Exchange(I, I - 1); Favlist.Selected[I - 1] := True; end; Inc(I); end; end; end.
unit vNoteCreator_MainForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, MyDialogs, MySkinCtrls, MySkinButtons, MySkinTheme, StdCtrls, MySkinEditors, MySkinEngine, AIMP_BaseSysUtils, AnsiStrings, JwaBluetoothAPIs, JwaBtHDef, Menus, MySkinMenus, WinSock, JwaWs2Bth; type TMainForm = class(TMyForm) smText: TMySkinMemo; stMain: TMySkinTheme; sbOpen: TMySkinButton; sbAbout: TMySkinButton; fdOpenSave: TMyFileDialog; sbSave: TMySkinButton; sbQuit: TMySkinButton; ssLUID: TMySkinSpin; slbLUID: TMySkinLabel; sbClear: TMySkinButton; sbSend: TMySkinButton; spDevices: TMySkinPopup; procedure FormCreate(Sender: TObject); procedure sbQuitClick(Sender: TObject); procedure sbOpenClick(Sender: TObject); procedure sbSaveClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure sbClearClick(Sender: TObject); procedure sbAboutClick(Sender: TObject); private { Private declarations } public function EncodeDateTime: AnsiString; function EncodeStr: AnsiString; procedure SaveToFile(const AFileName: WideString); procedure EnumBluetoothDevices(ARadio: Cardinal); procedure EnumBluetoothRadio; procedure SendFile; end; {$R vNoteCreator_Skin.res} var MainForm: TMainForm; const Pattern: AnsiString = 'BEGIN:VNOTE' + #13#10 + 'VERSION:1.1' + #13#10 + 'BODY;ENCODING=QUOTED-PRINTABLE;CHARSET=UTF-8:%s' + #13#10 + 'DCREATED:%s' + #13#10 + 'X-IRMC-LUID:%d' + #13#10 + 'END:VNOTE'; BT_SOCKET_VERSION = $0202; implementation {$R *.dfm} uses vNoteCreator_AboutForm; // ByteToHex function ByteToHex(AByte: Byte): AnsiString; const Convert: array[0..15] of AnsiChar = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'); begin Result := Convert[AByte shr 4] + Convert[AByte and $F]; end; function TMainForm.EncodeDateTime: AnsiString; var ATemp: WideString; begin ATemp := FormatDateTime('yyyymmdd"T"hhnnss', Now); Result := AnsiFromWide(ATemp); end; function TMainForm.EncodeStr: AnsiString; var ATemp: RawByteString; I: Integer; begin Result := ''; ATemp := EncodeUTF8(smText.Text); for I := 1 to Length(ATemp) do begin Result := Result + '=' + ByteToHex(Byte(ATemp[I])); end; end; procedure TMainForm.EnumBluetoothDevices(ARadio: Cardinal); var AFind: HBLUETOOTH_DEVICE_FIND; AParams: BLUETOOTH_DEVICE_SEARCH_PARAMS; AInfo: BLUETOOTH_DEVICE_INFO; AItem: TMenuItem; begin ZeroMemory(@AParams, SizeOf(BLUETOOTH_DEVICE_SEARCH_PARAMS)); AParams.dwSize := SizeOf(BLUETOOTH_DEVICE_SEARCH_PARAMS); AParams.fReturnRemembered := True; AParams.hRadio := ARadio; AInfo.dwSize := SizeOf(BLUETOOTH_DEVICE_INFO); AFind := BluetoothFindFirstDevice(AParams, AInfo); if AFind <> 0 then begin repeat AItem := TMenuItem.Create(spDevices); AItem.Caption := WideString(AInfo.szName); spDevices.Items.Add(AItem); until not BluetoothFindNextDevice(AFind, AInfo); BluetoothFindDeviceClose(AFind); end; end; procedure TMainForm.EnumBluetoothRadio; var AFind: HBLUETOOTH_RADIO_FIND; AParams: BLUETOOTH_FIND_RADIO_PARAMS; ARadio: Cardinal; begin AParams.dwSize := SizeOf(BLUETOOTH_FIND_RADIO_PARAMS); AFind := BluetoothFindFirstRadio(@AParams, ARadio); if AFind <> 0 then begin repeat EnumBluetoothDevices(ARadio); CloseHandle(ARadio); until not BluetoothFindNextRadio(AFind, ARadio); BluetoothFindRadioClose(ARadio); end; end; procedure TMainForm.FormCreate(Sender: TObject); var AIni: TAIMPIniFile; begin AIni := TAIMPIniFile.Create(ExtractFilePath(ParamStr(0)) + 'config.ini', False); try if AIni.ValueExists('Window', 'Bounds') then begin Position := poDesigned; BoundsRect := AIni.ReadRect('Window', 'Bounds'); end; ssLUID.Value := AIni.ReadInteger('LastLUID', 'Value', 27); stMain.LoadFromResource(HInstance, 'Skin', RT_RCDATA); Color := stMain.ContentColor; EnumBluetoothRadio; sendfile; finally AIni.Free; end; end; procedure TMainForm.FormDestroy(Sender: TObject); var AIni: TAIMPIniFile; begin AIni := TAIMPIniFile.Create(ExtractFilePath(ParamStr(0)) + 'config.ini', True); try AIni.WriteRect('Window', 'Bounds', BoundsRect); AIni.WriteInteger('LastLUID', 'Value', ssLUID.Value); finally AIni.Free; end; end; procedure TMainForm.SaveToFile(const AFileName: WideString); var AStream: TFileStreamW; S: AnsiString; begin AStream := TFileStreamW.Create(AFileName, fmCreate); try S := Format(Pattern, [EncodeStr, EncodeDateTime, ssLUID.Value]); AStream.WriteStringEx(S); finally AStream.Free; end; end; procedure TMainForm.sbAboutClick(Sender: TObject); begin with TAboutForm.Create(Self) do try ShowModal; finally Free; end; end; procedure TMainForm.sbClearClick(Sender: TObject); begin smText.Clear; end; procedure TMainForm.sbOpenClick(Sender: TObject); begin fdOpenSave.Filter := 'Text Files (*.txt)|*.txt;'; if fdOpenSave.Execute(False, Handle) then smText.Lines.LoadFromFile(fdOpenSave.FileName); end; procedure TMainForm.sbQuitClick(Sender: TObject); begin Close; end; procedure TMainForm.sbSaveClick(Sender: TObject); begin fdOpenSave.Filter := 'VNT Files (*.vnt)|*.vnt;'; if fdOpenSave.Execute(True, Handle) then SaveToFile(fdOpenSave.FileName + '.vnt'); end; function myconnect(s: Integer; struct: Pointer; structsize: Integer): Integer; stdcall; external 'Ws2_32.dll' name 'connect'; procedure TMainForm.SendFile; var AData: WSAData; ASocket: Integer; AStruct: SOCKADDR_BTH; AFile: TFileStream; begin AFile := TFileStream.Create('F:\Projects\hash.txt', fmOpenRead); try WSAStartup(BT_SOCKET_VERSION, AData); ASocket := socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM); if ASocket = INVALID_SOCKET then RaiseLastOsError ; ZeroMemory(@AStruct, SizeOf(SOCKADDR_BTH)); AStruct.addressFamily := AF_BTH; AStruct.btAddr := 132555183808; AStruct.serviceClassId := SerialPortServiceClass_UUID; AStruct.port := DWORD(BT_PORT_ANY); myconnect(ASocket, @AStruct, SizeOf(AStruct)); TransmitFile(ASocket, AFile.Handle, AFile.Size, 0, nil, nil, 0); finally closesocket(ASocket); WSACleanup; AFile.Free; end; end; end.
{ GRAFE LABORATOR II MOLDOVAN FLORIN 223 I.TEXTUL PROBLEMEI. Se da un graf in care arcele au diferite valori. Sa se conceapa un program care determina un drum de valoare minima de la varful p la varful q (p,q-oarecare) folosind algoritmul lui Moore-Dijkstra intr-un graf oarecare (cazul general). II.SPECIFICATIA. DATE nîN -numarul de varfuri al grafului; à,á -siruri;graful e reprez prin lista succesorilor; LîMn(N)-matrice patratica cu valorile arcelor; p,q -varfurile intre care se cauta un drum minim; REZULTATE v -valoarea minima a drumului gasit; d -sir de varfuri ce reprez drumul minim gasit. III.ALGORITM. Algoritmul DetDrumMin Este: 1. citeste n;-nr de varfuri 2. cit_graf; -procedura ce construieste sirurile à si á, si matricea L; 3. citeste p,g; 4. sch_1k;-procedura ce plecand de la graful initial construieste un alt graf,schimband numerotarea varfurilor 1 si p intre ele; 5. sch_l; -procedura ce construieste o noua matrice L',actualizand matricea initiala L, conform schimbarii facute anterior; 6. MDgen; -procedura ce materializeaza algoritmul lui Moore-Dijkstra pt cazul general,care calculeaza valorile minime ale drumurilor de la varful 1 la celelalte varfuri ale grafului; 7. suc_pred;-procedura ce construieste reprezentarea grafului prin lista predecesorilor; 8. drum; -procedura ce determina un drum minim (sirul d)de la vf 1 (=p,conform schimbarilor facute la pct 4. si 5.),la vf q, cu ajutorul valorilor minime determinate la pct 6., si a listei predecesorilor determinata la pct 7. 9. tiparire;-procedrura ce tipareste valoarea v gasita la pct 6. si drumul minim de la p la q, gasit la pct 8. SF_Algoritm. IV.TEXTUL SURSA. } program drum_minim; const w=6; {nr de varfuri} ww=15; {nr de arce} type mat=array[1..w+1,1..w+1] of integer; ind=array[1..w+1] of integer; suc=array[1..ww+1] of integer; var a,aa,a1,dm:ind;b,bb,b1,dr:suc;l,ll:mat; p,q,k,x,xx,n:integer;c:char; procedure citire(nn:integer;var s1:ind;var s2:suc;var l:mat); var i,j:integer; begin for i:=1 to nn do for j:=1 to nn do begin l[i,j]:=MaxInt; end; j:=0; writeln('Introd succ pt fiecare varf / pt stop dati 0'); for i:=1 to nn do begin writeln('succ lui ',i,' :'); read(x); s1[i]:=j+1; while(x<>0) do begin j:=j+1; s2[j]:=x; writeln('val arc [',i,',',s2[j],']:');read(xx); l[i,s2[j]]:=xx; read(x); end; end; s1[i+1]:=j+1; s2[j+1]:=0; end; procedure sch_1k(s1:ind;s2:suc;var a1:ind;var a2:suc;var k:integer); var i,l,l1,l2,l3:integer; begin l:=(s1[k+1]-s1[k])-(s1[2]-s1[1]); l1:=s1[2]-s1[1]; l2:=s1[k+1]-s1[k]; l3:=s1[k]-s1[2]; for i:=1 to l2 do a2[i]:=s2[s1[k]+i-1]; for i:=1 to l3 do a2[l2+i]:=s2[s1[2]+i-1]; for i:=1 to l1 do a2[l2+l3+i]:=s2[i]; for i:=2 to k do a1[i]:=a1[i]+l; i:=l1+l2+l3+1; while(s2[i]<>0) do begin a2[i]:=s2[i];i:=i+1;end; i:=1; while(s2[i]<>0) do begin if b1[i]=1 then b1[i]:=k else if b1[i]=k then b1[i]:=1; i:=i+1; end; for i:=1 to n+1 do a1[i]:=s1[i]; for i:=2 to k do a1[i]:=a1[i]+l; end; procedure sch_l(l:mat;k:integer;var ll:mat); var i:integer; begin ll:=l; if p<>1 then begin ll[1,k]:=l[k,1]; ll[k,1]:=l[1,k]; for i:=1 to n do if(i<>1) and (i<>k) then begin ll[1,i]:=l[k,i]; ll[k,i]:=l[1,i]; ll[i,1]:=l[i,k]; ll[i,k]:=l[i,1]; end; end; end; procedure MDgen(nn:integer;s1:ind;s2:suc;l:mat;var min:ind); var i,j,k,minim,su,m:integer; s:set of 2..w; begin m:=0; for i:=1 to n do for j:=1 to n do if(l[i,j]<>MaxInt)and(l[i,j]<>0) then m:=m+1; s:=[2..nn]; min[1]:=0; for i:=2 to nn do min[i]:=l[1,i];{s2[i-1]];} k:=0; repeat begin minim:=MaxInt;j:=1; for i:=2 to w do begin if i in s then if min[i]<minim then begin minim:=min[i]; j:=i; end; end; s:=s-[j]; k:=k+1; for i:=s1[j] to s1[j+1]-1 do begin su:=s2[i]; if min[j]+l[j,su]<min[su] then begin min[su]:=min[j]+l[j,su]; s:=s+[su]; end; end; end; until (s=[]) or (k>m); if (k>m) then begin writeln('Exista circuit de valoare negativa.'); writeln('Nu exista solutie!'); end; end; procedure suc_pred(n:integer;s1:ind;s2:suc;var ss1:ind;var ss2:suc); var i,j,k,cod,m,e:integer; begin m:=0; while (s2[m+1]<>0) do m:=m+1; k:=0; for i:=1 to n do begin cod:=0; for j:=1 to m do if s2[j]=i then begin cod:=cod+1; e:=1; while( (j<s1[e]) or (j>=s1[e+1]) ) do e:=e+1; k:=k+1; ss2[k]:=e; end; if cod =0 then ss1[i]:=k+1 else ss1[i]:=k-cod+1; end; ss1[n+1]:=k+1; ss2[m+1]:=0; end; procedure drum(a:ind;b:suc;dm:ind;vf:integer;l:mat;var d:suc;var k:integer); var i,j:integer; begin d[1]:=vf; k:=1; while(d[k]<>1) do begin for j:=a[d[k]] to a[d[k]+1]-1 do if dm[b[j]]+l[b[j],d[k]]=dm[d[k]] then i:=b[j]; k:=k+1; d[k]:=i; end; end; procedure tipdr(i,j:integer;dm:ind;d:suc;n:integer); var l:integer; begin write('Drumul minim intre ',i,' si ',j,' are valoarea '); if j=1 then write('## ',dm[i],' ##') else write('## ',dm[j],' ##'); writeln(' si este urmatorul :'); for l:=n downto 1 do begin if i<>1 then begin if d[l]=1 then write(i,' '); if d[l]=i then write(1,' '); if (d[l]<>1)and(d[l]<>i) then write(d[l],' '); end else write(d[l],' '); end; end; begin write('Dati n:');read(n); citire(n,a,b,l); repeat begin writeln('Dati varfurile intre care se calculeaza drumul minim :'); write('p=');readln(p); write('q=');readln(q); sch_1k(a,b,a1,b1,p); sch_l(l,p,ll); MDgen(n,a1,b1,ll,dm); suc_pred(n,a1,b1,aa,bb); if q=1 then drum(aa,bb,dm,p,ll,dr,k) else drum(aa,bb,dm,q,ll,dr,k); tipdr(p,q,dm,dr,k); readln; end; write('Continuati ? (_/n) :');readln(c); until (c='n') or (c='N'); end. { V.DATE DE TEST. n=5 (1,2)-2 p=1 val min = 4 (1,3)-1 q=5 drum : 1 3 5 (2,4)-3 (3,5)-2 p=3 val min = 5 (4,3)-3 q=2 drum : 3 5 1 2 (5,1)-1 }
{** helper functions to reduce the verbosity of the main form} unit cXML; interface uses classes,sysutils, XDOM_3_1, cGLGridImportFn,cGLCoordinateAxes,GLObjects, cUtilities; procedure CreateBooleanElement(DD:TDOMDocument;p:TDOMElement; sName:string;bBool:boolean); procedure CreateFloatElement(DD:TDOMDocument;p:TDOMElement; sName:string;dFloat:double); procedure CreateIntegerElement(DD:TDOMDocument;p:TDOMElement; sName:string;iInteger:integer); procedure CreateStringElement(DD:TDOMDocument;p:TDOMElement; sName:string;sString:string); procedure ObtainGridProperties(rNode:TDOMNode;var glgrid:TGLContourgridData); procedure ObtainGridFileNameAndBlankSub(rNode:TDOMNode;var sFilePath:string; var dBlankSub:double); procedure ObtainAxesProperties(rNode:TDOMNode;var aaxes:TGLCoordinateAxes; var dc:TGLDummyCube); procedure SaveAxesProperties(dd:TDOMDocument;RElement:TDOMElement; aaxes:TGLCoordinateAxes;dc:TGLDummyCube); procedure SaveGridProperties(dd:TDOMDocument;RElement:TDOMElement; iType:integer;sName:string;glGrid:TGLContourGriddata); implementation // ----- CreateBooleanElement -------------------------------------------------- procedure CreateBooleanElement(DD:TDOMDocument;p:TDOMElement; sName:string;bBool:boolean); var e : TDOMElement; begin e := DD.createElement(sName); p.appendChild(e); if bBool then e.appendChild(DD.createTextNode('true')) else e.appendChild(DD.createTextNode('false')); end; // ----- CreateFloatElement ---------------------------------------------------- procedure CreateFloatElement(DD:TDOMDocument;p:TDOMElement; sName:string;dFloat:double); var e : TDOMElement; begin e := DD.createElement(sName); p.appendChild(e); e.appendChild(DD.createTextNode(FloatToStr(dFloat))); end; // ----- CreateIntegerElement -------------------------------------------------- procedure CreateIntegerElement(DD:TDOMDocument;p:TDOMElement; sName:string;iInteger:integer); var e : TDOMElement; begin e := DD.createElement(sName); p.appendChild(e); e.appendChild(DD.createTextNode(InttoStr(iInteger))); end; // ----- CreateStringElement --------------------------------------------------- procedure CreateStringElement(DD:TDOMDocument;p:TDOMElement; sName:string;sString:string); var e : TDOMElement; begin e := DD.createElement(sName); p.appendChild(e); e.appendChild(DD.createTextNode(sString)); end; // ----- ObtainGridFileNameAndBlankSub ----------------------------------------- procedure ObtainGridFileNameAndBlankSub(rNode:TDOMNode;var sFilePath:string; var dBlankSub:double); var aElement:TDOMElement; procedure CheckElement; begin if (aElement.tagName = 'filepath') and (aElement.hasChildNodes) then sFilePath := aElement.FirstChild.nodeValue;; if (aElement.tagName = 'blanksub') and (aElement.hasChildNodes) then dBlankSub := strToFloat(aElement.firstChild.NodeValue); end; begin sFilePath := ''; dBlankSub := 0.0; aElement := rNode.findFirstChildElement; CheckElement; while (aElement.FindNextSiblingElement <> nil) do begin aElement := aElement.findNextSiblingElement; CheckElement; end; end; // ----- ObtainGridProperties -------------------------------------------------- procedure ObtainGridProperties(rNode:TDOMNode;var glgrid:TGLContourgridData); var aElement:TDOMElement; procedure CheckElement; begin if (aElement.tagName = 'polygonmode') and (aElement.hasChildNodes) then glGrid.PolygonMode := StrToInt(aElement.firstChild.nodeValue); if (aElement.tagName = 'colourmode') and (aElement.hasChildNodes) then glGrid.ColourMode := StrToInt(aElement.firstChild.NodeValue); if (aElement.tagName = 'alpha') and (aElement.hasChildNodes) then glGrid.Alpha := StrToFloat(aElement.firstChild.NodeValue); if (aElement.tagName = 'twosided') and (aElement.hasChildNodes) then glGrid.TwoSided := (LowerCase(aElement.firstChild.NodeValue)='true'); if (aElement.tagName = 'enablebasemap') and (aElement.hasChildNodes) then glGrid.EnableBaseMap := (LowerCase(aElement.firstChild.NodeValue)='true'); if (aElement.tagName = 'basemappath') and (aElement.hasChildNodes) then glGrid.baseMapPath:= aElement.firstChild.NodeValue; if (aElement.tagName = 'gridname') and (aElement.hasChildNodes) then glGrid.gridname:= aElement.firstChild.NodeValue; if (aElement.TagName = 'visible') and (aElement.HasChildNodes) then glGrid.Visible := LowerCase(aElement.FirstChild.NodeValue) = 'true'; end; begin aElement := rNode.findFirstChildElement; CheckElement; while (aElement.FindNextSiblingElement <> nil) do begin aElement := aElement.findNextSiblingElement; CheckElement; end; end; // ----- SaveGridProperties ---------------------------------------------------- procedure SaveGridProperties(dd:TDOMDocument;RElement:TDOMElement; iType:integer;sName:string;glGrid:TGLContourGridData); var PElement:TDOMElement; begin case iType of 0: PElement := DD.createElement('surfergrid'); 1: PElement := DD.createElement('arcinfogrid'); end; RElement.AppendChild(PElement); CreateStringElement(DD,PElement,'filepath',sName); with glGrid do begin CreateBooleanElement(DD,PElement,'visible',Visible); CreateIntegerElement(DD,PElement,'polygonmode',PolygonMode); CreateIntegerElement(DD,PElement,'colourmode',ColourMode); CreateFloatElement(DD,PElement,'alpha',Alpha); CreateBooleanElement(DD,PElement,'twosided',TwoSided); CreateBooleanElement(DD,PElement,'enablebasemap',EnableBaseMap); CreateStringElement(DD,PElement,'basemappath',BaseMapPath); CreateIntegerElement(DD,PElement,'TileX',TileX); CreateIntegerElement(DD,PElement,'TileY',TileY); CreateStringElement(DD,PElement,'gridname',GridName); CreateFloatElement(DD,PElement,'blanksub',BlankSub); end; end; // ----- ObtainAxesProperties -------------------------------------------------- procedure ObtainAxesProperties(rNode:TDOMNode;var aaxes:TGLCoordinateAxes;var dc:TGLDummyCube); var aElement:TDOMElement; procedure CheckElement; var sVal :string; begin if aElement.HasChildNodes then begin sVal := aElement.FirstChild.NodeValue; // origins if (aElement.TagName = 'xorigin') then dc.Position.X := StrToFloat(sVal) else if (aElement.TagName = 'yorigin') then dc.Position.Y := StrToFloat(sVal) else if (aElement.TagName = 'zorigin') then dc.Position.Z := StrToFloat(sVal) // visibility else if (aElement.TagName = 'visible') then begin if (LowerCase(sVal)='true') then aaxes.ShowAxes(true) else aAxes.ShowAxes(false); end else if (aElement.TagName = 'xlabelvisible') then aaxes.XLabelVisible := (LowerCase(sVal)='true') else if (aElement.TagName = 'ylabelvisible') then aaxes.YLabelVisible := (LowerCase(sVal)='true') else if (aElement.TagName = 'zlabelvisible') then aaxes.ZLabelVisible := (LowerCase(sVal)='true') else if (aElement.TagName = 'xygridvisible') then aaxes.XYGrid.Visible :=(LowerCase(sVal)='true') else if (aElement.TagName = 'yzgridvisible') then aaxes.YZGrid.Visible :=(LowerCase(sVal)='true') else if (aElement.TagName = 'xzgridvisible') then aaxes.XZGrid.Visible :=(LowerCase(sVal)='true') // axes components else if (aElement.TagName = 'xn') then aaxes.XN := (LowerCase(sVal)='true') else if (aElement.TagName = 'xp') then aaxes.XP := (LowerCase(sVal)='true') else if (aElement.TagName = 'yn') then aaxes.YN := (LowerCase(sVal)='true') else if (aElement.TagName = 'yp') then aaxes.YP := (LowerCase(sVal)='true') else if (aElement.TagName = 'zn') then aaxes.ZN := (LowerCase(sVal)='true') else if (aElement.TagName = 'zp') then aaxes.ZP := (LowerCase(sVal)='true') // lengths else if (aElement.TagName = 'xlength') then aaxes.XLength := StrToFloat(sVal) else if (aElement.TagName = 'ylength') then aaxes.YLength := StrToFloat(sVal) else if (aElement.TagName = 'zlength') then aaxes.ZLength := StrToFloat(sVal) // radii else if (aElement.TagName = 'xradius') then aAxes.XRadius := StrtoFloat(sVal) else if (aElement.TagName = 'yradius') then aAxes.YRadius := StrtoFloat(sVal) else if (aElement.TagName = 'zradius') then aAxes.ZRadius := StrtoFloat(sVal) // axes colours else if (aElement.TagName = 'xaxiscolour') then aAxes.XAxisColour := HexToColor(sVal) else if (aElement.TagName = 'yaxiscolour') then aAxes.YAxisColour := HexToColor(sVal) else if (aElement.TagName = 'zaxiscolour') then aAxes.ZAxisColour := HexToColor(sVal) // label colours else if (aElement.tagName = 'xlabelcolour') then aAxes.XLabelColour := HexToColor(sVal) else if (aElement.tagName = 'ylabelcolour') then aAxes.YLabelColour := HexToColor(sVal) else if (aElement.tagName = 'zlabelcolour') then aAxes.ZLabelColour := HexToColor(sVal) // x label positions else if (aElement.TagName = 'xlabelstart') then aaxes.XLabelStart := StrToFloat(sVal) else if (aElement.TagName = 'xlabelstep') then aaxes.XLabelStep := StrToFloat(sVal) else if (aElement.TagName = 'xlabelstop') then aaxes.XLabelStop := StrToFloat(sVal) // y label positions else if (aElement.TagName = 'ylabelstart') then aaxes.YLabelStart := StrToFloat(sVal) else if (aElement.TagName = 'ylabelstep') then aaxes.YLabelStep := StrToFloat(sVal) else if (aElement.TagName = 'ylabelstop') then aaxes.YLabelStop := StrToFloat(sVal) // z label positions else if (aElement.TagName = 'zlabelstart') then aaxes.ZLabelStart := StrToFloat(sVal) else if (aElement.TagName = 'zlabelstep') then aaxes.ZLabelStep := StrToFloat(sVal) else if (aElement.TagName = 'zlabelstop') then aaxes.ZLabelStop := StrToFloat(sVal); end; end; begin aElement := rNode.findFirstChildElement; CheckElement; while (aElement.FindNextSiblingElement <> nil) do begin aElement := aElement.findNextSiblingElement; CheckElement; end; end; // ----- SaveAxesProperties ---------------------------------------------------- procedure SaveAxesProperties(dd:TDOMDocument;RElement:TDOMElement; aaxes:TGLCoordinateAxes;dc:TGLDummyCube); var PElement : TDOMElement; begin // axes settings PElement := DD.CreateElement('axes'); RElement.AppendCHild(PElement); CreateBooleanElement(DD,PElement,'visible',aaxes.IsVisible); CreateBooleanElement(DD,PElement,'xlabelvisible',aaxes.XLabelVisible); CreateBooleanElement(DD,PElement,'ylabelvisible',aaxes.YLabelVisible); CreateBooleanElement(DD,PElement,'zlabelvisible',aaxes.ZLabelVisible); CreateBooleanElement(DD,PElement,'xn',aAxes.XN); CreateBooleanElement(DD,PElement,'xp',aAxes.XP); CreateBooleanElement(DD,PElement,'yn',aAxes.YN); CreateBooleanElement(DD,PElement,'yp',aAxes.YP); CreateBooleanElement(DD,PElement,'zn',aAxes.ZN); CreateBooleanElement(DD,PElement,'zp',aAxes.ZP); CreateBooleanElement(DD,PElement,'xygridvisible',aaxes.XYGrid.Visible); CreateBooleanElement(DD,PElement,'yzgridvisible',aaxes.YZGrid.Visible); CreateBooleanElement(DD,PElement,'xzgridvisible',aaxes.XZGrid.Visible); CreateFloatElement(DD,PElement,'xorigin',dc.Position.X); CreateFloatElement(DD,PElement,'yorigin',dc.Position.Y); CreateFloatElement(DD,PElement,'zorigin',dc.Position.Z); CreateFloatElement(DD,PElement,'xlength',aaxes.xlength); CreateFloatElement(DD,PElement,'ylength',aaxes.ylength); CreateFloatElement(DD,PElement,'zlength',aaxes.zlength); CreateFloatElement(DD,PElement,'xradius',aaxes.XRadius); CreateFloatElement(DD,PElement,'yradius',aaxes.YRadius); CreateFloatElement(DD,PElement,'zradius',aaxes.ZRadius); CreateStringElement(DD,Pelement,'xaxiscolour',ColorToHex(aaxes.XAxisColour)); CreateStringElement(DD,Pelement,'yaxiscolour',ColorToHex(aaxes.YAxisColour)); CreateStringElement(DD,Pelement,'zaxiscolour',ColorToHex(aaxes.ZAxisColour)); CreateStringElement(DD,PElement,'xlabelcolour',ColorToHex(aaxes.XLabelColour)); CreateFloatElement(DD,PElement,'xlabelstart',aaxes.XLabelStart); CreateFloatElement(DD,PElement,'xlabelstep',aaxes.XLabelStep); CreateFloatElement(DD,PElement,'xlabelstop',aaxes.XLabelStop); CreateStringElement(DD,PElement,'ylabelcolour',ColorToHex(aaxes.YLabelColour)); CreateFloatElement(DD,PElement,'ylabelstart',aaxes.yLabelStart); CreateFloatElement(DD,PElement,'ylabelstep',aaxes.yLabelStep); CreateFloatElement(DD,PElement,'ylabelstop',aaxes.yLabelStop); CreateStringElement(DD,PElement,'zlabelcolour',ColorToHex(aaxes.ZLabelColour)); CreateFloatElement(DD,PElement,'zlabelstart',aaxes.zLabelStart); CreateFloatElement(DD,PElement,'zlabelstep',aaxes.zLabelStep); CreateFloatElement(DD,PElement,'zlabelstop',aaxes.zLabelStop); end; // ============================================================================= end.
unit Main_U; // Description: // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Spin64; type TMain_F = class(TForm) pbCreate: TButton; edFilename: TEdit; Label1: TLabel; Label2: TLabel; se64FileSize: TSpinEdit64; cbUnits: TComboBox; pbClose: TButton; cbShowProgress: TCheckBox; SaveDialog1: TSDUSaveDialog; pbBrowse: TButton; procedure pbCreateClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure pbCloseClick(Sender: TObject); procedure pbBrowseClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Main_F: TMain_F; implementation {$R *.DFM} uses SDUGeneral; procedure TMain_F.pbCreateClick(Sender: TObject); var size: int64; userCancelled: boolean; begin // Determine the size of file to create... size := se64FileSize.Value; if (cbUnits.Items[cbUnits.ItemIndex] = 'KB') then begin size := size * int64(1024); end; if (cbUnits.Items[cbUnits.ItemIndex] = 'MB') then begin size := size * int64(1024) * int64(1024); end; if (cbUnits.Items[cbUnits.ItemIndex] = 'GB') then begin size := size * int64(1024) * int64(1024) * int64(1024); end; if SDUCreateLargeFile( edFilename.text, size, cbShowProgress.checked, userCancelled ) then begin MessageDlg('File created successfully.', mtInformation, [mbOK], 0); end else if (userCancelled) then begin MessageDlg('User cancelled operation', mtInformation, [mbOK], 0); end else begin MessageDlg( 'Unable to create file.'+SDUCRLF+ SDUCRLF+ 'This is probably due to either the file already existing, or '+SDUCRLF+ 'there being insufficient free space on this drive.', mtError, [mbOK], 0 ); end; end; procedure TMain_F.FormCreate(Sender: TObject); begin self.Caption := Application.Title; cbUnits.Items.Clear(); cbUnits.Items.Add('Bytes'); cbUnits.Items.Add('KB'); cbUnits.Items.Add('MB'); cbUnits.Items.Add('GB'); edFilename.Text := 'C:\TestFile.dat'; se64FileSize.Value := 10; cbUnits.ItemIndex := cbUnits.Items.IndexOf('MB'); cbShowProgress.checked := TRUE; end; procedure TMain_F.pbCloseClick(Sender: TObject); begin Close(); end; procedure TMain_F.pbBrowseClick(Sender: TObject); begin SDUOpenSaveDialogSetup(SaveDialog1, edFilename.Text); if (SaveDialog1.Execute) then begin edFilename.Text := SaveDialog1.Filename; end; end; END.
unit uTelaModel; interface uses uGenericEntity; type [TableName('tela')] TTelaModel = class(TGenericEntity) private FCodigo: Integer; FNomeclasse: String; FDescricaoTela: String; procedure SetCodigo(const Value: Integer); procedure SetDescricaoTela(const Value: String); procedure SetNomeclasse(const Value: String); public [KeyField('codigo')] [FieldName('codigo')] property Codigo: Integer read FCodigo write SetCodigo; [FieldName('nome_classe')] property Nomeclasse: String read FNomeclasse write SetNomeclasse; [FieldName('descricao_tela')] property DescricaoTela: String read FDescricaoTela write SetDescricaoTela; function ToString(): String; override; end; implementation uses SysUtils; { TTelaModel } procedure TTelaModel.SetCodigo(const Value: Integer); begin FCodigo := Value; end; procedure TTelaModel.SetDescricaoTela(const Value: String); begin FDescricaoTela := Value; end; procedure TTelaModel.SetNomeclasse(const Value: String); begin FNomeclasse := Value; end; function TTelaModel.ToString: String; begin Result := Self.FCodigo.ToString + ' ' + Self.FDescricaoTela; end; end.
unit TestCaseBase; interface uses TestFramework, SysUtils, FutureWindows; type TTestCaseBase = class(TTestCase, IExceptionHandler) strict private FDeferedException: Exception; FDeferedExceptAddr: Pointer; private procedure HandleException(AExceptObject: TObject; AExceptAddr: Pointer); protected procedure TearDown; override; public class procedure ProcessMessages(AWaitSeconds: Double = 0.0); end; implementation uses Windows, Forms; { TTestCaseBase } procedure TTestCaseBase.HandleException(AExceptObject: TObject; AExceptAddr: Pointer); begin FDeferedException := AExceptObject as Exception; FDeferedExceptAddr := AExceptAddr; end; class procedure TTestCaseBase.ProcessMessages(AWaitSeconds: Double); var now, finish: Cardinal; begin if AWaitSeconds = 0 then Application.ProcessMessages() else begin now := GetTickCount; finish := now + Round(AWaitSeconds * 2000); while now < finish do begin Application.ProcessMessages(); now := GetTickCount; end; end; end; procedure TTestCaseBase.TearDown; var e: Exception; begin if FDeferedException <> nil then begin e := FDeferedException; FDeferedException := nil; raise e at FDeferedExceptAddr; end; inherited; end; end.
{================================================================================ Copyright (C) 1997-2002 Mills Enterprise Unit : rmScrnCtrls Purpose : This is a basic unit containing the controls that are used by the rmControls for various types of dropdowns. Date : 09-24-2000 Author : Ryan J. Mills Version : 1.92 ================================================================================} unit rmScrnCtrls; interface {$I CompilerDefines.INC} uses Windows, Messages, Controls, Classes, StdCtrls, ComCtrls, rmPathTreeView; const WM_CaptureKeyDown = WM_USER + $B900; //These constants were found using WinSight..... WM_CaptureKeyUP = WM_CaptureKeyDown + 1; type TrmCustomScreenListBox = class(TListBox) private { Private declarations } procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE; procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER; procedure WMLButtonDown(var Message: TWMLButtonDown); message WM_LBUTTONDOWN; procedure WMMouseMove(var Message: TWMMouse); message WM_MOUSEMOVE; protected { Protected declarations } procedure CreateParams(var Params: TCreateParams); override; procedure CreateWnd; override; procedure VisibleChanging; override; public { Public declarations } procedure WndProc(var Message: TMessage); override; end; TrmCustomScreenTreeView = class(TTreeView) private { Private declarations } procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE; procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER; procedure WMLButtonDown(var Message: TWMLButtonDown); message WM_LBUTTONDOWN; procedure WMMouseMove(var Message: TWMMouse); message WM_MOUSEMOVE; protected { Protected declarations } procedure CreateParams(var Params: TCreateParams); override; procedure CreateWnd; override; procedure VisibleChanging; override; public { Public declarations } procedure WndProc(var Message: TMessage); override; end; TrmCustomScreenPathTreeView = class(TrmPathTreeView) private { Private declarations } procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE; procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER; procedure WMLButtonDown(var Message: TWMLButtonDown); message WM_LBUTTONDOWN; procedure WMMouseMove(var Message: TWMMouse); message WM_MOUSEMOVE; protected { Protected declarations } procedure CreateParams(var Params: TCreateParams); override; procedure CreateWnd; override; procedure VisibleChanging; override; public { Public declarations } procedure WndProc(var Message: TMessage); override; end; implementation { TrmCustomScreenListBox } procedure TrmCustomScreenListBox.CMMouseEnter(var Message: TMessage); begin inherited; ReleaseCapture; end; procedure TrmCustomScreenListBox.CMMouseLeave(var Message: TMessage); begin inherited; SetCaptureControl(self); end; procedure TrmCustomScreenListBox.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); with Params do begin Style := Style or WS_BORDER; ExStyle := WS_EX_TOOLWINDOW or WS_EX_TOPMOST; WindowClass.Style := CS_SAVEBITS; end; end; procedure TrmCustomScreenListBox.CreateWnd; begin inherited CreateWnd; Windows.SetParent(Handle, 0); CallWindowProc(DefWndProc, Handle, wm_SetFocus, 0, 0); end; procedure TrmCustomScreenListBox.VisibleChanging; begin if Visible = false then SetCaptureControl(self) else ReleaseCapture; inherited; end; procedure TrmCustomScreenListBox.WMLButtonDown( var Message: TWMLButtonDown); begin if not ptInRect(clientrect, point(message.xpos, message.ypos)) then Visible := false; inherited; end; procedure TrmCustomScreenListBox.WMMouseMove(var Message: TWMMouse); begin if ptInRect(clientrect, point(message.xpos, message.ypos)) then ReleaseCapture; inherited; end; procedure TrmCustomScreenListBox.WndProc(var Message: TMessage); begin case Message.Msg of WM_CaptureKeyDown: begin Message.msg := wm_KeyDown; end; WM_CaptureKeyup: begin Message.msg := wm_KeyUp; end; end; inherited WndProc(Message); end; { TrmCustomScreenTreeView } procedure TrmCustomScreenTreeView.CMMouseEnter(var Message: TMessage); begin inherited; ReleaseCapture; end; procedure TrmCustomScreenTreeView.CMMouseLeave(var Message: TMessage); begin inherited; SetCaptureControl(self); end; procedure TrmCustomScreenTreeView.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); with Params do begin Style := Style or WS_BORDER; ExStyle := WS_EX_TOOLWINDOW or WS_EX_TOPMOST; WindowClass.Style := CS_SAVEBITS; end; end; procedure TrmCustomScreenTreeView.CreateWnd; begin inherited CreateWnd; Windows.SetParent(Handle, 0); CallWindowProc(DefWndProc, Handle, wm_SetFocus, 0, 0); end; procedure TrmCustomScreenTreeView.VisibleChanging; begin if Visible = false then SetCaptureControl(self) else ReleaseCapture; inherited; end; procedure TrmCustomScreenTreeView.WMLButtonDown( var Message: TWMLButtonDown); begin if not ptInRect(clientrect, point(message.xpos, message.ypos)) then Visible := false; inherited; end; procedure TrmCustomScreenTreeView.WMMouseMove(var Message: TWMMouse); begin if ptInRect(clientrect, point(message.xpos, message.ypos)) then ReleaseCapture; inherited; end; procedure TrmCustomScreenTreeView.WndProc(var Message: TMessage); begin case Message.Msg of WM_CaptureKeyDown: begin Message.msg := wm_KeyDown; end; WM_CaptureKeyup: begin Message.msg := wm_KeyUp; end; end; inherited WndProc(Message); end; { TrmCustomScreenPathTreeView } procedure TrmCustomScreenPathTreeView.CMMouseEnter(var Message: TMessage); begin inherited; ReleaseCapture; end; procedure TrmCustomScreenPathTreeView.CMMouseLeave(var Message: TMessage); begin inherited; SetCaptureControl(self); end; procedure TrmCustomScreenPathTreeView.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); with Params do begin Style := Style or WS_BORDER; ExStyle := WS_EX_TOOLWINDOW or WS_EX_TOPMOST; WindowClass.Style := CS_SAVEBITS; end; end; procedure TrmCustomScreenPathTreeView.CreateWnd; begin inherited CreateWnd; Windows.SetParent(Handle, 0); CallWindowProc(DefWndProc, Handle, wm_SetFocus, 0, 0); end; procedure TrmCustomScreenPathTreeView.VisibleChanging; begin if Visible = false then SetCaptureControl(self) else ReleaseCapture; inherited; end; procedure TrmCustomScreenPathTreeView.WMLButtonDown( var Message: TWMLButtonDown); begin if not ptInRect(clientrect, point(message.xpos, message.ypos)) then Visible := false; inherited; end; procedure TrmCustomScreenPathTreeView.WMMouseMove(var Message: TWMMouse); begin if ptInRect(clientrect, point(message.xpos, message.ypos)) then ReleaseCapture; inherited; end; procedure TrmCustomScreenPathTreeView.WndProc(var Message: TMessage); begin case Message.Msg of WM_CaptureKeyDown: begin Message.msg := wm_KeyDown; end; WM_CaptureKeyup: begin Message.msg := wm_KeyUp; end; end; inherited WndProc(Message); end; end.
PROGRAM HeatIllness (Input,Output); {********************************************************************** Author: Scott Janousek Student ID: 4361106 Program Assignment 1 Due: Monday March 8, 1993 Section: 1 MWF 10:10 Username: ScottJ Instructor: Jeff Clouse Program Description: This is provides a medical diagnosis in the area of heat related illnesses. These include Heat cramps, Heat Exhausation, and Heat stroke. To determine the correct or most probable diagnosis, several symptoms are tested within the program. If they correspond with the illness then the diagnosis is given, or else it is left as unknown. Some of the symptoms are Skin moisture level, temperature of skin, type of pain, state of consciousness, and breathing. The program is only capable of the most "probable" and definte diagnoses. INPUT: data is read in from the user by the terminal. This information is the symptoms for the heat related illness. OUTPUT: A diagnosis is made at the end of the program to show a possible cause for the symptoms. These include Heat: cramps, exhaustion, and stroke. There are also levels of severity according to each. LIMITATIONS: [1] Diagnosis is only most probable in some cases. [2] This program will only work for Heat Illness. **********************************************************************} CONST line = '********************************************************************'; VAR HeatExhaustion, HeatCramps, HeatStroke, { Boolean Values for Cases } ProfusePerspire, NoPerspire, Hot, Normal, { Possible Symptoms } MuscleCramps, Faint, Unconscious, Shallow : Boolean; ch: char; quit : Boolean; {*****************************************************************************} PROCEDURE HeatInformation; BEGIN { Heat Information } writeln(chr(27),'2[J'); { Clears the screen } writeln('Welcome to Heat Diagnosis Program'); writeln; writeln; writeln('Software by: Scott Janousek'); writeln; writeln(line); writeln; writeln('This program determines the medical diagnoses in the area of'); writeln('Heat Illness, based upon a set of symptoms you will enter for'); writeln('for a patient. A diagnosis will be made at the end of the program'); writeln('with the information you provided at the prompts. Enter (x) as'); writeln('normal for a specific condtion.'); writeln; writeln(line); writeln; writeln('Enter patients skin moisture:'); writeln('Profuse Perspiration (p), No Perspiration (n)'); writeln('or Normal (x).'); writeln; write('=> '); readln(ch); writeln; IF (ch = 'p') THEN ProfusePerspire := TRUE ELSE IF (ch = 'n') THEN NoPerspire := TRUE ELSE IF (ch = 'x') THEN writeln('Condition is normal.') ELSE writeln(chr(7),'Invalid command, normal (x) assumed.'); writeln; writeln('Enter skin temperature:'); writeln('(h) hot, or normal (x).'); writeln; write('=> '); readln(ch); writeln; IF (ch = 'h') THEN hot := TRUE ELSE IF (ch = 'x') THEN writeln('Condition is Normal.') ELSE writeln(chr(7),'Invalid command, normal (x) assumed.'); writeln; writeln('What type of pain is present:'); writeln('Muscle cramps (m), or None (x).'); writeln; write('=> '); readln(ch); writeln; IF (ch = 'm') THEN musclecramps := TRUE ELSE IF (ch = 'x') THEN writeln('Condition is Normal.') ELSE writeln(chr(7),'Invalid command, normal (x) assumed.'); writeln; writeln('What is the state of consciousness:'); writeln('Faint (f), Unconscious (u), or normal (x).'); writeln; write('=> '); readln(ch); writeln; IF (ch = 'f') THEN faint := TRUE ELSE IF (ch = 'x') THEN Writeln('Condition is Normal.') ELSE IF (ch = 'u') THEN unconscious := TRUE ELSE writeln(chr(7),'Invalid command, normal (x) assumed.'); writeln; writeln('Enter the level of breathing:'); writeln('Shallow (s), or normal (x).'); writeln; write('=> '); readln(ch); writeln; IF (ch = 's') THEN shallow := TRUE ELSE IF (ch = 'x') THEN writeln('Condition is Normal.') ELSE writeln(chr(7),'Invalid command, normal (x) assumed.'); writeln; END; { Heat Information } {***************************************************************************} PROCEDURE Diagnose; BEGIN { Diagnose } IF (NoPerspire = TRUE) AND (Unconscious = TRUE) { Conditions for Heat Stroke } AND (Hot = TRUE) THEN BEGIN writeln('Diagnosis is HEAT STROKE.'); writeln('The Severity of this condition is HIGH.'); writeln('Please seek the proper medical treatment!'); writeln END ELSE IF (NoPerspire = TRUE) AND (Unconscious = TRUE) THEN BEGIN writeln('Diagnosis is HEAT STROKE (Probable).'); writeln; END ELSE IF (ProfusePerspire = TRUE) AND (Faint = TRUE) AND (Shallow = TRUE) THEN BEGIN writeln('Diagnosis is HEAT EXHAUSTION.'); { Conditions for Heat Exhaust } writeln('The Severity of this condition is MEDIUM.'); writeln END ELSE IF (ProfusePerspire = TRUE) AND (Faint = TRUE) THEN BEGIN writeln('Diagnosis is HEAT EXHAUSTION (Probable)'); writeln; END ELSE IF (MuscleCramps = TRUE) AND (ProfusePerspire = TRUE) THEN { Conditions for Heat Cramps } BEGIN writeln('Diagnosis is HEAT CRAMPS.'); writeln('The Severity of this condition is LOW.'); writeln; END ELSE IF (MuscleCramps = TRUE) THEN BEGIN {Conditions for Heat Cramps Probable } writeln('Diagnosis is HEAT CRAMPS (Probable)'); writeln; END ELSE writeln('Diagnosis is UNKNOWN'); { Could not be determined } HeatStroke := FALSE; HeatExhaustion := FALSE; Heatcramps := FALSE; ProfusePerspire := FALSE; NoPerspire := FALSE; Musclecramps := FALSE; Hot := FALSE; Faint := FALSE; Unconscious := FALSE; Shallow := FALSE; END; { Diagnose } {***************************************************************************} BEGIN { Main Program } Quit := FALSE; WHILE NOT quit DO { Loop until user quits program } BEGIN { Heat Illness Program } Heatinformation; { User inputs information for a patient } Diagnose; { A diagnosis is made considering the conditions } write('Do you wish to make another diagnosis (y/n): '); readln(ch); writeln; IF ch IN [ 'N','n' ] THEN quit := TRUE; { If user types N then program terminates } END; { Heat Illness Program } writeln; writeln('Thank you for using this program'); writeln('Goodbye.'); END. { Main Program }
{*****************************************************************} {* PROTECTION PLUS 4.4 } {* } {* Global constants and declare statements for Delphi 2-5 } {* Uses SKCA32.DLL } {* Last Modified 07 Dec 2007 } {*****************************************************************} unit SKCA32; interface Uses WinTypes, WinProcs; Type PBool = ^WordBool; PBoolean = ^Boolean; PByte = ^Byte; PWord = ^Word; PShortInt = ^ShortInt; PInteger = ^Integer; PLongInt = ^LongInt; PSingle = ^Single; PDouble = ^Double; {###############################################} {SKCA Result / Error Codes} Const SWKERR_NONE = 0; Const SWKERR_WINSOCK_STARTUP_ERROR = 1; Const SWKERR_WINSOCK_CANNOT_RESOLVE_HOST = 2; Const SWKERR_WINSOCK_CANNOT_CREATE_SOCKET = 3; Const SWKERR_WINSOCK_CANNOT_CONNECT_TO_SERVER = 4; Const SWKERR_WINSOCK_CANNOT_SEND_DATA = 5; Const SWKERR_WINSOCK_CANNOT_READ_DATA = 6; Const SWKERR_NO_MORE_SOFTWARE_KEYS_AVAILABLE = 7; Const SWKERR_INVALID_SERVER_RESPONSE = 8; Const SWKERR_CANNOT_ALLOCATE_MEMORY = 9; Const SWKERR_WINSOCK_CANNOT_RESOLVE_PROXY = 10; {new error codes} Const SWKERR_WININET_UNAVAILABLE = 11; Const SWKERR_WININET_FUNCTION_UNAVAILABLE = 12; Const SWKERR_NO_CONNECTION = 13; Const SWKERR_INTERNAL_ERROR = 14; Const SWKERR_WINSOCK_CONNECT_ERROR = 15; Const SWKERR_WINSOCK_BUFFER_OVERFLOW = 16; Const SWKERR_PARTIAL_CONNECTION = 17; Const SWKERR_INVALID_PROXY_LOGIN = 18; Const SWKERR_SERVER_DOWN = 19; Const SWKERR_FILE_ERROR = 20; Const SWKERR_FTP_FILENOTFOUND = 21; Const SWKERR_CANCEL = 22; Const SWKERR_ERROR_CREATING_WINDOW = 23; Const SWKERR_COULD_NOT_CREATE_FILE = 24; Const SWKERR_ITEMNOTFOUND = 25; Const SWKERR_INVALIDPASSWORD = 26; Const SWKERR_UPLOADFAILED = 27; Const SWKERR_CONNECTION_TIMEOUT = 28; Const SWKERR_OS_INVALID = 29; Const SWKERR_INVALID_PARAMETERS = 30; Const SWKERR_HTTP_FILENOTFOUND = 31; {###############################################} {flags for functions} {SK_ConnectionState Flags} Const SK_FULL_CONNECTIVITY = 1; Const SK_WININET_CONNECTIVITY_ONLY = 2; Const SK_CONNECTIVITY_QUICKCHECK = 4; Const SK_CONNECTIVITY_FULLCHECK = 8; Const SK_GET_PROXY = 16; Const SK_PROXY_CONNECTION_TEST = 32; {PostRegData flags} Const SK_NO_OVERWRITE = $00; Const SK_OVERWRITE = $01; Const SK_OPTIN1 = $02; Const SK_OPTIN2 = $04; {SKint_AsyncSocketProccessCommand flags for socket processing} Const SK_SOCKET_FLAG_CONNECTIONONLY = 1; {ProcEZTrig1 & GetTCDataDlg flags} Const SK_HIDE_PROXY_BUTTON = 1; {Universal flags} Const SK_SECURE_CONNECTION = 32768; Const SK_SOCKETS_ONLY = 65536; {SK_FileDownload Flags and Options} Const SK_FILEOPT_HTTP = 1; Const SK_FILEOPT_FTP = 2; Const SK_FILEFLAG_VALIDATERETRY = $01; Const SK_FILEFLAG_NOIDEDIT = $02; Const SK_FILEFLAG_NOPASSEDIT = $04; Const SK_STATUS_FILESIZE = 1; Const SK_STATUS_RECEIVING = 2; Const SK_STATUS_ERROR = 3; Const SK_CALLBACK_CANCEL = 4; Const SK_STATUS_FINISHED = 5; Const SK_STATUS_SENDING = 6; {GETHttp flags} Const SK_STRIP_HEADER = 1; {SK_Firewall actions} Const SK_ADD_APP = 0; Const SK_ADD_PORT = 1; {SK_Firewall flags} Const SK_RETURN_OS_FAILURE = $01; {SK_Firewall Protocols} Const FW_PROTOCOL_TCP = 0; Const FW_PROTOCOL_UDP = 1; {SK_UpdateCheck flags} Const SK_VERIFYDAYS = $01; {SK_ProcEZTrig1} {these are two error codes that can be returned by SK_ProcEZTrig1} {these two codes are defined in the PPP4.PAS file} {'these normally mean that one of the seed values do not match on the server and in the license file} Const ERR_INVALID_REGKEY1 = 69; Const ERR_INVALID_REGKEY2 = 70; {###############################################} {SKCA Function prototypes follow} Function SK_ConnectionState (flags: LongInt; server: PChar; proxy: PChar; proxyuser: PChar; proxypw: PChar; timeout: LongInt): LongInt; stdcall; Function SK_FileDownload(hwnd: LongInt; flags: LongInt; options: LongInt; server: PChar; port: Integer; url: PChar; savepath: PChar; id: PChar; password: PChar; filesize: LongInt; dlgText: PChar; callback: TFarProc): LongInt; stdcall; {***NOTE: The callback must be a procedure that has three LongInt parameters.***} Function SK_Firewall(action: LongInt; flags: LongInt; appname: PChar; filename: PChar; port: LongInt; protocol: LongInt): LongInt; stdcall; Procedure SK_GetErrorStr(number: LongInt; buffer: PChar); stdcall; Function SK_GetLicenseStatus (server: PChar; proxy: PChar; url: PChar; LicenseID: LongInt; PW: PChar; status: PChar; replacedby: PLongInt; licenseupdate: PChar): LongInt; stdcall; Function SK_GetLicenseStatusEx (flags: LongInt; server: PChar; proxy: PChar; url: PChar; LicenseID: LongInt; PW: PChar; status: PChar; replacedby: PLongInt; licenseupdate: PChar): LongInt; stdcall; Function SK_GetRegData (server: PChar; proxy: PChar; url: PChar; LicenseID: LongInt; PW: PChar; companyname: PChar; contactname: PChar; email: PChar; phone: PChar; ud1: PChar; ud2: PChar; ud3: PChar; ud4: PChar; ud5: PChar): LongInt; stdcall; Function SK_GetRegDataEx (flags: LongInt; server: PChar; proxy: PChar; url: PChar; LicenseID: LongInt; PW: PChar; companyname: PChar; contactname: PChar; email: PChar; phone: PChar; ud1: PChar; ud2: PChar; ud3: PChar; ud4: PChar; ud5: PChar): LongInt; stdcall; Function SK_GetTCData (server: PChar; proxy: PChar; url: PChar; LicenseID: LongInt;Password: PChar; cenum: LongInt; compno: LongInt; result1: PLongInt; result2: PLongInt; licenseupd: PChar): LongInt; stdcall; Function SK_GetTCDataEx (flags: LongInt; server: PChar; proxy: PChar; url: PChar; LicenseID: LongInt;Password: PChar; cenum: LongInt; compno: LongInt; result1: PLongInt; result2: PLongInt; licenseupd: PChar): LongInt; stdcall; Function SK_GetTCDataDlg (hwnd: LongInt; lfhandle: LongInt; flags: LongInt; server: PChar; proxy: PChar; url: PChar; usercode1: LongInt; usercode2: LongInt; regkey1: PLongInt; regkey2: PLongInt; licenseid: PLongInt; password: PChar; licenseupd: PChar): LongInt; stdcall; Function SK_Parse (flags: LongInt; data: PChar; item: LongInt; delimiter: PChar; value: PChar): LongInt; stdcall; Function SK_PostCounters (server: PChar; proxy: PChar; url: PChar; LicenseID: LongInt; counter1: LongInt; counter2: LongInt; counter3: LongInt; counter4: LongInt; counter5: LongInt; licenseupd: PChar): LongInt; stdcall; Function SK_PostCounterEx (flags: LongInt; server: PChar; proxy: PChar; url: PChar; LicenseID: LongInt; counter1: LongInt; counter2: LongInt; counter3: LongInt; counter4: LongInt; counter5: LongInt; licenseupd: PChar): LongInt; stdcall; Function SK_PostEvalData (server: PChar; proxy: PChar; url: PChar; firstname: PChar; lastname: PChar; email: PChar; phone: PChar; ud1: PChar; ud2: PChar; ud3: PChar; ud4: PChar; ud5: PChar; regid: PLongInt): LongInt; stdcall; Function SK_PostEvalDataEx (flags: LongInt; server: PChar; proxy: PChar; url: PChar; firstname: PChar; lastname: PChar; email: PChar; phone: PChar; ud1: PChar; ud2: PChar; ud3: PChar; ud4: PChar; ud5: PChar; regid: PLongInt): LongInt; stdcall; Function SK_PostRegData (flags: LongInt; server: PChar; proxy: PChar; url: PChar; LicenseID: LongInt; password: PChar; companyname: PChar; firstname: PChar; lastname: PChar; address1: PChar; address2: PChar; city: PChar; state: PChar; postalcode: PChar; country: PChar; phone: PChar; fax: PChar; email: PChar): LongInt; stdcall; Function SK_PostStrings (server: PChar; proxy: PChar; url: PChar; LicenseID: LongInt; string1: PChar; string2: PChar; string3: PChar; string4: PChar; string5: PChar; licenseupd: PChar): LongInt; stdcall; Function SK_PostStringEx (flags: LongInt; server: PChar; proxy: PChar; url: PChar; LicenseID: LongInt; string1: PChar; string2: PChar; string3: PChar; string4: PChar; string5: PChar; licenseupd: PChar): LongInt; stdcall; Function SK_ProcEZTrig1 (hwnd: LongInt; filename: PChar; password: PChar; flags: LongInt; errorcode: PLongInt): LongInt; stdcall; Function SK_UpdateCheck (flags: LongInt; options: LongInt; server: PChar; port: Integer; url: PChar; productid: LongInt; productname: PChar; languagecode: PChar; ver1: LongInt; ver2: LongInt; ver3: LongInt; ver4: LongInt; action: PChar; data: PChar; datasize: LongInt; msg: PChar; msgsize: LongInt; urlinfo: PChar; latestversion: PChar; releasedate: PChar; licenseid: LongInt; Password: PChar; status: PChar; replacedby: PLongInt; licenseupdate: PChar): LongInt; stdcall; implementation Function SK_ConnectionState; external 'SKCA32.dll'; Function SK_FileDownload; external 'SKCA32.dll'; Function SK_Firewall; external 'SKCA32.dll'; Procedure SK_GetErrorStr; external 'SKCA32.dll'; Function SK_GetLicenseStatus; external 'SKCA32.dll'; Function SK_GetLicenseStatusEx; external 'SKCA32.dll'; Function SK_GetRegData; external 'SKCA32.dll'; Function SK_GetRegDataEx; external 'SKCA32.dll'; Function SK_GetTCData; external 'SKCA32.dll'; Function SK_GetTCDataEx; external 'SKCA32.dll'; Function SK_GetTCDataDlg; external 'SKCA32.dll'; Function SK_Parse; external 'SKCA32.dll'; Function SK_PostCounters; external 'SKCA32.dll'; Function SK_PostCounterEx; external 'SKCA32.dll'; Function SK_PostEvalData; external 'SKCA32.dll'; Function SK_PostEvalDataEx; external 'SKCA32.dll'; Function SK_PostRegData; external 'SKCA32.dll'; Function SK_PostStrings; external 'SKCA32.dll'; Function SK_PostStringEx; external 'SKCA32.dll'; Function SK_ProcEzTrig1; external 'SKCA32.dll'; Function SK_UpdateCheck; external 'SKCA32.dll'; end.
unit LA.LU.Main; interface uses System.SysUtils, LA.Matrix, LA.LU; procedure Main; implementation procedure Main; var a1, a2, a3: TMatrix; lu1, lu2, lu3: T_LU; begin a1 := TMatrix.Create([[1, 2, 3], [4, 5, 6], [3, -3, 5]]); lu1 := LU(a1); Writeln(lu1.L^.ToString); Writeln(lu1.U^.ToString); Writeln(lu1.L^.Dot(lu1.U^).ToString); Writeln; a2 := TMatrix.Create([[1, 4, 5, 3], [5, 22, 27, 11], [6, 19, 27, 31], [5, 28, 35, -8]]); lu2 := LU(a2); Writeln(lu2.L^.ToString); Writeln(lu2.U^.ToString); Writeln(lu2.L^.Dot(lu2.U^).ToString); Writeln; a3 := TMatrix.Create([[1, 2, 3], [3, 7, 14], [4, 13, 38]]); lu3 := LU(a3); Writeln(lu3.L^.ToString); Writeln(lu3.U^.ToString); Writeln(lu3.L^.Dot(lu3.U^).ToString); end; end.
//------------------------------------------------------------------------------ //BeingList UNIT //------------------------------------------------------------------------------ // What it does - // A list of TCharacters // // Changes - // [2008/12/17] Aeomin- Changed to BeingList from CharaList // December 22nd, 2006 - RaX - Created. //------------------------------------------------------------------------------ unit BeingList; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses Being, ContNrs; type PBeing = ^TBeing; //------------------------------------------------------------------------------ //TCharacterList CLASS //------------------------------------------------------------------------------ TBeingList = Class(TObject) Private fList : TObjectList; fOwnsObject : Boolean; Function GetValue(Index : Integer) : TBeing; Procedure SetValue(Index : Integer; Value : TBeing); Function GetCount : Integer; Public Constructor Create(OwnsBeings : Boolean); Destructor Destroy; override; Property Items[Index : Integer] : TBeing read GetValue write SetValue;default; Property Count : Integer read GetCount; Procedure Add(const ABeing : TBeing); Procedure Insert(const ABeing : TBeing; Index : Integer); Procedure Delete(Index : Integer); Procedure Clear(); Function IndexOf(const ID : LongWord) : Integer; Function IndexOfAID(const AID : LongWord) : Integer; // DO NOT USE THIS UNLESS MUST function IndexOfName(const Name : String):Integer; end; //------------------------------------------------------------------------------ implementation uses Character ; //------------------------------------------------------------------------------ //Create CONSTRUCTOR //------------------------------------------------------------------------------ // What it does - // Initializes our characterlist. Creates a storage area. // // Changes - // December 22nd, 2006 - RaX - Created. //------------------------------------------------------------------------------ constructor TBeingList.Create(OwnsBeings : Boolean); begin inherited Create; fOwnsObject := OwnsBeings; fList := TObjectList.Create(FALSE); end;{Create} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Destroy DESTRUCTOR //------------------------------------------------------------------------------ // What it does - // Destroys our list and frees any memory used. // // Changes - // December 22nd, 2006 - RaX - Created. //------------------------------------------------------------------------------ destructor TBeingList.Destroy; var Index : Integer; begin if fOwnsObject AND (fList.Count >0) then begin for Index := fList.Count -1 downto 0 do fList.Items[Index].Free; end; fList.Free; // Call TObject destructor inherited; end;{Destroy} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Add PROCEDURE //------------------------------------------------------------------------------ // What it does - // Adds a TCharacter to the list. // // Changes - // December 22nd, 2006 - RaX - Created. //------------------------------------------------------------------------------ procedure TBeingList.Add(const ABeing : TBeing); begin fList.Add(ABeing); end;{Add} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Insert PROCEDURE //------------------------------------------------------------------------------ // What it does - // Inserts a TCharacter at Index Position. // // Changes - // December 22nd, 2006 - RaX - Created. //------------------------------------------------------------------------------ procedure TBeingList.Insert(const ABeing : TBeing; Index: Integer); begin fList.Insert(Index, ABeing); end;{Insert} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Delete PROCEDURE //------------------------------------------------------------------------------ // What it does - // Removes a TCharacter at Index from the list. // // Changes - // December 22nd, 2006 - RaX - Created. //------------------------------------------------------------------------------ procedure TBeingList.Delete(Index : Integer); begin if fOwnsObject then fList.Items[Index].Free; fList.Delete(Index); end;{Delete} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //IndexOf FUNCTION //------------------------------------------------------------------------------ // What it does - // Returns the index in the list of the TCharacter; // // Changes - // December 22nd, 2006 - RaX - Created. //------------------------------------------------------------------------------ function TBeingList.IndexOf(const ID: LongWord): Integer; var Index : Integer; begin Index := fList.Count-1; Result := -1; while (Index >= 0) do begin if ID = Items[Index].ID then begin Result := Index; Exit; end; dec(Index, 1); end; end;{IndexOf} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //IndexOfAID FUNCTION //------------------------------------------------------------------------------ // What it does - // Returns the index in the list of the TCharacter; // // Changes - // December 22nd, 2006 - RaX - Created. //------------------------------------------------------------------------------ function TBeingList.IndexOfAID(const AID: LongWord): Integer; var Index : Integer; begin Index := fList.Count-1; Result := -1; while (Index >= 0) do begin if (Items[Index] is TCharacter)AND(AID = TCharacter(Items[Index]).AccountID) then begin Result := Index; Break; end; Dec(Index); end; end;{IndexOfAID} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //IndexOfName FUNCTION //------------------------------------------------------------------------------ // What it does- // Find index by name, DO NOT USE THIS UNLESS MUST // // Changes - // [2009/06/27] Aeomin - Created. // //------------------------------------------------------------------------------ function TBeingList.IndexOfName(const Name : String):Integer; var Index : Integer; begin Index := fList.Count-1; Result := -1; while (Index >= 0) do begin if (Items[Index] is TCharacter)AND(Name = TCharacter(Items[Index]).Name) then begin Result := Index; Break; end; Dec(Index); end; end; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Clear PROCEDURE //------------------------------------------------------------------------------ // What it does - // Clears the list. // // Changes - // December 22nd, 2006 - RaX - Created. //------------------------------------------------------------------------------ procedure TBeingList.Clear; var Index : Integer; begin if fOwnsObject AND (fList.Count >0) then begin for Index := fList.Count -1 downto 0 do fList.Items[Index].Free; end; fList.Clear; end;{Clear} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //GetValue FUNCTION //------------------------------------------------------------------------------ // What it does - // Returns a TCharacter at the index. // // Changes - // December 22nd, 2006 - RaX - Created. //------------------------------------------------------------------------------ function TBeingList.GetValue(Index : Integer): TBeing; begin Result := TBeing(fList.Items[Index]); end;{GetValue} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetValue PROCEDURE //------------------------------------------------------------------------------ // What it does - // Sets a TCharacter into the list at Index. // // Changes - // December 22nd, 2006 - RaX - Created. //------------------------------------------------------------------------------ procedure TBeingList.SetValue(Index : Integer; Value : TBeing); begin fList.Items[Index] := Value; end;{SetValue} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //GetCount PROCEDURE //------------------------------------------------------------------------------ // What it does - // Gets the count from the fList object // // Changes - // October 30th, 2007 - RaX - Created. //------------------------------------------------------------------------------ Function TBeingList.GetCount : Integer; begin Result := fList.Count; end;{GetCount} //------------------------------------------------------------------------------ end.
unit Main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, GLWin32Viewer, GLCrossPlatform, GLBaseClasses, GLScene, GLCoordinates, GLObjects, GLCadencer, GLSimpleNavigation, GLGraph, GLGeomObjects; type TForm1 = class(TForm) GLSceneViewer1: TGLSceneViewer; GLSimpleNavigation1: TGLSimpleNavigation; GLCadencer1: TGLCadencer; GLScene1: TGLScene; GLLightSource1: TGLLightSource; GLCamera1: TGLCamera; GLDummyCube1: TGLDummyCube; procedure FormCreate(Sender: TObject); private Superellipsoids: array[0..5, 0..5] of TGLSuperellipsoid; protected public end; var Form1: TForm1; implementation {$R *.dfm} uses GLVectorGeometry; procedure TForm1.FormCreate(Sender: TObject); var i, j: integer; x, y, d: single; begin d := 6; Randomize; for j := 0 to 5 do for i := 0 to 5 do begin x := -d*2.5 + d*i; y := d*2.5 - d*j; Superellipsoids[i, j] := TGLSuperellipsoid(GLScene1.Objects.AddNewChild(TGLSuperellipsoid)); with Superellipsoids[i, j] do begin Slices := 32; Stacks := 32; Scale.SetVector(5, 5, 5); Position.SetPoint(x, y, 0); Direction.SetVector(0, 1, 0); Up.SetVector(0, 0, 1); case i of 0:VCurve := 0.2; 1:VCurve := 0.8; 2:VCurve := 1.0; 3:VCurve := 1.5; 4:VCurve := 2.0; 5:VCurve := 3.0; end; case j of 0:HCurve := 0.2; 1:HCurve := 0.8; 2:HCurve := 1.0; 3:HCurve := 1.5; 4:HCurve := 2.0; 5:HCurve := 3.0; end; with Material.FrontProperties do begin Ambient.RandomColor; Diffuse.RandomColor; Specular.RandomColor; Shininess := 125; end; end; end; end; end.
unit uPrintCashReg; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Db, DBTables, ADODB; const TICKET_CASH_OPEN = 1; TICKET_CASH_CLOSE = 2; TICKET_CASH_PETTY = 3; TICKET_CASH_ADD = 4; type TRegCash = record AOpenDate: TDateTime; ACloseDate: TDateTime; AOpenUser: String; ACloseUser: String; AIDCashReg: Integer; ACashReg: String; ABill100: Integer; ABill50: Integer; ABill20: Integer; ABill10: Integer; ABill5: Integer; ABill2: Integer; ABill1: Integer; ACoin001: Integer; ACoin005: Integer; ACoin010: Integer; ACoin025: Integer; ACoin050: Integer; ACoin1: Integer; ATotalCash: Currency; ATotalCard: Currency; ATotalPreCard: Currency; ATotalCheck: Currency; ATotalOther: Currency; ATotalDebit: Currency; ATotalPetty: Currency; ATotalWithdraw: Currency; end; TPrintCashReg = class(TForm) Label1: TLabel; Panel1: TPanel; quCashRegLog: TADOQuery; quCashRegLogIDCashRegLog: TIntegerField; quCashRegLogIDUser: TIntegerField; quCashRegLogLogTime: TDateTimeField; quCashRegLogBill100: TIntegerField; quCashRegLogBill50: TIntegerField; quCashRegLogBill20: TIntegerField; quCashRegLogBill10: TIntegerField; quCashRegLogBill5: TIntegerField; quCashRegLogBill2: TIntegerField; quCashRegLogBill1: TIntegerField; quCashRegLogCoin1: TIntegerField; quCashRegLogCoin050: TIntegerField; quCashRegLogCoin025: TIntegerField; quCashRegLogCoin010: TIntegerField; quCashRegLogCoin005: TIntegerField; quCashRegLogCoin001: TIntegerField; quCashRegLogTotalCard: TFloatField; quCashRegLogOpenTime: TDateTimeField; quCashRegLogTotalCheck: TFloatField; quCashRegLogTotalOther: TFloatField; quCashRegLogTotalCash: TFloatField; quCashRegLogIDCashRegister: TIntegerField; quCashRegLogCashRegister: TStringField; quCashRegLogOpenUser: TStringField; quCashRegLogLogUser: TStringField; quCashRegLogTotalCardPre: TFloatField; quCashRegLogTotalDebit: TBCDField; quCashRegMov: TADOQuery; quCashRegMovTotalWidraw: TBCDField; quCashRegMovTotalPetty: TBCDField; quCashRegLogIDCashRegMov: TIntegerField; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); private { Private declarations } //Translation sModel, sDesc, sGroup, sQty, sOpenCash, sCash, sOpenUser, sOpenTime, sCloseCash, sCloseUser, sCloseTime, sTotalCash, sTotalCard, sTotalDebit, sTotalCardP, sTotalCheck, sTotalOther, sTotalConta, sCashDetail, sTotalPetty, sTotalWithDraw, sCountItem : String; function GetItemsToCount(Num: Integer):String; function GetItemsToCountDB(Num: Integer): String; function GetItemsToCountTXT(Num: Integer): String; public { Public declarations } procedure Start(IDCashRegLog : Integer; ReceiptType: Integer); end; implementation uses uDM, uPassword, XBase, uMsgBox, uStringFunctions, uMsgConstant, uDMGlobal, uSystemConst, uTXTCashInfo, uFrmPOSFunctions; {$R *.DFM} function TPrintCashReg.GetItemsToCount(Num: Integer):String; begin case DM.PersistenceType of ptDB: Result := GetItemsToCountDB(Num); ptTXT: Result := GetItemsToCountTXT(Num); end; end; function TPrintCashReg.GetItemsToCountDB(Num:Integer):String; var iMax, i : Integer; bEmpty : Boolean; begin iMax := 1 + DM.GetMaxKey(MR_MODEL_ID); with DM.quFreeSQL do begin if Active then Close; SQL.Clear; SQL.Add('SELECT M.Model, M.Description, TG.Name'); SQL.Add('FROM Model M'); SQL.Add('JOIN TabGroup TG ON (M.GroupID = TG.IDGroup)'); SQL.Add('WHERE IDModel = :IDModel'); SQL.Add('AND M.Desativado = 0 AND M.Hidden = 0'); Result := sCountItem + #13#10; for i := 1 to Num do begin bEmpty := True; while bEmpty do begin Close; Parameters.ParamByName('IDModel').Value := Random(iMax); Open; bEmpty := IsEmpty; end; Result := Result + sModel + Copy(FieldByName('Model').AsString,1,50) + #13#10 + sDesc + Copy(FieldByName('Description').AsString,1,50) + #13#10 + sGroup + Copy(FieldByName('Name').AsString,1,50) + #13#10 + sQty + #13#10 + '----------------------------------------' + #13#10 ; Close; end; end; end; function TPrintCashReg.GetItemsToCountTXT(Num:Integer):String; begin Result := ''; end; procedure TPrintCashReg.Start(IDCashRegLog : Integer; ReceiptType: Integer); var NotOk: Boolean; RCR: TRegCash; TF: TTXTCashInfo; begin case DM.PersistenceType of ptDB: begin with quCashRegLog do begin Parameters.ParambyName('IDCashRegLog').Value := IDCashRegLog; Open; end; with quCashRegMov do begin Parameters.ParambyName('IDCashRegMov').Value := quCashRegLogIDCashRegMov.AsInteger; Open; end; with RCR do begin AOpenDate := quCashRegLogOpenTime.AsDateTime; ACloseDate := quCashRegLogLogTime.AsDateTime; AOpenUser := quCashRegLogOpenUser.AsString; ACloseUser := quCashRegLogLogUser.AsString; AIDCashReg := quCashRegLogIDCashRegister.AsInteger; ACashReg := quCashRegLogCashRegister.AsString; ATotalCash := quCashRegLogTotalCash.AsCurrency; ATotalCard := quCashRegLogTotalCard.AsCurrency; ATotalDebit := quCashRegLogTotalDebit.AsCurrency; ATotalPreCard := quCashRegLogTotalCardPre.AsCurrency; ATotalCheck := quCashRegLogTotalCheck.AsCurrency; ATotalOther := quCashRegLogTotalOther.AsCurrency; ABill100 := quCashRegLogBill100.AsInteger; ABill50 := quCashRegLogBill50.AsInteger; ABill20 := quCashRegLogBill20.AsInteger; ABill10 := quCashRegLogBill10.AsInteger; ABill5 := quCashRegLogBill5.AsInteger; ABill2 := quCashRegLogBill2.AsInteger; ABill1 := quCashRegLogBill1.AsInteger; ACoin001 := quCashRegLogCoin001.AsInteger; ACoin005 := quCashRegLogCoin005.AsInteger; ACoin010 := quCashRegLogCoin010.AsInteger; ACoin025 := quCashRegLogCoin025.AsInteger; ACoin050 := quCashRegLogCoin050.AsInteger; ACoin1 := quCashRegLogCoin1.AsInteger; ATotalPetty := quCashRegMovTotalPetty.AsCurrency; ATotalWithdraw:= quCashRegMovTotalWidraw.AsCurrency; end; quCashRegLog.Close; quCashRegMov.Close; end; ptTXT: begin TF := DM.TXTCashInfoFactory(DM.fCashRegister.RecentClosedCash); try with RCR do begin AOpenDate := TF.OpenDate; ACloseDate := TF.CloseDate; AOpenUser := DM.fPOS.TXTDescSystemUser(TF.IDOpenUser); ACloseUser := DM.fPOS.TXTDescSystemUser(TF.IDCloseUser); AIDCashReg := TF.IDCashReg; ACashReg := DM.fPOS.TXTDescCashReg(TF.IDCashReg); case ReceiptType of TICKET_CASH_OPEN: begin ABill100 := TF.OpenBill100; ABill50 := TF.OpenBill50; ABill20 := TF.OpenBill20; ABill10 := TF.OpenBill10; ABill5 := TF.OpenBill5; ABill2 := TF.OpenBill2; ABill1 := TF.OpenBill1; ACoin001 := TF.OpenCoin001; ACoin005 := TF.OpenCoin005; ACoin010 := TF.OpenCoin010; ACoin025 := TF.OpenCoin025; ACoin050 := TF.OpenCoin050; ACoin1 := TF.OpenCoin1; ATotalCash := TF.OpenTotalCash; ATotalCard := TF.OpenTotalCard; ATotalDebit := TF.OpenTotalDebit; ATotalPreCard := TF.OpenTotalPreCard; ATotalCheck := TF.OpenTotalCheck; ATotalOther := TF.OpenTotalOther; end; TICKET_CASH_CLOSE: begin ABill100 := TF.CloseBill100; ABill50 := TF.CloseBill50; ABill20 := TF.CloseBill20; ABill10 := TF.CloseBill10; ABill5 := TF.CloseBill5; ABill2 := TF.CloseBill2; ABill1 := TF.CloseBill1; ACoin001 := TF.CloseCoin001; ACoin005 := TF.CloseCoin005; ACoin010 := TF.CloseCoin010; ACoin025 := TF.CloseCoin025; ACoin050 := TF.CloseCoin050; ACoin1 := TF.CloseCoin1; ATotalCash := TF.CloseTotalCash; ATotalCard := TF.CloseTotalCard; ATotalDebit := TF.CloseTotalDebit; ATotalPreCard := TF.CloseTotalPreCard; ATotalCheck := TF.CloseTotalCheck; ATotalOther := TF.CloseTotalOther; ATotalPetty := TF.PettyCashTotal; ATotalWithdraw:= TF.WidrawTotal; end; end; end; finally TF.Free; end; end; end; Show; Update; Application.ProcessMessages; NotOk := True; while NotOk do begin try DM.PrinterStart; NotOk := False; except if MsgBox(MSG_CRT_ERROR_PRINTING, vbCritical + vbYesNo) = vbYes then NotOk := True else begin Exit; end; end; end; // ----------------------------------------------------------------- // Impressăo do cabecalho do ticket case ReceiptType of TICKET_CASH_OPEN : // Open begin DM.PrintLine('========================================'); DM.PrintLine(sOpenCash); DM.PrintLine(' ---------------------------------- '); DM.PrintLine(sCash + RCR.ACashReg); DM.PrintLine(''); DM.PrintLine(sOpenUser+ RCR.AOpenUser); DM.PrintLine(sOpenTime+ DateTimeToStr(RCR.AOpenDate)); DM.PrintLine('----------------------------------------'); end; TICKET_CASH_CLOSE : // Close begin DM.PrintLine('========================================'); DM.PrintLine(sCloseCash); DM.PrintLine(' ---------------------------------- '); DM.PrintLine(sCash + RCR.ACashReg); DM.PrintLine(sOpenUser + RCR.AOpenUser); DM.PrintLine(sOpenTime + DateTimeToStr(RCR.AOpenDate)); DM.PrintLine(sCloseUser+ RCR.ACloseUser); DM.PrintLine(sCloseTime+ DateTimeToStr(RCR.ACloseDate)); DM.PrintLine('----------------------------------------'); end; TICKET_CASH_PETTY: // Petty Cash begin end; TICKET_CASH_ADD: //CashAdd begin end; end; DM.PrintLine(sTotalCash + IdentRight(18, FloatToStrF(RCR.ATotalCash, ffCurrency, 20, 2))); DM.PrintLine(sTotalCard + IdentRight(18, FloatToStrF(RCR.ATotalCard, ffCurrency, 20, 2))); DM.PrintLine(sTotalCardP + IdentRight(18, FloatToStrF(RCR.ATotalPreCard, ffCurrency, 20, 2))); DM.PrintLine(sTotalDebit + IdentRight(18, FloatToStrF(RCR.ATotalDebit, ffCurrency, 20, 2))); DM.PrintLine(sTotalCheck + IdentRight(18, FloatToStrF(RCR.ATotalCheck, ffCurrency, 20, 2))); DM.PrintLine(sTotalOther + IdentRight(18, FloatToStrF(RCR.ATotalOther, ffCurrency, 20, 2))); DM.PrintLine(''); DM.PrintLine(sTotalConta + IdentRight(18, FloatToStrF(RCR.ATotalCash + RCR.ATotalCard + RCR.ATotalPreCard + RCR.ATotalDebit + RCR.ATotalCheck + RCR.ATotalOther, ffCurrency, 20, 2))); DM.PrintLine(' '); DM.PrintLine(sCashDetail); DM.PrintLine('$100 : ' + FloatToStrF(RCR.ABill100, ffGeneral , 20, 2)); DM.PrintLine('$50 : ' + FloatToStrF(RCR.ABill50, ffGeneral , 20, 2)); DM.PrintLine('$20 : ' + FloatToStrF(RCR.ABill20, ffGeneral , 20, 2)); DM.PrintLine('$10 : ' + FloatToStrF(RCR.ABill10, ffGeneral , 20, 2)); DM.PrintLine('$5 : ' + FloatToStrF(RCR.ABill5, ffGeneral , 20, 2)); DM.PrintLine('$2 : ' + FloatToStrF(RCR.ABill2, ffGeneral , 20, 2)); DM.PrintLine('$1 : ' + FloatToStrF(RCR.ABill1, ffGeneral , 20, 2)); DM.PrintLine('$.01 : ' + FloatToStrF(RCR.ACoin001, ffGeneral , 20, 2)); DM.PrintLine('$.05 : ' + FloatToStrF(RCR.ACoin005, ffGeneral , 20, 2)); DM.PrintLine('$.10 : ' + FloatToStrF(RCR.ACoin010, ffGeneral , 20, 2)); DM.PrintLine('$.25 : ' + FloatToStrF(RCR.ACoin025, ffGeneral , 20, 2)); DM.PrintLine('$.50 : ' + FloatToStrF(RCR.ACoin050, ffGeneral , 20, 2)); DM.PrintLine('$1.00 : ' + FloatToStrF(RCR.ACoin1, ffGeneral , 20, 2)); DM.PrintLine(''); DM.PrintLine(''); DM.PrintLine(''); case ReceiptType of TICKET_CASH_CLOSE : begin DM.PrintLine(sTotalPetty + IdentRight(18, FloatToStrF(RCR.ATotalPetty, ffCurrency, 20, 2))); DM.PrintLine(sTotalWithDraw + IdentRight(18, FloatToStrF(RCR.ATotalWithdraw, ffCurrency, 20, 2))); end; end; DM.PrintLine(''); DM.PrintLine(''); DM.PrintLine(''); DM.PrintLine(''); DM.PrintLine(''); DM.PrintLine(''); DM.PrintLine('-------------------------------'); //Verifica se tem items para ser impresso no close da caixa if DM.fSystem.SrvParam[PARAM_NUM_ITEM_TO_PRINT] > 0 Then begin if (ReceiptType = TICKET_CASH_OPEN) AND (DM.fSystem.SrvParam[PARAM_PRINT_ON_OPENCASHREG]) then DM.PrintLine(GetItemsToCount(DM.fSystem.SrvParam[PARAM_NUM_ITEM_TO_PRINT])) else if (ReceiptType = TICKET_CASH_CLOSE) AND (not DM.fSystem.SrvParam[PARAM_PRINT_ON_OPENCASHREG]) then DM.PrintLine(GetItemsToCount(DM.fSystem.SrvParam[PARAM_NUM_ITEM_TO_PRINT])); end; DM.PrinterStop; DM.SendAfterPrintCode(True); Close; ModalResult := mrOK; end; procedure TPrintCashReg.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TPrintCashReg.FormCreate(Sender: TObject); begin inherited; Case DMGlobal.IDLanguage of LANG_ENGLISH : begin sCountItem := '------ Please count these Inventory Items -------'; sModel := 'Model :'; sDesc := 'Desc. :'; sGroup := 'Categ :'; sQty := 'Qty :'; sOpenCash := ' O P E N C A S H R E G I S T E R '; sCash := 'Cash : '; sOpenUser := 'Open User : '; sOpenTime := 'Open Time : '; sCloseCash := ' C L O S E C A S H R E G I S T E R '; sCloseUser := 'Close User : '; sCloseTime := 'Close Time : '; sTotalCash := 'Total Cash : '; sTotalCard := 'Total Card : '; sTotalCardP := 'Total Card Pre: '; sTotalDebit := 'Total Debit : '; sTotalPetty := 'Total Petty :'; sTotalWithDraw := 'Total Withdraw :'; sTotalCheck := 'Total Check : '; sTotalOther := 'Total Other : '; sTotalConta := 'TOTAL COUNTED : '; sCashDetail := 'Cash Details '; end; LANG_PORTUGUESE : begin sCountItem := '----- Por favor conte esses itens no stoque -----'; sModel := 'Modelo :'; sDesc := 'Desc. :'; sGroup := 'Categ. :'; sQty := 'Qtd :'; sOpenCash := ' ABERTURA DO CAIXA REGISTRADORA '; sCash := 'Dinheiro : '; sOpenUser := 'Usuário A : '; sOpenTime := 'Abertura : '; sCloseCash := ' FECHAMENTO DO CAIXA REGISTRADORA '; sCloseUser := 'Usuário F : '; sCloseTime := 'Fechamento: '; sTotalCash := 'Total Dinheiro : '; sTotalCard := 'Total Cartăo : '; sTotalCardP := 'Total Crt Débito: '; sTotalDebit := 'Total Débito : '; sTotalCheck := 'Total Cheque : '; sTotalOther := 'Total Outros : '; sTotalConta := 'TOTAL CONTADO : '; sCashDetail := 'Detalhe do dinheiro '; sTotalPetty := 'Total Suprimento :'; sTotalWithDraw := 'Total Sangria :'; end; LANG_SPANISH : begin sCountItem := '-- Porfavor contar estos items del Inventario ---'; sModel := 'Modelo :'; sDesc := 'Desc. :'; sGroup := 'Categ :'; sQty := 'Ctd :'; sOpenCash := ' A B R I R L A C A J A '; sCash := 'Efectivo : '; sOpenUser := 'Usuario A : '; sOpenTime := 'Apertura : '; sCloseCash := ' C E R R A R L A C A J A '; sCloseUser := 'Usuario C : '; sCloseTime := 'Fecha : '; sTotalCash := 'Total Efectivo : '; sTotalCard := 'Total Tarjeta : '; sTotalCardP := 'Total Tarjeta Fec: '; sTotalCardP := 'Total Trj Dédito : '; sTotalCheck := 'Total Cheques : '; sTotalOther := 'Total Otros : '; sTotalConta := 'TOTAL CONTADO : '; sCashDetail := 'Detalle del efectivo '; sTotalPetty := 'Total Suprimento :'; sTotalWithDraw := 'Total Sangria :'; end; end; end; end.
unit ThDataConnection; interface uses SysUtils, Classes, Forms, ADODB, Db, ThComponent; type TThConnectionString = string; // TThConnectionStore = class(TThComponent) private FConnectionStrings: TStringList; FFilename: string; protected procedure SetConnectionStrings(const Value: TStringList); procedure SetFilename(const Value: string); public constructor Create(inOwner: TComponent); override; destructor Destroy; override; procedure Add(const inConnectionString: string); procedure Save; property Filename: string read FFilename write SetFilename; published property ConnectionStrings: TStringList read FConnectionStrings write SetConnectionStrings; end; // TThDataConnection = class(TPersistent) private FADOConnection: TADOConnection; FADOTable: TADOTable; FConnectionString: TThConnectionString; FDataSource: TDataSource; protected function GetConnected: Boolean; function GetLoginPrompt: Boolean; procedure SetConnected(const Value: Boolean); procedure SetConnectionString(const Value: TThConnectionString); procedure SetLoginPrompt(const Value: Boolean); public constructor Create(inOwner: TComponent); //override; destructor Destroy; override; property Connection: TADOConnection read FADOConnection; published property Connected: Boolean read GetConnected write SetConnected; property ConnectionString: TThConnectionString read FConnectionString write SetConnectionString; property LoginPrompt: Boolean read GetLoginPrompt write SetLoginPrompt; end; // TThDbConnect = class(TThComponent) end; function NeedConnectionStore: TThConnectionStore; implementation const cTpConnectionStoreFilename = 'connections.turbophp.cfg'; var ConnectionStore: TThConnectionStore; function NeedConnectionStore: TThConnectionStore; begin if ConnectionStore = nil then begin ConnectionStore := TThConnectionStore.Create(nil); ConnectionStore.Filename := ExtractFilePath(Application.ExeName) + cTpConnectionStoreFilename; end; Result := ConnectionStore end; { TThConnectionStore } constructor TThConnectionStore.Create(inOwner: TComponent); begin inherited; FConnectionStrings := TStringList.Create; FConnectionStrings.Duplicates := dupIgnore; end; destructor TThConnectionStore.Destroy; begin FConnectionStrings.Free; inherited; end; procedure TThConnectionStore.SetConnectionStrings(const Value: TStringList); begin FConnectionStrings.Assign(Value); end; procedure TThConnectionStore.SetFilename(const Value: string); begin FFilename := Value; LoadFromFile(FFilename); end; procedure TThConnectionStore.Add(const inConnectionString: string); begin if FConnectionStrings.IndexOf(inConnectionString) < 0 then begin FConnectionStrings.Add(inConnectionString); Save; end; end; procedure TThConnectionStore.Save; begin SaveToFile(FFilename); end; { TThDataConnection } constructor TThDataConnection.Create(inOwner: TComponent); begin inherited Create; FAdoConnection := TAdoConnection.Create(inOwner); FAdoTable := TAdoTable.Create(inOwner); FAdoTable.Connection := FAdoConnection; FDataSource := TDataSource.Create(inOwner); FDataSource.DataSet := FAdoTable; { inherited; FAdoConnection := TAdoConnection.Create(Self); FAdoTable := TAdoTable.Create(Self); FAdoTable.Connection := FAdoConnection; FDataSource := TDataSource.Create(Self); FDataSource.DataSet := FAdoTable; } LoginPrompt := false; end; destructor TThDataConnection.Destroy; begin FDataSource.Free; FAdoTable.Free; FAdoConnection.Free; inherited; end; function TThDataConnection.GetConnected: Boolean; begin Result := FAdoConnection.Connected; end; function TThDataConnection.GetLoginPrompt: Boolean; begin Result := FAdoConnection.LoginPrompt; end; procedure TThDataConnection.SetConnected(const Value: Boolean); begin if (Connected <> Value) and (ConnectionString <> '') then begin FAdoConnection.ConnectionString := ConnectionString; FAdoConnection.Connected := Value; if Value then NeedConnectionStore.Add(FAdoConnection.ConnectionString); end; end; procedure TThDataConnection.SetConnectionString( const Value: TThConnectionString); begin FConnectionString := Value; end; procedure TThDataConnection.SetLoginPrompt(const Value: Boolean); begin FAdoConnection.LoginPrompt := Value; end; end.
unit FicDefAc; {Version Delphi} { La description de l'entŕte est dans fichac1.doc } { Pour imprimer les offsets, on peut utiliser offsetAC.Pas } INTERFACE {$IFDEF FPC} {$mode delphi} {$DEFINE AcqElphy2} {$A1} {$Z1} {$ENDIF} uses util1,dtf0; const maxMarqueAcq=100; type TypeMarqueAcq=record l:char; n:SmallInt; end; typeTabMarqueAcq=array[1..maxMarqueAcq] of typeMarqueAcq; const signatureAC1='ACQUIS1/GS/1991'; tailleInfoAC1=1024; { valeur minimale du bloc info } type typeInfoAC1=object id:string[15]; tailleInfo:SmallInt; nbvoie:byte; nbpt:SmallInt; uX:string[3]; uY:array[1..6] of string[3]; i1,i2:SmallInt; x1,x2:float; j1,j2:array[1..6] of SmallInt; y1,y2:array[1..6] of float; NbMacq:SmallInt; Macq:typeTabMarqueAcq; { 300 octets } Xmini,Xmaxi,Ymini,Ymaxi:array[1..6] of float; modeA:array[1..6] of byte; continu:boolean; preseqI,postSeqI:SmallInt; EchelleSeqI:boolean; nbptEx:word; { Qnbpt=nbptEx*32768+nbpt } x1s,x2s:single; y1s,y2s:array[1..6] of single; Xminis,Xmaxis,Yminis,Ymaxis:array[1..6] of single; nseq:SmallInt; tpData:typeTypeG; NoAnalogData:boolean; procedure init(taille:integer); { Fixe la valeur de tailleInfo et la signature } (* procedure sauver(var f:file); { Sauve un bloc de 1024 octets sans se soucier de tailleInfo. Les champs au-delů de la taille de typeInfoAc1 contiendront 0 } procedure charger(var f:file;var ok:boolean); *) function Fperiode:float; function FdureeSeq:float; procedure copierSingle; end; typeInfoSeqAC1= object uX:string[3]; uY:array[1..6] of string[3]; i1,i2:SmallInt; x1,x2:float; j1,j2:array[1..6] of SmallInt; y1,y2:array[1..6] of float; procedure init; procedure sauver(var f:file); procedure charger(var f:file); end; const tokBoolean= 1; tokByte= 2; tokInteger= 3; tokLongint= 4; tokExtended=5; tokString= 6; type typePostSeqRec=record case tok:byte of tokBoolean: (bb:boolean); tokByte: (xb:byte); tokInteger: (xi:SmallInt); tokLongint: (xl:longint); tokExtended:(xe:float); tokString: (st:string[255]); end; PtrPostSeqRec=^typePostSeqRec; type typeInfoPostSeq= object tailleBuf:Integer; buf:PtabOctet; ad:Integer; procedure init(taille:integer); procedure done; procedure setByte(x:byte); procedure setBoolean(x:boolean); procedure setInteger(x:SmallInt); procedure setLongint(x:longint); procedure setExtended(x:float); procedure setString(st0:AnsiString); function getByte(n:integer):byte; function getBoolean(n:integer):boolean; function getInteger(n:integer):SmallInt; function getLongint(n:integer):longint; function getExtended(n:integer):float; function getString(n:integer):AnsiString; function suivant(p:PtrPostSeqRec):PtrPostSeqRec; procedure sauver(var f:file); procedure charger(var f:file); function getInfo(var x;nb,dep:integer):boolean; function setInfo(var x;nb,dep:integer):boolean; function readInfo(var x;nb:integer):boolean; function writeInfo(var x;nb:integer):boolean; procedure resetInfo; end; typeInfoFich=object(typeInfoAc1) typeFich:SmallInt; longDat:longint; offtag:longint; spaceTag:longint; nbtag:word; error:SmallInt; procedure init; procedure charger(var f:file); function getDx:float; function getX0:float; function getDy(n:integer):float; function getY0(n:integer):float; function getTag(n:integer):longint; end; IMPLEMENTATION {********************* Méthodes de typeInfoAc1 *****************************} procedure typeInfoAC1.init(taille:integer); begin fillchar(self,sizeof(typeInfoAc1),0); id:=signatureAC1; tailleInfo:=taille; end; (* procedure typeInfoAC1.sauver(var f:file); var res:intG; buf:pointer; begin getmem(buf,1024); fillchar(buf^,1024,0); move(self,buf^,sizeof(typeInfoAC1)); GblockWrite(f,buf^,1024,res); freemem(buf,1024); end; procedure typeInfoAC1.charger(var f:file;var ok:boolean); var res:intG; buf:pointer; begin getmem(buf,1024); Gblockread(f,buf^,1024,res); move(buf^,self,sizeof(typeInfoAC1)); freemem(buf,1024); ok:=(id=signatureAC1); end; *) function typeInfoAC1.Fperiode:float; begin if (i2<>i1) and (nbvoie<>0) then Fperiode:=(x2-x1)/(i2-i1)/nbvoie else Fperiode:=0; end; function typeInfoAC1.FdureeSeq:float; begin FdureeSeq:=Fperiode*nbpt*nbvoie; end; procedure typeInfoAC1.copierSingle; var i:integer; begin x1s:=x1; x2s:=x2; for i:=1 to 6 do begin y1s[i]:=y1[i]; y2s[i]:=y2[i]; XminiS[i]:=Xmini[i]; XmaxiS[i]:=Xmaxi[i]; YminiS[i]:=Ymini[i]; YmaxiS[i]:=Ymaxi[i]; end; end; {********************* Méthodes de typeInfoSeqAc1 **************************} procedure typeInfoSeqAC1.init; begin end; procedure typeInfoSeqAC1.sauver(var f:file); var res:integer; begin blockwrite(f,self,sizeof(typeInfoSeqAC1),res); end; procedure typeInfoSeqAC1.charger(var f:file); begin end; {********************* Méthodes de typeInfoPostSeq *************************} procedure typeInfoPostSeq.init(taille:integer); begin if (taille<=0) or (taille>maxavail) then begin buf:=nil; tailleBuf:=0; end else begin getmem(buf,taille); tailleBuf:=taille; ad:=0; end; end; procedure typeInfoPostSeq.done; begin if tailleBuf<>0 then freemem(buf,tailleBuf); tailleBuf:=0; buf:=nil; ad:=0; end; procedure typeInfoPostSeq.setBoolean(x:Boolean); var pp:PtrPostSeqRec; begin if (buf<>nil) and (ad+sizeof(Boolean)<tailleBuf) then begin pp:=@buf; inc(intG(pp),ad); with pp^ do begin tok:=tokBoolean; bb:=x; inc(ad,1+sizeof(Boolean)); end; end; end; procedure typeInfoPostSeq.setByte(x:Byte); var pp:PtrPostSeqRec; begin if (buf<>nil) and (ad+sizeof(Byte)<tailleBuf) then begin pp:=@buf; inc(intG(pp),ad); with pp^ do begin tok:=tokByte; xb:=x; inc(ad,1+sizeof(Byte)); end; end; end; procedure typeInfoPostSeq.setInteger(x:SmallInt); var pp:PtrPostSeqRec; begin if (buf<>nil) and (ad+sizeof(SmallInt)<tailleBuf) then begin pp:=@buf; inc(intG(pp),ad); with pp^ do begin tok:=tokInteger; xi:=x; inc(ad,1+sizeof(SmallInt)); end; end; end; procedure typeInfoPostSeq.setlongint(x:longint); var pp:PtrPostSeqRec; begin if (buf<>nil) and (ad+sizeof(longint)<tailleBuf) then begin pp:=@buf; inc(intG(pp),ad); with pp^ do begin tok:=tokLongint; xl:=x; inc(ad,1+sizeof(longint)); end; end; end; procedure typeInfoPostSeq.setExtended(x:float); var pp:PtrPostSeqRec; begin if (buf<>nil) and (ad+sizeof(float)<tailleBuf) then begin pp:=@buf; inc(intG(pp),ad); with pp^ do begin tok:=tokExtended; xe:=x; inc(ad,1+sizeof(extended)); end; end; end; procedure typeInfoPostSeq.setString(st0:AnsiString); var pp:PtrPostSeqRec; begin if (buf<>nil) and (ad+length(st0)+1<tailleBuf) then begin pp:=@buf; inc(intG(pp),ad); with pp^ do begin tok:=tokExtended; st:=st0; inc(ad,1+length(st)+1); end; end; end; function typeInfoPostSeq.getBoolean(n:integer):boolean; var p:ptrPostSeqRec; i:integer; begin getBoolean:=false; if buf=nil then exit; p:=ptrPostSeqRec(buf); i:=1; while (i<n) and (p^.tok<>0) do begin inc(i); p:=suivant(p); end; if (i=n) and (p^.tok=tokBoolean) then getBoolean:=p^.bb; end; function typeInfoPostSeq.suivant(p:ptrPostSeqRec):ptrPostSeqRec; var t:integer; begin case p^.tok of tokBoolean: t:=2; tokByte: t:=2; tokInteger: t:=3; tokLongint: t:=5; tokExtended:t:=9; tokString: t:=length(p^.st)+2; else t:=0; end; inc(intG(p),t); suivant:=p; end; function typeInfoPostSeq.getByte(n:integer):byte; var p:ptrPostSeqRec; i:integer; begin getByte:=0; if buf=nil then exit; p:=ptrPostSeqRec(buf); i:=1; while (i<n) and (p^.tok<>0) do begin inc(i); p:=suivant(p); end; if (i=n) and (p^.tok=tokByte) then getByte:=p^.xb; end; function typeInfoPostSeq.getinteger(n:integer):SmallInt; var p:ptrPostSeqRec; i:integer; begin getinteger:=0; if buf=nil then exit; p:=ptrPostSeqRec(buf); i:=1; while (i<n) and (p^.tok<>0) do begin inc(i); p:=suivant(p); end; if (i=n) and (p^.tok=tokInteger) then getInteger:=p^.xi; end; function typeInfoPostSeq.getLongint(n:Integer):Longint; var p:ptrPostSeqRec; i:integer; begin getLongint:=0; if buf=nil then exit; p:=ptrPostSeqRec(buf); i:=1; while (i<n) and (p^.tok<>0) do begin inc(i); p:=suivant(p); end; if (i=n) and (p^.tok=tokLongint) then getLongint:=p^.xl; end; function typeInfoPostSeq.getExtended(n:Integer):float; var p:ptrPostSeqRec; i:integer; begin getExtended:=0; if buf=nil then exit; p:=ptrPostSeqRec(buf); i:=1; while (i<n) and (p^.tok<>0) do begin inc(i); p:=suivant(p); end; if (i=n) and (p^.tok=tokExtended) then getExtended:=p^.xe; end; function typeInfoPostSeq.getString(n:Integer):AnsiString; var p:ptrPostSeqRec; i:integer; begin getString:=''; if buf=nil then exit; p:=ptrPostSeqRec(buf); i:=1; while (i<n) and (p^.tok<>0) do begin inc(i); p:=suivant(p); end; if (i=n) and (p^.tok=tokString) then getString:=p^.st; end; procedure typeInfoPostSeq.sauver(var f:file); var res:integer; begin if buf<>nil then blockwrite(f,buf^,tailleBuf,res); end; procedure typeInfoPostSeq.charger(var f:file); var res:integer; begin if buf<>nil then blockread(f,buf^,tailleBuf,res); end; function typeInfoPostSeq.getInfo(var x;nb,dep:integer):boolean; begin if (buf=nil) or (dep<0) or (tailleBuf<dep+nb) then begin fillchar(x,nb,0); getInfo:=false; exit; end; move(buf^[dep],x,nb); getInfo:=true; end; function typeInfoPostSeq.setInfo(var x;nb,dep:integer):boolean; begin if (buf=nil) or (dep<0) or (tailleBuf<dep+nb) then setInfo:=false else begin move(x,buf^[dep],nb); setInfo:=true; end; end; function typeInfoPostSeq.readInfo(var x;nb:integer):boolean; begin readInfo:=getInfo(x,nb,ad); inc(ad,nb); end; function typeInfoPostSeq.writeInfo(var x;nb:integer):boolean; begin writeInfo:=setInfo(x,nb,ad); inc(ad,nb); end; procedure typeInfoPostSeq.resetInfo; begin ad:=0; end; {********************** Méthodes de TypeInfoFich **************************} procedure typeInfoFich.init; begin fillchar(self,sizeof(typeInfoFich),0); typeFich:=0; end; procedure typeInfoFich.charger(var f:file); var res:integer; buf:pointer; function lireAC:boolean; begin lireAC:=false; with typeInfoAC1(buf^) do begin if id<>signatureAC1 then exit; move(buf^,self,sizeof(typeInfoAC1)); typeFich:=5; longdat:=fileSize(f)-tailleInfo; end; lireAC:=true; end; function lirePCLAMP:boolean; type typeBufFetch=record typeF: single; nbChan: single; nbSample: single; nbEpisode:single; Clock1: single; Clock2: single; bid1: array[7..22] of single; tagInfo: single; bid5: array[24..30] of single; ascending:single; FirstChan:single; bid2: array[33..80] of single; comment: array[1..77] of char; bid3: array[1..243] of byte; ExtOffset:array[0..15] of single; ExtGain: array[0..15] of single; bid4: array[1..32] of single; unitM: array[0..15] of array[1..8] of char; end; var i,j:integer; v:array[1..6] of integer; res:integer; begin lirePclamp:=false; with typeBufFetch(buf^) do begin if (typeF<>1) and (typeF<>10) then exit; Continu:=(typeF=10); nbvoie:=roundI(nbChan); nbpt:=roundI(nbSample); v[1]:=roundI(firstChan) and $0F; if ascending=0 then for i:=2 to nbVoie do v[i]:=(v[i-1]+1) and $0F else for i:=2 to nbVoie do v[i]:=(v[i-1]-1) and $0F; uX:='ms '; i1:=0; i2:=nbpt; x1:=0; x2:=Clock1*nbPt*nbVoie*0.001; if Continu then begin uX:='sec'; X2:=x2/1000; end; for i:=1 to nbVoie do begin uY[i]:=''; for j:=1 to 8 do if (unitM[v[i]][j]<>#0) and (unitM[v[i]][j]<>' ') then uY[i]:=uY[i]+unitM[v[i]][j]; J1[i]:=0; J2[i]:=2048; Y1[i]:=extOffset[v[i]]; if abs(extGain[v[i]])>1E-20 then Y2[i]:=10.0/extGain[v[i]]+extOffset[v[i]]; {writeln(Estr(extGain[v[i]],9));} end; typeFich:=2; tailleInfo:=1024; longdat:=roundL(nbEpisode*nbSample*2); OffTag:=512*roundL(TagInfo); seek(f,OffTag); blockread(f,nbtag,2,res); inc(offTag,2); SpaceTag:=4; end; lirePclamp:=true; end; function lireABF:boolean; type Pinteger=^integer; Psingle=^single; Plongint=^longint; var i:integer; w:longint; v:integer; periode1{,periode2}:float; ADCres:longint; ADCrange,ScaleF:float; ADCdiv:integer; p:PtabOctet; seizeBit:boolean; function Finteger(n:integer):integer; begin Finteger:=Pinteger(@p^[n])^; end; function Fsingle(n:integer):single; begin Fsingle:=Psingle(@p^[n])^; end; function Flong(n:integer):longint; begin Flong:=Plongint(@p^[n])^; end; function Fstring(n,l:integer):AnsiString; var st:string[255]; begin byte(st[0]):=l; move(p^[n],st[1],l); Fstring:=st; end; function numPhysique(n:integer):integer; { n de 0 ů 15 } begin numPhysique:=Finteger(410+n*2); end; begin p:=buf; lireABF:=false; if Fstring(0,4)<>'ABF ' then exit; TailleInfo:=512*Flong(40); w:=Finteger(8); Continu:= (w=1) or (w=3); nbvoie:=Finteger(120); nbpt:=Flong(138); if Continu then nbpt:=1000; uX:='ms '; Periode1:=Fsingle(122); {Periode2:=Fsingle(126);} i1:=0; i2:=nbpt; x1:=0; x2:=Periode1*nbPt*nbVoie*0.001; if Continu then begin uX:='sec'; X2:=x2/1000; end; ADCres:=Flong(252); SeizeBit:=(ADCres>2048); if ADCres>=32768 then ADCdiv:=2 else ADCdiv:=1; ADCrange:=Fsingle(244); for i:=1 to nbVoie do begin v:=numPhysique(i-1); uY[i]:=Fstring(602+v*8,8); J1[i]:=0; J2[i]:=ADCres div ADCdiv; Y1[i]:=Fsingle(986+v*4); ScaleF:=Fsingle(922+v*4)*Fsingle(730+v*4)*ADCdiv; if SeizeBit then scaleF:=scaleF/16; if scaleF<>0 then Y2[i]:=ADCrange/scaleF+Fsingle(986+v*4); end; typeFich:=7; longDat:=Flong(10)*2; OffTag:=512*Flong(44); nbtag:=Flong(48); SpaceTag:=64; lireABF:=true; end; procedure controle; var i:integer; begin if error<>0 then exit; if (nbvoie<1) or (nbvoie>6) then begin error:=2; exit; end; if (nbpt<1) then begin error:=3; exit; end; if (i1>=i2) or (x1>=x2) then begin error:=4; exit; end; for i:=1 to nbvoie do if not( (j1[i]<j2[i]) and (y1[i]<y2[i]) or (j2[i]<j1[i]) and (y2[i]<y1[i]) ) then begin { messageCentral(Istr(j1[i])+' '+Istr(j2[i])+' '+ Estr1(y1[i],15,5)+' '+Estr1(y2[i],15,5)); } error:=5; exit; end; end; begin getmem(buf,1024); fillchar(buf^,1024,0); blockread(f,buf^,1024,res); error:=0; if not lireAC then if not LirePclamp then if not LireABF then error:=1;; freemem(buf,1024); controle; {messageCentral('Error='+Istr(error));} end; function typeInfoFich.getDx:float; begin getDx:=(X2-X1)/(I2-I1); end; function typeInfoFich.getX0:float; begin getX0:=X1-I1*getDx; end; function typeInfoFich.getDy(n:integer):float; begin getDy:=(y2[n]-y1[n])/(j2[n]-j1[n]); end; function typeInfoFich.getY0(n:integer):float; begin getY0:=Y1[n]-J1[n]*getDy(n); end; function typeInfoFich.getTag(n:integer):longint; begin getTag:=0; end; end.
(* Category: SWAG Title: MATH ROUTINES Original name: 0015.PAS Description: PI1.PAS Author: SWAG SUPPORT TEAM Date: 05-28-93 13:50 *) Program CalcPI(input, output); { Not the most efficient Program I've ever written. Mostly it's quick and dirty. The infinite series is very effective converging very quickly. It's much better than Pi/4 = 1 - 1/3 + 1/5 - 1/7 ... which converges like molasses. } { Pi / 4 = 4 * (1/5 - 1/(3*5^3) + 1/(5*5^5) - 1/(7*5^7) + ...) - (1/239 - 1/(3*239^3) + 1/(5*239^5) - 1/(7*239^7) + ...) } {* Infinite series courtesy of Machin (1680 - 1752). I found it in my copy of Mathematics and the Imagination by Edward Kasner and James R. Newman (Simon and Schuster, New York 1940, p. 77) * } Uses Crt; Var Pi_Fourths, Pi : Double; Temp : Double; ct : Integer; num : Integer; Function Power(Number, Exponent : Integer) : double; Var ct : Integer; temp : double; begin temp := 1.00; For ct := 1 to Exponent DO temp := temp * number; Power := temp end; begin ClrScr; ct := 1; num := 1; Pi_Fourths := 0; While ct < 15 DO begin Temp := (1.0 / (Power(5, num) * num)) * 4; if ct MOD 2 = 1 then Pi_Fourths := Pi_Fourths + Temp ELSE Pi_Fourths := Pi_Fourths - Temp; Temp := 1.0 / (Power(239, num) * num); if ct MOD 2 = 1 then Pi_Fourths := Pi_Fourths - Temp ELSE Pi_Fourths := Pi_Fourths + Temp; ct := ct + 1; num := num + 2; end; Pi := Pi_Fourths * 4.0; Writeln( 'PI = ', Pi); end.
unit feli_constants; interface const configFilePath = 'ets.cfg.json'; logFilePath = 'ets.log'; chars = 'abcdefghijklmnopqrstuvqxyzABCDEFGHIJKLMNOPQRSTUVQXYZ1234567890_-'; lineSeparator = #13#10; eventsFilePath = 'database/events.json'; usersFilePath = 'database/users.json'; stackTraceDepthPath = 'stack_trace.txt'; implementation end.
//Connexion V1.1 // //Révision 2011/10/04 //Patrick Lafrance 2011/09/17 unit uniteConnexion; interface uses SysUtils, StrUtils, SocketUnit; type //Connexion TCP client ou serveur à une adresse et un port quelconque //Permet de recevoir ou envoyer une ligne de texte à la fois. //Il est important de terminer chaque ligne par un retour de chariot (#13#10) Connexion = class public const //Raccourci pour le retour de chariot CRLF = chr(13) + chr(10); //Crée une connexion client vers le serveur spécifié par l'adresse et le port // //@param uneAdresse L'adresse du serveur distant //@param unPort Le port sur lequel se connecter sur le serveur // //@raises Exception si la connexion ne peut être établie constructor create( uneAdresse : String; unPort : Integer ); overload; //Crée un objet Connexion serveur qui écoutera sur le port spécifié // //@param unPort Le port local sur lequel écouter les connection entrantes constructor create( unPort : Integer ); overload; //Destructeur par défaut. Ferme toutes les connexions existantes. destructor destroy; //Donne l'adresse de l'hôte distant lorsque connecté. Chaîne vide si la connexion //n'est pas établie // //@return L'adresse de l'hôte distant ou chaîne vide si la connexion n'est pas établie. function getAdresseDistante : String; //Lit une chaîne de caractère de l'ordinateur distant // //@param uneChaine La variable qui contiendra la chaîne reçue // //@raises Exception si la connexion ne permet pas de lire une chaîne procedure lireChaine (var uneChaine : String ); overload; //Lit une chaîne de caractère de l'ordinateur distant // //@return La chaîne reçue // //@raises Exception si la connexion ne permet pas de lire une chaîne function lireChaine : String; overload; //Envoie une chaîne de caractère à l'ordinateur distant // //@param uneChaine La chaîne à envoyer. Elle doit se terminer par un retour //de chariot (caractères 13 et 10) // //@raises Exception si la connexion ne permet pas d'écrire une chaîne procedure ecrireChaine ( uneChaine:String ); //Ferme la connexion. // //@raises Exception si la connexion ne peut être refermée procedure fermerConnexion; virtual; protected //Adresse du serveur distant adresse : String; //Port utilisé par la connexion (autant serveur que client) port : Integer; private //Tampon pour recevoir les messages buffer : String; //Connexion client clientSocket : TClientSocket; //Connexion serveur serveurSocket: TServerSocket; end; implementation constructor Connexion.create( uneAdresse : String; unPort : Integer ); begin if (unPort<1) or (unPort>65535) then raise Exception.Create('Numéro de port invalide'); port := unPort; adresse := uneAdresse; clientSocket:=TClientSocket.create; clientSocket.Connect(uneAdresse, unPort); end; constructor Connexion.create( unPort : Integer ); begin if (unPort<1) or (unPort>65535) then raise Exception.Create('Numéro de port invalide'); port := unPort; serveurSocket:=TServerSocket.create; try serveurSocket.listen(unPort); except on e:Exception do raise Exception.Create('Impossible d''ouvrir le port '+intToStr(unPort)+'.'); end; end; destructor Connexion.destroy; begin serveurSocket.destroy; if not (clientSocket = nil) then clientSocket.destroy; end; function Connexion.getAdresseDistante : String; begin result := ''; if serveurSocket <> nil then result := clientSocket.RemoteAddress end; procedure Connexion.lireChaine( var uneChaine : String ); var longueur:Integer; errorCode : Integer; begin //Si le buffer n'est pas vide, on doit d'abord le vider if (length(buffer) = 0) then begin //S'il n'y a pas de client connecté, attendre une connexion if (clientSocket=nil) then if(adresse<>'') then raise Exception.create('Connexion non établie') else begin clientSocket:=serveurSocket.accept; end; //Initialise le buffer setlength(buffer,0); repeat begin //Lit les données longueur := clientSocket.Receivelength; if longueur>0 then buffer:=buffer + clientSocket.ReceiveString end; //Jusqu'à la fin d'une ligne // until ansiRightStr( buffer, 2 ) = CRLF; until (length(buffer) > 0) and (longueur = 0); end; //Extrait la première ligne terminée par un retour de chariot du buffer uneChaine := buffer; if ansiPos( chr(13), buffer) > 0 then begin //S''il en reste, le conserve dans le buffer buffer := ansiMidStr( uneChaine, ansiPos( CRLF, uneChaine) + 2, length( uneChaine)); uneChaine := AnsiLeftStr( uneChaine, ansiPos( CRLF, uneChaine)-1 ); end else buffer := ''; end; function Connexion.lireChaine : String; var chaine : String; begin lireChaine( chaine ); result := chaine; end; procedure Connexion.ecrireChaine( uneChaine:String ); begin if clientSocket = nil then if adresse <> '' then raise Exception.create('Connexion non établie') else begin clientSocket:=TClientSocket.create; clientSocket.Connect(adresse, port); end; clientSocket.SendString(uneChaine); end; procedure Connexion.fermerConnexion; begin if (clientSocket=nil) or (not clientSocket.Connected) then exit; clientSocket.Disconnect; clientSocket.destroy; clientSocket := nil; buffer := ''; end; end.
namespace UINavigationController; interface uses UIKit; type [IBObject] AppDelegate = class(IUIApplicationDelegate) private public property window: UIWindow; method application(application: UIApplication) didFinishLaunchingWithOptions(launchOptions: NSDictionary): Boolean; method applicationWillResignActive(application: UIApplication); method applicationDidEnterBackground(application: UIApplication); method applicationWillEnterForeground(application: UIApplication); method applicationDidBecomeActive(application: UIApplication); method applicationWillTerminate(application: UIApplication); end; implementation method AppDelegate.application(application: UIApplication) didFinishLaunchingWithOptions(launchOptions: NSDictionary): Boolean; begin window := new UIWindow withFrame(UIScreen.mainScreen.bounds); window.rootViewController := new UINavigationController withRootViewController(new RootViewController); window.makeKeyAndVisible; result := true; end; method AppDelegate.applicationWillResignActive(application: UIApplication); begin // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. end; method AppDelegate.applicationDidEnterBackground(application: UIApplication); begin // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. end; method AppDelegate.applicationWillEnterForeground(application: UIApplication); begin // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. end; method AppDelegate.applicationDidBecomeActive(application: UIApplication); begin // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. end; method AppDelegate.applicationWillTerminate(application: UIApplication); begin // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. end; end.
{------------------------------------ 功能说明:对象工厂接口,对象工程通过此接口来创建对象 创建日期:2014/08/12 作者:mx 版权:mx -------------------------------------} unit uFactoryFormIntf; interface uses Classes, Controls, Forms, uParamObject, uDefCom; type //业务窗体接口 IFormIntf = interface ['{2237D50E-2D63-4FF3-8E42-96AD31403C02}'] procedure CreateParamList(AOwner: TComponent; AParam: TParamObject); procedure FrmShow; function FrmShowModal: Integer; function FrmShowStyle: TShowStyle;//窗体显示的类型,是否modal, 或者在销毁中 procedure FrmFree; procedure FrmClose; procedure ResizeFrm(AParentForm: TWinControl);//窗体容器大小发生改变 function GetForm: TForm; end; //业务窗体调度控制接口 IFromFactory = interface ['{084505D9-26AA-4265-8CDB-03D90F50FF33}'] function GetFormAsFromName(AFromName: string; AParam: TParamObject; AOwner: TComponent): IFormIntf; function GetFormAsFromNo(AFromNo: Integer; AParam: TParamObject; AOwner: TComponent): IFormIntf; end; implementation end.
unit ibSHRegisterActions; interface uses SysUtils, Classes, Controls, Dialogs, StrUtils, SHDesignIntf, ibSHDesignIntf; type IibSHRegisterServerAction = interface ['{596F42B0-5C53-482C-9A2A-540ED742978F}'] end; IibSHRegisterDatabaseAction = interface ['{37FB7438-3281-4ECD-90FD-84EA7E63A9B4}'] end; IibSHCloneServerAction = interface ['{A574050D-5B30-4B4E-AD3B-D706294D1748}'] end; IibSHCloneDatabaseAction = interface ['{6BD1B818-D74A-4834-84D1-DF9612D4644E}'] end; IibSHUnregisterServerAction = interface ['{9DE62BCE-0AA6-4A11-BBFF-7CD0C155B4E0}'] end; IibSHUnregisterDatabaseAction = interface ['{CDDA0495-8C74-46F6-988D-8A804FABC2E4}'] end; IibSHCreateDatabaseAction = interface ['{5D62554E-3032-40AD-8615-EBB5C2857772}'] end; IibSHDropDatabaseAction = interface ['{A7DA1734-9C23-45A8-8BD6-903CD6C07115}'] end; IibSHAliasInfoServerAction = interface ['{B16D8420-05AA-4B75-9852-8561FFCBF36D}'] end; IibSHAliasInfoDatabaseAction = interface ['{BEE9C039-60E1-4640-AAEB-475168E9B4AD}'] end; // Server Editor IibSHServerEditorRegisterDatabase = interface ['{F8866A8C-FEF3-4059-8153-605164E39E20}'] end; IibSHServerEditorCreateDatabase = interface ['{772D970C-4AF3-4C7D-91AC-E0F9D8202004}'] end; IibSHServerEditorClone = interface ['{A35CBB41-2ADA-4CC0-9276-D62796F91149}'] end; IibSHServerEditorUnregister = interface ['{9F442F2B-54DE-4AF1-8342-D6B9C5348798}'] end; IibSHServerEditorTestConnect = interface ['{7D8EA024-138B-4F95-88D6-15A2C291EBE6}'] end; IibSHServerEditorRegInfo = interface ['{E388BECA-1A91-4937-8CD0-1DC0E50C446D}'] end; // Database Editor IibSHDatabaseEditorConnect = interface ['{95A34CAC-5A56-4B7D-B548-AA21B9056020}'] end; IibSHDatabaseEditorReconnect = interface ['{EBFC98BA-7ED8-4508-9828-628C5B951E2B}'] end; IibSHDatabaseEditorDisconnect = interface ['{F67A9C92-79D2-4173-BC8C-8F714AA268F3}'] end; IibSHDatabaseEditorRefresh = interface ['{264901AA-82A9-41DB-A4FB-CF8D40AE261E}'] end; IibSHDatabaseEditorActiveUsers = interface ['{8B597B1A-5881-4647-94E1-B694E095ED5E}'] end; IibSHDatabaseEditorOnline = interface ['{6A793041-083C-4896-8687-10E206185EE5}'] end; IibSHDatabaseEditorShutdown = interface ['{DD31AA1F-0314-43B5-AAF8-4E15823E3498}'] end; IibSHDatabaseEditorClone = interface ['{3F9EDB78-9E15-471C-8C69-51EAE5C7DF34}'] end; IibSHDatabaseEditorUnregister = interface ['{6C8D988C-B50D-4991-96F5-D918B063F7D9}'] end; IibSHDatabaseEditorDrop = interface ['{EEB974CB-866B-4CB6-8A2D-CE149952868C}'] end; IibSHDatabaseEditorTestConnect = interface ['{9A0A489D-9D42-4E8F-A68E-15BD179485A6}'] end; IibSHDatabaseEditorRegInfo = interface ['{74ED32E4-9921-4977-A0E5-F69176693B1D}'] end; TibSHCustomRegAction = class(TSHAction) protected procedure CloneAssignServer(AClone, ATarget: TSHComponent); procedure CloneAssignDatabase(AClone, ATarget: TSHComponent); procedure RegisterServer(AClone: TSHComponent); procedure RegisterDatabase(AClone: TSHComponent); procedure UnregisterServer; procedure UnregisterDatabase; procedure CreateDatabase; procedure DropDatabase; procedure TestConnect; procedure ShowServerAliasInfo; procedure ShowDatabaseAliasInfo; public constructor Create(AOwner: TComponent); override; function SupportComponent(const AClassIID: TGUID): Boolean; override; procedure EventExecute(Sender: TObject); override; procedure EventHint(var HintStr: String; var CanShow: Boolean); override; procedure EventUpdate(Sender: TObject); override; end; TibSHRegisterSeparatorAction = class(TibSHCustomRegAction) end; TibSHRegisterServerAction = class(TibSHCustomRegAction, IibSHRegisterServerAction) end; TibSHRegisterDatabaseAction = class(TibSHCustomRegAction, IibSHRegisterDatabaseAction) end; TibSHCloneServerAction = class(TibSHCustomRegAction, IibSHCloneServerAction) end; TibSHCloneDatabaseAction = class(TibSHCustomRegAction, IibSHCloneDatabaseAction) end; TibSHUnregisterServerAction = class(TibSHCustomRegAction, IibSHUnregisterServerAction) end; TibSHUnregisterDatabaseAction = class(TibSHCustomRegAction, IibSHUnregisterDatabaseAction) end; TibSHCreateDatabaseAction = class(TibSHCustomRegAction, IibSHCreateDatabaseAction) end; TibSHDropDatabaseAction = class(TibSHCustomRegAction, IibSHDropDatabaseAction) end; TibSHAliasInfoServerAction = class(TibSHCustomRegAction, IibSHAliasInfoServerAction) end; TibSHAliasInfoDatabaseAction = class(TibSHCustomRegAction, IibSHAliasInfoDatabaseAction) end; TibSHCustomServerRegEditorAction = class(TibSHCustomRegAction) public constructor Create(AOwner: TComponent); override; function SupportComponent(const AClassIID: TGUID): Boolean; override; procedure EventExecute(Sender: TObject); override; procedure EventHint(var HintStr: String; var CanShow: Boolean); override; procedure EventUpdate(Sender: TObject); override; end; TibSHServerSeparatorEditorAction = class(TibSHCustomServerRegEditorAction) end; TibSHCustomDatabaseRegEditorAction = class(TibSHCustomRegAction) private procedure ShowActiveUsers; procedure DatabaseOnline; procedure DatabaseShutdown; public constructor Create(AOwner: TComponent); override; function SupportComponent(const AClassIID: TGUID): Boolean; override; procedure EventExecute(Sender: TObject); override; procedure EventHint(var HintStr: String; var CanShow: Boolean); override; procedure EventUpdate(Sender: TObject); override; end; TibSHDatabaseSeparatorEditorAction = class(TibSHCustomDatabaseRegEditorAction) end; // Server Editor TibSHServerEditorRegisterDatabase = class(TibSHCustomServerRegEditorAction, IibSHServerEditorRegisterDatabase) end; TibSHServerEditorCreateDatabase = class(TibSHCustomServerRegEditorAction, IibSHServerEditorCreateDatabase) end; TibSHServerEditorClone = class(TibSHCustomServerRegEditorAction, IibSHServerEditorClone) end; TibSHServerEditorUnregister = class(TibSHCustomServerRegEditorAction, IibSHServerEditorUnregister) end; TibSHServerEditorTestConnect = class(TibSHCustomServerRegEditorAction, IibSHServerEditorTestConnect) end; TibSHServerEditorRegInfo = class(TibSHCustomServerRegEditorAction, IibSHServerEditorRegInfo) end; // Database Editor TibSHDatabaseEditorConnect = class(TibSHCustomDatabaseRegEditorAction, IibSHDatabaseEditorConnect) end; TibSHDatabaseEditorReconnect = class(TibSHCustomDatabaseRegEditorAction, IibSHDatabaseEditorReconnect) end; TibSHDatabaseEditorDisconnect = class(TibSHCustomDatabaseRegEditorAction, IibSHDatabaseEditorDisconnect) end; TibSHDatabaseEditorRefresh = class(TibSHCustomDatabaseRegEditorAction, IibSHDatabaseEditorRefresh) end; TibSHDatabaseEditorActiveUsers = class(TibSHCustomDatabaseRegEditorAction, IibSHDatabaseEditorActiveUsers) end; TibSHDatabaseEditorOnline = class(TibSHCustomDatabaseRegEditorAction, IibSHDatabaseEditorOnline) end; TibSHDatabaseEditorShutdown = class(TibSHCustomDatabaseRegEditorAction, IibSHDatabaseEditorShutdown) end; TibSHDatabaseEditorClone = class(TibSHCustomDatabaseRegEditorAction, IibSHDatabaseEditorClone) end; TibSHDatabaseEditorUnregister = class(TibSHCustomDatabaseRegEditorAction, IibSHDatabaseEditorUnregister) end; TibSHDatabaseEditorDrop = class(TibSHCustomDatabaseRegEditorAction, IibSHDatabaseEditorDrop) end; TibSHDatabaseEditorTestConnect = class(TibSHCustomDatabaseRegEditorAction, IibSHDatabaseEditorTestConnect) end; TibSHDatabaseEditorRegInfo = class(TibSHCustomDatabaseRegEditorAction, IibSHDatabaseEditorRegInfo) end; implementation uses ibSHMessages, ibSHConsts, ibSHValues; { TibSHCustomRegAction } constructor TibSHCustomRegAction.Create(AOwner: TComponent); begin inherited Create(AOwner); FCallType := actCallRegister; Caption := '-'; // separator if Supports(Self, IibSHRegisterServerAction) then Caption := Format('%s', ['Register Server']); if Supports(Self, IibSHRegisterDatabaseAction) then Caption := Format('%s', ['Register Database']); if Supports(Self, IibSHCloneServerAction) then Caption := Format('%s', ['Clone Server']); if Supports(Self, IibSHCloneDatabaseAction) then Caption := Format('%s', ['Clone Database']); if Supports(Self, IibSHUnregisterServerAction) then Caption := Format('%s', ['Unregister Server']); if Supports(Self, IibSHUnregisterDatabaseAction) then Caption := Format('%s', ['Unregister Database']); if Supports(Self, IibSHCreateDatabaseAction) then Caption := Format('%s', ['Create Database']); if Supports(Self, IibSHDropDatabaseAction) then Caption := Format('%s', ['Drop Database']); if Supports(Self, IibSHAliasInfoServerAction) then Caption := Format('%s', ['View Server Alias Info...']); if Supports(Self, IibSHAliasInfoDatabaseAction) then Caption := Format('%s', ['View Database Alias Info...']); end; function TibSHCustomRegAction.SupportComponent(const AClassIID: TGUID): Boolean; begin Result := IsEqualGUID(IibSHBranch, AClassIID) or IsEqualGUID(IfbSHBranch, AClassIID); end; procedure TibSHCustomRegAction.CloneAssignServer(AClone, ATarget: TSHComponent); begin (ATarget as IibSHServer).Host := (AClone as IibSHServer).Host; (ATarget as IibSHServer).Alias := Format('%s CLONE', [(AClone as IibSHServer).Alias]); (ATarget as IibSHServer).Version := (AClone as IibSHServer).Version; (ATarget as IibSHServer).LongMetadataNames := (AClone as IibSHServer).LongMetadataNames; (ATarget as IibSHServer).ClientLibrary := (AClone as IibSHServer).ClientLibrary; (ATarget as IibSHServer).Protocol := (AClone as IibSHServer).Protocol; (ATarget as IibSHServer).Port := (AClone as IibSHServer).Port; (ATarget as IibSHServer).SecurityDatabase := (AClone as IibSHServer).SecurityDatabase; (ATarget as IibSHServer).UserName := (AClone as IibSHServer).UserName; (ATarget as IibSHServer).Password := (AClone as IibSHServer).Password; (ATarget as IibSHServer).Role := (AClone as IibSHServer).Role; (ATarget as IibSHServer).LoginPrompt := (AClone as IibSHServer).LoginPrompt; (ATarget as IibSHServer).Description := (AClone as IibSHServer).Description; end; procedure TibSHCustomRegAction.CloneAssignDatabase(AClone, ATarget: TSHComponent); begin (ATarget as IibSHDatabase).OwnerIID := (AClone as IibSHDatabase).OwnerIID; (ATarget as IibSHDatabase).Database := (AClone as IibSHDatabase).Database; (ATarget as IibSHDatabase).Alias := Format('%s CLONE ', [(AClone as IibSHDatabase).Alias]); (ATarget as IibSHDatabase).PageSize := (AClone as IibSHDatabase).PageSize; (ATarget as IibSHDatabase).Charset := (AClone as IibSHDatabase).Charset; (ATarget as IibSHDatabase).SQLDialect := (AClone as IibSHDatabase).SQLDialect; (ATarget as IibSHDatabase).CapitalizeNames := (AClone as IibSHDatabase).CapitalizeNames; (ATarget as IibSHDatabase).AdditionalConnectParams.Assign((AClone as IibSHDatabase).AdditionalConnectParams); (ATarget as IibSHDatabase).UserName := (AClone as IibSHDatabase).UserName; (ATarget as IibSHDatabase).Password := (AClone as IibSHDatabase).Password; (ATarget as IibSHDatabase).Role := (AClone as IibSHDatabase).Role; (ATarget as IibSHDatabase).LoginPrompt := (AClone as IibSHDatabase).LoginPrompt; (ATarget as IibSHDatabase).Description := (AClone as IibSHDatabase).Description; // TODO DatabaseAliasOptions ? end; procedure TibSHCustomRegAction.RegisterServer(AClone: TSHComponent); var Connection: TSHComponent; begin Connection := nil; Connection := Designer.GetComponent(IibSHServer).Create(nil); if Assigned(Connection) then begin Connection.OwnerIID := Designer.CurrentBranch.InstanceIID; if Assigned(AClone) then CloneAssignServer(AClone, Connection); Connection.Tag := 1; // rtServer if IsPositiveResult(Designer.ShowModal(Connection, SCallRegister)) then begin Designer.RegisterConnection(Connection); (Connection as ISHDataRootDirectory).CreateDirectory((Connection as ISHDataRootDirectory).DataRootDirectory); if Connection.Tag = 5 then RegisterDatabase(nil); end else FreeAndNil(Connection); end; if Assigned(Connection) then Connection.Tag := 0; end; procedure TibSHCustomRegAction.RegisterDatabase(AClone: TSHComponent); var Connection: TSHComponent; begin Connection := nil; if Assigned(AClone) and (AClone.Tag = 5) then Connection := AClone else Connection := Designer.GetComponent(IibSHDatabase).Create(nil); if Assigned(Connection) then begin if Assigned(AClone) and (AClone <> Connection) then CloneAssignDatabase(AClone, Connection) else if Assigned(Designer.CurrentServer) then Connection.OwnerIID := Designer.CurrentServer.InstanceIID; Connection.Tag := 2; // rtDatabase if IsPositiveResult(Designer.ShowModal(Connection, SCallRegister)) then begin Designer.RegisterConnection(Connection); (Connection as ISHDataRootDirectory).CreateDirectory((Connection as ISHDataRootDirectory).DataRootDirectory); if Connection.Tag = 5 then Designer.ConnectTo(Connection); end else FreeAndNil(Connection); end; if Assigned(Connection) then Connection.Tag := 0; end; procedure TibSHCustomRegAction.UnregisterServer; var Connection: TSHComponent; begin Connection := Designer.CurrentServer; if Designer.ShowMsg(Format(SUnregisterServer, [Connection.Caption]), mtConfirmation) then begin if Designer.UnregisterConnection(Connection) then begin (Connection as ISHDataRootDirectory).DeleteDirectory((Connection as ISHDataRootDirectory).DataRootDirectory); Designer.DestroyConnection(Connection); end; end; end; procedure TibSHCustomRegAction.UnregisterDatabase; var Connection: TSHComponent; begin Connection := Designer.CurrentDatabase; if Designer.ShowMsg(Format(SUnregisterDatabase, [Connection.Caption]), mtConfirmation) then begin if Designer.UnregisterConnection(Connection) then begin (Connection as ISHDataRootDirectory).DeleteDirectory((Connection as ISHDataRootDirectory).DataRootDirectory); Designer.DestroyConnection(Connection); end; end; end; procedure TibSHCustomRegAction.CreateDatabase; var Connection: TSHComponent; begin Connection := nil; Connection := Designer.GetComponent(IibSHDatabase).Create(nil); if Assigned(Connection) then begin if Assigned(Designer.CurrentServer) then Connection.OwnerIID := Designer.CurrentServer.InstanceIID; Connection.Tag := 3; // rtCreate Connection.MakePropertyVisible('PageSize'); Connection.MakePropertyVisible('SQLDialect'); Connection.MakePropertyInvisible('Alias'); Connection.MakePropertyInvisible('Role'); Connection.MakePropertyInvisible('LoginPrompt'); Connection.MakePropertyInvisible('AdditionalConnectParams'); Connection.MakePropertyInvisible('CapitalizeNames'); Connection.MakePropertyInvisible('Description'); Connection.MakePropertyInvisible('DatabaseAliasOptions'); if IsPositiveResult(Designer.ShowModal(Connection, SCallRegister)) then begin (Connection as IibSHDatabase).CreateDatabase; if Connection.Tag = 5 then begin Connection.MakePropertyInvisible('PageSize'); Connection.MakePropertyInvisible('SQLDialect'); Connection.MakePropertyVisible('Alias'); Connection.MakePropertyVisible('Role'); Connection.MakePropertyVisible('LoginPrompt'); Connection.MakePropertyVisible('AdditionalConnectParams'); Connection.MakePropertyVisible('CapitalizeNames'); Connection.MakePropertyVisible('Description'); Connection.MakePropertyVisible('DatabaseAliasOptions'); RegisterDatabase(Connection); end else FreeAndNil(Connection); end else FreeAndNil(Connection); end; end; procedure TibSHCustomRegAction.DropDatabase; var Connection: TSHComponent; begin Connection := Designer.CurrentDatabase; if Designer.ShowMsg(Format(SDropDatabase, [Connection.Caption]), mtConfirmation) then begin (Connection as IibSHDatabase).DropDatabase; if Designer.UnregisterConnection(Connection) then begin (Connection as ISHDataRootDirectory).DeleteDirectory((Connection as ISHDataRootDirectory).DataRootDirectory); Designer.DestroyConnection(Connection); end; end; end; procedure TibSHCustomRegAction.TestConnect; var TestConnectionIntf: ISHTestConnection; begin TestConnectionIntf := nil; if Self.SupportComponent(IibSHServer) then Supports(Designer.CurrentServer, ISHTestConnection, TestConnectionIntf); if Self.SupportComponent(IibSHDatabase) then Supports(Designer.CurrentDatabase, ISHTestConnection, TestConnectionIntf); if Assigned(TestConnectionIntf) and TestConnectionIntf.CanTestConnection then TestConnectionIntf.TestConnection; end; procedure TibSHCustomRegAction.ShowServerAliasInfo; var RegistrationIntf: ISHRegistration; begin Supports(Designer.CurrentServer, ISHRegistration, RegistrationIntf); if Assigned(RegistrationIntf) and RegistrationIntf.CanShowRegistrationInfo then RegistrationIntf.ShowRegistrationInfo; end; procedure TibSHCustomRegAction.ShowDatabaseAliasInfo; var RegistrationIntf: ISHRegistration; begin Supports(Designer.CurrentDatabase, ISHRegistration, RegistrationIntf); if Assigned(RegistrationIntf) and RegistrationIntf.CanShowRegistrationInfo then RegistrationIntf.ShowRegistrationInfo; end; procedure TibSHCustomRegAction.EventExecute(Sender: TObject); begin if Supports(Self, IibSHRegisterServerAction) then RegisterServer(nil); if Supports(Self, IibSHRegisterDatabaseAction) then RegisterDatabase(nil); if Supports(Self, IibSHCloneServerAction) then RegisterServer(Designer.CurrentServer); if Supports(Self, IibSHCloneDatabaseAction) then RegisterDatabase(Designer.CurrentDatabase); if Supports(Self, IibSHUnregisterServerAction) then UnregisterServer; if Supports(Self, IibSHUnregisterDatabaseAction) then UnregisterDatabase; if Supports(Self, IibSHCreateDatabaseAction) then CreateDatabase; if Supports(Self, IibSHDropDatabaseAction) then DropDatabase; if Supports(Self, IibSHAliasInfoServerAction) then ShowServerAliasInfo; if Supports(Self, IibSHAliasInfoDatabaseAction) then ShowDatabaseAliasInfo; Designer.SaveRegisteredConnectionInfo; end; procedure TibSHCustomRegAction.EventHint(var HintStr: String; var CanShow: Boolean); begin end; procedure TibSHCustomRegAction.EventUpdate(Sender: TObject); begin if Supports(Self, IibSHRegisterServerAction) then begin Enabled := True; FDefault := Designer.ServerCount = 0; end; if Supports(Self, IibSHRegisterDatabaseAction) then begin Enabled := Designer.ServerCount > 0; FDefault := Enabled; end; if Supports(Self, IibSHCloneServerAction) then Enabled := Assigned(Designer.CurrentServer); if Supports(Self, IibSHCloneDatabaseAction) then Enabled := Assigned(Designer.CurrentDatabase); if Supports(Self, IibSHUnregisterServerAction) then Enabled := Assigned(Designer.CurrentServer) and not Designer.CurrentServerInUse; if Supports(Self, IibSHUnregisterDatabaseAction) then Enabled := Assigned(Designer.CurrentDatabase) and not Designer.CurrentDatabaseInUse; if Supports(Self, IibSHCreateDatabaseAction) then Enabled := Designer.ServerCount > 0; if Supports(Self, IibSHDropDatabaseAction) then Enabled := Assigned(Designer.CurrentDatabase) and not Designer.CurrentDatabaseInUse; if Supports(Self, IibSHAliasInfoServerAction) then begin Enabled := Assigned(Designer.CurrentServer); if Assigned(Designer.CurrentServer) then begin if Designer.CurrentServerInUse then Caption := Format('%s', ['View Server Alias Info...']) else Caption := Format('%s', ['Edit Server Alias Info...']); end; end; if Supports(Self, IibSHAliasInfoDatabaseAction) then begin Enabled := Assigned(Designer.CurrentDatabase); if Assigned(Designer.CurrentDatabase) then begin if Designer.CurrentDatabaseInUse then Caption := Format('%s', ['View Database Alias Info...']) else Caption := Format('%s', ['Edit Database Alias Info...']); end; end; end; { TibSHCustomServerRegEditorAction } constructor TibSHCustomServerRegEditorAction.Create(AOwner: TComponent); begin inherited Create(AOwner); FCallType := actCallEditor; if Supports(Self, IibSHServerEditorRegisterDatabase) then Caption := Format('%s', ['Register Database']); if Supports(Self, IibSHServerEditorCreateDatabase) then Caption := Format('%s', ['Create Database']); if Supports(Self, IibSHServerEditorClone) then Caption := Format('%s', ['Clone Alias...']); if Supports(Self, IibSHServerEditorUnregister) then Caption := Format('%s', ['Unregister']); if Supports(Self, IibSHServerEditorTestConnect) then Caption := Format('%s', ['Test Connect']); if Supports(Self, IibSHServerEditorRegInfo) then Caption := Format('%s', ['Show Alias Info...']); end; function TibSHCustomServerRegEditorAction.SupportComponent(const AClassIID: TGUID): Boolean; begin Result := IsEqualGUID(IibSHServer, AClassIID); end; procedure TibSHCustomServerRegEditorAction.EventExecute(Sender: TObject); begin if Supports(Self, IibSHServerEditorRegisterDatabase) then RegisterDatabase(nil); if Supports(Self, IibSHServerEditorCreateDatabase) then CreateDatabase; if Supports(Self, IibSHServerEditorClone) then RegisterServer(Designer.CurrentServer); if Supports(Self, IibSHServerEditorUnregister) then UnregisterServer; if Supports(Self, IibSHServerEditorTestConnect) then TestConnect; if Supports(Self, IibSHServerEditorRegInfo) then ShowServerAliasInfo; end; procedure TibSHCustomServerRegEditorAction.EventHint(var HintStr: String; var CanShow: Boolean); begin end; procedure TibSHCustomServerRegEditorAction.EventUpdate(Sender: TObject); begin if Supports(Self, IibSHServerEditorRegisterDatabase) then ; if Supports(Self, IibSHServerEditorCreateDatabase) then ; if Supports(Self, IibSHServerEditorClone) then ; if Supports(Self, IibSHServerEditorUnregister) then Visible := Assigned(Designer.CurrentServer) and not Designer.CurrentServerInUse; if Supports(Self, IibSHServerEditorTestConnect) then Visible := Assigned(Designer.CurrentServer) and not Designer.CurrentServerInUse; if Supports(Self, IibSHServerEditorRegInfo) then begin if Assigned(Designer.CurrentServer) then begin if Designer.CurrentServerInUse then Caption := Format('%s', ['View Alias Info...']) else Caption := Format('%s', ['Edit Alias Info...']); end; end; end; { TibSHCustomDatabaseRegEditorAction } constructor TibSHCustomDatabaseRegEditorAction.Create(AOwner: TComponent); begin inherited Create(AOwner); FCallType := actCallEditor; if Supports(Self, IibSHDatabaseEditorConnect) then Caption := Format('%s', ['Connect']); if Supports(Self, IibSHDatabaseEditorReconnect) then Caption := Format('%s', ['Reconnect']); if Supports(Self, IibSHDatabaseEditorDisconnect) then Caption := Format('%s', ['Disconnect']); if Supports(Self, IibSHDatabaseEditorRefresh) then Caption := Format('%s', ['Refresh']); if Supports(Self, IibSHDatabaseEditorActiveUsers) then Caption := Format('%s', ['Active Users...']); if Supports(Self, IibSHDatabaseEditorOnline) then Caption := Format('%s', ['Online']); if Supports(Self, IibSHDatabaseEditorShutdown) then Caption := Format('%s', ['Shutdown']); if Supports(Self, IibSHDatabaseEditorClone) then Caption := Format('%s', ['Clone Alias...']); if Supports(Self, IibSHDatabaseEditorUnregister) then Caption := Format('%s', ['Unregister']); if Supports(Self, IibSHDatabaseEditorDrop) then Caption := Format('%s', ['Drop']); if Supports(Self, IibSHDatabaseEditorTestConnect) then Caption := Format('%s', ['Test Connect']); if Supports(Self, IibSHDatabaseEditorRegInfo) then Caption := Format('%s', ['Show Alias Info...']); end; function TibSHCustomDatabaseRegEditorAction.SupportComponent(const AClassIID: TGUID): Boolean; begin Result := IsEqualGUID(IibSHDatabase, AClassIID); end; procedure TibSHCustomDatabaseRegEditorAction.ShowActiveUsers; begin if Assigned(Designer.CurrentDatabase) then Designer.ShowModal(Designer.CurrentDatabase, SCallActiveUsers); end; procedure TibSHCustomDatabaseRegEditorAction.DatabaseOnline; begin Designer.UnderConstruction; end; procedure TibSHCustomDatabaseRegEditorAction.DatabaseShutdown; begin Designer.UnderConstruction; end; procedure TibSHCustomDatabaseRegEditorAction.EventExecute(Sender: TObject); begin if Supports(Self, IibSHDatabaseEditorConnect) then Designer.ConnectTo(Designer.CurrentDatabase); if Supports(Self, IibSHDatabaseEditorReconnect) then Designer.ReconnectTo(Designer.CurrentDatabase); if Supports(Self, IibSHDatabaseEditorDisconnect) then Designer.DisconnectFrom(Designer.CurrentDatabase); if Supports(Self, IibSHDatabaseEditorRefresh) then Designer.RefreshConnection(Designer.CurrentDatabase); if Supports(Self, IibSHDatabaseEditorActiveUsers) then ShowActiveUsers; if Supports(Self, IibSHDatabaseEditorOnline) then DatabaseOnline; if Supports(Self, IibSHDatabaseEditorShutdown) then DatabaseShutdown; if Supports(Self, IibSHDatabaseEditorClone) then RegisterDatabase(Designer.CurrentDatabase); if Supports(Self, IibSHDatabaseEditorUnregister) then UnregisterDatabase; if Supports(Self, IibSHDatabaseEditorDrop) then DropDatabase; if Supports(Self, IibSHDatabaseEditorTestConnect) then TestConnect; if Supports(Self, IibSHDatabaseEditorRegInfo) then ShowDatabaseAliasInfo; end; procedure TibSHCustomDatabaseRegEditorAction.EventHint(var HintStr: String; var CanShow: Boolean); begin end; procedure TibSHCustomDatabaseRegEditorAction.EventUpdate(Sender: TObject); begin if Supports(Self, IibSHDatabaseEditorConnect) then begin Visible := Assigned(Designer.CurrentDatabase) and not Designer.CurrentDatabaseInUse; FDefault := Visible; end; if Supports(Self, IibSHDatabaseEditorReconnect) then Visible := Assigned(Designer.CurrentDatabase) and Designer.CurrentDatabaseInUse; if Supports(Self, IibSHDatabaseEditorDisconnect) then begin Visible := Assigned(Designer.CurrentDatabase) and Designer.CurrentDatabaseInUse; FDefault := Visible; end; if Supports(Self, IibSHDatabaseEditorRefresh) then Visible := Assigned(Designer.CurrentDatabase) and Designer.CurrentDatabaseInUse; if Supports(Self, IibSHDatabaseEditorActiveUsers) then Visible := Assigned(Designer.CurrentDatabase) and Designer.CurrentDatabaseInUse; if Supports(Self, IibSHDatabaseEditorOnline) then Visible := Assigned(Designer.CurrentDatabase) and not Designer.CurrentDatabaseInUse; if Supports(Self, IibSHDatabaseEditorShutdown) then Visible := Assigned(Designer.CurrentDatabase) and not Designer.CurrentDatabaseInUse; if Supports(Self, IibSHDatabaseEditorClone) then ; if Supports(Self, IibSHDatabaseEditorUnregister) then Visible := Assigned(Designer.CurrentDatabase) and not Designer.CurrentDatabaseInUse; if Supports(Self, IibSHDatabaseEditorDrop) then Visible := Assigned(Designer.CurrentDatabase) and not Designer.CurrentDatabaseInUse; if Supports(Self, IibSHDatabaseEditorTestConnect) then Visible := Assigned(Designer.CurrentDatabase) and not Designer.CurrentDatabaseInUse; if Supports(Self, IibSHDatabaseEditorRegInfo) then begin if Assigned(Designer.CurrentDatabase) then begin if Designer.CurrentDatabaseInUse then Caption := Format('%s', ['View Alias Info...']) else Caption := Format('%s', ['Edit Alias Info...']); end; end; end; end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { } { Copyright (c) 1997, 1999 Inprise Corporation } { } {*******************************************************} unit bdeconst; interface resourcestring SAutoSessionExclusive = 'Não foi possível permitir a propriedade de AutoSessionName com mais de uma sessão em um formulário ou em um dado-módulo'; SAutoSessionExists = 'Não foi possível adicionar uma sessão ao formulário ou ao dado-módulo quando a sessão '' %s'' ainda tiver AutoSessionName permitido'; SAutoSessionActive = 'Não foi possível modificar a SessionName quando o AutoSessionName for permitido'; SDuplicateDatabaseName = 'Nome da tabela ''%s'' duplicado'; SDuplicateSessionName = 'Nome da seção ''%s'' duplicado'; SInvalidSessionName = 'Nome da seção ''%s'' inválido'; SDatabaseNameMissing = 'Nome da seção ausente'; SSessionNameMissing = 'Nome da seção ausente'; SDatabaseOpen = 'Não é possível executar esta operação em um banco de dados aberto'; SDatabaseClosed = 'Não é possível executar esta operação em um banco de dados fechado'; SDatabaseHandleSet = 'Handle de banco de dados pertence a uma sessão diferente'; SSessionActive = 'Não é possível executar esta operação em uma sessão ativa'; SHandleError = 'Erro ao criar handle do cursor'; SInvalidFloatField = 'Não é possível converter o campo ''%s'' para um valor de ponto flutuante'; SInvalidIntegerField = 'Não é possível converter o campo ''%s'' para um valor inteiro'; STableMismatch = 'Tabelas fonte e destino são incompatíveis'; SFieldAssignError = 'Campos ''%s'' e ''%s'' não são compatíveis para atribuição'; SNoReferenceTableName = 'Referência do nome da tabela não especificado para o campo ''%s'''; SCompositeIndexError = 'Não é possível usar um array de valores de campos em Expressões de Índice'; SInvalidBatchMove = 'Parâmetros inválidos para batch move'; SEmptySQLStatement = 'Nenhuma declaração SQL disponível'; SNoParameterValue = 'Nenhum valor para o parâmetro ''%s'''; SNoParameterType = 'Parâmetro sem tipo: ''%s'''; SLoginError = 'Não é possível conectar com o banco de dados ''%s'''; SInitError = 'Um erro ocorreu durante a inicialização do Borland Database Engine (erro $%.4x)'; SDatabaseEditor = 'Da&tabase Editor...'; SExplore = 'E&xplorar'; SLinkDetail = '''%s'' não pode ser aberto'; SLinkMasterSource = 'A propriedade MasterSource do ''%s'' deve estar associado a um DataSource!!!'; SLinkMaster = 'Incapaz de abrir a tabela MasterSource'; SGQBEVerb = '&Query Builder...'; SBindVerb = 'Definir &Parâmetros...'; SIDAPILangID = '0009'; SDisconnectDatabase = 'O banco de dados está atualmente conectado. Desconectar e continuar ?'; SBDEError = 'Erro do BDE $%.4x'; SLookupSourceError = 'Incapaz de usar DataSource e LookupSource duplicados'; SLookupTableError = 'LookupSource deve estar conectado a um componente TTable'; SLookupIndexError = '%s deve ser um índice ativo da tabela lookup'; SParameterTypes = ';Input;Output;Input/Output;Result'; SInvalidParamFieldType = 'Deve haver um tipo de campo válido selecionado'; STruncationError = 'Parâmetro ''%s'' truncado na saída'; SDataTypes = ';String;SmallInt;Integer;Word;Boolean;Float;Currency;BCD;Date;Time;DateTime;;;;Blob;Memo;Graphic;;;;;Cursor;'; SResultName = 'Result'; SDBCaption = '%s%s%s Base de Dados'; SParamEditor = '%s%s%s Parâmetros'; SIndexFilesEditor = '%s%s%s Arquivos de Índice'; SNoIndexFiles = '(Nenhum)'; SIndexDoesNotExist = 'Índice não existe. Índice: %s'; SNoTableName = 'Propriedade TableName faltando'; SNoDataSetField = 'Propriedades dos campos do arquivo ausentes'; SBatchExecute = 'E&xecutar'; SNoCachedUpdates = 'Não está no modo cached update'; SInvalidAliasName = 'Nome inválido do alias %s'; SNoFieldAccess = 'Não é possível acessar o campo ''%s'' em um filtro'; SUpdateSQLEditor = '&UpdateSQL Editor...'; SNoDataSet = 'Nenhum arquivo associado'; SUntitled = 'Aplicação sem título'; SUpdateWrongDB = 'Não é possível atualizar, %s não pertence a %s'; SUpdateFailed = 'Atualização falhou'; SSQLGenSelect = 'Deve selecionar no mínimo um campo chave e um campo update'; SSQLNotGenerated = 'SQL de atualização não foi gerada, sair de qualquer forma?'; SSQLDataSetOpen = 'Incapaz de determinar os nomes dos campos para %s'; SLocalTransDirty = 'O nível de isolamento da transação deve ser dirty read para os banco de dados locais'; SMissingDataSet = 'Faltando propriedade do DataSet'; SNoProvider = 'Não há provedor disponível'; SNotAQuery = 'Este arquivo não é uma query'; implementation end.
unit UnitMenuDateForm; interface uses Winapi.Windows, Winapi.Messages, System.DateUtils, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.ComCtrls, Vcl.StdCtrls, Vcl.Menus, Vcl.ExtCtrls, Vcl.PlatformDefaultStyleActnCtrls, Vcl.ActnPopup, uConstants, uDBForm; type TFormMenuDateEdit = class(TDBForm) McDate: TMonthCalendar; BtOK: TButton; BtCancel: TButton; PmDate: TPopupActionBar; GoToCurrentDate1: TMenuItem; DateNotExists1: TMenuItem; DateExists1: TMenuItem; Image1: TImage; Label1: TLabel; Label2: TLabel; DtpTime: TDateTimePicker; PmTime: TPopupActionBar; GoToCurrentTime1: TMenuItem; TimeNotExists1: TMenuItem; TimeExists1: TMenuItem; Image2: TImage; Label3: TLabel; procedure FormCreate(Sender: TObject); procedure BtOKClick(Sender: TObject); procedure BtCancelClick(Sender: TObject); procedure GoToCurrentDate1Click(Sender: TObject); procedure DateNotExists1Click(Sender: TObject); procedure DateExists1Click(Sender: TObject); procedure PmDatePopup(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure GoToCurrentTime1Click(Sender: TObject); procedure TimeNotExists1Click(Sender: TObject); procedure TimeExists1Click(Sender: TObject); procedure PmTimePopup(Sender: TObject); private { Private declarations } FChanged : Boolean; protected function GetFormID : string; override; public { Public declarations } procedure Execute(var Date: TDateTime; var IsDate: Boolean; out Changed: Boolean; var Time: TDateTime; var IsTime: Boolean); procedure LoadLanguage; end; procedure ChangeDate(var Date : TDateTime; var IsDate : Boolean; out Changed : Boolean; var Time : TDateTime; var IsTime : Boolean); implementation {$R *.dfm} { TFormMenuDateEdit } procedure ChangeDate(var Date: TDateTime; var IsDate: Boolean; out Changed: Boolean; var Time: TDateTime; var IsTime: Boolean); var FormMenuDateEdit: TFormMenuDateEdit; begin Application.CreateForm(TFormMenuDateEdit, FormMenuDateEdit); try FormMenuDateEdit.Execute(Date, IsDate, Changed, Time, IsTime); finally FormMenuDateEdit.Release; end; end; procedure TFormMenuDateEdit.Execute(var Date: TDateTime; var IsDate: Boolean; out Changed: Boolean; var Time: TDateTime; var IsTime: Boolean); begin if YearOf(Date) > cMinEXIFYear then McDate.Date := DateOf(Date) else McDate.Date := DateOf(Now); McDate.Visible := IsDate; DtpTime.Time := Time; DtpTime.Visible := IsTime; ShowModal; if FChanged then begin Date := McDate.Date; IsDate := McDate.Visible; Time := TimeOf(DtpTime.Time); IsTime := DtpTime.Visible; end; Changed := FChanged; end; procedure TFormMenuDateEdit.FormCreate(Sender: TObject); begin FChanged := False; LoadLanguage; end; procedure TFormMenuDateEdit.BtOKClick(Sender: TObject); begin FChanged := True; Close; end; procedure TFormMenuDateEdit.BtCancelClick(Sender: TObject); begin Close; end; function TFormMenuDateEdit.GetFormID: string; begin Result := 'DateChange'; end; procedure TFormMenuDateEdit.GoToCurrentDate1Click(Sender: TObject); begin McDate.Date := Now; end; procedure TFormMenuDateEdit.DateNotExists1Click(Sender: TObject); begin McDate.Visible := False; end; procedure TFormMenuDateEdit.DateExists1Click(Sender: TObject); begin McDate.Visible := True; end; procedure TFormMenuDateEdit.PmDatePopup(Sender: TObject); begin GoToCurrentDate1.Visible := McDate.Visible; DateNotExists1.Visible := McDate.Visible; DateExists1.Visible := not McDate.Visible; end; procedure TFormMenuDateEdit.FormShow(Sender: TObject); begin if BtCancel.Enabled then BtCancel.SetFocus else BtOK.SetFocus; end; procedure TFormMenuDateEdit.FormKeyPress(Sender: TObject; var Key: Char); begin if Key = Char(VK_ESCAPE) then Close; end; procedure TFormMenuDateEdit.LoadLanguage; begin BeginTranslate; try Caption := L('Change date and time'); GoToCurrentDate1.Caption := L('Go to current date'); DateNotExists1.Caption := L('No date'); DateExists1.Caption := L('Set up date'); Label1.Caption := L('No date'); Label2.Caption := L('Choose "Date set" in popup menu'); BtOK.Caption := L('Ok'); BtCancel.Caption := L('Cancel'); GoToCurrentTime1.Caption := L('Go to current time'); TimeNotExists1.Caption := L('No time'); TimeExists1.Caption := L('Set up time'); Label3.Caption := L('No time'); finally EndTranslate; end; end; procedure TFormMenuDateEdit.GoToCurrentTime1Click(Sender: TObject); begin DtpTime.Time := Now; end; procedure TFormMenuDateEdit.TimeNotExists1Click(Sender: TObject); begin DtpTime.Visible := False; end; procedure TFormMenuDateEdit.TimeExists1Click(Sender: TObject); begin DtpTime.Visible := True; end; procedure TFormMenuDateEdit.PmTimePopup(Sender: TObject); begin GoToCurrentTime1.Visible := DtpTime.Visible; TimeNotExists1.Visible := DtpTime.Visible; TimeExists1.Visible := not DtpTime.Visible; end; end.
unit uJpegUtils; interface uses System.Math, System.Classes, Vcl.Imaging.jpeg, Vcl.Graphics, uMemory, uSettings, uBitmapUtils; type TJPEGX = class(TJpegImage) public function InnerBitmap: TBitmap; end; type TCompresJPEGToSizeCallback = procedure(CurrentSize, CompressionRate: Integer; var Break: Boolean) of object; procedure AssignJpeg(Bitmap: TBitmap; Jpeg: TJPEGImage); procedure JPEGScale(Graphic: TGraphic; Width, Height: Integer); function CalcJpegResampledSize(Jpeg: TJpegImage; Size: Integer; CompressionRate: Byte; out JpegImageResampled: TJpegImage): Int64; function CalcBitmapToJPEGCompressSize(Bitmap: TBitmap; CompressionRate: Byte; out JpegImageResampled: TJpegImage): Int64; procedure FreeJpegBitmap(J: TJpegImage); function CompresJPEGToSize(JS: TGraphic; var ToSize: Integer; Progressive: Boolean; var CompressionRate: Integer; CallBack: TCompresJPEGToSizeCallback = nil): Boolean; procedure SetJPEGGraphicSaveOptions(Section: string; Graphic: TGraphic); implementation procedure SetJPEGGraphicSaveOptions(Section: string; Graphic: TGraphic); var OptimizeToSize: Integer; Progressive: Boolean; Compression: Integer; begin if Graphic is TJPEGImage then begin OptimizeToSize := AppSettings.ReadInteger(Section, 'JPEGOptimizeSize', 250) * 1024; Progressive := AppSettings.ReadBool(Section, 'JPEGProgressiveMode', False); if AppSettings.ReadBool(Section, 'JPEGOptimizeMode', False) then CompresJPEGToSize(Graphic, OptimizeToSize, Progressive, Compression) else Compression := AppSettings.ReadInteger(Section, 'JPEGCompression', 85); (Graphic as TJPEGImage).CompressionQuality := Compression; (Graphic as TJPEGImage).ProgressiveEncoding := Progressive; (Graphic as TJPEGImage).Compress; end; end; { TJPEGX } procedure FreeJpegBitmap(J: TJpegImage); begin TJpegX(J).FreeBitmap; end; function TJPEGX.InnerBitmap: TBitmap; begin Result := Bitmap; end; procedure AssignJpeg(Bitmap: TBitmap; Jpeg: TJPEGImage); begin JPEG.Performance := jpBestSpeed; try JPEG.DIBNeeded; except //incorrect file will throw an error, but bitmap will be available so we can display partially decompressed image end; if TJPEGX(JPEG).InnerBitmap <> nil then SetLastError(0); AssignBitmap(Bitmap, TJPEGX(JPEG).InnerBitmap); end; procedure JPEGScale(Graphic: TGraphic; Width, Height: Integer); var ScaleX, ScaleY, Scale: Extended; begin if (Graphic is TJpegImage) then begin (Graphic as TJpegImage).Performance := jpBestSpeed; (Graphic as TJpegImage).ProgressiveDisplay := False; ScaleX:= Graphic.Width / Width; ScaleY := Graphic.Height / Height; Scale := Max(ScaleX, ScaleY); if Scale < 2 then (Graphic as TJpegImage).Scale := JsFullSize; if (Scale >= 2) and (Scale < 4) then (Graphic as TJpegImage).Scale := JsHalf; if (Scale >= 4) and (Scale < 8) then (Graphic as TJpegImage).Scale := JsQuarter; if Scale >= 8 then (Graphic as TJpegImage).Scale := JsEighth; end; end; function CalcBitmapToJPEGCompressSize(Bitmap: TBitmap; CompressionRate: Byte; out JpegImageResampled: TJpegImage): Int64; var Jpeg: TJpegImage; MS: TMemoryStream; begin Jpeg := TJpegImage.Create; try Jpeg.Assign(Bitmap); if CompressionRate < 1 then CompressionRate := 1; if CompressionRate > 100 then CompressionRate := 100; Jpeg.CompressionQuality := CompressionRate; Jpeg.Compress; MS := TMemoryStream.Create; try Jpeg.SaveToStream(MS); JpegImageResampled := TJpegImage.Create; MS.Seek(0, soFromBeginning); JpegImageResampled.LoadFromStream(MS); Result := MS.Size; finally F(MS); end; finally F(Jpeg); end; end; function CalcJpegResampledSize(jpeg: TJpegImage; Size: Integer; CompressionRate: Byte; out JpegImageResampled: TJpegImage): Int64; var Bitmap, OutBitmap: TBitmap; W, H: Integer; begin Bitmap := TBitmap.Create; try Bitmap.Assign(Jpeg); OutBitmap := TBitmap.Create; try W := Jpeg.Width; H := Jpeg.Height; ProportionalSize(Size, Size, W, H); DoResize(W, H, Bitmap, OutBitmap); Result := CalcBitmapToJPEGCompressSize(OutBitmap, CompressionRate, JpegImageResampled); finally F(OutBitmap); end; finally F(Bitmap); end; end; function CompresJPEGToSize(JS: TGraphic; var ToSize: Integer; Progressive: Boolean; var CompressionRate: Integer; CallBack: TCompresJPEGToSizeCallback = nil): Boolean; var Ms: TMemoryStream; Jd: TJPEGImage; Max_size, Cur_size, Cur_cr, Cur_cr_inc: Integer; IsBreak: Boolean; begin Result := False; Max_size := ToSize; Cur_cr := 50; Cur_cr_inc := 50; IsBreak := False; Jd := TJpegImage.Create; try repeat Jd.Assign(Js); Jd.CompressionQuality := Cur_cr; Jd.ProgressiveEncoding := Progressive; Jd.Compress; Ms := TMemoryStream.Create; try Jd.SaveToStream(Ms); Cur_size := Ms.Size; if Assigned(CallBack) then CallBack(Cur_size, Cur_cr, IsBreak); if IsBreak then begin CompressionRate := -1; ToSize := -1; Exit; end; if ((Cur_size < Max_size) and (Cur_cr_inc = 1)) or (Cur_cr = 1) then Break; Cur_cr_inc := Round(Cur_cr_inc / 2); if Cur_cr_inc < 1 then Cur_cr_inc := 1; if Cur_size < Max_size then begin Cur_cr := Cur_cr + Cur_cr_inc; end else Cur_cr := Cur_cr - Cur_cr_inc; if (Cur_size < Max_size) and (Cur_cr = 99) then Cur_cr_inc := 2; finally F(MS); end; until False; finally F(JD); end; CompressionRate := Cur_cr; ToSize := Cur_size; Result := True; end; end.
unit BZK2_Sector; interface uses SysUtils,Voxel_Engine; type TBZKFacesDirection = (bfdNorth,bfdEast,bfdSouth,bfdWest,bfdFloor,bfdCeiling); TVector4i = record X, Y, Z, W : integer; end; TBZK2Sector = class public // Constructors constructor Create; destructor Destroy; override; // I/O procedure WriteToFile (var MyFile : System.Text); // Adds procedure AddTrigger(value : integer); // Removes function RemoveTrigger(ID : integer): Boolean; // Gets function GetPosition : TVector3i; function GetVoxelPosition : TVector3i; function GetVolume : TVector3i; function GetName : string; function GetConnection(Direction : TBZKFacesDirection) : integer; function GetConnectionMap(Direction : TBZKFacesDirection) : string; function GetConnectionColours(Direction : TBZKFacesDirection) : TVector3i; function GetTrigger(ID : integer): integer; function GetNumTriggers: integer; function GetColour : TVector4i; function GetRenderFace(ID : integer): boolean; // Sets procedure SetPosition( value : TVector3i); procedure SetVoxelPosition( value : TVector3i); procedure SetVolume( value : TVector3i); overload; procedure SetVolume( value : integer); overload; procedure SetName( const value : string); procedure SetConnection( Direction : TBZKFacesDirection; value : integer); procedure SetConnections( north, east, south, west, floor, ceil : integer); procedure SetConnectionMap( Direction : TBZKFacesDirection; value : string); procedure SetConnectionColours( Direction : TBZKFacesDirection; value : TVector3i); function SetTrigger( ID, Value : integer): Boolean; procedure SetColour( value : TVector4i); function SetRenderFace( ID : integer; Value : boolean): Boolean; // Assign procedure Assign(const Sector : TBZK2Sector); // AutoSet procedure AutoSetForceRenderFaces; private Position : TVector3i; VoxelPosition : TVector3i; Volume : TVector3i; Name : string; Connections : array [TBzkFacesDirection] of integer; ConnectionMaps : array [TBzkFacesDirection] of string; ConnectionColours : array [TBzkFacesDirection] of TVector3i; Triggers : array of integer; Colour : TVector4i; ForceRenderFace : array[0..5] of boolean; // I/O procedure WriteTriggers (var MyFile : System.Text); procedure WritePosition (var MyFile : System.Text); procedure WriteVolume (var MyFile : System.Text); procedure WriteName (var MyFile : System.Text); procedure WriteConnection (var MyFile : System.Text; Direction : TBZKFacesDirection); procedure WriteConnections (var MyFile : System.Text); procedure WriteConnectionColour (var MyFile : System.Text; Direction : TBZKFacesDirection); procedure WriteConnectionColours (var MyFile : System.Text); procedure WriteColour (var MyFile : System.Text); procedure WriteForceRenderFace (var MyFile : System.Text); end; implementation // Constructors & Destructors constructor TBZK2Sector.Create; var i : integer; begin Position := SetVectorI(0,0,0); VoxelPosition := SetVectorI(0,0,0); Volume := SetVectorI(0,0,0); Name := ''; Connections[bfdNorth] := 0; Connections[bfdEast] := 0; Connections[bfdSouth] := 0; Connections[bfdWest] := 0; Connections[bfdFloor] := 0; Connections[bfdCeiling] := 0; ConnectionMaps[bfdNorth] := ''; ConnectionMaps[bfdEast] := ''; ConnectionMaps[bfdSouth] := ''; ConnectionMaps[bfdWest] := ''; ConnectionMaps[bfdFloor] := ''; ConnectionMaps[bfdCeiling] := ''; ConnectionColours[bfdNorth] := SetVectorI(0,0,0); ConnectionColours[bfdEast] := SetVectorI(0,0,0); ConnectionColours[bfdSouth] := SetVectorI(0,0,0); ConnectionColours[bfdWest] := SetVectorI(0,0,0); ConnectionColours[bfdFloor] := SetVectorI(0,0,0); ConnectionColours[bfdCeiling] := SetVectorI(0,0,0); SetLength(Triggers,0); Colour.X := 0; Colour.Y := 0; Colour.Z := 0; Colour.W := 0; for i := 0 to 5 do ForceRenderFace[i] := false; end; destructor TBZK2Sector.Destroy; begin Name := ''; SetLength(Triggers,0); inherited Destroy; end; // Gets function TBZK2Sector.GetPosition : TVector3i; begin Result.X := Position.X; Result.Y := Position.Y; Result.Z := Position.Z; end; function TBZK2Sector.GetVoxelPosition : TVector3i; begin Result.X := VoxelPosition.X; Result.Y := VoxelPosition.Y; Result.Z := VoxelPosition.Z; end; function TBZK2Sector.GetVolume : TVector3i; begin Result.X := Volume.X; Result.Y := Volume.Y; Result.Z := Volume.Z; end; function TBZK2Sector.GetName : string; begin Result := Name; end; function TBZK2Sector.GetConnection(Direction : TBZKFacesDirection) : integer; begin Result := Connections[Direction]; end; function TBZK2Sector.GetConnectionMap(Direction : TBZKFacesDirection) : string; begin Result := ConnectionMaps[Direction]; end; function TBZK2Sector.GetConnectionColours(Direction : TBZKFacesDirection) : TVector3i; begin Result.X := ConnectionColours[Direction].X; Result.Y := ConnectionColours[Direction].Y; Result.Z := ConnectionColours[Direction].Z; end; function TBZK2Sector.GetTrigger(ID : integer): integer; begin if ID > High(Triggers) then Result := -1 else Result := Triggers[ID]; end; function TBZK2Sector.GetNumTriggers: integer; begin Result := High(Triggers)+1; end; function TBZK2Sector.GetColour : TVector4i; begin Result.X := Colour.X; Result.Y := Colour.Y; Result.Z := Colour.Z; Result.W := Colour.W; end; function TBZK2Sector.GetRenderFace(ID : integer): boolean; begin if ID > High(ForceRenderFace) then Result := false else Result := ForceRenderFace[ID]; end; // Sets procedure TBZK2Sector.SetPosition( value : TVector3i); begin Position.X := Value.X; Position.Y := Value.Y; Position.Z := Value.Z; end; procedure TBZK2Sector.SetVoxelPosition( value : TVector3i); begin VoxelPosition.X := Value.X; VoxelPosition.Y := Value.Y; VoxelPosition.Z := Value.Z; end; procedure TBZK2Sector.SetVolume( value : TVector3i); begin Volume.X := Value.X; Volume.Y := Value.Y; Volume.Z := Value.Z; end; procedure TBZK2Sector.SetVolume( value : integer); begin Volume.X := Value; Volume.Y := Value; Volume.Z := Value; end; procedure TBZK2Sector.SetName( const value : string); begin Name := Value; end; procedure TBZK2Sector.SetConnection( Direction : TBZKFacesDirection; value : integer); begin Connections[Direction] := Value; end; procedure TBZK2Sector.SetConnectionMap( Direction : TBZKFacesDirection; value : string); begin ConnectionMaps[Direction] := Value; end; procedure TBZK2Sector.SetConnections( north, east, south, west, floor, ceil : integer); begin Connections[bfdNorth] := North; Connections[bfdEast] := East; Connections[bfdSouth] := South; Connections[bfdWest] := West; Connections[bfdFloor] := Floor; Connections[bfdCeiling] := Ceil; end; procedure TBZK2Sector.SetConnectionColours( Direction : TBZKFacesDirection; value : TVector3i); begin ConnectionColours[Direction].X := Value.X; ConnectionColours[Direction].Y := Value.Y; ConnectionColours[Direction].Z := Value.Z; end; function TBZK2Sector.SetTrigger( ID, Value : integer): Boolean; begin Result := false; if ID <= High(Triggers) then begin Triggers[ID] := Value; Result := true; end; end; procedure TBZK2Sector.SetColour( value : TVector4i); begin Colour.X := Value.X; Colour.Y := Value.Y; Colour.Z := Value.Z; Colour.W := Value.W; end; function TBZK2Sector.SetRenderFace( ID: Integer; Value : Boolean): Boolean; begin Result := false; if ID <= High(ForceRenderFace) then begin ForceRenderFace[ID] := Value; Result := true; end; end; // Adds procedure TBZK2Sector.AddTrigger(value : integer); begin SetLength(Triggers,High(Triggers)+2); Triggers[High(Triggers)] := Value; end; // Removes function TBZK2Sector.RemoveTrigger(ID : integer): Boolean; var i : integer; begin Result := false; if ID <= High(Triggers) then begin i := ID; while i < High(Triggers) do begin Triggers[i] := Triggers[i+1]; inc(i); end; SetLength(Triggers,High(Triggers)); Result := true; end; end; // I/O procedure TBZK2Sector.WriteToFile (var MyFile : System.Text); begin WriteLn(MyFile,'<Sector>'); WriteTriggers(MyFile); WriteVolume(MyFile); WriteName(MyFile); WriteConnections(MyFile); WriteConnectionColours(MyFile); WriteColour(MyFile); WriteForceRenderFace(MyFile); WriteLn(MyFile,'</Sector>'); end; procedure TBZK2Sector.WriteTriggers (var MyFile : System.Text); var i : integer; begin if High(Triggers) >= 0 then begin WriteLn(MyFile,'<Triggers>'); for i := Low(Triggers) to High(Triggers) do WriteLn(MyFile,Triggers[i]); WriteLn(MyFile,'</Triggers>'); end; end; procedure TBZK2Sector.WritePosition (var MyFile : System.Text); begin WriteLn(MyFile,'<Vec3f>'); WriteLn(MyFile,Position.X); WriteLn(MyFile,Position.Y); WriteLn(MyFile,Position.Z); WriteLn(MyFile,'</Vec3f>'); end; procedure TBZK2Sector.WriteVolume (var MyFile : System.Text); begin WriteLn(MyFile,'<Volume>'); WritePosition(MyFile); WriteLn(MyFile,Volume.X); WriteLn(MyFile,Volume.Y); WriteLn(MyFile,Volume.Z); WriteLn(MyFile,'</Volume>'); end; procedure TBZK2Sector.WriteName (var MyFile : System.Text); begin WriteLn(MyFile,'<Name>'); WriteLn(MyFile,Name); WriteLn(MyFile,'</Name>'); end; procedure TBZK2Sector.WriteConnection (var MyFile : System.Text; Direction : TBZKFacesDirection); begin if CompareStr(ConnectionMaps[Direction],'') = 0 then WriteLn(MyFile,Connections[Direction]) else WriteLn(MyFile,ConnectionMaps[Direction] + ' / ' + IntToStr(Connections[Direction])); end; procedure TBZK2Sector.WriteConnections (var MyFile : System.Text); begin WriteLn(MyFile,'<Connections>'); WriteConnection(MyFile,bfdNorth); WriteConnection(MyFile,bfdEast); WriteConnection(MyFile,bfdSouth); WriteConnection(MyFile,bfdWest); WriteConnection(MyFile,bfdFloor); WriteConnection(MyFile,bfdCeiling); WriteLn(MyFile,'</Connections>'); end; procedure TBZK2Sector.WriteConnectionColour (var MyFile : System.Text; Direction : TBZKFacesDirection); begin WriteLn(MyFile,'<RGB>'); WriteLn(MyFile,ConnectionColours[Direction].X); WriteLn(MyFile,ConnectionColours[Direction].Y); WriteLn(MyFile,ConnectionColours[Direction].Z); WriteLn(MyFile,'</RGB>'); end; procedure TBZK2Sector.WriteConnectionColours (var MyFile : System.Text); begin WriteLn(MyFile,'<Color>'); WriteConnectionColour(MyFile,bfdNorth); WriteConnectionColour(MyFile,bfdEast); WriteConnectionColour(MyFile,bfdSouth); WriteConnectionColour(MyFile,bfdWest); WriteConnectionColour(MyFile,bfdFloor); WriteConnectionColour(MyFile,bfdCeiling); WriteLn(MyFile,'</Color>'); end; procedure TBZK2Sector.WriteColour (var MyFile : System.Text); begin if (Colour.X > 0) or (Colour.Y > 0) or (Colour.Z > 0) or (Colour.W > 0) then begin WriteLn(MyFile,'<RGBA>'); WriteLn(MyFile,Colour.X); WriteLn(MyFile,Colour.Y); WriteLn(MyFile,Colour.Z); WriteLn(MyFile,Colour.W); WriteLn(MyFile,'</RGBA>'); end; end; procedure TBZK2Sector.WriteForceRenderFace (var MyFile : System.Text); var i : integer; begin for i := 0 to 5 do begin if ForceRenderFace[i] then begin WriteLn(MyFile,'<Force_Render_Face>'); WriteLn(MyFile,i); WriteLn(MyFile,'</Force_Render_Face>'); end; end; end; procedure TBZK2Sector.Assign(const Sector : TBZK2Sector); var i: integer; begin SetPosition(Sector.GetPosition); SetVoxelPosition(Sector.GetVoxelPosition); SetVolume(Sector.GetVolume); SetName(Sector.GetName); SetConnections(Sector.GetConnection(bfdNorth),Sector.GetConnection(bfdEast),Sector.GetConnection(bfdSouth),Sector.GetConnection(bfdWest),Sector.GetConnection(bfdFloor),Sector.GetConnection(bfdCeiling)); SetConnectionMap(bfdNorth,Sector.GetConnectionMap(bfdNorth)); SetConnectionMap(bfdEast,Sector.GetConnectionMap(bfdEast)); SetConnectionMap(bfdSouth,Sector.GetConnectionMap(bfdSouth)); SetConnectionMap(bfdWest,Sector.GetConnectionMap(bfdWest)); SetConnectionMap(bfdFloor,Sector.GetConnectionMap(bfdFloor)); SetConnectionMap(bfdCeiling,Sector.GetConnectionMap(bfdCeiling)); SetConnectionColours(bfdNorth,Sector.GetConnectionColours(bfdNorth)); SetConnectionColours(bfdEast,Sector.GetConnectionColours(bfdEast)); SetConnectionColours(bfdSouth,Sector.GetConnectionColours(bfdSouth)); SetConnectionColours(bfdWest,Sector.GetConnectionColours(bfdWest)); SetConnectionColours(bfdFloor,Sector.GetConnectionColours(bfdFloor)); SetConnectionColours(bfdCeiling,Sector.GetConnectionColours(bfdCeiling)); SetLength(Triggers,0); if Sector.GetNumTriggers > 0 then for i := 0 to Sector.GetNumTriggers do AddTrigger(Sector.GetTrigger(i)); SetColour(Sector.GetColour); for i := 0 to 5 do SetRenderFace(i,Sector.GetRenderFace(i)); end; // AutoSets procedure TBZK2Sector.AutoSetForceRenderFaces; var i : integer; begin if (Colour.X > 0) or (Colour.Y > 0) or (Colour.Z > 0) or (Colour.W > 0) then begin for i := 0 to 5 do ForceRenderFace[0] := false; if Connections[bfdNorth] = 0 then ForceRenderFace[0] := true; if Connections[bfdEast] = 0 then ForceRenderFace[1] := true; if Connections[bfdSouth] = 0 then ForceRenderFace[2] := true; if Connections[bfdWest] = 0 then ForceRenderFace[3] := true; if Connections[bfdFloor] = 0 then ForceRenderFace[4] := true; if Connections[bfdCeiling] = 0 then ForceRenderFace[5] := true; end; end; end.
//*******************************************************// // // // DelphiFlash.com // // Copyright (c) 2004 FeatherySoft, Inc. // // info@delphiflash.com // // // //*******************************************************// // Description: GDI+ adapting for Delphi SWF SWK // Last update: 2 jun 2005 unit FlashGDI; interface uses Windows, ActiveX, Classes, FlashObjects; procedure LoadCustomImageProcedure(sender: TFlashImage; FileName: string); {============================== GDI+ function ==============================} type TGPStatus = (Ok, GenericError, InvalidParameter, OutOfMemory, ObjectBusy, InsufficientBuffer, NotImplemented, Win32Error, WrongState, Aborted, FileNotFound, ValueOverflow, AccessDenied, UnknownImageFormat, FontFamilyNotFound, FontStyleNotFound, NotTrueTypeFont, UnsupportedGdiplusVersion, GdiplusNotInitialized, PropertyNotFound, PropertyNotSupported); TGdiplusStartupInput = packed record GdiplusVersion: Cardinal; DebugEventCallback: Pointer; SuppressBackgroundThread: boolean; SuppressExternalCodecs: boolean; end; PGdiplusStartupInput = ^TGdiplusStartupInput; TImageCodecInfo = packed record Clsid: TGUID; FormatID: TGUID; CodecName: PWideChar; DllName: PWideChar; FormatDescription: PWideChar; FilenameExtension: PWideChar; MimeType: PWideChar; Flags: DWORD; Version: DWORD; SigCount: DWORD; SigSize: DWORD; SigPattern: PBYTE; SigMask: PBYTE; end; PImageCodecInfo = ^TImageCodecInfo; var token: DWord; procedure InitGDIPlus; function GdiplusStartup(out token: DWORD; const input: PGdiplusStartupInput; output: pointer): TGPStatus; stdcall; procedure GdiplusShutdown(token: DWORD); stdcall; function GdipLoadImageFromFileICM(filename: PWideChar; out image: Pointer): TGPStatus; stdcall; function GdipGetImageEncodersSize(out numEncoders: DWord; out size: DWord): TGPStatus; stdcall; function GdipGetImageEncoders(numEncoders: DWord; size: DWord; encoders: PImageCodecInfo): TGPStatus; stdcall; function GdipSaveImageToStream(image: Pointer; stream: IStream; clsidEncoder: PGUID; encoderParams: Pointer): TGPStatus; stdcall; function GdipDisposeImage(image: Pointer): TGPStatus; stdcall; implementation {============================== GDI+ function ==============================} const GdiPlusLib = 'gdiplus.dll'; var DefStartup: TGdiplusStartupInput; function GdiplusStartup; external GdiPlusLib name 'GdiplusStartup'; procedure GdiplusShutdown; external GdiPlusLib name 'GdiplusShutdown'; function GdipLoadImageFromFileICM; external GdiPlusLib name 'GdipLoadImageFromFileICM'; function GdipGetImageEncodersSize; external GdiPlusLib name 'GdipGetImageEncodersSize'; function GdipGetImageEncoders; external GdiPlusLib name 'GdipGetImageEncoders'; function GdipSaveImageToStream; external GdiPlusLib name 'GdipSaveImageToStream'; function GdipDisposeImage; external GdiPlusLib name 'GdipDisposeImage'; function GetEncoderClsid(format: string; var pClsid: TGUID): integer; var num, size, il: DWord; ImageCodecInfo: PImageCodecInfo; type ArrIMgInf = array of TImageCodecInfo; begin num := 0; // number of image encoders size := 0; // size of the image encoder array in bytes result := -1; GdipGetImageEncodersSize(num, size); if (size = 0) then exit; GetMem(ImageCodecInfo, size); if GdipGetImageEncoders(num, size, ImageCodecInfo) = Ok then for il := 0 to num - 1 do begin if (ArrIMgInf(ImageCodecInfo)[il].MimeType = format) then begin pClsid := ArrIMgInf(ImageCodecInfo)[il].Clsid; result := il; Break; end; end; FreeMem(ImageCodecInfo, size); end; procedure InitGDIPlus; begin DefStartup.GdiplusVersion := 1; DefStartup.DebugEventCallback := nil; DefStartup.SuppressBackgroundThread := False; DefStartup.SuppressExternalCodecs := False; if GdiPlusStartup(token, @DefStartup, nil) = Ok then LoadCustomImageProc := LoadCustomImageProcedure; end; {===========================================================================} procedure LoadCustomImageProcedure(sender: TFlashImage; FileName: string); var EncoderID: TGUID; Mem: TMemoryStream; Adapt: TStreamAdapter; SrcImage: Pointer; begin Mem := TMemoryStream.Create; Adapt := TStreamAdapter.Create(Mem); SrcImage := nil; try GdipLoadImageFromFileICM(PWideChar(WideString(FileName)), SrcImage); if GetEncoderClsid('image/bmp', EncoderID) > -1 then if GdipSaveImageToStream(SrcImage, (Adapt as IStream), @EncoderID, nil) = Ok then begin Mem.Position := 0; Sender.LoadDataFromStream(Mem); end; finally if SrcImage <> nil then GdipDisposeImage(SrcImage); Mem.Free; end; end; initialization InitGDIPlus; finalization GdiPlusShutdown(token); end. d.
// // Generated by JavaToPas v1.5 20171018 - 171221 //////////////////////////////////////////////////////////////////////////////// unit android.widget.SimpleCursorAdapter; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, Androidapi.JNI.GraphicsContentViewText, android.content.ContentProvider, android.widget.SimpleCursorAdapter_ViewBinder, android.widget.ImageView, android.text.method.MovementMethod, android.widget.SimpleCursorAdapter_CursorToStringConverter; type JSimpleCursorAdapter = interface; JSimpleCursorAdapterClass = interface(JObjectClass) ['{911A0A68-B27F-4EFE-BD73-60983B710962}'] function convertToString(cursor : JCursor) : JCharSequence; cdecl; // (Landroid/database/Cursor;)Ljava/lang/CharSequence; A: $1 function getCursorToStringConverter : JSimpleCursorAdapter_CursorToStringConverter; cdecl;// ()Landroid/widget/SimpleCursorAdapter$CursorToStringConverter; A: $1 function getStringConversionColumn : Integer; cdecl; // ()I A: $1 function getViewBinder : JSimpleCursorAdapter_ViewBinder; cdecl; // ()Landroid/widget/SimpleCursorAdapter$ViewBinder; A: $1 function init(context : JContext; layout : Integer; c : JCursor; from : TJavaArray<JString>; &to : TJavaArray<Integer>) : JSimpleCursorAdapter; deprecated; cdecl; overload;// (Landroid/content/Context;ILandroid/database/Cursor;[Ljava/lang/String;[I)V A: $1 function init(context : JContext; layout : Integer; c : JCursor; from : TJavaArray<JString>; &to : TJavaArray<Integer>; flags : Integer) : JSimpleCursorAdapter; cdecl; overload;// (Landroid/content/Context;ILandroid/database/Cursor;[Ljava/lang/String;[II)V A: $1 function swapCursor(c : JCursor) : JCursor; cdecl; // (Landroid/database/Cursor;)Landroid/database/Cursor; A: $1 procedure bindView(view : JView; context : JContext; cursor : JCursor) ; cdecl;// (Landroid/view/View;Landroid/content/Context;Landroid/database/Cursor;)V A: $1 procedure changeCursorAndColumns(c : JCursor; from : TJavaArray<JString>; &to : TJavaArray<Integer>) ; cdecl;// (Landroid/database/Cursor;[Ljava/lang/String;[I)V A: $1 procedure setCursorToStringConverter(cursorToStringConverter : JSimpleCursorAdapter_CursorToStringConverter) ; cdecl;// (Landroid/widget/SimpleCursorAdapter$CursorToStringConverter;)V A: $1 procedure setStringConversionColumn(stringConversionColumn : Integer) ; cdecl;// (I)V A: $1 procedure setViewBinder(viewBinder : JSimpleCursorAdapter_ViewBinder) ; cdecl;// (Landroid/widget/SimpleCursorAdapter$ViewBinder;)V A: $1 procedure setViewImage(v : JImageView; value : JString) ; cdecl; // (Landroid/widget/ImageView;Ljava/lang/String;)V A: $1 procedure setViewText(v : JTextView; text : JString) ; cdecl; // (Landroid/widget/TextView;Ljava/lang/String;)V A: $1 end; [JavaSignature('android/widget/SimpleCursorAdapter$CursorToStringConverter')] JSimpleCursorAdapter = interface(JObject) ['{8542EBB4-A35E-41E2-AF7A-A358E9A01873}'] function convertToString(cursor : JCursor) : JCharSequence; cdecl; // (Landroid/database/Cursor;)Ljava/lang/CharSequence; A: $1 function getCursorToStringConverter : JSimpleCursorAdapter_CursorToStringConverter; cdecl;// ()Landroid/widget/SimpleCursorAdapter$CursorToStringConverter; A: $1 function getStringConversionColumn : Integer; cdecl; // ()I A: $1 function getViewBinder : JSimpleCursorAdapter_ViewBinder; cdecl; // ()Landroid/widget/SimpleCursorAdapter$ViewBinder; A: $1 function swapCursor(c : JCursor) : JCursor; cdecl; // (Landroid/database/Cursor;)Landroid/database/Cursor; A: $1 procedure bindView(view : JView; context : JContext; cursor : JCursor) ; cdecl;// (Landroid/view/View;Landroid/content/Context;Landroid/database/Cursor;)V A: $1 procedure changeCursorAndColumns(c : JCursor; from : TJavaArray<JString>; &to : TJavaArray<Integer>) ; cdecl;// (Landroid/database/Cursor;[Ljava/lang/String;[I)V A: $1 procedure setCursorToStringConverter(cursorToStringConverter : JSimpleCursorAdapter_CursorToStringConverter) ; cdecl;// (Landroid/widget/SimpleCursorAdapter$CursorToStringConverter;)V A: $1 procedure setStringConversionColumn(stringConversionColumn : Integer) ; cdecl;// (I)V A: $1 procedure setViewBinder(viewBinder : JSimpleCursorAdapter_ViewBinder) ; cdecl;// (Landroid/widget/SimpleCursorAdapter$ViewBinder;)V A: $1 procedure setViewImage(v : JImageView; value : JString) ; cdecl; // (Landroid/widget/ImageView;Ljava/lang/String;)V A: $1 procedure setViewText(v : JTextView; text : JString) ; cdecl; // (Landroid/widget/TextView;Ljava/lang/String;)V A: $1 end; TJSimpleCursorAdapter = class(TJavaGenericImport<JSimpleCursorAdapterClass, JSimpleCursorAdapter>) end; implementation end.
procedure MouseParaControle(Controle: TControl); // // Posiciona o mouse em cima do objeto definido em Controle // // use-a no evento OnShow do form: // // MouseParaControle(button1); // var IrPara: TPoint; begin IrPara.X := Controle.Left + (Controle.Width div 2); IrPara.Y := Controle.Top + (Controle.Height div 2); if Controle.Parent <> nil then IrPara := Controle.Parent.ClientToScreen(IrPara); SetCursorPos(IrPara.X, IrPara.Y); end;
{ Laz-Model Copyright (C) 2002 Eldean AB, Peter Söderman, Ville Krumlinde Portions (C) 2016 Peter Dyson. Initial Lazarus port This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit uJavaParser; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Types, Dialogs, uCodeParser, uModel, uModelEntity, uIntegrator; type TJavaImporter = class(TImportIntegrator) private function NeedPackageHandler(const AName: string; var AStream: TStream; OnlyLookUp: Boolean = False):String; public procedure ImportOneFile(const FileName : string); override; class function GetFileExtensions : TStringList; override; end; TJavaParser = class(TCodeParser) private FStream: TMemoryStream; FCurrPos: PChar; Token: string; FOM: TObjectModel; FUnit: TUnitPackage; Comment: string; // Accumulated comment string used for documentation of entities. ModAbstract : boolean; ModVisibility: TVisibility; ClassImports,FullImports : TStringList; NameCache : TStringList; FSourcePos: TPoint; FTokenPos: TPoint; FFilename: String; TokenPosLocked : boolean; function SkipToken(const what: string): Boolean; function SkipPair(const open, close: string): Boolean; function GetChar: char; procedure EatWhiteSpace; function GetNextToken: string; procedure ParseCompilationUnit; procedure ParseTypeDeclaration; procedure ParseModifiersOpt; procedure ParseClassDeclaration(IsInner : boolean = False; const ParentName : string = ''); procedure ParseInterfaceDeclaration; procedure DoOperation(O: TOperation; const ParentName, TypeName: string); procedure DoAttribute(A: TAttribute; const TypeName: string); function GetTypeName : string; procedure SetVisibility(M: TModelEntity); function NeedClassifier(const CName: string; Force : boolean = True; TheClass: TModelEntityClass = nil): TClassifier; function NeedSource(const SourceName : string) : boolean; public constructor Create; destructor Destroy; override; procedure ParseStream(AStream: TStream; AModel: TAbstractPackage; AOM: TObjectModel); overload; override; property Filename: String read FFilename write FFilename; end; implementation function ExtractPackageName(const CName: string): string; var I : integer; begin I := LastDelimiter('.',CName); if I=0 then Result := '' else Result := Copy(CName,1,I-1); end; function ExtractClassName(const CName: string): string; var I : integer; begin I := LastDelimiter('.',CName); if I=0 then Result := CName else Result := Copy(CName,I+1,255); end; { TJavaImporter } procedure TJavaImporter.ImportOneFile(const FileName : string); var Str : TStream; Parser: TJavaParser; begin Str := CodeProvider.LoadStream(FileName); if Assigned(Str) then begin Parser := TJavaParser.Create; try Parser.FileName := FileName; Parser.NeedPackage := @NeedPackageHandler; Parser.ParseStream(Str, Model.ModelRoot, Model); finally Parser.Free; end; end; end; function TJavaImporter.NeedPackageHandler(const AName: string; var AStream: TStream; OnlyLookUp: Boolean = False):String; var FileName: string; begin AStream := nil; FileName := AName + '.java'; FileName := CodeProvider.LocateFile(FileName); Result := FileName; //Avoid reading same file twice if (not OnlyLookUp) and (FileName<>'') and (FilesRead.IndexOf(FileName)=-1) then begin AStream := CodeProvider.LoadStream(FileName); FilesRead.Add(FileName); end; end; class function TJavaImporter.GetFileExtensions: TStringList; begin Result := TStringList.Create; Result.Values['.java'] := 'Java'; end; { TJavaParser } constructor TJavaParser.Create; begin inherited; ClassImports := TStringList.Create; FullImports := TStringList.Create; NameCache := TStringList.Create; NameCache.Sorted := True; NameCache.Duplicates := dupIgnore; end; destructor TJavaParser.Destroy; begin inherited; if Assigned(FStream) then FreeAndNil(FStream); ClassImports.Free; FullImports.Free; NameCache.Free; end; function TJavaParser.SkipToken(const what: string): Boolean; begin Result := False; GetNextToken; if Token = what then begin GetNextToken; Result := True; end; end; function TJavaParser.SkipPair(const open, close: string): Boolean; procedure InternalSkipPair(const open, close: string); begin while (Token <> close) and (Token<>'') do begin GetNextToken; while Token = open do InternalSkipPair(open, close); end; GetNextToken; end; begin Result := False; InternalSkipPair(open, close); if Token <> '' then Result := True; end; procedure TJavaParser.EatWhiteSpace; var inComment, continueLastComment, State: Boolean; procedure EatOne; begin if inComment then Comment := Comment + GetChar else GetChar; end; function EatWhite: Boolean; begin Result := False; while not (FCurrPos^ in [#0, #33..#255]) do begin Result := True; EatOne; end; end; function EatStarComment: Boolean; begin Result := True; while (not ((FCurrPos^ = '*') and ((FCurrPos + 1)^ = '/'))) or (FCurrPos^=#0) do begin Result := True; EatOne; end; continueLastComment := False; inComment := False; EatOne; EatOne; end; function EatSlashComment: Boolean; begin Result := True; while (FCurrPos^ <> #13) and (FCurrPos^ <> #10) and (FCurrPos^ <> #0) do begin Result := True; EatOne; end; continueLastComment := True; inComment := False; while FCurrPos^ in [#13,#10] do EatOne; end; begin inComment := False; continueLastComment := False; State := True; while State do begin State := False; if (FCurrPos^ = #10) or ((FCurrPos^ = #13) and ((FCurrPos + 1)^ = #10)) then continueLastComment := False; if not (FCurrPos^ in [#0,#33..#255]) then State := EatWhite; if (FCurrPos^ = '/') and ((FCurrPos + 1)^ = '*') then begin Comment := ''; EatOne; EatOne; // Skip slash star inComment := True; State := EatStarComment; inComment := False; end; if (FCurrPos^ = '/') and ((FCurrPos + 1)^ = '/') then begin if not continueLastComment then Comment := '' else Comment := Comment + #13#10; EatOne; EatOne; // Skip the double slashes inComment := True; State := EatSlashComment; inComment := False; end; end; end; function TJavaParser.GetNextToken: string; procedure AddOne; begin Token := Token + GetChar; end; begin //Handle qualified identifier as a token //'[', ']', '.' are treated as part of a name if directly after chars Token := ''; EatWhiteSpace; if not TokenPosLocked then FTokenPos := FSourcePos; if FCurrPos^ = '"' then // Parse String begin AddOne; while not (FCurrPos^ in ['"',#0]) do begin if ((FCurrPos^ = '\') and ((FCurrPos + 1)^ in ['"','\'])) then AddOne; AddOne; end; AddOne; end else if FCurrPos^ = '''' then // Parse char begin AddOne; while not (FCurrPos^ in ['''',#0]) do begin if ((FCurrPos^ = '\') and ((FCurrPos + 1)^ in ['''','\'])) then AddOne; AddOne; end; AddOne; end else if FCurrPos^ in ['A'..'Z', 'a'..'z', '_', '$'] then begin //Identifier AddOne; while True do begin while FCurrPos^ in ['A'..'Z', 'a'..'z', '0'..'9', '_'] do AddOne; if FCurrPos^ = '.' then begin AddOne; Continue; end; Break; end; while FCurrPos^ in ['[', ']'] do AddOne; end else if FCurrPos^ in [';', '{', '}', '(', ')', ',', '='] then begin //Single chars AddOne; end else if FCurrPos^ = '[' then //Loose brackets while FCurrPos^ in ['[', ']'] do AddOne else //Everything else, forward to whitespace or interesting char begin while not (FCurrPos^ in [#0, #9, #10, #12, #13, #32, ',', '=', ';', '{', '}', '(', ')', '"', '''']) do AddOne; end; Result := Token; end; procedure TJavaParser.ParseStream(AStream: TStream; AModel: TAbstractPackage; AOM: TObjectModel); var oldCurrentSourcefilename: PString; oldCurrentSourceX: PInteger; oldCurrentSourceY: PInteger; begin if Assigned(FStream) then FreeAndNil(FStream); oldCurrentSourcefilename := uModelEntity.CurrentSourcefilename; oldCurrentSourceX := uModelEntity.CurrentSourceX; oldCurrentSourceY := uModelEntity.CurrentSourceY; uModelEntity.CurrentSourcefilename := @FFileName; uModelEntity.CurrentSourceX := @FTokenPos.X; uModelEntity.CurrentSourceY := @FTokenPos.Y; try FStream := StreamToMemory(AStream); FCurrPos := FStream.Memory; FModel := AModel; FOM := AOM; ParseCompilationUnit; finally uModelEntity.CurrentSourcefilename := oldCurrentSourcefilename; uModelEntity.CurrentSourceX := oldCurrentSourceX; uModelEntity.CurrentSourceY := oldCurrentSourceY; end; end; (* QualifiedIdentifier: Identifier { . Identifier } *) procedure TJavaParser.ParseModifiersOpt; (* ModifiersOpt: { Modifier } Modifier: public protected private static abstract final native synchronized transient volatile strictfp *) begin //Clear flags ModVisibility := viPublic; ModAbstract := False; while True do begin //Set flags based on visibility if Token = 'public' then ModVisibility := viPublic else if Token = 'protected' then ModVisibility := viProtected else if Token = 'private' then ModVisibility := viPrivate else if Token = 'abstract' then ModAbstract := True else if (Token = 'static') or (Token = 'final') or (Token = 'native') or (Token = 'synchronized') or (Token = 'transient') or (Token = 'volatile') or (Token = 'strictfp') then else Break; GetNextToken; end; end; procedure TJavaParser.ParseCompilationUnit; (* CompilationUnit: [package QualifiedIdentifier ; ] {ImportDeclaration} {TypeDeclaration} *) var sUnitName: string; S : string; begin GetNextToken; if Token = 'package' then begin sUnitName := GetNextToken; SkipToken(';'); end else sUnitName := 'Default'; FUnit := (FModel as TLogicPackage).FindUnitPackage(sUnitName); if not Assigned(FUnit) then FUnit := (FModel as TLogicPackage).AddUnit(sUnitName); while Token = 'import' do begin (* ImportDeclaration import Identifier { . Identifier } [ . * ] ; *) S := GetNextToken; if GetNextToken = '*' then begin FullImports.Add( ExtractPackageName(S) ); GetNextToken; end else begin ClassImports.Values[ ExtractClassName(S) ] := ExtractPackageName(S); // NeedClassifier(S); end; GetNextToken; end; while Token<>'' do ParseTypeDeclaration; end; procedure TJavaParser.ParseTypeDeclaration; (* TypeDeclaration: ClassOrInterfaceDeclaration ; ClassOrInterfaceDeclaration: ModifiersOpt (ClassDeclaration | InterfaceDeclaration) InterfaceDeclaration: interface Identifier [extends TypeList] InterfaceBody *) begin ParseModifiersOpt; if Token = 'class' then ParseClassDeclaration else if Token = 'interface' then ParseInterfaceDeclaration else if Token = ';' then GetNextToken else //**error // raise Exception.Create('JavaParser error') GetNextToken ; end; procedure TJavaParser.ParseClassDeclaration(IsInner : boolean = False; const ParentName : string = ''); (* ClassDeclaration: class Identifier [extends Type] [implements TypeList] ClassBody ClassBody: { {ClassBodyDeclaration} } ClassBodyDeclaration: ; [static] Block ModifiersOpt MemberDecl MemberDecl: MethodOrFieldDecl void Identifier MethodDeclaratorRest Identifier ConstructorDeclaratorRest ClassOrInterfaceDeclaration MethodOrFieldDecl: Type Identifier MethodOrFieldRest MethodOrFieldRest: VariableDeclaratorRest MethodDeclaratorRest *) var C: TClass; Int: TInterface; TypeName, Ident: string; begin GetNextToken; C := FUnit.AddClass(Token); SetVisibility(C); GetNextToken; if Token = 'extends' then begin C.Ancestor := NeedClassifier(GetNextToken, True, TClass) as TClass; GetNextToken; end; if Token = 'implements' then begin repeat Int := NeedClassifier(GetNextToken, True, TInterface) as TInterface; if Assigned(Int) then C.AddImplements(Int); GetNextToken; until Token <> ','; end; if Token = '{' then begin GetNextToken; while True do begin ParseModifiersOpt; if Token = '{' then //Static initializer SkipPair('{', '}') else if Token = ';' then //single semicolon GetNextToken else if Token = 'class' then //Inner class ParseClassDeclaration(True,C.Name) else if Token = 'interface' then //Inner interface ParseInterfaceDeclaration else if (Token = '}') or (Token='') then begin //End of class declaration GetNextToken; Break; end else begin //Must be typename for attr or operation //Or constructor TypeName := GetTypeName; if (TypeName = C.Name) and (Token = '(') then begin Ident := TypeName; //constructor TypeName := ''; end else begin TokenPosLocked := True; Ident := Token; GetNextToken; end; if Token = '(' then begin //Operation DoOperation(C.AddOperation(Ident), C.Name, TypeName); GetNextToken; //')' //Skip Throws if present while (Token<>';') and (Token <> '{') and (Token <> '') do GetNextToken; //Either ; for abstract method or { for body if Token='{' then SkipPair('{', '}'); end else begin //Attributes DoAttribute(C.AddAttribute(Ident), TypeName); while Token = ',' do begin DoAttribute(C.AddAttribute(GetNextToken), TypeName); GetNextToken; end; Comment := ''; end; end; end; end; //Parent name is added last to make constructors etc to work //**Is this sufficent if IsInner then C.Name := ParentName + '.' + C.Name; end; procedure TJavaParser.ParseInterfaceDeclaration; (* InterfaceDeclaration: interface Identifier [extends TypeList] InterfaceBody InterfaceBody: { {InterfaceBodyDeclaration} } InterfaceBodyDeclaration: ; ModifiersOpt InterfaceMemberDecl InterfaceMemberDecl: InterfaceMethodOrFieldDecl void Identifier VoidInterfaceMethodDeclaratorRest ClassOrInterfaceDeclaration InterfaceMethodOrFieldDecl: Type Identifier InterfaceMethodOrFieldRest InterfaceMethodOrFieldRest: ConstantDeclaratorsRest ; InterfaceMethodDeclaratorRest InterfaceMethodDeclaratorRest: FormalParameters BracketsOpt [throws QualifiedIdentifierList] ; VoidInterfaceMethodDeclaratorRest: FormalParameters [throws QualifiedIdentifierList] ; *) var Int: TInterface; TypeName, Ident: string; begin GetNextToken; Int := FUnit.AddInterface(Token); SetVisibility(Int); GetNextToken; if Token = 'extends' then begin Int.Ancestor := NeedClassifier(GetNextToken, True, TInterface) as TInterface; //**limitation: an java interface can extend several interfaces, but our model only support one ancestor GetNextToken; while Token=',' do begin GetNextToken; GetNextToken; end; end; if Token = '{' then begin GetNextToken; while True do begin ParseModifiersOpt; if Token = ';' then //empty GetNextToken else if Token = 'class' then //Inner class ParseClassDeclaration else if Token = 'interface' then //Inner interface ParseInterfaceDeclaration else if (Token = '}') or (Token='') then begin //End of interfacedeclaration GetNextToken; Break; end else begin //Must be type of attr or return type of operation TypeName := GetTypeName; Ident := Token; TokenPosLocked := True; if GetNextToken = '(' then begin //Operation DoOperation(Int.AddOperation(Ident), Int.Name, TypeName); GetNextToken; //Skip Throws if present while (Token<>';') and (Token <> '') do GetNextToken; end else begin DoAttribute(Int.AddAttribute(Ident) , TypeName); while Token = ',' do begin DoAttribute(Int.AddAttribute(GetNextToken), TypeName); GetNextToken; end; Comment := ''; end; end; end; end; end; function TJavaParser.NeedClassifier(const CName: string; Force : boolean = True; TheClass: TModelEntityClass = nil): TClassifier; var PName,ShortName : string; CacheI : integer; function InLookInModel : TClassifier; var U : TUnitPackage; I : integer; begin Result := nil; if PName='' then //No packagename, check in current unit and imports begin //Classimports ( java.util.HashTable ) for I := 0 to ClassImports.Count-1 do //Can not use indexofname because of casesensetivity if ClassImports.Names[I]=ShortName then begin Result := NeedClassifier( ClassImports.Values[ShortName] + '.' + ShortName, False, TheClass ); if Assigned(Result) then Break; end; //Fullimports ( java.util.* ) if not Assigned(Result) then begin for I := 0 to FullImports.Count-1 do begin Result := NeedClassifier( FullImports[I] + '.' + ShortName, False, TheClass ); if Assigned(Result) then Break; end; end; //Check in current unit if not Assigned(Result) then Result := FUnit.FindClassifier(ShortName,False,TheClass,True); end else //Packagename, look for package begin U := FOM.ModelRoot.FindUnitPackage(PName); if not Assigned(U) then //Try to find shortname.java file in all known paths //Then look in model again //**Not sufficient, finds List.java first in awt when it is List.java in util that is needed //**Should iterate all .java files that have shortname if NeedSource(ShortName) then U := FOM.ModelRoot.FindUnitPackage(PName); if Assigned(U) then Result := U.FindClassifier(ShortName,False,TheClass,True); end; end; begin //First of all, look in cache of names we have already looked up //Optimization that saves a lot of time for large projects CacheI := NameCache.IndexOf(CName); //Stringlist indexof is not casesensitive so we must double check if (CacheI<>-1) and (NameCache[CacheI]=CName) and ((TheClass=nil) or (NameCache.Objects[CacheI] is TheClass)) then begin Result := TClassifier(NameCache.Objects[CacheI]); Exit; end; PName := ExtractPackageName(CName); ShortName := ExtractClassName(CName); //Look in the model Result := InLookInModel; //Otherwise see if we can find the file we need if not Assigned(Result) then if NeedSource(ShortName) then Result := InLookInModel; if not Assigned(Result) then begin //Look in unknown Result := FOM.UnknownPackage.FindClassifier(CName,False,TheClass,True); if Force and (not Assigned(Result)) then begin //Missing, create in unknown (if Force) if (TheClass=nil) or (TheClass=TClass) then Result := FOM.UnknownPackage.AddClass(CName) else if TheClass=TInterface then Result := FOM.UnknownPackage.AddInterface(CName) else if TheClass=TDataType then Result := FOM.UnknownPackage.AddDataType(CName) end; end; if Assigned(Result) and (CacheI=-1) then NameCache.AddObject(CName,Result); if Force and (not Assigned(Result)) then raise Exception.Create(ClassName + ' failed to locate ' + Cname); end; //Set visibility based on flags assigned by parseOptModifier procedure TJavaParser.SetVisibility(M: TModelEntity); begin M.Visibility := ModVisibility; if ModAbstract and (M is TOperation) then (M as TOperation).IsAbstract := ModAbstract; end; function TJavaParser.GetChar: char; begin Result := FCurrPos^; if Result<>#0 then Inc(FCurrPos); if FCurrPos^ = #10 then begin Inc(FSourcePos.Y); FSourcePos.X := 0; end else Inc(FSourcePos.X); end; procedure TJavaParser.DoOperation(O: TOperation; const ParentName, TypeName: string); var ParType: string; begin TokenPosLocked := False; SetVisibility(O); if (TypeName <> '') and (TypeName <> 'void') then O.ReturnValue := NeedClassifier(TypeName); if Assigned(O.ReturnValue) then O.OperationType := otFunction else if ParentName = O.Name then O.OperationType := otConstructor else O.OperationType := otProcedure; //Parameters GetNextToken; while (Token<>'') and (Token <> ')') do begin if Token = 'final' then GetNextToken; ParType := GetTypeName; O.AddParameter(Token).TypeClassifier := NeedClassifier(ParType); GetNextToken; if Token=',' then GetNextToken; end; O.Documentation.Description := Comment; Comment := ''; end; procedure TJavaParser.DoAttribute(A: TAttribute; const TypeName: string); begin TokenPosLocked := False; SetVisibility(A); if Token = '=' then while (Token <> ';') and (Token<>'') do begin GetNextToken; //Attribute initializers can hold complete inner class declarations if Token='{' then SkipPair('{','}'); end; A.TypeClassifier := NeedClassifier(TypeName); A.Documentation.Description := Comment; if Token=';' then GetNextToken; end; //Handles that a typename can be followed by a separate [] function TJavaParser.GetTypeName: string; (* Type: Identifier { . Identifier } BracketsOpt BasicType *) begin Result := Token; GetNextToken; if (Length(Token)>0) and (Token[1]='[') then begin Result := Result + Token; GetNextToken; end; end; //Call needpackage //Note that 'package' in javaparser is a .java-file function TJavaParser.NeedSource(const SourceName: string): boolean; var Str : TStream; Parser : TJavaParser; sFileName : string; begin Result := False; if Assigned(NeedPackage) then begin sFileName := NeedPackage(SourceName,Str{%H-}); if Assigned(Str) then begin Parser := TJavaParser.Create; try Parser.FileName := sFileName; Parser.NeedPackage := NeedPackage; Parser.ParseStream(Str, FOM.ModelRoot, FOM); finally Parser.Free; end; Result := True; end; end; end; initialization Integrators.Register(TJavaImporter); end.
unit UPlanoContasVO; interface uses Atributos, Classes, Constantes, Generics.Collections, SysUtils, UGenericVO, UCondominioVO, UUnidadeVO, UPessoasVO; type [TEntity] [TTable('PlanoContas')] TPlanoContasVO = class(TGenericVO) private FidPlanoContas : Integer; FidConta: Integer; FdsConta : string; FnrClassificacao : string; FflTipo: string; FidCondominio : Integer; FidUnidade : Integer; FidPessoa : Integer; public CondominioVO : TCondominioVO; UnidadeVO : TUnidadeVO; PessoaVO : TPessoasVO; [TId('idPlanoContas')] [TGeneratedValue(sAuto)] property idPlanoContas : Integer read FidPlanoContas write FidPlanoContas; [TColumn('idConta','Código',0,[ldLookup,ldComboBox], False)] property idConta: Integer read FidConta write FidConta; [TColumn('nrClassificacao','Classificação',200,[ldGrid,ldLookup,ldComboBox], False)] property nrClassificacao: string read FnrClassificacao write FnrClassificacao; [TColumn('dsConta','Conta',400,[ldGrid,ldLookup,ldComboBox], False)] property dsConta: string read FdsConta write FdsConta; [TColumn('flTipo','Tipo',10,[ldGrid,ldLookup,ldComboBox], False)] property flTipo: string read FflTipo write FflTipo; [TColumn('idCondominio','Condomínio',0,[ldLookup,ldComboBox], False)] property idcondominio: integer read Fidcondominio write Fidcondominio; [TColumn('idUnidade','Unidade',0,[ldLookup,ldComboBox], False)] property idUnidade: integer read FidUnidade write FidUnidade; [TColumn('idPessoa','Pessoa',0,[ldLookup,ldComboBox], False)] property idPessoa: integer read FidPessoa write FidPessoa; Procedure ValidarCamposObrigatorios; // Function Classificacao(Str: String): String; end; implementation { function TPlanoContasVO.Classificacao(Str: String): String; begin begin if (Self.FflTipo = '0' ) then else if Length(Str)=14 then Result:='99.999.999/9999-99;0; ' else Result:='99999999999999;0; '; end; end; } Procedure TPlanoContasVO.ValidarCamposObrigatorios; begin if (Self.FdsConta = '') then begin raise Exception.Create('O campo Descrição é obrigatório!'); end else if (self.FnrClassificacao = '') then begin raise Exception.Create('O campo Classificação é obrigatório!'); end; end; end.
PROGRAM birthday; { This program is a small example of the use of the random access facilities in the file RANDREC.PAS. In fact this simple program could be written more efficiently using several ordinary sequential files. } CONST rsize=38; {the record size : calculated below } TYPE name= ARRAY[1..32] OF CHAR; rec= RECORD n:name; {32 bytes } day,month,year:INTEGER { 6 bytes } END; VAR f: TEXT; r: rec; com: CHAR; {$F RANDREC } FUNCTION upper(c:CHAR):CHAR; BEGIN IF c IN ['a'..'z'] THEN c:=CHR(ORD(c)-ORD('a')+ORD('A')); upper:=c END; PROCEDURE NewFile; BEGIN REWRITE(f,' BIRTHDAY.DAT'); r.n:='}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}'; WRITERAND(f,0,ADDR(r),rsize); END; PROCEDURE GetRec(VAR r:rec); BEGIN WITH r DO BEGIN WRITE('Enter the person''s name '); READLN; READ(n); WRITE('Enter their data of birth dd/mm/yy '); READLN; READ(day); GET(INPUT); READ(month); GET(INPUT); READ(year); END END; PROCEDURE PrintRec(VAR r:rec); VAR i:INTEGER; BEGIN WITH r DO BEGIN FOR i:=1 TO 32 DO IF n[i]<>CHR(0) THEN WRITE(n[i]); WRITELN(day:10,'/',month:2,'/',year:2); END; END; {Finds the number of the last record in the file starting at i } FUNCTION FindEnd(VAR r1:rec;i:INTEGER):INTEGER; VAR dum:BOOLEAN; BEGIN WHILE r1.n[1]<>'}' DO BEGIN i:=i+1; dum:=READRAND(f,i,ADDR(r1),rsize); END; FindEnd:=i; END; PROCEDURE InsertRec(VAR r:rec); VAR r1:rec; i,j:INTEGER; dum:BOOLEAN; BEGIN i:=0; WHILE READRAND(f,i,ADDR(r1),rsize) DO NewFile; WHILE r.n>r1.n DO BEGIN i:=i+1; dum:=READRAND(f,i,ADDR(r1),rsize); END; IF r.n=r1.n THEN WRITERAND(f,i,ADDR(r),rsize) ELSE BEGIN {Insert record in file} FOR j:=FindEnd(r1,i) DOWNTO i DO BEGIN dum:=READRAND(f,j,ADDR(r1),rsize); WRITERAND(f,j+1,ADDR(r1),rsize) END; WRITERAND(f,i,ADDR(r),rsize); END END; FUNCTION DeleteRec(VAR r:rec):BOOLEAN; VAR r1:rec; i,j:INTEGER; dum:BOOLEAN; BEGIN i:=0; IF READRAND(f,i,ADDR(r1),rsize) THEN NewFile; WHILE r1.n<r.n DO BEGIN i:=i+1; dum:=READRAND(f,i,ADDR(r1),rsize); END; IF r.n=r1.n THEN BEGIN {Delete record from file} FOR j:=i+1 TO FindEnd(r1,i) DO BEGIN dum:=READRAND(f,j,ADDR(r1),rsize); WRITERAND(f,j-1,ADDR(r1),rsize) END; DeleteRec:=FALSE; END ELSE DeleteRec:=TRUE END; PROCEDURE Delete; VAR r1:rec; s:name;i:INTEGER; dum:BOOLEAN; BEGIN WRITE('Which name to delete ? '); READLN; READ(r1.n); IF DeleteRec(r1) THEN WRITE(r1.n,' not found'); END; PROCEDURE Print; VAR i:INTEGER; dum:BOOLEAN; r:rec; BEGIN i:=0; REPEAT dum:=READRAND(f,i,ADDR(r),rsize); IF r.n[1] <>'}' THEN PrintRec(r); i:=i+1; UNTIL r.n[1]='}'; END; BEGIN RESET(f,' BIRTHDAY.DAT'); IF EOF(f) THEN NewFile; REPEAT WRITELN; WRITELN('Type one of '); WRITELN('(I)nsert '); WRITELN('(D)elete '); WRITELN('(E)xit '); WRITELN('(P)rint '); READLN; READ(com); CASE upper(com) OF 'I': BEGIN GetRec(r);InsertRec(r) END; 'D': Delete; 'E': CLOSE(f); 'P': Print END; UNTIL upper(com)='E' END. 
unit InfluxDB.Request; interface uses System.SysUtils, System.Net.HttpClient, System.NetEncoding, System.Generics.Collections, System.JSON, System.Variants, System.RTTI, InfluxDB.Core, InfluxDB.Interfaces, System.DateUtils; type TInfluxResult = class(TInterfacedObject, IInfluxResult) private FResponse: IHTTPResponse; FResult: TArray<TResultStatement>; protected procedure ParseResponse(Response: IHTTPResponse); function GetHTTPResponse: IHTTPResponse; function GetResult: TArray<TResultStatement>; public property Response: IHTTPResponse read GetHTTPResponse; property Result: TArray<TResultStatement> read GetResult; function GetNameValues: TArray<String>; class function CreateResult: IInfluxResult; overload; class function CreateResult(Response: IHTTPResponse): IInfluxResult; overload; end; TInfluxRequest = class(TRequest, IInfluxRequest) private FPort: Integer; FHost: String; FUsername: String; FPassword: String; protected function EndPoint: String; function Auth : String; public property Host: String read FHost write FHost; property Port: Integer read FPort write FPort; property Username: String read FUsername write FUsername; property Password: String read FPassword write FPassword; function CreateDatabase(DatabaseName: String; Duration: Integer; DurationUnit: TDurationUnit = duDay): Boolean; overload; function CreateDatabase(DatabaseName: String; Duration: Integer; out Response: IHTTPResponse; DurationUnit: TDurationUnit = duDay): Boolean; overload; function ShowDatabases: TArray<String>; function ShowMeasurements(Database: String): TArray<String>; function ServerVersion: String; function Query(Database: String; QueryString: String): IInfluxResult; function Write(Database: String; ValueString: String): Boolean; overload; function Write(Database: String; ValueString: String; out Response: IHTTPResponse): Boolean; overload; function Write(Database: String; Value: TInfluxValue): Boolean; overload; function Write(Database: String; Value: TInfluxValue; out Response: IHTTPResponse): Boolean; overload; end; implementation { TInfluxDBRequest } function TInfluxRequest.CreateDatabase(DatabaseName: String; Duration: Integer; DurationUnit: TDurationUnit = duDay): Boolean; var LResp: IHTTPResponse; begin Result := CreateDatabase(DatabaseName, Duration, LResp, DurationUnit); end; function TInfluxRequest.CreateDatabase(DatabaseName: String; Duration: Integer; out Response: IHTTPResponse; DurationUnit: TDurationUnit = duDay): Boolean; var LUrl, LStmt: String; LUnit: String; begin LUrl := EndPoint + '/query' + Auth; case DurationUnit of duWeek: LUnit := 'w'; duDay: LUnit := 'd'; duHour: LUnit := 'h'; duMinute: LUnit := 'm'; else LUnit := 'd'; end; LStmt := 'CREATE DATABASE ' + DatabaseName.QuotedString('"') + ' WITH DURATION ' + Duration.ToString + LUnit + ' REPLICATION 1'; QueryParams.AddOrSetValue('q', LStmt); Response := Post(LUrl, ''); Result := Response.StatusCode = 200; end; function TInfluxRequest.EndPoint: String; begin Result := 'http://' + Host + ':' + Port.ToString; end; function TInfluxRequest.Auth : String; begin if (Username <> '') then begin Result := '?u=' + Username + '&p=' + Password; end else Result := ''; end; function TInfluxRequest.Query(Database, QueryString: String): IInfluxResult; var LUrl: String; LResp: IHTTPResponse; begin LUrl := EndPoint + '/query' + Auth; QueryParams.AddOrSetValue('db', Database); QueryParams.AddOrSetValue('q', QueryString); LResp := Get(LUrl); Result := TInfluxResult.CreateResult(LResp); end; function TInfluxRequest.Write(Database, ValueString: String): Boolean; var LResp: IHTTPResponse; begin Result := Write(Database, ValueString, LResp); end; function TInfluxRequest.Write(Database: String; Value: TInfluxValue): Boolean; var LResp: IHTTPResponse; begin Result := Write(Database, Value, LResp); end; function TInfluxRequest.ServerVersion: String; var LUrl: String; LResp: IHTTPResponse; LObj: TJSONObject; LVal: TJSONValue; begin Result := ''; LUrl := EndPoint + '/ping' + Auth; QueryParams.AddOrSetValue('verbose', 'true'); LResp := Get(LUrl); if LResp.StatusCode = 200 then begin LObj := TJSONObject.ParseJSONValue(LResp.ContentAsString(TEncoding.UTF8)) as TJSONObject; if LObj <> nil then begin if LObj.TryGetValue('version', LVal) then Result := LVal.Value; LObj.Free; end; end; end; function TInfluxRequest.ShowDatabases: TArray<String>; var LUrl, LStmt: String; LResp: IHTTPResponse; LResult: IInfluxResult; begin LUrl := EndPoint + '/query' + Auth; LStmt := 'SHOW DATABASES'; Self.QueryParams.AddOrSetValue('q', LStmt); LResp := Self.Get(LUrl); SetLength(Result, 0); if LResp.StatusCode = 200 then begin LResult := TInfluxResult.CreateResult(LResp); Result := LResult.GetNameValues; end; end; function TInfluxRequest.ShowMeasurements(Database: String): TArray<String>; var LUrl, LStmt: String; LResp: IHTTPResponse; LResult: IInfluxResult; begin LUrl := EndPoint + '/query' + Auth; LStmt := 'SHOW MEASUREMENTS ON ' + Database; Self.QueryParams.AddOrSetValue('q', LStmt); LResp := Self.Get(LUrl); SetLength(Result, 0); if LResp.StatusCode = 200 then begin LResult := TInfluxResult.CreateResult(LResp); Result := LResult.GetNameValues; end; end; function TInfluxRequest.Write(Database: String; Value: TInfluxValue; out Response: IHTTPResponse): Boolean; begin if Value.TimeStamp > 0 then QueryParams.AddOrSetValue('precision', 's'); Result := Write(Database, Value.AsString, Response); end; function TInfluxRequest.Write(Database, ValueString: String; out Response: IHTTPResponse): Boolean; var LUrl: String; begin LUrl := EndPoint + '/write' + Auth; QueryParams.AddOrSetValue('db', Database); Response := Post(LUrl, ValueString); Result := (Response.StatusCode = 204); end; { TInfluxResult } class function TInfluxResult.CreateResult: IInfluxResult; begin Result := TInfluxResult.Create; end; class function TInfluxResult.CreateResult(Response: IHTTPResponse): IInfluxResult; var R: TInfluxResult; begin R := TInfluxResult.Create; R.ParseResponse(Response); Result := R; end; function TInfluxResult.GetHTTPResponse: IHTTPResponse; begin Result := FResponse; end; function TInfluxResult.GetNameValues: TArray<String>; var LObj: TJSONObject; LVal: TJSONValue; LArr: TJSONArray; I: Integer; begin LObj := TJSONObject.ParseJSONValue(FResponse.ContentAsString(TEncoding.UTF8)) as TJSONObject; if LObj.TryGetValue('results', LArr) then begin LVal := LArr.Items[0]; if TJSONObject(LVal).TryGetValue('series', LArr) then begin LVal := LArr.Items[0]; if TJSONObject(LVal).TryGetValue('values', LArr) then begin SetLength(Result, LArr.Count); for I := 0 to LArr.Count -1 do Result[I] := TJSONArray(LArr.Items[I]).Items[0].Value; end; end; end; LObj.Free; end; function TInfluxResult.GetResult: TArray<TResultStatement>; begin ParseResponse(FResponse); Result := FResult; end; procedure TInfluxResult.ParseResponse(Response: IHTTPResponse); var LObj: TJSONObject; LStArr, LSerArr, LValArr, LFieldArr: TJSONArray; I, J, K, L, Cols: Integer; begin FResponse := Response; SetLength(FResult, 0); Cols := 0; LObj := TJSONObject.ParseJSONValue(FResponse.ContentAsString(TEncoding.UTF8)) as TJSONObject; if LObj <> nil then begin if LObj.TryGetValue('results', LStArr) then begin SetLength(FResult, LStArr.Count); for I := 0 to LStArr.Count -1 do begin FResult[I].Id := LStArr.Items[I].GetValue<Integer>('statement_id', -1); LSerArr := LStArr.Items[I].GetValue<TJSONArray>('series', nil); if LSerArr <> nil then begin SetLength(FResult[I].Series, LSerArr.Count); for J := 0 to LSerArr.Count -1 do begin FResult[I].Series[J] := TResultSerie.Create; FResult[I].Series[J].Name := LSerArr.Items[J].P['name'].Value; LValArr := LSerArr.Items[J].GetValue<TJSONArray>('columns', nil); if LValArr <> nil then begin Cols := LValArr.Count; SetLength(FResult[I].Series[J].Columns, Cols); for K := 0 to LValArr.Count -1 do FResult[I].Series[J].Columns[K] := LValArr.Items[K].Value; end; LValArr := LSerArr.Items[J].GetValue<TJSONArray>('values', nil); if LValArr <> nil then begin SetLength(FResult[I].Series[J].Values, LValArr.Count); for K := 0 to LValArr.Count -1 do begin LFieldArr := LValArr.Items[K].GetValue<TJSONArray>(); if LFieldArr <> nil then begin SetLength(FResult[I].Series[J].Values[K].Columns, Cols); for L := 0 to Cols -1 do begin FResult[I].Series[J].Values[K].Columns[L].Key := FResult[I].Series[J].Columns[L]; if FResult[I].Series[J].Columns[L] = 'time' then FResult[I].Series[J].Values[K].Columns[L].Value := TValue.From<TDateTime>(System.DateUtils.ISO8601ToDate(LFieldArr.Items[L].Value)) else begin if LFieldArr.Items[L] is TJSONString then FResult[I].Series[J].Values[K].Columns[L].Value := TValue.From<String>(LFieldArr.Items[L].Value) else if LFieldArr.Items[L] is TJSONNull then FResult[I].Series[J].Values[K].Columns[L].Value := TValue.FromVariant(null) else if LFieldArr.Items[L] is TJSONNumber then FResult[I].Series[J].Values[K].Columns[L].Value := TValue.From<Double>(LFieldArr.Items[L].GetValue<Double>) else if LFieldArr.Items[L] is TJSONTrue then FResult[I].Series[J].Values[K].Columns[L].Value := TValue.From<Boolean>(True) else if LFieldArr.Items[L] is TJSONFalse then FResult[I].Series[J].Values[K].Columns[L].Value := TValue.From<Boolean>(False); end; end; end; end; end; end; end; end; end; LObj.Free; end; end; end.
unit Utils; interface procedure PrintSwitchValue(const Switch, Value: string); inline; implementation procedure PrintSwitchValue(const Switch, Value: string); inline; begin WriteLn(#9, Switch, #9, Value); end; end.
unit uModel; interface type tUserInfo = class private FPassword: String; FUser: string; FRole: string; FLoginTime: TDateTime; procedure SetPassword(const Value: String); procedure SetUser(const Value: string); procedure SetRole(const Value: string); procedure SetLoginTime(const Value: TDateTime); published property User: string read FUser write SetUser; property Password: String read FPassword write SetPassword; property Role:string read FRole write SetRole; property LoginTime: TDateTime read FLoginTime write SetLoginTime; end; implementation { tUserInfo } procedure tUserInfo.SetLoginTime(const Value: TDateTime); begin FLoginTime := Value; end; procedure tUserInfo.SetPassword(const Value: String); begin FPassword := Value; end; procedure tUserInfo.SetRole(const Value: string); begin FRole := Value; end; procedure tUserInfo.SetUser(const Value: string); begin FUser := Value; end; end.
//------------------------------------------------------------------------------ //MapQueries UNIT //------------------------------------------------------------------------------ // What it does- // Map related database routines // // Changes - // February 12th, 2008 // //------------------------------------------------------------------------------ unit MapQueries; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses {RTL/VCL} Classes, {Project} QueryBase, MapTypes, MapList, {3rd Party} ZSqlUpdate ; type //------------------------------------------------------------------------------ //TMapQueries CLASS //------------------------------------------------------------------------------ TMapQueries = class(TQueryBase) protected public Function CantSave( const MapName : String ) : Boolean; Function GetZoneID( const MapName : string ): Integer; Procedure LoadFlags( var Flags : TFlags; const MapName : String ); Procedure LoadList( const MapList: TMapList; const ZoneID : LongWord ); end; //------------------------------------------------------------------------------ implementation uses {RTL/VCL} SysUtils, Types, {Project} Map, {3rd Party} ZDataset, DB //none ; //------------------------------------------------------------------------------ //CantSave FUNCTION //------------------------------------------------------------------------------ // What it does- // checks to see if we can save on a map // // Changes - // February 12th, 2008 - RaX - Created. // //------------------------------------------------------------------------------ function TMapQueries.CantSave( const MapName : String ) : Boolean; const AQuery = 'SELECT no_return_on_dc FROM maps WHERE map_name=:MapName;'; var ADataSet : TZQuery; AParam : TParam; NoReturnOnDC: Integer; begin Result := TRUE; ADataSet := TZQuery.Create(nil); try //MapName AParam := ADataset.Params.CreateParam(ftString, 'MapName', ptInput); AParam.AsString := MapName; ADataSet.Params.AddParam( AParam ); Query(ADataSet, AQuery); ADataset.First; if NOT ADataSet.Eof then begin noReturnOnDC := ADataset.Fields[0].AsInteger; if NoReturnOnDC = 0 then begin Result := FALSE; end; end; finally ADataSet.Free; end; end;//CantSave //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //GetZoneID FUNCTION //------------------------------------------------------------------------------ // What it does- // Gets a map's zone id // // Changes - // February 12th, 2008 - RaX - Created. // //------------------------------------------------------------------------------ function TMapQueries.GetZoneID( const MapName : String ) : integer; const AQuery = 'SELECT zone_id FROM maps WHERE map_name=:MapName;'; var ADataSet : TZQuery; AParam : TParam; begin Result := 0; ADataSet := TZQuery.Create(nil); try //MapName AParam := ADataset.Params.CreateParam(ftString, 'MapName', ptInput); AParam.AsString := MapName; ADataSet.Params.AddParam( AParam ); Query(ADataSet, AQuery); ADataset.First; if NOT ADataSet.Eof then begin Result := ADataset.Fields[0].AsInteger; end; finally ADataSet.Free; end; end;//GetZoneID //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //LoadFlags FUNCTION //------------------------------------------------------------------------------ // What it does- // Loads a map's flags // // Changes - // February 12th, 2008 - RaX - Created. // //------------------------------------------------------------------------------ procedure TMapQueries.LoadFlags( var Flags : TFlags; const MapName : string ); const AQuery = 'SELECT memo, no_return_on_dc, teleport, item_drop, exp_loss, pvp, '+ 'pvp_nightmare, guild_pvp, items, skill, dead_branches, fly_wings, '+ 'butterfly_wings, turbo_track, no_party, no_guild, weather FROM maps '+ 'WHERE map_name=:MapName;'; var ADataSet : TZQuery; AParam : TParam; Weather : Integer; begin Weather := 0; ADataSet := TZQuery.Create(nil); try //MapName AParam := ADataset.Params.CreateParam(ftString, 'MapName', ptInput); AParam.AsString := MapName; ADataSet.Params.AddParam( AParam ); Query(ADataSet, AQuery); ADataSet.First; if NOT ADataSet.Eof then begin Flags.Memo := Boolean(ADataset.Fields[0].AsInteger); Flags.NoReturnOnDC := Boolean(ADataset.Fields[1].AsInteger); Flags.Teleport := Boolean(ADataset.Fields[2].AsInteger); Flags.ItemDrop := Boolean(ADataset.Fields[3].AsInteger); Flags.ExpLoss := Boolean(ADataset.Fields[4].AsInteger); Flags.PvP := Boolean(ADataset.Fields[5].AsInteger); Flags.PvPNightmare := Boolean(ADataset.Fields[6].AsInteger); Flags.GuildPvP := Boolean(ADataset.Fields[7].AsInteger); Flags.Items := Boolean(ADataset.Fields[8].AsInteger); Flags.Skill := Boolean(ADataset.Fields[9].AsInteger); Flags.DeadBranches := Boolean(ADataset.Fields[10].AsInteger); Flags.FlyWings := Boolean(ADataset.Fields[11].AsInteger); Flags.ButterflyWings := Boolean(ADataset.Fields[12].AsInteger); Flags.TurboTrack := Boolean(ADataset.Fields[13].AsInteger); Flags.NoParty := Boolean(ADataset.Fields[14].AsInteger); Flags.NoGuild := Boolean(ADataset.Fields[15].AsInteger); Weather := ADataset.Fields[16].AsInteger; end; //initialize weather Flags.Rain := FALSE; Flags.Snow := FALSE; Flags.Sakura := FALSE; Flags.Fog := FALSE; Flags.Leaves := FALSE; Flags.Smog := FALSE; //Figure out weather. case Weather of 1 : Flags.Rain := TRUE; 2 : Flags.Snow := TRUE; 3 : Flags.Sakura := TRUE; 4 : Flags.Fog := TRUE; 5 : Flags.Leaves := TRUE; 6 : Flags.Smog := TRUE; end; finally ADataSet.Free; end; end;//LoadFlags //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //LoadList FUNCTION //------------------------------------------------------------------------------ // What it does- // Loads a map list for a zone // // Changes - // February 12th, 2008 - RaX - Created. // //------------------------------------------------------------------------------ procedure TMapQueries.LoadList( const MapList : TMapList; const ZoneID : LongWord ); const AQuery = 'SELECT id, map_name FROM maps '+ 'WHERE zone_id=:ID;'; var ADataSet : TZQuery; AParam : TParam; AMap : TMap; begin ADataSet := TZQuery.Create(nil); try //ID AParam := ADataset.Params.CreateParam(ftString, 'ID', ptInput); AParam.AsInteger:= ZoneID; ADataSet.Params.AddParam( AParam ); Query(ADataSet, AQuery); ADataSet.First; while NOT ADataSet.Eof do begin AMap := TMap.Create; AMap.ID := ADataset.Fields[0].AsInteger; AMap.Name := ADataset.Fields[1].AsString; MapList.Add(AMap); ADataset.Next; end; finally ADataSet.Free; end; end;//GetZoneID //------------------------------------------------------------------------------ end.
unit DBUnic; interface uses SysUtils, stmDatabase2, stmObj, stmPG, stmMemo1, DBObjects, DBModels, DBManagers, DBQuerySets, ZDbcIntfs, Classes; procedure initCache; function model_is_installed:Boolean; type TDBUnic = class(typeUO) public class function stmClassName:string;override; end; var dbConnector:TDBUnic; function fonctionDBUnic:pointer;pascal; procedure proTDBUnic_InitConnection(protocol,host:String;port:Integer;database,login,password:String;var pu:typeUO);pascal; procedure proTDBUnic_CloseConnection(var pu:typeUO);pascal; procedure proTDBUnic_LaunchCommit(var pu:typeUO);pascal; function constructAnalysisQuery(analysis_type,condition,order:String):String; function constructStatistics:String; {shortcuts for installing or uninstalling the analysis database model} procedure proTDBUnic_InstallAnalysisModel(var pu:typeUO);pascal; {tested} procedure proTDBUnic_UninstallAnalysisModel(var pu:typeUO);pascal; {tested} procedure proTDBUnic_GetModels(var memo:TstmMemo;var pu:typeUO);pascal; {shortcuts for AnalysisType creation, redefinition and deletion} procedure proTDBUnic_DefineAnalysisType(id,usecase,path:String;commit:Boolean;var pu:typeUO);pascal; {tested} procedure proTDBUnic_RenameAnalysisType(old_id,new_id:String;commit:Boolean;var pu:typeUO);pascal; {tested} procedure proTDBUnic_RelocateAnalysisType(id,new_path:String;commit:Boolean;var pu:typeUO);pascal; {tested} procedure proTDBUnic_ExplainAnalysisType(id,usecase:String;commit:Boolean;var pu:typeUO);pascal; {tested} procedure proTDBUnic_RemoveAnalysisType(id:String;commit:Boolean;var pu:typeUO);pascal; {tested} {shortcuts for Input/Output creation, redefinition and deletion} procedure proTDBUnic_DefineInputOutput(analysis_type,name,iotype,iocoding,usecase:String;commit:Boolean;var pu:typeUO);pascal; {tested} procedure proTDBUnic_RemoveInputOutput(analysis_type,name:String;commit:Boolean;var pu:typeUO);pascal; {tested} procedure proTDBUnic_RenameInputOutput(analysis_type,old_name,new_name:String;commit:Boolean;var pu:typeUO);pascal; {tested} procedure proTDBUnic_ExplainInputOutput(analysis_type,name,usecase:String;commit:Boolean;var pu:typeUO);pascal; {tested} {shortcuts for Analysis creation and deletion} procedure proTDBUnic_StoreAnalysis(var analysis_object:TDBObject;commit:Boolean;var pu:typeUO);pascal; {tested} procedure proTDBUnic_RemoveAnalysis(id:String;commit:Boolean;var pu:typeUO);pascal; {tested} procedure proTDBUnic_GetAnalyses(analysis_type,condition,order:String;var resultset:TDBResultSet;var pu:typeUO);pascal; procedure proTDBUnic_GetStatistics(var resultset:TDBResultSet;var pu:typeUO);pascal; procedure proTDBUnic_GetAnalysesAsObjects(analysis_type,condition,order:String;var queryset:TDBQuerySet;var pu:typeUO);pascal; implementation uses DBCache; class function TDBUnic.stmClassName:string; begin result:='DBUnic'; end; function fonctionDBUnic:pointer; begin result:=@dbConnector; end; procedure proTDBUnic_GetModels(var memo:TstmMemo;var pu:typeUO);pascal; var statement:IZStatement; resultset:IZResultSet; query,table:String; begin verifierObjet(typeUO(memo)); memo.memo.Clear; statement := DBConnection.Connection.createStatement; query := 'SELECT table_name FROM information_schema.tables WHERE table_schema = ''public'' AND table_type = ''BASE TABLE'' ORDER BY table_name'; resultset := statement.ExecuteQuery(query); while resultset.Next do begin table := resultset.GetStringByName('table_name'); memo.memo.Lines.add(table); end; end; procedure proTDBUnic_CloseConnection(var pu:typeUO);pascal; begin DBCONNECTION.closeDB; anTypeManager.Free; anManager.Free; ioManager.Free; potManager.Free; subpotManager_bool.Free; subpotManager_int.Free; subpotManager_float.Free; subpotManager_str.Free; inputManager.Free; outputManager.Free; anTypeModel.Free; anModel.Free; ioModel.Free; potModel.Free; subpotModel_bool.Free; subpotModel_int.Free; subpotModel_float.Free; subpotModel_str.Free; inputModel.Free; outputModel.Free; end; function model_is_installed:Boolean; var statement:IZStatement; resultset:IZResultSet; query,table:String; count:Integer; begin statement := DBConnection.Connection.createStatement; query := 'SELECT table_name FROM information_schema.tables WHERE table_schema = ''public'' AND table_type = ''BASE TABLE'' AND table_name LIKE ''analysis_%'' ORDER BY table_name'; resultset := statement.ExecuteQuery(query); count := 0; while resultset.Next do count := count + 1; if count > 0 then Result := True else Result := False; end; procedure initCache; begin {create managers relative analyses} anTypeModel := TDBModel.Create('analysis_component'); anModel := TDBModel.Create('analysis_analysis'); ioModel := TDBModel.Create('analysis_pin'); potModel := TDBModel.Create('analysis_potential'); subpotModel_bool := TDBModel.Create('analysis_potential_boolean'); subpotModel_int := TDBModel.Create('analysis_potential_integer'); subpotModel_float := TDBModel.Create('analysis_potential_float'); subpotModel_str := TDBModel.Create('analysis_potential_string'); inputModel := TDBModel.Create('analysis_analysis_inputs'); outputModel := TDBModel.Create('analysis_analysis_outputs'); {create managers relative analyses} anTypeManager := TDBManager.Create(anTypeModel); anManager := TDBManager.Create(anModel); ioManager := TDBManager.Create(ioModel); potManager := TDBManager.Create(potModel); subpotManager_bool := TDBManager.Create(subpotModel_bool); subpotManager_int := TDBManager.Create(subpotModel_int); subpotManager_float := TDBManager.Create(subpotModel_float); subpotManager_str := TDBManager.Create(subpotModel_str); inputManager := TDBManager.Create(inputModel); outputManager := TDBManager.Create(outputModel); end; procedure proTDBUnic_InitConnection(protocol,host:String;port:Integer;database,login,password:String;var pu:typeUO);pascal; begin { if not assigned(connection) then createPgObject('',typeUO(connection),TDBConnection) else connection.closeDB; connection.connectDB(protocol, host, port, database, login, password); DBCONNECTION := connection; } if DBCONNECTION = nil then DBCONNECTION := TDBConnection.Create else proTDBUnic_CloseConnection(pu); DBCONNECTION.connectDB(protocol, host, port, database, login, password); if model_is_installed then initCache; end; procedure proTDBUnic_LaunchCommit(var pu:typeUO); begin DBCONNECTION.connection.commit; end; procedure proTDBUnic_InstallAnalysisModel(var pu:typeUO); var statement:IZStatement; resultset:IZResultSet; query:String; begin if model_is_installed then raise Exception.Create('Analysis Model Already Installed'); query := 'BEGIN;' + 'CREATE TABLE "analysis_component" (' + ' "id" varchar(256) NOT NULL PRIMARY KEY,' + ' "usecase" text NULL,' + ' "base" boolean NOT NULL,' + ' "package" text NULL,' + ' "language" varchar(16) NULL );' + 'CREATE TABLE "analysis_subcomponent" (' + ' "id" serial NOT NULL PRIMARY KEY,' + ' "component_id" varchar(256) NOT NULL REFERENCES "analysis_component" ("id") DEFERRABLE INITIALLY DEFERRED,'+ ' "subcomponent_id" varchar(256) NOT NULL REFERENCES "analysis_component" ("id") DEFERRABLE INITIALLY DEFERRED,'+ ' "alias" varchar(256) NOT NULL,'+ ' UNIQUE ("component_id", "subcomponent_id", "alias"));'+ 'CREATE TABLE "analysis_pintype" ('+ ' "id" varchar(32) NOT NULL PRIMARY KEY);'+ 'CREATE TABLE "analysis_codingtype" ('+ ' "id" varchar(32) NOT NULL PRIMARY KEY);'+ 'CREATE TABLE "analysis_pin" ( '+ ' "id" serial NOT NULL PRIMARY KEY, '+ ' "component" varchar(256) NOT NULL REFERENCES "analysis_component" ("id") DEFERRABLE INITIALLY DEFERRED,'+ ' "name" varchar(256) NOT NULL,'+ ' "usecase" text NULL,'+ ' "pintype" varchar(32) NOT NULL REFERENCES "analysis_pintype" ("id") DEFERRABLE INITIALLY DEFERRED,'+ ' "codingtype" varchar(32) NULL REFERENCES "analysis_codingtype" ("id") DEFERRABLE INITIALLY DEFERRED,'+ ' UNIQUE ("component", "name"));'+ 'CREATE TABLE "analysis_connection" ('+ ' "id" serial NOT NULL PRIMARY KEY,'+ ' "component" varchar(256) NOT NULL REFERENCES "analysis_component" ("id") DEFERRABLE INITIALLY DEFERRED,'+ ' "pin_left_id" integer NOT NULL REFERENCES "analysis_pin" ("id") DEFERRABLE INITIALLY DEFERRED,'+ ' "pin_right_id" integer NOT NULL REFERENCES "analysis_pin" ("id") DEFERRABLE INITIALLY DEFERRED,'+ ' "alias_left_id" integer NULL REFERENCES "analysis_subcomponent" ("id") DEFERRABLE INITIALLY DEFERRED,'+ ' "alias_right_id" integer NULL REFERENCES "analysis_subcomponent" ("id") DEFERRABLE INITIALLY DEFERRED);'+ 'CREATE TABLE "analysis_potential" ('+ ' "id" serial NOT NULL PRIMARY KEY,'+ ' "pin" integer NOT NULL REFERENCES "analysis_pin" ("id") DEFERRABLE INITIALLY DEFERRED);'+ 'CREATE TABLE "analysis_potential_existing" ('+ ' "potential_ptr_id" integer NOT NULL PRIMARY KEY REFERENCES "analysis_potential" ("id") DEFERRABLE INITIALLY DEFERRED,'+ ' "value_id" integer NOT NULL REFERENCES "analysis_potential" ("id") DEFERRABLE INITIALLY DEFERRED);'+ 'CREATE TABLE "analysis_potential_integer" ('+ ' "potential_ptr_id" integer NOT NULL PRIMARY KEY REFERENCES "analysis_potential" ("id") DEFERRABLE INITIALLY DEFERRED,'+ ' "value" integer NOT NULL);'+ 'CREATE TABLE "analysis_potential_float" ('+ ' "potential_ptr_id" integer NOT NULL PRIMARY KEY REFERENCES "analysis_potential" ("id") DEFERRABLE INITIALLY DEFERRED,'+ ' "value" double precision NOT NULL);'+ 'CREATE TABLE "analysis_potential_string" ('+ ' "potential_ptr_id" integer NOT NULL PRIMARY KEY REFERENCES "analysis_potential" ("id") DEFERRABLE INITIALLY DEFERRED,'+ ' "value" text NOT NULL);'+ 'CREATE TABLE "analysis_potential_date" ('+ ' "potential_ptr_id" integer NOT NULL PRIMARY KEY REFERENCES "analysis_potential" ("id") DEFERRABLE INITIALLY DEFERRED,'+ ' "value" date NOT NULL);'+ 'CREATE TABLE "analysis_potential_time" ('+ ' "potential_ptr_id" integer NOT NULL PRIMARY KEY REFERENCES "analysis_potential" ("id") DEFERRABLE INITIALLY DEFERRED,'+ ' "value" time NOT NULL);'+ 'CREATE TABLE "analysis_potential_datetime" ('+ ' "potential_ptr_id" integer NOT NULL PRIMARY KEY REFERENCES "analysis_potential" ("id") DEFERRABLE INITIALLY DEFERRED,'+ ' "value" timestamp with time zone NOT NULL);'+ 'CREATE TABLE "analysis_potential_boolean" ('+ ' "potential_ptr_id" integer NOT NULL PRIMARY KEY REFERENCES "analysis_potential" ("id") DEFERRABLE INITIALLY DEFERRED,'+ ' "value" boolean NOT NULL);'+ 'CREATE TABLE "analysis_potential_pythonobject" ('+ ' "potential_ptr_id" integer NOT NULL PRIMARY KEY REFERENCES "analysis_potential" ("id") DEFERRABLE INITIALLY DEFERRED,'+ ' "value" text NOT NULL);'+ 'CREATE TABLE "analysis_analysis" ('+ ' "id" varchar(256) NOT NULL PRIMARY KEY,'+ ' "component" varchar(256) NOT NULL REFERENCES "analysis_component" ("id") DEFERRABLE INITIALLY DEFERRED,'+ ' "comments" text NULL);'+ 'CREATE TABLE "analysis_analysis_inputs" ('+ ' "id" serial NOT NULL PRIMARY KEY,'+ ' "analysis_id" varchar(256) NOT NULL REFERENCES "analysis_analysis" ("id") DEFERRABLE INITIALLY DEFERRED,'+ ' "potential_id" integer NOT NULL REFERENCES "analysis_potential" ("id") DEFERRABLE INITIALLY DEFERRED,'+ ' UNIQUE ("analysis_id", "potential_id"));'+ 'CREATE TABLE "analysis_analysis_outputs" ('+ ' "id" serial NOT NULL PRIMARY KEY,'+ ' "analysis_id" varchar(256) NOT NULL REFERENCES "analysis_analysis" ("id") DEFERRABLE INITIALLY DEFERRED,'+ ' "potential_id" integer NOT NULL REFERENCES "analysis_potential" ("id") DEFERRABLE INITIALLY DEFERRED,'+ ' UNIQUE ("analysis_id", "potential_id"));'+ 'CREATE TABLE "analysis_analysis_debugs" ('+ ' "id" serial NOT NULL PRIMARY KEY,'+ ' "analysis_id" varchar(256) NOT NULL REFERENCES "analysis_analysis" ("id") DEFERRABLE INITIALLY DEFERRED,'+ ' "potential_id" integer NOT NULL REFERENCES "analysis_potential" ("id") DEFERRABLE INITIALLY DEFERRED,'+ ' UNIQUE ("analysis_id", "potential_id"));'+ 'CREATE LANGUAGE plpythonu;' + 'CREATE FUNCTION ar_median(ar float8[]) RETURNS float AS $$'+ #13#10 + ' tmp = ar.replace(''{'','''')'+ #13#10 + ' tmp = tmp.replace(''}'','''')'+ #13#10 + ' tmp = tmp.split('','')'+ #13#10 + ' tmp = [float(k) for k in tmp]'+ #13#10 + ' tmp.sort()'+ #13#10 + ' N = len(tmp)'+ #13#10 + ' if N == 0 :'+ #13#10 + ' return 0'+ #13#10 + ' elif N == 1 :'+ #13#10 + ' return tmp[0]'+ #13#10 + ' elif (N%2)==0 :'+ #13#10 + ' return 0.5*(tmp[N/2-1] + tmp[N/2])'+ #13#10 + ' else :'+ #13#10 + ' return float(tmp[N/2])'+ #13#10 + '$$ LANGUAGE plpythonu;'+ 'CREATE AGGREGATE median(float8) (sfunc=array_append,stype=float8[],finalfunc=ar_median,initcond=''{}'');'+ 'CREATE FUNCTION ar_median(ar text[]) RETURNS varchar AS $$'+ #13#10 + ' return None'+ #13#10 + '$$ LANGUAGE plpythonu;'+ 'CREATE AGGREGATE median(text) (sfunc=array_append,stype=text[],finalfunc=ar_median,initcond=''{}'');'+ 'CREATE FUNCTION ar_avg(ar text[]) RETURNS varchar AS $$'+ #13#10 + ' return None'+ #13#10 + '$$ LANGUAGE plpythonu;'+ 'CREATE AGGREGATE avg(text) (sfunc=array_append,stype=text[],finalfunc=ar_avg,initcond=''{}'');'+ { 'CREATE FUNCTION ar_stddev_pop(ar text[]) RETURNS varchar AS $$'+ #13#10 + ' return None'+ #13#10 + '$$ LANGUAGE plpythonu;'+ 'CREATE AGGREGATE stddev_pop(text) (sfunc=array_append,stype=text[],finalfunc=ar_stddev_pop,initcond='''');'+ } 'CREATE FUNCTION ar_stddev_samp(ar text[]) RETURNS varchar AS $$'+ #13#10 + ' return None'+ #13#10 + '$$ LANGUAGE plpythonu;'+ 'CREATE AGGREGATE stddev(text) (sfunc=array_append,stype=text[],finalfunc=ar_stddev_samp,initcond=''{}'');'+ { 'CREATE FUNCTION ar_var_pop(ar text[]) RETURNS varchar AS $$'+ #13#10 + ' return None'+ #13#10 + '$$ LANGUAGE plpythonu;'+ 'CREATE AGGREGATE var_pop(text) (sfunc=array_append,stype=text[],finalfunc=ar_var_pop,initcond='''');'+ 'CREATE FUNCTION ar_var_samp(ar text[]) RETURNS varchar AS $$'+ #13#10 + ' return None'+ #13#10 + '$$ LANGUAGE plpythonu;'+ 'CREATE AGGREGATE variance(text) (sfunc=array_append,stype=text[],finalfunc=ar_var_samp,initcond='''');'+ } 'CREATE FUNCTION ar_min(ar float8[]) RETURNS float AS $$' + #13#10 + ' tmp = ar.replace(''{'','''')' + #13#10 + ' tmp = tmp.replace(''}'','''')' + #13#10 + ' tmp = tmp.split('','')' + #13#10 + ' return min(tmp)' + #13#10 + '$$ LANGUAGE plpythonu;' + 'CREATE AGGREGATE pmin(float8) (sfunc=array_append,stype=float8[],finalfunc=ar_min,initcond=''{}'');' + 'CREATE FUNCTION ar_max(ar float8[]) RETURNS float AS $$' + #13#10 + ' tmp = ar.replace(''{'','''')' + #13#10 + ' tmp = tmp.replace(''}'','''')' + #13#10 + ' tmp = tmp.split('','')' + #13#10 + ' return max(tmp)' + #13#10 + '$$ LANGUAGE plpythonu;' + 'CREATE AGGREGATE pmax(float8) (sfunc=array_append,stype=float8[],finalfunc=ar_max,initcond=''{}'');' + 'CREATE FUNCTION ar_min(ar int[]) RETURNS integer AS $$' + #13#10 + ' tmp = ar.replace(''{'','''')' + #13#10 + ' tmp = tmp.replace(''}'','''')' + #13#10 + ' tmp = tmp.split('','')' + #13#10 + ' return min(tmp)' + #13#10 + '$$ LANGUAGE plpythonu;' + 'CREATE AGGREGATE pmin(int) (sfunc=array_append,stype=int[],finalfunc=ar_min,initcond=''{}'');' + 'CREATE FUNCTION ar_max(ar int[]) RETURNS integer AS $$' + #13#10 + ' tmp = ar.replace(''{'','''')' + #13#10 + ' tmp = tmp.replace(''}'','''')' + #13#10 + ' tmp = tmp.split('','')' + #13#10 + ' return max(tmp)' + #13#10 + '$$ LANGUAGE plpythonu;' + 'CREATE AGGREGATE pmax(int) (sfunc=array_append,stype=int[],finalfunc=ar_max,initcond=''{}'');' + 'CREATE FUNCTION ar_min(ar text[]) RETURNS text AS $$' + #13#10 + ' return None' + #13#10 + '$$ LANGUAGE plpythonu;' + 'CREATE AGGREGATE pmin(text) (sfunc=array_append,stype=text[],finalfunc=ar_min,initcond=''{}'');' + 'CREATE FUNCTION ar_max(ar text[]) RETURNS text AS $$' + #13#10 + ' return None' + #13#10 + '$$ LANGUAGE plpythonu;' + 'CREATE AGGREGATE pmax(text) (sfunc=array_append,stype=text[],finalfunc=ar_max,initcond=''{}'');' + 'CREATE FUNCTION ar_avg_name(ar text[]) RETURNS text AS $$' + #13#10 + ' return ''=== Mean ===''' + #13#10 + '$$ LANGUAGE plpythonu;' + 'CREATE AGGREGATE avg_name(text) (sfunc=array_append,stype=text[],finalfunc=ar_avg_name,initcond=''{}'');' + 'CREATE FUNCTION ar_pmin_name(ar text[]) RETURNS text AS $$ ' + #13#10 + ' return ''=== Min ===''' + #13#10 + '$$ LANGUAGE plpythonu; ' + 'CREATE AGGREGATE pmin_name(text) (sfunc=array_append,stype=text[],finalfunc=ar_pmin_name,initcond=''{}'');' + 'CREATE FUNCTION ar_pmax_name(ar text[]) RETURNS text AS $$' + #13#10 + ' return ''=== Max ===''' + #13#10 + '$$ LANGUAGE plpythonu; ' + 'CREATE AGGREGATE pmax_name(text) (sfunc=array_append,stype=text[],finalfunc=ar_pmax_name,initcond=''{}'');' + 'CREATE FUNCTION ar_median_name(ar text[]) RETURNS text AS $$ ' + #13#10 + ' return ''=== Median ==='' ' + #13#10 + '$$ LANGUAGE plpythonu; ' + 'CREATE AGGREGATE median_name(text) (sfunc=array_append,stype=text[],finalfunc=ar_median_name,initcond=''{}'');' + { 'CREATE FUNCTION ar_stddev_pop_name(ar text[]) RETURNS text AS $$ ' + #13#10 + ' return ''Std Population''' + #13#10 + '$$ LANGUAGE plpythonu;' + 'CREATE AGGREGATE stddev_pop_name(text) (sfunc=array_append,stype=text[],finalfunc=ar_stddev_pop_name,initcond='''');' + } 'CREATE FUNCTION ar_stddev_samp_name(ar text[]) RETURNS text AS $$' + #13#10 + ' return ''=== Std ===''' + #13#10 + '$$ LANGUAGE plpythonu;' + 'CREATE AGGREGATE stddev_name(text) (sfunc=array_append,stype=text[],finalfunc=ar_stddev_samp_name,initcond=''{}'');' + { 'CREATE FUNCTION ar_var_pop_name(ar text[]) RETURNS text AS $$' + #13#10 + ' return ''Variance Population''' + #13#10 + '$$ LANGUAGE plpythonu;' + 'CREATE AGGREGATE var_pop_name(text) (sfunc=array_append,stype=text[],finalfunc=ar_var_pop_name,initcond='''');' + 'CREATE FUNCTION ar_var_samp_name(ar text[]) RETURNS text AS $$' + #13#10 + ' return ''Variance Sample''' + #13#10 + '$$ LANGUAGE plpythonu;' + 'CREATE AGGREGATE variance_name(text) (sfunc=array_append,stype=text[],finalfunc=ar_var_samp_name,initcond='''');' + } {'INSERT INTO analysis_pintype (id) VALUES (''Parameter'');'+} 'INSERT INTO analysis_pintype (id) VALUES (''Input'');'+ 'INSERT INTO analysis_pintype (id) VALUES (''Output'');'+ 'INSERT INTO analysis_codingtype (id) VALUES (''int'');'+ 'INSERT INTO analysis_codingtype (id) VALUES (''float'');'+ 'INSERT INTO analysis_codingtype (id) VALUES (''str'');'+ 'INSERT INTO analysis_codingtype (id) VALUES (''bool'');'+ 'INSERT INTO analysis_codingtype (id) VALUES (''file'');'+ { 'INSERT INTO analysis_codingtype (id) VALUES (''date'');'+ 'INSERT INTO analysis_codingtype (id) VALUES (''time'');'+ 'INSERT INTO analysis_codingtype (id) VALUES (''datetime'');'+ 'INSERT INTO analysis_codingtype (id) VALUES (''file'');'+ 'INSERT INTO analysis_codingtype (id) VALUES (''object'');'+ 'INSERT INTO analysis_codingtype (id) VALUES (''none'');'+ } 'COMMIT;'; statement := DBCONNECTION.connection.createStatement; statement.ExecuteQuery(query); DBCONNECTION.connection.Commit; initCache; end; procedure proTDBUnic_UninstallAnalysisModel(var pu:typeUO); var statement:IZStatement; query:String; begin if not model_is_installed then raise Exception.Create('Analysis Model Not Installed'); query := 'DROP TABLE analysis_potential_integer;' + 'DROP TABLE analysis_potential_float;' + 'DROP TABLE analysis_potential_boolean;' + 'DROP TABLE analysis_potential_string;' + 'DROP TABLE analysis_potential_date;' + 'DROP TABLE analysis_potential_datetime;' + 'DROP TABLE analysis_potential_time;' + 'DROP TABLE analysis_potential_existing;' + 'DROP TABLE analysis_potential_pythonobject;' + 'DROP TABLE analysis_analysis_debugs;' + 'DROP TABLE analysis_analysis_inputs;' + 'DROP TABLE analysis_analysis_outputs;' + 'DROP TABLE analysis_potential;' + 'DROP TABLE analysis_analysis;' + 'DROP TABLE analysis_connection;' + 'DROP TABLE analysis_pin;' + 'DROP TABLE analysis_subcomponent;' + 'DROP TABLE analysis_component;' + 'DROP TABLE analysis_pintype;' + 'DROP TABLE analysis_codingtype;' + 'DROP AGGREGATE median(float8);' + 'DROP FUNCTION ar_median(float8[]);' + 'DROP AGGREGATE median(text);' + 'DROP FUNCTION ar_median(text[]);' + 'DROP AGGREGATE avg(text);' + 'DROP FUNCTION ar_avg(text[]);' + { 'DROP AGGREGATE stddev_pop(text);' + 'DROP FUNCTION ar_stddev_pop(text[]);' + } 'DROP AGGREGATE stddev(text);' + 'DROP FUNCTION ar_stddev_samp(text[]);' + { 'DROP AGGREGATE var_pop(text);' + 'DROP FUNCTION ar_var_pop(text[]);' + 'DROP AGGREGATE variance(text);' + 'DROP FUNCTION ar_var_samp(text[]);' + } 'DROP AGGREGATE pmin(int);' + 'DROP FUNCTION ar_min(int[]);' + 'DROP AGGREGATE pmax(int);' + 'DROP FUNCTION ar_max(int[]);' + 'DROP AGGREGATE pmin(float8);' + 'DROP FUNCTION ar_min(float8[]);' + 'DROP AGGREGATE pmax(float8);' + 'DROP FUNCTION ar_max(float8[]);' + 'DROP AGGREGATE pmin(text);' + 'DROP FUNCTION ar_min(text[]);' + 'DROP AGGREGATE pmax(text);' + 'DROP FUNCTION ar_max(text[]);'+ 'DROP AGGREGATE avg_name(text);'+ 'DROP AGGREGATE pmin_name(text);'+ 'DROP AGGREGATE pmax_name(text);'+ 'DROP AGGREGATE median_name(text);'+ {'DROP AGGREGATE stddev_pop_name(text);'+} 'DROP AGGREGATE stddev_name(text);'+ { 'DROP AGGREGATE var_pop_name(text);'+ 'DROP AGGREGATE variance_name(text);'+ } 'DROP FUNCTION ar_avg_name(text[]);'+ 'DROP FUNCTION ar_pmin_name(text[]);'+ 'DROP FUNCTION ar_pmax_name(text[]);'+ 'DROP FUNCTION ar_median_name(text[]);'+ {'DROP FUNCTION ar_stddev_pop_name(text[]);'+ } 'DROP FUNCTION ar_stddev_samp_name(text[]);'+ { 'DROP FUNCTION ar_var_pop_name(text[]);'+ 'DROP FUNCTION ar_var_samp_name(text[]);'+ } 'DROP LANGUAGE plpythonu;'; statement := DBCONNECTION.connection.createStatement; statement.ExecuteQuery(query); DBCONNECTION.connection.Commit; end; { function constructAnalysisQuery(analysis_type,condition,order:String;connection:TDBConnection):String; var ioModel:TDBModel; ioManager:TDBManager; pins:TDBQuerySet; pin:TDBObject; i:Integer; coding,cls,pinname,pintype,select,from,where,join:String; query:AnsiString; begin select := 'SELECT an.id,an.comments,'; from := ' FROM analysis_analysis as an,'; where := ' WHERE an.component = ''' + analysis_type + ''' AND '; ioModel := TDBModel.Create('analysis_pin',connection.connection); ioManager := TDBManager.Create(ioModel); pins := ioManager.filter('component = ''' + analysis_type + '''','id'); for i:=1 to pins.count do begin pin := pins.objects[i-1]; coding := pin.value['codingtype'].VString; if coding = 'bool' then cls:='boolean'; if coding = 'int' then cls:='integer'; if coding = 'float' then cls:='float'; if coding = 'str' then cls:='string'; if coding = 'file' then cls:='string'; pinname := pin.value['name'].VString; select := select + '"' + pinname + '"' + '.value as "' + pinname + '"'; pintype := pin.value['pintype'].VString; if (pintype = 'Input') or (pintype = 'Parameter') then pintype := 'inputs' else if (pintype = 'Output') then pintype := 'outputs'; join := '(SELECT an.id,pin.name,pottype.value ' + 'FROM analysis_analysis as an,' + 'analysis_potential_' + cls + ' as pottype,' + 'analysis_potential as pot,' + 'analysis_pin as pin,' + 'analysis_analysis_' + pintype + ' as ' + pintype + ' WHERE an.id = ' + pintype + '.analysis_id' + ' AND ' + pintype + '.potential_id = pot.id' + ' AND pot.pin = pin.id' + ' AND pot.id = pottype.potential_ptr_id' + ' AND pin.name = ''' + pinname + ''')' + ' as "' + pinname + '"'; where := where + '"' + pinname + '"' + '.id = an.id'; from := from + join; if i < pins.count then begin select := select + ','; from := from + ','; where := where + ' AND '; end; end; if condition <> '' then where := where + ' AND ' + condition; if order <> '' then query := select + from + where + ' ORDER BY "' + order + '"' else query := select + from + where; constructAnalysisQuery := query; end; } function constructStatistics:String; var i,j:Integer; statistics:TStringList; stat_query,tmp_query,null_row:String; begin if all_fields = nil then raise Exception.create('cannot do statistics before listing analyses'); {some basic analyses} statistics := TStringList.Create; statistics.Add('avg'); statistics.Add('pmin'); statistics.Add('pmax'); statistics.Add('median'); statistics.Add('stddev'); { statistics.Add('stddev_pop'); statistics.Add('var_pop'); statistics.Add('variance'); } stat_query := ''; for i := 1 to statistics.Count do begin tmp_query := 'SELECT ' + statistics[i-1] + '_name(id) as id,' + statistics[i-1] + '(component) as component,' + statistics[i-1] + '(comments) as comments,'; for j := 1 to all_fields.count do begin tmp_query := tmp_query + statistics[i-1] + '("' + all_fields[j-1] + '") as "' + all_fields[j-1] + '"'; if j < all_fields.Count then tmp_query := tmp_query + ','; end; stat_query := stat_query + tmp_query + ' FROM (VALUES ' + LAST_ANALYSES_CONSTRUCT + ') as an(' + LAST_ANALYSES_SELECT + ')'; if LAST_ANALYSES_WHERE <> '' then stat_query := stat_query + ' WHERE ' + LAST_ANALYSES_WHERE; if i < statistics.Count then stat_query := stat_query + ' UNION '; end; statistics.Free; Result := stat_query; end; function constructAnalysisQuery(analysis_type,condition,order:String):String; var delegateManager:TDBManager; analyses,inouts,ios,pins,potentials,subpotentials:TDBQuerySet; analysis,pin,potential,subpotential,inout,void_object:TDBObject; i,j,k,m,pin_id,potential_id,subpotential_id,total_pins, npins,old_npins,index,last_index:Integer; analysis_id,analysis_comments,coding,cls,pintype,oldpinname,pinname,select,from,where,join,query,row,values,value,aliases:String; field_state:TStringList; begin field_state := TStringList.Create; all_fields.Free;{come from cache} all_fields := TStringList.Create; pins := ioManager.filter('component = ''' + analysis_type + '''','id'); select := 'id,component,comments,'; total_pins := pins.count; for i:=1 to total_pins do begin pinname := pins.objects[i-1].value['name'].VString; field_state.Values[pinname] := 'False'; end; LAST_ANALYSES_WHERE := condition; if condition <> '' then where := ' WHERE ' + condition else where := ''; analyses := anManager.filter('component = ''' + analysis_type + '''','id'); value := ''; for i:=1 to analyses.count do begin analysis := analyses.objects[i-1]; analysis_id := analysis.value['id'].VString; analysis_comments := analysis.value['comments'].VString; row := '(''' + analysis_id + ''',''' + analysis_type + ''',''' + analysis_comments + ''','; npins := 0; for j:= 1 to 2 do begin if j = 1 then begin delegateManager := inputManager; pintype := 'Input'; end else begin delegateManager := outputManager; pintype := 'Output'; end; inouts := delegateManager.filter('analysis_id = ''' + analysis_id + '''','id'); ios := ioManager.filter('pintype = ''' + pintype + ''' and component = ''' + analysis_type + '''','id'); if ios.count <> inouts.count then begin field_state.Clear; for k:=1 to ios.count do begin pinname := ios.objects[k-1].value['name'].VString; field_state.Values[pinname] := 'False'; end; for k := 1 to inouts.count do begin potential_id := inouts.objects[k-1].value['potential_id'].VInteger; potential := potManager.get('id = ' + IntToStr(potential_id)); pin_id := potential.value['pin'].Vinteger; pin := ioManager.get('id = ' + IntToStr(pin_id)); pinname := pin.value['name'].VString; field_state.Values[pinname] := 'True'; potential.Free; pin.Free; end; last_index := 0; for k := 1 to ios.count do begin pinname := ios.objects[k-1].value['name'].VString; if field_state.Values[pinname] = 'False' then begin index := field_state.IndexOf(pinname + '=' + field_state.Values[pinname]); if (index > inouts.list.count) or (inouts.list.count = 0) then begin inouts.list.Add(TDBObject.Create); index := 0; end else inouts.list.Insert(index,TDBObject.Create); void_object := inouts.list[index]; void_object.AddField('potential_id',gvInteger); void_object.AddField('pinname',gvString); void_object.VInteger[0] := -1; void_object.VString[1] := pinname; end; end; end; ios.Free; for k := 1 to inouts.count do begin npins := npins + 1; potential_id := inouts.objects[k-1].value['potential_id'].VInteger; if potential_id > -1 then begin potential := potManager.get('id = ' + IntToStr(potential_id)); pin_id := potential.value['pin'].Vinteger; pin := ioManager.get('id = ' + IntToStr(pin_id)); coding := pin.value['codingtype'].VString; pinname := pin.value['name'].VString; if all_fields.IndexOf(pinname) < 0 then all_fields.Add(pinname); if coding = 'bool' then delegateManager:=subpotManager_bool; if coding = 'int' then delegateManager:=subpotManager_int; if coding = 'float' then delegateManager:=subpotManager_float; if (coding = 'str') or (coding = 'file') then delegateManager:=subpotManager_str; subpotentials := delegateManager.filter('potential_ptr_id = ' + IntToStr(potential_id),'potential_ptr_id'); if subpotentials.count < 1 then value := 'NULL' else begin subpotential := subpotentials.objects[0]; value := subpotential.value['value'].getValString; end; potential.Free; pin.Free; subpotentials.Free; end else begin value := 'NULL'; pinname := inouts.objects[k-1].value['pinname'].VString; if all_fields.IndexOf(pinname) < 0 then all_fields.Add(pinname); end; if (value <> 'NULL') and ((coding = 'str') or (coding = 'file')) then value := '''' + value + ''''; row := row + value; if npins < total_pins then row := row + ',' else row := row + ')'; end; inouts.Free; end; values := values + row; if i < analyses.count then values := values + ','; end; if analyses.count > 0 then begin for i := 1 to all_fields.count do begin select := select + '"' + all_fields[i-1] + '"'; if i < all_fields.Count then select := select + ','; end; from := ' FROM (VALUES ' + values + ') as an(' + select + ')'; LAST_ANALYSES_SELECT := select; select := 'SELECT ' + select; if order <> '' then query := select + from + where + ' ORDER BY "' + order + '"' else query := select + from + where; end else query := ''; Result := query; LAST_ANALYSES_CONSTRUCT := values; analyses.Free; {all_fields.Free;} field_state.Free; pins.Free; end; procedure proTDBUnic_DefineAnalysisType(id,usecase,path:String;commit:Boolean;var pu:typeUO); {tested} {Defines a new analysis type in database : - id : the name that identify the analysis - usecase : the explanation of the analysis type, what does it supposed to do - path : the location of the file that contain the program that computes the analysis - connection : the TDBConnection object communicating with the database system - commit : boolean that tells if the database will be automatically updated or later manually } var tmp_object,anType:TDBObject; begin anType := TDBObject.Create(anTypeModel); {define all fields of an analysis type} anType.AddField('id',gvString); anType.AddField('base',gvBoolean); anType.AddField('language',gvString); anType.AddField('usecase',gvString); anType.AddField('package',gvString); {init all fields} anType.VString[0] := id; anType.VBoolean[1] := True; anType.VString[2] := 'Elphy'; anType.Vstring[3] := usecase; anType.Vstring[4] := path; tmp_object := anTypeManager.insert(anType,False); if commit then DBCONNECTION.connection.commit; tmp_object.Free; anType.Free; end; procedure proTDBUnic_RenameAnalysisType(old_id,new_id:String;commit:Boolean;var pu:typeUO);{tested} {Renames the string that identifies an analysis type : - old_id : the current name of the analysis type - new_id : the new name of the analysis - connection : the TDBConnection object communicating with the database system - commit : boolean that tells if the database will be automatically updated or later manually } var anType,io,analysis:TDBObject; ios,analyses:TDBQuerySet; index,i:Integer; begin if old_id <> new_id then begin {get the old object, change its id and create a new object with old properties but the old id} anType := anTypeManager.get('id = '''+ old_id + ''''); index := anType.fields.IndexOf('id'); anType.VString[index] := new_id; anType.save(False); anType.Free; {get all inputs/outputs attached to the old analysis type and link them to the new one} ios := ioManager.filter('component = '''+ old_id + '''','id'); for i:=1 to ios.count do begin io := ios.objects[i-1]; index := io.fields.IndexOf('component'); io.VString[index] := new_id; io.save(False); end; ios.Free; {get all analyses attached to the old analysis type and link them to the new one} analyses := anManager.filter('component = '''+ old_id + '''','id'); for i:=1 to analyses.count do begin analysis := analyses.objects[i-1]; index := analysis.fields.IndexOf('component'); analysis.VString[index] := new_id; analysis.save(False); end; analyses.Free; {remove the old analysis type} anType := anTypeManager.get('id = '''+ old_id + ''''); anType.remove(False); anType.Free; if commit then DBCONNECTION.connection.commit; end; end; procedure proTDBUnic_RelocateAnalysisType(id,new_path:String;commit:Boolean;var pu:typeUO);{tested} {Relocates the analysis type : - id : the name of the analysis type - new_path : the new location of the file containing the analysis program - connection : the TDBConnection object communicating with the database system - commit : boolean that tells if the actions done with the function is done automatically or performed later manually } var anType:TDBObject; index:Integer; begin anType := anTypeManager.get('id = '''+ id + ''''); index := anType.fields.IndexOf('package'); anType.VString[index] := new_path; anType.save(False); if commit then DBCONNECTION.connection.commit; anType.Free; end; procedure proTDBUnic_ExplainAnalysisType(id,usecase:String;commit:Boolean;var pu:typeUO);{tested} {Explains the analysis type : - id : the name of the analysis type - usecase : the new explanation of the purpose of the analysis - connection : the TDBConnection object communicating with the database system - commit : boolean that tells if the actions done with the function is done automatically or performed later manually } var anType:TDBObject; index:Integer; begin anType := anTypeManager.get('id = '''+ id + ''''); index := anType.fields.IndexOf('usecase'); anType.VString[index] := usecase; anType.save(False); if commit then DBCONNECTION.connection.commit; anType.Free; end; procedure proTDBUnic_DefineInputOutput(analysis_type,name,iotype,iocoding,usecase:String;commit:Boolean;var pu:typeUO);{tested} {Defines a new Input/Output for a specified Analysis Type : - analysis_type : the name of the analysis type - name : the name of the input/output - usecase : the explanation of the input/output, what does it supposed to be - iotype : specify if it is a Input, an Output or an Extern value coming from another analysis - iocoding : the kind of coding that is hold by the input/output choosen from [str,int,bool,float,file] - connection : the TDBConnection object communicating with the database system - commit : boolean that tells if the database will be automatically updated or later manually } var anType,io,tmp_object:TDBObject; test1,test2:Boolean; begin test1 := (iocoding = 'str') or (iocoding = 'bool') or (iocoding = 'int') or (iocoding = 'float') or (iocoding = 'file'); test2 := (iotype = 'Input') or (iotype = 'Output'); if not test1 then raise Exception.Create('iocoding must be in [str,bool,int,float,file]'); if not test2 then raise Exception.Create('iotype must be in [Input,Output]'); {test if analysis type is in database} try anType := anTypeManager.get('id = ''' + analysis_type + ''''); except raise Exception('analysis type ' + analysis_type + ' not in database'); end; anType.Free; io := TDBObject.Create(ioModel); {define all fields of an analysis type} io.AddField('component',gvString); io.AddField('name',gvString); io.AddField('pintype',gvString); io.AddField('codingtype',gvString); if usecase <> '' then io.AddField('usecase',gvString); {init all fields} io.VString[0] := analysis_type; io.VString[1] := name; io.VString[2] := iotype; io.Vstring[3] := iocoding; if usecase <> '' then io.VString[4] := usecase; tmp_object := ioManager.insert(io,False); if commit then DBCONNECTION.connection.commit; tmp_object.Free; io.Free; end; procedure proTDBUnic_RenameInputOutput(analysis_type,old_name,new_name:String;commit:Boolean;var pu:typeUO);{tested} {Renames the analysis type input/output : - analysis_type : the name of the analysis type - old_name : the old name of the input/output - new_path : the new name of the input/output - connection : the TDBConnection object communicating with the database system - commit : boolean that tells if the actions done with the function is done automatically or performed later manually } var io:TDBObject; index:Integer; begin io := ioManager.get('component = ''' + analysis_type + ''' AND name = '''+ old_name + ''''); index := io.fields.IndexOf('name'); io.VString[index] := new_name; io.save(False); if commit then DBCONNECTION.connection.commit; io.Free; end; procedure proTDBUnic_ExplainInputOutput(analysis_type,name,usecase:String;commit:Boolean;var pu:typeUO);{tested} {Explains the analysis type input/output : - analysis_type : the name of the analysis type - name : the name of the input/output - usecase : the explanation of the input/output, what does it supposed to be - connection : the TDBConnection object communicating with the database system - commit : boolean that tells if the actions done with the function is done automatically or performed later manually } var io:TDBObject; index:Integer; begin io := ioManager.get('component = ''' + analysis_type + ''' AND name = '''+ name + ''''); index := io.fields.IndexOf('usecase'); io.VString[index] := usecase; io.save(False); if commit then DBCONNECTION.connection.commit; io.Free; end; procedure proTDBUnic_RemoveInputOutput(analysis_type,name:String;commit:Boolean;var pu:typeUO);{tested} {Removes an Input/Output and all of its computed value relative to an Analysis Type - analysis_type : the name of the analysis type - name : the name of the Input/Output - connection : the TDBConnection object communicating with the database system - commit : boolean that tells if the actions done with the function is done automatically or performed later manually } var delegateManager1,delegateManager2:TDBManager; pin,potential,subpotential,inout:TDBObject; coding,pintype:String; potentials:TDBQuerySet; i,pin_id,potential_id:Integer; begin pin := ioManager.get('name = ''' + name + ''' AND component = ''' + analysis_type + ''''); pin_id := pin.value['id'].VInteger; coding := pin.value['codingtype'].VString; pintype := pin.value['pintype'].VString; if coding = 'bool' then delegateManager1:=subpotManager_bool; if coding = 'int' then delegateManager1:=subpotManager_int; if coding = 'float' then delegateManager1:=subpotManager_float; if (coding = 'str') or (coding = 'file') then delegateManager1:=subpotManager_str; if (pintype = 'Input') or (pintype = 'Output') then delegateManager2 := inputManager; if (pintype = 'Output') then delegateManager2 := outputManager; potentials := potManager.filter('pin = ' + IntToStr(pin_id),'id'); for i := 1 to potentials.count do begin potential_id := potentials.objects[i-1].value['id'].VInteger; subpotential := delegateManager1.get('potential_ptr_id = ' + IntToStr(potential_id)); subpotential.remove(False); inout := delegateManager2.get('potential_id = ' + IntToStr(potential_id)); inout.remove(False); subpotential.Free; inout.Free; end; potentials.remove(False); pin.remove(False); if commit then DBCONNECTION.connection.commit; potentials.Free; pin.Free; end; procedure proTDBUnic_StoreAnalysis(var analysis_object:TDBObject;commit:Boolean;var pu:typeUO); {Stores a complete analysis : - analysis_object : the TDBObject that capture all analysis parameters, it must contain these fields : + id : the identification string of the new analysis + analysis_type : the name of the analysis type relative to the new analysis + if in1 ... inN and out1 ... outM corresponding to names of inputs/outputs of the analysis type, the TDBObject must contain fields that have got the names you can add a field named 'comments' to add comments concerning the new analysis - connection : the TDBConnection object communicating with the database system - commit : boolean that tells if the actions done with the function is done automatically or performed later manually } begin anManager.insert(analysis_object,False); if commit then DBCONNECTION.connection.commit; end; procedure proTDBUnic_RemoveAnalysis(id:String;commit:Boolean;var pu:typeUO);{tested} {Removes a complete analysis : - id : the name of the analysis - connection : the TDBConnection object communicating with the database system - commit : boolean that tells if the actions done with the function is done automatically or performed later manually } var {anModel,ioModel,potModel,subpotModel_int,subpotModel_float,subpotModel_bool,subpotModel_str,inputModel,outputModel:TDBModel;} delegateManager1,delegateManager2{,anManager,ioManager,potManager,subpotManager_int,subpotManager_float,subpotManager_bool,subpotManager_str,inputManager,outputManager}:TDBManager; an,pin,potential,subpotential:TDBObject; coding:String; ios:TDBQuerySet; i,j:Integer; begin an := anManager.get('id = ''' + id + ''''); for i:=1 to 2 do begin if i = 1 then delegateManager1 := inputManager else delegateManager1 := outputManager; ios := delegateManager1.filter('analysis_id = ''' + id + '''','id'); for j:=1 to ios.count do begin potential := potManager.get('id =' + IntToStr(ios.objects[j-1].value['potential_id'].Vinteger)); pin := ioManager.get('id = ' + IntToStr(potential.value['pin'].VInteger)); coding := pin.value['codingtype'].VString; if coding = 'bool' then delegateManager2:=subpotManager_bool; if coding = 'int' then delegateManager2:=subpotManager_int; if coding = 'float' then delegateManager2:=subpotManager_float; if (coding = 'str') or (coding = 'file') then delegateManager2:=subpotManager_str; subpotential := delegateManager2.get('potential_ptr_id = ' + IntToStr(potential.value['id'].Vinteger)); subpotential.remove(False); ios.objects[j-1].remove(False); subpotential.Free; potential.remove(False); pin.Free; potential.Free; end; ios.Free; end; an.remove(False); if commit then DBCONNECTION.connection.commit; an.Free; end; procedure proTDBUnic_RemoveAnalysisType(id:String;commit:Boolean;var pu:typeUO);{tested without dependent ios or analyses} {Removes a complete analysis type and all of dependeing inputs/outputs/analyses : - id : the name of the analysis type - connection : the TDBConnection object communicating with the database system - commit : boolean that tells if the actions done with the function is done automatically or performed later manually } var {anTypeModel,anModel,ioModel,potModel,subpotModel_bool,subpotModel_int,subpotModel_float,subpotModel_str,inputModel,outputModel:TDBModel;} delegateManager1,delegateManager2{,anTypeManager,anManager,ioManager,potManager,subpotManager_bool,subpotManager_int,subpotManager_float,subpotManager_str,inputManager,outputManager}:TDBManager; pins,analyses,ios:TDBQuerySet; analysis,component,potential,subpotential,pin:TDBObject; i,j,k:Integer; coding:String; begin analyses := anManager.filter('component = ''' + id + '''', 'id'); for i := 1 to analyses.count do begin analysis := analyses.objects[i-1]; for j:=1 to 2 do begin if j = 1 then delegateManager1 := inputManager else delegateManager1 := outputManager; ios := delegateManager1.filter('analysis_id = ''' + analyses.objects[i-1].value['id'].VString + '''','id'); for k:=1 to ios.count do begin potential := potManager.get('id =' + IntToStr(ios.objects[k-1].value['potential_id'].Vinteger)); pin := ioManager.get('id = ' + IntToStr(potential.value['pin'].VInteger)); coding := pin.value['codingtype'].VString; if coding = 'bool' then delegateManager2:=subpotManager_bool; if coding = 'int' then delegateManager2:=subpotManager_int; if coding = 'float' then delegateManager2:=subpotManager_float; if (coding = 'str') or (coding = 'file') then delegateManager2:=subpotManager_str; subpotential := delegateManager2.get('potential_ptr_id = ' + IntToStr(potential.value['id'].Vinteger)); subpotential.remove(False); ios.objects[k-1].remove(False); potential.remove(False); subpotential.Free; pin.Free; potential.Free; end; ios.Free; end; analysis.remove(False); {proRemoveAnalysis(analysis.value['id'].VString,connection,False);} end; component := anTypeManager.get('id = ''' + id + ''''); component.remove(False); pins := ioManager.filter('component = '''+ component.value['id'].VString + '''','id'); if pins.count > 0 then pins.remove(False); if commit then DBCONNECTION.connection.Commit; pins.Free; analyses.Free; component.Free; end; procedure proTDBUnic_GetAnalyses(analysis_type,condition,order:String;var resultset:TDBResultSet;var pu:typeUO); var query:String; statement:IZStatement; begin if not assigned(resultset) then createPgObject('',typeUO(resultset),TDBresultset) else resultset.resultSet.Close; query := constructAnalysisQuery(analysis_type,condition,order); if query = '' then query := 'SELECT * FROM analysis_analysis WHERE component = ''' + analysis_type + ''''; statement := DBCONNECTION.connection.createStatement; try resultset.ResultSet:=nil; resultset.resultSet := statement.ExecuteQuery(query); resultset.initParams; if resultset.rowCount > 0 then resultset.invalidate; finally resultset.IsOpen:=assigned(resultset.resultSet); end; end; procedure proTDBUnic_GetStatistics(var resultset:TDBResultSet;var pu:typeUO);pascal; var query:String; statement:IZStatement; begin if not assigned(resultset) then createPgObject('',typeUO(resultset),TDBresultset) else resultset.resultSet.Close; query := constructStatistics; statement := DBCONNECTION.connection.createStatement; try resultset.ResultSet:=nil; resultset.resultSet := statement.ExecuteQuery(query); resultset.initParams; if resultset.rowCount > 0 then resultset.invalidate; finally resultset.IsOpen:=assigned(resultset.resultSet); end; end; procedure proTDBUnic_GetAnalysesAsObjects(analysis_type,condition,order:String;var queryset:TDBQuerySet;var pu:typeUO); var query:String; begin query := constructAnalysisQuery(analysis_type,condition,order); if query <> '' then begin if not assigned(queryset) then createPgObject('',typeUO(queryset),TDBQuerySet); queryset.initQuerySet(anModel); queryset.finalizeQuerySet(query); end; end; initialization registerObject(TDBUnic,sys); end.
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright © 2019 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DPM.Console.Command.ExitCodes; interface uses VSoft.CancellationToken, DPM.Console.Writer, DPM.Console.ExitCodes, DPM.Console.Command; type TExitCodesCommand = class(TInterfacedObject,ICommandHandler) private FConsole : IConsoleWriter; protected function ExecuteCommand(const cancellationToken : ICancellationToken) : TExitCode; function Execute(const cancellationToken : ICancellationToken) : TExitCode; function ForceNoBanner: Boolean; public constructor Create(const console : IConsoleWriter); end; implementation uses DPM.Console.Options, DPM.Console.Banner; { TUpdateCommand } constructor TExitCodesCommand.Create(const console: IConsoleWriter); begin FConsole := console; end; function TExitCodesCommand.Execute(const cancellationToken : ICancellationToken) : TExitCode; begin FConsole.WriteLine; FConsole.WriteLine('Exit Codes :',ccBrightWhite); DPM.Console.ExitCodes.LogExitCodes(FConsole); result := TExitCode.OK; end; function TExitCodesCommand.ExecuteCommand(const cancellationToken : ICancellationToken) : TExitCode; begin result := Execute(cancellationToken); end; function TExitCodesCommand.ForceNoBanner: Boolean; begin result := false; end; end.
unit Objekt.DHLDeleteShipmentOrderRequestAPI; interface uses SysUtils, System.Classes, geschaeftskundenversand_api_2, Objekt.DHLVersion; type TDHLDeleteShipmentOrderRequestAPI = class private fRequest: DeleteShipmentOrderRequest; fArray_Of_ShipmentNumber: Array_Of_shipmentNumber; fShipmentNumber: string; FVersion: TDHLVersion; procedure setShipmentNumber(const Value: string); public constructor Create; destructor Destroy; override; property Request: DeleteShipmentOrderRequest read fRequest write fRequest; property Version: TDHLVersion read FVersion write fVersion; property ShipmentNumber: string read fShipmentNumber write setShipmentNumber; end; implementation { TDHLDeleteShipmentOrderRequestAPI } constructor TDHLDeleteShipmentOrderRequestAPI.Create; begin fRequest := DeleteShipmentOrderRequest.Create; fVersion := TDHLVersion.Create; fRequest.Version := fVersion.VersionAPI; setLength(fArray_Of_ShipmentNumber, 1); end; destructor TDHLDeleteShipmentOrderRequestAPI.Destroy; begin FreeAndNil(fRequest); FreeAndNil(fVersion); inherited; end; procedure TDHLDeleteShipmentOrderRequestAPI.setShipmentNumber(const Value: string); var Shipnr: Array_Of_shipmentNumber; begin fArray_Of_ShipmentNumber[0] := Value; fRequest.shipmentNumber := fArray_Of_ShipmentNumber; fShipmentNumber := Value; end; end.
unit MultiThreadingTest; interface uses DUnitX.TestFramework, SysUtils, Classes, Threading, uIntX; type [TestFixture] TMultiThreadingTest = class(TObject) strict private function StartNewShiftMemoryCorruptionTask(): ITask; public [Test] procedure ShiftMemoryCorruptionTasks(); end; implementation [Test] procedure TMultiThreadingTest.ShiftMemoryCorruptionTasks(); var ATasks: Array of ITask; begin SetLength(ATasks, 2); ATasks[0] := StartNewShiftMemoryCorruptionTask(); ATasks[1] := StartNewShiftMemoryCorruptionTask(); TTask.WaitForAll(ATasks); end; function TMultiThreadingTest.StartNewShiftMemoryCorruptionTask(): ITask; var myTask: ITask; x: TIntX; begin x := 1; myTask := TTask.Create( procedure var i: Integer; begin i := 0; while i <= Pred(1000000) do begin x := x shl 63; x := x shr 63; Assert.IsTrue(x = 1); Inc(i); end; end); result := myTask.Start; end; initialization TDUnitX.RegisterTestFixture(TMultiThreadingTest); end.
unit docparam; interface uses Classes, SysUtils; const cname_goods_id = 'GoodsId'; cname_goods_name = 'GoodsName'; cname_goods_article = 'GoodsArticle'; cname_goods_count = 'GoodsCount'; cname_goods_cost = 'GoodsCost'; cname_goods_size = 'GoodsSize'; cname_shipment_id = 'ShipmentId'; cname_shipment_name = 'ShipmentName'; cname_place_id = 'PlaceId'; cname_place_name = 'PlaceName'; cname_warehouse_id = 'WarehouseId'; cname_warehouse_name = 'WarehouseName'; type TStringIndex = class private FId: Cardinal; FName: string; public property Id: Cardinal read FId write FId; property Name: string read FName write FName; procedure Clear; end; TDictionary = class(TStringIndex) private FShipment: TStringIndex; FPlace: TStringIndex; FWarehouse: TStringIndex; public constructor Create; reintroduce; destructor Destroy; override; procedure Clear; property Shipment: TStringIndex read FShipment; property Place: TStringIndex read FPlace; property Warehouse: TStringIndex read FWarehouse; end; TGoods = class(TStringIndex) private FHeader: TDictionary; FDictionary: TDictionary; protected FArticle: string; FCount: integer; FSize: double; FCost: double; private function GetShipmentId: Cardinal; function GetPlaceId: Cardinal; function GetWarehouseId: Cardinal; function GetShipmentName: string; function GetPlaceName: string; function GetWarehouseName: string; public constructor Create; reintroduce; destructor Destroy; override; procedure Clear; procedure AssignTo(Destination: TStrings); property Header: TDictionary read FHeader; property Dictionary: TDictionary read FDictionary; property Article: string read FArticle write FArticle; property Count: integer read FCount write FCount; property Size: double read FSize write FSize; property Cost: double read FCost write FCost; public property ShipmentId: Cardinal read GetShipmentId; property PlaceId: Cardinal read GetPlaceId; property WarehouseId: Cardinal read GetWarehouseId; property ShipmentName: string read GetShipmentName; property PlaceName: string read GetPlaceName; property WarehouseName: string read GetWarehouseName; end; implementation // TStringIndex procedure TStringIndex.Clear; begin FId := 0; FName := ''; end; // TDictionary constructor TDictionary.Create; begin inherited Create; FShipment := TStringIndex.Create; FPlace := TStringIndex.Create; FWarehouse := TStringIndex.Create; end; destructor TDictionary.Destroy; begin FShipment.Free; FPlace.Free; FWarehouse.Free; inherited Destroy; end; procedure TDictionary.Clear; begin inherited Clear; FShipment.Clear; FPlace.Clear; FWarehouse.Clear; end; // TGoods constructor TGoods.Create; begin inherited Create; FHeader := TDictionary.Create; FDictionary := TDictionary.Create; end; destructor TGoods.Destroy; begin FHeader.Free; FDictionary.Free; inherited Destroy; end; procedure TGoods.Clear; begin inherited Clear; FDictionary.Clear; FArticle := ''; FCount := 0; FSize := 0; FCost := 0; end; function TGoods.GetShipmentId: Cardinal; begin if FDictionary.Shipment.Id > 0 then Result := FDictionary.Shipment.Id else Result := FHeader.Shipment.Id; end; function TGoods.GetPlaceId: Cardinal; begin if FDictionary.Place.Id > 0 then Result := FDictionary.Place.Id else Result := FHeader.Place.Id; end; function TGoods.GetWarehouseId: Cardinal; begin if FDictionary.Warehouse.Id > 0 then Result := FDictionary.Warehouse.Id else Result := FHeader.Warehouse.Id; end; function TGoods.GetShipmentName: string; begin if FDictionary.Shipment.Id > 0 then Result := FDictionary.Shipment.Name else Result := FHeader.Shipment.Name; end; function TGoods.GetPlaceName: string; begin if FDictionary.Place.Id > 0 then Result := FDictionary.Place.Name else Result := FHeader.Place.Name; end; function TGoods.GetWarehouseName: string; begin if FDictionary.Warehouse.Id > 0 then Result := FDictionary.Warehouse.Name else Result := FHeader.Warehouse.Name; end; function float2str(const value: double): string; var j: integer; begin Result := FloatToStr(value); j := pos(',', Result); if j > 0 then Result[j] := '.'; end; procedure TGoods.AssignTo(Destination: TStrings); begin Destination.Values[cname_shipment_id] := ShipmentId.ToString; Destination.Values[cname_shipment_name] := ShipmentName; Destination.Values[cname_place_id] := PlaceId.ToString; Destination.Values[cname_place_name] := PlaceName; Destination.Values[cname_warehouse_id] := WarehouseId.ToString; Destination.Values[cname_warehouse_name] := WarehouseName; Destination.Values[cname_goods_id] := FId.ToString; Destination.Values[cname_goods_name] := FName; Destination.Values[cname_goods_article] := FArticle; Destination.Values[cname_goods_count] := FCount.ToString; Destination.Values[cname_goods_cost] := float2str(FCost); Destination.Values[cname_goods_size] := float2str(FSize); end; end.
unit uSQLFile; interface uses Windows, Messages, SysUtils, Classes, Controls, Dialogs, StdCtrls; { TReadSQLScript class } type TReadSQLScript = class private fFileStrings: TStrings; fScriptStrings: TStrings; fFlag: string; fIndex: Integer; fScriptCount: Integer; public constructor Create; destructor Destroy; override; procedure LoadFromFile(const FileName: string); function GetSQLScript: string; procedure Next; property Flag: string read fFlag write fFlag; property Index: Integer read fIndex write fIndex; property ScriptCount: Integer read fScriptCount write fScriptCount; end; implementation constructor TReadSQLScript.Create; begin fFileStrings := TStringList.Create; fScriptStrings := TStringList.Create; end; destructor TReadSQLScript.Destroy; begin fFileStrings.Free; fScriptStrings.Free; inherited; end; procedure TReadSQLScript.LoadFromFile(const FileName: string); var F: TextFile; sTemp: string; begin if fFlag = '' then raise Exception.Create('Flag not defined.'); AssignFile(F, FileName); Reset(F); try fFileStrings.Clear; fScriptCount := 0; fIndex := 0; while not Eof(F) do begin Readln(F, sTemp); fFileStrings.Append(sTemp); if sTemp = fFlag then Inc(fScriptCount); end; finally CloseFile(F); end; end; function TReadSQLScript.GetSQLScript: string; var I: Integer; str: string; Strings: TStrings; begin Result := ''; if fIndex > -1 then begin fScriptStrings.Clear; str := fFileStrings[fIndex]; while (str <> fFlag) and (fIndex < fFileStrings.Count) do begin fScriptStrings.Append(str); Inc(fIndex); str := fFileStrings[fIndex]; end; Result := Trim(fScriptStrings.Text); end; end; procedure TReadSQLScript.Next; begin if fIndex > -1 then begin Inc(fIndex); if fIndex >= (fFileStrings.Count -1) then fIndex := -1; end; end; end.
(* Player setup and stats *) unit player; {$mode objfpc}{$H+} interface uses Graphics, SysUtils, plot_gen; type (* Store information about the player *) Creature = record currentHP, maxHP, attack, defense, posX, posY, visionRange: smallint; experience: integer; playerName, title: string; (* status effects *) stsDrunk, stsPoison: boolean; (* status timers *) tmrDrunk, tmrPoison: smallint; (* Player Glyph *) glyph: TBitmap; end; (* Create player character *) procedure createPlayer; (* Players starting inventory *) procedure createEquipment; (* Moves the player on the map *) procedure movePlayer(dir: word); (* Process status effects *) procedure processStatus; (* Attack NPC *) procedure combat(npcID: smallint); (* Check if tile is occupied by an NPC *) function combatCheck(x, y: smallint): boolean; (* Pick up an item from the floor *) procedure pickUp; (*Increase Health, no more than maxHP *) procedure increaseHealth(amount: smallint); (* Display game over screen *) procedure gameOver; implementation uses globalutils, map, fov, ui, entities, player_inventory, items, main; procedure createPlayer; begin plot_gen.generateName; // Add Player to the list of creatures entities.listLength := length(entities.entityList); SetLength(entities.entityList, entities.listLength + 1); with entities.entityList[0] do begin npcID := 0; race := plot_gen.playerName; description := 'your character'; glyph := '@'; maxHP := 20; currentHP := 20; attack := 5; defense := 2; weaponDice := 0; weaponAdds := 0; xpReward := 0; visionRange := 4; NPCsize := 3; trackingTurns := 3; moveCount := 0; targetX := 0; targetY := 0; inView := True; discovered := True; weaponEquipped := False; armourEquipped := False; isDead := False; abilityTriggered := False; stsDrunk := False; stsPoison := False; tmrDrunk := 0; tmrPoison := 0; posX := map.startX; posY := map.startY; end; (* Occupy tile *) map.occupy(entityList[0].posX, entityList[0].posY); (* set up inventory *) player_inventory.initialiseInventory; (* Draw player and FOV *) fov.fieldOfView(entityList[0].posX, entityList[0].posY, entityList[0].visionRange, 1); end; procedure createEquipment; begin { TODO : Once character creation is implemented, replace this with a function that generates starting equipment based on the type of player chosen. } (* Add a club to the players inventory *) with player_inventory.inventory[0] do begin id := 0; Name := 'Wooden club'; equipped := True; description := 'adds 1D6 to attack [equipped]'; itemType := 'weapon'; glyph := '4'; inInventory := True; useID := 4; end; ui.updateWeapon('Wooden club'); entityList[0].weaponEquipped := True; Inc(entityList[0].weaponDice); end; (* Move the player within the confines of the game map *) procedure movePlayer(dir: word); var (* store original values in case player cannot move *) originalX, originalY: smallint; begin (* Unoccupy tile *) map.unoccupy(entityList[0].posX, entityList[0].posY); (* Repaint visited tiles *) fov.fieldOfView(entities.entityList[0].posX, entities.entityList[0].posY, entities.entityList[0].visionRange, 0); originalX := entities.entityList[0].posX; originalY := entities.entityList[0].posY; case dir of 1: Dec(entities.entityList[0].posY); // N 2: Dec(entities.entityList[0].posX); // W 3: Inc(entities.entityList[0].posY); // S 4: Inc(entities.entityList[0].posX); // E 5: // NE begin Inc(entities.entityList[0].posX); Dec(entities.entityList[0].posY); end; 6: // SE begin Inc(entities.entityList[0].posX); Inc(entities.entityList[0].posY); end; 7: // SW begin Dec(entities.entityList[0].posX); Inc(entities.entityList[0].posY); end; 8: // NW begin Dec(entities.entityList[0].posX); Dec(entities.entityList[0].posY); end; end; (* check if tile is occupied *) if (map.isOccupied(entities.entityList[0].posX, entities.entityList[0].posY) = True) then (* check if tile is occupied by hostile NPC *) if (combatCheck(entities.entityList[0].posX, entities.entityList[0].posY) = True) then begin entities.entityList[0].posX := originalX; entities.entityList[0].posY := originalY; end; Inc(playerTurn); (* check if tile is walkable *) if (map.canMove(entities.entityList[0].posX, entities.entityList[0].posY) = False) then begin entities.entityList[0].posX := originalX; entities.entityList[0].posY := originalY; ui.displayMessage('You bump into a wall'); Dec(playerTurn); end; (* Occupy tile *) map.occupy(entityList[0].posX, entityList[0].posY); fov.fieldOfView(entities.entityList[0].posX, entities.entityList[0].posY, entities.entityList[0].visionRange, 1); ui.writeBufferedMessages; end; procedure processStatus; begin (* Inebriation *) if (entities.entityList[0].stsDrunk = True) then begin if (entities.entityList[0].tmrDrunk <= 0) then begin entities.entityList[0].tmrDrunk := 0; entities.entityList[0].stsDrunk := False; ui.bufferMessage('The effects of the alcohol wear off'); end else Dec(entities.entityList[0].tmrDrunk); end; (* Poison *) if (entities.entityList[0].stsPoison = True) then begin if (ui.poisonStatusSet = False) then begin (* Update UI *) ui.displayStatusEffect(1, 'poison'); ui.poisonStatusSet := True; end; if (entities.entityList[0].tmrPoison <= 0) then begin entities.entityList[0].tmrPoison := 0; entities.entityList[0].stsPoison := False; (* Update UI *) ui.displayStatusEffect(0, 'poison'); ui.poisonStatusSet := False; end else begin Dec(entityList[0].currentHP); Dec(entityList[0].tmrPoison); updateHealth; end; end; end; (* Combat is decided by rolling a random number between 1 and the entity's ATTACK value. Then modifiers are added, for example, a 1D6+4 axe will roll a 6 sided die and add the result plus 4 to the total damage amount. This is then removed from the opponents DEFENSE rating. If the opponents defense doesn't soak up the whole damage amount, the remainder is taken from their Health. This is partly inspired by the Tunnels & Trolls rules, my favourite tabletop RPG. *) procedure combat(npcID: smallint); var damageAmount: smallint; begin damageAmount := (globalutils.randomRange(1, entityList[0].attack) + // Base attack globalutils.rollDice(entityList[0].weaponDice) + // Weapon dice entityList[0].weaponAdds) - // Weapon adds entities.entityList[npcID].defense; if ((damageAmount - entities.entityList[0].tmrDrunk) > 0) then begin entities.entityList[npcID].currentHP := (entities.entityList[npcID].currentHP - damageAmount); if (entities.entityList[npcID].currentHP < 1) then begin if (entities.entityList[npcID].race = 'barrel') then ui.bufferMessage('You break open the barrel') else ui.bufferMessage('You kill the ' + entities.entityList[npcID].race); entities.killEntity(npcID); entities.entityList[0].xpReward := entities.entityList[0].xpReward + entities.entityList[npcID].xpReward; ui.updateXP; exit; end else if (damageAmount = 1) then ui.bufferMessage('You slightly injure the ' + entities.entityList[npcID].race) else ui.bufferMessage('You hit the ' + entities.entityList[npcID].race + ' for ' + IntToStr(damageAmount) + ' points of damage'); end else begin if (entities.entityList[0].stsDrunk = True) then ui.bufferMessage('You drunkenly miss') else ui.bufferMessage('You miss'); end; end; function combatCheck(x, y: smallint): boolean; { TODO : Replace this with a check to see if the tile is occupied } var i: smallint; begin Result := False; for i := 1 to entities.npcAmount do begin if (x = entities.entityList[i].posX) then begin if (y = entities.entityList[i].posY) then player.combat(i); Result := True; end; end; end; procedure pickUp; var i: smallint; begin for i := 1 to itemAmount do begin if (entities.entityList[0].posX = itemList[i].posX) and (entities.entityList[0].posY = itemList[i].posY) and (itemList[i].onMap = True) then begin if (player_inventory.addToInventory(i) = True) then Inc(playerTurn) else ui.displayMessage('Your inventory is full'); end else if (entities.entityList[0].posX = itemList[i].posX) and (entities.entityList[0].posY = itemList[i].posY) and (itemList[i].onMap = False) then ui.displayMessage('There is nothing on the ground here'); end; end; procedure increaseHealth(amount: smallint); begin if (entities.entityList[0].currentHP <> entities.entityList[0].maxHP) then begin if ((entities.entityList[0].currentHP + amount) >= entities.entityList[0].maxHP) then entities.entityList[0].currentHP := entities.entityList[0].maxHP else entities.entityList[0].currentHP := entities.entityList[0].currentHP + amount; ui.updateHealth; ui.bufferMessage('You feel restored'); end else ui.bufferMessage('You are already at full health'); end; procedure gameOver; begin globalutils.deleteGame; main.gameState := 4; currentScreen := RIPscreen; (* Clear the screen *) RIPscreen.Canvas.Brush.Color := globalutils.BACKGROUNDCOLOUR; RIPscreen.Canvas.FillRect(0, 0, RIPscreen.Width, RIPscreen.Height); (* Draw title *) RIPscreen.Canvas.Font.Color := UITEXTCOLOUR; RIPscreen.Canvas.Brush.Style := bsClear; RIPscreen.Canvas.Font.Size := 12; RIPscreen.Canvas.TextOut(100, 50, 'You have died...'); RIPscreen.Canvas.Font.Size := 10; (* Display message *) RIPscreen.Canvas.TextOut(30, 100, 'Killed by a ' + killer + ' after ' + IntToStr(playerTurn) + ' turns, whilst testing a roguelike ;-)'); (* Menu options *) RIPscreen.Canvas.Font.Size := 9; RIPscreen.Canvas.TextOut(10, 410, 'Exit game? [Q] - Quit game | [X] - Exit to main menu'); end; end.
program asciibattle; uses Crt, CrtInterface, SysUtils, Game, Physics, BattleField, Geometry, Config, StaticConfig; type ConfigType = (CGAME, CMAP, CFORT); { Returns the filename of a config file of given type and name } function config_filename(t: ConfigType; name: ansistring) : ansistring; var dir: ansistring; begin case t of CGAME: dir := 'games'; CMAP: dir := 'maps'; CFORT: dir := 'forts'; end; config_filename := GetAppConfigDir(False) + '/' + dir + '/' + name; DoDirSeparators(config_filename); end; procedure create_stub_config(path: ansistring); begin ForceDirectories(path); ForceDirectories(config_filename(CGAME, '')); ForceDirectories(config_filename(CFORT, '')); ForceDirectories(config_filename(CMAP, '')); end; procedure read_game_config(var conf: ConfigStruct; gamename: ansistring); var filename: ansistring; confstring: ansistring; err: ErrorCode; begin filename := config_filename(CGAME, gamename); err := read_file_to_string(filename, confstring); if err.code <> OK then begin writeln('Error: no such game (file: ', filename, ')'); halt; end; err := parse_game_string(confstring, conf); if err.code <> OK then begin writeln('Error reading game file: ', err.msg, ' (file: ', filename, ')'); halt; end; end; procedure read_fort(var field: BField; var conf: ConfigStruct; var pl: Player; num: integer); var filename: ansistring; err: ErrorCode; map: ansistring; cannon, king: IntVector; begin filename := config_filename(CFORT, conf.fort_file[num]); err := read_file_to_string(filename, map); if err.code <> OK then begin writeln('Error: no such fort (file: ', filename, ')'); halt; end; err := parse_bfield_string(field, conf.fort_pos[num], map, cannon, king, conf.fort_modifier, num, conf.initial_hp); if err.code <> OK then begin writeln('Error reading fort file: ', err.msg, ' (file: ', filename, ')'); halt; end; pl.cannon := cannon + conf.fort_pos[num]; pl.king := king + conf.fort_pos[num]; end; var conf: ConfigStruct; confdir: ansistring; filename : ansistring; iface: ABInterface; err: ErrorCode; bf: BField; gc: GameController; map: ansistring; turn: integer; field_w, field_h: integer; p1, p2: Player; begin randomize; if ParamCount = 0 then begin { Temporary } writeln('Specify game name'); halt; end; confdir := GetAppConfigDir(False); if not DirectoryExists(confdir) then create_stub_config(confdir); read_game_config(conf, ParamStr(1)); filename := config_filename(CMAP, conf.bfield_file); err := read_file_to_string(filename, map); if err.code <> OK then begin writeln('Error: no such map (file: ', filename, ')'); halt; end; err := parse_bfield_dimensions(map, field_w, field_h); if err.code <> OK then begin writeln('Error reading map file: ', err.msg, ' (file: ', filename, ')'); halt; end; new_bfield(bf, field_w, field_h); err := parse_bfield_string(bf, iv(0, 0), map, 1, 0, conf.initial_hp); if err.code <> OK then begin writeln('Error reading map file: ', err.msg, ' (file: ', filename, ')'); halt; end; new_player(p1, conf.name[1], conf.color[1], conf.equipment, conf.max_force); new_player(p2, conf.name[2], conf.color[2], conf.equipment, conf.max_force); read_fort(bf, conf, p1, 1); read_fort(bf, conf, p2, 2); new_gc(gc, @bf, p1, p2, conf.max_wind, conf.max_force); new_abinterface(iface, @gc); turn := 1; while True do begin if not iface.locked then gc_step(gc, 0.033); iface_step(iface); if iface.exitting then halt; if iface.shooting and not iface.locked then begin if gc_player_has_weapon(gc, gc.current_player, gc.player[gc.current_player].current_weapon) then begin gc_shoot(gc); iface_change_player(iface, (turn mod 2) + 1); inc(turn); end; iface.shooting := False; end; if gc.player[1].won or gc.player[2].won then iface.locked := True; delay(33); end; end.
unit AST.Delphi.DataTypes; interface { Elementary | |--Ordinal | | | |- Integer | |- Boolean | |- Enumerated | |- Character | |- Subrange | |-- Sets |-- Real |-- String |-- Variant Structured | |-- Record |-- Array Referenced | |--Reference |--Class |--Interface } type TDataTypeID = ( dtInt8, // Int8 dtInt16, // Int16 dtInt32, // Int32 dtInt64, // Int64 dtUInt8, // UInt8 dtUInt16, // UInt16 dtUInt32, // UInt32 dtUInt64, // UInt64 dtNativeInt, // NativeInt dtNativeUInt, // NativeUInt dtFloat32, // Single dtFloat64, // Double dtFloat80, // Extended dtCurrency, // Currency dtComp, // Comp dtBoolean, // Boolean dtAnsiChar, // ansi char dtChar, // utf16 char dtShortString, // ansi short string dtAnsiString, // ansi string dtString, // unicode string dtWideString, // WideString dtPAnsiChar, // PAnsiChar dtPWideChar, // PWideChar dtVariant, // Variant dtGuid, // TGUID dtUntypedRef, // Untyped Reference dtPointer, // Pointer dtWeakRef, // dtGeneric, // any generic type (generic type parameter) dtRange, // any range type dtEnum, // any enum type dtSet, // any set type dtStaticArray, // any staic array dtDynArray, // any dynamic array dtOpenArray, // any open array dtProcType, // any procedural type dtRecord, // record dtClass, // class dtClassOf, // class of dtInterface // interface ); TASTArgMatchRate = Integer; const // неизвестный тип dtUnknown = 128; cDataTypeManaged: array [TDataTypeID] of Boolean = ( {dtInt8} False, {dtInt16} False, {dtInt32} False, {dtInt64} False, {dtUint8} False, {dtUint16} False, {dtUint32} False, {dtUint64} False, {dtNativeInt} False, {dtNativeUInt} False, {dtFloat32} False, {dtFloat64} False, {dtFloat80} False, {dtCurrency} False, {dtComp} False, {dtBoolean} False, {dtAnsiChar} False, {dtChar} False, {dtShortString} True, {dtAnsiString} True, {dtString} True, {dtWideString} True, {dtPAnsiChar} False, {dtPWideChar} False, {dtVariant} True, {dtGuid} False, {dtUntypedRef} False, {dtPointer} False, {dtWeakRef} True, {dtGeneric} False, {dtRange} False, {dtEnum} False, {dtSet} False, {dtArray} False, {dtDynArray} True, {dtOpenArray} False, {dtProcType} False, {dtRecord} False, {dtClass} True, {dtClassOf} False, {dtInterface} True ); function GetDataTypeName(DataType: TDataTypeID): string; inline; function GetDataTypeSize(DataType: TDataTypeID): Integer; inline; function IsDataTypeReferenced(DataType: TDataTypeID): Boolean; inline; function ImplicitFactor2(const Source, Destination: TDataTypeID): Integer; inline; function GetImplicitRate(const Src, Dst: TDataTypeID; out DataLoss: Boolean): TASTArgMatchRate; const cDataTypeNames: array [TDataTypeID] of string = ( {dtInt8} 'ShortInt', {dtInt16} 'SmallInt', {dtInt32} 'Integer', {dtInt64} 'Int64', {dtUInt8} 'Byte', {dtUInt16} 'Word', {dtUInt32} 'Cardinal', {dtUInt64} 'UInt64', {dtNativeInt} 'NativeInt', {dtNativeUInt} 'NativeUInt', {dtFloat32} 'Single', {dtFloat64} 'Double', {dtFloat80} 'Extended', {dtCurrency} 'Currency', {dtComp} 'Comp', {dtBoolean} 'Boolean', {dtAnsiChar} 'AnsiChar', {dtChar} 'Char', {dtShortString} 'ShortString', {dtAnsiString} 'AnsiString', {dtString} 'String', {dtWideString} 'WideString', {dtPAnsiChar} 'PAnsiChar', {dtPWideChar} 'PWideChar', {dtVariant} 'Variant', {dtUntypedRef} 'Untyped Reference', {dtGuid} 'Guid', {dtPointer} 'Pointer', {dtWeakRef} 'WeakRef', {dtGeneric} 'Generic', {dtRange} 'Range', {dtEnum} 'Enum', {dtSet} 'Set', {dtArray} 'Array', {dtDynArray} 'DynArray', {dtOpenArray} 'OpenArray', {dtProcType} 'ProcType', {dtRecord} 'Record', {dtClass} 'Class', {dtClassOf} 'ClassOf', {dtInterface} 'Interface' ); cDataTypeISReferenced: array [TDataTypeID] of Boolean = ( {dtInt8} False, {dtInt16} False, {dtInt32} False, {dtInt64} False, {dtUint8} False, {dtUint16} False, {dtUint32} False, {dtUint64} False, {dtNativeInt} False, {dtNativeUInt} False, {dtFloat32} False, {dtFloat64} False, {dtFloat80} False, {dtCurrency} False, {dtComp} False, {dtBoolean} False, {dtAnsiChar} False, {dtChar} False, {dtShortString} True, {dtAnsiString} True, {dtString} True, {dtWideString} True, {dtPAnsiChar} True, {dtPWideChar} True, {dtVariant} True, {dtGuid} False, {dtUntypedRef} True, {dtPointer} True, {dtWeakRef} True, {dtGeneric} False, {dtRange} False, {dtEnum} False, {dtSet} False, {dtArray} False, {dtDynArray} True, {dtOpenArray} True, {dtProcType} True, {dtRecord} False, {dtClass} True, {dtClassOf} True, {dtInterface} True ); cDataTypeSizes: array [TDataTypeID] of Integer = ( {dtInt8} 1, {dtInt16} 2, {dtInt32} 4, {dtInt64} 8, {dtUInt8} 1, {dtUInt16} 2, {dtUInt32} 4, {dtUInt64} 8, {dtNativeInt} -1, {dtNativeUInt} -1, {dtFloat32} 4, {dtFloat64} 8, {dtFloat80} 10, {dtCurrency} 8, {dtComp} 8, {dtBoolean} 1, {dtAnsiChar} 1, {dtChar} 2, // UTF16 {dtShortString} -1, // refernce type {dtAnsiString} -1, // refernce type {dtString} -1, // refernce type {dtWideString} -1, // refernce type {dtPAnsiChar} -1, {dtPWideChar} -1, {dtVariant} 16, {dtGuid} SizeOf(TGUID), {dtUntypedRef} -1, {dtPointer} -1, {dtWeakRef} -1, {dtGeneric} 0, {dtRange} 0, {dtEnum} 0, {dtSet} 0, {dtArray} 0, {dtDynArray} SizeOf(Pointer), {dtOpenArray} 0, {dtProcType} 0, {dtRecord} 0, {dtClass} SizeOf(Pointer), {dtClassOf} SizeOf(Pointer), {dtInterface} SizeOf(Pointer) ); implementation uses SysUtils; var implicitRates: array [dtInt8..dtPointer, dtInt8..dtPointer] of Integer; function IsDataTypeReferenced(DataType: TDataTypeID): Boolean; begin Result := cDataTypeISReferenced[DataType]; end; function ImplicitFactor2(const Source, Destination: TDataTypeID): Integer; inline; var DLF, ILF: Integer; IsDataLoss: Boolean; begin if (Source <= dtPointer) and (Destination <= dtPointer) then begin // todo ILF := GetImplicitRate(Source, Destination, IsDataLoss); DLF := ord(not IsDataLoss); Result := (DLF shl 16) + ILF; end else Result := 0; end; function GetDataTypeName(DataType: TDataTypeID): string; begin Result := cDataTypeNames[DataType]; end; function GetDataTypeSize(DataType: TDataTypeID): Integer; inline; begin Result := cDataTypeSizes[DataType]; end; function GetImplicitRate(const Src, Dst: TDataTypeID; out DataLoss: Boolean): TASTArgMatchRate; begin if (Src <= dtPointer) and (Dst <= dtPointer) then begin var RValue := implicitRates[Src, Dst]; DataLoss := RValue < 0; Exit(Abs(RValue)); end; Result := 0; DataLoss := False; end; procedure Rate(Src: TDataTypeID; Dsts: array of TDataTypeID); begin for var i := 0 to Length(Dsts) - 1 do begin if implicitRates[Src, Dsts[i]] <> 0 then raise Exception.Create('Rate is already set'); var RateValue: Integer := Length(Dsts) - i; implicitRates[Src, Dsts[i]] := RateValue; end; end; procedure RateWDL(Src: TDataTypeID; Dsts: array of TDataTypeID); begin for var i := 0 to Length(Dsts) - 1 do begin if implicitRates[Src, Dsts[i]] <> 0 then raise Exception.Create('Rate is already set'); var RateValue: Integer := - (Length(Dsts) - i); implicitRates[Src, Dsts[i]] := RateValue; end; end; procedure InitImplicitRates; begin // IMPORTANT: These rates are approximate and should be adjusted FillChar(implicitRates, Sizeof(implicitRates), #0); // Int8 /////////////////////////////////////////// Rate(dtInt8, [dtInt8, dtInt16, dtInt32, dtInt64, dtUntypedRef, dtFloat32, dtFloat64, dtVariant]); RateWDL(dtInt8, [dtUInt16, dtUInt32, dtUInt64, dtUInt8]); // Int16 ////////////////////////////////////////// Rate(dtInt16, [dtInt16, dtInt32, dtInt64, dtUntypedRef, dtFloat32, dtFloat64, dtVariant]); RateWDL(dtInt16, [dtUInt32, dtUInt64, dtUInt16, dtInt8, dtUInt8]); // Int32 ////////////////////////////////////////// Rate(dtInt32, [dtInt32, dtNativeInt, dtInt64, dtUntypedRef, dtFloat64, dtVariant]); RateWDL(dtInt32, [dtUInt32, dtNativeUInt, dtFloat32, dtUInt64, dtInt16, dtUInt16, dtInt8, dtUInt8]); // Int64 ////////////////////////////////////////// Rate(dtInt64, [dtInt64, dtUntypedRef, dtVariant]); RateWDL(dtInt64, [dtUInt64, dtFloat64, dtInt32, dtFloat32, dtUInt32, dtInt16, dtUInt16, dtInt8, dtUInt8]); // UInt8 /////////////////////////////////////////// Rate(dtUInt8, [dtUInt8, dtUInt16, dtInt16, dtInt32, dtUInt32, dtInt64, dtUInt64, dtUntypedRef, dtFloat32, dtFloat64, dtVariant]); RateWDL(dtUInt8, [dtInt8]); // UInt16 ////////////////////////////////////////// Rate(dtUInt16, [dtUInt16, dtUInt32, dtInt32, dtInt64, dtUInt64, dtUntypedRef, dtFloat32, dtFloat64, dtVariant]); RateWDL(dtUInt16, [dtInt16, dtUInt8, dtInt8]); // UInt32 ////////////////////////////////////////// Rate(dtUInt32, [dtUInt32, dtNativeUInt, dtInt64, dtUInt64, dtUntypedRef, dtFloat64, dtVariant]); RateWDL(dtUInt32, [dtInt32, dtNativeInt, dtFloat32, dtUInt16, dtInt16, dtUInt8, dtInt8]); // UInt64 ////////////////////////////////////////// Rate(dtUInt64, [dtUInt64, dtUntypedRef, dtVariant]); RateWDL(dtUInt64, [dtInt64, dtFloat64, dtInt32, dtUInt32, dtFloat32, dtInt16, dtUInt16, dtInt8, dtUInt8]); // NativeInt ////////////////////////////////////////// Rate(dtNativeInt, [dtNativeInt, dtUntypedRef, dtInt32, dtInt64]); RateWDL(dtNativeInt, [dtNativeUInt, dtUInt32, dtUInt64, dtInt16, dtUInt16, dtInt8, dtUInt8, dtFloat64, dtFloat32]); // NativeUInt ////////////////////////////////////////// Rate(dtNativeUInt, [dtNativeUInt, dtUntypedRef, dtUInt32, dtUInt64]); RateWDL(dtNativeUInt, [dtInt64, dtNativeInt, dtInt32, dtInt16, dtUInt16, dtInt8, dtUInt8, dtFloat64, dtFloat32]); // Float32 ///////////////////////////////////////// Rate(dtFloat32, [dtFloat32, dtFloat64, dtFloat80, dtCurrency, dtUntypedRef, dtVariant]); // Float64 ///////////////////////////////////////// Rate(dtFloat64, [dtFloat64, dtFloat80, dtUntypedRef, dtVariant]); RateWDL(dtFloat64, [dtCurrency, dtFloat32]); // Float80 ///////////////////////////////////////// Rate(dtFloat80, [dtFloat80, dtUntypedRef, dtVariant]); RateWDL(dtFloat80, [dtFloat64, dtCurrency, dtFloat32]); // Currency ///////////////////////////////////////// Rate(dtCurrency, [dtFloat80, dtFloat64, dtFloat32, dtUntypedRef, dtVariant]); // Boolean ///////////////////////////////////////// Rate(dtBoolean, [dtBoolean, dtUntypedRef, dtVariant]); // AnsiChar ///////////////////////////////////////// Rate(dtAnsiChar, [dtAnsiChar, dtAnsiString, dtUntypedRef, dtVariant]); // Char ///////////////////////////////////////// Rate(dtChar, [dtChar, dtString, dtUntypedRef, dtVariant]); // ShortString ///////////////////////////////////////// Rate(dtShortString, [dtShortString, dtAnsiString, dtUntypedRef, dtVariant, dtString, dtWideString]); // AnsiString ///////////////////////////////////////// Rate(dtAnsiString, [dtAnsiString, dtPAnsiChar, dtUntypedRef, dtVariant, dtString, dtWideString, dtPWideChar]); // String ///////////////////////////////////////// Rate(dtString, [dtString, dtWideString, dtPWideChar, dtUntypedRef, dtVariant, dtPAnsiChar]); RateWDL(dtString, [dtAnsiString]); // WideString ///////////////////////////////////////// Rate(dtWideString, [dtWideString, dtString, dtUntypedRef, dtVariant]); // PAnsiChar ///////////////////////////////////////// Rate(dtPAnsiChar, [dtPAnsiChar, dtPointer, dtUntypedRef, dtAnsiString, dtString]); // PWideChar ///////////////////////////////////////// Rate(dtPWideChar, [dtPWideChar, dtPointer, dtUntypedRef, dtWideString, dtString, dtAnsiString]); // Variant ///////////////////////////////////////// Rate(dtVariant, [dtVariant]); // todo // Variant ///////////////////////////////////////// end; initialization InitImplicitRates(); finalization end.
unit JMC_Parts; interface uses SysUtils; function ReadPart(const S: string; const Index: Integer; const Sep: Char): string; overload; function ReadPart(const S: string; const Index: Integer; const Sep: string): string; overload; function WritePart(var S: string; const Part: string; const Index: Integer; const Sep: Char): Boolean; function CountParts(const S: string; const Sep: Char): Integer; overload; function CountParts(const S: string; const Sep: string): Integer; overload; function SwapParts(var S: string; const Index1, Index2: Integer; const Sep: Char): Boolean; implementation function ReadPart(const S: string; const Index: Integer; const Sep: Char): string; var i, n: Integer; begin Result := ''; n := 1; for i := 1 to Length(S) do begin if S[i] = Sep then Inc(n); if n > Index then Break; if (n = Index) and (S[i] <> Sep) then Result := Result + S[i]; end; Result := Trim(Result); end; function ReadPart(const S: string; const Index: Integer; const Sep: string): string; var i, n: Integer; begin Result := ''; n := 1; i := 1; while i <= Length(S) do begin if Copy(S, i, Length(Sep)) = Sep then begin Inc(n); Inc(i, Length(Sep)); end; if n > Index then Break; if n = Index then Result := Result + S[i]; Inc(i); end; Result := Trim(Result); end; function WritePart(var S: string; const Part: string; const Index: Integer; const Sep: Char): Boolean; var a, i, n: Integer; begin Result := False; a := 0; n := 1; for i := 1 to Length(S) do begin if S[i] = Sep then Inc(n); if n = Index then begin a := i + 1; Break; end; end; if a > 0 then begin n := 0; for i := a to Length(S) do if S[i] <> Sep then Inc(n) else Break; Delete(S, a, n); Insert(Part, S, a); Result := True; end; end; function CountParts(const S: string; const Sep: Char): Integer; var i: Integer; begin if S = '' then Result := 0 else begin Result := 1; for i := 1 to Length(S) do if S[i] = Sep then Inc(Result); end; end; function CountParts(const S: string; const Sep: string): Integer; var i, n: Integer; begin if S = '' then begin Result := 0; Exit; end; n := 1; i := 1; while i <= Length(S) do begin if Copy(S, i, Length(Sep)) = Sep then begin Inc(n); Inc(i, Length(Sep)); end; Inc(i); end; Result := n; end; function SwapParts(var S: string; const Index1, Index2: Integer; const Sep: Char): Boolean; var i, n, i1, i2, j1, j2: Integer; Part1, Part2, Backup: string; begin Result := not (Index1 = Index2); if not Result then Exit; Backup := S; i1 := 0; i2 := 0; j1 := 0; j2 := 0; Part1 := ''; Part2 := ''; n := 1; i := 1; repeat if (n = Index1) and (i1 = 0) then i1 := i; if (n = Index1) and (j1 = 0) then if S[i] = Sep then j1 := i else if i = Length(S) then j1 := i + 1; if (n = Index2) and (i2 = 0) then i2 := i; if (n = Index2) and (j2 = 0) then if S[i] = Sep then j2 := i else if i = Length(S) then j2 := i + 1; if S[i] = Sep then Inc(n); Inc(i); until i > Length(S); Result := (i1 > 0) and (i2 > 0) and (j1 > 0) and (j2 > 0); if not Result then Exit; Part1 := Copy(S, i1, j1 - i1); Part2 := Copy(S, i2, j2 - i2); if i2 > i1 then begin Delete(S, i2, j2 - i2); Delete(S, i1, j1 - i1); Insert(Part2, S, i1); Insert(Part1, S, i2); end else begin Delete(S, i1, j1 - i1); Delete(S, i2, j2 - i2); Insert(Part1, S, i2); Insert(Part2, S, i1); end; Result := (Length(S) = Length(Backup)) and (i1 > 0) and (i2 > 0); if not Result then S := Backup; end; end.
// Copyright 2014 Asbjørn Heid // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. unit Compute.Detail; interface uses Compute, Compute.Common, Compute.ExprTrees, Compute.OpenCL, Compute.Future.Detail; type IComputeAlgorithms = interface ['{941C09AD-FEEC-4BFE-A9C1-C40A3C0D27C0}'] procedure Initialize(const DeviceSelection: ComputeDeviceSelection; const LogProc, DebugLogProc: TLogProc); function Transform(const Input, Output: TArray<double>; const Expression: Expr): IFuture<TArray<double>>; overload; function Transform(const InputBuffers: array of IFuture<Buffer<double>>; const FirstElement, NumElements: UInt64; const OutputBuffer: IFuture<Buffer<double>>; const Expression: Expr): IFuture<Buffer<double>>; overload; function GetContext: CLContext; function GetCmdQueue: CLCommandQueue; property Context: CLContext read GetContext; property CmdQueue: CLCommandQueue read GetCmdQueue; end; function Algorithms: IComputeAlgorithms; implementation uses System.SysUtils, System.Math, Compute.OpenCL.KernelGenerator; type TComputeAlgorithmsOpenCLImpl = class(TInterfacedObject, IComputeAlgorithms) strict private FLogProc: TLogProc; FDebugLogProc: TLogProc; FDevice: CLDevice; FContext: CLContext; FCmdQueue: CLCommandQueue; FMemReadQueue: CLCommandQueue; FMemWriteQueue: CLCommandQueue; FKernelCache: IDictionary<string, CLKernel>; procedure Log(const Msg: string); procedure DebugLog(const Msg: string); overload; procedure DebugLog(const FmtMsg: string; const Args: array of const); overload; function DeviceOptimalNonInterleavedBufferSize: UInt64; function DeviceOptimalInterleavedBufferSize: UInt64; procedure VerifyInputBuffers<T>(const InputBuffers: array of IFuture<Buffer<T>>; const NumElements: UInt64); procedure Initialize(const DeviceSelection: ComputeDeviceSelection; const LogProc, DebugLogProc: TLogProc); function TransformPlain(const Input, Output: TArray<double>; const Expression: Expr): IFuture<TArray<double>>; overload; function TransformInterleaved(const Input, Output: TArray<double>; const Expression: Expr): IFuture<TArray<double>>; overload; function Transform(const Input, Output: TArray<double>; const Expression: Expr): IFuture<TArray<double>>; overload; function Transform(const InputBuffers: array of IFuture<Buffer<double>>; const FirstElement, NumElements: UInt64; const OutputBuffer: IFuture<Buffer<double>>; const Expression: Expr): IFuture<Buffer<double>>; overload; function GetContext: CLContext; function GetCmdQueue: CLCommandQueue; property Device: CLDevice read FDevice; property Context: CLContext read FContext; property CmdQueue: CLCommandQueue read FCmdQueue; property MemReadQueue: CLCommandQueue read FMemReadQueue; property MemWriteQueue: CLCommandQueue read FMemWriteQueue; public constructor Create; end; var _AlgorithmsImpl: IComputeAlgorithms; procedure InitializeAlgorithmsImpl; var alg: IComputeAlgorithms; begin alg := TComputeAlgorithmsOpenCLImpl.Create; if (AtomicCmpExchange(pointer(_AlgorithmsImpl), pointer(alg), nil) = nil) then begin // successfully updated _Algorithms, so manually bump reference count alg._AddRef; end; end; function Algorithms: IComputeAlgorithms; begin result := _AlgorithmsImpl; if (result <> nil) then exit; InitializeAlgorithmsImpl; result := _AlgorithmsImpl; end; { TComputeAlgorithmsOpenCLImpl } constructor TComputeAlgorithmsOpenCLImpl.Create; begin inherited Create; end; procedure TComputeAlgorithmsOpenCLImpl.DebugLog(const Msg: string); begin if not Assigned(FDebugLogProc) then exit; FDebugLogProc(Msg); end; procedure TComputeAlgorithmsOpenCLImpl.DebugLog(const FmtMsg: string; const Args: array of const); begin if not Assigned(FDebugLogProc) then exit; FDebugLogProc(Format(FmtMsg, Args)); end; function TComputeAlgorithmsOpenCLImpl.DeviceOptimalInterleavedBufferSize: UInt64; begin // for now some magic numbers // to be replaced by something better if Device.IsType[DeviceTypeCPU] then result := 32 else if Device.IsType[DeviceTypeGPU] then result := 32 else result := 32; result := result * 1024 * 1024; end; function TComputeAlgorithmsOpenCLImpl.DeviceOptimalNonInterleavedBufferSize: UInt64; begin // for now some magic numbers // to be replaced by something better if Device.IsType[DeviceTypeCPU] then result := 32 else if Device.IsType[DeviceTypeGPU] then result := 128 else result := 32; result := result * 1024 * 1024; end; function TComputeAlgorithmsOpenCLImpl.GetCmdQueue: CLCommandQueue; begin result := FCmdQueue; end; function TComputeAlgorithmsOpenCLImpl.GetContext: CLContext; begin result := FContext; end; procedure TComputeAlgorithmsOpenCLImpl.Initialize(const DeviceSelection: ComputeDeviceSelection; const LogProc, DebugLogProc: TLogProc); var platforms: CLPlatforms; plat: CLPlatform; foundDevice: boolean; foundPreferredDevice: boolean; devIsPreferredType: boolean; selectDevice: boolean; dev, selectedDev: CLDevice; begin FLogProc := LogProc; FDebugLogProc := DebugLogProc; platforms := CLPlatforms.Create(DebugLogProc); plat := platforms[0]; foundDevice := False; foundPreferredDevice := False; for dev in plat.AllDevices do begin if not (dev.SupportsFP64 and dev.IsAvailable) then continue; case DeviceSelection of PreferCPUDevice: devIsPreferredType := dev.IsType[DeviceTypeCPU]; PreferGPUDevice: devIsPreferredType := dev.IsType[DeviceTypeGPU]; else devIsPreferredType := False; end; if (foundPreferredDevice and (not devIsPreferredType)) then continue; selectDevice := (not foundDevice) or ((not foundPreferredDevice) and devIsPreferredType); // GPU - prefer memory over compute units selectDevice := selectDevice or ((dev.IsType[DeviceTypeGPU]) and ((dev.MaxMemAllocSize > selectedDev.MaxMemAllocSize) or (dev.MaxComputeUnits > selectedDev.MaxComputeUnits))); // CPU - assume memory is not an issue, prefer compute units selectDevice := selectDevice or ((dev.IsType[DeviceTypeGPU]) and ((dev.MaxComputeUnits > selectedDev.MaxComputeUnits) or (dev.MaxMemAllocSize > selectedDev.MaxMemAllocSize))); if (selectDevice) then begin selectedDev := dev; foundDevice := True; foundPreferredDevice := devIsPreferredType; end; end; if (not foundDevice) then raise ENotSupportedException.Create('No suitable OpenCL device found'); FDevice := selectedDev; Log('Compute device used: ' + FDevice.Name); FContext := plat.CreateContext([FDevice]); FCmdQueue := FContext.CreateCommandQueue(FDevice); FMemReadQueue := FContext.CreateCommandQueue(FDevice); // AMD dev suggests using two queues only (exec/mem), Intel is broken with separate read/write queues // so for now, use same queue for read/write //FMemWriteQueue := FContext.CreateCommandQueue(FDevice); FMemWriteQueue := FMemReadQueue; FKernelCache := TDictionaryImpl<string, CLKernel>.Create; end; procedure TComputeAlgorithmsOpenCLImpl.Log(const Msg: string); begin if not Assigned(FLogProc) then exit; FLogProc(Msg); end; function TComputeAlgorithmsOpenCLImpl.Transform(const Input, Output: TArray<double>; const Expression: Expr): IFuture<TArray<double>>; begin if (Length(Input) <> Length(Output)) then raise EArgumentException.Create('Transform: Input length is not equal to output length'); //if (Length(Input) <= 256 * 1024 * 1024) then //result := TransformPlain(Input, Output, Expression); result := TransformInterleaved(Input, Output, Expression); end; function TComputeAlgorithmsOpenCLImpl.TransformInterleaved(const Input, Output: TArray<double>; const Expression: Expr): IFuture<TArray<double>>; var vectorWidth, vectorSize: UInt32; inputSize, bufferSize: UInt64; srcBuffer, resBuffer: array[0..1] of CLBuffer; prog: CLProgram; kernel: CLKernel; kernelSrc: string; kernelGen: IKernelGenerator; workGroupSize: UInt32; globalWorkSize: UInt64; writeEvent, execEvent, readEvent: array[0..1] of CLEvent; bufferOffset, bufferRemaining, workItemOffset: UInt64; current_idx: integer; begin vectorWidth := Max(1, Device.PreferredVectorWidthDouble); inputSize := Length(Input) * SizeOf(double); bufferSize := Min(DeviceOptimalInterleavedBufferSize, inputSize); vectorSize := SizeOf(double) * vectorWidth; if ((bufferSize mod vectorSize) <> 0) then begin bufferSize := vectorSize * CeilU(bufferSize / vectorSize); end; srcBuffer[0] := Context.CreateDeviceBuffer(BufferAccessReadOnly, bufferSize); srcBuffer[1] := Context.CreateDeviceBuffer(BufferAccessReadOnly, bufferSize); resBuffer[0] := Context.CreateDeviceBuffer(BufferAccessWriteOnly, srcBuffer[0].Size); resBuffer[1] := Context.CreateDeviceBuffer(BufferAccessWriteOnly, srcBuffer[1].Size); kernelGen := DefaultKernelGenerator(vectorWidth); kernelSrc := kernelGen.GenerateDoubleTransformKernel(Expression); DebugLog(kernelSrc); prog := Context.CreateProgram(kernelSrc); if not prog.Build([Device]) then begin raise Exception.Create('Error building OpenCL kernel:' + #13#10 + prog.BuildLog); end; kernel := prog.CreateKernel('transform_double_1'); workGroupSize := kernel.PreferredWorkgroupSizeMultiple; if (workGroupSize = 1) then workGroupSize := kernel.MaxWorkgroupSize; if (workGroupSize > 1) or (bufferSize < inputSize) then begin globalWorkSize := workGroupSize * UInt32(Ceil(bufferSize / (SizeOf(double) * workGroupSize))); end else begin globalWorkSize := Length(Input); end; workItemOffset := 0; bufferOffset := 0; writeEvent[0] := nil; writeEvent[1] := nil; execEvent[0] := nil; execEvent[1] := nil; readEvent[0] := nil; readEvent[1] := nil; current_idx := 1; while (bufferOffset < inputSize) do begin current_idx := (current_idx + 1) and 1; bufferRemaining := inputSize - bufferOffset; // write doesn't have to wait for the read, only kernel exec using this buffer writeEvent[current_idx] := MemWriteQueue.EnqueueWriteBuffer(srcBuffer[current_idx], BufferCommmandNonBlocking, 0, Min(bufferRemaining, srcBuffer[current_idx].Size), @Input[workItemOffset], [execEvent[current_idx]]); // update kernel arguments kernel.Arguments[0] := srcBuffer[current_idx]; kernel.Arguments[1] := resBuffer[current_idx]; kernel.Arguments[2] := UInt64(Length(Input)); // don't exec kernel until previous write has been done execEvent[current_idx] := CmdQueue.Enqueue1DRangeKernel(kernel, Range1D(0), Range1D(globalWorkSize), Range1D(workGroupSize), [writeEvent[current_idx]]); readEvent[current_idx] := MemReadQueue.EnqueueReadBuffer(resBuffer[current_idx], BufferCommmandNonBlocking, 0, Min(bufferRemaining, resBuffer[current_idx].Size), @Output[workItemOffset], [execEvent[current_idx]]); workItemOffset := workItemOffset + globalWorkSize; bufferOffset := workItemOffset * SizeOf(double); end; // wait for last read result := TOpenCLFutureImpl<TArray<double>>.Create(readEvent[current_idx], Output); end; function TComputeAlgorithmsOpenCLImpl.TransformPlain(const Input, Output: TArray<double>; const Expression: Expr): IFuture<TArray<double>>; var vectorWidth, vectorSize: UInt32; inputSize, bufferSize: UInt64; srcBuffer, resBuffer: CLBuffer; prog: CLProgram; kernel: CLKernel; kernelSrc: string; kernelGen: IKernelGenerator; workGroupSize: UInt32; globalWorkSize: UInt64; writeEvent, execEvent, readEvent: CLEvent; bufferOffset, bufferRemaining, workItemOffset: UInt64; begin vectorWidth := Max(1, Device.PreferredVectorWidthDouble); inputSize := Length(Input) * SizeOf(double); bufferSize := Min(DeviceOptimalNonInterleavedBufferSize, inputSize); vectorSize := SizeOf(double) * vectorWidth; if ((bufferSize mod vectorSize) <> 0) then begin bufferSize := vectorSize * CeilU(bufferSize / vectorSize); end; srcBuffer := Context.CreateDeviceBuffer(BufferAccessReadOnly, bufferSize); resBuffer := Context.CreateDeviceBuffer(BufferAccessWriteOnly, srcBuffer.Size); kernelGen := DefaultKernelGenerator(vectorWidth); kernelSrc := kernelGen.GenerateDoubleTransformKernel(Expression); DebugLog(kernelSrc); prog := Context.CreateProgram(kernelSrc); if not prog.Build([Device]) then begin raise Exception.Create('Error building OpenCL kernel:' + #13#10 + prog.BuildLog); end; kernel := prog.CreateKernel('transform_double_1'); kernel.Arguments[0] := srcBuffer; kernel.Arguments[1] := resBuffer; kernel.Arguments[2] := UInt64(Length(Input)); workGroupSize := kernel.PreferredWorkgroupSizeMultiple; if (workGroupSize = 1) then workGroupSize := kernel.MaxWorkgroupSize; if (workGroupSize > 1) or (bufferSize < inputSize) then begin globalWorkSize := workGroupSize * UInt32(Ceil(bufferSize / (SizeOf(double) * workGroupSize))); end else begin globalWorkSize := Length(Input); end; workItemOffset := 0; bufferOffset := 0; writeEvent := nil; execEvent := nil; readEvent := nil; while (bufferOffset < inputSize) do begin bufferRemaining := inputSize - bufferOffset; // write doesn't have to wait for the read, only last kernel exec writeEvent := MemWriteQueue.EnqueueWriteBuffer(srcBuffer, BufferCommmandNonBlocking, 0, Min(bufferRemaining, srcBuffer.Size), @Input[workItemOffset], [execEvent]); // don't exec kernel until previous write has been done execEvent := CmdQueue.Enqueue1DRangeKernel(kernel, Range1D(0), Range1D(globalWorkSize), Range1D(workGroupSize), [writeEvent]); readEvent := MemReadQueue.EnqueueReadBuffer(resBuffer, BufferCommmandNonBlocking, 0, Min(bufferRemaining, resBuffer.Size), @Output[workItemOffset], [execEvent]); workItemOffset := workItemOffset + globalWorkSize; bufferOffset := workItemOffset * SizeOf(double); end; // wait for last read result := TOpenCLFutureImpl<TArray<double>>.Create(readEvent, Output); end; procedure TComputeAlgorithmsOpenCLImpl.VerifyInputBuffers<T>( const InputBuffers: array of IFuture<Buffer<T>>; const NumElements: UInt64); var numElms: TArray<UInt64>; minNum: UInt64; begin numElms := Functional.Map<IFuture<Buffer<T>>, UInt64>(InputBuffers, function(const f: IFuture<Buffer<T>>): UInt64 begin result := f.PeekValue.NumElements; end); minNum := Functional.Reduce<UInt64>(numElms, function(const accumulator, v: UInt64): UInt64 begin result := IfThen(accumulator = 0, v, Min(accumulator, v)); end); if (minNum < NumElements) then raise EArgumentException.Create('At least one input buffer contains less than the requested number of elements'); end; function TComputeAlgorithmsOpenCLImpl.Transform( const InputBuffers: array of IFuture<Buffer<double>>; const FirstElement, NumElements: UInt64; const OutputBuffer: IFuture<Buffer<double>>; const Expression: Expr): IFuture<Buffer<double>>; var numInputs: UInt32; vectorWidth, vectorSize: UInt32; inputLength, inputSize: UInt64; prog: CLProgram; kernel: CLKernel; kernelSrc: string; kernelGen: IKernelGenerator; workGroupSize: UInt32; globalWorkSize: UInt64; inputEvents: TArray<CLEvent>; execEvent: CLEvent; i: UInt32; begin numInputs := Length(InputBuffers); //vectorWidth := Max(1, Device.PreferredVectorWidthDouble); vectorWidth := 1; // seems AMD's OpenCL compiler isn't too keen on vectorized doubles inputSize := NumElements * SizeOf(double); inputLength := NumElements; vectorSize := SizeOf(double) * vectorWidth; VerifyInputBuffers<double>(InputBuffers, NumElements); if ((inputSize mod vectorSize) <> 0) then begin vectorWidth := 1; end; kernelGen := DefaultKernelGenerator(vectorWidth); kernelSrc := kernelGen.GenerateDoubleTransformKernel(Expression, numInputs); if not FKernelCache.Contains[kernelSrc] then begin DebugLog(kernelSrc); prog := Context.CreateProgram(kernelSrc); if not prog.Build([Device]) then begin raise Exception.Create('Error building OpenCL kernel:' + #13#10 + prog.BuildLog); end; DebugLog(prog.BuildLog); kernel := prog.CreateKernel('transform_double_' + IntToStr(numInputs)); FKernelCache[kernelSrc] := kernel; end else begin kernel := FKernelCache[kernelSrc]; end; for i := 0 to numInputs-1 do begin kernel.Arguments[i] := InputBuffers[i].PeekValue.Handle; end; kernel.Arguments[numInputs+0] := OutputBuffer.PeekValue.Handle; kernel.Arguments[numInputs+1] := inputLength; workGroupSize := kernel.PreferredWorkgroupSizeMultiple; if (workGroupSize = 1) then workGroupSize := kernel.MaxWorkgroupSize; if (workGroupSize > 1) then begin globalWorkSize := workGroupSize * UInt32(Ceil(inputSize / (SizeOf(double) * workGroupSize))); end else begin globalWorkSize := inputLength; end; SetLength(inputEvents, numInputs+1); for i := 0 to numInputs-1 do inputEvents[i] := InputBuffers[i].Event; inputEvents[numInputs] := OutputBuffer.Event; // don't exec kernel until buffer is ready execEvent := CmdQueue.Enqueue1DRangeKernel(kernel, Range1D(0), Range1D(globalWorkSize), Range1D(workGroupSize), inputEvents); // wait for last read result := TOpenCLFutureImpl<Buffer<double>>.Create(execEvent, OutputBuffer.PeekValue); end; end.
{ Copyright (c) 2020 Adrian Siekierka Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. } {$I-} unit PC98; interface const Black = 0; Blue = 1; Green = 2; Cyan = 3; Red = 4; Magenta = 5; Yellow = 6; White = 7; procedure Sound(hz: word); procedure NoSound; procedure ClrScr; implementation uses Dos, Sounds, PC98FONT; procedure Sound(hz: word); var convHz: word; begin convHz := SoundFreqDivisor div hz; if not SpeakerActive then begin Port[$77] := $76; SpeakerActive := true; end; Port[$73] := Lo(convHz); Port[$73] := Hi(convHz); Port[$37] := $08; Port[$35] := Port[$35] and $F7; end; procedure NoSound; begin Port[$35] := Port[$35] or $08; Port[$37] := $09; SpeakerActive := false; end; procedure ClrScr; var regs: Registers; begin regs.AH := $16; regs.DX := $0020; Intr($18, regs); end; procedure LoadFontData; var chr: array[0 .. 33] of byte; cPtr: pointer; i, j: integer; regs: Registers; begin cPtr := Ptr(Seg(chr), Ofs(chr) + 2); for i := 0 to (PC98FONTSize shr 4) do begin for j := 0 to 15 do begin chr[(j shl 1) + 2] := PC98FONTData[(i shl 4) or j]; chr[(j shl 1) + 3] := PC98FONTData[(i shl 4) or j]; end; regs.AH := $1A; regs.BX := Seg(chr); regs.CX := Ofs(chr); regs.DX := ($7601 + ((i and $7E) shr 1)) + ((i and $01) shl 8); Intr($18, regs); end; end; begin LoadFontData; end.
unit uRtfmtFileReader; interface uses Classes,SysUtils,Contnrs, DateUtils,uLKJRuntimeFile,uVSConst, Windows,uRtFileReaderBase; const FILEHEAD_LENGTH = 3; //文件头长度 FLAG_SETINFO_TRIANTYPE = $8121; //车型标志 (设定) FLAG_SETINFO_TRIANTYPE_IC = $8221; //车型标志 (IC设定) FLAG_SETINFO_TRIANTYPE_JIAN = $8421; //车型标志 (检修设定) FLAG_CHECI_HEAD = $B0F0; //车次头标志 FLAG_FILE_BEGIN = $B001; //文件开始 FLAG_SETTING_JL = $8105; //设定交路 FLAG_SETTING_STATION = $8106; //设定车站 FLAG_STATIONINFO = $20F0; //车站信息 type {TFileRec运行记录中一行记录} TFileRec = array[0..25] of byte; ////////////////////////////////////////////////////////////////////////////// /// 类名:TFileInfoReader /// 功能:从格式化文件里读取文件信息 ////////////////////////////////////////////////////////////////////////////// TfmtFileReader = class(TRunTimeFileReaderBase) private m_LastRecordTime: TDateTime; protected {功能:读取车次} procedure ReadCheCi(fmtFile: TMemoryStream;var HeadInfo : RLKJRTFileHeadInfo); {功能:读取乘务员信息} procedure ReadDriver(fmtFile: TMemoryStream;var HeadInfo : RLKJRTFileHeadInfo); {功能:读取机车型号} procedure ReadTrainType(fmtFile: TMemoryStream;var HeadInfo : RLKJRTFileHeadInfo); {功能:读取机车号} procedure ReadTrainNo(fmtFile: TMemoryStream;var HeadInfo : RLKJRTFileHeadInfo); {功能:读取文件时间} procedure ReadFileTime(fmtFile: TMemoryStream;var HeadInfo : RLKJRTFileHeadInfo); {功能:读取开车时间} procedure ReadKCTime(fmtFile: TMemoryStream;var HeadInfo : RLKJRTFileHeadInfo); {功能:读取客货状态} procedure ReadKeHuo(fmtFile: TMemoryStream;var HeadInfo : RLKJRTFileHeadInfo); protected m_FileDateTime: TDateTime; procedure ReadFileHead(fmtFile: TMemoryStream;RuntimeFile : TLKJRuntimeFile); {功能:新生成一条记录,继承上一条记录的内容} function NewLKJCommonRec(RuntimeFile : TLKJRuntimeFile): TLKJCommonRec; {功能:获取事件代码} class function GetEventCode(FileRec: TFileRec): Integer; {功能:Byte序列转换为字符串} function ByteToStr(FileRec: TFileRec; BeginPos, EndPos: byte): string; {功能:获取一行记录的时间} function GetTime(FileRec: TFileRec): TDateTime; procedure ReadCommonInfo(FileRec: TFileRec;LKJCommonRec: TLKJCommonRec); //功能:获取入库时间 function GetRuKuTime(Mem: TMemoryStream; var OutTime: TDateTime): Boolean; procedure Read(RuntimeFile : TLKJRuntimeFile;fmtFile: TMemoryStream); public {功能:从原始文件加载信息} procedure LoadFromFile(orgFile : string;RuntimeFile : TLKJRuntimeFile);override; {功能:根据传入参数获取文件的对应时间,使用了fmtdll} function GetFileTime(orgFileName: string; TimeType: TFileTimeType; var OutTime: TDateTime): Boolean; end; implementation { TFileInfoReader } function TfmtFileReader.ByteToStr(FileRec: TFileRec; BeginPos, EndPos: byte): string; var i: byte; str: string; begin i := BeginPos; str := ''; while i <= EndPos do begin str := str + chr(FileRec[i]); i := i + 1; end; Result := Trim(str) end; class function TfmtFileReader.GetEventCode(FileRec: TFileRec): Integer; begin Result := FileRec[0] * 256 + FileRec[1]; end; function TfmtFileReader.GetFileTime(orgFileName: string; TimeType: TFileTimeType; var OutTime: TDateTime): Boolean; var HeadInfo: RLKJRTFileHeadInfo; strFormatFile: string; Mem: TMemoryStream; T: array[0..25] of Byte; begin Result := False; ReadHead(orgFileName, HeadInfo); if TimeType <> fttBegin then begin strFormatFile := FmtLkjOrgFile(orgFileName) end; case TimeType of fttBegin: begin OutTime := HeadInfo.DTFileHeadDt; Result := True; end; fttEnd: begin Mem := TMemoryStream.Create; try Mem.LoadFromFile(strFormatFile); Mem.Seek(Mem.Size - 26, 0); Mem.Read(T, 26); if (T[2] > 23) or (T[3] > 59) or (T[4] > 59) then begin Result := False; Exit; end; OutTime := EncodeTime(T[2], T[3], T[4], 0); OutTime := CombineDateTime(HeadInfo.DTFileHeadDt, OutTime); if CompareTime(OutTime, HeadInfo.DTFileHeadDt) < 0 then IncDay(OutTime, 1); Result := True; finally Mem.Free; SysUtils.DeleteFile(strFormatFile); end; end; fttRuKu: begin Mem := TMemoryStream.Create; try Mem.LoadFromFile(strFormatFile); Result := GetRuKuTime(Mem, OutTime); if Result then begin OutTime := CombineDateTime(HeadInfo.DTFileHeadDt, OutTime); if CompareTime(OutTime, HeadInfo.DTFileHeadDt) < 0 then IncDay(OutTime, 1); end; finally Mem.Free; SysUtils.DeleteFile(strFormatFile); end; end; end; end; function TfmtFileReader.GetRuKuTime(Mem: TMemoryStream; var OutTime: TDateTime): Boolean; var T: array[0..25] of Byte; i, index: integer; begin Result := False; i := 0; index := 0; while Mem.Position < Mem.Size do begin Mem.Read(T, 26); //站内停车 if (T[0] = $87) and (T[1] = $18) then begin index := -1; end; //入段 if (T[0] = $86) and (T[1] = $12) and (index = -1) then begin index := i; end; Inc(I); end; if index > 0 then begin Mem.Seek(26 * index, 0); Mem.Read(T, 26); OutTime := EncodeTime(T[2], T[3], T[4], 0); Result := True; end; end; function TfmtFileReader.GetTime(FileRec: TFileRec): TDateTime; begin if (FileRec[2] >= 24) or (FileRec[3] >= 60) or (FileRec[4] >= 60) then begin if m_LastRecordTime < 1 then m_LastRecordTime := m_FileDateTime; Result := m_LastRecordTime; Exit; end; Result := EncodeTime(FileRec[2],FileRec[3],FileRec[4],0); Result := CombineDateTime(m_FileDateTime,Result); if CompareTime(Result,m_FileDateTime) < 0 then Result := IncDay(Result); m_LastRecordTime := Result; end; procedure TfmtFileReader.LoadFromFile(orgFile: string; RuntimeFile: TLKJRuntimeFile); var strFmtFile: string; fmtFileStream: TMemoryStream; FileInfoReader: TfmtFileReader; begin fmtFileStream := TMemoryStream.Create; FileInfoReader := TfmtFileReader.Create; try //读取头信息 ReadHead(orgFile,RuntimeFile.HeadInfo); strFmtFile := FmtLkjOrgFile(orgFile); fmtFileStream.LoadFromFile(strFmtFile); if fmtFileStream.Size = 0 then raise Exception.Create('格式化运行记录文件: ' + ExtractFileName(orgFile) +'失败'); FileInfoReader.Read(RuntimeFile,fmtFileStream) finally if FileExists(strFmtFile) then SysUtils.DeleteFile(strFmtFile); fmtFileStream.Free; FileInfoReader.Free; end; end; function TfmtFileReader.NewLKJCommonRec( RuntimeFile: TLKJRuntimeFile): TLKJCommonRec; begin Result := TLKJCommonRec.Create; if RuntimeFile.Records.Count > 0 then Result.Clone(RuntimeFile.Records[RuntimeFile.Records.Count - 1]) else Result.CommonRec.DTEvent := m_FileDateTime; end; procedure TfmtFileReader.Read(RuntimeFile: TLKJRuntimeFile; fmtFile: TMemoryStream); var nEventCode: Integer; LKJCommonRec: TLKJCommonRec; FileRec: TFileRec; begin if RuntimeFile = nil then raise Exception.Create('RuntimeFile 参数不能为空'); {读取文件头} ReadFileHead(fmtFile,RuntimeFile); fmtFile.Seek(FILEHEAD_LENGTH * SizeOf(TFileRec),0); while fmtFile.Position < fmtFile.Size do begin fmtFile.Read(FileRec,SizeOf(FileRec)); nEventCode := GetEventCode(FileRec); LKJCommonRec := NewLKJCommonRec(RuntimeFile); LKJCommonRec.CommonRec.nRow := RuntimeFile.Records.Count; LKJCommonRec.CommonRec.nEvent := nEventCode; RuntimeFile.Records.Add(LKJCommonRec); case nEventCode of CommonRec_Event_DuiBiao, CommonRec_Event_CuDuan, CommonRec_Event_TrainPosForward, CommonRec_Event_TrainPosBack, CommonRec_Event_TrainPosReset, CommonRec_Event_SpeedChange, CommonRec_Event_RotaChange, CommonRec_Event_GanYChange, CommonRec_Event_SpeedLmtChange, CommonRec_Event_GangYChange, CommonRec_Event_GuoFX, $8B08, //定量记录 $8B0C, //变量记录 $8B0D, //时间地点 $8B0E, //记录距离 CommonRec_Event_XingHaoTuBian, CommonRec_Event_GLBTuBian, CommonRec_Event_EnterStation, CommonRec_Event_SectionSignal, CommonRec_Event_InOutStation, CommonRec_Event_LeaveStation, CommonRec_Event_StartTrain, CommonRec_Event_ZiTing, CommonRec_Event_StopInRect, CommonRec_Event_StartInRect, CommonRec_Event_StopInJiangJi, CommonRec_Event_StopInStation, CommonRec_Event_StopOutSignal, CommonRec_Event_StartInStation, CommonRec_Event_StartInJiangJi, CommonRec_Event_RuDuan : ReadCommonInfo(FileRec,LKJCommonRec); else begin if FileRec[0] = $8A then //信号变化 begin if FileRec[1] <> $02 then //制式电平变化 ReadCommonInfo(FileRec,LKJCommonRec); end; end; end; end; end; procedure TfmtFileReader.ReadCheCi(fmtFile: TMemoryStream; var HeadInfo: RLKJRTFileHeadInfo); var FileRec: TFileRec; begin fillchar(FileRec,SizeOf(FileRec),0); fmtFile.Seek(SizeOf(FileRec),0); fmtFile.Read(FileRec,SizeOf(FileRec)); HeadInfo.nTrainNo := FileRec[2] + FileRec[3] * 256 + FileRec[17] * 65536; fmtFile.Read(FileRec,SizeOf(FileRec)); if GetEventCode(FileRec) = FLAG_CHECI_HEAD then begin HeadInfo.strTrainHead := ByteToStr(FileRec,15,18); end; end; procedure TfmtFileReader.ReadCommonInfo(FileRec: TFileRec; LKJCommonRec: TLKJCommonRec); begin LKJCommonRec.CommonRec.DTEvent := GetTime(FileRec); if FileRec[7] <= 128 then begin LKJCommonRec.CommonRec.nCoord := FileRec[5] + 256 * (FileRec[6] + FileRec[7] * 256); end; LKJCommonRec.CommonRec.nDistance := FileRec[8] + FileRec[9] * 256; if FileRec[12] = $80 then LKJCommonRec.CommonRec.bIsPingdiao := True; LKJCommonRec.CommonRec.nLampNo := FileRec[10] + FileRec[11] * 256; LKJCommonRec.CommonRec.nLieGuanPressure := FileRec[13] * 10; LKJCommonRec.CommonRec.nGangPressure := FileRec[14] * 10; LKJCommonRec.CommonRec.nRotate := (FileRec[17] + FileRec[18] * 256) mod 10000; LKJCommonRec.CommonRec.nSpeed := (FileRec[19] + FileRec[20] * 256) mod 1000; LKJCommonRec.CommonRec.nLimitSpeed := (FileRec[21] + FileRec[22] * 256) mod 1000; end; procedure TfmtFileReader.ReadDriver(fmtFile: TMemoryStream; var HeadInfo: RLKJRTFileHeadInfo); function GetDriverNo(FileRec: TFileRec): string; begin Result := Trim(chr(FileRec[7]) + chr(FileRec[8]) + chr(FileRec[9]) + chr(FileRec[10]) + chr(FileRec[11]) + chr(FileRec[12]) + chr(FileRec[13]) + chr(FileRec[14])); end; var FileRec: TFileRec; begin fmtFile.Seek(0,0); while fmtFile.Position < fmtFile.Size do begin FillChar(FileRec,sizeof(FileRec),0); fmtFile.Read(FileRec,SizeOf(FileRec)); if (FileRec[0] = $81) or (FileRec[0] = $82) or (FileRec[0] = $84) then begin case FileRec[1] of $04, $57, $58, $59: begin HeadInfo.nFirstDriverNO := StrToInt(GetDriverNo(FileRec)); end; $11: begin HeadInfo.nSecondDriverNO := StrToInt(GetDriverNo(FileRec)); end; end; end; end; end; procedure TfmtFileReader.ReadFileHead(fmtFile: TMemoryStream; RuntimeFile: TLKJRuntimeFile); begin ReadCheCi(fmtFile,RuntimeFile.HeadInfo); ReadDriver(fmtFile,RuntimeFile.HeadInfo); ReadTrainType(fmtFile,RuntimeFile.HeadInfo); ReadTrainNo(fmtFile,RuntimeFile.HeadInfo); ReadFileTime(fmtFile,RuntimeFile.HeadInfo); ReadKCTime(fmtFile,RuntimeFile.HeadInfo); ReadKeHuo(fmtFile,RuntimeFile.HeadInfo); fmtFile.Seek(0,0); end; procedure TfmtFileReader.ReadFileTime(fmtFile: TMemoryStream; var HeadInfo: RLKJRTFileHeadInfo); var FileRec: TFileRec; bFindFileTime: Boolean; begin bFindFileTime := False; fmtFile.Seek(SizeOf(FileRec) * FILEHEAD_LENGTH,0); while fmtFile.Position < fmtFile.Size do begin fmtFile.Read(FileRec,SizeOf(FileRec)); if TfmtFileReader.GetEventCode(FileRec) = FLAG_FILE_BEGIN then begin HeadInfo.DTFileHeadDt := EncodeDateTime(FileRec[2] + 2000,FileRec[3],FileRec[4], FileRec[5],FileRec[6],FileRec[7],0); m_FileDateTime := HeadInfo.DTFileHeadDt; bFindFileTime := True; Break; end; end; fmtFile.Seek(0,0); if not bFindFileTime then raise Exception.Create('未找到文件开始时间'); end; procedure TfmtFileReader.ReadKCTime(fmtFile: TMemoryStream; var HeadInfo: RLKJRTFileHeadInfo); var FileRec: TFileRec; nEventCode: Integer; begin fmtFile.Seek(0,0); while fmtFile.Position < fmtFile.Size do begin fmtFile.Read(FileRec,SizeOf(FileRec)); nEventCode := GetEventCode(FileRec); if (nEventCode = CommonRec_Event_DuiBiao) or (nEventCode = CommonRec_Event_LeaveStation) then begin HeadInfo.dtKCDataTime := GetTime(FileRec); Break; end; end; end; procedure TfmtFileReader.ReadKeHuo(fmtFile: TMemoryStream; var HeadInfo: RLKJRTFileHeadInfo); var FileRec: TFileRec; begin fmtFile.Seek(SizeOf(FileRec),0); fmtFile.Read(FileRec,SizeOf(FileRec)); if FileRec[1] mod 2 = 1 then HeadInfo.TrainType := ttPassenger else HeadInfo.TrainType := ttCargo; end; procedure TfmtFileReader.ReadTrainNo(fmtFile: TMemoryStream; var HeadInfo: RLKJRTFileHeadInfo); var FileRec: TFileRec; begin fmtFile.Seek(0,0); fmtFile.Read(FileRec,SizeOf(FileRec)); HeadInfo.nLocoID := FileRec[20] + FileRec[21] * 256; end; procedure TfmtFileReader.ReadTrainType(fmtFile: TMemoryStream; var HeadInfo: RLKJRTFileHeadInfo); var FileRec: TFileRec; begin fmtFile.Seek(0,0); while fmtFile.Position < fmtFile.Size do begin fmtFile.Read(FileRec,SizeOf(FileRec)); case FileRec[0] of $81,$82,$84 : begin if FileRec[1] = $21 then begin HeadInfo.nLocoType := FileRec[5] + FileRec[6] * 256; end; end; end; if GetEventCode(FileRec) = CommonRec_Event_DuiBiao then Break; end; end; end.
program HowToRespondToKeystrokes; uses SwinGame, sgTypes; procedure Main(); var clr: Color; begin OpenGraphicsWindow('Keyboard Input', 240, 180); LoadDefaultColors(); clr := RGBAColor(255, 255, 255, 64); ClearScreen(ColorWhite); repeat // The game loop... ProcessEvents(); FillRectangle(clr, 0, 0, 240, 180); if KeyReleased(aKey) then DrawText('A Release', ColorBlue, 'Arial', 14, 20, 40); if KeyTyped(aKey) then DrawText('A Typed', ColorGreen, 'Arial', 14, 20, 70); if KeyDown(aKey) then DrawText('A Down', ColorRed, 'Arial', 14, 20, 100); if KeyUp(aKey) then DrawText('A Up', ColorTurquoise, 'Arial', 14, 20, 130); DrawText('KeyBoard Input', ColorRed, 'Arial', 18, 60, 15); RefreshScreen(60); until WindowCloseRequested() OR KeyTyped(ESCAPEKey) OR KeyTyped(QKey); ReleaseAllResources(); end; begin Main(); end.
unit Controller; interface uses SysUtils, Classes, ActnList, Dialogs, Forms, Graphics, LrDocument, Project, Config; type TControllerModule = class(TDataModule) ActionList1: TActionList; PublishAction: TAction; SaveAsAction: TAction; OpenAction: TAction; OpenDialog: TOpenDialog; SaveDialog: TSaveDialog; SetupDatabasesAction: TAction; SaveAction: TAction; NewTurboPhpAction: TAction; CloseAllAction: TAction; SetupServersAction: TAction; SaveProjectAction: TAction; SaveProjectAsAction: TAction; CloseProjectAction: TAction; ViewPreviewAction: TAction; NewTurboAjaxAction: TAction; procedure PublishActionExecute(Sender: TObject); procedure DataModuleCreate(Sender: TObject); procedure SaveAsActionExecute(Sender: TObject); procedure OpenActionExecute(Sender: TObject); procedure SetupDatabasesActionExecute(Sender: TObject); procedure NewTurboPhpActionExecute(Sender: TObject); procedure CloseAllActionExecute(Sender: TObject); procedure SaveActionExecute(Sender: TObject); procedure SetupServersActionExecute(Sender: TObject); procedure SaveProjectActionUpdate(Sender: TObject); procedure SaveProjectActionExecute(Sender: TObject); procedure SaveProjectAsActionExecute(Sender: TObject); procedure SaveActionUpdate(Sender: TObject); procedure CloseProjectActionExecute(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); procedure ViewPreviewActionExecute(Sender: TObject); procedure NewTurboAjaxActionExecute(Sender: TObject); private { Private declarations } function CreateTurboAjaxDocument: TLrDocument; function CreateTurboPhpDocument: TLrDocument; function GetDocument: TLrDocument; function OpenDocument(inClass: TLrDocumentClass; const inFilename: string): TLrDocument; function OpenImageDocument(const inFilename: string): TLrDocument; function OpenPhpDocument(const inFilename: string): TLrDocument; function OpenProject(const inFilename: string): TLrDocument; function OpenTurboAjaxDocument(const inFilename: string): TLrDocument; function OpenTurboPhpDocument(const inFilename: string): TLrDocument; procedure CreateStartPage; procedure NewDocument(inDocument: TLrDocument); procedure NewProject; public { Public declarations } function CloseAll: Boolean; function CloseProject: Boolean; function Open(const inFilename: string): TLrDocument; function SaveDocumentAs: Boolean; function SaveProjectAs: Boolean; procedure Shutdown; procedure Startup; property Document: TLrDocument read GetDocument; end; var ControllerModule: TControllerModule; Project: TProject; const cTurboPhpDocuments = 'TurboPhp Documents'; //cTurboPhpPages = 'TurboPhp Pages'; cTurboPhpProjects = 'TurboPhp Projects'; //cPageExt = '.tphp'; cProjectExt = '.tprj'; cPhpExt = '.php'; cConfigProject = 'Project'; implementation uses LrUtils, Globals, Documents, LiteBrowserDocument, PhpDocument, ImageDocument, TurboPhpDocument, TurboAjaxDocument, DesignHost, Inspector, ProjectView, BrowserView, DatabasesSetup, ServerSetup, TurboDocumentHost; {$R *.dfm} procedure TControllerModule.DataModuleCreate(Sender: TObject); begin OpenDialog.Filter := MakeFilter( cTurboPhpDocuments, '*' + TTurboAjaxDocument.DocumentExt + ';' + '*' + TTurboPhpDocument.DocumentExt + ';' + '*' + cProjectExt + ';' + '*' + cPhpExt + ';' + GraphicFileMask(TGraphic) ); OpenDialog.InitialDir := ProjectsHome; // SaveDialog.Filter := MakeFilter( TTurboAjaxDocument.DocumentDescription, '*' + TTurboAjaxDocument.DocumentExt // TTurboPhpDocument.DocumentDescription, // '*' + TTurboPhpDocument.DocumentExt ); SaveDialog.DefaultExt := TTurboAjaxDocument.DocumentExt; //SaveDialog.DefaultExt := TTurboPhpDocument.DocumentExt; SaveDialog.InitialDir := ProjectsHome; end; procedure TControllerModule.DataModuleDestroy(Sender: TObject); begin Project.Free; end; procedure TControllerModule.Startup; begin DocumentsForm.DocumentPanel.Visible := false; NewProject; CreateStartPage; OpenProject(Configuration.Values[cConfigProject]); end; procedure TControllerModule.Shutdown; begin Configuration.Values[cConfigProject] := Project.Filename; end; procedure TControllerModule.CreateStartPage; begin with TLiteBrowserDocument.Create do begin Filename := 'Start'; Html.Add('Welcome to TurboPhp!'); Desktop.AddDocument(ThisDocument); end; end; function TControllerModule.GetDocument: TLrDocument; begin Result := Desktop.Current; end; function TControllerModule.SaveProjectAs: Boolean; begin Result := Project.SaveAs(SaveDialog); end; procedure TControllerModule.NewProject; begin Project := TProject.Create; ProjectForm.Project := Project; Desktop.AddDocumentObserver(Project.DocumentChange); end; function TControllerModule.CloseProject: Boolean; begin Result := Project.CanClose; if Result then if Project.Modified {and Project.Untitled} then Result := SaveProjectAs; end; function TControllerModule.SaveDocumentAs: Boolean; begin Result := Document.SaveAs(SaveDialog); end; function TControllerModule.CloseAll: Boolean; begin Result := Desktop.CloseAll; end; function TControllerModule.CreateTurboAjaxDocument: TLrDocument; begin Result := TTurboAjaxDocument.Create; Result.Filename := Project.Documents.GenerateUniqueSource(Result.DisplayName); end; function TControllerModule.CreateTurboPhpDocument: TLrDocument; begin Result := TTurboPhpDocument.Create; Result.Filename := Project.Documents.GenerateUniqueSource(Result.DisplayName); end; function TControllerModule.Open(const inFilename: string): TLrDocument; var e: string; begin e := LowerCase(ExtractFileExt(inFilename)); if (e = TTurboAjaxDocument.DocumentExt) then Result := OpenTurboAjaxDocument(inFilename) else if (e = TTurboPhpDocument.DocumentExt) then Result := OpenTurboPhpDocument(inFilename) else if (e = cProjectExt) then Result := OpenProject(inFilename) else if (e = cPhpExt) then Result := OpenPhpDocument(inFilename) else Result := OpenImageDocument(inFilename); end; function TControllerModule.OpenProject(const inFilename: string): TLrDocument; begin Project.Open(inFilename); Result := Project; end; function TControllerModule.OpenDocument(inClass: TLrDocumentClass; const inFilename: string): TLrDocument; begin Result := Desktop.FindDocument(inFilename); if Result <> nil then Desktop.Current := Result else begin Result := inClass.Create; Result.Open(inFilename); Desktop.AddDocument(Result); end; end; function TControllerModule.OpenTurboAjaxDocument( const inFilename: string): TLrDocument; begin Result := OpenDocument(TTurboAjaxDocument, inFilename); end; function TControllerModule.OpenTurboPhpDocument( const inFilename: string): TLrDocument; begin Result := OpenDocument(TTurboPhpDocument, inFilename); end; function TControllerModule.OpenPhpDocument( const inFilename: string): TLrDocument; begin Result := OpenDocument(TPhpDocument, inFilename); end; function TControllerModule.OpenImageDocument( const inFilename: string): TLrDocument; begin Result := OpenDocument(TImageDocument, inFilename); end; procedure TControllerModule.PublishActionExecute(Sender: TObject); begin if Desktop.Current is TPublishableDocument then begin TurboDocumentHostForm.LazyUpdate; with TPublishableDocument(Desktop.Current) do BrowserForm.ForceNavigate(Publish(Project)); end; // with TTurboPhpDocument(Desktop.Current) do // begin // Generate(Project.PublishFolder[ThisDocument]); // BrowserForm.ForceNavigate(Project.PublishUrl[ThisDocument]); // end; //BrowserForm.ForceNavigate('http://localhost/turbophp5/test.html'); //BrowserForm.ForceNavigate(Home + 'test.html'); end; procedure TControllerModule.NewDocument(inDocument: TLrDocument); begin inDocument.New; Desktop.AddDocument(inDocument); Project.AddDocumentItem(inDocument.Filename); end; procedure TControllerModule.NewTurboPhpActionExecute(Sender: TObject); begin NewDocument(CreateTurboPhpDocument); end; procedure TControllerModule.NewTurboAjaxActionExecute(Sender: TObject); begin NewDocument(CreateTurboAjaxDocument); end; procedure TControllerModule.OpenActionExecute(Sender: TObject); begin with OpenDialog do if Execute then Open(Filename); end; procedure TControllerModule.SaveActionUpdate(Sender: TObject); begin TAction(Sender).Enabled := Document.Modified; end; procedure TControllerModule.SaveActionExecute(Sender: TObject); begin TurboDocumentHostForm.LazyUpdate; if Document.Untitled then SaveDocumentAs else Document.Save; end; procedure TControllerModule.SaveAsActionExecute(Sender: TObject); begin TurboDocumentHostForm.LazyUpdate; SaveDocumentAs; end; procedure TControllerModule.CloseAllActionExecute(Sender: TObject); begin CloseAll; end; procedure TControllerModule.SetupDatabasesActionExecute(Sender: TObject); begin with TDatabasesSetupForm.Create(nil) do try Databases := Project.Databases; ShowModal; finally Free; end; Project.Modified := true; end; procedure TControllerModule.SetupServersActionExecute(Sender: TObject); begin with TServerSetupForm.Create(nil) do try Servers := Project.Servers; ShowModal; finally Free; end; Project.Modified := true; end; procedure TControllerModule.SaveProjectActionUpdate(Sender: TObject); begin TAction(Sender).Enabled := Project.Modified; end; procedure TControllerModule.SaveProjectActionExecute(Sender: TObject); begin if Project.Untitled then SaveProjectAs else Project.Save; end; procedure TControllerModule.SaveProjectAsActionExecute(Sender: TObject); begin SaveProjectAs; end; procedure TControllerModule.CloseProjectActionExecute(Sender: TObject); begin if CloseProject then NewProject; end; procedure TControllerModule.ViewPreviewActionExecute(Sender: TObject); begin TurboDocumentHostForm.PreviewDock.Visible := true; end; end.
unit gr_AccountData_MainForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxCheckBox, dxBar, dxBarExtItems, cxSplitter, cxLabel, cxContainer, cxTextEdit, cxMaskEdit, cxDBEdit, ExtCtrls, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses, cxControls, cxGridCustomView, cxGrid, dxDockPanel, dxDockControl, cxMemo, ZcxLocateBar, FIBQuery, pFIBQuery, Dates, ZTypes, pFIBStoredProc, FIBDatabase, pFIBDatabase, FIBDataSet, pFIBDataSet, IBase, cxCheckListBox, cxGridBandedTableView, cxGridDBBandedTableView, dxStatusBar, ActnList, gr_uCommonLoader, gr_uCommonConsts, gr_uMessage, gr_uCommonProc, gr_dmCommonStyles, gr_uWaitForm; type TgrTypeDataFilter = (tdfPeople,tdfDepartment,tdfVidOpl,tdfNULL); type TFgrAccountData = class(TForm) BarManager: TdxBarManager; RefreshBtn: TdxBarLargeButton; ExitBtn: TdxBarLargeButton; DSource3: TDataSource; DSource1: TDataSource; DataBase: TpFIBDatabase; DSet3: TpFIBDataSet; DSet1: TpFIBDataSet; ReadTransaction: TpFIBTransaction; WriteTransaction: TpFIBTransaction; StoredProc: TpFIBStoredProc; dxBarDockControl2: TdxBarDockControl; FilterBtn: TdxBarLargeButton; PrintBtn: TdxBarLargeButton; PanelGrid3: TPanel; Grid3: TcxGrid; Grid3DBBandedTableView1: TcxGridDBBandedTableView; Grid3ClVo: TcxGridDBBandedColumn; Grid3ClVidOpl: TcxGridDBBandedColumn; Grid3ClSumma: TcxGridDBBandedColumn; Grid3ClP1: TcxGridDBBandedColumn; Grid3ClDepartment: TcxGridDBBandedColumn; Grid3ClSmeta: TcxGridDBBandedColumn; Grid3ClKodSetup3: TcxGridDBBandedColumn; Grid3ClReCount: TcxGridDBBandedColumn; Grid3ClNDay: TcxGridDBBandedColumn; Grid3Level1: TcxGridLevel; PanelGrid3DopData: TPanel; DBMaskEditDepartment: TcxDBMaskEdit; DBMaskEditSmeta: TcxDBMaskEdit; LabelDepartment: TcxLabel; LabelSmeta: TcxLabel; cxSplitter1: TcxSplitter; PanelGrids1and2: TPanel; SplitterGrids1And2: TSplitter; Grid2View1: TcxGridDBTableView; Grid2Level1: TcxGridLevel; Grid2: TcxGrid; cxSplitter2: TcxSplitter; Grid1: TcxGrid; Grid1View1: TcxGridDBTableView; Grid1ClTin: TcxGridDBColumn; Grid1ClFIO: TcxGridDBColumn; Grid1Level1: TcxGridLevel; Grid2ClKodSetup: TcxGridDBColumn; Grid2ClDateAcc: TcxGridDBColumn; Grid2ClTypeAcc: TcxGridDBColumn; DSet2: TpFIBDataSet; DSource2: TDataSource; dxStatusBar1: TdxStatusBar; BarDockLocate: TdxBarDockControl; ActionList: TActionList; ActionSystem: TAction; PersonBtn: TdxBarLargeButton; VObtn: TdxBarLargeButton; DepartmentBtn: TdxBarLargeButton; NotFilterBtn: TdxBarLargeButton; EditData: TdxBarEdit; MonthList1: TdxBarCombo; YearSpin1: TdxBarSpinEdit; dxBarStatic1: TdxBarStatic; MonthList2: TdxBarCombo; YearSpin2: TdxBarSpinEdit; BtnPrintAll: TdxBarLargeButton; procedure ExitBtnClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FilterBtnClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Grid3ClP1GetDisplayText(Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: String); procedure PrintBtnClick(Sender: TObject); procedure Grid3ClKodSetup3GetDisplayText( Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: String); procedure Grid3ClNDayGetDisplayText( Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: String); procedure Grid3ClClockGetDisplayText( Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: String); procedure Grid2ClKodSetupGetDisplayText(Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: String); procedure Grid1View1KeyPress(Sender: TObject; var Key: Char); procedure DSet3AfterOpen(DataSet: TDataSet); procedure Grid3DBBandedTableView1DataControllerSummaryFooterSummaryItemsSummary( ASender: TcxDataSummaryItems; Arguments: TcxSummaryEventArguments; var OutArguments: TcxSummaryEventOutArguments); procedure RefreshBtnClick(Sender: TObject); procedure dxStatusBar1Resize(Sender: TObject); procedure PanelGrid3DopDataResize(Sender: TObject); procedure ActionSystemExecute(Sender: TObject); procedure PersonBtnClick(Sender: TObject); procedure NeedFilterBtnDown(Sender:TObject); procedure VObtnClick(Sender: TObject); procedure DepartmentBtnClick(Sender: TObject); procedure NotFilterBtnClick(Sender: TObject); procedure Grid2View1FocusedRecordChanged( Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean); procedure BtnPrintAllClick(Sender: TObject); private PMode:boolean; PLanguageIndex:byte; PBarLocate:TZBarLocate; PdmStyles:TStylesDM; pCurrentFilterBtnIndex:byte; pIdFilter:integer; pTypeDataFilter:TgrTypeDataFilter; KOD_SETUP1:String; KOD_SETUP2:String; id:String; ID_TYPE:String; PAYMENT_TYPE:String; public constructor Create(AOwner : TComponent;DB:TISC_DB_HANDLE;APriznak:boolean);reintroduce; property Mode:boolean read PMode; end; function View_grAccountData(AParameter:TObject):Variant; stdcall; exports View_grAccountData; implementation uses StrUtils, Math; {$R *.dfm} const PPayment_Type=11; function TypeDataFilterToByte(AParameter:TgrTypeDataFilter):Byte; begin Result:=0; case AParameter of tdfPeople: Result:=1; tdfDepartment: Result:=2; tdfNULL: Result:=3; tdfVidOpl: Result:=4; end; end; function View_grAccountData(AParameter:TObject):Variant; var ViewForm: TFgrAccountData; i:integer; begin result:=False; for i:=Application.MainForm.MDIChildCount-1 downto 0 do if (Application.MainForm.MDIChildren[i].ClassType = TFgrAccountData) then if (Application.MainForm.MDIChildren[i] as TFgrAccountData).Mode=TgrBooleanParam(AParameter).Priznak then begin Application.MainForm.MDIChildren[i].BringToFront; Result:=True; break; end; if Result=False then begin ViewForm := TFgrAccountData.Create(TgrBooleanParam(AParameter).Owner, TgrBooleanParam(AParameter).DB_Handle, TgrBooleanParam(AParameter).Priznak); end; Result:=NULL; end; constructor TFgrAccountData.Create(AOwner : TComponent;DB:TISC_DB_HANDLE;APriznak:boolean); var pCurrKodSetup:integer; i:integer; begin Inherited Create(AOwner); //****************************************************************************** PLanguageIndex:=IndexLanguage; Caption := IfThen(APriznak,LastPeriodData_Text[PLanguageIndex],ViewAccData_Text[PLanguageIndex]); RefreshBtn.Caption := RefreshBtn_Caption[PLanguageIndex]; PrintBtn.Caption := PrintBtn_Caption[PLanguageIndex]; FilterBtn.Caption := FilterBtn_Caption[PLanguageIndex]; ExitBtn.Caption := ExitBtn_Caption[PLanguageIndex]; PersonBtn.Caption := LabelStudent_Caption[PLanguageIndex]; DepartmentBtn.Caption := LabelDepartment_Caption[PLanguageIndex]; VObtn.Caption := LabelVidOpl_Caption[PLanguageIndex]; NotFilterBtn.Caption := NotFilter_Text[PLanguageIndex]; MonthList1.Caption := LabelMonth_Caption[PLanguageIndex]; YearSpin1.Caption := LabelYear_Caption[PLanguageIndex]; MonthList2.Caption := LabelMonth_Caption[PLanguageIndex]; YearSpin2.Caption := LabelYear_Caption[PLanguageIndex]; EditData.Caption := ''; //****************************************************************************** MonthList1.Items.Text := MonthesList_Text[PLanguageIndex]; MonthList2.Items.Text := MonthesList_Text[PLanguageIndex]; pCurrKodSetup := grKodSetup(DB); MonthList1.ItemIndex := YearMonthFromKodSetup(pCurrKodSetup,False)-1; MonthList2.ItemIndex := YearMonthFromKodSetup(pCurrKodSetup,False)-1; YearSpin1.Value := YearMonthFromKodSetup(pCurrKodSetup); YearSpin2.Value := YearMonthFromKodSetup(pCurrKodSetup); //****************************************************************************** Grid1ClTin.Caption := GridClTin_Caption[PLanguageIndex]; Grid1ClFIO.Caption := GridClFIO_Caption[PLanguageIndex]; //****************************************************************************** Grid2ClKodSetup.Caption := GridClKodSetup_Caption[PLanguageIndex]; Grid2ClDateAcc.Caption := GridClDate_Caption[PLanguageIndex]; Grid2ClTypeAcc.Caption := GridClTypeCount_Caption[PLanguageIndex]; //****************************************************************************** Grid3ClVo.Caption := GridClKodVo_Caption[PLanguageIndex]; Grid3ClVidOpl.Caption := GridClNameVo_Caption[PLanguageIndex]; Grid3ClSumma.Caption := GridClSumma_Caption[PLanguageIndex]; Grid3ClP1.Caption := GridClP1_Caption[PLanguageIndex]; Grid3ClDepartment.Caption := GridClKodDepartment_Caption[PLanguageIndex]; Grid3ClSmeta.Caption := GridClKodSmeta_Caption[PLanguageIndex]; Grid3ClKodSetup3.Caption := GridClKodSetup_Caption[PLanguageIndex]; Grid3ClReCount.Caption := ''; Grid3ClNDay.Caption := GridClNday_Caption[PLanguageIndex]; //****************************************************************************** LabelDepartment.Caption := LabelDepartment_Caption[PLanguageIndex]; LabelSmeta.Caption := LabelSmeta_Caption[PLanguageIndex]; //****************************************************************************** pCurrentFilterBtnIndex:=0; PMode:=APriznak; //****************************************************************************** Grid1View1.DataController.Summary.FooterSummaryItems[0].Format := Summary_Text[PLanguageIndex]+': 0'; Grid3DBBandedTableView1.DataController.Summary.FooterSummaryItems[1].Format := Summary_Text[PLanguageIndex]+':'; //****************************************************************************** PBarLocate:=TZBarLocate.Create(BarManager); PBarLocate.DataSet := DSet1; PBarLocate.BorderStyle := bbsNone; PBarLocate.AddLocateItem('TIN', Grid1ClTin.Caption, [loCaseInsensitive]); PBarLocate.AddLocateItem('FIO', Grid1ClFIO.Caption, [loCaseInsensitive,loPartialKey]); PBarLocate.DigitalField := 'TN'; PBarLocate.DockControl := BarDockLocate; //****************************************************************************** for i:=0 to dxStatusBar1.Panels.Count-1 do dxStatusBar1.Panels[i].Width := dxStatusBar1.Width div dxStatusBar1.Panels.Count; dxStatusBar1.Panels[0].Text:= RefreshBtn.Caption+' (F5)'; dxStatusBar1.Panels[1].Text:= PBarLocate.LocateBtn.Caption+' (F7)'; dxStatusBar1.Panels[2].Text:= PBarLocate.LocateNextBtn.Caption+' (Ctrl+F7)'; dxStatusBar1.Panels[3].Text:= FilterBtn.Caption+' (F8)'; dxStatusBar1.Panels[4].Text:= PrintBtn.Caption+' (Ctrl+F5)'; dxStatusBar1.Panels[5].Text:= ExitBtn.Caption+' (Esc)'; //****************************************************************************** DataBase.Handle := DB; ReadTransaction.StartTransaction; DSet1.SQLs.SelectSQL.Text := ''; DSet2.SQLs.SelectSQL.Text := ''; DSet3.SQLs.SelectSQL.Text := ''; //****************************************************************************** SetOptionsBarManager(BarManager); SetOptionsGridView(Grid1View1); SetOptionsGridView(Grid2View1); SetOptionsGridView(Grid3DBBandedTableView1); dxBarDockControl2.SunkenBorder := True; PdmStyles := TStylesDM.Create(Self); Grid1View1.Styles.StyleSheet := PdmStyles.GridTableViewStyleSheetDevExpress; Grid2View1.Styles.StyleSheet := PdmStyles.GridTableViewStyleSheetDevExpress; Grid3DBBandedTableView1.Styles.StyleSheet := PdmStyles.GridBandedTableViewStyleSheetDevExpress; Grid1View1.OptionsView.Footer := True; Grid3DBBandedTableView1.OptionsView.Footer := True; //****************************************************************************** PanelGrid3DopData.Color := Grid3DBBandedTableView1.Styles.Background.Color; cxSplitter1.Color := Grid3DBBandedTableView1.Styles.Header.Color; //****************************************************************************** end; procedure TFgrAccountData.ExitBtnClick(Sender: TObject); begin Close; end; procedure TFgrAccountData.FormClose(Sender: TObject; var Action: TCloseAction); begin if ReadTransaction.InTransaction then ReadTransaction.Commit; if FormStyle=fsMDIChild then Action:=caFree; end; procedure TFgrAccountData.FilterBtnClick(Sender: TObject); var wf:TForm; TypeId:byte; begin wf:=ShowWaitForm(self,wfSelectData); try DSet3.Close; DSet2.Close; DSet1.Close; TypeId:=IfThen(PMode,0,2); DSet3.SQLs.SelectSQL.Text:='SELECT * FROM Z_ACCOUNT_ACC_S(?ID_GROUP_ACCOUNT,?ID_MAN,?KOD_SETUP_2,' +IntToStr(TypeId)+') order by Kod_vidopl'; TypeId:=IfThen(PMode,0,1)+TypeDataFilterToByte(pTypeDataFilter)*2; KOD_SETUP1:=IntToStr(PeriodToKodSetup(YearSpin1.IntValue,MonthList1.ItemIndex+1)) ; KOD_SETUP2:=IntToStr(PeriodToKodSetup(YearSpin2.IntValue,MonthList2.ItemIndex+1)) ; ID:=IntToStr(pIdFilter); ID_TYPE:= IntToStr(TypeId); PAYMENT_TYPE:=IntToStr(PPayment_Type); DSet1.SQLs.SelectSQL.Text:='SELECT * FROM Z_ACC_PEOPLE_LIST('+IntToStr(PeriodToKodSetup(YearSpin1.IntValue,MonthList1.ItemIndex+1))+',' +IntToStr(PeriodToKodSetup(YearSpin2.IntValue,MonthList2.ItemIndex+1))+',' +IntToStr(pIdFilter)+',' +IntToStr(TypeId)+',' +IntToStr(PPayment_Type)+') order by tn'; // ShowMessage(DSet1.SQLs.SelectSQL.Text); DSet2.SQLs.SelectSQL.Text:='SELECT * FROM Z_ACC_PEOPLE_LIST_ACCS(?ID_MAN,' +IntToStr(PeriodToKodSetup(YearSpin1.IntValue,MonthList1.ItemIndex+1))+',' +IntToStr(PeriodToKodSetup(YearSpin2.IntValue,MonthList2.ItemIndex+1))+',' +IntToStr(pIdFilter)+',' +IntToStr(TypeId)+',' +IntToStr(PPayment_Type)+') order by KOD_SETUP_2,DATE_ACC descending'; DSet1.Open; DSet2.Open; DSet3.Open; finally CloseWaitForm(wf); end; end; procedure TFgrAccountData.FormCreate(Sender: TObject); begin Grid3DBBandedTableView1.DataController.Summary.FooterSummaryItems[1].Format := Summary_Text[PLanguageIndex]; end; procedure TFgrAccountData.Grid3ClP1GetDisplayText( Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: String); begin if AText='False' then AText:=GridClP1_Ud_Text[PLanguageIndex]; if AText='True' then AText:=GridClP1_Nar_Text[PLanguageIndex]; end; procedure TFgrAccountData.PrintBtnClick(Sender: TObject); var grParam:TgrAccListParam; begin grParam:=TgrAccListParam.Create; grParam.DB_Handle := DataBase.Handle; grParam.Owner := self; grParam.Id_Man:=DSet2['ID_MAN']; grParam.IdGroupAccount:=DSet2['ID_GROUP_ACCOUNT']; grParam.KodSetup2:=DSet2['KOD_SETUP_2']; grParam.TypeTable:=IfThen(PMode,0,1); DoFunctionFromPackage(grParam,Stud_AccList_Pack); grParam.Destroy; end; procedure TFgrAccountData.Grid3ClKodSetup3GetDisplayText( Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: String); begin Atext:=KodSetupToPeriod(StrToInt(Atext),1); end; procedure TFgrAccountData.Grid3ClNDayGetDisplayText( Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: String); begin if AText='' then Exit; if StrToInt(AText)=0 then AText:=''; end; procedure TFgrAccountData.Grid3ClClockGetDisplayText( Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: String); begin if AText='' then Exit; if StrToFloat(AText)=0 then AText:=''; end; procedure TFgrAccountData.Grid2ClKodSetupGetDisplayText( Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: String); begin Atext:=KodSetupToPeriod(StrToInt(AText),0); end; procedure TFgrAccountData.Grid1View1KeyPress(Sender: TObject; var Key: Char); begin If (Key in ['0'..'9']) then begin if (Grid1View1.OptionsBehavior.IncSearchItem <> Grid1ClTin)then begin Grid1View1.Controller.IncSearchingText := ''; Grid1View1.OptionsBehavior.IncSearchItem := Grid1ClTin; end end else if (Grid1View1.OptionsBehavior.IncSearchItem <> Grid1ClFIO)then begin Grid1View1.Controller.IncSearchingText := ''; Grid1View1.OptionsBehavior.IncSearchItem := Grid1ClFIO; end; end; procedure TFgrAccountData.DSet3AfterOpen(DataSet: TDataSet); begin Grid3DBBandedTableView1.ViewData.Expand(False); end; procedure TFgrAccountData.Grid3DBBandedTableView1DataControllerSummaryFooterSummaryItemsSummary( ASender: TcxDataSummaryItems; Arguments: TcxSummaryEventArguments; var OutArguments: TcxSummaryEventOutArguments); var AItem: TcxGridTableSummaryItem; begin AItem := TcxGridTableSummaryItem(Arguments.SummaryItem); if (AItem.Column = Grid3ClSumma) and (AItem.Kind = skSum) and (AItem.Position = spFooter) then begin if (VarToStr(Grid3DBBandedTableView1.DataController.Values[Arguments.RecordIndex, Grid3ClP1.Index]) ='F') then OutArguments.Value:=-OutArguments.Value; end; end; procedure TFgrAccountData.RefreshBtnClick(Sender: TObject); var wf:TForm; begin wf:=ShowWaitForm(self,wfSelectData); if DSet3.Active then DSet3.Close; if DSet2.Active then DSet2.Close; if DSet1.Active then DSet1.Close; if Trim(DSet1.SQLs.SelectSQL.Text)<>'' then DSet1.Open; if Trim(DSet2.SQLs.SelectSQL.Text)<>'' then DSet2.Open; if Trim(DSet3.SQLs.SelectSQL.Text)<>'' then DSet3.Open; CloseWaitForm(wf); end; procedure TFgrAccountData.dxStatusBar1Resize(Sender: TObject); var i:byte; begin for i:=0 to dxStatusBar1.Panels.Count-1 do dxStatusBar1.Panels[i].Width := dxStatusBar1.Width div dxStatusBar1.Panels.Count; end; procedure TFgrAccountData.PanelGrid3DopDataResize(Sender: TObject); begin DBMaskEditDepartment.Width:=PanelGrid3DopData.Width-61; DBMaskEditSmeta.Width:=PanelGrid3DopData.Width-61; end; procedure TFgrAccountData.ActionSystemExecute(Sender: TObject); begin grShowMessage('System Data','ID_MAN = '+VarToStrDef(DSet2['ID_MAN'],'NULL')+#13+ 'ID_GROUP_ACCOUNT = '+VarToStrDef(DSet2['ID_GROUP_ACCOUNT'],'NULL')+#13+ 'KOD_SETUP_2 = '+VarToStrDef(DSet2['KOD_SETUP_2'],'NULL'),mtInformation,[mbOk]); end; procedure TFgrAccountData.PersonBtnClick(Sender: TObject); var Man:variant; begin Man:=ShowSpPeople(Self,DataBase.Handle); if VarArrayDimCount(Man)>0 then begin EditData.Text := ifThen(varIsNull(Man[4]),'',VarToStr(Man[4])+' - ')+ VarToStr(Man[1])+' '+VarToStr(Man[2])+' '+VarToStr(Man[3]); pTypeDataFilter := tdfPeople; pIdFilter := Man[0]; EditData.Caption := PersonBtn.Caption; EditData.ShowCaption := True; end else NeedFilterBtnDown(Sender); end; procedure TFgrAccountData.NeedFilterBtnDown(Sender:TObject); begin case pTypeDataFilter of tdfPeople: PersonBtn.Down := True; tdfDepartment: DepartmentBtn.Down := True; tdfVidOpl: VObtn.Down := True; tdfNULL: NotFilterBtn.Down := True; end; end; procedure TFgrAccountData.VObtnClick(Sender: TObject); var VidOpl:variant; begin VidOpl:=ShowSpVidOpl(Self,DataBase.Handle); if VarArrayDimCount(VidOpl)>0 then begin EditData.Text := ifThen(varIsNull(VidOpl[2]),'',VarToStr(VidOpl[2])+' - ')+ VarToStr(VidOpl[1]); pTypeDataFilter := tdfVidOpl; pIdFilter := VidOpl[0]; EditData.Caption := VObtn.Caption; EditData.ShowCaption := True; end else NeedFilterBtnDown(Sender); end; procedure TFgrAccountData.DepartmentBtnClick(Sender: TObject); var Department:variant; begin Department:=ShowSpDepartment(DataBase.Handle); if VarArrayDimCount(Department)>0 then begin EditData.Text := ifThen(varIsNull(Department[1]),'',VarToStr(Department[1])+' - ')+ VarToStr(Department[3]); pTypeDataFilter := tdfDepartment; pIdFilter := Department[0]; EditData.Caption := DepartmentBtn.Caption; EditData.ShowCaption := True; end else NeedFilterBtnDown(Sender); end; procedure TFgrAccountData.NotFilterBtnClick(Sender: TObject); begin pTypeDataFilter := tdfNULL; EditData.Text := ''; pIdFilter := 0; EditData.ShowCaption := False; EditData.Caption := NotFilterBtn.Caption; end; procedure TFgrAccountData.Grid2View1FocusedRecordChanged( Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean); begin PrintBtn.Enabled := not((AFocusedRecord=nil) or (AFocusedRecord.Expandable)); BtnPrintAll.Enabled := not((AFocusedRecord=nil) or (AFocusedRecord.Expandable)); end; procedure TFgrAccountData.BtnPrintAllClick(Sender: TObject); var grParam:TgrAccListParam; begin grParam:=TgrAccListParam.Create; grParam.DB_Handle := DataBase.Handle; grParam.Owner := self; grParam.Id_Man:=0; grParam.IdGroupAccount:=0;//DSet2['ID_GROUP_ACCOUNT']; grParam.KodSetup2:=DSet2['KOD_SETUP_2']; grParam.TypeTable:=2; grParam.KOD_SETUP1:=KOD_SETUP1; grParam.KOD_SETUP2:=KOD_SETUP2; grParam.id:=id; grParam.ID_TYPE:=ID_TYPE; grParam.PAYMENT_TYPE:=PAYMENT_TYPE; DoFunctionFromPackage(grParam,Stud_AccList_Pack); grParam.Destroy; end; end.
unit Ils.Utils.License; interface uses IniFiles, Classes, LbCipher, LbClass, LbAsym, LbRSA, SysUtils, LbUtils, Ils.Utils, Ils.Logger, JwaIpHlpApi, JwaIpTypes, JwaWinError, StrUtils; type TIlsLicenseChecker = class protected const CPublicKey = '30818802818069521B3AB7C725FA2F9B90F763F4751B11CAD053ECB46492B209245BA3' + '3724299BC10A0D38D7B2849268BC5C616D7D60EBFB92890CBEB25A34C3FCD1D90A55B8' + '593CDA20F4C740DB834DEBA9511E82B7FF84ED22B5CDB998B5001A3231B18F1EF62E01' + '972B2402B327A9EBC76298D7719667644817880DB205DE292FE60DB5B70203009310'; type TLicenseEventType = (letNormal, letExpired); TLicenseEvent = procedure(ASender: TObject; AEventType: TLicenseEventType) of object; class var FIlsLicenseChecker: TIlsLicenseChecker; private FValidFile: Boolean; FValidMac: Boolean; FLicenseFileName: string; FSignature: AnsiString; FValues: TStringList; FRSASSA: TLbRSASSA; FOnLicenseEvent: TLicenseEvent; FLogFunction: TLogFunction; procedure OnGetSignature(Sender: TObject; var Sig: TRSASignatureBlock); function ToLog(const AMessage: string): string; class constructor Create; class destructor Destroy; public function ValidFile: Boolean; function Expired: Boolean; function ValidMac: Boolean; function Valid: Boolean; property OnLicenseEvent: TLicenseEvent read FOnLicenseEvent write FOnLicenseEvent; constructor Create(const ALicenseFileName: string); destructor Destroy; override; end; function IlsLicenseChecker: TIlsLicenseChecker; implementation function IlsLicenseChecker: TIlsLicenseChecker; begin Result := TIlsLicenseChecker.FIlsLicenseChecker; end; { TIlsLicenseChecker } constructor TIlsLicenseChecker.Create(const ALicenseFileName: string); { function IsMacValid: Boolean; var NumInterfaces: Cardinal; OutBufLen: Cardinal; i: integer; AdapterInfo: TArray<TIpAdapterInfo>; MAC: string; begin Result := False; if FValues.Values['MAC'] = '' then Exit(True); try GetNumberOfInterfaces(NumInterfaces); SetLength(AdapterInfo, NumInterfaces); OutBufLen := NumInterfaces * SizeOf(TIpAdapterInfo); GetAdaptersInfo(@AdapterInfo[0], OutBufLen); for i := 0 to NumInterfaces - 1 do begin MAC := Format('%.2x:%.2x:%.2x:%.2x:%.2x:%.2x', [AdapterInfo[i].Address[0], AdapterInfo[i].Address[1], AdapterInfo[i].Address[2], AdapterInfo[i].Address[3], AdapterInfo[i].Address[4], AdapterInfo[i].Address[5]]); LogMessage('проверка MAC-адреса(' + MAC + ')'); if SameText(Trim(MAC), Trim(FValues.Values['MAC'])) then Exit(True); end; except on E: Exception do begin end; end; end;} function IsMacValid: Boolean; const AF_UNSPEC = 0; GAA_FLAG_INCLUDE_ALL_INTERFACES = $100; WORKING_BUFFER_SIZE = 15000; MAX_TRIES = 3; var pAddresses, pCurrAddresses: PIpAdapterAddresses; dwRetVal, outBufLen: Cardinal; i: Integer; MAC: string; begin // Memo1.Lines.Clear; Result := False; if FValues.Values['MAC'] = '' then Exit(True); outBufLen := WORKING_BUFFER_SIZE; pAddresses := nil; i := 0; repeat if Assigned(pAddresses) then FreeMem(pAddresses); GetMem(pAddresses, outBufLen); if not Assigned(pAddresses) then Exit(False); dwRetVal := GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_ALL_INTERFACES, nil, pAddresses, @outBufLen); Inc(i); until (dwRetVal <> ERROR_BUFFER_OVERFLOW) or (i = MAX_TRIES); try if NO_ERROR <> dwRetVal then // begin // if ERROR_NO_DATA = dwRetVal then begin // MessageDlg('No addresses were found for the requested parameters', mtInformation, [mbOK], 0); Exit(False); // end // else // raise Exception.Create(SysErrorMessage(dwRetVal)); // end; pCurrAddresses := pAddresses; while Assigned(pCurrAddresses) do begin if pCurrAddresses^.PhysicalAddressLength > 0 then begin // Memo1.Lines.Add(pCurrAddresses^.FriendlyName); MAC := ''; for i := 0 to pCurrAddresses^.PhysicalAddressLength - 1 do MAC := MAC + IfThen(i > 0, '-', '') + Format('%.2X', [pCurrAddresses^.PhysicalAddress[i]]); if SameText(Trim(MAC), Trim(FValues.Values['MAC'])) then Exit(True); // Memo1.Lines.Add(macAddress); // Memo1.Lines.Add(''); end; pCurrAddresses := pCurrAddresses^.Next; end; finally if Assigned(pAddresses) then FreeMem(pAddresses); end; end; var i: Integer; bin: TMemoryStream; ssig: TStringList; ini: tinifile; begin FLogFunction := Ils.Logger.ToLog; FValidFile := False; FValidMac := False; FLicenseFileName := ALicenseFileName; FValues := TStringList.Create; ssig := TStringList.Create; FRSASSA := TLbRSASSA.Create(nil); FRSASSA.OnGetSignature := OnGetSignature; bin := TMemoryStream.Create; ini := TIniFile.Create(ALicenseFileName); try FRSASSA.HashMethod := hmSHA1; FRSASSA.KeySize := aks1024; bin.SetSize(Trunc(Length(CPublicKey) / 2)); HexToBin(CPublicKey, bin.Memory, bin.Size); FRSASSA.PublicKey.LoadFromStream(bin); ini.ReadSectionValues('license_values', FValues); FValues.Sort; ini.ReadSectionValues('license', ssig); FSignature := ''; for i := 0 to ssig.Count - 1 do begin FSignature := FSignature + AnsiString(ssig.ValueFromIndex[i]); ToLog(ssig.ValueFromIndex[i]); end; try FValidFile := FRSASSA.VerifyString(AnsiString(FValues.Text)); FValidMac := IsMacValid; except on E: Exception do begin // logmessage() end; end; finally ssig.Free; ini.Free; end; end; class constructor TIlsLicenseChecker.Create; begin FIlsLicenseChecker := TIlsLicenseChecker.Create(ChangeFileExt(GetModuleName(HInstance), '.license')); end; class destructor TIlsLicenseChecker.Destroy; begin FIlsLicenseChecker.Free; end; procedure TIlsLicenseChecker.OnGetSignature(Sender: TObject; var Sig: TRSASignatureBlock); begin HexToBuffer(string(FSignature), Sig, SizeOf(Sig)); end; function TIlsLicenseChecker.Valid: Boolean; begin Result := ValidFile and ValidMac and (not Expired); if not Result then ToLog('Лицензия проверку не прошла.'); end; function TIlsLicenseChecker.ValidFile: Boolean; begin Result := FValidFile; if not Result then ToLog('Некорректный файл лицензии(' + FLicenseFileName + ').'); end; destructor TIlsLicenseChecker.Destroy; begin FRSASSA.Free; FValues.Free; inherited; end; function TIlsLicenseChecker.Expired: Boolean; begin Result := (FValues.Values['validtrough'] <> '') and (Now >= (IlsToDateTime(FValues.Values['validtrough']) + 1)); if Result then ToLog('Лицензия закончилась(' + FValues.Values['validtrough'] + ').'); end; function TIlsLicenseChecker.ValidMac: Boolean; begin Result := FValidMac; if not Result then ToLog('Не найден MAC-адрес(' + FValues.Values['MAC'] + ').'); end; function TIlsLicenseChecker.ToLog(const AMessage: string): string; begin if not Assigned(FLogFunction) then Result := AMessage else Result := FLogFunction(AMessage); end; end.
unit WdxFieldsProc; //Юнит для плагина Super_WDX interface uses StdCtrls,Windows,SysUtils,ContPlug,Classes; type TContentGetSupportedField = function(FieldIndex: integer; FieldName: pchar; Units: pchar; maxlen: integer): integer; stdcall; TContentGetValue = function(FileName: pchar; FieldIndex, UnitIndex: integer; FieldValue: pbyte; maxlen, flags: integer): integer; stdcall; TContentSetDefaultParams = procedure(dps: pContentDefaultParamStruct); stdcall; TContentGetFormattedValue = function (FileName,ContentString : pchar;FieldValue:pchar;MaxLen:Integer):integer; stdcall; Function GetWdxFieldName (const fPlugin:string; FieldNum:integer):string; function GetWdxField(const fPlugin, fFile: string; FieldNumber:integer): string; Function GetWdxFieldNum (const fPlugin:string; FieldName:string):integer; Function GetFormattedValue (PluginName,FileName,ContentString:string):string; Procedure DebugLog (LogMessage:string);//создаёт отчёт об ошибке var PluginPath:String;// - общая переменная - путь к плагину, чтоб не передавать его каждый раз, пущай висит в памяти Debug:boolean; Implementation Procedure DebugLog (LogMessage:string);//создаёт отчёт об ошибке var f:textfile; Begin if not debug then exit; if not fileexists (IncludeTrailingBackSlash(extractfilepath (PluginPath))+'DebugLog.txt') then begin AssignFile (f,IncludeTrailingBackSlash(extractfilepath (PluginPath))+'DebugLog.txt'); rewrite (f); closefile (f); end; AssignFile (f,IncludeTrailingBackSlash(extractfilepath (PluginPath))+'DebugLog.txt'); Append (f); Writeln (f,datetostr (now)+'-'+timetostr(now)+': '+LogMessage); closefile (f); end; function WdxFieldType(n: integer): string; begin case n of FT_NUMERIC_32: Result:= 'FT_NUMERIC_32'; FT_NUMERIC_64: Result:= 'FT_NUMERIC_64'; FT_NUMERIC_FLOATING: Result:= 'FT_NUMERIC_FLOATING'; FT_DATE: Result:= 'FT_DATE'; FT_TIME: Result:= 'FT_TIME'; FT_DATETIME: Result:= 'FT_DATETIME'; FT_BOOLEAN: Result:= 'FT_BOOLEAN'; FT_MULTIPLECHOICE: Result:= 'FT_MULTIPLECHOICE'; FT_STRING: Result:= 'FT_STRING'; FT_FULLTEXT: Result:= 'FT_FULLTEXT'; FT_NOSUCHFIELD: Result:= 'FT_NOSUCHFIELD'; FT_FILEERROR: Result:= 'FT_FILEERROR'; FT_FIELDEMPTY: Result:= 'FT_FIELDEMPTY'; FT_DELAYED: Result:= 'FT_DELAYED'; else Result:= '?'; end; end; //----------------------------------------------- var fieldsNum: integer; Function LoadPlugin (PluginName:pchar):hWnd; Begin result:=GetModuleHandle(PluginName);// Эта функция и заменяет весь динамический массив с хэндлами. if result=0 then //если не загружена result:=LoadLibrary(PluginName); end; {-------function not used in wdx plugin, only in ssettings---------------------} //по номеру поля плагина выдаёт название поля. Function GetWdxFieldName (const fPlugin:string; FieldNum:integer):string; var hLib: THandle; Proc1: TContentGetSupportedField; Proc2: TContentGetValue; Proc3: TContentSetDefaultParams; dps: TContentDefaultParamStruct; buf1, buf2: array[0..2*1024] of char; res: integer; Begin result:=''; hLib:= LoadPlugin(PChar(fPlugin));//получаем хендл библиотеки if hLib=0 then Exit; //загрузка не получилась. В идеале надо бы написать if (hLib=0) or (hLib=INVALID_HANDLE_VALUE, ну да ладно. Дальше: тут же можно сделать какое-либо действие при несостоявшейся загрузки, хотя сейчас это обрабатывается вполне корректно (просто результат будет пустым) @Proc3:= GetProcAddress(hLib, 'ContentSetDefaultParams'); if @Proc3<>nil then begin FillChar(dps, SizeOf(dps), 0); dps.Size:= SizeOf(dps); dps.PluginInterfaceVersionLow:= 30; dps.PluginInterfaceVersionHi:= 1; lstrcpy(dps.DefaultIniName, Pchar(IncludeTrailingBackSlash(extractfilepath (PluginPath))+'Plugins.ini')); Proc3(@dps); end; @Proc1:= GetProcAddress(hLib, 'ContentGetSupportedField');//получаем адрес процедуры ContentGetSupportedField из плагина if @Proc1=nil then begin FreeLibrary(hLib); Exit end; //да будет так, хотя можно и по другому. try FillChar(buf1, SizeOf(buf1), 0); //заполняем буфера нулями FillChar(buf2, SizeOf(buf2), 0); res:= Proc1(fieldNum+1, buf1, buf2, SizeOf(buf1));//вызываем ContentGetSupportedField, параметры ясны. //res - тип поля (см. справку по написанию плагинов), buf1 - название fieldNum+1 поля плагина. if res=ft_nomorefields then //если тип ft_nomorefields - такого поля не существует. begin result:=''; end; result:=buf1; if buf2[0]<>#0 then begin result:=result+'>'; result:=result+buf2; end; finally // FreeLibrary(hLib); - не нужно (библиотеки не выгружаются, чтобы избежать повторной долгой загрузки). end; End; //Процедура, обратная предыдущей - по имени поля возвращает его номер //Процедура, обратная предыдущей - по имени поля возвращает его номер Function GetWdxFieldNum (const fPlugin:string; FieldName:string):integer; var hLib: THandle; Proc1: TContentGetSupportedField; Proc2: TContentGetValue; buf1, buf2: array[0..2*1024] of char; res: integer; begin result:=-1; hlib:=LoadPlugin (pchar (fPlugin));//загрузка плагина if hLib=0 then Exit; @Proc1:= GetProcAddress(hLib, 'ContentGetSupportedField'); if @Proc1=nil then begin FreeLibrary(hLib); Exit end; fieldsNum:= -1; repeat FillChar(buf1, SizeOf(buf1), 0); FillChar(buf2, SizeOf(buf2), 0); res:= Proc1(fieldsNum+1, buf1, buf2, SizeOf(buf1));//проходим по всем полям плагина, пока процедура не вернёт ft_nomorefields (что исключает зацикливание) или не будет найдено нужное поле. Можно бы сделать через while, но несущественно if res=ft_nomorefields then Break;//выход из цикла Inc(fieldsNum); if copy(buf1,1,length(FieldName))=(FieldName) then//проверяем имя очередного найденного поля с именем искомого begin result:=FieldsNum+1;//если сошлось - возвращаем результат (+1 потому что нумерация в плаге на 1 меньше) break;//выходим из цикла end; until false; END; //по имени плагина fPlugin выдаёт значение поля FieldNumber для файла fFile. function GetWdxField(const fPlugin, fFile: string; FieldNumber:integer): string; var hLib: THandle; Proc1: TContentGetSupportedField; Proc2: TContentGetValue; Proc3: TContentSetDefaultParams; dps: TContentDefaultParamStruct; buf1, buf2: array[0..2*1024] of char; fnval: integer absolute buf1; fnval64: Int64 absolute buf1; ffval: Double absolute buf1; fdate: TDateFormat absolute buf1; ftime: TTimeFormat absolute buf1; xtime: TFileTime absolute buf1; stime: TSystemTime; sval: string; res: integer; begin Result:= ''; hlib:=LoadPlugin (pchar (fPlugin));//получаем хендл плагина if hLib=0 then Exit; //без вызова ContentSetDefaultParams начинаются глюки @Proc3:= GetProcAddress(hLib, 'ContentSetDefaultParams'); if @Proc3<>nil then begin FillChar(dps, SizeOf(dps), 0); dps.Size:= SizeOf(dps); dps.PluginInterfaceVersionLow:= 30; dps.PluginInterfaceVersionHi:= 1; lstrcpy(dps.DefaultIniName, Pchar(IncludeTrailingBackSlash(extractfilepath (PluginPath))+'Plugins.ini')); Proc3(@dps); end; @Proc2:= GetProcAddress(hLib, 'ContentGetValue');//получаем адрес процедуры ContentGetValue из плагина. if @Proc2=nil then begin FreeLibrary(hLib); Exit end; try FieldsNum:=FieldNumber; FillChar(buf1, SizeOf(buf1), 0); FillChar(buf2, SizeOf(buf2), 0); res:= Proc2(PChar(fFile), FieldNumber-1, 0, @buf1, SizeOf(buf1), 0);//вызываем ContentGetValue, передаём имя файла, номер поля, UnitIndex нас не интересует - равен 0, адрес и размер буфера для возвращаемого результата. Res - тип поля sval:= ''; case res of//по типу поля ковертируем полученное значение в String. ft_fieldempty: sval:= ''; ft_numeric_32: sval:= IntToStr(fnval); ft_numeric_64: sval:= IntToStr(fnval64); ft_numeric_floating: sval:= FloatToStr(ffval); ft_date: sval:= Format('%2.2d.%2.2d.%4.4d', [fdate.wDay, fdate.wMonth, fdate.wYear]); ft_time: sval:= Format('%2.2d:%2.2d:%2.2d', [ftime.wHour, ftime.wMinute, ftime.wSecond]); ft_datetime: begin FileTimeToSystemTime(xtime, stime); sval:= Format('%2.2d.%2.2d.%4.4d %2.2d:%2.2d:%2.2d', [stime.wDay, stime.wMonth, stime.wYear, stime.wHour, stime.wMinute, stime.wSecond]); end; ft_boolean: if fnval=0 then sval:= 'FALSE' else sval:= 'TRUE'; ft_string, ft_multiplechoice, ft_fulltext: sval:= buf1; else sval:= WdxFieldType(res);//если тип поля неучтённый - возвращаем в результате название типа. end; result:=sval; Except on e:Exception do begin result:='ERROR!'; //если произошла ошибка в блоке try возвращаем ошибку. end; end; END; Function GetFormattedValue (PluginName,FileName,ContentString:string):string; var hLib: THandle; GFV: TContentGetFormattedValue; res:array [0..2*1024] of char; begin Result:= ''; hlib:=LoadPlugin (pchar (PluginName));//получаем хендл плагина if hLib=0 then Exit; @GFV:= GetProcAddress(hLib, 'GetFormattedValue'); if @GFV<>nil then begin FillChar(res, SizeOf(res), 0); if GFV (Pchar(FileName),PChar(ContentString),@res,sizeof (res))=1 then result:=res else result:='Can''t get value'; end; End; end. //That`s all.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TForm1 = class(TForm) edt: TEdit; Button1: TButton; Memo1: TMemo; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Button1Click(Sender: TObject); private fList: TStringList; public function Suchen(aZahl: Integer): Integer; end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); var i1: Integer; begin fList := TStringList.Create; //for i1 := 1 to 1000000 do for i1 := 1 to 10000 do begin fList.Add(IntToStr(i1)); end; end; procedure TForm1.FormDestroy(Sender: TObject); begin FreeAndNil(fList); end; function TForm1.Suchen(aZahl: Integer): Integer; var L, R, M : Integer; Gefunden: Boolean; Zahl: Integer; Durchlauf: Integer; begin Result := -1; Memo1.Clear; if aZahl > fList.Count then begin memo1.Lines.Add('Zahl ist zu hoch'); exit; end; L := 0; R := fList.Count; M := -1; Gefunden := false; Durchlauf := 0; while (L <= R) and (not Gefunden) do begin M := (L+R) div 2; Zahl := StrToInt(fList.Strings[M]); Memo1.Lines.Add('Geprüfte Zahl: ' + fList.Strings[M]); if aZahl < Zahl then R := M - 1; if aZahl > Zahl then L := M + 1; if aZahl = Zahl then Gefunden := true; inc(Durchlauf); end; if Gefunden then Result := M; Memo1.Lines.Add('Durchlauf: ' + IntToStr(Durchlauf)); end; procedure TForm1.Button1Click(Sender: TObject); var ItemIndex: Integer; begin ItemIndex := Suchen(StrToInt(edt.Text)); if ItemIndex > -1 then Caption := 'Gefunden = ' + fList.Strings[ItemIndex] else Caption := 'Nicht Gefunden '; end; end.
unit Objekt.Dateikopieren; interface uses System.SysUtils, System.Classes; type TDateiKopierenProgressEvent = procedure(aFileSize, aBytesTransferred: Int64) of object; TDateiKopierenFileSizeEvent = procedure(aFileSize: Int64) of object; type TDateiKopieren = class private fOnProgress: TDateiKopierenProgressEvent; fCancel: Boolean; fOnFileSize: TDateiKopierenFileSizeEvent; fOnAfterCopy: TNotifyEvent; public procedure CopyFile(aSource, aDest: String); property OnProgress: TDateiKopierenProgressEvent read fOnProgress write fOnProgress; property OnFileSize: TDateiKopierenFileSizeEvent read fOnFileSize write fOnFileSize; property OnAfterCopy: TNotifyEvent read fOnAfterCopy write fOnAfterCopy; property Cancel: Boolean read fCancel write fCancel; constructor Create; end; implementation { TDateiKopieren } constructor TDateiKopieren.Create; begin fCancel := false; end; function GetFileSize(const FileName: string): Int64; var FileStream: TFileStream; begin FileStream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyNone); try try Result := FileStream.Size; except Result := 0; end; finally FileStream.Free; end; end; procedure TDateiKopieren.CopyFile(aSource, aDest: String); var FromF, ToF: file; NumRead, NumWritten, DataSize: Integer; Buf: array[1..2048] of Char; FileSize: Int64; BytesTransferred: Int64; begin Filesize := GetFileSize(aSource); if Assigned(fOnFileSize) then fOnFileSize(FileSize); BytesTransferred := 0; try DataSize := SizeOf(Buf); AssignFile(FromF, aSource); Reset(FromF, 1); AssignFile(ToF, aDest); Rewrite(ToF, 1); repeat BlockRead(FromF, Buf, DataSize, NumRead); BlockWrite(ToF, Buf, NumRead, NumWritten); if Assigned(fOnProgress) then begin BytesTransferred := BytesTransferred + DataSize; fOnProgress(FileSize, BytesTransferred); if fCancel then break; end; until (NumRead = 0) or (NumWritten <> NumRead); finally CloseFile(FromF); CloseFile(ToF); if fCancel then DeleteFile(aDest); if Assigned(fOnAfterCopy) then fOnAfterCopy(Self); end; end; end.
unit ArrayUtils; interface // Converts an input byte array to hexadecimal string representation function GetHexadecimalString(inputArray : array of byte) : String; implementation uses SysUtils; function GetHexadecimalString(inputArray : array of byte) : String; var i : Integer; resultStr : String; begin resultStr := ''; for i:= 0 to Length(inputArray) - 1 do begin resultStr := resultStr + IntToHex(inputArray[i],2); end; Result := resultStr; end; end.
(*==========================================================================; * * Copyright (C) 1995-1997 Microsoft Corporation. All Rights Reserved. * * File: d3dtypes.h * Content: Direct3D types include file * * DirectX 5 Delphi adaptation by Erik Unger * (based on Blake Stone's DirectX 3 adaptation) * * Modyfied: 21.3.98 * * Download: http://www.sbox.tu-graz.ac.at/home/ungerik/DelphiGraphics/ * E-Mail: h_unger@magnet.at * ***************************************************************************) unit D3DTypes; {$MODE Delphi} {$INCLUDE COMSWITCH.INC} interface uses {$IFDEF D2COM} OLE2, {$ENDIF} Windows, DDraw; (* TD3DValue is the fundamental Direct3D fractional data type *) type TRefClsID = TGUID; type TD3DValue = single; TD3DFixed = LongInt; float = TD3DValue; PD3DColor = ^TD3DColor; TD3DColor = DWORD; // #define D3DVALP(val, prec) ((float)(val)) // #define D3DVAL(val) ((float)(val)) function D3DVAL(val: variant) : float; function D3DDivide(a,b: variant) : variant; function D3DMultiply(a,b: variant) : variant; (* * Format of CI colors is * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | alpha | color index | fraction | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ *) // #define CI_GETALPHA(ci) ((ci) >> 24) function CI_GETALPHA(ci: DWORD) : DWORD; // #define CI_GETINDEX(ci) (((ci) >> 8) & 0xffff) function CI_GETINDEX(ci: DWORD) : DWORD; // #define CI_GETFRACTION(ci) ((ci) & 0xff) function CI_GETFRACTION(ci: DWORD) : DWORD; // #define CI_ROUNDINDEX(ci) CI_GETINDEX((ci) + 0x80) function CI_ROUNDINDEX(ci: DWORD) : DWORD; // #define CI_MASKALPHA(ci) ((ci) & 0xffffff) function CI_MASKALPHA(ci: DWORD) : DWORD; // #define CI_MAKE(a, i, f) (((a) << 24) | ((i) << 8) | (f)) function CI_MAKE(a,i,f: DWORD) : DWORD; (* * Format of RGBA colors is * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | alpha | red | green | blue | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ *) // #define RGBA_GETALPHA(rgb) ((rgb) >> 24) function RGBA_GETALPHA(rgb: TD3DColor) : DWORD; // #define RGBA_GETRED(rgb) (((rgb) >> 16) & 0xff) function RGBA_GETRED(rgb: TD3DColor) : DWORD; // #define RGBA_GETGREEN(rgb) (((rgb) >> 8) & 0xff) function RGBA_GETGREEN(rgb: TD3DColor) : DWORD; // #define RGBA_GETBLUE(rgb) ((rgb) & 0xff) function RGBA_GETBLUE(rgb: TD3DColor) : DWORD; // #define RGBA_MAKE(r, g, b, a) ((TD3DColor) (((a) << 24) | ((r) << 16) | ((g) << 8) | (b))) function RGBA_MAKE(r, g, b, a: DWORD) : TD3DColor; (* D3DRGB and D3DRGBA may be used as initialisers for D3DCOLORs * The float values must be in the range 0..1 *) // #define D3DRGB(r, g, b) \ // (0xff000000L | (((long)((r) * 255)) << 16) | (((long)((g) * 255)) << 8) | (long)((b) * 255)) function D3DRGB(r, g, b: float) : TD3DColor; // #define D3DRGBA(r, g, b, a) \ // ( (((long)((a) * 255)) << 24) | (((long)((r) * 255)) << 16) \ // | (((long)((g) * 255)) << 8) | (long)((b) * 255) \ // ) function D3DRGBA(r, g, b, a: float) : TD3DColor; (* * Format of RGB colors is * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | ignored | red | green | blue | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ *) // #define RGB_GETRED(rgb) (((rgb) >> 16) & 0xff) function RGB_GETRED(rgb: TD3DColor) : DWORD; // #define RGB_GETGREEN(rgb) (((rgb) >> 8) & 0xff) function RGB_GETGREEN(rgb: TD3DColor) : DWORD; // #define RGB_GETBLUE(rgb) ((rgb) & 0xff) function RGB_GETBLUE(rgb: TD3DColor) : DWORD; // #define RGBA_SETALPHA(rgba, x) (((x) << 24) | ((rgba) & 0x00ffffff)) function RGBA_SETALPHA(rgba: TD3DColor; x: DWORD) : TD3DColor; // #define RGB_MAKE(r, g, b) ((TD3DColor) (((r) << 16) | ((g) << 8) | (b))) function RGB_MAKE(r, g, b: DWORD) : TD3DColor; // #define RGBA_TORGB(rgba) ((TD3DColor) ((rgba) & 0xffffff)) function RGBA_TORGB(rgba: TD3DColor) : TD3DColor; // #define RGB_TORGBA(rgb) ((TD3DColor) ((rgb) | 0xff000000)) function RGB_TORGBA(rgb: TD3DColor) : TD3DColor; (* * Flags for Enumerate functions *) (* * Stop the enumeration *) const D3DENUMRET_CANCEL = DDENUMRET_CANCEL; (* * Continue the enumeration *) D3DENUMRET_OK = DDENUMRET_OK; type // typedef HResult (WINAPI* LPD3DVALIDATECALLBACK)(LPVOID lpUserArg, DWORD dwOffset); TD3DValidateCallback = function (lpUserArg: Pointer; dwOffset: DWORD): HResult; stdcall; // typedef HResult (WINAPI* LPD3DENUMTEXTUREFORMATSCALLBACK)(LPDDSURFACEDESC lpDdsd, LPVOID lpContext); TD3DEnumTextureFormatsCallback = function (const lpDdsd: TDDSurfaceDesc; lpUserArg: Pointer): HResult; stdcall; PD3DMaterialHandle = ^TD3DMaterialHandle; TD3DMaterialHandle = DWORD; PD3DTextureHandle = ^TD3DTextureHandle; TD3DTextureHandle = DWORD; PD3DMatrixHandle = ^TD3DMatrixHandle; TD3DMatrixHandle = DWORD; PD3DColorValue = ^TD3DColorValue; TD3DColorValue = packed record case Integer of 0: ( r: TD3DValue; g: TD3DValue; b: TD3DValue; a: TD3DValue; ); 1: ( dvR: TD3DValue; dvG: TD3DValue; dvB: TD3DValue; dvA: TD3DValue; ); end; PD3DRect = ^TD3DRect; TD3DRect = packed record case Integer of 0: ( x1: LongInt; y1: LongInt; x2: LongInt; y2: LongInt; ); 1: ( lX1: LongInt; lY1: LongInt; lX2: LongInt; lY2: LongInt; ); 2: ( a: array[0..3] of LongInt; ); end; PD3DVector = ^TD3DVector; TD3DVector = packed record case Integer of 0: ( x: TD3DValue; y: TD3DValue; z: TD3DValue; ); 1: ( dvX: TD3DValue; dvY: TD3DValue; dvZ: TD3DValue; ); end; // Addition and subtraction function VectorAdd(const v1, v2: TD3DVector) : TD3DVector; function VectorSub(const v1, v2: TD3DVector) : TD3DVector; // Scalar multiplication and division function VectorMulS(const v: TD3DVector; s: TD3DValue) : TD3DVector; function VectorDivS(const v: TD3DVector; s: TD3DValue) : TD3DVector; // Memberwise multiplication and division function VectorMul(const v1, v2: TD3DVector) : TD3DVector; function VectorDiv(const v1, v2: TD3DVector) : TD3DVector; // Vector dominance function VectorSmaller(v1, v2: TD3DVector) : boolean; function VectorSmallerEquel(v1, v2: TD3DVector) : boolean; // Bitwise equality function VectorEquel(v1, v2: TD3DVector) : boolean; // Length-related functions function VectorSquareMagnitude(v: TD3DVector) : TD3DValue; function VectorMagnitude(v: TD3DVector) : TD3DValue; // Returns vector with same direction and unit length function VectorNormalize(const v: TD3DVector) : TD3DVector; // Return min/max component of the input vector function VectorMin(v: TD3DVector) : TD3DValue; function VectorMax(v: TD3DVector) : TD3DValue; // Return memberwise min/max of input vectors function VectorMinimize(const v1, v2: TD3DVector) : TD3DVector; function VectorMaximize(const v1, v2: TD3DVector) : TD3DVector; // Dot and cross product function VectorDotProduct(v1, v2: TD3DVector) : TD3DValue; function VectorCrossProduct(const v1, v2: TD3DVector) : TD3DVector; type (* * Vertex data types supported in an ExecuteBuffer. *) (* * Homogeneous vertices *) TD3DHVertex = packed record dwFlags: DWORD; (* Homogeneous clipping flags *) case Integer of 0: ( hx: TD3DValue; hy: TD3DValue; hz: TD3DValue; ); 1: ( dvHX: TD3DValue; dvHY: TD3DValue; dvHZ: TD3DValue; ); end; (* * Transformed/lit vertices *) TD3DTLVertex = packed record case Integer of 0: ( sx: TD3DValue; (* Screen coordinates *) sy: TD3DValue; sz: TD3DValue; rhw: TD3DValue; (* Reciprocal of homogeneous w *) color: TD3DColor; (* Vertex color *) specular: TD3DColor; (* Specular component of vertex *) tu: TD3DValue; (* Texture coordinates *) tv: TD3DValue; ); 1: ( dvSX: TD3DValue; dvSY: TD3DValue; dvSZ: TD3DValue; dvRHW: TD3DValue; dcColor: TD3DColor; dcSpecular: TD3DColor; dvTU: TD3DValue; dvTV: TD3DValue; ); end; (* * Untransformed/lit vertices *) TD3DLVertex = packed record case Integer of 0: ( x: TD3DValue; (* Homogeneous coordinates *) y: TD3DValue; z: TD3DValue; dwReserved: DWORD; color: TD3DColor; (* Vertex color *) specular: TD3DColor; (* Specular component of vertex *) tu: TD3DValue; (* Texture coordinates *) tv: TD3DValue; ); 1: ( dvX: TD3DValue; dvY: TD3DValue; dvZ: TD3DValue; UNIONFILLER1d: DWORD; dcColor: TD3DColor; dcSpecular: TD3DColor; dvTU: TD3DValue; dvTV: TD3DValue; ); end; (* * Untransformed/unlit vertices *) TD3DVertex = packed record case Integer of 0: ( x: TD3DValue; (* Homogeneous coordinates *) y: TD3DValue; z: TD3DValue; nx: TD3DValue; (* Normal *) ny: TD3DValue; nz: TD3DValue; tu: TD3DValue; (* Texture coordinates *) tv: TD3DValue; ); 1: ( dvX: TD3DValue; dvY: TD3DValue; dvZ: TD3DValue; dvNX: TD3DValue; dvNY: TD3DValue; dvNZ: TD3DValue; dvTU: TD3DValue; dvTV: TD3DValue; ); end; (* * Matrix, viewport, and tranformation structures and definitions. *) TD3DMatrix = packed record _11, _12, _13, _14: TD3DValue; _21, _22, _23, _24: TD3DValue; _31, _32, _33, _34: TD3DValue; _41, _42, _43, _44: TD3DValue; end; TD3DMatrix_ = array [0..3, 0..3] of TD3DValue; TD3DViewport = packed record dwSize: DWORD; dwX: DWORD; dwY: DWORD; (* Top left *) dwWidth: DWORD; dwHeight: DWORD; (* Dimensions *) dvScaleX: TD3DValue; (* Scale homogeneous to screen *) dvScaleY: TD3DValue; (* Scale homogeneous to screen *) dvMaxX: TD3DValue; (* Min/max homogeneous x coord *) dvMaxY: TD3DValue; (* Min/max homogeneous y coord *) dvMinZ: TD3DValue; dvMaxZ: TD3DValue; (* Min/max homogeneous z coord *) end; TD3DViewport2 = packed record dwSize: DWORD; dwX: DWORD; dwY: DWORD; (* Top left *) dwWidth: DWORD; dwHeight: DWORD; (* Dimensions *) dvClipX: TD3DValue; (* Top left of clip volume *) dvClipY: TD3DValue; dvClipWidth: TD3DValue; (* Clip Volume Dimensions *) dvClipHeight: TD3DValue; dvMinZ: TD3DValue; dvMaxZ: TD3DValue; (* Min/max homogeneous z coord *) end; (* * Values for clip fields. *) const D3DCLIP_LEFT = $00000001; D3DCLIP_RIGHT = $00000002; D3DCLIP_TOP = $00000004; D3DCLIP_BOTTOM = $00000008; D3DCLIP_FRONT = $00000010; D3DCLIP_BACK = $00000020; D3DCLIP_GEN0 = $00000040; D3DCLIP_GEN1 = $00000080; D3DCLIP_GEN2 = $00000100; D3DCLIP_GEN3 = $00000200; D3DCLIP_GEN4 = $00000400; D3DCLIP_GEN5 = $00000800; (* * Values for d3d status. *) D3DSTATUS_CLIPUNIONLEFT = D3DCLIP_LEFT; D3DSTATUS_CLIPUNIONRIGHT = D3DCLIP_RIGHT; D3DSTATUS_CLIPUNIONTOP = D3DCLIP_TOP; D3DSTATUS_CLIPUNIONBOTTOM = D3DCLIP_BOTTOM; D3DSTATUS_CLIPUNIONFRONT = D3DCLIP_FRONT; D3DSTATUS_CLIPUNIONBACK = D3DCLIP_BACK; D3DSTATUS_CLIPUNIONGEN0 = D3DCLIP_GEN0; D3DSTATUS_CLIPUNIONGEN1 = D3DCLIP_GEN1; D3DSTATUS_CLIPUNIONGEN2 = D3DCLIP_GEN2; D3DSTATUS_CLIPUNIONGEN3 = D3DCLIP_GEN3; D3DSTATUS_CLIPUNIONGEN4 = D3DCLIP_GEN4; D3DSTATUS_CLIPUNIONGEN5 = D3DCLIP_GEN5; D3DSTATUS_CLIPINTERSECTIONLEFT = $00001000; D3DSTATUS_CLIPINTERSECTIONRIGHT = $00002000; D3DSTATUS_CLIPINTERSECTIONTOP = $00004000; D3DSTATUS_CLIPINTERSECTIONBOTTOM = $00008000; D3DSTATUS_CLIPINTERSECTIONFRONT = $00010000; D3DSTATUS_CLIPINTERSECTIONBACK = $00020000; D3DSTATUS_CLIPINTERSECTIONGEN0 = $00040000; D3DSTATUS_CLIPINTERSECTIONGEN1 = $00080000; D3DSTATUS_CLIPINTERSECTIONGEN2 = $00100000; D3DSTATUS_CLIPINTERSECTIONGEN3 = $00200000; D3DSTATUS_CLIPINTERSECTIONGEN4 = $00400000; D3DSTATUS_CLIPINTERSECTIONGEN5 = $00800000; D3DSTATUS_ZNOTVISIBLE = $01000000; D3DSTATUS_CLIPUNIONALL = ( D3DSTATUS_CLIPUNIONLEFT or D3DSTATUS_CLIPUNIONRIGHT or D3DSTATUS_CLIPUNIONTOP or D3DSTATUS_CLIPUNIONBOTTOM or D3DSTATUS_CLIPUNIONFRONT or D3DSTATUS_CLIPUNIONBACK or D3DSTATUS_CLIPUNIONGEN0 or D3DSTATUS_CLIPUNIONGEN1 or D3DSTATUS_CLIPUNIONGEN2 or D3DSTATUS_CLIPUNIONGEN3 or D3DSTATUS_CLIPUNIONGEN4 or D3DSTATUS_CLIPUNIONGEN5); D3DSTATUS_CLIPINTERSECTIONALL = ( D3DSTATUS_CLIPINTERSECTIONLEFT or D3DSTATUS_CLIPINTERSECTIONRIGHT or D3DSTATUS_CLIPINTERSECTIONTOP or D3DSTATUS_CLIPINTERSECTIONBOTTOM or D3DSTATUS_CLIPINTERSECTIONFRONT or D3DSTATUS_CLIPINTERSECTIONBACK or D3DSTATUS_CLIPINTERSECTIONGEN0 or D3DSTATUS_CLIPINTERSECTIONGEN1 or D3DSTATUS_CLIPINTERSECTIONGEN2 or D3DSTATUS_CLIPINTERSECTIONGEN3 or D3DSTATUS_CLIPINTERSECTIONGEN4 or D3DSTATUS_CLIPINTERSECTIONGEN5); D3DSTATUS_DEFAULT = ( D3DSTATUS_CLIPINTERSECTIONALL or D3DSTATUS_ZNOTVISIBLE); (* * Options for direct transform calls *) D3DTRANSFORM_CLIPPED = $00000001; D3DTRANSFORM_UNCLIPPED = $00000002; type TD3DTransformData = packed record dwSize: DWORD; lpIn: Pointer; (* Input vertices *) dwInSize: DWORD; (* Stride of input vertices *) lpOut: Pointer; (* Output vertices *) dwOutSize: DWORD; (* Stride of output vertices *) lpHOut: ^TD3DHVertex; (* Output homogeneous vertices *) dwClip: DWORD; (* Clipping hint *) dwClipIntersection: DWORD; dwClipUnion: DWORD; (* Union of all clip flags *) drExtent: TD3DRect; (* Extent of transformed vertices *) end; (* * Structure defining position and direction properties for lighting. *) TD3DLightingElement = packed record dvPosition: TD3DVector; (* Lightable point in model space *) dvNormal: TD3DVector; (* Normalised unit vector *) end; (* * Structure defining material properties for lighting. *) TD3DMaterial = packed record dwSize: DWORD; case Integer of 0: ( diffuse: TD3DColorValue; (* Diffuse color RGBA *) ambient: TD3DColorValue; (* Ambient color RGB *) specular: TD3DColorValue; (* Specular 'shininess' *) emissive: TD3DColorValue; (* Emissive color RGB *) power: TD3DValue; (* Sharpness if specular highlight *) hTexture: TD3DTextureHandle; (* Handle to texture map *) dwRampSize: DWORD; ); 1: ( dcvDiffuse: TD3DColorValue; dcvAmbient: TD3DColorValue; dcvSpecular: TD3DColorValue; dcvEmissive: TD3DColorValue; dvPower: TD3DValue; ); end; TD3DLightType = ( D3DLIGHT_INVALID_0, D3DLIGHT_POINT, D3DLIGHT_SPOT, D3DLIGHT_DIRECTIONAL, D3DLIGHT_PARALLELPOINT, D3DLIGHT_GLSPOT); (* * Structure defining a light source and its properties. *) TD3DLight = packed record dwSize: DWORD; dltType: TD3DLightType; (* Type of light source *) dcvColor: TD3DColorValue; (* Color of light *) dvPosition: TD3DVector; (* Position in world space *) dvDirection: TD3DVector; (* Direction in world space *) dvRange: TD3DValue; (* Cutoff range *) dvFalloff: TD3DValue; (* Falloff *) dvAttenuation0: TD3DValue; (* Constant attenuation *) dvAttenuation1: TD3DValue; (* Linear attenuation *) dvAttenuation2: TD3DValue; (* Quadratic attenuation *) dvTheta: TD3DValue; (* Inner angle of spotlight cone *) dvPhi: TD3DValue; (* Outer angle of spotlight cone *) end; (* * Structure defining a light source and its properties. *) (* flags bits *) const D3DLIGHT_ACTIVE = $00000001; D3DLIGHT_NO_SPECULAR = $00000002; (* maximum valid light range *) //... D3DLIGHT_RANGE_MAX = sqrt(FLT_MAX); type TD3DLight2 = packed record dwSize: DWORD; dltType: TD3DLightType; (* Type of light source *) dcvColor: TD3DColorValue; (* Color of light *) dvPosition: TD3DVector; (* Position in world space *) dvDirection: TD3DVector; (* Direction in world space *) dvRange: TD3DValue; (* Cutoff range *) dvFalloff: TD3DValue; (* Falloff *) dvAttenuation0: TD3DValue; (* Constant attenuation *) dvAttenuation1: TD3DValue; (* Linear attenuation *) dvAttenuation2: TD3DValue; (* Quadratic attenuation *) dvTheta: TD3DValue; (* Inner angle of spotlight cone *) dvPhi: TD3DValue; (* Outer angle of spotlight cone *) dwFlags: DWORD; end; TD3DLightData = packed record dwSize: DWORD; lpIn: ^TD3DLightingElement; (* Input positions and normals *) dwInSize: DWORD; (* Stride of input elements *) lpOut: ^TD3DTLVertex; (* Output colors *) dwOutSize: DWORD; (* Stride of output colors *) end; (* * Before DX5, these values were in an enum called * TD3DColorModel. This was not correct, since they are * bit flags. A driver can surface either or both flags * in the dcmColorModel member of D3DDEVICEDESC. *) TD3DColorModel = ( D3DCOLOR_INVALID_0, D3DCOLOR_MONO, D3DCOLOR_RGB ); (* * Options for clearing *) const D3DCLEAR_TARGET = $00000001; (* Clear target surface *) D3DCLEAR_ZBUFFER = $00000002; (* Clear target z buffer *) (* * Execute buffers are allocated via Direct3D. These buffers may then * be filled by the application with instructions to execute along with * vertex data. *) (* * Supported op codes for execute instructions. *) type TD3DOpcode = ( D3DOP_INVALID_0, D3DOP_POINT, D3DOP_LINE, D3DOP_TRIANGLE, D3DOP_MATRIXLOAD, D3DOP_MATRIXMULTIPLY, D3DOP_STATETRANSFORM, D3DOP_STATELIGHT, D3DOP_STATERENDER, D3DOP_PROCESSVERTICES, D3DOP_TEXTURELOAD, D3DOP_EXIT, D3DOP_BRANCHFORWARD, D3DOP_SPAN, D3DOP_SETSTATUS); TD3DInstruction = packed record bOpcode: BYTE; (* Instruction opcode *) bSize: BYTE; (* Size of each instruction data unit *) wCount: WORD; (* Count of instruction data units to follow *) end; (* * Structure for texture loads *) TD3DTextureLoad = packed record hDestTexture: TD3DTextureHandle; hSrcTexture: TD3DTextureHandle; end; (* * Structure for picking *) TD3DPickRecord = packed record bOpcode: BYTE; bPad: BYTE; dwOffset: DWORD; dvZ: TD3DValue; end; (* * The following defines the rendering states which can be set in the * execute buffer. *) TD3DShadeMode = ( D3DSHADE_INVALID_0, D3DSHADE_FLAT, D3DSHADE_GOURAUD, D3DSHADE_PHONG); TD3DFillMode = ( D3DFILL_INVALID_0, D3DFILL_POINT, D3DFILL_WIREFRAME, D3DFILL_SOLID); TD3DLinePattern = packed record wRepeatFactor: WORD; wLinePattern: WORD; end; TD3DTextureFilter = ( D3DFILTER_INVALID_0, D3DFILTER_NEAREST, D3DFILTER_LINEAR, D3DFILTER_MIPNEAREST, D3DFILTER_MIPLINEAR, D3DFILTER_LINEARMIPNEAREST, D3DFILTER_LINEARMIPLINEAR); TD3DBlend = ( D3DBLEND_INVALID_0, D3DBLEND_ZERO, D3DBLEND_ONE, D3DBLEND_SRCCOLOR, D3DBLEND_INVSRCCOLOR, D3DBLEND_SRCALPHA, D3DBLEND_INVSRCALPHA, D3DBLEND_DESTALPHA, D3DBLEND_INVDESTALPHA, D3DBLEND_DESTCOLOR, D3DBLEND_INVDESTCOLOR, D3DBLEND_SRCALPHASAT, D3DBLEND_BOTHSRCALPHA, D3DBLEND_BOTHINVSRCALPHA); TD3DTextureBlend = ( D3DTBLEND_INVALID_0, D3DTBLEND_DECAL, D3DTBLEND_MODULATE, D3DTBLEND_DECALALPHA, D3DTBLEND_MODULATEALPHA, D3DTBLEND_DECALMASK, D3DTBLEND_MODULATEMASK, D3DTBLEND_COPY, D3DTBLEND_ADD); TD3DTextureAddress = ( D3DTADDRESS_INVALID_0, D3DTADDRESS_WRAP, D3DTADDRESS_MIRROR, D3DTADDRESS_CLAMP, D3DTADDRESS_BORDER); TD3DCull = ( D3DCULL_INVALID_0, D3DCULL_NONE, D3DCULL_CW, D3DCULL_CCW); TD3DCmpFunc = ( D3DCMP_INVALID_0, D3DCMP_NEVER, D3DCMP_LESS, D3DCMP_EQUAL, D3DCMP_LESSEQUAL, D3DCMP_GREATER, D3DCMP_NOTEQUAL, D3DCMP_GREATEREQUAL, D3DCMP_ALWAYS); TD3DFogMode = ( D3DFOG_NONE, D3DFOG_EXP, D3DFOG_EXP2, D3DFOG_LINEAR); TD3DAntialiasMode = ( D3DANTIALIAS_NONE, D3DANTIALIAS_SORTDEPENDENT, D3DANTIALIAS_SORTINDEPENDENT); // Vertex types supported by Direct3D TD3DVertexType = ( D3DVT_INVALID_0, D3DVT_VERTEX, D3DVT_LVERTEX, D3DVT_TLVERTEX); // Primitives supported by draw-primitive API TD3DPrimitiveType = ( D3DPT_INVALID_0, D3DPT_POINTLIST, D3DPT_LINELIST, D3DPT_LINESTRIP, D3DPT_TRIANGLELIST, D3DPT_TRIANGLESTRIP, D3DPT_TRIANGLEFAN); (* * Amount to add to a state to generate the override for that state. *) const D3DSTATE_OVERRIDE_BIAS = 256; (* * A state which sets the override flag for the specified state type. *) // #define D3DSTATE_OVERRIDE(type) ((DWORD) (type) + D3DSTATE_OVERRIDE_BIAS) function D3DSTATE_OVERRIDE(StateType: DWORD) : DWORD; type TD3DTransformStateType = ( D3DTRANSFORMSTATE_INVALID_0, D3DTRANSFORMSTATE_WORLD, D3DTRANSFORMSTATE_VIEW, D3DTRANSFORMSTATE_PROJECTION); TD3DLightStateType = ( D3DLIGHTSTATE_INVALID_0, D3DLIGHTSTATE_MATERIAL, D3DLIGHTSTATE_AMBIENT, D3DLIGHTSTATE_COLORMODEL, D3DLIGHTSTATE_FOGMODE, D3DLIGHTSTATE_FOGSTART, D3DLIGHTSTATE_FOGEND, D3DLIGHTSTATE_FOGDENSITY); TD3DRenderStateType = ( D3DRENDERSTATE_INVALID_0, D3DRENDERSTATE_TEXTUREHANDLE, (* Texture handle *) D3DRENDERSTATE_ANTIALIAS, (* Antialiasing prim edges *) D3DRENDERSTATE_TEXTUREADDRESS, (* D3DTextureAddress *) D3DRENDERSTATE_TEXTUREPERSPECTIVE, (* TRUE for perspective correction *) D3DRENDERSTATE_WRAPU, (* TRUE for wrapping in u *) D3DRENDERSTATE_WRAPV, (* TRUE for wrapping in v *) D3DRENDERSTATE_ZENABLE, (* TRUE to enable z test *) D3DRENDERSTATE_FILLMODE, (* D3DFILL_MODE *) D3DRENDERSTATE_SHADEMODE, (* TD3DShadeMode *) D3DRENDERSTATE_LINEPATTERN, (* TD3DLinePattern *) D3DRENDERSTATE_MONOENABLE, (* TRUE to enable mono rasterization *) D3DRENDERSTATE_ROP2, (* ROP2 *) D3DRENDERSTATE_PLANEMASK, (* DWORD physical plane mask *) D3DRENDERSTATE_ZWRITEENABLE, (* TRUE to enable z writes *) D3DRENDERSTATE_ALPHATESTENABLE, (* TRUE to enable alpha tests *) D3DRENDERSTATE_LASTPIXEL, (* TRUE for last-pixel on lines *) D3DRENDERSTATE_TEXTUREMAG, (* TD3DTextureFilter *) D3DRENDERSTATE_TEXTUREMIN, (* TD3DTextureFilter *) D3DRENDERSTATE_SRCBLEND, (* TD3DBlend *) D3DRENDERSTATE_DESTBLEND, (* TD3DBlend *) D3DRENDERSTATE_TEXTUREMAPBLEND, (* TD3DTextureBlend *) D3DRENDERSTATE_CULLMODE, (* TD3DCull *) D3DRENDERSTATE_ZFUNC, (* TD3DCmpFunc *) D3DRENDERSTATE_ALPHAREF, (* TD3DFixed *) D3DRENDERSTATE_ALPHAFUNC, (* TD3DCmpFunc *) D3DRENDERSTATE_DITHERENABLE, (* TRUE to enable dithering *) D3DRENDERSTATE_BLENDENABLE, (* TRUE to enable alpha blending *) D3DRENDERSTATE_FOGENABLE, (* TRUE to enable fog *) D3DRENDERSTATE_SPECULARENABLE, (* TRUE to enable specular *) D3DRENDERSTATE_ZVISIBLE, (* TRUE to enable z checking *) D3DRENDERSTATE_SUBPIXEL, (* TRUE to enable subpixel correction *) D3DRENDERSTATE_SUBPIXELX, (* TRUE to enable correction in X only *) D3DRENDERSTATE_STIPPLEDALPHA, (* TRUE to enable stippled alpha *) D3DRENDERSTATE_FOGCOLOR, (* TD3DColor *) D3DRENDERSTATE_FOGTABLEMODE, (* TD3DFogMode *) D3DRENDERSTATE_FOGTABLESTART, (* Fog table start *) D3DRENDERSTATE_FOGTABLEEND, (* Fog table end *) D3DRENDERSTATE_FOGTABLEDENSITY, (* Fog table density *) D3DRENDERSTATE_STIPPLEENABLE, (* TRUE to enable stippling *) D3DRENDERSTATE_EDGEANTIALIAS, (* TRUE to enable edge antialiasing *) D3DRENDERSTATE_COLORKEYENABLE, (* TRUE to enable source colorkeyed textures *) D3DRENDERSTATE_BORDERCOLOR, (* Border color for texturing w/border *) D3DRENDERSTATE_TEXTUREADDRESSU, (* Texture addressing mode for U coordinate *) D3DRENDERSTATE_TEXTUREADDRESSV, (* Texture addressing mode for V coordinate *) D3DRENDERSTATE_MIPMAPLODBIAS, (* TD3DValue Mipmap LOD bias *) D3DRENDERSTATE_ZBIAS, (* LONG Z bias *) D3DRENDERSTATE_RANGEFOGENABLE, (* Enables range-based fog *) D3DRENDERSTATE_ANISOTROPY, (* Max. anisotropy. 1 = no anisotropy *) D3DRENDERSTATE_FLUSHBATCH, (* Explicit flush for DP batching (DX5 Only) *) D3DRENDERSTATE_INVALID_51, D3DRENDERSTATE_INVALID_52, D3DRENDERSTATE_INVALID_53, D3DRENDERSTATE_INVALID_54, D3DRENDERSTATE_INVALID_55, D3DRENDERSTATE_INVALID_56, D3DRENDERSTATE_INVALID_57, D3DRENDERSTATE_INVALID_58, D3DRENDERSTATE_INVALID_59, D3DRENDERSTATE_INVALID_60, D3DRENDERSTATE_INVALID_61, D3DRENDERSTATE_INVALID_62, D3DRENDERSTATE_INVALID_63, D3DRENDERSTATE_STIPPLEPATTERN00, (* Stipple pattern 01... *) D3DRENDERSTATE_STIPPLEPATTERN01, D3DRENDERSTATE_STIPPLEPATTERN02, D3DRENDERSTATE_STIPPLEPATTERN03, D3DRENDERSTATE_STIPPLEPATTERN04, D3DRENDERSTATE_STIPPLEPATTERN05, D3DRENDERSTATE_STIPPLEPATTERN06, D3DRENDERSTATE_STIPPLEPATTERN07, D3DRENDERSTATE_STIPPLEPATTERN08, D3DRENDERSTATE_STIPPLEPATTERN09, D3DRENDERSTATE_STIPPLEPATTERN10, D3DRENDERSTATE_STIPPLEPATTERN11, D3DRENDERSTATE_STIPPLEPATTERN12, D3DRENDERSTATE_STIPPLEPATTERN13, D3DRENDERSTATE_STIPPLEPATTERN14, D3DRENDERSTATE_STIPPLEPATTERN15, D3DRENDERSTATE_STIPPLEPATTERN16, D3DRENDERSTATE_STIPPLEPATTERN17, D3DRENDERSTATE_STIPPLEPATTERN18, D3DRENDERSTATE_STIPPLEPATTERN19, D3DRENDERSTATE_STIPPLEPATTERN20, D3DRENDERSTATE_STIPPLEPATTERN21, D3DRENDERSTATE_STIPPLEPATTERN22, D3DRENDERSTATE_STIPPLEPATTERN23, D3DRENDERSTATE_STIPPLEPATTERN24, D3DRENDERSTATE_STIPPLEPATTERN25, D3DRENDERSTATE_STIPPLEPATTERN26, D3DRENDERSTATE_STIPPLEPATTERN27, D3DRENDERSTATE_STIPPLEPATTERN28, D3DRENDERSTATE_STIPPLEPATTERN29, D3DRENDERSTATE_STIPPLEPATTERN30, D3DRENDERSTATE_STIPPLEPATTERN31); // #define D3DRENDERSTATE_STIPPLEPATTERN(y) (D3DRENDERSTATE_STIPPLEPATTERN00 + (y)) TD3DState = packed record case Integer of 0: ( dtstTransformStateType: TD3DTransformStateType; dwArg: Array [ 0..0 ] of DWORD; ); 1: ( dlstLightStateType: TD3DLightStateType; dvArg: Array [ 0..0 ] of TD3DValue; ); 2: ( drstRenderStateType: TD3DRenderStateType; ); end; (* * Operation used to load matrices * hDstMat = hSrcMat *) TD3DMatrixLoad = packed record hDestMatrix: TD3DMatrixHandle; (* Destination matrix *) hSrcMatrix: TD3DMatrixHandle; (* Source matrix *) end; (* * Operation used to multiply matrices * hDstMat = hSrcMat1 * hSrcMat2 *) TD3DMatrixMultiply = packed record hDestMatrix: TD3DMatrixHandle; (* Destination matrix *) hSrcMatrix1: TD3DMatrixHandle; (* First source matrix *) hSrcMatrix2: TD3DMatrixHandle; (* Second source matrix *) end; (* * Operation used to transform and light vertices. *) TD3DProcessVertices = packed record dwFlags: DWORD; (* Do we transform or light or just copy? *) wStart: WORD; (* Index to first vertex in source *) wDest: WORD; (* Index to first vertex in local buffer *) dwCount: DWORD; (* Number of vertices to be processed *) dwReserved: DWORD; (* Must be zero *) end; const D3DPROCESSVERTICES_TRANSFORMLIGHT = $00000000; D3DPROCESSVERTICES_TRANSFORM = $00000001; D3DPROCESSVERTICES_COPY = $00000002; D3DPROCESSVERTICES_OPMASK = $00000007; D3DPROCESSVERTICES_UPDATEEXTENTS = $00000008; D3DPROCESSVERTICES_NOCOLOR = $00000010; (* * Triangle flags *) (* * Tri strip and fan flags. * START loads all three vertices * EVEN and ODD load just v3 with even or odd culling * START_FLAT contains a count from 0 to 29 that allows the * whole strip or fan to be culled in one hit. * e.g. for a quad len = 1 *) D3DTRIFLAG_START = $00000000; // #define D3DTRIFLAG_STARTFLAT(len) (len) (* 0 < len < 30 *) function D3DTRIFLAG_STARTFLAT(len: DWORD) : DWORD; const D3DTRIFLAG_ODD = $0000001e; D3DTRIFLAG_EVEN = $0000001f; (* * Triangle edge flags * enable edges for wireframe or antialiasing *) D3DTRIFLAG_EDGEENABLE1 = $00000100; (* v0-v1 edge *) D3DTRIFLAG_EDGEENABLE2 = $00000200; (* v1-v2 edge *) D3DTRIFLAG_EDGEENABLE3 = $00000400; (* v2-v0 edge *) D3DTRIFLAG_EDGEENABLETRIANGLE = ( D3DTRIFLAG_EDGEENABLE1 or D3DTRIFLAG_EDGEENABLE2 or D3DTRIFLAG_EDGEENABLE3); (* * Primitive structures and related defines. Vertex offsets are to types * TD3DVertex, TD3DLVertex, or TD3DTLVertex. *) (* * Triangle list primitive structure *) type TD3DTriangle = packed record case Integer of 0: ( v1: WORD; (* Vertex indices *) v2: WORD; v3: WORD; wFlags: WORD; (* Edge (and other) flags *) ); 1: ( wV1: WORD; wV2: WORD; wV3: WORD; ); end; (* * Line strip structure. * The instruction count - 1 defines the number of line segments. *) TD3DLine = packed record case Integer of 0: ( v1: WORD; (* Vertex indices *) v2: WORD; ); 1: ( wV1: WORD; wV2: WORD; ); end; (* * Span structure * Spans join a list of points with the same y value. * If the y value changes, a new span is started. *) TD3DSpan = packed record wCount: WORD; (* Number of spans *) wFirst: WORD; (* Index to first vertex *) end; (* * Point structure *) TD3DPoint = packed record wCount: WORD; (* number of points *) wFirst: WORD; (* index to first vertex *) end; (* * Forward branch structure. * Mask is logically anded with the driver status mask * if the result equals 'value', the branch is taken. *) TD3DBranch = packed record dwMask: DWORD; (* Bitmask against D3D status *) dwValue: DWORD; bNegate: BOOL; (* TRUE to negate comparison *) dwOffset: DWORD; (* How far to branch forward (0 for exit)*) end; (* * Status used for set status instruction. * The D3D status is initialised on device creation * and is modified by all execute calls. *) TD3DStatus = packed record dwFlags: DWORD; (* Do we set extents or status *) dwStatus: DWORD; (* D3D status *) drExtent: TD3DRect; end; const D3DSETSTATUS_STATUS = $00000001; D3DSETSTATUS_EXTENTS = $00000002; D3DSETSTATUS_ALL = (D3DSETSTATUS_STATUS or D3DSETSTATUS_EXTENTS); type TD3DClipStatus = packed record dwFlags : DWORD; (* Do we set 2d extents, 3D extents or status *) dwStatus : DWORD; (* Clip status *) minx, maxx : single; (* X extents *) miny, maxy : single; (* Y extents *) minz, maxz : single; (* Z extents *) end; const D3DCLIPSTATUS_STATUS = $00000001; D3DCLIPSTATUS_EXTENTS2 = $00000002; D3DCLIPSTATUS_EXTENTS3 = $00000004; (* * Statistics structure *) type D3DStats = packed record dwSize: DWORD; dwTrianglesDrawn: DWORD; dwLinesDrawn: DWORD; dwPointsDrawn: DWORD; dwSpansDrawn: DWORD; dwVerticesProcessed: DWORD; end; (* * Execute options. * When calling using D3DEXECUTE_UNCLIPPED all the primitives * inside the buffer must be contained within the viewport. *) const D3DEXECUTE_CLIPPED = $00000001; D3DEXECUTE_UNCLIPPED = $00000002; type TD3DExecuteData = packed record dwSize: DWORD; dwVertexOffset: DWORD; dwVertexCount: DWORD; dwInstructionOffset: DWORD; dwInstructionLength: DWORD; dwHVertexOffset: DWORD; dsStatus: TD3DStatus; (* Status after execute *) end; (* * Palette flags. * This are or'ed with the peFlags in the PALETTEENTRYs passed to DirectDraw. *) const D3DPAL_FREE = $00; (* Renderer may use this entry freely *) D3DPAL_READONLY = $40; (* Renderer may not set this entry *) D3DPAL_RESERVED = $80; (* Renderer may not use this entry *) implementation function D3DVAL(val: variant) : float; begin Result := val; end; function D3DDivide(a,b: variant) : variant; begin Result := a / b; end; function D3DMultiply(a,b: variant) : variant; begin Result := a * b; end; // #define CI_GETALPHA(ci) ((ci) >> 24) function CI_GETALPHA(ci: DWORD) : DWORD; begin Result := ci shr 24; end; // #define CI_GETINDEX(ci) (((ci) >> 8) & 0xffff) function CI_GETINDEX(ci: DWORD) : DWORD; begin Result := (ci shr 8) and $ffff; end; // #define CI_GETFRACTION(ci) ((ci) & 0xff) function CI_GETFRACTION(ci: DWORD) : DWORD; begin Result := ci and $ff; end; // #define CI_ROUNDINDEX(ci) CI_GETINDEX((ci) + 0x80) function CI_ROUNDINDEX(ci: DWORD) : DWORD; begin Result := CI_GETINDEX(ci + $80); end; // #define CI_MASKALPHA(ci) ((ci) & 0xffffff) function CI_MASKALPHA(ci: DWORD) : DWORD; begin Result := ci and $ffffff; end; // #define CI_MAKE(a, i, f) (((a) << 24) | ((i) << 8) | (f)) function CI_MAKE(a,i,f: DWORD) : DWORD; begin Result := (a shl 24) or (i shl 8) or f; end; // #define RGBA_GETALPHA(rgb) ((rgb) >> 24) function RGBA_GETALPHA(rgb: TD3DColor) : DWORD; begin Result := rgb shr 24; end; // #define RGBA_GETRED(rgb) (((rgb) >> 16) & 0xff) function RGBA_GETRED(rgb: TD3DColor) : DWORD; begin Result := (rgb shr 16) and $ff; end; // #define RGBA_GETGREEN(rgb) (((rgb) >> 8) & 0xff) function RGBA_GETGREEN(rgb: TD3DColor) : DWORD; begin Result := (rgb shr 8) and $ff; end; // #define RGBA_GETBLUE(rgb) ((rgb) & 0xff) function RGBA_GETBLUE(rgb: TD3DColor) : DWORD; begin Result := rgb and $ff; end; // #define RGBA_MAKE(r, g, b, a) ((TD3DColor) (((a) << 24) | ((r) << 16) | ((g) << 8) | (b))) function RGBA_MAKE(r, g, b, a: DWORD) : TD3DColor; begin Result := (a shl 24) or (r shl 16) or (g shl 8) or b; end; // #define D3DRGB(r, g, b) \ // (0xff000000L | (((long)((r) * 255)) << 16) | (((long)((g) * 255)) << 8) | (long)((b) * 255)) function D3DRGB(r, g, b: float) : TD3DColor; begin Result := $ff000000 or (round(r * 255) shl 16) or (round(g * 255) shl 8) or round(b * 255); end; // #define D3DRGBA(r, g, b, a) \ // ( (((long)((a) * 255)) << 24) | (((long)((r) * 255)) << 16) \ // | (((long)((g) * 255)) << 8) | (long)((b) * 255) \ // ) function D3DRGBA(r, g, b, a: float) : TD3DColor; begin Result := (round(a * 255) shl 24) or (round(r * 255) shl 16) or (round(g * 255) shl 8) or round(b * 255); end; // #define RGB_GETRED(rgb) (((rgb) >> 16) & 0xff) function RGB_GETRED(rgb: TD3DColor) : DWORD; begin Result := (rgb shr 16) and $ff; end; // #define RGB_GETGREEN(rgb) (((rgb) >> 8) & 0xff) function RGB_GETGREEN(rgb: TD3DColor) : DWORD; begin Result := (rgb shr 8) and $ff; end; // #define RGB_GETBLUE(rgb) ((rgb) & 0xff) function RGB_GETBLUE(rgb: TD3DColor) : DWORD; begin Result := rgb and $ff; end; // #define RGBA_SETALPHA(rgba, x) (((x) << 24) | ((rgba) & 0x00ffffff)) function RGBA_SETALPHA(rgba: TD3DColor; x: DWORD) : TD3DColor; begin Result := (x shl 24) or (rgba and $00ffffff); end; // #define RGB_MAKE(r, g, b) ((TD3DColor) (((r) << 16) | ((g) << 8) | (b))) function RGB_MAKE(r, g, b: DWORD) : TD3DColor; begin Result := (r shl 16) or (g shl 8) or b; end; // #define RGBA_TORGB(rgba) ((TD3DColor) ((rgba) & 0xffffff)) function RGBA_TORGB(rgba: TD3DColor) : TD3DColor; begin Result := rgba and $00ffffff; end; // #define RGB_TORGBA(rgb) ((TD3DColor) ((rgb) | 0xff000000)) function RGB_TORGBA(rgb: TD3DColor) : TD3DColor; begin Result := rgb or $ff000000; end; function D3DSTATE_OVERRIDE(StateType: DWORD) : DWORD; begin Result := StateType + D3DSTATE_OVERRIDE_BIAS; end; function D3DTRIFLAG_STARTFLAT(len: DWORD) : DWORD; begin if not (len in [1..29]) then len := 0; result := len; end; // Addition and subtraction function VectorAdd(const v1, v2: TD3DVector) : TD3DVector; begin result.x := v1.x+v2.x; result.y := v1.y+v2.y; result.z := v1.z+v2.z; end; function VectorSub(const v1, v2: TD3DVector) : TD3DVector; begin result.x := v1.x-v2.x; result.y := v1.y-v2.y; result.z := v1.z-v2.z; end; // Scalar multiplication and division function VectorMulS(const v: TD3DVector; s: TD3DValue) : TD3DVector; begin result.x := v.x*s; result.y := v.y*s; result.z := v.z*s; end; function VectorDivS(const v: TD3DVector; s: TD3DValue) : TD3DVector; begin result.x := v.x/s; result.y := v.y/s; result.z := v.z/s; end; // Memberwise multiplication and division function VectorMul(const v1, v2: TD3DVector) : TD3DVector; begin result.x := v1.x*v2.x; result.y := v1.y*v2.y; result.z := v1.z*v2.z; end; function VectorDiv(const v1, v2: TD3DVector) : TD3DVector; begin result.x := v1.x/v2.x; result.y := v1.y/v2.y; result.z := v1.z/v2.z; end; // Vector dominance function VectorSmaller(v1, v2: TD3DVector) : boolean; begin result := (v1.x < v2.x) and (v1.y < v2.y) and (v1.z < v2.z); end; function VectorSmallerEquel(v1, v2: TD3DVector) : boolean; begin result := (v1.x <= v2.x) and (v1.y <= v2.y) and (v1.z <= v2.z); end; // Bitwise equality function VectorEquel(v1, v2: TD3DVector) : boolean; begin result := (v1.x = v2.x) and (v1.y = v2.y) and (v1.z = v2.z); end; // Length-related functions function VectorSquareMagnitude(v: TD3DVector) : TD3DValue; begin result := (v.x*v.x) + (v.y*v.y) + (v.z*v.z); end; function VectorMagnitude(v: TD3DVector) : TD3DValue; begin result := sqrt((v.x*v.x) + (v.y*v.y) + (v.z*v.z)); end; // Returns vector with same direction and unit length function VectorNormalize(const v: TD3DVector) : TD3DVector; begin result := VectorDivS(v,VectorMagnitude(v)); end; // Return min/max component of the input vector function VectorMin(v: TD3DVector) : TD3DValue; var ret : TD3DValue; begin ret := v.x; if (v.y < ret) then ret := v.y; if (v.z < ret) then ret := v.z; result := ret; end; function VectorMax(v: TD3DVector) : TD3DValue; var ret : TD3DValue; begin ret := v.x; if (ret < v.y) then ret := v.y; if (ret < v.z) then ret := v.z; result := ret; end; // Return memberwise min/max of input vectors function VectorMinimize(const v1, v2: TD3DVector) : TD3DVector; begin if v1.x < v2.x then result.x := v1.x else result.x := v2.x; if v1.y < v2.y then result.y := v1.y else result.y := v2.y; if v1.z < v2.z then result.z := v1.z else result.z := v2.z; end; function VectorMaximize(const v1, v2: TD3DVector) : TD3DVector; begin if v1.x > v2.x then result.x := v1.x else result.x := v2.x; if v1.y > v2.y then result.y := v1.y else result.y := v2.y; if v1.z > v2.z then result.z := v1.z else result.z := v2.z; end; // Dot and cross product function VectorDotProduct(v1, v2: TD3DVector) : TD3DValue; begin result := (v1.x*v2.x) + (v1.y * v2.y) + (v1.z*v2.z); end; function VectorCrossProduct(const v1, v2: TD3DVector) : TD3DVector; begin result.x := (v1.y*v2.z) - (v1.z*v2.y); result.y := (v1.z*v2.x) - (v1.x*v2.z); result.z := (v1.x*v2.y) - (v1.y*v2.x); end; end.
unit uniteLecteurFichierBinaire; interface uses uniteLecteurFichier, sysUtils; type LecteurFichierBinaire = class (LecteurFichier) public //Accesseur du type MIME du fichier déduit de l'extension du fichier. //@return type MIME du fichier. function getType : String; override; //Accesseur du contenu du fichier au format de chaîne de caractère long (le format, pas le caractère). Retourne image/jpeg pour les .jpg/.jpeg, image/gif pour les .gif, et application/octet-stream pour tout autre type. //@return le contenu du fichier lu sous sa forme brute (octets) et retourné transposé en chaîne de caractères. //@raises exception exception levée si il y a une erreur lors de la lecture du fichier (ouverture du fichier inclut) function lireContenu : Widestring; override; end; implementation function LecteurFichierBinaire.getType : String; begin if (AnsiUpperCase(extractFileExt(chemin)) = '.JPG') or (AnsiUpperCase(extractFileExt(chemin)) = '.JPEG') then result:= 'image/jpeg' else if (AnsiUpperCase(extractFileExt(chemin)) = '.GIF') then result:= 'image/gif' else inherited getType; end; function LecteurFichierBinaire.lireContenu : Widestring; var tableauCar : Array of Char; fichier : File; i : Integer; begin assignFile(fichier, chemin); setLength(tableauCar, getTaille); try reset(fichier); blockRead(fichier, tableauCar, 1); close(fichier); except on e : Exception do raise Exception.create('Problème lors de la lecture du fichier'); end; result:=''; for i:=0 to high(tableauCar) do result:=result+tableauCar[i]; end; end.
unit uRawExif; interface uses Classes, Windows, Math, SysUtils, FreeImage, FreeBitmap, GraphicCrypt, Dmitry.Utils.System, uFreeImageIO, uMemory, uExifUtils, uFIRational, uTranslate, uSessionPasswords; type TRAWExifRecord = class(TObject) private FDescription: string; FKey: string; FValue: string; public property Key: string read FKey write FKey; property Value: string read FValue write FValue; property Description: string read FDescription write FDescription; end; TRAWExif = class(TObject) private FExifList: TList; function GetCount: Integer; function GetValueByIndex(Index: Integer): TRAWExifRecord; function GetTimeStamp: TDateTime; procedure LoadFromFreeImage(Image: TFreeWinBitmap); public constructor Create; destructor Destroy; override; procedure LoadFromFile(FileName: string); procedure LoadFromStream(Stream: TStream); function Add(Description, Key, Value: string): TRAWExifRecord; function IsEXIF: Boolean; property TimeStamp: TDateTime read GetTimeStamp; property Count: Integer read GetCount; property Items[Index: Integer]: TRAWExifRecord read GetValueByIndex; default; end; implementation function L(S: string): string; begin Result := TTranslateManager.Instance.TA(S, 'EXIF'); end; (** Convert a tag to a C string *) function ConvertAnyTag(tag: PFITAG): string; const MAX_TEXT_EXTENT = 512; var Buffer: AnsiString; tag_type: FREE_IMAGE_MDTYPE; //tag_count: Cardinal; max_size: Integer; TagValue: Pointer; begin if (tag = nil) then Exit(''); buffer := ''; // convert the tag value to a string buffer tag_type := FreeImage_GetTagType(tag); //tag_count := FreeImage_GetTagCount(tag); case (tag_type) of FIDT_BYTE: // N x 8-bit unsigned integer begin {BYTE *pvalue := (BYTE*)FreeImage_GetTagValue(tag); sprintf(format, '%ld', (LONG) pvalue[0]); buffer + := format; for(i := 1; i < tag_count; i++) begin sprintf(format, ' %ld', (LONG) pvalue[i]); buffer + := format; end; break; } end; FIDT_SHORT: // N x 16-bit unsigned integer begin {unsigned SmallInt *pvalue := (unsigned SmallInt *)FreeImage_GetTagValue(tag); sprintf(format, '%hu', pvalue[0]); buffer + := format; for(i := 1; i < tag_count; i++) begin sprintf(format, ' %hu', pvalue[i]); buffer + := format; end; break; } end; FIDT_LONG: // N x 32-bit unsigned integer begin {DWORD *pvalue := (DWORD *)FreeImage_GetTagValue(tag); sprintf(format, '%lu', pvalue[0]); buffer + := format; for(i := 1; i < tag_count; i++) begin sprintf(format, ' %lu', pvalue[i]); buffer + := format; end; break; } end; FIDT_RATIONAL: // N x 64-bit unsigned fraction begin {DWORD *pvalue := (DWORD*)FreeImage_GetTagValue(tag); sprintf(format, '%ld/%ld', pvalue[0], pvalue[1]); buffer + := format; for(i := 1; i < tag_count; i++) begin sprintf(format, ' %ld/%ld', pvalue[2*i], pvalue[2*i+1]); buffer + := format; end; break; } end; FIDT_SBYTE: // N x 8-bit signed integer begin {char *pvalue := (char*)FreeImage_GetTagValue(tag); sprintf(format, '%ld', (LONG) pvalue[0]); buffer + := format; for(i := 1; i < tag_count; i++) begin sprintf(format, ' %ld', (LONG) pvalue[i]); buffer + := format; end; break;} end; FIDT_SSHORT: // N x 16-bit signed integer begin {SmallInt *pvalue := (SmallInt *)FreeImage_GetTagValue(tag); sprintf(format, '%hd', pvalue[0]); buffer + := format; for(i := 1; i < tag_count; i++) begin sprintf(format, ' %hd', pvalue[i]); buffer + := format; end; break;} end; FIDT_SLONG: // N x 32-bit signed integer begin {LONG *pvalue := (LONG *)FreeImage_GetTagValue(tag); sprintf(format, '%ld', pvalue[0]); buffer + := format; for(i := 1; i < tag_count; i++) begin sprintf(format, ' %ld', pvalue[i]); buffer + := format; end; break; } end; FIDT_SRATIONAL:// N x 64-bit signed fraction begin {LONG *pvalue := (LONG*)FreeImage_GetTagValue(tag); sprintf(format, '%ld/%ld', pvalue[0], pvalue[1]); buffer + := format; for(i := 1; i < tag_count; i++) begin sprintf(format, ' %ld/%ld', pvalue[2*i], pvalue[2*i+1]); buffer + := format; end; break; } end; FIDT_FLOAT: // N x 32-bit IEEE floating point begin {Single *pvalue := (Single *)FreeImage_GetTagValue(tag); sprintf(format, '%f', (Double) pvalue[0]); buffer + := format; for(i := 1; i < tag_count; i++) begin sprintf(format, '%f', (Double) pvalue[i]); buffer + := format; end; break; } end; FIDT_DOUBLE: // N x 64-bit IEEE floating point begin {Double *pvalue := (Double *)FreeImage_GetTagValue(tag); sprintf(format, '%f', pvalue[0]); buffer + := format; for(i := 1; i < tag_count; i++) begin sprintf(format, '%f', pvalue[i]); buffer + := format; end; break; } end; FIDT_IFD: // N x 32-bit unsigned integer (offset) begin {DWORD *pvalue := (DWORD *)FreeImage_GetTagValue(tag); sprintf(format, '%X', pvalue[0]); buffer + := format; for(i := 1; i < tag_count; i++) begin sprintf(format, ' %X', pvalue[i]); buffer + := format; end; break; } end; FIDT_PALETTE: // N x 32-bit RGBQUAD begin {RGBQUAD *pvalue := (RGBQUAD *)FreeImage_GetTagValue(tag); sprintf(format, '(%d,%d,%d,%d)', pvalue[0].rgbRed, pvalue[0].rgbGreen, pvalue[0].rgbBlue, pvalue[0].rgbReserved); buffer + := format; for(i := 1; i < tag_count; i++) begin sprintf(format, ' (%d,%d,%d,%d)', pvalue[i].rgbRed, pvalue[i].rgbGreen, pvalue[i].rgbBlue, pvalue[i].rgbReserved); buffer + := format; end; break;} end; FIDT_LONG8: // N x 64-bit unsigned integer begin {UINT64 *pvalue := (UINT64 *)FreeImage_GetTagValue(tag); sprintf(format, '%ld', pvalue[0]); buffer + := format; for(i := 1; i < tag_count; i++) begin sprintf(format, '%ld', pvalue[i]); buffer + := format; end; break; } end; FIDT_IFD8: // N x 64-bit unsigned integer (offset) begin {UINT64 *pvalue := (UINT64 *)FreeImage_GetTagValue(tag); sprintf(format, '%X', pvalue[0]); buffer + := format; for(i := 1; i < tag_count; i++) begin sprintf(format, '%X', pvalue[i]); buffer + := format; end; break; } end; FIDT_SLONG8: // N x 64-bit signed integer begin {INT64 *pvalue := (INT64 *)FreeImage_GetTagValue(tag); sprintf(format, '%ld', pvalue[0]); buffer + := format; for(i := 1; i < tag_count; i++) begin sprintf(format, '%ld', pvalue[i]); buffer + := format; end; break; } end; //FIDT_ASCII, // 8-bit bytes w/ last byte null //FIDT_UNDEFINED:// 8-bit untyped data else begin max_size := Min(FreeImage_GetTagLength(tag), MAX_TEXT_EXTENT); if max_size > 0 then begin SetLength(Buffer, max_size); TagValue := FreeImage_GetTagValue(tag); CopyMemory(PAnsiChar(Buffer), TagValue, max_size); if buffer[Length(buffer)] = #0 then SetLength(buffer, Length(buffer) - 1); end; end; end; Result := string(buffer); end; // //Convert a Exif tag to a string //*/ function ConvertExifTag(tag: PFITAG): string; const ComponentStrings: array[0..6] of string = ('', 'Y', 'Cb', 'Cr', 'R', 'G', 'B' ); var Orienation, ColorSpace, ResolutionUnit, dFocalLength, YCbCrPosition, flash, meteringMode, lightSource, sensingMethod, ExposureProgram, customRendered, exposureMode, whiteBalance, sceneType, gainControl, contrast, saturation, sharpness, distanceRange, isoEquiv, compression: DWORD; apexValue, apexPower: LONG; I, J: Integer; PByteValue: PByte; Buffer: string; R: TFIRational; userComment: PByte; apertureApex, rootTwo, fStop, fnumber, focalLength, distance: Double; begin Result := ''; if tag = nil then Exit; Buffer := ''; // convert the tag value to a string buffer case (FreeImage_GetTagID(tag)) of TAG_ORIENTATION: begin Orienation := PWORD(FreeImage_GetTagValue(tag))^; case Orienation of 1: Result := 'top, left side'; 2: Result := 'top, right side'; 3: Result := 'bottom, right side'; 4: Result := 'bottom, left side'; 5: Result := 'left side, top'; 6: Result := 'right side, top'; 7: Result := 'right side, bottom'; 8: Result := 'left side, bottom'; end; Result := L(Result); Exit; end; { TAG_REFERENCE_BLACK_WHITE: begin DWORD *pvalue := (DWORD*)FreeImage_GetTagValue(tag); if (FreeImage_GetTagLength(tag) = 48) then begin // reference black point value and reference white point value (ReferenceBlackWhite) Integer blackR := 0, whiteR := 0, blackG := 0, whiteG := 0, blackB := 0, whiteB := 0; if (pvalue[1]) then blackR := (Integer)(pvalue[0] / pvalue[1]); if (pvalue[3]) then whiteR := (Integer)(pvalue[2] / pvalue[3]); if (pvalue[5]) then blackG := (Integer)(pvalue[4] / pvalue[5]); if (pvalue[7]) then whiteG := (Integer)(pvalue[6] / pvalue[7]); if (pvalue[9]) then blackB := (Integer)(pvalue[8] / pvalue[9]); if (pvalue[11]) then whiteB := (Integer)(pvalue[10] / pvalue[11]); sprintf(format, '[%d,%d,%d] [%d,%d,%d]', blackR, blackG, blackB, whiteR, whiteG, whiteB); buffer + := format; (* C2PAS: Exit *) Result := buffer.c_str(); end; end;} TAG_COLOR_SPACE: begin ColorSpace := PWORD(FreeImage_GetTagValue(tag))^; if (colorSpace = 1) then begin Result := 'sRGB'; end else if (colorSpace = 65535) then begin Result := 'Undefined'; end else begin Result := 'Unknown'; end; Exit; end; TAG_COMPONENTS_CONFIGURATION: begin PByteValue := PByte(FreeImage_GetTagValue(tag)); for I := 0 to Min(4, FreeImage_GetTagCount(tag)) - 1 do begin j := PByteValue[I]; if (j > 0) and (j < 7) then Result := Result + componentStrings[j]; end; Exit; end; TAG_COMPRESSED_BITS_PER_PIXEL: begin R := TFIRational.Create(tag); try Result := R.ToString(); if (Result = '1') then Result := Result + ' ' + L('bit/pixel') else Result := Result + ' ' + L('bits/pixel'); Exit; finally F(R); end; end; TAG_X_RESOLUTION, TAG_Y_RESOLUTION, TAG_FOCAL_PLANE_X_RES, TAG_FOCAL_PLANE_Y_RES, TAG_BRIGHTNESS_VALUE, TAG_EXPOSURE_BIAS_VALUE: begin R := TFIRational.Create(tag); try Result := R.ToString(); finally F(R); end; Exit; end; TAG_RESOLUTION_UNIT, TAG_FOCAL_PLANE_UNIT: begin ResolutionUnit := PWORD(FreeImage_GetTagValue(tag))^; case (resolutionUnit) of 1: Result := L('(No unit)'); 2: Result := L('inches'); 3: Result := L('cm'); end; Exit; end; {TAG_YCBCR_POSITIONING: begin YCbCrPosition := PWORD(FreeImage_GetTagValue(tag))^; case (yCbCrPosition) of 1: Result := 'Center of pixel array'; 2: Result := 'Datum point'; end; end;} TAG_EXPOSURE_TIME: begin R := TFIRational.Create(tag); try Result := R.ToString() + ' ' + L('sec'); Exit; finally F(R); end; end; TAG_SHUTTER_SPEED_VALUE: begin R := TFIRational.Create(tag); try apexValue := r.longValue; apexPower := 1 shl apexValue; Result := FormatEx(L('1/{0} sec'), [Integer(apexPower)]); Exit; finally F(R); end; end; TAG_APERTURE_VALUE, TAG_MAX_APERTURE_VALUE: begin R := TFIRational.Create(tag); try apertureApex := r.doubleValue; rootTwo := sqrt(2); fStop := Power(rootTwo, apertureApex); Result := FormatEx(L('F{0:0.#}'), [fStop]); Exit; finally F(R); end; end; TAG_FNUMBER: begin R := TFIRational.Create(tag); try fnumber := r.doubleValue; Result := FormatEx(L('F{0:0.#}'), [fnumber]); Exit; finally F(R); end; end; TAG_FOCAL_LENGTH: begin R := TFIRational.Create(tag); try focalLength := r.doubleValue; Result := FormatEx(L('{0:0.#} mm'), [focalLength]); Exit; finally F(R); end; end; TAG_FOCAL_LENGTH_IN_35MM_FILM: begin dFocalLength := PWORD(FreeImage_GetTagValue(tag))^; Result := FormatEx(L('{0} mm'), [dFocalLength]); Exit; end; TAG_FLASH: begin flash := PWORD(FreeImage_GetTagValue(tag))^; case (flash) of $0000: (* C2PAS: Exit *) Result := 'Flash did not fire'; $0001: (* C2PAS: Exit *) Result := 'Flash fired'; $0005: (* C2PAS: Exit *) Result := 'Strobe return light not detected'; $0007: (* C2PAS: Exit *) Result := 'Strobe return light detected'; $0009: (* C2PAS: Exit *) Result := 'Flash fired, compulsory flash mode'; $000D: (* C2PAS: Exit *) Result := 'Flash fired, compulsory flash mode, return light not detected'; $000F: (* C2PAS: Exit *) Result := 'Flash fired, compulsory flash mode, return light detected'; $0010: (* C2PAS: Exit *) Result := 'Flash did not fire, compulsory flash mode'; $0018: (* C2PAS: Exit *) Result := 'Flash did not fire, auto mode'; $0019: (* C2PAS: Exit *) Result := 'Flash fired, auto mode'; $001D: (* C2PAS: Exit *) Result := 'Flash fired, auto mode, return light not detected'; $001F: (* C2PAS: Exit *) Result := 'Flash fired, auto mode, return light detected'; $0020: (* C2PAS: Exit *) Result := 'No flash function'; $0041: (* C2PAS: Exit *) Result := 'Flash fired, red-eye reduction mode'; $0045: (* C2PAS: Exit *) Result := 'Flash fired, red-eye reduction mode, return light not detected'; $0047: (* C2PAS: Exit *) Result := 'Flash fired, red-eye reduction mode, return light detected'; $0049: (* C2PAS: Exit *) Result := 'Flash fired, compulsory flash mode, red-eye reduction mode'; $004D: (* C2PAS: Exit *) Result := 'Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected'; $004F: (* C2PAS: Exit *) Result := 'Flash fired, compulsory flash mode, red-eye reduction mode, return light detected'; $0059: (* C2PAS: Exit *) Result := 'Flash fired, auto mode, red-eye reduction mode'; $005D: (* C2PAS: Exit *) Result := 'Flash fired, auto mode, return light not detected, red-eye reduction mode'; $005F: (* C2PAS: Exit *) Result := 'Flash fired, auto mode, return light detected, red-eye reduction mode'; else Result := FormatEx(L('Unknown ({0})'), [flash]); end; Result := L(Result); Exit; end; { TAG_SCENE_TYPE: begin BYTE sceneType := *((BYTE*)FreeImage_GetTagValue(tag)); if (sceneType = 1) then begin (* C2PAS: Exit *) Result := 'Directly photographed image'; end else begin sprintf(format, 'Unknown (%d)', sceneType); buffer + := format; (* C2PAS: Exit *) Result := buffer.c_str(); end; end; } TAG_SUBJECT_DISTANCE: begin R := TFIRational.Create(tag); try if (DWORD(r.Numerator) = $FFFFFFFF) then begin (* C2PAS: Exit *) Result := L('Infinity'); end else if(r.Numerator = 0) then begin (* C2PAS: Exit *) Result := L('Distance unknown'); end else begin distance := r.doubleValue; Result := FormatEx(L('{0:###} meters'), [distance]); end; finally F(R); end; Exit; end; TAG_METERING_MODE: begin meteringMode := PWORD(FreeImage_GetTagValue(tag))^; case (meteringMode) of 0: (* C2PAS: Exit *) Result := 'Unknown'; 1: (* C2PAS: Exit *) Result := 'Average'; 2: (* C2PAS: Exit *) Result := 'Center weighted average'; 3: (* C2PAS: Exit *) Result := 'Spot'; 4: (* C2PAS: Exit *) Result := 'Multi-spot'; 5: (* C2PAS: Exit *) Result := 'Multi-segment'; 6: (* C2PAS: Exit *) Result := 'Partial'; 255: (* C2PAS: Exit *) Result := '(Other)'; else (* C2PAS: Exit *) Result := ''; end; Result := L(Result); Exit; end; TAG_LIGHT_SOURCE: begin lightSource := PWORD(FreeImage_GetTagValue(tag))^; case (lightSource) of 0: (* C2PAS: Exit *) Result := 'Unknown'; 1: (* C2PAS: Exit *) Result := 'Daylight'; 2: (* C2PAS: Exit *) Result := 'Fluorescent'; 3: (* C2PAS: Exit *) Result := 'Tungsten (incandescent light)'; 4: (* C2PAS: Exit *) Result := 'Flash'; 9: (* C2PAS: Exit *) Result := 'Fine weather'; 10: (* C2PAS: Exit *) Result := 'Cloudy weather'; 11: (* C2PAS: Exit *) Result := 'Shade'; 12: (* C2PAS: Exit *) Result := 'Daylight fluorescent (D 5700 - 7100K)'; 13: (* C2PAS: Exit *) Result := 'Day white fluorescent (N 4600 - 5400K)'; 14: (* C2PAS: Exit *) Result := 'Cool white fluorescent (W 3900 - 4500K)'; 15: (* C2PAS: Exit *) Result := 'White fluorescent (WW 3200 - 3700K)'; 17: (* C2PAS: Exit *) Result := 'Standard light A'; 18: (* C2PAS: Exit *) Result := 'Standard light B'; 19: (* C2PAS: Exit *) Result := 'Standard light C'; 20: (* C2PAS: Exit *) Result := 'D55'; 21: (* C2PAS: Exit *) Result := 'D65'; 22: (* C2PAS: Exit *) Result := 'D75'; 23: (* C2PAS: Exit *) Result := 'D50'; 24: (* C2PAS: Exit *) Result := 'ISO studio tungsten'; 255: (* C2PAS: Exit *) Result := '(Other)'; else (* C2PAS: Exit *) Result := ''; end; Result := L(Result); Exit; end; { TAG_SENSING_METHOD: begin sensingMethod := PWORD(FreeImage_GetTagValue(tag))^; case (sensingMethod) of 1: (* C2PAS: Exit *) Result := '(Not defined)'; 2: (* C2PAS: Exit *) Result := 'One-chip color area sensor'; 3: (* C2PAS: Exit *) Result := 'Two-chip color area sensor'; 4: (* C2PAS: Exit *) Result := 'Three-chip color area sensor'; 5: (* C2PAS: Exit *) Result := 'Color sequential area sensor'; 7: (* C2PAS: Exit *) Result := 'Trilinear sensor'; 8: (* C2PAS: Exit *) Result := 'Color sequential linear sensor'; else (* C2PAS: Exit *) Result := ''; end; end; } { TAG_FILE_SOURCE: begin BYTE fileSource := *((BYTE*)FreeImage_GetTagValue(tag)); if (fileSource = 3) then begin (* C2PAS: Exit *) Result := 'Digital Still Camera (DSC)'; end else begin sprintf(format, 'Unknown (%d)', fileSource); buffer + := format; (* C2PAS: Exit *) Result := buffer.c_str(); end; end; break; } TAG_EXPOSURE_PROGRAM: begin ExposureProgram := PWORD(FreeImage_GetTagValue(tag))^; case (ExposureProgram) of 1: Result := 'Manual control'; 2: Result := 'Program normal'; 3: Result := 'Aperture priority'; 4: Result := 'Shutter priority'; 5: Result := 'Program creative (slow program)'; 6: Result := 'Program action (high-speed program)'; 7: Result := 'Portrait mode'; 8: Result := 'Landscape mode'; else Result := FormatEx(L('Unknown program ({0})'), [ExposureProgram]); end; Result := L(Result); Exit; end; (* TAG_CUSTOM_RENDERED: begin customRendered := PWORD(FreeImage_GetTagValue(tag))^; case (customRendered) of 0: Result := 'Normal process'; 1: Result := 'Custom process'; else Result := FormatEx('Unknown rendering ({0})', [customRendered]); end; end; *) TAG_EXPOSURE_MODE: begin exposureMode := PWORD(FreeImage_GetTagValue(tag))^; case (exposureMode) of 0: (* C2PAS: Exit *) Result := 'Auto exposure'; 1: (* C2PAS: Exit *) Result := 'Manual exposure'; 2: (* C2PAS: Exit *) Result := 'Auto bracket'; else Result := FormatEx('Unknown mode ({0})', [exposureMode]); end; Result := L(Result); Exit; end; TAG_WHITE_BALANCE: begin whiteBalance := PWORD(FreeImage_GetTagValue(tag))^; case (whiteBalance) of 0: (* C2PAS: Exit *) Result := 'Auto white balance'; 1: (* C2PAS: Exit *) Result := 'Manual white balance'; else Result := FormatEx('Unknown ({0})', [whiteBalance]); end; Result := L(Result); Exit; end; TAG_SCENE_CAPTURE_TYPE: begin sceneType := PWORD(FreeImage_GetTagValue(tag))^; case (sceneType) of 0: (* C2PAS: Exit *) Result := 'Standard'; 1: (* C2PAS: Exit *) Result := 'Landscape'; 2: (* C2PAS: Exit *) Result := 'Portrait'; 3: (* C2PAS: Exit *) Result := 'Night scene'; else Result := FormatEx('Unknown ({0})', [sceneType]); end; Result := L(Result); Exit; end; (* TAG_GAIN_CONTROL: begin gainControl := PWORD(FreeImage_GetTagValue(tag))^; case (gainControl) of 0: Result := 'None'; 1: Result := 'Low gain up'; 2: Result := 'High gain up'; 3: Result := 'Low gain down'; 4: Result := 'High gain down'; else Result := FormatEx('Unknown ({0})', [gainControl]); end; end; *) TAG_CONTRAST: begin contrast := PWORD(FreeImage_GetTagValue(tag))^; case (contrast) of 0: (* C2PAS: Exit *) Result := 'Normal'; 1: (* C2PAS: Exit *) Result := 'Soft'; 2: (* C2PAS: Exit *) Result := 'Hard'; else Result := FormatEx('Unknown ({0})', [contrast]); end; Result := L(Result); Exit; end; TAG_SATURATION: begin saturation := PWORD(FreeImage_GetTagValue(tag))^; case (saturation) of 0: (* C2PAS: Exit *) Result := 'Normal'; 1: (* C2PAS: Exit *) Result := 'Low saturation'; 2: (* C2PAS: Exit *) Result := 'High saturation'; else Result := FormatEx('Unknown ({0})', [saturation]); end; Result := L(Result); Exit; end; TAG_SHARPNESS: begin sharpness := PWORD(FreeImage_GetTagValue(tag))^; case (sharpness) of 0: (* C2PAS: Exit *) Result := 'Normal'; 1: (* C2PAS: Exit *) Result := 'Soft'; 2: (* C2PAS: Exit *) Result := 'Hard'; else Result := FormatEx('Unknown ({0})', [sharpness]); end; Result := L(Result); Exit; end; TAG_SUBJECT_DISTANCE_RANGE: begin distanceRange := PWORD(FreeImage_GetTagValue(tag))^; case (distanceRange) of 0: (* C2PAS: Exit *) Result := 'unknown'; 1: (* C2PAS: Exit *) Result := 'Macro'; 2: (* C2PAS: Exit *) Result := 'Close view'; 3: (* C2PAS: Exit *) Result := 'Distant view'; else Result := FormatEx('Unknown ({0})', [distanceRange]); end; Result := L(Result); Exit; end; TAG_ISO_SPEED_RATINGS: begin isoEquiv := PWORD(FreeImage_GetTagValue(tag))^; if (isoEquiv < 50) then isoEquiv := isoEquiv * 200; Result := IntToStr(isoEquiv); Exit; end; TAG_USER_COMMENT: begin // first 8 bytes are used to define an ID code // we assume this is an ASCII string userComment := FreeImage_GetTagValue(tag); for I := 8 to FreeImage_GetTagLength(tag) - 1 do Result := Result + string(AnsiChar(userComment[I])); Exit; end; TAG_COMPRESSION: begin compression := PWORD(FreeImage_GetTagValue(tag))^; case (compression) of TAG_COMPRESSION_NONE: Result := FormatEx('dump mode ({0})', [compression]); TAG_COMPRESSION_CCITTRLE: Result := FormatEx('CCITT modified Huffman RLE ({0})', [compression]); TAG_COMPRESSION_CCITTFAX3: Result := FormatEx('CCITT Group 3 fax encoding ({0})', [compression]); (* case TAG_COMPRESSION_CCITT_T4: Result := FormatEx("CCITT T.4 (TIFF 6 name) ({0})", [compression]); break; *) TAG_COMPRESSION_CCITTFAX4: Result := FormatEx('CCITT Group 4 fax encoding ({0})', [compression]); (* case TAG_COMPRESSION_CCITT_T6: Result := FormatEx("CCITT T.6 (TIFF 6 name) ({0})", [compression]); break; *) TAG_COMPRESSION_LZW: Result := FormatEx('LZW ({0})', [compression]); TAG_COMPRESSION_OJPEG: Result := FormatEx('!6.0 JPEG ({0})', [compression]); TAG_COMPRESSION_JPEG: Result := FormatEx('JPEG ({0})', [compression]); TAG_COMPRESSION_NEXT: Result := FormatEx('NeXT 2-bit RLE ({0})', [compression]); TAG_COMPRESSION_CCITTRLEW: Result := FormatEx('CCITTRLEW ({0})', [compression]); TAG_COMPRESSION_PACKBITS: Result := FormatEx('PackBits Macintosh RLE ({0})', [compression]); TAG_COMPRESSION_THUNDERSCAN: Result := FormatEx('ThunderScan RLE ({0})', [compression]); TAG_COMPRESSION_PIXARFILM: Result := FormatEx('Pixar companded 10bit LZW ({0})', [compression]); TAG_COMPRESSION_PIXARLOG: Result := FormatEx('Pixar companded 11bit ZIP ({0})', [compression]); TAG_COMPRESSION_DEFLATE: Result := FormatEx('Deflate [compression] ({0})', [compression]); TAG_COMPRESSION_ADOBE_DEFLATE: Result := FormatEx('Adobe Deflate [compression] ({0})', [compression]); TAG_COMPRESSION_DCS: Result := FormatEx('Kodak DCS encoding ({0})', [compression]); TAG_COMPRESSION_JBIG: Result := FormatEx('ISO JBIG ({0})', [compression]); TAG_COMPRESSION_SGILOG: Result := FormatEx('SGI Log Luminance RLE ({0})', [compression]); TAG_COMPRESSION_SGILOG24: Result := FormatEx('SGI Log 24-bit packed ({0})', [compression]); TAG_COMPRESSION_JP2000: Result := FormatEx('Leadtools JPEG2000 ({0})', [compression]); TAG_COMPRESSION_LZMA: Result := FormatEx('LZMA2 ({0})', [compression]); else Result := FormatEx('Unknown type ({0})', [compression]); end; Exit; end; end; Result := ConvertAnyTag(tag); end; ///** //Convert a Exif GPS tag to a C string //*/ function ConvertExifGPSTag(tag: PFITAG): string; type DWORD_ARRAY = array[0..5] of DWORD; PDWORD_ARRAY = ^DWORD_ARRAY; var pvalue: PDWORD_ARRAY; dd, mm: Integer; ss: Double; begin Result := ''; if (tag = nil) then Exit; // convert the tag value to a string buffer case (FreeImage_GetTagID(tag)) of TAG_GPS_LATITUDE, TAG_GPS_LONGITUDE, TAG_GPS_TIME_STAMP: begin pvalue := FreeImage_GetTagValue(tag); if (FreeImage_GetTagLength(tag) = 24) then begin // dd:mm:ss or hh:mm:ss ss := 0; // convert to seconds if (pvalue[1] > 0) then ss := ss + (pvalue[0] / pvalue[1]) * 3600; if (pvalue[3] > 0) then ss := ss + (pvalue[2] / pvalue[3]) * 60; if(pvalue[5] > 0) then ss := ss + (pvalue[4] / pvalue[5]); // convert to dd:mm:ss.ss dd := Round(ss / 3600); mm := Round(ss / 60) - dd * 60; ss := ss - dd * 3600 - mm * 60; Result := FormatEx('{0}:{1}:{2:0.##}', [dd, mm, ss]); end; end; end; end; //from FreeImage\Source\Metadata\TagConversion.cpp function FreeImageTagToString(model: FREE_IMAGE_MDMODEL; tag: PFITAG): string; begin Result := ''; case (model) of FIMD_EXIF_MAIN, FIMD_EXIF_EXIF: Exit(ConvertExifTag(tag)); FIMD_EXIF_GPS: Exit(ConvertExifGPSTag(tag)); end; Exit(ConvertAnyTag(tag)); end; { TRAWExif } function TRAWExif.Add(Description, Key, Value: string): TRAWExifRecord; begin Result := TRAWExifRecord.Create; Result.Description := Description; Result.Key := Key; Result.Value := Value; FExifList.Add(Result); end; constructor TRAWExif.Create; begin FreeImageInit; FExifList := TList.Create; end; destructor TRAWExif.Destroy; begin FreeList(FExifList); inherited; end; function TRAWExif.GetCount: Integer; begin Result:= FExifList.Count; end; function TRAWExif.GetTimeStamp: TDateTime; var I : Integer; begin Result := 0; for I := 0 to Count - 1 do if Self[I].Key = 'DateTime' then Result := EXIFDateToDate(Self[I].Value) + EXIFDateToTime(Self[I].Value); end; function TRAWExif.GetValueByIndex(Index: Integer): TRAWExifRecord; begin Result := FExifList[Index]; end; function TRAWExif.IsEXIF: Boolean; begin Result := Count > 0; end; procedure TRAWExif.LoadFromFile(FileName: string); var RawBitmap: TFreeWinBitmap; Stream: TMemoryStream; Password: string; begin RawBitmap := TFreeWinBitmap.Create; try if ValidCryptGraphicFile(FileName) then begin Stream := TMemoryStream.Create; try Password := SessionPasswords.FindForFile(FileName); if Password <> '' then begin if DecryptFileToStream(FileName, Password, Stream) then RawBitmap.LoadFromMemoryStream(Stream, FIF_LOAD_NOPIXELS); end; finally F(Stream); end; end else RawBitmap.LoadU(FileName, FIF_LOAD_NOPIXELS); LoadFromFreeImage(RawBitmap); finally F(RawBitmap); end; end; procedure TRAWExif.LoadFromStream(Stream: TStream); var RawBitmap: TFreeWinBitmap; IO: FreeImageIO; begin RawBitmap := TFreeWinBitmap.Create; try SetStreamFreeImageIO(IO); RawBitmap.LoadFromHandle(@IO, Stream, FIF_LOAD_NOPIXELS); LoadFromFreeImage(RawBitmap); finally F(RawBitmap); end; end; procedure TRAWExif.LoadFromFreeImage(Image: TFreeWinBitmap); var TagData: PFITAG; I: Integer; FindMetaData: PFIMETADATA; procedure AddTag; var Description, Key: PAnsiChar; Value: string; begin Description := FreeImage_GetTagDescription(TagData); Key := FreeImage_GetTagKey(TagData); Value := FreeImageTagToString(I, TagData); if Description <> nil then begin Add(string(Description), string(Key), string(Value)); end; end; begin TagData := nil; for I := FIMD_NODATA to FIMD_EXIF_RAW do begin FindMetaData := FreeImage_FindFirstMetadata(I, Image.Dib, TagData); try if FindMetaData <> nil then begin AddTag; while FreeImage_FindNextMetadata(FindMetaData, TagData) do AddTag; end; finally Image.FindCloseMetadata(FindMetaData); end; end; end; end.
program HowToDrawCustomText; uses SwinGame, sgTypes; procedure Main(); begin OpenGraphicsWindow('Draw Custom Text', 800, 600); ClearScreen(); DrawText('You Win!!!', ColorGreen, 300, 200); DrawTextLines('OR DO YOU???', ColorRed, ColorWhite, 'Arial', 18, AlignCenter, 400, 400, 160, 100); RefreshScreen(); Delay(5000); ReleaseAllResources(); end; begin Main(); end.
unit RNGTest_U; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, ExtCtrls, MouseRNG, OTFEFreeOTFE_WizardCommon; type TRNGTest = class(TForm) pbClose: TButton; reReport: TRichEdit; pbGenerateRandomData: TButton; pbClear: TButton; edGPGFilename: TEdit; lblGPGFilename: TLabel; MouseRNG: TMouseRNG; lblMouseRNGBits: TLabel; Panel1: TPanel; Panel2: TPanel; Panel3: TPanel; gbRNG: TGroupBox; ckRNGMouseMovement: TCheckBox; ckRNGCryptoAPI: TCheckBox; ckRNGcryptlib: TCheckBox; ckRNGGPG: TCheckBox; procedure pbCloseClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure pbGenerateRandomDataClick(Sender: TObject); procedure pbClearClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure rgRNGClick(Sender: TObject); procedure MouseRNGByteGenerated(Sender: TObject; random: Byte); private CanUseCryptlib: boolean; fRandomData: string; function GetRNGSet(): TRNGSet; public { Public declarations } end; var RNGTest: TRNGTest; implementation {$R *.DFM} uses DriverAPI, // Required for CRITICAL_DATA_LENGTH SDUGeneral; procedure TRNGTest.pbCloseClick(Sender: TObject); begin Close(); end; procedure TRNGTest.FormShow(Sender: TObject); begin ckRNGcryptlib.Enabled := CanUseCryptlib; reReport.Lines.Clear(); Panel1.Caption := ''; Panel2.Caption := ''; Panel3.Caption := ''; end; function TRNGTest.GetRNGSet(): TRNGSet; var retval: TRNGSet; begin retval := []; if ckRNGCryptoAPI.checked then begin retval := retval + [rngCryptoAPI]; end; if ckRNGMouseMovement.checked then begin retval := retval + [rngMouseMovement]; end; if ckRNGcryptlib.checked then begin retval := retval + [rngcryptlib]; end; if ckRNGGPG.checked then begin retval := retval + [rngGPG]; end; Result := retval; end; procedure TRNGTest.pbGenerateRandomDataClick(Sender: TObject); var allOK: boolean; tmpStringList: TStringList; begin allOK := GenerateRandomData( GetRNGSet(), (CRITICAL_DATA_LENGTH div 8), nil, // PKCS#11 related 0, // PKCS#11 related edGPGFilename.Text, fRandomData ); if (allOK) then begin reReport.Lines.Add('SUCCESS: Random data generated'); tmpStringList := TStringList.Create(); try SDUPrettyPrintHex( fRandomData, 0, length(fRandomData), tmpStringList ); reReport.Lines.AddStrings(tmpStringList); finally tmpStringList.Free(); end; end else begin reReport.Lines.Add('FAILED: Random data NOT generated'); end; end; procedure TRNGTest.pbClearClick(Sender: TObject); begin reReport.Lines.Clear(); end; procedure TRNGTest.FormCreate(Sender: TObject); begin fRandomData:= ''; // Start cryptlib, if possible, as early as we can to allow it as much time // as possible to poll entropy CanUseCryptlib := cryptlibLoad(); end; procedure TRNGTest.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin // Shutdown cryptlib, if used if CanUseCryptlib then begin cryptlibUnload(); CanUseCryptlib := FALSE; end; end; procedure TRNGTest.rgRNGClick(Sender: TObject); begin fRandomData := ''; // Just for testing... SDUEnableControl(MouseRNG, ckRNGMouseMovement.checked); SDUEnableControl(lblMouseRNGBits, ckRNGMouseMovement.checked); SDUEnableControl(lblGPGFilename, ckRNGGPG.checked); SDUEnableControl(edGPGFilename, ckRNGGPG.checked); end; procedure TRNGTest.MouseRNGByteGenerated(Sender: TObject; random: Byte); var randomBitsGenerated: integer; allOK: boolean; begin // Note: This is correct; if it's *less than* CRITICAL_DATA_LEN, then store it if ((length(fRandomData) * 8) < CRITICAL_DATA_LENGTH) then begin fRandomData := fRandomData + char(random); end; // This is a good place to update the display of the number of random bits // generated... randomBitsGenerated:= (length(fRandomData) * 8); lblMouseRNGBits.Caption := 'Random bits generated: '+inttostr(randomBitsGenerated)+'/'+inttostr(CRITICAL_DATA_LENGTH); allOK := (randomBitsGenerated >= CRITICAL_DATA_LENGTH); MouseRNG.Enabled := not(allOK); if MouseRNG.Enabled then begin MouseRNG.Color := clWindow; end else begin MouseRNG.Color := clBtnFace; end; end; END.
(* Category: SWAG Title: TEXT FILE MANAGEMENT ROUTINES Original name: 0070.PAS Description: Measures # of lines in textfiles Author: CHRIS AUSTIN Date: 11-22-95 15:49 *) Function Measure(FileName : String) : LongInt; Var Counter : LongInt; FileHandle: Text; Begin Assign(FileHandle,FileName); Reset(FileHandle); Counter:=0; Repeat Inc(Counter); ReadLn(FileHandle); { This line was missing in the original snippet } Until EOF(FileHandle); Measure:=Counter; End; begin WriteLn(Measure('CountLinesInTextfiles.pas')); end.
unit Unit1; (*WMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWM This demo shows how to synchronize checkboxes between the VETree and the VEListview. It tries to mimic the behavior of the MS Backup utility. Based on robleen1's and Jim Kueneman's demo. Rules: - When a VETree node is checked/unchecked it will try to sync the changes in the VEListview. It'll work with checked/unchecked/mixed. For example: if you are currently browsing the Desktop and you check "Drive C" node in the VETree (don't change the dir, just check it) then you'll see a mixed state in the "My Computer" node under the VETListview. Pretty cool, eh? - When a VETree node is expanded all it's children will be updated. - When a VEListview node is checked/unchecked it will try to sync the changes in the VETree. It'll work with checked/unchecked/mixed. For example: select "Drive C" in the VETree without expanding it, now in the VEListview select a folder, for example "Windows", you'll see a mixed state in the "Drive C" under the VETree (even though it's not expanded). Pretty cool, eh? :D - When you browse a folder with VEListview by double-clicking a node or pressing Backspace to go up a level the VEListview will be automatically synched with it's corresponding node in the VETree. To store the checked nodes to a file use the "Write Tree" button, only the VETree checked nodes are saved because they are all that we need. To retrieve the checked nodes from a file use the "Read Tree" button. The "Checked" and "Resolved" buttons will scan the VETree and show you all the checked folders out in the Memo box. Use the "Set Paths" button to check a node FROM the Memo box, simply type in a valid folder path and when you click that button the folder will be checked in the Tree, now how cool is that? WMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWM*) interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, VirtualTrees, VirtualExplorerTree, VirtualShellUtilities, StdCtrls, ExtCtrls, Buttons, ComCtrls, InfoForm, VirtualCheckboxesSynchronizer; type TForm1 = class(TForm) Splitter1: TSplitter; StatusBar1: TStatusBar; Panel3: TPanel; Panel5: TPanel; ReadTreeFileBtn: TButton; CheckBoxTreeInfo: TCheckBox; WriteTreeFileBtn: TButton; GetTreeCheckedBtn: TButton; GetTreeResolvedBtn: TButton; SetTreeBtn: TButton; TreeMemo: TMemo; SysTree: TVirtualExplorerTreeview; SysList: TVirtualExplorerListview; CheckBoxListInfo: TCheckBox; procedure FormShow(Sender: TObject); procedure WriteFileBtnClick(Sender: TObject); procedure ReadFileBtnClick(Sender: TObject); procedure SetPathsButtonClick(Sender: TObject); procedure GetAllCheckedPathsButtonClick(Sender: TObject); procedure GetResolvedPathsButtonClick(Sender: TObject); procedure CheckBoxTreeInfoClick(Sender: TObject); procedure CheckBoxListInfoClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure SysTreeChange(Sender: TBaseVirtualTree; Node: PVirtualNode); procedure SysListChange(Sender: TBaseVirtualTree; Node: PVirtualNode); private VCS: TVirtualCheckboxesSynchronizer; TreeInfo: TFormInfo; ListInfo: TFormInfo; procedure BuildTree; end; var Form1: TForm1; implementation {$R *.dfm} //{$R winxp.res} //WMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWM { Form } procedure TForm1.BuildTree; var MyComputer: PVirtualNode; begin SysTree.BeginUpdate; try SysList.Active := True; SysTree.Active := True; MyComputer := SysTree.FindNodeByPIDL(DrivesFolder.AbsolutePIDL); if MyComputer <> nil then SysTree.Expanded[MyComputer] := true; finally SysTree.EndUpdate; end; end; procedure TForm1.FormCreate(Sender: TObject); begin VCS := TVirtualCheckboxesSynchronizer.Create(Self); VCS.VirtualExplorerTreeview := SysTree; VCS.VirtualExplorerListview := SysList; ListInfo := TFormInfo.Create(Form1); TreeInfo := TFormInfo.Create(Form1); end; procedure TForm1.FormShow(Sender: TObject); begin BuildTree; end; procedure TForm1.FormDestroy(Sender: TObject); begin VCS.Free; ListInfo.Free; TreeInfo.Free; end; procedure TForm1.CheckBoxTreeInfoClick(Sender: TObject); var NS: TNamespace; Begin TreeInfo.Visible := CheckBoxTreeInfo.Checked; If SysTree.ValidateNamespace(SysTree.GetFirstSelected, NS) And CheckBoxTreeInfo.Checked Then TreeInfo.UpdateInfo(NS); end; procedure TForm1.CheckBoxListInfoClick(Sender: TObject); var NS: TNamespace; Begin ListInfo.Visible := CheckBoxListInfo.Checked; If SysList.ValidateNamespace(SysList.GetFirstSelected, NS) And CheckBoxListInfo.Checked Then ListInfo.UpdateInfo(NS); end; //WMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWM { Storage } procedure TForm1.WriteFileBtnClick(Sender: TObject); begin ViewManager.Snapshot('SysTree Checks', SysTree); ViewManager.SaveToFile('Tree.dat'); end; procedure TForm1.ReadFileBtnClick(Sender: TObject); begin ViewManager.LoadFromFile('Tree.dat'); ViewManager.ShowView('SysTree Checks', SysTree); VCS.UpdateListView; end; procedure TForm1.SetPathsButtonClick(Sender: TObject); begin VCS.SetCheckedFileNames(TreeMemo.Lines); end; procedure TForm1.GetAllCheckedPathsButtonClick(Sender: TObject); begin VCS.GetCheckedFileNames(TreeMemo.Lines); end; procedure TForm1.GetResolvedPathsButtonClick(Sender: TObject); begin VCS.GetResolvedFileNames(TreeMemo.Lines); end; //WMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWM { SysTree} procedure TForm1.SysTreeChange(Sender: TBaseVirtualTree; Node: PVirtualNode); var NS: TNamespace; begin If SysTree.ValidateNamespace(SysTree.GetFirstSelected, NS) And CheckBoxTreeInfo.Checked Then TreeInfo.UpdateInfo(NS); end; //WMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWM { SysList } procedure TForm1.SysListChange(Sender: TBaseVirtualTree; Node: PVirtualNode); var NS: TNamespace; begin If SysList.ValidateNamespace(SysList.GetFirstSelected, NS) and CheckBoxListInfo.Checked Then ListInfo.UpdateInfo(NS); end; end.