-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathboatingbash_script.py
More file actions
461 lines (394 loc) · 18.5 KB
/
Copy pathboatingbash_script.py
File metadata and controls
461 lines (394 loc) · 18.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
import struct
import os
import zlib
import re
import tkinter as tk
from tkinter import filedialog
import datetime
# =============================================================================
# --- LOGGING SYSTEM ---
# =============================================================================
class Logger:
def __init__(self):
self.log_file = None
def start(self, output_dir):
timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
self.log_path = os.path.join(output_dir, f"_Extraction_Log_{timestamp}.txt")
self.log_file = open(self.log_path, "w", encoding="utf-8")
self.log(f"--- EXTRACTION STARTED: {timestamp} ---")
def log(self, message):
print(message)
if self.log_file:
self.log_file.write(message + "\n")
self.log_file.flush()
def close(self):
if self.log_file:
self.log("--- EXTRACTION FINISHED ---")
self.log_file.close()
LOG = Logger()
# =============================================================================
# --- UTILITIES ---
# =============================================================================
def read_u32(data, offset):
if offset + 4 > len(data): return 0
return struct.unpack('<I', data[offset:offset+4])[0]
def read_u16(data, offset):
if offset + 2 > len(data): return 0
return struct.unpack('<H', data[offset:offset+2])[0]
def read_float(data, offset):
if offset + 4 > len(data): return 0.0
try: return struct.unpack('<f', data[offset:offset+4])[0]
except: return 0.0
def sanitize_name(name):
return re.sub(r'[<>:"/\\|?*]', '_', name).rstrip('\x00')
# =============================================================================
# --- 1. TEXTURE DESWIZZLER ---
# =============================================================================
def unzip_texture_golden(width, height, data):
linear_data = bytearray(len(data))
idx = 0
for y in range(0, height, 4):
for x in range(0, width, 16):
if idx + 32 > len(data): break
tile_data = data[idx : idx+32]
idx += 32
b0, b1, b2, b3 = tile_data[0:8], tile_data[8:16], tile_data[16:24], tile_data[24:32]
def place(tx, ty, b):
bx, by = tx // 4, ty // 4
off = (by * (width // 4) + bx) * 8
if off + 8 <= len(linear_data): linear_data[off : off+8] = b
place(x, y, b0); place(x+4, y, b1); place(x+8, y, b2); place(x+12, y, b3)
return linear_data
def decode_dds_file(file_path):
try:
with open(file_path, 'rb') as f:
header = bytearray(f.read(128)); data = f.read()
raw_h = struct.unpack('<I', header[12:16])[0]
raw_w = struct.unpack('<I', header[16:20])[0]
height, width = raw_h & 0xFFFF, raw_w & 0xFFFF
if header[84:88] == b'DXT1':
struct.pack_into('<I', header, 12, height)
struct.pack_into('<I', header, 16, width)
decoded = unzip_texture_golden(width, height, data)
with open(file_path, 'wb') as out: out.write(header); out.write(decoded)
return True
except: pass
return False
# =============================================================================
# --- 2. MODEL EXTRACTOR ---
# =============================================================================
def build_material_db(data):
tex_names = []
c = 0
while True:
pos = data.find(b'name', c)
if pos == -1: break
sz = read_u32(data, pos + 4)
if 0 < sz < 256:
try: tex_names.append(data[pos+8:pos+8+sz].decode('utf-8', errors='ignore').rstrip('\x00'))
except: tex_names.append("INVALID")
c = pos + 4
mat_to_tex = {}
mtls_pos = 0; best_mtls = None; max_sz = 0
while True:
pos = data.find(b'MTLS', mtls_pos)
if pos == -1: break
sz = read_u32(data, pos + 4)
if sz > max_sz: max_sz = sz; best_mtls = data[pos+8 : pos+8+sz]
mtls_pos = pos + 4
if best_mtls:
cnt = 0
for i in range(0, len(best_mtls) - 4, 1):
if best_mtls[i+2] == 0x8E and best_mtls[i+3] == 0x29:
idx = read_u16(best_mtls, i)
if idx < len(tex_names): mat_to_tex[cnt] = tex_names[idx]; cnt += 1
return mat_to_tex
def determine_format(vert_data):
dl = len(vert_data) - 8
if dl <= 0: return "Empty", 0, 0
i56, i44 = (dl % 56 == 0), (dl % 44 == 0)
if i56 and i44:
v56, v44 = abs(read_float(vert_data, 52)), abs(read_float(vert_data, 40))
return ("World_56", 56, 44) if v56 > 2.0 and v44 < 2.0 else ("Prop_44", 44, 32)
return ("World_56", 56, 44) if i56 else (("Prop_44", 44, 32) if i44 else ("Prop_Fallback", 44, 32))
def parse_mesh(vert_body, sub_chunks, output_path, mesh_name, mtl_filename):
fmt, stride, pos_off = determine_format(vert_body)
if stride == 0: return
num_verts = (len(vert_body) - 8) // stride
pos, uvs, nrms = [], [], []
for i in range(num_verts):
b = 8 + (i * stride)
pos.append((read_float(vert_body, b+pos_off), read_float(vert_body, b+pos_off+4), read_float(vert_body, b+pos_off+8)))
nrms.append((read_float(vert_body, b+pos_off-12), read_float(vert_body, b+pos_off-8), read_float(vert_body, b+pos_off-4)))
u, v = read_float(vert_body, b + (0 if fmt == "World_56" else 8)), read_float(vert_body, b + (0 if fmt == "World_56" else 8) + 4)
uvs.append((u, 1.0 - v))
with open(output_path, 'w') as f:
f.write(f"mtllib {mtl_filename}\n")
f.write(f"o {mesh_name}\n")
for p in pos: f.write(f"v {p[0]:.6f} {p[1]:.6f} {p[2]:.6f}\n")
for uv in uvs: f.write(f"vt {uv[0]:.6f} {uv[1]:.6f}\n")
for n in nrms: f.write(f"vn {n[0]:.6f} {n[1]:.6f} {n[2]:.6f}\n")
for ch in sub_chunks:
if ch['type'] == 'face':
fd = ch['data']
mat_id = read_u32(fd, 4) & 0xFFFF
f.write(f"\nusemtl Mat_{mat_id}\n")
idxs = [read_u16(fd, 12 + i*2) for i in range((len(fd) - 12) // 2)]
for i in range(len(idxs) - 2):
i1, i2, i3 = idxs[i], idxs[i+1], idxs[i+2]
if i1 == 65535 or i2 == 65535 or i3 == 65535 or i1==i2 or i2==i3 or i1==i3: continue
p1, p2, p3 = i1+1, i2+1, i3+1
f.write(f"f {p3}/{p3}/{p3} {p2}/{p2}/{p2} {p1}/{p1}/{p1}\n" if i%2==1 else f"f {p1}/{p1}/{p1} {p2}/{p2}/{p2} {p3}/{p3}/{p3}\n")
def recursive_model_extract(data, cursor, end, out_dir, counter, mtl_file):
while cursor < end:
if cursor + 8 > end: break
chunk_size = read_u32(data, cursor + 4)
if cursor + 8 + chunk_size > len(data): chunk_size = len(data) - cursor - 8
cid = data[cursor:cursor+4]
if cid == b'RIFF' or cid == b'LIST':
if data[cursor+8:cursor+12] == b'obj ':
mesh_idx = counter[0]; counter[0] += 1
vb, sc, sc_cur, sc_end = None, [], cursor + 12, cursor + 8 + chunk_size
while sc_cur < sc_end:
if sc_cur + 8 > sc_end: break
ssize = read_u32(data, sc_cur+4)
sid = data[sc_cur:sc_cur+4]
if sid == b'vert': vb = data[sc_cur+8 : sc_cur+8+ssize]
elif sid == b'face': sc.append({'type': 'face', 'data': data[sc_cur+8 : sc_cur+8+ssize]})
sc_cur += 8 + ssize + (ssize%2)
if vb and sc:
parse_mesh(vb, sc, os.path.join(out_dir, f"Mesh_{mesh_idx}.obj"), f"Mesh_{mesh_idx}", mtl_file)
else: recursive_model_extract(data, cursor+12, cursor+8+chunk_size, out_dir, counter, mtl_file)
cursor += 8 + chunk_size + (chunk_size % 2)
# =============================================================================
# --- 3. INFLATOR & SCANNING ---
# =============================================================================
def inflate_lfd_data(data):
if len(data) < 12: return data
usz, off = read_u32(data, 4), read_u32(data, 8)
if usz > 200_000_000 or usz == 0 or off > len(data) or off < 12: return data
offsets = []
cur = 8
while cur < off:
val = read_u32(data, cur)
if val is None: break
offsets.append(val)
cur += 4
if not offsets: return data
if offsets[-1] != len(data): offsets.append(len(data))
out = bytearray()
for i in range(len(offsets)-1):
try: out.extend(zlib.decompress(data[offsets[i]:offsets[i+1]]))
except:
try: out.extend(zlib.decompress(data[offsets[i]:offsets[i+1]], -15))
except: pass
return out
def get_internal_name(data):
# Standard LFD name check
limit = min(len(data), 8000)
cur = 0
while cur < limit:
pos = data.find(b'name', cur)
if pos == -1: break
sz = read_u32(data, pos+4)
if 0 < sz < 256:
try: return sanitize_name(data[pos+8:pos+8+sz].decode('utf-8', errors='ignore'))
except: pass
cur = pos + 4
return None
def get_text_file_name(data):
# Looks for TEXTURE_FILE "Name" inside sprite scripts
try:
text_content = data[:1000].decode('utf-8', errors='ignore')
match = re.search(r'TEXTURE_FILE\s+"([^"]+)"', text_content)
if match:
return sanitize_name(match.group(1))
except: pass
return None
def check_content_type(data):
has_assets = False
has_geometry = False
if b'obj ' in data[:100000]: has_geometry = True
else:
if data.find(b'obj ') != -1: has_geometry = True
if b'tex ' in data: has_assets = True
return has_assets, has_geometry
# =============================================================================
# --- 4. PROCESSING (Smart Detector) ---
# =============================================================================
def process_file_content(data, hash_str, unique_index, root_dir, raw_dir):
inflated = inflate_lfd_data(data)
# 1. Check for standard LFD name
internal_name = get_internal_name(inflated)
display_name = internal_name if internal_name else hash_str
has_assets, has_geometry = check_content_type(inflated)
# --- BRANCH A: Standard LFD Container (Models/Texture Collections) ---
if has_assets or has_geometry:
folder_name = f"{display_name} [{hash_str}]_{unique_index:04d}"
extract_dir = os.path.join(root_dir, folder_name)
if not os.path.exists(extract_dir): os.makedirs(extract_dir)
LOG.log(f" [EXTRACT] {folder_name}")
# Extract Textures
cur = 0
while True:
pos = inflated.find(b'name', cur)
if pos == -1: break
try:
sz = read_u32(inflated, pos+4)
if sz is None or sz > 256 or sz == 0: cur = pos+4; continue
fname = inflated[pos+8:pos+8+sz].decode('utf-8', errors='ignore').rstrip('\x00')
tex_pos = pos+8+sz
found = False
dstart, dsize = 0, 0
for p in range(4):
if inflated[tex_pos+p:tex_pos+p+4] == b'tex ':
dsize = read_u32(inflated, tex_pos+p+4)
dstart = tex_pos+p+8
found = True; break
if found and dsize and dsize < 20_000_000:
cnt = inflated[dstart:dstart+dsize]
head = cnt[:4].hex().upper()
ext = ".bin"
if head == "44445320": ext = ".dds"
elif head == "89504E47": ext = ".png"
final_name = fname + (ext if "." not in fname else "")
out_p = os.path.join(extract_dir, final_name)
with open(out_p, "wb") as f: f.write(cnt)
if ext == ".dds": decode_dds_file(out_p)
cur = dstart + dsize
else: cur = pos + 4
except: cur = pos + 4
# Extract Models
if has_geometry:
mtl_name = f"{display_name}.mtl"
mat_db = build_material_db(inflated)
if mat_db:
with open(os.path.join(extract_dir, mtl_name), 'w') as mtl:
for mid, tex in mat_db.items():
base = os.path.splitext(tex)[0]
mtl.write(f"newmtl Mat_{mid}\nmap_Kd {base}.dds\nmap_d {base}.dds\n\n")
cnt = [0]
recursive_model_extract(inflated, 0, len(inflated), extract_dir, cnt, mtl_name)
# --- BRANCH B: Special File Types (PNG, Sprite Scripts) ---
else:
# Check for PNG
if inflated.startswith(b'\x89PNG'):
final_name = f"{display_name}_{unique_index:04d}.png"
LOG.log(f" [PNG] {final_name}")
with open(os.path.join(root_dir, final_name), "wb") as f: f.write(inflated)
# Check for DDS (Raw)
elif inflated.startswith(b'DDS '):
final_name = f"{display_name}_{unique_index:04d}.dds"
LOG.log(f" [DDS] {final_name}")
with open(os.path.join(root_dir, final_name), "wb") as f: f.write(inflated)
# Check for Sprite Script (starts with //)
elif inflated.startswith(b'//'):
# Try to find the texture name inside the text
script_name = get_text_file_name(inflated)
if script_name:
final_name = f"{script_name}_{unique_index:04d}.sprite" # Using .spr for sprite definition
else:
final_name = f"{display_name}_{unique_index:04d}.txt"
LOG.log(f" [SCRIPT] {final_name}")
with open(os.path.join(root_dir, final_name), "wb") as f: f.write(inflated)
# --- BRANCH C: Fallback to Raw ---
else:
final_name = f"{display_name} [{hash_str}]_{unique_index:04d}.lfd"
with open(os.path.join(raw_dir, final_name), "wb") as f:
f.write(inflated)
# =============================================================================
# --- 5. PAK EXTRACTOR ---
# =============================================================================
def is_stream_header(data):
if len(data) < 16: return False
u, o = read_u32(data, 4), read_u32(data, 8)
return (o >= 12 and o <= 0xFFFF and u >= 50_000 and len(data) <= u)
def extract_pak_universal(pak_path):
LOG.log(f"Processing PAK: {os.path.basename(pak_path)}")
with open(pak_path, "rb") as f: pak_data = f.read()
riff_pos = pak_data.find(b'RIFF')
if riff_pos == -1: return LOG.log("Invalid PAK: No RIFF header")
dir_pos = pak_data.find(b'dir ', riff_pos)
dir_size = read_u32(pak_data, dir_pos + 4) if dir_pos != -1 else 0
file_pos = pak_data.find(b'file', riff_pos)
file_size = read_u32(pak_data, file_pos + 4) if file_pos != -1 else 0
files = []
file_blob_size = len(pak_data)
if dir_size > 1000:
LOG.log(f"Mode: DATA.PAK Style")
table_start = dir_pos + 24
table_end = dir_pos + 8 + dir_size
c = table_start
while c < table_end:
h = read_u32(pak_data, c)
o = read_u32(pak_data, c+4)
if o > 0 and o < file_blob_size:
files.append({'h': h, 'o': o, 'sz': 0})
c += 8
elif file_size > 1000:
LOG.log(f"Mode: VEHICLES.PAK Style")
table_start = file_pos + 8
table_end = file_pos + 8 + file_size
c = table_start
while c < table_end - 12:
h = read_u32(pak_data, c)
o = read_u32(pak_data, c+4)
sz = read_u32(pak_data, c+8)
if o > 0 and o < file_blob_size and sz < 20_000_000:
files.append({'h': h, 'o': o, 'sz': sz})
c += 12
else:
return LOG.log("CRITICAL ERROR: Could not find a valid file table.")
files.sort(key=lambda x: x['o'])
root = os.path.join(os.path.dirname(pak_path), os.path.basename(pak_path) + "_Extracted")
raw_dir = os.path.join(root, "_Raw_Files")
if not os.path.exists(raw_dir): os.makedirs(raw_dir)
LOG.start(root)
LOG.log(f"Found {len(files)} entries. Extracting...")
i = 0
global_counter = 0
while i < len(files):
curr = files[i]
start = curr['o']
if curr['sz'] > 0:
chunk_size = curr['sz']
else:
chunk_size = (files[i+1]['o'] if i < len(files)-1 else file_blob_size) - start
if start + chunk_size > len(pak_data): chunk_size = len(pak_data) - start
blob = pak_data[start : start+chunk_size]
if is_stream_header(blob) and curr['sz'] == 0:
merged = bytearray(blob)
j = i + 1
while j < len(files):
nxt = files[j]
if nxt['o'] != (files[j-1]['o'] + (files[j]['o'] - files[j-1]['o'])): break
nsz = (files[j+1]['o'] if j < len(files)-1 else file_blob_size) - nxt['o']
if is_stream_header(pak_data[nxt['o'] : nxt['o'] + min(32, nsz)]): break
merged.extend(pak_data[nxt['o'] : nxt['o'] + nsz])
j += 1
process_file_content(merged, f"{curr['h']:08X}", global_counter, root, raw_dir)
i = j
else:
process_file_content(blob, f"{curr['h']:08X}", global_counter, root, raw_dir)
i += 1
global_counter += 1
LOG.close()
def main():
print("--- BOATING BASH EXTRACTOR ---")
root = tk.Tk(); root.withdraw()
path = filedialog.askopenfilename()
if not path: return
if path.lower().endswith(".pak"): extract_pak_universal(path)
else:
with open(path, "rb") as f: d = f.read()
base = os.path.basename(path).split('.')[0]
root_dir = os.path.join(os.path.dirname(path), f"{base}_Content")
raw_dir = os.path.join(root_dir, "_Raw_Files")
if not os.path.exists(raw_dir): os.makedirs(raw_dir)
LOG.start(root_dir)
process_file_content(d, base, 0, root_dir, raw_dir)
LOG.close()
print("\nDone. Check the Output Folder for the Log File.")
input("\nPress Enter to close this window...")
if __name__ == "__main__":
main()