{******************************************************************************}
{* Иллюстрация к книге "DirectX. Графика в проектах Delphi".                  *}
{* Издательство BHV. www.bhv.ru                                               *}
{* Краснов М.В. softgl@chat.ru                                                *}
{******************************************************************************}
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  AppEvnts, ExtCtrls,
  DirectDraw, DDUtil;

type
  TfrmDD = class(TForm)
    ApplicationEvents1: TApplicationEvents;
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure FormKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure ApplicationEvents1Deactivate(Sender: TObject);
    procedure ApplicationEvents1Restore(Sender: TObject);
    procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X,
      Y: Integer);
    procedure FormResize(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
  private
    { Private declarations }
    FDD            : IDirectDraw7;
    FDDSPrimary    : IDirectDrawSurface7;
    FDDSBack       : IDirectDrawSurface7;
    FDDSImage      : IDirectDrawSurface7;
    FDDSBackGround : IDirectDrawSurface7;
    FDDClipper     : IDirectDrawClipper;
    procedure ErrorOut(hRet : HRESULT; FuncName : String);
    function RestoreAll : HRESULT;
    function UpdateFrame : BOOL;
    function InitSurfaces(Window : THandle) : HRESULT;
  public
    { Public declarations }
  protected
    procedure WindowMove (var Msg: TWMMove); message WM_MOVE;
  end;

const
  groundBmp     = '..\LAKE.BMP';
  imageBmp      = '..\HAND.BMP';

var
  frmDD : TfrmDD;
  mouseX : Integer = 0;
  mouseY : Integer = 0;

  rcScreen    : TRECT;
  rcViewport  : TRECT;
  rcWindow    : TRECT;
  flgWindowed : BOOL = True;
  First       : BOOL = True;

implementation

{$R *.DFM}

procedure TfrmDD.ErrorOut(hRet : HRESULT; FuncName : String);
var
  t : TextFile;
begin
  AssignFile (t, 'Debug.txt');
  Rewrite (t);
  WriteLn (t, FuncName + ': ' + DDErrorString (hRet));
  CloseFile (t);
  Destroy;
end;

procedure TfrmDD.FormCreate(Sender: TObject);
var
  hRet : HRESULT;
begin
  FDDSImage := nil;
  FDDSBackGround := nil;
  FDDClipper := nil;
  FDDSBack := nil;
  FDDSPrimary := nil;
  FDD := nil;

  if flgWindowed
     then BorderStyle := bsSizeable
     else BorderStyle := bsNone;

  ShowCursor(False);

  hRet := DirectDrawCreateEx (nil, FDD, IDirectDraw7, nil);
  if Failed(hRet) then ErrorOut(hRet, 'DirectDrawCreateEx');

  if Failed (InitSurfaces(Handle)) then Close;

  if flgWindowed then FormResize (nil);
end;

procedure TfrmDD.FormDestroy(Sender: TObject);
begin
  if Assigned(FDD) then begin
      if Assigned(FDDSImage) then FDDSImage := nil;
      if Assigned(FDDSBackGround) then FDDSBackGround := nil;
      if Assigned(FDDSBack) then FDDSBack := nil;
      if Assigned(FDDSPrimary) then FDDSPrimary := nil;
      FDD := nil;
  end;
  ShowCursor (True);
end;

procedure TfrmDD.FormKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  if (Key = VK_RETURN) and (ssAlt in Shift) then begin
     flgWindowed := not flgWindowed;
     FormCreate(nil);
  end;
  if (Key = VK_ESCAPE) or (Key = VK_F12) then Close;
end;

var
  rcMouse : TRECT;

function TfrmDD.UpdateFrame : BOOL;
var
  rcDest, wrkRect : TRECT;
  p : TPOINT;
  hRet : HResult;
begin
  Result := False;

  if flgWindowed then begin
     p.X := 0;
     p.Y := 0;
     Windows.ClientToScreen(Handle, p);
     Windows.GetClientRect(Handle, rcDest);
     OffsetRect(rcDest, p.X, p.Y);
     SetRect (wrkRect, 0, 0, ClientWidth, ClientHeight);
     if Failed (FDDSBack.Blt (@wrkRect, FDDSBackGround, nil, DDBLT_WAIT, nil))
        then if Failed (RestoreAll) then Exit;
     if Failed (FDDSBack.BltFast (mouseX, mouseY, FDDSImage, @rcMouse, DDBLTFAST_WAIT or
        DDBLTFAST_SRCCOLORKEY))
        then if Failed (RestoreAll) then Exit;
     if Failed (FDDSPrimary.Blt (@rcDest, FDDSBack, nil, DDBLT_WAIT, nil))
        then if Failed (RestoreAll) then Exit;
     end
     else begin
     if Failed (FDDSBack.Blt (nil, FDDSBackGround, nil, DDBLT_WAIT, nil))
        then if Failed (RestoreAll) then Exit;
     if Failed (FDDSBack.BltFast (mouseX, mouseY, FDDSImage, @rcMouse, DDBLTFAST_WAIT or
        DDBLTFAST_SRCCOLORKEY))
        then if Failed (RestoreAll) then Exit;
  end;

  while TRUE do begin
        if flgWindowed
            then
            hRet := FDDSPrimary.Blt(@rcScreen, FDDSBack,
                                    @rcViewport, DDBLT_WAIT,
                                    nil)
            else hRet := FDDSPrimary.Flip(nil, 0);

        if hRet = DD_OK then Break;
        if hRet = DDERR_SURFACELOST then begin
           hRet := FDDSPrimary._Restore;
           if Failed(hRet) then Break;
        end;
        if hRet <> DDERR_WASSTILLDRAWING then Break;
  end;

  Result := True;
end;

function TfrmDD.InitSurfaces(Window : THandle) : HRESULT;
var
  hRet : HRESULT;
  ddsd : TDDSURFACEDESC2;
  ddscaps : TDDSCAPS2;
  p : TPoint;
begin
  if flgWindowed then begin
     hRet := FDD.SetCooperativeLevel(Window, DDSCL_NORMAL);
     if Failed(hRet) then ErrorOut(hRet, 'SetCooperativeLevel');
     Windows.GetClientRect(Window, rcViewport);
     Windows.GetClientRect(Window, rcScreen);

     p.X := rcScreen.Left;
     p.Y := rcScreen.Top;
     Windows.ClientToScreen(Window, p);
     OffsetRect(rcScreen, p.X, p.Y);

     ZeroMemory(@ddsd, SizeOf(ddsd));
     with ddsd do begin
          dwSize := SizeOf(ddsd);
          dwFlags := DDSD_CAPS;
          ddsCaps.dwCaps := DDSCAPS_PRIMARYSURFACE;
     end;
     hRet := FDD.CreateSurface(ddsd, FDDSPrimary, nil);
     if Failed(hRet) then ErrorOut(hRet, 'CreateSurface FAILED');

     hRet := FDD.CreateClipper(0, FDDClipper, nil);
     if Failed(hRet) then ErrorOut(hRet, 'CreateClipper FAILED');

     FDDClipper.SetHWnd(0, Window);
     FDDSPrimary.SetClipper(FDDClipper);
     FDDClipper := nil;
  end
  else begin
     hRet := FDD.SetCooperativeLevel(Window, DDSCL_EXCLUSIVE or
                                             DDSCL_FULLSCREEN);
     if Failed(hRet) then ErrorOut(hRet, 'SetCooperativeLevel FAILED');

     hRet := FDD.SetDisplayMode(640, 480, 16, 0, 0);
     if Failed(hRet) then ErrorOut(hRet, 'SetDisplayMode FAILED');

     SetRect(rcViewport, 0, 0, 640, 480);
     CopyMemory (@rcScreen, @rcViewport, SizeOf(TRECT));

     ZeroMemory(@ddsd, SizeOf(ddsd));
     with ddsd do begin
          dwSize := SizeOf(ddsd);
          dwFlags := DDSD_CAPS or DDSD_BACKBUFFERCOUNT;
          ddsCaps.dwCaps := DDSCAPS_PRIMARYSURFACE or DDSCAPS_FLIP or
     	                    DDSCAPS_COMPLEX;
          dwBackBufferCount := 1;
     end;
     hRet := FDD.CreateSurface(ddsd, FDDSPrimary, nil);
     if Failed(hRet) then ErrorOut(hRet, 'CreateSurface FAILED');

     ZeroMemory(@ddscaps, SizeOf(ddscaps));
     ddscaps.dwCaps := DDSCAPS_BACKBUFFER;
     hRet := FDDSPrimary.GetAttachedSurface(ddscaps, FDDSBack);
     if Failed(hRet) then ErrorOut(hRet, 'GetAttachedSurface FAILED');
  end;

  FDDSBackGround := DDLoadBitmap(FDD, groundBmp, 0, 0);
  if FDDSBackGround = nil then ErrorOut(DD_FALSE, 'DDLoadBitmap');

  FDDSImage := DDLoadBitmap(FDD, imageBmp, 0, 0);
  if FDDSImage = nil then ErrorOut(DD_FALSE, 'DDLoadBitmap');

  hRet := DDSetColorKey (FDDSImage, RGB (0, 0, 0));
  if Failed (hRet) then ErrorOut(hRet, 'DDSetColorKey');

  Result := DD_OK;
end;

procedure TfrmDD.WindowMove (var Msg: TWMMove);
var
  p : TPoint;
begin
  Windows.GetClientRect(Handle, rcViewport);
  Windows.GetClientRect(Handle, rcScreen);

  p.X := rcScreen.Left;
  p.Y := rcScreen.Top;
  Windows.ClientToScreen(Handle, p);
  OffsetRect(rcScreen, p.X, p.Y);
  UpdateFrame;
end;

procedure TfrmDD.ApplicationEvents1Deactivate(Sender: TObject);
begin
  if flgWindowed
     then begin
          GetWindowRect(Handle, rcWindow);
          if First then First := False;
     end
     else begin
     if First
        then First := False
        else Application.Minimize;
  end;
end;

procedure TfrmDD.ApplicationEvents1Restore(Sender: TObject);
begin
  if flgWindowed then begin
     Left := rcWindow.Left;
     Top := rcWindow.Top;
     end
     else WindowState := wsMaximized;
  UpdateFrame;     
end;

function TfrmDD.RestoreAll : HRESULT;
var
  hRet : HRESULT;
begin
  hRet := FDDSPrimary._Restore;
  if Succeeded (hRet) then begin
      hRet := FDDSImage._Restore;
      if Failed (hRet) then begin
         Result := hRet;
         Exit;
      end;
      hRet := DDReLoadBitmap(FDDSImage, imageBmp);
      if Failed (hRet) then ErrorOut(hRet, 'DDReLoadBitmap');
      hRet := FDDSBackGround._Restore;
      if Failed (hRet) then begin
         Result := hRet;
         Exit;
      end;
      hRet := DDReLoadBitmap(FDDSBackGround, groundBmp);
      if Failed (hRet) then ErrorOut(hRet, 'DDReLoadBitmap');
      if flgWindowed then begin
         hRet := FDDSBack._Restore;
         if Failed (hRet) then begin
            Result := hRet;
            Exit;
         end;
      end;
      Result := DD_OK;
  end else Result := hRet;
end;

procedure TfrmDD.FormMouseMove(Sender: TObject; Shift: TShiftState; X,
  Y: Integer);
var
  wrkI, wrkJ : Integer;
begin
  mouseX := X;
  if X < ClientWidth - 32
     then wrkI := 32
     else wrkI := ClientWidth - X;
  mouseY := Y;
  if Y < ClientHeight - 32
     then wrkJ := 32
     else wrkJ := ClientHeight - Y;
  SetRect (rcMouse, 0, 0, wrkI, wrkJ);

  UpdateFrame;
end;

procedure TfrmDD.FormResize(Sender: TObject);
var
  hRet : HRESULT;
  ddsd : TDDSurfaceDesc2;
begin
  if flgWindowed then begin
  if Assigned(FDDSBack) then FDDSBack := nil;
  ZeroMemory(@ddsd, SizeOf(ddsd));
  with ddsd do begin
     dwSize := SizeOf(ddsd);
     dwFlags := DDSD_CAPS or DDSD_HEIGHT or DDSD_WIDTH;
     ddsCaps.dwCaps := DDSCAPS_OFFSCREENPLAIN;
     dwWidth  := ClientWidth;
     dwHeight := ClientHeight;
  end;
  hRet := FDD.CreateSurface(ddsd, FDDSBack, nil);
  if Failed(hRet) then ErrorOut(hRet, 'Create Back Surface');
  end;
  UpdateFrame;  
end;

procedure TfrmDD.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  Hide
end;

end.

