{******************************************************************************}
{* Иллюстрация к книге "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;
    FDDSPrimary    : IDirectDrawSurface7;
    FDDSBackGround : IDirectDrawSurface7;
    FDDSBack       : IDirectDrawSurface7;
    FDDSImage      : IDirectDrawSurface7;
    FActive        : BOOL;
    function UpdateFrame : HRESULT;
    function RestoreAll : HRESULT;
    function FlipPages : HRESULT;
    procedure NextFrame;
    procedure FirstFrame;
    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 = 16;
  groundBmp      = '..\LAKE.BMP';
  AVIName        = '..\highway.avi';

var
  frmDD : TfrmDD;

implementation

uses VFW;

{$R *.DFM}

var
  TmpBmp : TBitmap;
  AviStream : PAVISTREAM;
  Frame : PGetFrame;
  pbmi : PBITMAPINFOHEADER;
  bits : Pointer;

  CurrFrame : DWORD = 0;
  AVIClock  : DWORD;

  AVIDelay  : DWORD;
  AVIWidth  : DWORD;
  AVIHeight : DWORD;
  AVILength : DWORD;

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;
  AVIFile : PAVIFile;
  AVIInfo : TAVIFileInfo;
begin
  TmpBmp := TBitmap.Create;

  AVIFileOpen(AVIFile, AVIName, OF_READ, nil);
  AVIFileInfo(AVIFile, AVIInfo, SizeOf (AVIInfo));
     AVIWidth := AVIInfo.dwWidth;
     AVIHeight := AVIInfo.dwHeight;
     AVILength := AVIInfo.dwLength;
     AVIDelay := 1000 div (AVIInfo.dwRate div AVIInfo.dwScale);
  AVIFileRelease(AVIFile);

  FDDSImage := nil;
  FDDSBack := nil;
  FDDSBackGround := 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');

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

  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  := AviWidth;
       dwHeight := AVIHeight;
  end;
  hRet := FDD.CreateSurface(ddsd, FDDSImage, nil);
  if Failed(hRet) then ErrorOut(hRet, 'Create Second Surface');

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

  FirstFrame;
end;

procedure TfrmDD.FormDestroy(Sender: TObject);
begin
  AVIStreamRelease(AviStream);
  AVIFileExit;
  TmpBmp.Free;

  if Assigned(FDD) then begin
      if Assigned(FDDSBackGround) then FDDSBackGround := nil;
      if Assigned(FDDSBack) then FDDSBack := nil;
      if Assigned(FDDSImage) then FDDSImage := nil;
      if Assigned(FDDSPrimary) then FDDSPrimary := nil;
      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
      FDDSBackGround := nil;
      FDDSBackGround := DDLoadBitmap(FDD, groundBmp, ScreenWidth, ScreenHeight);
      if FDDSBackGround = nil then ErrorOut(DD_FALSE, 'DDLoadBitmap');
      Result := FDDSImage._Restore;
  end else Result := hRet;
end;

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

procedure TfrmDD.FormActivate(Sender: TObject);
begin
  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
  hRet : HRESULT;
begin
  NextFrame;

  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;

  hRet := FDDSBack.BltFast (0, 0, FDDSImage, nil, DDBLTFAST_WAIT);
  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;
var
  hRet : HRESULT;
begin
  hRet := FDDSPrimary.Flip(nil, DDFLIP_WAIT);
  if hRet = DDERR_SURFACELOST
     then Result := RestoreAll
     else Result := hRet;
end;

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

procedure TfrmDD.NextFrame;
var
  wrkDC : HDC;
begin
  if GetTickCount - AVIClock > AVIDelay then begin
     pbmi := AVIStreamGetFrame(Frame, CurrFrame);

     if FDDSImage.GetDC (wrkDC) = DD_OK then begin
        TmpBmp.Handle := CreateDIBitmap(
            wrkDC,
  	    pbmi^,
  	    CBM_INIT,
  	    bits,
  	    PBITMAPINFO(pbmi)^,
  	    DIB_RGB_COLORS );

        BitBlt (wrkDC, 0, 0, AVIWidth, AVIHeight,
                TmpBmp.Canvas.Handle, 0, 0, SRCCOPY);
        FDDSImage.ReleaseDC (wrkDC);
     end;

     CurrFrame := (CurrFrame + 1) mod AVILength;

     AVIClock := GetTickCount;
  end;
end;

procedure TfrmDD.FirstFrame;
var
  wrkDC : HDC;
begin
  AVIFileInit;

  AVIStreamOpenFromFile(AviStream, AviName, streamtypeVIDEO, 0, OF_READ, nil);

  Frame := AVIStreamGetFrameOpen(AviStream, nil);

  pbmi := AVIStreamGetFrame(Frame, CurrFrame);

  bits := Pointer(Integer(pbmi) + SizeOf(TBITMAPINFOHEADER));
  if FDDSImage.GetDC (wrkDC) = DD_OK then begin
     TmpBmp.Handle := CreateDIBitmap(
            wrkDC,
  	    pbmi^,
  	    CBM_INIT,
  	    bits,
  	    PBITMAPINFO(pbmi)^,
  	    DIB_RGB_COLORS );

     BitBlt (wrkDC, 0, 0, AVIWidth, AVIHeight,
             TmpBmp.Canvas.Handle, 0, 0, SRCCOPY);
     FDDSImage.ReleaseDC (wrkDC);
  end;

  AVIClock := GetTickCount;
end;

end.


