type subimages=record // Type а utiliser uniquement sous forme de pointeur (subimages^) car structure trop grande pour la pile (stack overflow)
fps1,fps2:word;
nbframes:word;
frames:array[0..3000] of record
nbimages:word;
images:array[0..64] of record
val:byte; // Flag binaire (4, 8, 32...)
left,top,right,bottom:smallint;
imgindex:word;
end;
end;
nbimages:word;
images:array[0..1000] of record
width,height:word;
offset:longint;
end;
end;
type subsound=record
aifc:boolean; // si false, c'est du wav normal
offset,size:longword;
samples:longword;
bitrate,frames,rate:word;
end;
type subsubfile=record
subname:longint;
fileoffset,filesize:longword;
data:pointer; // Pointeur qui dйpendra du type
end;
type subfile=record
ftype:string[4]; // off4, snd....
nbsub:word;
subfile:array[0..1000] of subsubfile;
end;
var SRFhandler:file;
SRFdata:record
loaded:boolean;
nbfiles:word;
filelist:array[0..255] of subfile;
end;
qhdrCSV:string;
stringsCSV:string;
function openSRF(filename:string):shortint;
procedure closeSRF;
function filetype(ftype:string):string;
procedure exportSubimagesToGif(ssf:subsubfile;filename:string);
procedure exportSubsoundToFile(ssf:subsubfile;filename:string);
function readString(ssf:subsubfile):string;
procedure exportStringToFile(ssf:subsubfile;filename:string);
function exportStringlist(ssf:subsubfile):string;
function exportStringlist1(ssf:subsubfile):string;
function exportStringlist2(ssf:subsubfile):string;
function exportAnswers(ssf:subsubfile):string;
procedure exportQHeadersToFile(ssf:subsubfile);
procedure decodeImageBuffer(buf:array of byte; var bufresult:array of longint; buflen:longint);
function idfileoff4:word;
implementation
uses SysUtils,GifImage;
var colors:array[0..255] of longint;
rgbtopalette:array[0..255] of array[0..255] of array[0..255] of byte;
graphic:array[0..307200] of byte;
picture:array[0..307200] of longint;
// Fonctions palette
procedure InitColors;
var palette:TBitmap;
i:byte;
l:longint;
r,g,b:byte;
begin
palette:=TBitmap.Create;
palette.LoadFromResourceName(hinstance,'PALETTE');
for i:=0 to 255 do begin
l:=palette.Canvas.Pixels[i,0];
colors[i]:=l;
b:=l and FF;
l:=l shr 8;
r:=l and $FF;
rgbtopalette[r][g][b]:=i;
end;
palette.Free;
end;
Assistant
User
Нужно на пайтон перенести систему экстракта изображений
Палитра в виде bmp 256x1
Assistant
FF;l:=lshr8;g:=land
function pixel2palette(l:longint):byte;
var r,g,b:byte;
begin
b:=l and FF;l:=lshr8;g:=landFF;
l:=l shr 8;
r:=l and $FF;
result:=rgbtopalette[r][g][b];
end;
function GetColorIndex(GIF: TGIFSubImage; Color: TColor): Integer;
var
idx, x, y: Integer;
begin
// Find index for color in the colormap.
// The same color can be in the colormap more than once.
// Not all color indexes may be in use, so check if this index is being used.
// Return only an index which is actually being used in the image.
// If the index is not being used in the image,
// try to find the next index for the color in the colormap.
for idx := 0 to GIF.ActiveColorMap.Count - 1 do
if GIF.ActiveColorMap.Colors[idx] = Color then
begin
// Found an index, is it being used in the image?
for y := 0 to GIF.Height-1 do
for x := 0 to GIF.Width-1 do
if GIF.Pixels[x, y] = idx then
begin
Result := idx; // Index is used in image.
Exit;
end;
// Index not used in the image, try next index.
end;
Result := -1; // didn't find index for the color
end;
// Lecture du fichier
function BE4(l:Longword):Longword; // bigendian 4 octets
begin
result:=((l and FF)shl24)or((landFF00) shl 8) or ((l and FF0000)shr8)or((landFF000000) shr 24);
end;
function readlw:longint; // lire un longword (ou longint peu importe) en bigendian
var l:longint;
begin
blockread(SRFhandler,l,4);
result:=BE4(l);
end;
function BE2(l:word):word; // bigendian 2 octets
begin
result:=((l and FF)shl8)or((landFF00) shr 8);
end;
function readw:word; // lire un word en bigendian
var l:word;
begin
blockread(SRFhandler,l,2);
result:=BE2(l);
end;
function readb:word; // lire un byte
var l:byte;
begin
blockread(SRFhandler,l,1);
result:=l;
end;
// Dйcodage des images
procedure decodeImageBuffer(buf:array of byte; var bufresult:array of longint; buflen:longint);
var bitmap:array[0..307200] of byte;
infos:array[0..2] of byte;
status:byte;
widebf:word;
pos,i,l,offset,extrapixels:longint;
nbrepeat:word;
nextbg,bglength:longint;
begin
l:=0;
pos:=0;
extrapixels:=buf[0]-2;
bglength:=-1;
nextbg:=buf[0]+buf[1];
for i:=0 to 2 do begin
bitmap[l]:=buf[pos];inc(pos);
inc(l);
end;
while (l+extrapixels < buflen) and (l < 307200) do begin
widebf:=buf[pos];inc(pos);
widebf:=(widebf shl 1) or 1;
while (widebf and FF)<>0dobeginstatus:=(widebfand100) shr 8;
widebf := widebf shl 1;
if (status = 0) then begin // Pixel copiй tel quel
if (l = nextbg-extrapixels) or (bglength <> -1) then begin
if (bglength = -1) then bglength:=buf[pos] else begin
inc(extrapixels,bglength-2);
inc(nextbg,bglength+buf[pos]);
bglength:=-1;
end;
end;
bitmap[l]:=buf[pos];inc(pos);
inc(l);
end else begin // Rйpйtition
infos[0]:=buf[pos];inc(pos);
infos[1]:=buf[pos];inc(pos);
if (infos[1] and F0)=0thenbeg10;
end else begin // Rйpйtition а 2 octets
nbrepeat:=infos[1] and F0;nbrepeat:=nbrepeatshr4;en100*(infos[1] and $0F)); // Rйpйtition, offset : line[0]+0x100*LO(line[1]), qtй = HI(line[1])+2
for i:=1 to nbrepeat+2 do begin
if (l = nextbg-extrapixels) or (bglength <> -1) then begin
if (bglength = -1) then bglength:=bitmap[offset] else begin
inc(extrapixels,bglength-2);
inc(nextbg,bglength+bitmap[offset]);
bglength:=-1;
end;
end;
bitmap[l]:=bitmap[offset];inc(offset);
inc(l);
end;
end;
end;
end;
nextbg:=0;
bglength:=-1;
// Extraction а partir de bitmap
pos:=0;
for i:=0 to l-1 do begin
if (bglength <> -1) then begin
inc(nextbg,bglength+bitmap[i]);
while bglength > 0 do begin
bufresult[pos]:=$FF80FF; // Transparent (couleur inexistante dans la palette, rose clair)
inc(pos);
dec(bglength);
if (pos >= 307200) then break; // TODO: QNUMBERS.SRF, image n°48 (la derniиre) fait dйpasser la valeur de la position...
end;
bglength:=-1;
end else if (pos=nextbg) then begin
bglength:=bitmap[i];
end else begin
bufresult[pos] := colors[bitmap[i]];
inc(pos);
end;
if (pos >= 307200) then break;
end;
end;
// Export des images/animations en Gif+JS
const verticalGIF = 1; // 1 = GIF en mode vertical, 0 en mode horizontal
procedure exportSubimagesToGif(ssf:subsubfile;filename:string);
var si:^subimages;
GIF:TGifImage;
Ext: TGIFGraphicControlExtension;
ResultAdd:Integer;
idx: Integer;
pic:TPicture;
w,h,x,y,realx,realy:integer;
pos,graphlen: longint;
off4pos,i,j:word;
maxwidth,maxheight:integer;
js:string;
f:system.text;
begin
// Positionnement trиs simple et trиs inefficace des sprites
maxwidth:=0;maxheight:=0;
js:='';
si:=ssf.data;
if si^.nbimages > 0 then begin
for off4pos:=0 to si^.nbimages-1 do with si^.images[off4pos] do begin
if (verticalGIF = 1) then begin
if (width > maxwidth) then maxwidth:=width;
inc(maxheight,height);
end else begin
if (height > maxheight) then maxheight:=height;
inc(maxwidth,width);
end;
end;
if (verticalGIF = 1) then inc(maxheight,si^.nbimages) else inc(maxwidth,si^.nbimages);
// Dessin а partir de longbitmap
pic:=TPicture.Create;
pic.Bitmap.Width:=maxwidth;
pic.Bitmap.Height:=maxheight;
pic.Bitmap.Canvas.Brush.Color:=$FF80FF; // Remplir l'image de la couleur transparente
pic.Bitmap.Canvas.FillRect(pic.Bitmap.Canvas.ClipRect);
js:=js+'res[''tiles'']=new Array();';
realx:=0;
realy:=0;
for off4pos:=0 to si^.nbimages-1 do begin
seek(SRFhandler,si^.images[off4pos].offset);
w:=si^.images[off4pos].width;
h:=si^.images[off4pos].height;
blockread(SRFhandler,graphic,307200,graphlen);
decodeImageBuffer(graphic,picture,w*h);
js:=js+'res[''tiles'']['+inttostr(off4pos)+']={x:'+inttostr(realx)+',y:'+inttostr(realy)+',w:'+inttostr(w)+',h:'+inttostr(h)+'};';
x:=0;
y:=0;
pos:=0;
while y < h do begin
pic.Bitmap.Canvas.Pixels[x+realx,y+realy] := picture[pos];
inc(pos);
inc(x);
if (x >= w) then begin
x:=0;
inc(y);
end;
end;
if (verticalGIF = 1) then inc(realy,h+1) else inc(realx,w+1);
end;
// Create GIF
GIF := TGIFImage.Create;
GIF.Width := maxwidth;
GIF.Height := maxheight;
GIF.ColorReduction := rmNone; // rmQuantize rmNone
// GIF.DitherMode := dmNearest; // no dither, use nearest color in palette
GIF.DitherMode := dmNearest; // dmNearest dmFloydSteinberg
GIF.Compression := gcLZW;
// Add image
ResultAdd:=GIF.Add(pic.Graphic);
// Add Graphic Control Extension (for transparent color)
Ext := TGIFGraphicControlExtension.Create(GIF.Images[ResultAdd]);
idx := GetColorIndex(GIF.Images[ResultAdd], $FF80FF);
if idx in [0..255] then
begin
Ext.Transparent := True;
Ext.TransparentColorIndex := idx;
end;
GIF.Images[ResultAdd].Extensions.Add(Ext);
// Save GIF
GIF.SaveToFile(filename+'.gif');
// Release GIF
GIF.Free;
end;
// Add frames to JS
js:=js+#13#10'res[''frames'']=[';
for i:=0 to si^.nbframes-1 do begin
js:=js+'{n:'+inttostr(si^.frames[i].nbimages);
if (si^.frames[i].nbimages > 0) then begin
js:=js+',f:'+inttostr(si^.fps1)+',g:'+inttostr(si^.fps2)+',l:[';
for j:=0 to si^.frames[i].nbimages do begin
js:=js+'{'
+'v:'+inttostr(si^.frames[i].images[j].val)+','
+'l:'+inttostr(si^.frames[i].images[j].left)+','
+'t:'+inttostr(si^.frames[i].images[j].top)+','
+'r:'+inttostr(si^.frames[i].images[j].right)+','
+'b:'+inttostr(si^.frames[i].images[j].bottom)+','
+'i:'+inttostr(si^.frames[i].images[j].imgindex)
+'},';
end;
js:=js+']';
end;
js:=js+'},';
end;
js:=js+'];';
// Save JS
assignfile(f,filename+'.js');
rewrite(f);
writeln(f,js);
closefile(f);
end;
// Lecture du format des images (off4)
function openSubimages(filesize:longint):pointer; // ^subimages
var si:^subimages;
imagestartpointer,currentpos2,fileoffset:longint;
nbimages,i,j:word;
nbframes,frameoffset:word;
begin
getmem(si,sizeof(subimages));
fileoffset:=filepos(SRFhandler);
imagestartpointer:=readlw;
// Donnйes d'animation
si^.fps1:=readw; // 400
si^.fps2:=readw; // 6 400/6 = 66, 66 ms par frame ?
nbframes:=readw;
si^.nbframes:=nbframes;
if nbframes > 0 then begin
for i:=0 to nbframes-1 do begin
frameoffset:=readw;
if (frameoffset = 0) then begin
si^.frames[i].nbimages:=0;
end else begin
currentpos2:=filepos(SRFhandler);
seek(SRFhandler,fileoffset+10+nbframes2+(frameoffset-1)12);
sameoffset:=readw; // Si diffйrent de 0, alors on prend les mкmes images qu'а l'offset indiquй
left:=readw;
top:=readw;
right:=readw;
bottom:=readw;
nbframeimages:=readw;
si^.frames[i].nbimages:=nbframeimages;
si^.frames[i].images[0].val:=0;
si^.frames[i].images[0].left:=left;
si^.frames[i].images[0].top:=top;
si^.frames[i].images[0].right:=right;
si^.frames[i].images[0].bottom:=bottom;
if (sameoffset <> 0) then seek(SRFhandler,fileoffset+10+nbframes2+sameoffset12);
if (nbframeimages > 0) then for j:=1 to nbframeimages do begin
readb; // imgnum mais on l'a avec j de toutes faзons
si^.frames[i].images[j].val:=readb;
si^.frames[i].images[j].left:=readw;
si^.frames[i].images[j].top:=readw;
si^.frames[i].images[j].right:=readw;
si^.frames[i].images[j].bottom:=readw;
si^.frames[i].images[j].imgindex:=readw;
end;
seek(SRFhandler,currentpos2);
end;
end;
end;
// Liste d'images
seek(SRFhandler,fileoffset+imagestartpointer);
nbimages:=readw;
if (nbimages <> readw) then begin // Prйsent deux fois dans le fichier, pourquoi...
//form1.Label1.caption:='Alert nbimage different';
end;
si^.nbimages:=nbimages;
if nbimages > 0 then begin // On peut n'avoir aucune image, mais des frames... exemple avec 5QDemo.srf, premier bloc (42)
if (nbimages > 1000) then raise Exception.Create('Too many images');
for i:=0 to nbimages-1 do begin
si^.images[i].offset:=fileoffset+readlw;
si^.images[i].width:=readw;
si^.images[i].height:=readw;
end;
end;
result:=si;
end;
// Export des sons en wav ou aifc
procedure exportSubsoundToFile(ssf:subsubfile;filename:string);
var ss:subsound;
f:file;
data:array[0..8191] of byte;
size:longword;
procedure invertdata; // Inverse les mots dans data
var i:word;
a:byte;
begin
for i:=0 to 4095 do begin
a:=data[i2];
data[i2]:=data[i2+1];
data[i2+1]:=a;
end;
end;
begin
ss:=subsound(ssf.data^);
if (ss.aifc) then assignfile(f,filename+'.aifc') else assignfile(f,filename+'.wav');
rewrite(f,1);
if (ss.aifc) then begin // AIFC
// Construction du header
data[0]:=ord('F');data[1]:=ord('O');data[2]:=ord('R');data[3]:=ord('M');
size:=ss.size+92;
data[4]:=(size and FF000000)shr24;data[5]:=(sizeandFF0000) shr 16;data[6]:=(size and FF00)shr8;data[7]:=(sizeandFF);
data[8]:=ord('A');data[9]:=ord('I');data[10]:=ord('F');data[11]:=ord('C');data[12]:=ord('F');data[13]:=ord('V');data[14]:=ord('E');data[15]:=ord('R');
data[16]:=00;data[17]:=00;data[18]:=00;data[19]:=04;data[20]:=A2;data[21]:=80;data[22]:=51;data[23]:=40;
data[24]:=ord('C');data[25]:=ord('O');data[26]:=ord('M');data[27]:=ord('M');data[28]:=00;data[29]:=00;data[30]:=00;data[31]:=16;
data[32]:=00;data[33]:=01;
data[34]:=(ss.samples and FF000000)shr24;data[35]:=(ss.samplesandFF0000) shr 16;data[36]:=(ss.samples and FF00)shr8;data[37]:=(ss.samplesandFF); // Samples
data[38]:=00;data[39]:=10; // sampleSize (16)
data[40]:=(ss.frames and FF00)shr8;data[41]:=(ss.framesandFF); // numSampleFrames
data[42]:=(ss.rate and FF00)shr8;data[43]:=(ss.rateandFF); // sampleRate
data[44]:=00;data[45]:=00;data[46]:=00;data[47]:=00;
data[48]:=00;data[49]:=00;data[50]:=ord('i');data[51]:=ord('m');data[52]:=ord('a');data[53]:=ord('4');data[54]:=ord('S');data[55]:=ord('S');
data[56]:=ord('N');data[57]:=ord('D');
size:=ss.size+38;
data[58]:=(size and FF000000)shr24;data[59]:=(sizeandFF0000) shr 16;data[60]:=(size and FF00)shr8;data[61]:=(sizeandFF);
data[62]:=00;data[63]:=00;
data[64]:=00;data[65]:=00;data[66]:=00;data[67]:=00;data[68]:=00;data[69]:=00;
code
blockwrite(f,data,70);
// On copie les donnйes en brut
size:=ss.size;
seek(SRFhandler,ss.offset);
while size > 0 do begin
if (size > 8192) then begin
blockread(SRFhandler,data,8192);
blockwrite(f,data,8192);
dec(size,8192);
end else begin
blockread(SRFhandler,data,size);
blockwrite(f,data,size);
size:=0;
end;
end;
end else begin // WAV
// Construction du header
data[0]:=ord('R');data[1]:=ord('I');data[2]:=ord('F');data[3]:=ord('F');
size:=ss.size+120;
data[4]:=(size and FF);data[5]:=(sizeandFF00) shr 8;data[6]:=(size and FF0000)shr16;data[7]:=(sizeandFF000000) shr 24;
data[8]:=ord('W');data[9]:=ord('A');data[10]:=ord('V');data[11]:=ord('E');data[12]:=ord('f');data[13]:=ord('m');data[14]:=ord('t');data[15]:=ord(' ');
data[16]:=10;data[17]:=00;data[18]:=00;data[19]:=00;data[20]:=01;data[21]:=00;data[22]:=01;data[23]:=00;
data[24]:=(ss.bitrate and FF);data[25]:=(ss.bitrateandFF00) shr 8;data[26]:=00;data[27]:=00;data[28]:=C8;data[29]:=AF;data[30]:=00;data[31]:=00;
code
data[32]:=$02;data[33]:=$00;data[34]:=$10;data[35]:=$00;data[36]:=ord('d');data[37]:=ord('a');data[38]:=ord('t');data[39]:=ord('a');
data[40]:=(ss.size and $FF);data[41]:=(ss.size and $FF00) shr 8;data[42]:=(ss.size and $FF0000) shr 16;data[43]:=(ss.size and $FF000000) shr 24;
blockwrite(f,data,44);
// On copie les donnйes en brut, en inversant les word
size:=ss.size;
seek(SRFhandler,ss.offset);
while size > 0 do begin
if (size > 8192) then begin
blockread(SRFhandler,data,8192);
invertdata;
blockwrite(f,data,8192);
dec(size,8192);
end else begin
blockread(SRFhandler,data,size);
invertdata;
blockwrite(f,data,size);
size:=0;
end;
end;
end;
closefile(f);
end;
// Lecture du format des sons (snd, M*xx)
function openSubsound(filesize:longint):pointer; // ^subsound
var ss:^subsound;
data:array[0..41] of byte;
begin
getmem(ss,sizeof(subsound));
blockread(SRFhandler,data,28); // Infos inutiles a priori
ss.bitrate:=readw;
blockread(SRFhandler,data,12); // Infos inutiles a priori
ss.samples:=readlw;
ss.frames:=readw;
ss.rate:=readw;
blockread(SRFhandler,data,34); // Compression en 10-13
ss.offset:=filepos(SRFhandler);
ss.size:=filesize-84; // Taille totale moins le header
ss.aifc:=false;
if (data[10] = 0) and (data[11] = 0) and (data[12] = 0) and (data[13] = 0) then begin // WAV
ss.aifc:=false;
end else if (data[10] = 69)and(data[11]=6D) and (data[12] = 61)and(data[13]=34) then begin // AIFC (ima4)
ss.aifc:=true;
end;
result:=ss;
end;
function MactoUTF8(c:char):string; // Caractиres MAC vers UTF8
begin
if (ord(c) = 7B)thenresult:=chr(C2)+chr(A0)//Espaceinsйcableelseif(ord(c)=80) then result:=chr(C3)+chr(84) // Д
else if (ord(c) = 81)thenresult:=chr(C3)+chr(85)//Еelseif(ord(c)=82) then result:=chr(C3)+chr(87) // З
else if (ord(c) = 83)thenresult:=chr(C3)+chr(89)//Йelseif(ord(c)=84) then result:=chr(C3)+chr(91) // С
else if (ord(c) = 85)thenresult:=chr(C3)+chr(96)//Цelseif(ord(c)=86) then result:=chr(C3)+chr(9C) // Ь
else if (ord(c) = 87)thenresult:=chr(C3)+chr(A1)//бelseif(ord(c)=88) then result:=chr(C3)+chr(A0) // а
else if (ord(c) = 89)thenresult:=chr(C3)+chr(A2)//вelseif(ord(c)=8A) then result:=chr(C3)+chr(A4) // д
else if (ord(c) = 8B)thenresult:=chr(C3)+chr(A3)//гelseif(ord(c)=8C) then result:=chr(C3)+chr(A5) // е
else if (ord(c) = 8D)thenresult:=chr(C3)+chr(A7)//зelseif(ord(c)=8E) then result:=chr(C3)+chr(A9) // й
else if (ord(c) = 8F)thenresult:=chr(C3)+chr(A8)//иelseif(ord(c)=90) then result:=chr(C3)+chr(AA) // к
else if (ord(c) = 91)thenresult:=chr(C3)+chr(AB)//лelseif(ord(c)=92) then result:=chr(C3)+chr(AD) // н
else if (ord(c) = 93)thenresult:=chr(C3)+chr(AC)//мelseif(ord(c)=94) then result:=chr(C3)+chr(AE) // о
else if (ord(c) = 95)thenresult:=chr(C3)+chr(AF)//пelseif(ord(c)=96) then result:=chr(C3)+chr(B1) // с
else if (ord(c) = 97)thenresult:=chr(C3)+chr(B3)//уelseif(ord(c)=98) then result:=chr(C3)+chr(B2) // т
else if (ord(c) = 99)thenresult:=chr(C3)+chr(B4)//фelseif(ord(c)=9A) then result:=chr(C3)+chr(B6) // ц
else if (ord(c) = 9B)thenresult:=chr(C3)+chr(B5)//хelseif(ord(c)=9C) then result:=chr(C3)+chr(BA) // ъ
else if (ord(c) = 9D)thenresult:=chr(C3)+chr(B9)//щelseif(ord(c)=9E) then result:=chr(C3)+chr(BB) // ы
else if (ord(c) = 9F)thenresult:=chr(C3)+chr(BC)//ьelseif(ord(c)=A0) then result:=chr(E2)+chr(80)+chr(A0)//†elseif(ord(c)=A1) then result:=chr(C2)+chr(B0) // °
else if (ord(c) = A2)thenresult:=chr(C2)+chr(AE)//R◯elseif(ord(c)=A3) then result:=chr(C2)+chr(A3) // Ј
else if (ord(c) = A4)thenresult:=chr(C2)+chr(A7)//§elseif(ord(c)=A5) then result:=chr(E2)+chr(80)+chr(A2)//•elseif(ord(c)=A6) then result:=chr(C2)+chr(B6) // ¶
else if (ord(c) = A7)thenresult:=chr(C3)+chr(9F)//Яelseif(ord(c)=A8) then result:=chr(C2)+chr(AE) // ®
else if (ord(c) = A9)thenresult:=chr(C2)+chr(A9)//c◯elseif(ord(c)=AA) then result:=chr(E2)+chr(84)+chr(A2)//™elseif(ord(c)=AB) then result:=chr(C2)+chr(B4) // ґ
else if (ord(c) = AC)thenresult:=chr(C2)+chr(A8)//Ёelseif(ord(c)=AD) then result:=chr(E2)+chr(89)+chr(A0)//?elseif(ord(c)=AE) then result:=chr(C3)+chr(86) // Ж
else if (ord(c) = AF)thenresult:=chr(C3)+chr(98)//Шelseif(ord(c)=B0) then result:=chr(E2)+chr(88)+chr(9E)//8elseif(ord(c)=B1) then result:=chr(C2)+chr(B1) // ±
else if (ord(c) = B2)thenresult:=chr(E2)+chr(89)+chr(A4) // =
else if (ord(c) = B3)thenresult:=chr(E2)+chr(89)+chr(A5) // =
else if (ord(c) = B4)thenresult:=chr(C2)+chr(A5)//Ґelseif(ord(c)=B5) then result:=chr(C2)+chr(B5) // µ
else if (ord(c) = B6)thenresult:=chr(E2)+chr(88)+chr(82) // ?
else if (ord(c) = B7)thenresult:=chr(C3)+chr(9F)//Яelseif(ord(c)=B8) then result:=chr(E2)+chr(88)+chr(8F)//?elseif(ord(c)=B9) then result:=chr(CF)+chr(80) // p
else if (ord(c) = BA)thenresult:=chr(E2)+chr(88)+chr(AB) // ?
else if (ord(c) = BB)thenresult:=chr(C2)+chr(AA)//Єelseif(ord(c)=BC) then result:=chr(C2)+chr(BA) // є
else if (ord(c) = BD)thenresult:=chr(CE)+chr(A9)//Oelseif(ord(c)=BE) then result:=chr(C3)+chr(A6) // ж
else if (ord(c) = BF)thenresult:=chr(C3)+chr(B8)//шelseif(ord(c)=C0) then result:=chr(C2)+chr(BF) // ї
else if (ord(c) = C1)thenresult:=chr(C2)+chr(A1)//Ўelseif(ord(c)=C2) then result:=chr(C2)+chr(AC) // ¬
else if (ord(c) = C3)thenresult:=chr(E2)+chr(88)+chr(9A) // v
else if (ord(c) = C4)thenresult:=chr(C6)+chr(92)//ѓelseif(ord(c)=C5) then result:=chr(E2)+chr(89)+chr(88)//elseif(ord(c)=C6) then result:=chr(CE)+chr(94) // ?
else if (ord(c) = C7)thenresult:=chr(C2)+chr(AB)//«elseif(ord(c)=C8) then result:=chr(C2)+chr(BB) // »
else if (ord(c) = C9)thenresult:=chr(E2)+chr(80)+chr(A6) // …
else if (ord(c) = CA)thenresult:=chr(C2)+chr(A0)//elseif(ord(c)=CB) then result:=chr(C3)+chr(80) // А
else if (ord(c) = CC)thenresult:=chr(C3)+chr(83)//Гelseif(ord(c)=CD) then result:=chr(C3)+chr(95) // Х
else if (ord(c) = CE)thenresult:=chr(C5)+chr(92)//Њelseif(ord(c)=CF) then result:=chr(C5)+chr(93) // њ
else if (ord(c) = D0)thenresult:=chr(E2)+chr(80)+chr(93) // –
else if (ord(c) = D1)thenresult:=chr(E2)+chr(80)+chr(94) // —
else if (ord(c) = D2)thenresult:=chr(E2)+chr(80)+chr(9C) // “
else if (ord(c) = D3)thenresult:=chr(E2)+chr(80)+chr(9D) // ”
else if (ord(c) = D4)thenresult:=chr(E2)+chr(80)+chr(98) // ‘
else if (ord(c) = D5)thenresult:=chr(E2)+chr(80)+chr(99) // ’
else if (ord(c) = D6)thenresult:=chr(C3)+chr(B7)//чelseif(ord(c)=D7) then result:=chr(E2)+chr(97)+chr(8A)//?elseif(ord(c)=D8) then result:=chr(C3)+chr(BF) // я
else if (ord(c) = D9)thenresult:=chr(C5)+chr(B8)//џelseif(ord(c)=DA) then result:=chr(E2)+chr(81)+chr(84)///elseif(ord(c)=DB) then result:=chr(E2)+chr(82)+chr(AC)//Ђelseif(ord(c)=DC) then result:=chr(E2)+chr(80)+chr(B9)//‹elseif(ord(c)=DD) then result:=chr(E2)+chr(80)+chr(BA)//›elseif(ord(c)=DE) then result:=chr(EF)+chr(AC)+chr(81)//?elseif(ord(c)=DF) then result:=chr(EF)+chr(AC)+chr(82)//?elseif(ord(c)=E0) then result:=chr(E2)+chr(80)+chr(A1)//‡elseif(ord(c)=E1) then result:=chr(C2)+chr(B7) // ·
else if (ord(c) = E2)thenresult:=chr(E2)+chr(80)+chr(9A) // ‚
else if (ord(c) = E3)thenresult:=chr(E2)+chr(80)+chr(9E) // „
else if (ord(c) = E4)thenresult:=chr(E2)+chr(80)+chr(B0) // ‰
else if (ord(c) = E5)thenresult:=chr(C3)+chr(82)//Вelseif(ord(c)=E6) then result:=chr(C3)+chr(8A) // К
else if (ord(c) = E7)thenresult:=chr(C3)+chr(81)//Бelseif(ord(c)=E8) then result:=chr(C3)+chr(8B) // Л
else if (ord(c) = E9)thenresult:=chr(C3)+chr(88)//Иelseif(ord(c)=EA) then result:=chr(C3)+chr(8D) // Н
else if (ord(c) = EB)thenresult:=chr(C3)+chr(8E)//Оelseif(ord(c)=EC) then result:=chr(C3)+chr(8F) // П
else if (ord(c) = ED)thenresult:=chr(C3)+chr(8C)//Мelseif(ord(c)=EE) then result:=chr(C3)+chr(93) // У
else if (ord(c) = EF)thenresult:=chr(C3)+chr(94)//Фelseif(ord(c)=F0) then result:=chr(EE)+chr(80)+chr(9E)//?elseif(ord(c)=F1) then result:=chr(C3)+chr(92) // Т
else if (ord(c) = F2)thenresult:=chr(C3)+chr(9A)//Ъelseif(ord(c)=F3) then result:=chr(C3)+chr(9B) // Ы
else if (ord(c) = F4)thenresult:=chr(C3)+chr(99)//Щelseif(ord(c)=F5) then result:=chr(C4)+chr(B1) // i
else if (ord(c) = F6)thenresult:=chr(CB)+chr(86)//€elseif(ord(c)=F7) then result:=chr(CB)+chr(9C) //
else if (ord(c) = F8)thenresult:=chr(C2)+chr(AF)//Їelseif(ord(c)=F9) then result:=chr(CB)+chr(98) // ?
else if (ord(c) = FA)thenresult:=chr(CB)+chr(99)//?elseif(ord(c)=FB) then result:=chr(CB)+chr(9A) // °
else if (ord(c) = FC)thenresult:=chr(C2)+chr(B8)//ёelseif(ord(c)=FD) then result:=chr(CB)+chr(9D) // ?
else if (ord(c) = FE)thenresult:=chr(CB)+chr(9B)//?elseif(ord(c)=FF) then result:=chr(CB)+chr(87) // ?
else result:=c;
end;
// Export d'une string
function readString(ssf:subsubfile):string;
var data:array[0..65535] of char;
s:string;
i:word;
begin
seek(SRFhandler,ssf.fileoffset);
blockread(SRFhandler,data,ssf.filesize);
s:='';
for i:=0 to ssf.filesize-1 do begin
if (data[i] <> #00) then begin
if (data[i] = '''') then s:=s+'';
s:=s+MactoUTF8(data[i]);
end;
end;
result:=s;
end;
procedure exportStringToFile(ssf:subsubfile;filename:string);
var f:system.text;
begin
assignfile(f,filename+'.js');
rewrite(f);
writeln(f,'res[''string'']='''+readString(ssf)+'''};');
closefile(f);
end;
// Export d'une stringlist sйparйe par des zйros
function exportStringlist(ssf:subsubfile):string;
var data:array[0..65535] of char;
js,s:string;
i:word;
begin
js:='';
seek(SRFhandler,ssf.fileoffset);
blockread(SRFhandler,data,ssf.filesize);
s:='';
for i:=0 to ssf.filesize-1 do begin
if (data[i] <> #00) then begin
if (data[i] = '''') then s:=s+'';
s:=s+MactoUTF8(data[i]);
end else begin
if (s <> '') then begin
if (js <> '') then js:=js+',';
js:=js+''''+s+'''';
s:='';
end;
end;
end;
js:='['+js+']';
exportStringlist:=js;
end;
// Export d'une stringlist sйparйe par des zйros (2eme mйthode)
function exportStringlist1(ssf:subsubfile):string;
var data:array[0..65535] of char;
totaljs,js,s:string;
i,nbw:word;
begin
totaljs:='';
seek(SRFhandler,ssf.fileoffset);
blockread(SRFhandler,data,ssf.filesize);
s:='';
i:=1;
while (i < ssf.filesize) do begin
nbw:=ord(data[i]);
inc(i);
js:='';
while (i < ssf.filesize) and (nbw > 0) do begin
if (data[i] <> #00) then begin
if (data[i] = '''') then s:=s+'';
s:=s+MactoUTF8(data[i]);
end else begin
if (s <> '') then begin
if (js <> '') then js:=js+',';
js:=js+''''+s+'''';
s:='';
dec(nbw);
end;
end;
inc(i);
end;
if (totaljs <> '') then totaljs:=totaljs+',';
totaljs:=totaljs+'['+js+']';
end;
exportStringlist1:='['+totaljs+']';
end;
// Export d'une stringlist avec nombre de mots et taille de chaine
function exportStringlist2(ssf:subsubfile):string;
var data:array[0..65535] of char;
js,s:string;
i,j,nbstr,strlength:word;
begin
js:='[';
seek(SRFhandler,ssf.fileoffset);
blockread(SRFhandler,data,ssf.filesize);
nbstr:=ord(data[0])*$FF+ord(data[1]);
s:='';
i:=2;
while nbstr > 0 do begin
strlength:=ord(data[i]);inc(i);
for j:=1 to strlength do begin
if (data[i] = '''') then s:=s+'';
s:=s+MactoUTF8(data[i]);inc(i);
end;
js:=js+''''+s+'''';
if (nbstr > 1) then js:=js+',';
s:='';
dec(nbstr);
end;
js:=js+']';
exportStringlist2:=js;
end;
// Export des rйponses
function exportAnswers(ssf:subsubfile):string;
var data:array[0..65535] of byte;
js:string;
i:word;
nbans:longint;
begin
js:='[';
seek(SRFhandler,ssf.fileoffset);
blockread(SRFhandler,data,ssf.filesize);
nbans:=data[0]FFFFFF+data[1]∗FFFF+data[2]$FF+data[3];
i:=4;
while nbans > 0 do begin
js:=js+inttostr(data[i]);inc(i);
if (nbans > 1) then js:=js+',';
dec(nbans);
end;
js:=js+']';
exportAnswers:=js;
end;
// Export des QHDR
procedure exportQHeadersToFile(ssf:subsubfile);
var data:array[0..65535] of char;
id,title,filename,force:string;
i:word;
value,qtype,qsubtype,answer:byte;
begin
seek(SRFhandler,ssf.fileoffset);
blockread(SRFhandler,data,ssf.filesize);
id:='';
for i:=2 to 5 do begin
id:=id+MactoUTF8(data[i]);
end;
value:=ord(data[8]);
qtype:=ord(data[9]);
qsubtype:=ord(data[11]);
title:='';
for i:=16 to 80 do begin
if (data[i] <> #00) then begin
title:=title+MactoUTF8(data[i]);
end else break;
end;
filename:='';
for i:=81 to 145 do begin
if (data[i] <> #00) then begin
filename:=filename+MactoUTF8(data[i]);
end else break;
end;
answer:=ord(data[146]);
force:='';
if (ssf.filesize >= 152) then for i:=150 to 152 do begin
if (data[i] <> #00) then begin
force:=force+MactoUTF8(data[i]);
end else break;
end;
qhdrCSV:=qhdrCSV+'ѕ'+id+'ѕЅѕ'+title+'ѕЅѕ'+filename+'ѕЅѕ'+inttostr(qtype)+'ѕЅѕ'+inttostr(qsubtype)+'ѕЅѕ'+inttostr(value)+'ѕЅѕ'+inttostr(answer)+'ѕЅѕ'+force+'ѕ'+#10;
end;
function filetype(ftype:string):string;
begin
result:='';
if (ftype='off4') then result:='subimages';
if (ftype='snd') then result:='subsound';
if (ftype[1]='M') and (ftype <> 'Mtch') then result:='subsound';
if (ftype='STR') then result:='string';
if (ftype='STRL') then result:='stringlist';
if (ftype='Wrds') then result:='stringlist1';
if (ftype='Dcoy') then result:='stringlist';
if (ftype='Mtch') then result:='stringlist';
if (ftype='Root') then result:='stringlist';
// Utilisйs pour le Couci-Couзa, entre autres
if (ftype='ANS#') then result:='answers';
if (ftype='STR#') then result:='stringlist2';
// Rimatologie
if (ftype='Ansr') then result:='string';
if (ftype='Gibr') then result:='string';
if (ftype='Gory') then result:='string';
if (ftype='Hnt1') then result:='string';
if (ftype='Hnt2') then result:='string';
if (ftype='Hnt3') then result:='string';
if (ftype='qhdr') then result:='qheaders';
end;
// Lecture du fichier SRF
function openSRF(filename:string):shortint;
var buf:array[0..3] of byte;
headersize,currentpos:longint;
i,subcount:longword;
begin
closeSRF;
assignfile(SRFhandler,filename);
FileMode := fmOpenRead;
reset(SRFhandler,1);
blockread(SRFhandler,buf,4);
if (buf[0] <> 73)and(buf[1]<>72) and (buf[2] <> 66)and(buf[3]<>31) then begin // srf1
closeSRF;
result:=-1;
exit;
end;
SRFdata.loaded:=true;
readlw; // archivesize
headersize:=readlw;
SRFdata.nbfiles:=0;
while filepos(SRFhandler) < headersize do with SRFdata.filelist[SRFdata.nbfiles] do begin
blockread(SRFhandler,buf,4);
subcount:=readlw;
ftype:=chr(buf[0])+chr(buf[1])+chr(buf[2])+chr(buf[3]);
while ftype[length(ftype)] = ' ' do delete(ftype,length(ftype),1);
nbsub:=subcount;
if (nbsub > 1000) then raise Exception.create('Too many subfiles');
if (subcount > 0) then for i:=0 to subcount-1 do begin
subfile[i].subname:=readlw;
subfile[i].fileoffset:=readlw;
subfile[i].filesize:=readlw;
currentpos:=filepos(SRFhandler);
seek(SRFhandler,subfile[i].fileoffset);
if (filetype(ftype)='subimages') then begin
subfile[i].data:=openSubimages(subfile[i].filesize);
end else if (filetype(ftype)='subsound') then begin
subfile[i].data:=openSubsound(subfile[i].filesize);
end else begin
subfile[i].data:=nil;
end;
seek(SRFhandler,currentpos);
end;
inc(SRFdata.nbfiles);
if (SRFdata.nbfiles > 255) then raise Exception.Create('Too many nbfiles');
end;
result:=0;
end;
function idfileoff4:word;
var i:word;
begin
result:=9999; // Oui, drфle de n° de code d'erreur, mais bon, on est en unsigned...
if (SRFdata.nbfiles > 0) then
for i:=0 to SRFdata.nbfiles-1 do if (SRFdata.filelist[i].ftype = 'off4') then result:=i;
end;
procedure closeSRF;
var i,j:word;
begin
if SRFdata.loaded then closefile(SRFhandler);
if (SRFdata.nbfiles > 0) then for i:=0 to SRFdata.nbfiles-1 do begin
if (SRFdata.filelist[i].nbsub > 0) then for j:=0 to SRFdata.filelist[i].nbsub-1 do Freemem(SRFdata.filelist[i].subfile[j].data);
end;
SRFdata.nbfiles:=0;
SRFdata.loaded:=false;
end;
begin
InitColors;
SRFdata.loaded:=false;
closeSRF;
end.
procedure TForm1.Button3Click(Sender: TObject);
var i:word;
off4:^subimages;
begin
openSRF(SRFbasedir+SRFList.Items[SRFList.ItemIndex]);
ComboBox1.Items.Clear;
if (idfileoff4 < 9999) then begin
off4:=SRFdata.filelist[idfileoff4].subfile[0].data;
if off4^.nbimages > 0 then begin
for i:=0 to off4^.nbimages-1 do begin
ComboBox1.Items.Add(inttostr(i));
end;
end;
ComboBox1.Enabled:=true;
ComboBox1.ItemIndex:=0;
end;
Button4.Enabled:=true;
end;
var graphic:array[0..307200] of byte;
picture:array[0..307200] of longint;
procedure TForm1.ComboBox1Change(Sender: TObject);
var pos, graphlen: longint;
pic:TPicture;
x,y:word;
w,h:word;
off4:^subimages;
begin
off4:=SRFdata.filelist[idfileoff4].subfile[0].data;
seek(SRFhandler,off4^.images[ComboBox1.ItemIndex].offset);
w:=off4^.images[ComboBox1.ItemIndex].width;
h:=off4^.images[ComboBox1.ItemIndex].height;
blockread(SRFhandler,graphic,307200,graphlen);
decodeImageBuffer(graphic,picture,w*h);
// Dessin а partir de longbitmap
pic:=TPicture.Create;
pic.Bitmap.Width:=PaintBox1.Width;
pic.Bitmap.Height:=PaintBox1.Height;
x:=0;
y:=0;
pos:=0;
Label1.Caption:='';
while y < h do begin
pic.Bitmap.Canvas.Pixels[x,y] := picture[pos];
inc(pos);
inc(x);
if (x >= w) then begin
x:=0;
inc(y);
end;
end;
PaintBox1.Canvas.CopyRect(pic.Bitmap.Canvas.ClipRect, pic.Bitmap.Canvas, PaintBox1.Canvas.ClipRect);
end;
function RemoveBaseDir(basedir,s:string):string;
begin
if copy(s,1,length(basedir)) = basedir then result:=copy(s,length(basedir)+1,255)
else result:=s;
end;
function IncludeTrailingBackSlash2(s:string):string;
begin
if s[length(s)] <> '' then s:=s+'';
result:=s;
end;
function RemoveExt(s:string):string;
var ns:string;
begin
ns:=s;
while (length(ns) > 0) and (ns[length(ns)] <> '.') do delete(ns,length(ns),1);
delete(ns,length(ns),1);
if (length(ns) > 0) then result:=ns else result:=s;
end;
procedure FileSearch(const dirName:string);
var
searchResult: TSearchRec;
begin
if FindFirst(dirName+'*', faAnyFile, searchResult)=0 then begin
try
repeat
if (searchResult.Attr and faDirectory)=0 then begin
if SameText(ExtractFileExt(searchResult.Name), '.SRF') then begin
form1.SRFList.Items.Append(RemoveBaseDir(SRFbasedir,IncludeTrailingBackSlash2(dirName)+searchResult.Name));
end;
end else if (searchResult.Name<>'.') and (searchResult.Name<>'..') then begin
FileSearch(IncludeTrailingBackSlash2(dirName)+searchResult.Name);
end;
until FindNext(searchResult)<>0
finally
FindClose(searchResult);
end;
end;
end;
if (paramcount = 2) then begin
Edit1.Text := paramstr(1);
Edit2.Text := paramstr(2);
Button1.Click;
end;
end;
function SafeFileName(filename:string):string;
var i:word;
begin
i:=length(filename)-1;
while (i>0) do begin
if (filename[i] = '') and (filename[i+1] = '') then delete(filename,i,1);
dec(i);
end;
result:=filename;
end;
function removespaces(s:string):string;
var t:string;
i:word;
begin
t:='';
for i:=1 to length(s) do begin
if (s[i] <> ' ') then if (s[i] = '#') then t:=t+'0' else t:=t+s[i];
end;
result:=t;
end;
procedure TForm1.Button4Click(Sender: TObject);
var filepos,subpos:word;
fullname,ftype:string;
strings:string;
f:system.text;
begin
strings:='';
if SRFdata.nbfiles > 0 then for filepos:=0 to SRFdata.nbfiles-1 do begin
ftype:=SRFdata.filelist[filepos].ftype;
// if (filetype(ftype)='string') then // Considйrer que c'est une liste de chaines, а exporter en un seul fichier JS
code
if SRFdata.filelist[filepos].nbsub > 0 then for subpos:=0 to SRFdata.filelist[filepos].nbsub-1 do begin
if (filetype(ftype)<>'string') then begin
fullname:=RemoveExt(SafeFileName(GetCurrentDir()+'\'+resbasedir+SRFList.Items[SRFList.ItemIndex]))+'\'+removespaces(ftype);
ForceDirectories(fullname);
fullname:=fullname+'\'+inttostr(SRFdata.filelist[filepos].subfile[subpos].subname);
if (filetype(ftype)='subimages') then begin
exportSubimagesToGif(SRFdata.filelist[filepos].subfile[subpos],fullname);
end else if (filetype(ftype)='subsound') then begin
exportSubsoundToFile(SRFdata.filelist[filepos].subfile[subpos],fullname);
end else if (filetype(ftype)='string') then begin
//exportStringToFile(SRFdata.filelist[filepos].subfile[subpos],fullname);
end else if (filetype(ftype)='stringlist') then begin
if (strings <> '') then strings:=strings+',';
strings:=strings+'{id:'''+ftype+''',data:{'+exportStringlist(SRFdata.filelist[filepos].subfile[subpos])+'}';
end;
end else begin
strings:=strings+'{id:'+inttostr(SRFdata.filelist[filepos].subfile[subpos].subname)+',type:'''+ftype+''',str:'''+readString(SRFdata.filelist[filepos].subfile[subpos])+'''},';
end;
end;
end;
if (strings <> '') then begin
fullname:=RemoveExt(SafeFileName(GetCurrentDir()+''+resbasedir+SRFList.Items[SRFList.ItemIndex]));
ForceDirectories(fullname);
fullname:=fullname+'\STR.js';
assignfile(f,fullname);
rewrite(f);
write(f,'res[''STR'']=['+strings+'];');
closefile(f);
end;
Label1.Caption:='Conversion complete.';
end;
procedure convertSRF(filefrom:string);
var filepos,subpos:word;
fullname,ftype:string;
strings:string;
//f:system.text;
begin
strings:='';
try
openSRF(filefrom);
if SRFdata.nbfiles > 0 then for filepos:=0 to SRFdata.nbfiles-1 do begin
ftype:=SRFdata.filelist[filepos].ftype;
// if (filetype(ftype)='string') then // Considйrer que c'est une liste de chaines, а exporter en un seul fichier JS
code
if SRFdata.filelist[filepos].nbsub > 0 then for subpos:=0 to SRFdata.filelist[filepos].nbsub-1 do begin
if (filetype(ftype)='string') then begin
if (strings <> '') then strings:=strings+',';
strings:=strings+'{id:'+inttostr(SRFdata.filelist[filepos].subfile[subpos].subname)+',type:'''+ftype+''',data:'''+readString(SRFdata.filelist[filepos].subfile[subpos])+'''}';
end else if (filetype(ftype)='stringlist') then begin
if (strings <> '') then strings:=strings+',';
strings:=strings+'{id:'+inttostr(SRFdata.filelist[filepos].subfile[subpos].subname)+',type:'''+ftype+''',data:'+exportStringlist(SRFdata.filelist[filepos].subfile[subpos])+'}';
end else if (filetype(ftype)='stringlist1') then begin
if (strings <> '') then strings:=strings+',';
strings:=strings+'{id:'+inttostr(SRFdata.filelist[filepos].subfile[subpos].subname)+',type:'''+ftype+''',data:'+exportStringlist1(SRFdata.filelist[filepos].subfile[subpos])+'}';
end else if (filetype(ftype)='stringlist2') then begin
if (strings <> '') then strings:=strings+',';
strings:=strings+'{id:'+inttostr(SRFdata.filelist[filepos].subfile[subpos].subname)+',type:'''+ftype+''',data:'+exportStringlist2(SRFdata.filelist[filepos].subfile[subpos])+'}';
end else if (filetype(ftype)='answers') then begin
if (strings <> '') then strings:=strings+',';
strings:=strings+'{id:'+inttostr(SRFdata.filelist[filepos].subfile[subpos].subname)+',type:'''+ftype+''',data:'+exportAnswers(SRFdata.filelist[filepos].subfile[subpos])+'}';
end else begin
fullname:=RemoveExt(SafeFileName(Form1.Edit2.Text+'\'+RemoveBaseDir(Form1.Edit1.Text,filefrom)))+'\'+removespaces(ftype);
ForceDirectories(fullname);
fullname:=fullname+'\'+inttostr(SRFdata.filelist[filepos].subfile[subpos].subname);
if (filetype(ftype)='subimages') then begin
exportSubimagesToGif(SRFdata.filelist[filepos].subfile[subpos],fullname);
end else if (filetype(ftype)='subsound') then begin
exportSubsoundToFile(SRFdata.filelist[filepos].subfile[subpos],fullname);
end else if (filetype(ftype)='qheaders') then begin
exportQHeadersToFile(SRFdata.filelist[filepos].subfile[subpos]);
end;
end;
end;
end;
except on E : Exception do begin
Form1.Memo1.Lines.Add('Couldn''t open ('+E.ClassName+': '+E.Message+')');
end;
end;
try
closeSRF;
except
end;
if (strings <> '') then begin
{fullname:=RemoveExt(SafeFileName(Form1.Edit2.Text+''+RemoveBaseDir(Form1.Edit1.Text,filefrom)));
ForceDirectories(fullname);
fullname:=fullname+'\STR.js';
assignfile(f,fullname);
rewrite(f);
write(f,'res[''STR'']=['+strings+'];');
closefile(f);}
stringsCSV:=stringsCSV+'ѕ'+RemoveExt(RemoveBaseDir(Form1.Edit1.Text,filefrom))+'ѕЅѕ['+strings+']ѕ'#10;
end;
end;
procedure convertRecursive(const dirName:string);
var
searchResult: TSearchRec;
begin
if FindFirst(dirName+'*', faAnyFile, searchResult)=0 then begin
try
repeat
if (searchResult.Attr and faDirectory)=0 then begin
if SameText(ExtractFileExt(searchResult.Name), '.SRF') then begin
Form1.Memo1.Lines.Add(IncludeTrailingBackSlash2(dirName)+searchResult.Name);
convertSRF(IncludeTrailingBackSlash2(dirName)+searchResult.Name);
end;
end else if (searchResult.Name<>'.') and (searchResult.Name<>'..') then begin
convertRecursive(IncludeTrailingBackSlash2(dirName)+searchResult.Name);
end;
until FindNext(searchResult)<>0
finally
FindClose(searchResult);
end;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var fullname:string;
f:system.text;
begin
Memo1.Clear;
qhdrCSV:='';
stringsCSV:='';
convertRecursive(Edit1.Text);
if (qhdrCSV <> '') then begin
fullname:=SafeFileName(Form1.Edit2.Text)+'\qhdr.csv';
assignfile(f,fullname);
rewrite(f);
write(f,qhdrCSV);
closefile(f);
end;
if (stringsCSV <> '') then begin
fullname:=SafeFileName(Form1.Edit2.Text)+'\strings.csv';
assignfile(f,fullname);
rewrite(f);
write(f,stringsCSV);
closefile(f);
end;
Memo1.Lines.Add('Conversion done.');
end;
procedure TForm1.Button3Click(Sender: TObject);
var i:word;
off4:^subimages;
begin
openSRF(SRFbasedir+SRFList.Items[SRFList.ItemIndex]);
ComboBox1.Items.Clear;
if (idfileoff4 < 9999) then begin
off4:=SRFdata.filelist[idfileoff4].subfile[0].data;
if off4^.nbimages > 0 then begin
for i:=0 to off4^.nbimages-1 do begin
ComboBox1.Items.Add(inttostr(i));
end;
end;
ComboBox1.Enabled:=true;
ComboBox1.ItemIndex:=0;
end;
Button4.Enabled:=true;
end;
var graphic:array[0..307200] of byte;
picture:array[0..307200] of longint;
procedure TForm1.ComboBox1Change(Sender: TObject);
var pos, graphlen: longint;
pic:TPicture;
x,y:word;
w,h:word;
off4:^subimages;
begin
off4:=SRFdata.filelist[idfileoff4].subfile[0].data;
seek(SRFhandler,off4^.images[ComboBox1.ItemIndex].offset);
w:=off4^.images[ComboBox1.ItemIndex].width;
h:=off4^.images[ComboBox1.ItemIndex].height;
blockread(SRFhandler,graphic,307200,graphlen);
decodeImageBuffer(graphic,picture,w*h);
// Dessin а partir de longbitmap
pic:=TPicture.Create;
pic.Bitmap.Width:=PaintBox1.Width;
pic.Bitmap.Height:=PaintBox1.Height;
x:=0;
y:=0;
pos:=0;
Label1.Caption:='';
while y < h do begin
pic.Bitmap.Canvas.Pixels[x,y] := picture[pos];
inc(pos);
inc(x);
if (x >= w) then begin
x:=0;
inc(y);
end;
end;
PaintBox1.Canvas.CopyRect(pic.Bitmap.Canvas.ClipRect, pic.Bitmap.Canvas, PaintBox1.Canvas.ClipRect);
end;
function RemoveBaseDir(basedir,s:string):string;
begin
if copy(s,1,length(basedir)) = basedir then result:=copy(s,length(basedir)+1,255)
else result:=s;
end;
function IncludeTrailingBackSlash2(s:string):string;
begin
if s[length(s)] <> '' then s:=s+'';
result:=s;
end;
function RemoveExt(s:string):string;
var ns:string;
begin
ns:=s;
while (length(ns) > 0) and (ns[length(ns)] <> '.') do delete(ns,length(ns),1);
delete(ns,length(ns),1);
if (length(ns) > 0) then result:=ns else result:=s;
end;
procedure FileSearch(const dirName:string);
var
searchResult: TSearchRec;
begin
if FindFirst(dirName+'*', faAnyFile, searchResult)=0 then begin
try
repeat
if (searchResult.Attr and faDirectory)=0 then begin
if SameText(ExtractFileExt(searchResult.Name), '.SRF') then begin
form1.SRFList.Items.Append(RemoveBaseDir(SRFbasedir,IncludeTrailingBackSlash2(dirName)+searchResult.Name));
end;
end else if (searchResult.Name<>'.') and (searchResult.Name<>'..') then begin
FileSearch(IncludeTrailingBackSlash2(dirName)+searchResult.Name);
end;
until FindNext(searchResult)<>0
finally
FindClose(searchResult);
end;
end;
end;
if (paramcount = 2) then begin
Edit1.Text := paramstr(1);
Edit2.Text := paramstr(2);
Button1.Click;
end;
end;
function SafeFileName(filename:string):string;
var i:word;
begin
i:=length(filename)-1;
while (i>0) do begin
if (filename[i] = '') and (filename[i+1] = '') then delete(filename,i,1);
dec(i);
end;
result:=filename;
end;
function removespaces(s:string):string;
var t:string;
i:word;
begin
t:='';
for i:=1 to length(s) do begin
if (s[i] <> ' ') then if (s[i] = '#') then t:=t+'0' else t:=t+s[i];
end;
result:=t;
end;
procedure TForm1.Button4Click(Sender: TObject);
var filepos,subpos:word;
fullname,ftype:string;
strings:string;
f:system.text;
begin
strings:='';
if SRFdata.nbfiles > 0 then for filepos:=0 to SRFdata.nbfiles-1 do begin
ftype:=SRFdata.filelist[filepos].ftype;
// if (filetype(ftype)='string') then // Considйrer que c'est une liste de chaines, а exporter en un seul fichier JS
code
if SRFdata.filelist[filepos].nbsub > 0 then for subpos:=0 to SRFdata.filelist[filepos].nbsub-1 do begin
if (filetype(ftype)<>'string') then begin
fullname:=RemoveExt(SafeFileName(GetCurrentDir()+'\'+resbasedir+SRFList.Items[SRFList.ItemIndex]))+'\'+removespaces(ftype);
ForceDirectories(fullname);
fullname:=fullname+'\'+inttostr(SRFdata.filelist[filepos].subfile[subpos].subname);
if (filetype(ftype)='subimages') then begin
exportSubimagesToGif(SRFdata.filelist[filepos].subfile[subpos],fullname);
end else if (filetype(ftype)='subsound') then begin
exportSubsoundToFile(SRFdata.filelist[filepos].subfile[subpos],fullname);
end else if (filetype(ftype)='string') then begin
//exportStringToFile(SRFdata.filelist[filepos].subfile[subpos],fullname);
end else if (filetype(ftype)='stringlist') then begin
if (strings <> '') then strings:=strings+',';
strings:=strings+'{id:'''+ftype+''',data:{'+exportStringlist(SRFdata.filelist[filepos].subfile[subpos])+'}';
end;
end else begin
strings:=strings+'{id:'+inttostr(SRFdata.filelist[filepos].subfile[subpos].subname)+',type:'''+ftype+''',str:'''+readString(SRFdata.filelist[filepos].subfile[subpos])+'''},';
end;
end;
end;
if (strings <> '') then begin
fullname:=RemoveExt(SafeFileName(GetCurrentDir()+''+resbasedir+SRFList.Items[SRFList.ItemIndex]));
ForceDirectories(fullname);
fullname:=fullname+'\STR.js';
assignfile(f,fullname);
rewrite(f);
write(f,'res[''STR'']=['+strings+'];');
closefile(f);
end;
Label1.Caption:='Conversion complete.';
end;
procedure convertSRF(filefrom:string);
var filepos,subpos:word;
fullname,ftype:string;
strings:string;
//f:system.text;
begin
strings:='';
try
openSRF(filefrom);
if SRFdata.nbfiles > 0 then for filepos:=0 to SRFdata.nbfiles-1 do begin
ftype:=SRFdata.filelist[filepos].ftype;
// if (filetype(ftype)='string') then // Considйrer que c'est une liste de chaines, а exporter en un seul fichier JS
code
if SRFdata.filelist[filepos].nbsub > 0 then for subpos:=0 to SRFdata.filelist[filepos].nbsub-1 do begin
if (filetype(ftype)='string') then begin
if (strings <> '') then strings:=strings+',';
strings:=strings+'{id:'+inttostr(SRFdata.filelist[filepos].subfile[subpos].subname)+',type:'''+ftype+''',data:'''+readString(SRFdata.filelist[filepos].subfile[subpos])+'''}';
end else if (filetype(ftype)='stringlist') then begin
if (strings <> '') then strings:=strings+',';
strings:=strings+'{id:'+inttostr(SRFdata.filelist[filepos].subfile[subpos].subname)+',type:'''+ftype+''',data:'+exportStringlist(SRFdata.filelist[filepos].subfile[subpos])+'}';
end else if (filetype(ftype)='stringlist1') then begin
if (strings <> '') then strings:=strings+',';
strings:=strings+'{id:'+inttostr(SRFdata.filelist[filepos].subfile[subpos].subname)+',type:'''+ftype+''',data:'+exportStringlist1(SRFdata.filelist[filepos].subfile[subpos])+'}';
end else if (filetype(ftype)='stringlist2') then begin
if (strings <> '') then strings:=strings+',';
strings:=strings+'{id:'+inttostr(SRFdata.filelist[filepos].subfile[subpos].subname)+',type:'''+ftype+''',data:'+exportStringlist2(SRFdata.filelist[filepos].subfile[subpos])+'}';
end else if (filetype(ftype)='answers') then begin
if (strings <> '') then strings:=strings+',';
strings:=strings+'{id:'+inttostr(SRFdata.filelist[filepos].subfile[subpos].subname)+',type:'''+ftype+''',data:'+exportAnswers(SRFdata.filelist[filepos].subfile[subpos])+'}';
end else begin
fullname:=RemoveExt(SafeFileName(Form1.Edit2.Text+'\'+RemoveBaseDir(Form1.Edit1.Text,filefrom)))+'\'+removespaces(ftype);
ForceDirectories(fullname);
fullname:=fullname+'\'+inttostr(SRFdata.filelist[filepos].subfile[subpos].subname);
if (filetype(ftype)='subimages') then begin
exportSubimagesToGif(SRFdata.filelist[filepos].subfile[subpos],fullname);
end else if (filetype(ftype)='subsound') then begin
exportSubsoundToFile(SRFdata.filelist[filepos].subfile[subpos],fullname);
end else if (filetype(ftype)='qheaders') then begin
exportQHeadersToFile(SRFdata.filelist[filepos].subfile[subpos]);
end;
end;
end;
end;
except on E : Exception do begin
Form1.Memo1.Lines.Add('Couldn''t open ('+E.ClassName+': '+E.Message+')');
end;
end;
try
closeSRF;
except
end;
if (strings <> '') then begin
{fullname:=RemoveExt(SafeFileName(Form1.Edit2.Text+''+RemoveBaseDir(Form1.Edit1.Text,filefrom)));
ForceDirectories(fullname);
fullname:=fullname+'\STR.js';
assignfile(f,fullname);
rewrite(f);
write(f,'res[''STR'']=['+strings+'];');
closefile(f);}
stringsCSV:=stringsCSV+'ѕ'+RemoveExt(RemoveBaseDir(Form1.Edit1.Text,filefrom))+'ѕЅѕ['+strings+']ѕ'#10;
end;
end;
procedure convertRecursive(const dirName:string);
var
searchResult: TSearchRec;
begin
if FindFirst(dirName+'*', faAnyFile, searchResult)=0 then begin
try
repeat
if (searchResult.Attr and faDirectory)=0 then begin
if SameText(ExtractFileExt(searchResult.Name), '.SRF') then begin
Form1.Memo1.Lines.Add(IncludeTrailingBackSlash2(dirName)+searchResult.Name);
convertSRF(IncludeTrailingBackSlash2(dirName)+searchResult.Name);
end;
end else if (searchResult.Name<>'.') and (searchResult.Name<>'..') then begin
convertRecursive(IncludeTrailingBackSlash2(dirName)+searchResult.Name);
end;
until FindNext(searchResult)<>0
finally
FindClose(searchResult);
end;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var fullname:string;
f:system.text;
begin
Memo1.Clear;
qhdrCSV:='';
stringsCSV:='';
convertRecursive(Edit1.Text);
if (qhdrCSV <> '') then begin
fullname:=SafeFileName(Form1.Edit2.Text)+'\qhdr.csv';
assignfile(f,fullname);
rewrite(f);
write(f,qhdrCSV);
closefile(f);
end;
if (stringsCSV <> '') then begin
fullname:=SafeFileName(Form1.Edit2.Text)+'\strings.csv';
assignfile(f,fullname);
rewrite(f);
write(f,stringsCSV);
closefile(f);
end;
Memo1.Lines.Add('Conversion done.');
end;
end.
You've provided a substantial amount of Delphi code, which appears to involve several components for handling graphics, sound, and possibly some form of data extraction from a custom file format (SRF). Your project involves operations such as loading sub-images, decoding sound files, exporting data to various formats (like GIF, WAV, and JavaScript), and file searching.
Here are some general tips to consider as you work with this kind of Delphi project:
Code Organization: Structure your code into separate units meaningfully. You've already done this to some extent with YDKJUnit and Unit1. Ensure that each unit has a clear responsibility to improve maintainability. Consider separating the file handling, data structures, and the GUI logic into different units.
Error Handling: While you've included some error handling, ensure you handle exceptions gracefully throughout your application. For file operations, user interaction, and data processing, proper error handling will improve the user experience significantly by avoiding crashes or undefined behaviors.
Memory Management: Given that you allocate memory for structures like subimages and subsound using GetMem, ensure that you also free this memory correctly using FreeMem in the closeSRF method to prevent memory leaks.
Efficiency: If you work with large files or numerous operations (like graphics decoding), you might want to consider profiling your application to identify any bottlenecks. Check memory usage and consider using more efficient data structures if necessary.
User Interface: For the parts of your code that involve the user interface (like showing status in Memo1 or refreshing ComboBox1), ensure that these updates are done in a responsive way. If you perform lengthy operations (like reading files), consider using threads or background tasks to keep the UI responsive.
Project Documentation: Make sure to document your code thoroughly. Explain what each function does, the purpose of the main variables, parameters, return values, and any specific algorithm used. This will be beneficial for any future maintenance or updates.
Testing: Consider writing tests for critical parts of your application, especially the data processing parts. Automated tests can verify that everything works as expected after changes are made, thus avoiding regression.
Version Control: Always use version control for your project. This will help you track changes, collaborate with others, and revert to previous states if necessary.
Library Usage: Ensure that any libraries you utilize (like GifImage for handling GIFs) are actively maintained and suitable for your project’s needs. If you find that a library no longer meets your needs, look into alternatives.
User Feedback: As you develop and refine the usability of your tool, consider getting user feedback to improve the interface and workflow. This insight can guide you in changes that genuinely enhance user experience.
If you have specific questions or need help with certain parts of the code, feel free to ask!
Перенос системы извлечения изображений на Python требует несколько этапов. Мы будем использовать библиотеку PIL (Pillow) для работы с изображениями, а также стандартные библиотеки Python для обработки данных.
Давайте разберёмся, как можно выполнить ту же задачу, что и в вашем коде Delphi, в Python. Предположим, что у вас есть бинарный файл, который хранит недостаточную информацию о палитре и изображениях. Мы будем сначала загружать данные палитры, а затем извлекать изображения и записывать их в формате PNG или GIF.
Шаг 1: Установка необходимых библиотек
Вам нужно установить библиотеку Pillow, если она не установлена:
bash
pip install Pillow
Шаг 2: Подготовка базового кода
Ниже приведён пример кода, который демонстрирует, как загрузить палитру и изображение из бинарного файла, декодировать его и сохранить в качестве изображения.
python
import struct
from PIL import Image
# Функция для загрузки палитры
def load_palette(palette_file):
palette_image = Image.open(palette_file)
palette_image = palette_image.convert('RGB')
return list(palette_image.getdata())
# Функция для декодирования изображения
def decode_image(buffer, palette, width, height):
# Предполагаем, что буфер данных изображения представлен пикселями по 8 бит (индексы палитры)
image_data = []
for pixel in buffer:
color = palette[pixel] # Получаем RGB цвет по индексу
image_data.extend(color) # Добавляем RGB в выходной массив
# Создаем изображение
img = Image.new('RGB', (width, height))
img.putdata(image_data)
return img
# Основной процесс извлечения изображений
def extract_image_from_file(file_path, palette_file):
with open(file_path, 'rb') as file:
# Пример чтения заголовка и получения ширины/высоты (настраивайте в зависимости от вашего формата)
width = struct.unpack('H', file.read(2))[0] # Чтение ширины
height = struct.unpack('H', file.read(2))[0] # Чтение высоты
# Читаем буфер изображения
buffer = bytearray(file.read(width * height)) # Загрузка всего изображения
# Загружаем палитру
palette = load_palette(palette_file)
# Декодируем изображение
image = decode_image(buffer, palette, width, height)
# Сохраняем изображение
image.save('extracted_image.png')
# Пример использования
extract_image_from_file('path/to/your/srf/file.srf', 'path/to/your/palette.bmp')
Шаг 3: Настройка кода под ваш формат
Чтение файла: Измените логику чтения заголовка и получения ширины и высоты в зависимости от формата вашего файла SRF.
Чтение изображений: Убедитесь, что вы правильно читаете буфер изображения. Это может быть представление в байтах, где каждый байт указывает на индекс цвета в палитре. Также проверьте, используете ли вы вертикальные или горизонтальные палитры.
Сохранение: Вы можете сохранить изображения в различных форматах, таких как PNG или GIF, в зависимости от ваших требований.
Заключение
Этот пример кода даёт вам общее представление о том, как можно перенести логику из Delphi в Python для извлечения изображений на основе палитры. Дополнительно проверьте детали специфики вашего формата SRF, чтобы обеспечить правильное извлечение данных.