File size: 20,568 Bytes
ed552fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
#!/usr/bin/env python3
"""
foam_viz.py — OpenFOAM 2D VOF 场可视化。

从 OpenFOAM case 目录读取 alpha.water 与 U 场,
调用 viz_common.plot_snapshots 生成出版质量快照图。

支持串行和并行 (processor*/) case。

用法:
    from foam_viz import parse_scalar, parse_vector, parse_mesh, plot_foam
    python3 foam_viz.py   # 直接运行生成全部案例可视化
"""

import os
import sys
import re
import struct
import numpy as np

from viz_common import CASES, plot_snapshots, SUBPLOT_BASE_W


# ── OpenFOAM 字段解析 ─────────────────────────────────────────────────────────

def parse_scalar(path):
    """读取 OpenFOAM volScalarField,支持 ASCII 和 binary。"""
    with open(path, "rb") as f:
        raw = f.read()

    uniform_marker = b"internalField"
    uniform_pos = raw.find(uniform_marker)
    if uniform_pos != -1:
        after = raw[uniform_pos + len(uniform_marker):]
        j = 0
        while j < len(after) and after[j:j+1] in b" \t\n\r":
            j += 1
        if after[j:j+7] == b"uniform":
            val_str = after[j + 7:]
            semi = val_str.find(b";")
            if semi != -1:
                val_text = val_str[:semi].decode("ascii", errors="replace").strip()
                try:
                    return float(val_text)
                except ValueError:
                    pass

    marker = b"nonuniform List<scalar>"
    pos = raw.find(marker)
    if pos == -1:
        raise ValueError(f"未找到 nonuniform List<scalar>: {path}")

    rest = raw[pos + len(marker):]
    paren = rest.find(b"(")
    if paren == -1:
        raise ValueError(f"未找到 '(': {path}")
    data_start = pos + len(marker) + paren + 1

    i = data_start
    while i < len(raw) and raw[i:i+1] in b" \t\n\r":
        i += 1
    line_end = raw.find(b"\n", i)
    if line_end == -1:
        line_end = len(raw)
    first_token = raw[i:line_end].decode("ascii", errors="ignore").strip()
    try:
        float(first_token)
        return _parse_ascii_scalar(raw, data_start)
    except (ValueError, UnicodeDecodeError):
        return _parse_binary_scalar(raw, data_start)


def _parse_ascii_scalar(raw, data_start):
    text = raw[data_start:].decode("ascii", errors="replace")
    values = []
    for line in text.split("\n"):
        s = line.strip()
        if s == "" or s.startswith("//"):
            continue
        if s.startswith(")"):
            break
        s = s.lstrip("(")
        if not s:
            continue
        try:
            values.append(float(s))
        except ValueError:
            break
    return np.array(values, dtype=np.float64)


def _parse_binary_scalar(raw, data_start):
    paren_pos = data_start - 1
    line_end = paren_pos
    while line_end > 0 and raw[line_end - 1:line_end] in b"\n\r":
        line_end -= 1
    num_end = line_end
    while num_end > 0 and raw[num_end - 1:num_end].isdigit():
        num_end -= 1
    n_cells = int(raw[num_end:line_end])
    p = data_start
    while p < len(raw) and raw[p:p + 1] in b"\n\r":
        p += 1
    data_end = p + n_cells * 8
    values = struct.unpack(f"{n_cells}d", raw[p:data_end])
    return np.array(values, dtype=np.float64)


def parse_vector(path):
    """读取 OpenFOAM volVectorField,支持 ASCII 和 binary。"""
    with open(path, "rb") as f:
        raw = f.read()

    uniform_marker = b"internalField"
    uniform_pos = raw.find(uniform_marker)
    if uniform_pos != -1:
        after = raw[uniform_pos + len(uniform_marker):]
        j = 0
        while j < len(after) and after[j:j+1] in b" \t\n\r":
            j += 1
        if after[j:j+7] == b"uniform":
            val_str = after[j + 7:]
            semi = val_str.find(b";")
            if semi != -1:
                val_text = val_str[:semi].decode("ascii", errors="replace").strip()
                if val_text.startswith("(") and val_text.endswith(")"):
                    parts = val_text[1:-1].split()
                    if len(parts) >= 2:
                        try:
                            uz_val = float(parts[2]) if len(parts) >= 3 else 0.0
                            return float(parts[0]), float(parts[1]), uz_val
                        except ValueError:
                            pass

    marker = b"nonuniform List<vector>"
    pos = raw.find(marker)
    if pos == -1:
        raise ValueError(f"未找到 nonuniform List<vector>: {path}")

    rest = raw[pos + len(marker):]
    paren = rest.find(b"(")
    if paren == -1:
        raise ValueError(f"未找到 '(': {path}")
    data_start = pos + len(marker) + paren + 1

    i = data_start
    while i < len(raw) and raw[i:i+1] in b" \t\n\r":
        i += 1
    if i < len(raw) and raw[i:i+1] == b"(":
        return _parse_ascii_vector(raw, data_start)
    else:
        return _parse_binary_vector(raw, data_start)


def _parse_ascii_vector(raw, data_start):
    text = raw[data_start:].decode("ascii", errors="replace")
    ux, uy, uz = [], [], []
    for line in text.split("\n"):
        s = line.strip()
        if s == "" or s.startswith("//"):
            continue
        if s.startswith(")"):
            break
        s = s.strip("()")
        s = s.strip()
        if not s:
            continue
        try:
            parts = s.split()
            ux.append(float(parts[0]))
            uy.append(float(parts[1]))
            uz.append(float(parts[2]) if len(parts) >= 3 else 0.0)
        except (ValueError, IndexError):
            break
    return np.array(ux, dtype=np.float64), np.array(uy, dtype=np.float64), np.array(uz, dtype=np.float64)


def _parse_binary_vector(raw, data_start):
    paren_pos = data_start - 1
    line_end = paren_pos
    while line_end > 0 and raw[line_end - 1:line_end] in b"\n\r":
        line_end -= 1
    num_end = line_end
    while num_end > 0 and raw[num_end - 1:num_end].isdigit():
        num_end -= 1
    n_cells = int(raw[num_end:line_end])
    p = data_start
    while p < len(raw) and raw[p:p + 1] in b"\n\r":
        p += 1
    data_end = p + n_cells * 24
    all_vals = struct.unpack(f"{n_cells * 3}d", raw[p:data_end])
    arr = np.array(all_vals, dtype=np.float64).reshape(n_cells, 3)
    return arr[:, 0], arr[:, 1], arr[:, 2]


# ── 网格解析 ──────────────────────────────────────────────────────────────────

def parse_mesh(case_dir):
    """从 blockMeshDict 解析网格信息。"""
    bmd = os.path.join(case_dir, "system", "blockMeshDict")
    if not os.path.isfile(bmd):
        raise FileNotFoundError(f"blockMeshDict 不存在: {bmd}")

    with open(bmd, "r", encoding="utf-8", errors="replace") as f:
        content = f.read()

    v_start = content.find("vertices")
    if v_start == -1:
        raise ValueError("blockMeshDict 中未找到 vertices")
    bracket = content.find("(", v_start)
    depth = 0
    end = bracket
    for ci in range(bracket, len(content)):
        if content[ci] == "(":
            depth += 1
        elif content[ci] == ")":
            depth -= 1
            if depth == 0:
                end = ci
                break
    v_block = content[bracket + 1:end]

    verts = []
    for m in re.finditer(r"\(([^()]+)\)", v_block):
        parts = m.group(1).split()
        if len(parts) >= 3:
            verts.append([float(parts[0]), float(parts[1]), float(parts[2])])
        elif len(parts) >= 2:
            verts.append([float(parts[0]), float(parts[1]), 0.0])

    verts = np.array(verts)
    x0, y0, z0 = verts.min(axis=0)
    x1, y1, z1 = verts.max(axis=0)

    b_start = content.find("blocks")
    if b_start == -1:
        raise ValueError("blockMeshDict 中未找到 blocks")
    b_bracket = content.find("(", b_start)
    depth = 0
    b_end = b_bracket
    for ci in range(b_bracket, len(content)):
        if content[ci] == "(":
            depth += 1
        elif content[ci] == ")":
            depth -= 1
            if depth == 0:
                b_end = ci
                break
    b_block = content[b_bracket + 1:b_end]

    b_tokens = re.findall(r"\(([^()]+)\)", b_block)
    if len(b_tokens) >= 2:
        nums = b_tokens[1].split()
        nx = int(nums[0])
        ny = int(nums[1])
        nz = int(nums[2]) if len(nums) >= 3 else 1
        return {"nx": nx, "ny": ny, "nz": nz,
                "x0": x0, "y0": y0, "x1": x1, "y1": y1,
                "z0": z0, "z1": z1}
    raise ValueError("blockMeshDict 中未解析到 hex block")


# ── 并行 case 支持 ────────────────────────────────────────────────────────────

def _detect_parallel(case_dir, nx, ny):
    """检测并行 case,返回 (proc_dirs, proc_blocks) 或 None。"""
    proc_dirs = sorted(
        [d for d in os.listdir(case_dir)
         if os.path.isdir(os.path.join(case_dir, d)) and d.startswith("processor")],
        key=lambda d: int(re.search(r"\d+", d).group()),
    )
    if not proc_dirs:
        return None

    ref_dir = os.path.join(case_dir, proc_dirs[0])
    t_entries = sorted(os.listdir(ref_dir))
    first_n = nx * ny
    for entry in t_entries:
        if entry == "0":
            continue
        u_path = os.path.join(ref_dir, entry, "U")
        if os.path.isdir(os.path.join(ref_dir, entry)) and os.path.exists(u_path):
            with open(u_path, "rb") as f:
                raw = f.read()
            m = re.search(r"nonuniform\s+List<\w+>\s+(\d+)", raw.decode("latin-1"))
            if m:
                first_n = int(m.group(1))
            break
    else:
        return None

    n_procs = len(proc_dirs)
    total = nx * ny
    if first_n >= total:
        return proc_dirs[:1], [(nx, ny, slice(0, ny), slice(0, nx))]

    dict_path = os.path.join(case_dir, "system", "decomposeParDict")
    n_x, n_y = n_procs, 1
    if os.path.exists(dict_path):
        with open(dict_path, "r", encoding="latin-1") as f:
            content = f.read()
        m = re.search(r"n\s*\(\s*(\d+)\s+(\d+)\s+(\d+)\s*\)", content)
        if m:
            nx_f, ny_f = int(m.group(1)), int(m.group(2))
            if nx_f * ny_f == n_procs:
                n_x, n_y = nx_f, ny_f

    blocks = []
    if n_y > 1:
        block_nx = nx // n_x
        block_ny = ny // n_y
        for pid in range(n_procs):
            gx = pid % n_x
            gy = pid // n_x
            bx0, by0 = gx * block_nx, gy * block_ny
            bx1 = min(bx0 + block_nx, nx) if gx < n_x - 1 else nx
            by1 = min(by0 + block_ny, ny) if gy < n_y - 1 else ny
            blocks.append((bx1 - bx0, by1 - by0, slice(by0, by1), slice(bx0, bx1)))
    else:
        boundaries = [0]
        base, rem = divmod(nx, n_x)
        for p in range(n_x):
            boundaries.append(boundaries[-1] + base + (1 if p < rem else 0))
        for pid in range(n_procs):
            pnx = boundaries[pid + 1] - boundaries[pid]
            blocks.append((pnx, ny, slice(0, ny), slice(boundaries[pid], boundaries[pid + 1])))

    return proc_dirs, blocks


def _read_parallel_field(proc_dirs, blocks, case_dir, t_dir, field_name, is_vector, ny, nx):
    """从 processor 目录组装完整场。"""
    if is_vector:
        full = np.zeros((ny, nx, 3), dtype=np.float64)
    else:
        full = np.zeros((ny, nx), dtype=np.float64)

    for proc_dir, (pnx, pny, rows, cols) in zip(proc_dirs, blocks):
        fpath = os.path.join(case_dir, proc_dir, t_dir, field_name)
        if is_vector:
            ux, uy, uz = parse_vector(fpath)
            if isinstance(ux, (float, int)):
                ux = np.full(pnx * pny, ux)
                uy = np.full(pnx * pny, uy)
                uz = np.full(pnx * pny, uz)
            expected = pnx * pny
            if len(ux) > expected:
                ux_2d = ux.reshape(ny, nx)
                uy_2d = uy.reshape(ny, nx)
                uz_2d = uz.reshape(ny, nx)
                ux = ux_2d[rows, cols].ravel()
                uy = uy_2d[rows, cols].ravel()
                uz = uz_2d[rows, cols].ravel()
            local = np.column_stack([ux, uy, uz]).reshape(pny, pnx, 3)
            full[rows, cols, :] = local
        else:
            val = parse_scalar(fpath)
            if isinstance(val, (float, int)):
                val = np.full(pnx * pny, val)
            expected = pnx * pny
            if len(val) > expected:
                val_2d = val.reshape(ny, nx)
                val = val_2d[rows, cols].ravel()
            full[rows, cols] = val.reshape(pny, pnx)

    return full


def _find_parallel_timesteps(case_dir, proc_dirs):
    """从 processor0 发现所有数值时间步目录名。"""
    ref = os.path.join(case_dir, proc_dirs[0])
    t_dirs = []
    for entry in os.listdir(ref):
        if os.path.isdir(os.path.join(ref, entry)):
            try:
                float(entry)
                t_dirs.append(entry)
            except ValueError:
                continue
    t_dirs.sort(key=lambda x: float(x))
    return t_dirs


def _find_closest_parallel_timestep(t_dirs, t):
    best, best_diff = t_dirs[0], abs(float(t_dirs[0]) - t)
    for td in t_dirs:
        diff = abs(float(td) - t)
        if diff < best_diff:
            best, best_diff = td, diff
    return best, float(best)


def _find_closest_timestep(case_dir, t):
    available = []
    for name in os.listdir(case_dir):
        full = os.path.join(case_dir, name)
        if os.path.isdir(full):
            try:
                available.append((float(name), name))
            except ValueError:
                continue
    if not available:
        raise FileNotFoundError(f"无时间步目录: {case_dir}")
    closest_val, closest_name = min(available, key=lambda x: abs(x[0] - t))
    return closest_name, closest_val


# ── 绘图入口 ──────────────────────────────────────────────────────────────────

def plot_foam(case_dir, timesteps, title, outpath,
              max_aspect=None, axis_labels=("x", "y"), arrow_cfg=None):
    """从 OpenFOAM case 目录生成快照图。"""
    mesh = parse_mesh(case_dir)
    nx, ny = mesh["nx"], mesh["ny"]
    nz = mesh.get("nz", 1)

    is_xz = (ny == 1 and nz > 1)
    if is_xz:
        ncols, nrows = nx, nz
        d0, d1 = mesh["x0"], mesh["z0"]
        d2, d3 = mesh["x1"], mesh["z1"]
        mesh_label = f"{nx}x{nz}"
    else:
        ncols, nrows = nx, ny
        d0, d1 = mesh["x0"], mesh["y0"]
        d2, d3 = mesh["x1"], mesh["y1"]
        mesh_label = f"{nx}x{ny}"

    Ld = d2 - d0
    Lh = d3 - d1
    domain_label = f"{Ld:.3f}x{Lh:.3f}"

    # 检测并行
    parallel = _detect_parallel(case_dir, nx, ny if not is_xz else nz)
    par_t_dirs = None
    if parallel:
        proc_dirs, proc_blocks = parallel
        par_t_dirs = _find_parallel_timesteps(case_dir, proc_dirs)

    # 组装 frames
    frames = []
    for t in timesteps:
        if parallel:
            ts_name, ts_val = _find_closest_parallel_timestep(par_t_dirs, t)
            alpha_flat = _read_parallel_field(
                proc_dirs, proc_blocks, case_dir, ts_name,
                "alpha.water", False, nrows, ncols,
            )
            u_full = _read_parallel_field(
                proc_dirs, proc_blocks, case_dir, ts_name,
                "U", True, nrows, ncols,
            )
            if is_xz:
                alpha_2d = alpha_flat if alpha_flat.ndim == 2 else alpha_flat[:, :, 0]
                u_2d, v_2d = u_full[:, :, 0], u_full[:, :, 2]
            else:
                alpha_2d = alpha_flat if alpha_flat.ndim == 2 else alpha_flat[:, :, 0]
                u_2d, v_2d = u_full[:, :, 0], u_full[:, :, 1]
        else:
            ts_name, ts_val = _find_closest_timestep(case_dir, t)
            ts_dir = os.path.join(case_dir, ts_name)
            n_cells = ncols * nrows
            alpha_raw = parse_scalar(os.path.join(ts_dir, "alpha.water"))
            if isinstance(alpha_raw, (float, int)):
                alpha_raw = np.full(n_cells, alpha_raw)
            alpha_2d = alpha_raw.reshape(nrows, ncols)

            ux, uy, uz = parse_vector(os.path.join(ts_dir, "U"))
            if isinstance(ux, (float, int)):
                ux = np.full(n_cells, ux)
                uy = np.full(n_cells, uy)
                uz = np.full(n_cells, uz)
            if is_xz:
                u_2d = ux.reshape(nrows, ncols)
                v_2d = uz.reshape(nrows, ncols)
            else:
                u_2d = ux.reshape(nrows, ncols)
                v_2d = uy.reshape(nrows, ncols)

        frames.append({"alpha": alpha_2d, "u": u_2d, "v": v_2d, "t": ts_val})

    plot_snapshots(
        frames, outpath, title, mesh_label, domain_label,
        extent=[d0, d2, d1, d3],
        axis_labels=axis_labels, max_aspect=max_aspect, arrow_cfg=arrow_cfg,
    )


# ── 测试入口 ──────────────────────────────────────────────────────────────────

if __name__ == "__main__":
    _cwd = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", ".."))
    _candidate = os.path.join(_cwd, "Exp", "data")
    if os.path.isdir(os.path.join(_candidate, "raw")):
        BASE_DIR = os.path.join(_candidate, "raw")
        OUT_DIR = os.path.join(_candidate, "visualizations")
    elif sys.platform == "win32":
        BASE_DIR = r"F:\agent-workspace\paper2\Exp\data\raw"
        OUT_DIR = r"F:\agent-workspace\paper2\Exp\data\visualizations"
    else:
        BASE_DIR = "/mnt/f/agent-workspace/paper2/Exp/data/raw"
        OUT_DIR = "/mnt/f/agent-workspace/paper2/Exp/data/visualizations"
    os.makedirs(OUT_DIR, exist_ok=True)

    def _auto_select_timesteps(case_dir, requested, nx, ny):
        parallel = _detect_parallel(case_dir, nx, ny)
        if parallel:
            proc_dirs, _ = parallel
            available = sorted([float(t) for t in _find_parallel_timesteps(case_dir, proc_dirs)])
        else:
            available = []
            for name in os.listdir(case_dir):
                full = os.path.join(case_dir, name)
                if os.path.isdir(full):
                    try:
                        available.append(float(name))
                    except ValueError:
                        continue
            available.sort()
        if not available:
            return requested
        t_min, t_max = available[0], available[-1]
        valid = [t for t in requested if t_min - 0.01 <= t <= t_max + 0.01]
        if len(valid) >= 3:
            return valid
        n_show = min(5, len(available))
        indices = np.linspace(0, len(available) - 1, n_show, dtype=int)
        return [available[i] for i in indices]

    for case_name, cfg in CASES.items():
        print(f"\n{'='*60}")
        print(f"  {cfg['title']} ({case_name})")
        print(f"{'='*60}")

        case_dir = os.path.join(BASE_DIR, case_name, "t00")
        if not os.path.isdir(case_dir):
            print(f"  [SKIP] {case_dir}")
            continue

        mesh = parse_mesh(case_dir)
        nz = mesh.get("nz", 1)
        ncols_vis = mesh["nx"]
        nrows_vis = nz if (mesh["ny"] == 1 and nz > 1) else mesh["ny"]
        if nz > 1:
            print(f"  mesh: {mesh['nx']}x{mesh['ny']}x{nz}, "
                  f"domain: {mesh['x1']-mesh['x0']:.3f}x{mesh['y1']-mesh['y0']:.3f}x{mesh['z1']-mesh['z0']:.3f} m")
        else:
            print(f"  mesh: {mesh['nx']}x{mesh['ny']}, "
                  f"domain: {mesh['x1']-mesh['x0']:.3f}x{mesh['y1']-mesh['y0']:.3f} m")

        timesteps = _auto_select_timesteps(case_dir, cfg["timesteps"], ncols_vis, nrows_vis)
        if timesteps != cfg["timesteps"]:
            print(f"  可用时间步: [{timesteps[0]:.2f}...{timesteps[-1]:.2f}], 选取 {len(timesteps)} 个")

        outpath = os.path.join(OUT_DIR, f"{case_name}_foam.png")
        plot_foam(
            case_dir=case_dir,
            timesteps=timesteps,
            title=cfg["title"],
            outpath=outpath,
            max_aspect=cfg.get("max_aspect"),
            axis_labels=cfg.get("axis_labels", ("x", "y")),
            arrow_cfg=cfg.get("arrow_cfg"),
        )
        print(f"  -> {outpath}")

    print(f"\n全部完成。输出: {OUT_DIR}")