C#ATIA

↑タイトル詐欺 主にFusion360API 偶にCATIA V5 VBA(絶賛ネタ切れ中)※記載されている内容は個人の意見であり、所属する団体等を代表する意見では御座いません・・・・よ!

図面の寸法をCSV出力する2

こちらの続きです。
図面の寸法をCSV出力する - C#ATIA

前回の宿題を修正しました。

# Fusion360API Python script
# アクティブシートの寸法を CSV(UTF-8 BOM / Excel で開ける)に出力する
#   寸法は Drawing API では取れないため、AutoLISP 経由で取得する。

import csv
import math
import os
import re
import tempfile
import time
import traceback
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP

import adsk
import adsk.core as core
import adsk.drawing as drawing

# 結果の受け渡し用ファイル(LISP側は %TEMP%/FUSIONDIMS)
OUT_PATH = os.path.join(os.environ.get("TEMP", tempfile.gettempdir()), "FUSIONDIMS")
LISP_PATH = '(strcat (getenv "TEMP") "/FUSIONDIMS")'
END_MARK = "END"

# 1寸法あたりの出力行(LISP_SRC の出力順と一致させること)
FIELDS = (
    "handle",
    "ent",
    "type",
    "value",
    "override",
    "layout",
    "text",
    "dimtol",
    "dimlim",
    "dimtp",
    "dimtm",
    "dimdec",
    "dimadec",
    "dimzin",
    "dimazin",
    "p10x",
    "p10y",
    "p11x",
    "p11y",
    "p13x",
    "p13y",
    "p14x",
    "p14y",
    "p15x",
    "p15y",
)
FIELD_COUNT = len(FIELDS)

# 寸法を列挙して OUT_PATH に1行1項目で書き出すLISP(先頭行はCTAB)
#   公差は寸法のスタイル上書き(xdata ACAD/DSTYLE)から取り、無ければ寸法スタイルの値を使う
#   71:DIMTOL 72:DIMLIM 47:DIMTP 48:DIMTM
#   271:DIMDEC 179:DIMADEC 78:DIMZIN 79:DIMAZIN
LISP_SRC = f"""
(progn
  (defun _s (v) (if v v ""))
  (defun _r (v) (if v (rtos v 2 12) ""))
  (defun _w (v) (write-line v _f))
  (defun _p (c / p)
    (setq p (cdr (assoc c _d)))
    (_w (_r (car p)))
    (_w (_r (cadr p))))
  (defun _bt (n / e d r)
    (setq r "")
    (if (and n (setq e (tblobjname "BLOCK" n)))
      (while (setq e (entnext e))
        (setq d (entget e))
        (if (member (cdr (assoc 0 d)) (list "MTEXT" "TEXT"))
          (setq r (strcat r (_s (cdr (assoc 1 d))))))))
    r)
  (defun _xv (x c / r)
    (setq x (cdr (member (assoc 1002 x) x)))
    (while (and x (cdr x) (not r))
      (if (and (= (caar x) 1070) (= (cdar x) c)) (setq r (cdadr x)))
      (setq x (cddr x)))
    r)
  (defun _tv (c / v)
    (setq v (_xv _x c))
    (if (null v) (setq v (cdr (assoc c _st))))
    v)
  (setq _f (open {LISP_PATH} "w"))
  (_w (getvar "CTAB"))
  (setq _ss (ssget "X" (list (cons 0 "*DIMENSION"))))
  (setq _i 0)
  (if _ss
    (repeat (sslength _ss)
      (setq _e (ssname _ss _i) _i (1+ _i))
      (setq _d (entget _e (list "ACAD")))
      (setq _x (cdr (car (cdr (assoc -3 _d)))))
      (setq _st (if (cdr (assoc 3 _d)) (tblsearch "DIMSTYLE" (cdr (assoc 3 _d)))))
      (foreach _v
        (list
          (_s (cdr (assoc 5 _d)))
          (_s (cdr (assoc 0 _d)))
          (itoa (cdr (assoc 70 _d)))
          (_r (cdr (assoc 42 _d)))
          (_s (cdr (assoc 1 _d)))
          (_s (cdr (assoc 410 _d)))
          (_bt (cdr (assoc 2 _d)))
          (_r (_tv 71))
          (_r (_tv 72))
          (_r (_tv 47))
          (_r (_tv 48)))
        (_w _v))
      (foreach _c (list 271 179 78 79) (_w (_r (_tv _c))))
      (foreach _c (list 10 11 13 14 15) (_p _c))))
  (_w "{END_MARK}")
  (close _f)
  (princ))
"""

# DXF code 70 の下位3bit -> 寸法種類
KIND_NAMES = {
    0: "長さ",
    1: "平行",
    2: "角度",
    3: "直径",
    4: "半径",
    5: "角度",
    6: "座標",
}

CSV_HEADER = ("No", "ビュー", "寸法種類", "呼び寸法", "上の許容差", "下の許容差")

# どのビューにも入らない寸法のビュー名
OUTSIDE_NAME = "ビュー外"

# API座標 -> LISP座標 の単位換算候補(定義点が最も多くビュー内に入るものを採用)
UNIT_CANDIDATES = (1.0, 10.0, 0.1, 25.4, 1 / 25.4, 2.54, 1 / 2.54)

# ビュー種類(drawing.ViewTypes の値) -> 名前
VIEW_TYPE_NAMES = {
    0: "基準図",
    1: "投影図",
    2: "断面図",
    3: "詳細図",
    4: "補助投影図",
    5: "展開図",
}

# 基準図の向き(drawing.ViewOrientationTypes の値) -> 名前
ORIENT_NAMES = {
    0: "正面",
    1: "背面",
    2: "上面",
    3: "下面",
    4: "右側面",
    5: "左側面",
    6: "等角",
    7: "等角",
    8: "等角",
    9: "等角",
}


def run(context):
    ui: core.UserInterface = None
    try:
        app: core.Application = core.Application.get()
        ui = app.userInterface

        drw: drawing.Drawing = drawing.Drawing.cast(app.activeProduct)
        if not drw:
            ui.messageBox("図面ドキュメントをアクティブにしてください")
            return

        sheet: drawing.Sheet = drw.activeSheet
        print(f"Sheet: {sheet.name} 寸法数(API): {sheet.drawingDimensions.count}")

        # 実行の確認
        ans = ui.messageBox(
            f"ファイル名: {app.activeDocument.name}\n"
            f"シート名: {sheet.name}\n\n"
            "の寸法を CSV 出力します。良いですか?",
            "寸法出力",
            core.MessageBoxButtonTypes.YesNoButtonType,
            core.MessageBoxIconTypes.QuestionIconType,
        )
        if ans != core.DialogResults.DialogYes:
            return

        # 寸法の取得
        if os.path.exists(OUT_PATH):
            os.remove(OUT_PATH)
        command_result = exec_lisp(to_lisp(LISP_SRC))
        print(f"寸法取得 -> {command_result!r}")

        lines = wait_result(OUT_PATH)
        if lines is None:
            ui.messageBox(
                f"結果ファイルが作成されませんでした:\n{OUT_PATH}\n\n"
                f"コマンド応答: {command_result[:500]}"
            )
            return

        recs = parse_dims(lines)
        if not recs:
            ui.messageBox(f"シート「{sheet.name}」に寸法がありません")
            return
        rows = build_rows(get_views(sheet), recs)

        # 保存先の選択
        dlg = ui.createFileDialog()
        dlg.title = "寸法の出力先"
        dlg.filter = "CSV (*.csv)"
        dlg.initialFilename = safe_name(f"{app.activeDocument.name}_{sheet.name}.csv")
        if dlg.showSave() != core.DialogResults.DialogOK:
            return
        path = dlg.filename

        try:
            with open(path, "w", encoding="utf-8-sig", newline="") as f:
                w = csv.writer(f)
                w.writerow(CSV_HEADER)
                w.writerows(rows)
        except PermissionError:
            ui.messageBox(f"書き込めません(Excel で開いていないか確認してください):\n{path}")
            return

        ui.messageBox(f"{len(rows)} 件の寸法を出力しました\n{path}", "寸法出力")
    except Exception:
        if ui:
            ui.messageBox("Failed:\n{}".format(traceback.format_exc()))


# ---------------------------------------------------------------- 変換


def parse_dims(lines: list) -> list:
    ctab = lines[0]
    body = lines[1:]
    recs = [
        dict(zip(FIELDS, body[i : i + FIELD_COUNT]))
        for i in range(0, len(body) - FIELD_COUNT + 1, FIELD_COUNT)
    ]
    for r in recs:
        r["pts"] = {}
        for code in (10, 11, 13, 14, 15):
            x, y = to_float(r[f"p{code}x"]), to_float(r[f"p{code}y"])
            if x is not None and y is not None:
                r["pts"][code] = (x, y)
    # アクティブシートの寸法に絞る(判別できない場合は全件)
    same = [r for r in recs if r["layout"] == ctab]
    return same or recs


# ---------------------------------------------------------------- ビュー


class ViewBox:
    def __init__(self, index: int, view, pts: list):
        self.index = index
        try:
            self.vtype = view.type
        except Exception:
            self.vtype = None
        try:
            self.orientation = view.orientation  # 基準図のみ対応
        except Exception:
            self.orientation = None
        xs = [p[0] for p in pts]
        ys = [p[1] for p in pts]
        self.box = [min(xs), min(ys), max(xs), max(ys)]
        self.name = f"View{index + 1}"

    def scaled(self, f: float):
        self.box = [v * f for v in self.box]

    @property
    def center(self):
        return ((self.box[0] + self.box[2]) / 2, (self.box[1] + self.box[3]) / 2)

    @property
    def size(self):
        return (self.box[2] - self.box[0], self.box[3] - self.box[1])

    def contains(self, p, margin_ratio: float = 0.02) -> bool:
        w, h = self.size
        m = max(w, h) * margin_ratio + 1e-6
        return (
            self.box[0] - m <= p[0] <= self.box[2] + m
            and self.box[1] - m <= p[1] <= self.box[3] + m
        )


def get_views(sheet) -> list:
    """各ビューの viewCurves からシート上の外接矩形を作る"""
    views = []
    for i, view in enumerate(sheet.views):
        pts = []
        try:
            for crv in view.viewCurves:
                # 中心点は大半径の円弧で形状から大きく離れるため、範囲には始点・終点を使う
                ends = []
                for acc in ("startPoint", "endPoint"):
                    dp = getattr(crv, acc, None)
                    if dp:
                        c = dp.coordinate
                        ends.append((c.x, c.y))
                pts += ends
                # 閉じた曲線(円)だけは 中心±半径 を範囲に加える
                cp = getattr(crv, "centerPoint", None)
                if cp and len(ends) == 2 and math.dist(ends[0], ends[1]) < 1e-6:
                    c = cp.coordinate
                    r = math.dist((c.x, c.y), ends[0])
                    pts += [(c.x - r, c.y - r), (c.x + r, c.y + r)]
        except Exception:
            print(f"View{i + 1}: viewCurves を取得できません")
        if pts:
            views.append(ViewBox(i, view, pts))
    return views


def calibrate(views: list, recs: list) -> float:
    pts = [p for r in recs for p in r["pts"].values()]

    def score(f):
        n = 0
        for p in pts:
            for v in views:
                b = ViewBox.__new__(ViewBox)
                b.box = [x * f for x in v.box]
                if b.contains(p):
                    n += 1
                    break
        return n

    return max(UNIT_CANDIDATES, key=score)


def name_views(views: list):
    """「View番号 種類(向き)」の名前を付ける"""
    bases = [v for v in views if v.vtype == drawing.ViewTypes.BaseViewType]
    for v in views:
        direction = ""
        if v.vtype == drawing.ViewTypes.BaseViewType:
            direction = ORIENT_NAMES.get(v.orientation, "")
        elif v.vtype == drawing.ViewTypes.ProjectedViewType and bases:
            # 投影図は最も近い基準図との位置関係で判定
            b = min(bases, key=lambda b: math.dist(b.center, v.center))
            dx, dy = v.center[0] - b.center[0], v.center[1] - b.center[1]
            bw, bh = b.size
            if abs(dx) < bw * 0.1 and abs(dy) > bh / 2:
                direction = "上" if dy > 0 else "下"
            elif abs(dy) < bh * 0.1 and abs(dx) > bw / 2:
                direction = "右" if dx > 0 else "左"
            else:
                direction = "等角"
        label = VIEW_TYPE_NAMES.get(v.vtype, "ビュー")
        v.name = f"View{v.index + 1} {label}" + (f"({direction})" if direction else "")


def def_points(r: dict) -> list:
    """所属ビューの判定に使う定義点(無ければ文字位置)"""
    flags = int(to_float(r["type"]) or 0)
    codes = {
        0: (13, 14),
        1: (13, 14),
        2: (13, 14, 15, 10),
        3: (10, 15),
        4: (10, 15),
        5: (13, 14, 15),
        6: (13,),
    }.get(flags & 7, (13, 14))
    pts = [r["pts"][c] for c in codes if c in r["pts"]]
    if not pts and 11 in r["pts"]:
        pts = [r["pts"][11]]
    return pts


def find_view(views: list, r: dict):
    pts = def_points(r)
    if not pts:
        return None
    # 範囲が重なる場合に備え、含むビューのうち最小のものを選ぶ
    hits = [v for v in views if all(v.contains(p) for p in pts)]
    if not hits:
        hits = [v for v in views if v.contains(pts[0])]
    return min(hits, key=lambda v: v.size[0] * v.size[1]) if hits else None


def build_rows(views: list, recs: list) -> list:
    """ビュー順(ビュー外は最後)に並べた CSV の行"""
    if views:
        factor = calibrate(views, recs)
        for v in views:
            v.scaled(factor)
        name_views(views)
        print(f"単位換算(API→LISP): x{factor:g}")

    groups = {}
    for r in recs:
        groups.setdefault(find_view(views, r), []).append(r)

    order = [v for v in views if v in groups]
    if None in groups:
        order.append(None)
    rows = []
    for v in order:
        name = v.name if v else OUTSIDE_NAME
        for r in groups[v]:
            rows.append(to_row(len(rows) + 1, name, r))
    return rows


# ---------------------------------------------------------------- 寸法の項目


def to_row(no: int, view_name: str, r: dict) -> list:
    upper, lower = tolerance(r)
    return [no, view_name, kind_name(r), nominal_value(r), upper, lower]


def kind_name(r: dict) -> str:
    ent = r["ent"].upper()
    if ent == "ARC_DIMENSION":
        return "弧長"
    if ent == "LARGE_RADIAL_DIMENSION":
        return "半径(折れ線)"
    flags = int(to_float(r["type"]) or 0)
    kind = flags & 7
    if kind == 6:
        return "座標(X)" if flags & 64 else "座標(Y)"
    return KIND_NAMES.get(kind, ent)


def nominal_value(r: dict) -> str:
    """測定値を寸法スタイルの表示桁に丸め、寸法種類の記号を付ける。"""
    try:
        value = Decimal(r["value"])
    except (TypeError, ValueError, ArithmeticError):
        return ""
    if not value.is_finite():
        return ""

    ent = r["ent"].upper()
    kind = int(to_float(r["type"]) or 0) & 7
    angular = kind in (2, 5) and ent not in ("ARC_DIMENSION", "LARGE_RADIAL_DIMENSION")
    places = to_float(r["dimadec" if angular else "dimdec"])
    if angular and places == -1:
        places = to_float(r["dimdec"])
    places = int(places) if places is not None and places.is_integer() and 0 <= places <= 8 else (3 if angular else 6)
    if angular:
        places = min(places, 3)
    zero_code = to_float(r["dimazin" if angular else "dimzin"])
    zero_code = int(zero_code) if zero_code is not None else (0 if angular else 8)

    try:
        if angular:
            value = Decimal(str(math.degrees(float(value))))
        rounded = value.quantize(Decimal(1).scaleb(-places), rounding=ROUND_HALF_UP)
    except (InvalidOperation, OverflowError, ValueError):
        return ""
    if rounded == 0:
        rounded = abs(rounded)
    number = f"{rounded:.{places}f}"
    suppress_trailing = angular or bool(zero_code & 8)
    suppress_leading = zero_code & (1 if angular else 4)
    if suppress_trailing and "." in number:
        number = number.rstrip("0").rstrip(".")
    if suppress_leading and number.startswith(("0.", "-0.")):
        number = number.replace("0.", ".", 1)

    if ent == "ARC_DIMENSION":
        return number
    if ent == "LARGE_RADIAL_DIMENSION" or kind == 4:
        return "R" + number
    if kind == 3:
        return "φ" + number
    if angular:
        return number + "°"
    return number


def tolerance(r: dict):
    """(上の許容差, 下の許容差)。公差なしは ("", "")"""
    value = to_float(r["value"])
    tp, tm = to_float(r["dimtp"]), to_float(r["dimtm"])
    if to_float(r["dimtol"]) == 1 and tp is not None and tm is not None:
        return signed(tp), signed(-tm)
    if to_float(r["dimlim"]) == 1 and tp is not None and tm is not None and value is not None:
        # 限界寸法: 上限・下限
        return fmt(value + tp), fmt(value - tm)

    # スタイルで判別できない場合は表示文字列から拾う
    raw = r["text"] or r["override"]
    m = re.search(r"\\S([^;]*?)[\^/#]([^;]*);", raw)
    if m:
        a, b = to_float(m.group(1).strip()), to_float(m.group(2).strip())
        if a is not None and b is not None:
            return signed(a), signed(b)
    m = re.search(r"(?:%%[pP]|±)\s*([0-9.]+)", raw)
    if m:
        t = to_float(m.group(1))
        if t is not None:
            return signed(t), signed(-t)
    return "", ""


def to_float(s: str):
    try:
        return float(s)
    except (TypeError, ValueError):
        return None


def fmt(v) -> str:
    return "" if v is None else f"{round(v, 6):g}"


def signed(v: float) -> str:
    v = round(v, 6)
    return "0" if v == 0 else f"{v:+g}"


def safe_name(name: str) -> str:
    return re.sub(r'[\\/:*?"<>|]', "_", name)


# ---------------------------------------------------------------- LISP実行


def to_lisp(src: str) -> str:
    # テキストコマンドでは " と chr が使えないため、文字列リテラルをシンボル名から組み立てる
    return re.sub(
        r'"([^"]*)"',
        lambda m: lisp_str(m.group(1)),
        " ".join(src.split()),
    )


def lisp_str(text: str) -> str:
    if not text:
        return "(substr (itoa 1) 2)"

    parts = []
    for tok in re.findall(r"[A-Z_]+|[a-z]+|[0-9]|.", text):
        if re.fullmatch(r"[A-Z_]+", tok) or tok in "/*-":
            parts.append(f"(vl-symbol-name (quote {tok}))")
        elif tok.islower():
            parts.append(f"(strcase (vl-symbol-name (quote {tok})) t)")
        elif tok.isdigit():
            parts.append(f"(itoa {tok})")
        else:
            raise ValueError(f"LISPに渡せない文字です: {tok!r}")

    if len(parts) == 1:
        return parts[0]
    return "(strcat " + " ".join(parts) + ")"


def exec_lisp(src: str) -> str:
    app: core.Application = core.Application.get()
    try:
        return app.executeTextCommand(f"FusionDoc.ExecuteAcadCommand {src}")
    except Exception as e:
        return f"NG {e}"


def wait_result(path: str, timeout: float = 5.0) -> list:
    # 非同期で実行される場合に備え、終了マークが書かれるまで待つ
    start = time.time()
    while time.time() - start < timeout:
        adsk.doEvents()
        if os.path.exists(path):
            with open(path, "rb") as f:
                lines = decode(f.read()).splitlines()
            if lines and lines[-1] == END_MARK:
                return lines[:-1]
        time.sleep(0.1)
    return None


def decode(data: bytes) -> str:
    try:
        return data.decode("utf-8")
    except UnicodeDecodeError:
        return data.decode("cp932", errors="replace")