{******************************************************************************}
{* Иллюстрация к книге "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 ApplicationEvents1Deactivate(Sender: TObject);
    procedure FormKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure ApplicationEvents1Restore(Sender: TObject);
    procedure FormActivate(Sender: TObject);
    procedure ApplicationEvents1Idle(Sender: TObject; var Done: Boolean);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
  private
    { Private declarations }
    FDD            : IDirectDraw7;
    FDDSBack       : IDirectDrawSurface7;
    FDDSPrimary    : IDirectDrawSurface7;
    FDDSBackGround : IDirectDrawSurface7;
    FDDSImage      : IDirectDrawSurface7;
    FDDPal         : IDirectDrawPalette;
    FActive        : BOOL;
    ThisTickCount  : DWORD;
    LastTickCount  : DWORD;
    function UpdateFrame : HRESULT;
    function FlipPages : HRESULT;
    function RestoreAll : HRESULT;
    procedure ErrorOut(hRet : HRESULT; FuncName : String);
  public
    { Public declarations }
  protected
    procedure FormSetCursor(var aMsg : TMessage); message WM_SETCURSOR;
  end;

const
  ScreenWidth    = 640;
  ScreenHeight   = 480;
  ScreenBitDepth = 8;
  groundBmp      = '..\BACKGRD.BMP';
  imageBmp       = '..\DINO.BMP';

var
  frmDD : TfrmDD;
  Angle : Single = 0;
  frames : Integer = 0;
  fps : PChar = '';

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;
  ddsd : TDDSurfaceDesc2;
  ddscaps : TDDSCaps2;
begin
  FDDSImage := nil;
  FDDSBack := nil;
  FDDSBackGround := nil;
  FDDPal := nil;
  FDDSPrimary := nil;
  FDD := nil;

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

  hRet := FDD.SetCooperativeLevel(Handle, DDSCL_FULLSCREEN or DDSCL_EXCLUSIVE);
  if Failed (hRet) then ErrorOut(hRet, 'SetCooperativeLevel');

  hRet := FDD.SetDisplayMode (ScreenWidth, ScreenHeight, ScreenBitDepth, 0, 0);
  if Failed (hRet) then ErrorOut(hRet, 'SetDisplayMode');

  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, 'Create Primary Surface');

  FDDPal := DDLoadPalette(FDD, groundBmp);
  if FDDPal = nil then ErrorOut(DD_FALSE, 'DDLoadPalette');

  hRet := FDDSPrimary.SetPalette(FDDPal);
  if Failed (hRet) then ErrorOut(hRet, 'SetPalette');

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

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

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

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

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

procedure TfrmDD.ApplicationEvents1Deactivate(Sender: TObject);
begin
  FActive := False;
  Application.Minimize;
end;

procedure TfrmDD.FormKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  if (Key = VK_ESCAPE) or (Key = VK_F12) then Close;
end;

procedure TfrmDD.FormSetCursor(var aMsg : TMessage);
begin
  SetCursor(0);
end;

function TfrmDD.RestoreAll : HRESULT;
var
  hRet : HRESULT;
begin
  hRet := FDDSPrimary._Restore;
  if Succeeded (hRet) then begin
      FDDPal := nil;
      FDDPal := DDLoadPalette(FDD, groundBmp);
      if FDDPal <> nil then begin
         hRet := FDDSPrimary.SetPalette(FDDPal);
         if Failed (hRet)
            then ErrorOut(hRet, 'SetPalette');
         end
         else ErrorOut(DDERR_PALETTEBUSY, 'DDLoadPalette');
      hRet := FDDSBackGround._Restore;
      if Failed (hRet) then begin
         Result := hRet;
         Exit;
      end;
      hRet := DDReLoadBitmap(FDDSBackGround, groundBmp);
      if Failed (hRet) then ErrorOut(hRet, 'DDReLoadBitmap');
      hRet := FDDSImage._Restore;
      if Failed (hRet) then begin
         Result := hRet;
         Exit;
      end;
      if Failed (DDReLoadBitmap(FDDSImage, imageBmp))
         then ErrorOut(DD_FALSE, 'DDReLoadBitmap');
      Result := DD_OK;
  end else Result := hRet;
end;

procedure TfrmDD.ApplicationEvents1Restore(Sender: TObject);
begin
  WindowState := wsMaximized;
  FActive := True;
end;

procedure TfrmDD.FormActivate(Sender: TObject);
begin
  LastTickCount := GetTickCount;
  FActive := True;
end;

procedure TfrmDD.ApplicationEvents1Idle(Sender: TObject;
  var Done: Boolean);
begin
  if FActive then
     if Succeeded (UpdateFrame) then FlipPages;
  Done := False;
end;

function TfrmDD.UpdateFrame : HRESULT;
var
  DC : HDC;
  hRet : HRESULT;
begin
  ThisTickCount := GetTickCount;

  Inc (frames);
  if ThisTickCount - LastTickCount > 60 then begin
     Angle := Angle + 0.05;
     if Angle > 2 * Pi then Angle := Angle - 2 * Pi;
     fps := PChar ('FPS = ' + Format('%6.2f',
                                      [frames * 1000 / (ThisTickCount - LastTickCount)]));
     frames := 0;

     LastTickCount := GetTickCount;
  end;

  hRet := FDDSBack.BltFast (0, 0, FDDSBackGround, nil, DDBLTFAST_WAIT);
  if hRet = DDERR_SURFACELOST then begin
     hRet := RestoreAll;
     if Failed (hRet) then begin
        Result := hRet;
        Exit;
     end;
  end;

  if Succeeded (FDDSBack.GetDC (DC)) then begin
     TextOut (DC, 20, 20, fps, 12);
     FDDSBack.ReleaseDC (DC);
  end;

  hRet := FDDSBack.BltFast (320 + trunc (cos(Angle) * 150) - 32,
                       240 + trunc (sin(Angle) * 150) - 32,
                       FDDSImage, nil,
                       DDBLTFAST_WAIT or DDBLTFAST_SRCCOLORKEY);
  if hRet = DDERR_SURFACELOST then begin
     hRet := RestoreAll;
     if Failed (hRet) then begin
        Result := hRet;
        Exit;
     end;
  end;

  Result := DD_OK;
end;

function TfrmDD.FlipPages : HRESULT;
begin
  Result := FDDSPrimary.Flip(nil, DDFLIP_WAIT);
  if Result = DDERR_SURFACELOST then Result := RestoreAll;
end;

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

end.

