DEADSOFTWARE

wadcvt: creating more corrent apngs
[d2df-sdl.git] / src / sfs / wadcvt.dpr
index 85666cfabe50a5811e8fbb354627f3a6254fd386..5d1c1f1100afe4689e2c9bd4ccd377a6c90f925c 100644 (file)
@@ -14,17 +14,200 @@ uses
   sfs,
   sfsPlainFS,
   sfsZipFS,
-  paszlib;
+  paszlib,
+  wadreader in '../shared/wadreader.pas',
+  conbuf in '../shared/conbuf.pas',
+  BinEditor in '../shared/BinEditor.pas',
+  MAPSTRUCT in '../shared/MAPSTRUCT.pas',
+  MAPDEF in '../shared/MAPDEF.pas',
+  CONFIG in '../shared/CONFIG.pas',
+  e_log in '../engine/e_log.pas',
+  ImagingTypes, Imaging, ImagingUtility;
 
 
+{.$WARNINGS ON}
+{.$NOTES ON}
+{.$HINTS ON}
+
+var
+  optConvertATX: Boolean = false;
+
+
+function LoadAnimTexture (wadSt: TStream; wadName: AnsiString): TMemoryStream;
+var
+  WAD: TWADFile = nil;
+  TextureWAD: PChar = nil;
+  TextData: Pointer = nil;
+  TextureData: Pointer = nil;
+  cfg: TConfig = nil;
+  ResLength: Integer;
+  TextureResource: String;
+  _width, _height, _framecount, _speed: Integer;
+  _backanimation: Boolean;
+  ia: TDynImageDataArray = nil;
+  f: Integer;
+  img: TImageData;
+  x, y, ofsx, ofsy, nx, ny: Integer;
+  clr: TColor32Rec;
+  sto: TMemoryStream = nil;
+  buf: PChar;
+  buflen: Integer;
+begin
+  result := nil;
+
+  wadSt.position := 0;
+  buflen := Integer(wadSt.size);
+  GetMem(buf, buflen);
+  try
+    wadSt.ReadBuffer(buf^, buflen);
+
+    WAD := TWADFile.Create();
+    //WAD.ReadFile(wadName);
+    WAD.ReadMemory(buf, buflen);
+
+    // ×èòàåì INI-ðåñóðñ àíèì. òåêñòóðû è çàïîìèíàåì åãî óñòàíîâêè:
+    if not WAD.GetResource('TEXT/ANIM', TextData, ResLength) then
+    begin
+      writeln(Format('Animated texture file "%s" has invalid INI', [wadName]));
+      exit;
+    end;
+
+    try
+      cfg := TConfig.CreateMem(TextData, ResLength);
+
+      TextureResource := cfg.ReadStr('', 'resource', '');
+      if TextureResource = '' then
+      begin
+        writeln(Format('Animated texture WAD file "%s" has no "resource"', [wadName]));
+        exit;
+      end;
+
+      _width := cfg.ReadInt('', 'framewidth', 0);
+      _height := cfg.ReadInt('', 'frameheight', 0);
+      _framecount := cfg.ReadInt('', 'framecount', 0);
+      _speed := cfg.ReadInt('', 'waitcount', 0);
+      _backanimation := cfg.ReadBool('', 'backanimation', False);
+      if _speed < 0 then _speed := 0;
+
+      if (_width < 1) or (_width > 16383) or (_height < 1) or (_height > 16383) then
+      begin
+        writeln('invalid animation dimensions: ', _width, 'x', _height);
+        exit;
+      end;
+
+      if (_framecount < 1) or (_framecount > 1024) then
+      begin
+        writeln('invalid frame count: ', _framecount);
+        exit;
+      end;
+
+      cfg.Free();
+      cfg := nil;
+
+      // ×èòàåì ðåñóðñ òåêñòóð (êàäðîâ) àíèì. òåêñòóðû â ïàìÿòü:
+      if not WAD.GetResource('TEXTURES/'+TextureResource, TextureData, ResLength) then
+      begin
+        writeln(Format('Animated texture WAD file "%s" has no texture "%s"', [wadName, 'TEXTURES/'+TextureResource]));
+        exit;
+      end;
+
+      if not LoadImageFromMemory(TextureData, ResLength, img) then
+      begin
+        writeln(Format('Animated texture file "%s" has invalid texture image', [wadName]));
+        exit;
+      end;
+      //writeln('texture image: ', img.width, 'x', img.height, ' (', img.width div _width, ' frames)');
+
+      WAD.Free();
+      WAD := nil;
+
+      // now create animation frames
+      GlobalMetadata.ClearMetaItems();
+      GlobalMetadata.ClearMetaItemsForSaving();
+
+      GlobalMetadata.SetMetaItem(SMetaFrameDelay, _speed*28);
+      if _backanimation then
+        GlobalMetadata.SetMetaItem(SMetaAnimationLoops, 1)
+      else
+        GlobalMetadata.SetMetaItem(SMetaAnimationLoops, 0);
+
+      SetLength(ia, _framecount);
+      //writeln('creating ', length(ia), ' animation frames...');
+      for f := 0 to high(ia) do
+      begin
+        GlobalMetadata.SetMetaItem(SMetaFrameDelay, _speed*28, f);
+        if _backanimation then
+          GlobalMetadata.SetMetaItem(SMetaAnimationLoops, 1, f)
+        else
+          GlobalMetadata.SetMetaItem(SMetaAnimationLoops, 0, f);
+
+        InitImage(ia[f]);
+        NewImage(_width, _height, TImageFormat.ifA8R8G8B8, ia[f]);
+        ofsx := f*_width;
+        ofsy := 0;
+        for y := 0 to _height-1 do
+        begin
+          for x := 0 to _width-1 do
+          begin
+            nx := ofsx+x;
+            ny := ofsy+y;
+            if (nx >= 0) and (ny >= 0) and (nx < img.width) and (ny < img.height) then
+            begin
+              clr := GetPixel32(img, nx, ny);
+            end
+            else
+            begin
+              clr.r := 0;
+              clr.g := 0;
+              clr.b := 0;
+              clr.a := 0;
+            end;
+            SetPixel32(ia[f], x, y, clr);
+          end;
+        end;
+        //writeln('resizing image...');
+        //ResizeImage(ia[f], 320, 200, TResizeFilter.rfNearest);
+      end;
+      GlobalMetadata.CopyLoadedMetaItemsForSaving;
+
+      sto := TMemoryStream.Create();
+      //writeln(' ... [', ChangeFileExt(wadName, '.png'), '] (', length(ia), ') ');
+      if SaveMultiImageToStream('png', sto, ia) then
+      begin
+        sto.position := 0;
+        result := sto;
+        sto := nil;
+      end
+      else
+      begin
+        //writeln(' ...WTF?!');
+      end;
+    finally
+      FreeImage(img);
+    end;
+  finally
+    for f := 0 to High(ia) do FreeImage(ia[f]);
+    WAD.Free();
+    cfg.Free();
+    if TextureWAD <> nil then FreeMem(TextureWAD);
+    if TextData <> nil then FreeMem(TextData);
+    if TextureData <> nil then FreeMem(TextureData);
+    sto.Free();
+    FreeMem(buf);
+  end;
+end;
+
+
+{
 procedure processed (count: Cardinal);
 begin
   //writeln('  read ', count, ' bytes');
 end;
+}
 
 
 // returs crc
-function zpack (ds: TStream; ss: TStream): LongWord;
+function zpack (ds: TStream; ss: TStream; var aborted: Boolean): LongWord;
 const
   IBSize = 65536;
   OBSize = 65536;
@@ -35,12 +218,17 @@ var
   rd: Integer;
   eof: Boolean;
   crc: LongWord;
+  dstp, srcsize: Int64;
 begin
   result := 0;
+  //aborted := true; exit;
+  aborted := false;
   crc := crc32(0, nil, 0);
   GetMem(ib, IBSize);
   GetMem(ob, OBSize);
   ss.position := 0;
+  dstp := ds.position;
+  srcsize := ss.size;
   try
     zst.next_out := ob;
     zst.avail_out := OBSize;
@@ -70,6 +258,12 @@ begin
           if zst.avail_out < OBSize then
           begin
             //writeln('  written ', OBSize-zst.avail_out, ' bytes');
+            if ds.position+(OBSize-zst.avail_out)-dstp >= srcsize then
+            begin
+              // this will be overwritten anyway
+              aborted := true;
+              exit;
+            end;
             ds.writeBuffer(ob^, OBSize-zst.avail_out);
             zst.next_out := ob;
             zst.avail_out := OBSize;
@@ -85,6 +279,12 @@ begin
         if zst.avail_out < OBSize then
         begin
           //writeln('  .written ', OBSize-zst.avail_out, ' bytes');
+          if ds.position+(OBSize-zst.avail_out)-dstp >= srcsize then
+          begin
+            // this will be overwritten anyway
+            aborted := true;
+            exit;
+          end;
           ds.writeBuffer(ob^, OBSize-zst.avail_out);
           zst.next_out := ob;
           zst.avail_out := OBSize;
@@ -151,6 +351,7 @@ var
   buflen: Integer;
   f: Integer;
   st: string[24];
+  img: string;
 begin
   result := fname;
   if length(ExtractFileExt(fname)) <> 0 then exit;
@@ -215,6 +416,7 @@ begin
       end;
     end;
     // targa (stupid hack; this "signature" is not required by specs)
+    {
     if buflen >= 18 then
     begin
       Move((buf+buflen-18)^, (PChar(@st[1]))^, 16);
@@ -225,6 +427,27 @@ begin
         exit;
       end;
     end;
+    }
+    // detect image format
+    img := DetermineMemoryFormat(buf, buflen);
+    if length(img) > 0 then
+    begin
+      result := result+'.'+img;
+      exit;
+    end;
+    // check if this is text file
+    if buflen > 16 then
+    begin
+      for f := 0 to buflen-1 do
+      begin
+        if buf[f] = #127 then exit;
+        if buf[f] < #32 then
+        begin
+          if (buf[f] <> #9) and (buf[f] <> #10) and (buf[f] <> #13) then exit;
+        end;
+      end;
+      result := result+'.txt';
+    end;
   finally
     FreeMem(buf);
   end;
@@ -313,6 +536,7 @@ var
   sz: Word;
 begin
   fu := toUtf8(fname);
+  if fu = fname then begin result := nil; exit; end; // no need to write anything
   crc := crc32(0, @fname[1], length(fname));
   sz := 2+2+1+4+length(fu);
   SetLength(result, sz);
@@ -332,10 +556,13 @@ end;
 const UtfFlags = (1 shl 10); // bit 11
 {$ENDIF}
 
-function ZipOne (ds: TStream; fname: AnsiString; st: TStream): TFileInfo;
+function ZipOne (ds: TStream; fname: AnsiString; st: TStream; dopack: Boolean=true): TFileInfo;
 var
-  oldofs, nfoofs, pkdpos: Int64;
+  oldofs, nfoofs, pkdpos, rd: Int64;
   sign: packed array [0..3] of Char;
+  buf: PChar;
+  bufsz: Integer;
+  aborted: Boolean = false;
 {$IFDEF UTFEXTRA}
   ef: TByteArray;
 {$ENDIF}
@@ -344,6 +571,11 @@ begin
   result.pkofs := ds.position;
   result.size := st.size;
   if result.size > 0 then result.method := 8 else result.method := 0;
+  if not dopack then
+  begin
+    result.method := 0;
+    result.pksize := result.size;
+  end;
 {$IFDEF UTFEXTRA}
   result.name := fname;
   ef := buildUtfExtra(result.name);
@@ -372,19 +604,62 @@ begin
 {$IFDEF UTFEXTRA}
   if length(ef) > 0 then ds.writeBuffer(ef[0], length(ef));
 {$ENDIF}
-  // now write packed data
-  if result.size > 0 then
+  if dopack then
   begin
-    pkdpos := ds.position;
-    st.position := 0;
-    result.crc := zpack(ds, st);
-    result.pksize := ds.position-pkdpos;
+    // now write packed data
+    if result.size > 0 then
+    begin
+      pkdpos := ds.position;
+      st.position := 0;
+      result.crc := zpack(ds, st, aborted);
+      result.pksize := ds.position-pkdpos;
+      if {result.pksize >= result.size} aborted then
+      begin
+        // there's no sence to pack this file, so just store it
+        st.position := 0;
+        ds.position := result.pkofs;
+        result.Free();
+        // store it
+        result := ZipOne(ds, fname, st, false);
+        exit;
+      end
+      else
+      begin
+        // fix header
+        oldofs := ds.position;
+        ds.position := nfoofs;
+        writeInt(ds, LongWord(result.crc)); // crc32
+        writeInt(ds, LongWord(result.pksize)); // crc32
+        ds.position := oldofs;
+      end;
+    end;
+  end
+  else
+  begin
+    bufsz := 1024*1024;
+    GetMem(buf, bufsz);
+    try
+      st.position := 0;
+      result.crc := crc32(0, nil, 0);
+      result.pksize := 0;
+      while result.pksize < result.size do
+      begin
+        rd := result.size-result.pksize;
+        if rd > bufsz then rd := bufsz;
+        st.readBuffer(buf^, rd);
+        ds.writeBuffer(buf^, rd);
+        Inc(result.pksize, rd);
+        result.crc := crc32(result.crc, buf, rd);
+      end;
+    finally
+      FreeMem(buf);
+    end;
     // fix header
     oldofs := ds.position;
     ds.position := nfoofs;
     writeInt(ds, LongWord(result.crc)); // crc32
-    writeInt(ds, LongWord(result.pksize)); // crc32
     ds.position := oldofs;
+    write('(S) ');
   end;
 end;
 
@@ -446,11 +721,11 @@ end;
 
 
 var
-  fs, fo: TStream;
+  fs, fo, ast: TStream;
   fl: TSFSFileList;
   f: Integer;
-  infname: AnsiString;
-  outfname: AnsiString;
+  infname: AnsiString = '';
+  outfname: AnsiString = '';
   dvfn: AnsiString;
   newname: AnsiString;
   files: array of TFileInfo;
@@ -462,21 +737,28 @@ begin
     Halt(1);
   end;
 
-  infname := ParamStr(1);
+  for f := 1 to ParamCount() do
+  begin
+    if ParamStr(f) = '--apng' then optConvertATX := true
+    else
+    begin
+           if length(infname) = 0 then infname := ParamStr(f)
+      else if length(outfname) = 0 then outfname := ParamStr(f)
+      else
+      begin
+        writeln('FATAL: too many arguments!');
+        Halt(1);
+      end;
+    end;
+  end;
+
   if not StrEquCI1251(ExtractFileExt(infname), '.wad') and not StrEquCI1251(ExtractFileExt(infname), '.dfwad') then
   begin
     writeln('wtf?!');
     Halt(1);
   end;
 
-  if ParamCount() > 1 then
-  begin
-    outfname := ParamStr(2);
-  end
-  else
-  begin
-    outfname := ChangeFileExt(infname, '.pk3');
-  end;
+  if length(outfname) = 0 then outfname := ChangeFileExt(infname, '.pk3');
 
   if not SFSAddDataFile(infname) then begin WriteLn('shit!'); Halt(1); end;
   dvfn := SFSGetLastVirtualName(infname);
@@ -490,6 +772,10 @@ begin
     Halt(1);
   end;
 
+  Imaging.SetOption(ImagingPNGCompressLevel, 9);
+  Imaging.SetOption(ImagingPNGLoadAnimated, 1);
+  Imaging.SetOption(ImagingGIFLoadAnimated, 1);
+
   fo := TFileStream.Create(outfname, fmCreate);
   try
     for f := 0 to fl.Count-1 do
@@ -500,11 +786,35 @@ begin
       //fs.Free();
       //fs := SFSFileOpen(dvfn+'::'+fl[f].fPath+fl[f].fName);
       fs.position := 0;
-      writeln('[', f+1, '/', fl.Count, ']: ', fl[f].fPath, newname, '  ', fs.size);
+{$IFNDEF WINDOWS}
+      write(#13'[', f+1, '/', fl.Count, ']: ', fl[f].fPath, newname, '  ', fs.size, ' ... '#27'[K');
+{$ELSE}
+      write('[', f+1, '/', fl.Count, ']: ', fl[f].fPath, newname, '  ', fs.size, ' ... ');
+{$ENDIF}
+      //writeln(' : ', newname, ' : [', ExtractFileExt(newname), ']');
+      if optConvertATX and (StrEquCI1251(ExtractFileExt(newname), '.dfwad') or StrEquCI1251(ExtractFileExt(newname), '.wad')) then
+      begin
+        //writeln('  ANIMTEXT!');
+        ast := LoadAnimTexture(fs, newname);
+        if ast <> nil then
+        begin
+          fs.Free();
+          fs := ast;
+          newname := ChangeFileExt(newname, '.png');
+          //writeln('  ANIMTEXT! [', newname, ']');
+        end;
+      end;
       nfo := ZipOne(fo, fl[f].fPath+newname, fs);
+      write('DONE');
+{$IFDEF WINDOWS}
+      writeln;
+{$ENDIF}
       SetLength(files, length(files)+1);
       files[high(files)] := nfo;
     end;
+{$IFNDEF WINDOWS}
+    writeln(#13, fl.Count, ' files processed'#27'[K');
+{$ENDIF}
     writeCentralDir(fo, files);
   except
     fo.Free();