DEADSOFTWARE

wadcvt: option to aggressively compress pngs
[d2df-sdl.git] / src / sfs / wadcvt.dpr
index d8058379b63784914b93e0b581a934e50bc9a236..617edb69ad7cff939dfdb7587aa3af415083d678 100644 (file)
@@ -3,6 +3,11 @@
   {$APPTYPE CONSOLE}
 {$ENDIF}
 {$DEFINE UTFEXTRA}
+{.$DEFINE ONELINELOG}
+
+{$IFDEF WINDOWS}
+  {$UNDEF ONELINELOG}
+{$ENDIF}
 program __wadcvt__;
 
 uses
@@ -15,12 +20,221 @@ uses
   sfsPlainFS,
   sfsZipFS,
   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;
 
 
-procedure processed (count: Cardinal);
+{.$WARNINGS ON}
+{.$NOTES ON}
+{.$HINTS ON}
+
+var
+  optConvertATX: Boolean = false;
+  optConvertTGA: Boolean = false;
+  optLoCaseNames: Boolean = false;
+  optAggressivePng: Boolean = false;
+  optRecompress: Boolean = false;
+
+
+function convertAnimTexture (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
-  //writeln('  read ', count, ' bytes');
+  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), ') ');
+      Imaging.SetOption(ImagingPNGCompressLevel, 9);
+      if optAggressivePng then Imaging.SetOption(ImagingPNGPreFilter, 6);
+      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;
+
+
+function recompressImageToPng (ist: TStream): TStream;
+var
+  ia: TDynImageDataArray = nil;
+  sto: TMemoryStream = nil;
+  f: Integer;
+begin
+  result := nil;
+  ist.position := 0;
+  GlobalMetadata.ClearMetaItems();
+  GlobalMetadata.ClearMetaItemsForSaving();
+  if not LoadMultiImageFromStream(ist, ia) then exit;
+  try
+    GlobalMetadata.CopyLoadedMetaItemsForSaving;
+    sto := TMemoryStream.Create();
+    Imaging.SetOption(ImagingPNGCompressLevel, 9);
+    if optAggressivePng then Imaging.SetOption(ImagingPNGPreFilter, 6);
+    if SaveMultiImageToStream('png', sto, ia) then
+    begin
+      sto.position := 0;
+      result := sto;
+      sto := nil;
+    end;
+  finally
+    sto.Free();
+    for f := 0 to High(ia) do FreeImage(ia[f]);
+  end;
 end;
 
 
@@ -539,15 +753,17 @@ end;
 
 
 var
-  fs, fo: TStream;
+  fs, fo, ast: TStream;
   fl: TSFSFileList;
-  f: Integer;
-  infname: AnsiString;
-  outfname: AnsiString;
+  f, c: Integer;
+  infname: AnsiString = '';
+  outfname: AnsiString = '';
   dvfn: AnsiString;
   newname: AnsiString;
   files: array of TFileInfo;
   nfo: TFileInfo;
+  nomoreopts: Boolean;
+  arg: AnsiString;
 begin
   if ParamCount() < 1 then
   begin
@@ -555,21 +771,59 @@ begin
     Halt(1);
   end;
 
-  infname := ParamStr(1);
+  Imaging.SetOption(ImagingPNGCompressLevel, 9);
+  Imaging.SetOption(ImagingPNGLoadAnimated, 1);
+  Imaging.SetOption(ImagingGIFLoadAnimated, 1);
+
+  for f := 1 to ParamCount() do
+  begin
+    arg := ParamStr(f);
+    if length(arg) = 0 then continue;
+    if not nomoreopts and (arg[1] = '-') then
+    begin
+           if arg = '--apng' then optConvertATX := true
+      else if arg = '--tga' then optConvertTGA := true
+      else if arg = '--locase' then optLoCaseNames := true
+      else if arg = '--nocase' then optLoCaseNames := false
+      else if arg = '--aggressive' then begin optAggressivePng := true; Imaging.SetOption(ImagingPNGPreFilter, 6); end
+      else if arg = '--recompress' then optRecompress := true
+      else if (arg = '--help') or (arg = '-h') then
+      begin
+        writeln('usage: wadcvt [options] file.wad');
+        writeln('options:');
+        writeln('  --apng    convert animated textures to APNG format');
+        writeln('  --tga     convert Targa images to PNG format');
+{$IFNDEF WINDOWS}
+        writeln('  --locase  convert file names to lower case');
+{$ENDIF}
+        Halt(1);
+      end
+      else if arg = '--' then nomoreopts := true
+      else
+      begin
+        writeln('unknown option: "', arg, '"');
+        Halt(1);
+      end;
+    end
+    else
+    begin
+           if length(infname) = 0 then infname := arg
+      else if length(outfname) = 0 then outfname := arg
+      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);
@@ -583,6 +837,10 @@ begin
     Halt(1);
   end;
 
+{$IFNDEF WINDOWS}
+  optLoCaseNames := true;
+{$ENDIF}
+
   fo := TFileStream.Create(outfname, fmCreate);
   try
     for f := 0 to fl.Count-1 do
@@ -593,21 +851,54 @@ begin
       //fs.Free();
       //fs := SFSFileOpen(dvfn+'::'+fl[f].fPath+fl[f].fName);
       fs.position := 0;
-{$IFNDEF WINDOWS}
+{$IFNDEF ONELINELOG}
       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}
-      nfo := ZipOne(fo, fl[f].fPath+newname, fs);
-      write('DONE');
-{$IFDEF WINDOWS}
+      //writeln(' : ', newname, ' : [', ExtractFileExt(newname), ']');
+      if optConvertATX and (StrEquCI1251(ExtractFileExt(newname), '.dfwad') or StrEquCI1251(ExtractFileExt(newname), '.wad')) then
+      begin
+        //writeln('  ANIMTEXT!');
+        ast := convertAnimTexture(fs, newname);
+        if ast <> nil then
+        begin
+          fs.Free();
+          fs := ast;
+          newname := ChangeFileExt(newname, '.png');
+{$IFNDEF ONELINELOG}
+          write('APNG ');
+{$ENDIF}
+        end;
+      end
+      else if optRecompress or (optConvertTGA and (StrEquCI1251(ExtractFileExt(newname), '.tga') or StrEquCI1251(ExtractFileExt(newname), '.bmp'))) then
+      begin
+        ast := recompressImageToPng(fs);
+        if ast <> nil then
+        begin
+          fs.Free();
+          fs := ast;
+          newname := ChangeFileExt(newname, '.png');
+{$IFNDEF ONELINELOG}
+          write('PNG ');
+{$ENDIF}
+        end;
+        fs.position := 0;
+      end;
+      newname := fl[f].fPath+newname;
+      if optLoCaseNames then for c := 1 to length(newname) do newname[c] := LoCase1251(newname[c]);
+      nfo := ZipOne(fo, newname, fs);
+      write(nfo.pksize, ' DONE');
+{$IFNDEF ONELINELOG}
       writeln;
 {$ENDIF}
       SetLength(files, length(files)+1);
       files[high(files)] := nfo;
     end;
-{$IFNDEF WINDOWS}
-    writeln(#13, fl.Count, ' files processed'#27'[K');
+{$IFNDEF ONELINELOG}
+    writeln(fl.Count, ' files processed.');
+{$ELSE}
+    writeln(#13, fl.Count, ' files processed.'#27'[K');
 {$ENDIF}
     writeCentralDir(fo, files);
   except