Datasets:

Languages:
Chinese
Tags:
Not-For-All-Audiences
License:
File size: 8,913 Bytes
6b4490e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# https://zhuanlan.zhihu.com/p/623697843

# mamba create -n golang -c conda-forge go
# conda activate golang
# cd E:\tmp\ISLAND
# Get-Item -Path Env:\CONDA*
# $env:GOROOT = "$env:CONDA_PREFIX\go"
# go version
# go mod init cst
# go get github.com/regomne/eutil/codec
# go get github.com/regomne/eutil/textFile
# # https://github.com/regomne/chinesize/blob/master/CatSystem2/cstTextProc/cst.go
# go build .\cst.go
#
# E:\tmp\ISLAND\cst.exe -e -cst E:\tmp\ISLAND\cst\BAD_01.cst -o E:\tmp\ISLAND\cst\BAD_01.txt -cp 932

import os, sys
import struct
import zlib

warnings = []


def warn(value):
    warnings.append(value)


def clearWarnings():
    global warnings
    warnings = []


def printWarnings(sc):
    global warnings
    for wi in warnings:
        print('[WARNING]', sc, wi)
    clearWarnings()


def cst2bin(datcst):
    tag, sizcst, sizbin = struct.unpack_from('8sII', datcst)
    if tag != b'CatScene':
        raise Exception('Label Mismatch')
    datcst = datcst[16:]
    if sizcst != len(datcst):
        raise Exception('Size Ante Decompress Mismatch')
    datbin = zlib.decompress(datcst)
    if sizbin != len(datbin):
        raise Exception('Size Post Decompress Mismatch')
    return datbin


def bin2cst(datbin):
    datcst = zlib.compress(datbin)
    return b'CatScene' + struct.pack('II', len(datcst), len(datbin)) + datcst


class FormatCST:
    def __init__(self, fc):
        b = cst2bin(fc.read())
        (h0, self.h1, self.h2, self.h3), b = struct.unpack_from('4I', b), b[16:]
        self.b1, b2, b3 = b[:self.h2], b[self.h2:self.h3], b[self.h3:]
        if h0 != len(b) or self.h1 * 8 != self.h2 or (self.h3 - self.h2) % 4 != 0:
            raise Exception('Integrity Constraint 0 Violated')

        it = struct.iter_unpack('II', self.b1)
        flag = True
        self.n1 = 0
        while flag:
            try:
                d10, d11 = next(it)
                if d11 != self.n1:
                    flag = False
                self.n1 += d10
            except StopIteration:
                break
        if not flag or self.n1 * 4 != self.h3 - self.h2:
            raise Exception('Integrity Constraint 1 Violated')

        it = struct.iter_unpack('I', b2)
        d2 = []
        while True:
            try:
                d2.append(*next(it))
            except StopIteration:
                break
        if self.n1 != len(d2):
            raise Exception('Integrity Constraint 2 Violated')

        ofs = 0
        self.d3 = []
        for i in range(self.n1):
            if ofs < d2[i]:
                warn('Unaccessible Fragment Offset 0x{0:08X}'.format(ofs))
                ofs = d2[i]
            if ofs > d2[i]:
                raise Exception('Overflow Offset 0x{0:08X}'.format(ofs))
            try:
                d30, d31, d32 = struct.unpack_from('3B', b3, ofs)
            except Exception:
                raise Exception('Content Truncated')
            if d30 != 0x01:
                raise Exception('Invalid Offset 0x{0:08X}'.format(ofs))
            if d31 not in (0x02, 0x20, 0x21, 0x30):
                warn('Unknown Code 0x01{1:02X} Offset 0x{0:08X}'.format(ofs, d31))
            ofs += 3
            while d32 != 0x00:
                try:
                    d32, = struct.unpack_from('B', b3, ofs)
                except Exception:
                    raise Exception('Content Truncated')
                ofs += 1
            self.d3.append(b3[d2[i]: ofs])
        if ofs < len(b3):
            warn('Unaccessible Fragment Offset 0x{0:08X}'.format(ofs))

    def iter(self):
        self.idx = -1
        self.fslc = False

    def next(self, skp=True):
        self.idx += 1
        if skp:
            while self.idx < self.n1:
                if self.fslc:
                    break
                d31, = struct.unpack_from('B', self.d3[self.idx], 1)
                if d31 in (0x20, 0x21):
                    break
                if d31 == 0x30 and self.d3[self.idx][2:8] == b'scene\x20':
                    break
                if d31 == 0x30 and self.d3[self.idx][2:] == b'fselect\x00':
                    self.fslc = True
                self.idx += 1
        if self.idx >= self.n1:
            raise StopIteration

    def get(self, skp=True):
        if skp:
            return self.d3[self.idx][2:-1]
        else:
            return b'<\\x01><\\x' + bytes('{0:02X}'.format(self.d3[self.idx][1]), encoding='utf-8') + b'>' + self.d3[
                                                                                                                 self.idx][
                                                                                                             2:-1] + b'<\\x00>'

    def rep(self, bn):
        self.d3[self.idx] = self.d3[self.idx][:2] + bn + b'\x00'

    def pac(self):
        b2, b3 = b'', b''
        ofs = 0
        for i in range(self.n1):
            b2 += struct.pack('I', ofs)
            b3 += self.d3[i]
            ofs += len(self.d3[i])
        b0 = struct.pack('4I', self.h3 + ofs, self.h1, self.h2, self.h3)
        return b0 + self.b1 + b2 + b3


pathcst = 'scene_cst'
pathbin = 'scene_bin'
pathtxt = 'scene_txt'
pathdst = 'scene_dst'


def depacst():
    liscst = os.listdir(pathcst)
    if not os.path.exists(pathbin):
        os.makedirs(pathbin)
    s0, s1 = 0, 0
    for sc in liscst:
        if not sc.endswith('.cst'):
            continue
        s1 += 1
        clearWarnings()

        f = open(os.path.join(pathcst, sc), 'rb')
        try:
            b = cst2bin(f.read())
        except Exception as e:
            print('[ERROR]', sc, e)
            continue
        finally:
            f.close()

        sb = sc[:-3] + 'bin'
        f = open(os.path.join(pathbin, sb), 'wb')
        f.write(b)
        f.close()

        s0 += 1
        printWarnings(sc)
    return (s0, s1)


def unpacst(skp=True):
    liscst = os.listdir(pathcst)
    if not os.path.exists(pathtxt):
        os.makedirs(pathtxt)
    s0, s1 = 0, 0
    for sc in liscst:
        if not sc.endswith('.cst'):
            continue
        s1 += 1
        clearWarnings()

        f = open(os.path.join(pathcst, sc), 'rb')
        try:
            c = FormatCST(f)
        except Exception as e:
            print('[ERROR]', sc, e)
            continue
        finally:
            f.close()

        st = sc[:-3] + 'txt'
        f = open(os.path.join(pathtxt, st), 'wb')
        c.iter()
        while True:
            try:
                c.next(skp)
                f.write(c.get(skp))
                f.write(b'\x0D\x0A')
            except StopIteration:
                break
        f.close()

        s0 += 1
        printWarnings(sc)
    return (s0, s1)


def repacst():
    liscst = os.listdir(pathcst)
    listxt = os.listdir(pathtxt)
    if not os.path.exists(pathdst):
        os.makedirs(pathdst)
    s0, s1 = 0, 0
    for st in listxt:
        if not st.endswith('.txt'):
            continue
        sc = st[:-3] + 'cst'
        if sc not in liscst:
            print('[WARNING] Original CST File Missing: ' + sc)
            continue
        s1 += 1
        clearWarnings()

        f = open(os.path.join(pathcst, sc), 'rb')
        try:
            c = FormatCST(f)
        except Exception as e:
            print('[ERROR]', sc, e)
            continue
        finally:
            f.close()

        st = sc[:-3] + 'txt'
        f = open(os.path.join(pathtxt, st), 'rb')
        c.iter()
        flag = True
        s = 0
        while True:
            try:
                c.next()
                bn = b''
                while True:
                    bi = f.read(1)
                    di, = struct.unpack('B', bi)
                    if di < 0x20:
                        break
                    bn += bi
                if di != 0x0D:
                    flag = False
                    break
                bi = f.read(1)
                di, = struct.unpack('B', bi)
                if di != 0x0A:
                    flag = False
                    break
                c.rep(bn)
                s += 1
            except StopIteration:
                break
            except Exception:
                warn('Lack of Text')
                break
        f.close()
        if not flag:
            print('[ERROR]', st, 'Invalid Byte 0x{0:02X}'.format(di))
            continue
        f = open(os.path.join(pathdst, sc), 'wb')
        f.write(bin2cst(c.pac()))
        f.close()

        s0 += 1
        printWarnings(sc)
    return (s0, s1)


if __name__ == '__main__':
    pathcst = r'E:\tmp\ISLAND\cst'
    liscst = os.listdir(pathcst)
    tag = 0
    if tag not in (0, 1, 2, 3):
        print('Invalid Parametre')
        sys.exit()
    if tag == 0:
        s0, s1 = unpacst()
    if tag == 1:
        s0, s1 = repacst()
    if tag == 2:
        s0, s1 = depacst()
    if tag == 3:
        s0, s1 = unpacst(False)
    print('%d / %d completed' % (s0, s1))