unit MDF;

interface

uses Windows, SysUtils, Math3D, GL, GLu, GLext, WGLext, GLtools,
     VertexArray, Models;

function LoadMDF(filename: string; va: TVertexArray): TModel;

implementation

const
  MDF_ID: array[0..7] of char = '!!MDF1.0';

type
  TMDFHeader = record
    ID         : array[0..7] of char;     // must be "!!MDF1.0"
    numver     : cardinal;                // number of vertices
    numidx     : cardinal;                // number of indices
    mask       : cardinal;                // input mask
    mode       : cardinal;                // primitive drawing mode
    reserved   : array[0..231] of byte;   // reserved for expansion
  end;

function LoadMDF;
var
  f: file;
  hdr: TMDFHeader;
  i, idx: cardinal;
  v4: TVector4;
  v3: TVector3;
begin
  assign(f, filename);
  reset(f, 1);
  blockread(f, hdr, SizeOf(hdr));
  if hdr.ID <> MDF_ID then raise Exception.Create('Invalid file format');
  result := TModel.Create(va);
  result.Init(hdr.numver, hdr.numidx);
  result.BeginModel(hdr.mode);
  if hdr.mask and VERTEX_MASK > 0 then
    for i := 0 to hdr.numver-1 do
    begin
      blockread(f, v4, SizeOf(v4));
      result.Vertex(i, v4);
    end;
  if hdr.mask and COLOR0_MASK > 0 then
    for i := 0 to hdr.numver-1 do
    begin
      blockread(f, v4, SizeOf(v4));
      result.Color0(i, v4);
    end;
  if hdr.mask and COLOR1_MASK > 0 then
    for i := 0 to hdr.numver-1 do
    begin
      blockread(f, v4, SizeOf(v4));
      result.Color1(i, v4);
    end;
  if hdr.mask and NORMAL_MASK > 0 then
    for i := 0 to hdr.numver-1 do
    begin
      blockread(f, v3, SizeOf(v3));
      result.Normal(i, v3);
    end;
  if hdr.mask and TEXCOORD_MASK > 0 then
    for i := 0 to hdr.numver-1 do
    begin
      blockread(f, v4, SizeOf(v4));
      result.TexCoord(i, v4);
    end;
  for i := 0 to hdr.numidx-1 do
  begin
    blockread(f, idx, SizeOf(idx));
    result.Index(i, idx);
  end;
  result.EndModel;
  close(f);
end;

end.
