;;; AutoCATS 리습 자료실
;; 명령: XYZMOVE
;; 기능: 선택한 객체를 WCS 기준 ΔX·ΔY·ΔZ만큼 평행이동합니다.
;; 출처: https://www.autocats.co.kr/lisp/coordinate-shift
;; 버전: 1.0 (2026-10-23)
;; 라이선스: 자유 사용·수정, 재배포 시 출처(autocats.co.kr) 표기
;; 안전: 잠긴 레이어·외부참조 보호, 변경은 UNDO 그룹, 명령별 범위는 상세 가이드 참고

(vl-load-com)

(defun autocats-xyzmove-safe-p (ent / data row block)
  (setq data (entget ent)
    row (tblsearch "LAYER" (cdr (assoc 8 data))))
  (and data row (= 0 (logand 4 (cdr (assoc 70 row))))
    (or (/= "INSERT" (cdr (assoc 0 data)))
      (and (setq block (tblsearch "BLOCK" (cdr (assoc 2 data))))
        (= 0 (logand 12 (cdr (assoc 70 block))))))))

(defun autocats-xyzmove-batch (selection action / index changed skipped ent result)
  (setq index 0 changed 0 skipped 0)
  (if selection
    (repeat (sslength selection)
      (setq ent (ssname selection index)
        result (if (autocats-xyzmove-safe-p ent) (vl-catch-all-apply action (list ent))))
      (if (and result (not (vl-catch-all-error-p result)))
        (setq changed (1+ changed))
        (setq skipped (1+ skipped)))
      (setq index (1+ index))))
  (princ (strcat "\n[XYZMOVE] 완료: " (itoa changed) " / 건너뜀: " (itoa skipped)))
  (list changed skipped))

(defun autocats-xyzmove-apply (ent delta / result before)
  (if (autocats-xyzmove-safe-p ent)
    (progn
      (setq before (entget ent) result (vl-catch-all-apply
          '(lambda () (command "_.MOVE" ent "" "_non" (trans '(0.0 0.0 0.0) 0 1)
              "_non" (trans delta 0 1)) T)))
      (and (not (vl-catch-all-error-p result)) (not (equal before (entget ent)))))))

(defun c:XYZMOVE (/ *error* undo-open x y z delta selection)
  (defun *error* (msg)
    (if undo-open (progn (command-s "_.UNDO" "_End") (setq undo-open nil)))
    (if (and msg (not (wcmatch (strcase msg) "*CANCEL*,*QUIT*,*EXIT*,*취소*")))
      (princ (strcat "\n[XYZMOVE] 중단: " msg)))
    (princ))

  (setq x (getreal "\nWCS Delta X <0>: ") y (getreal "\nWCS Delta Y <0>: ") z (getreal "\nWCS Delta Z <0>: ")
    delta (mapcar '(lambda (v) (if v v 0.0)) (list x y z)))

  (princ "\n대상 객체를 선택하세요: ")
  (setq selection (ssget '((0 . "*"))))
  (if selection
    (progn
      (command "_.UNDO" "_Begin")

      (setq undo-open T)
      (autocats-xyzmove-batch selection '(lambda (ent) (autocats-xyzmove-apply ent delta)))
      (command "_.UNDO" "_End")
      (setq undo-open nil)))

  (princ))

(princ "\n[AutoCATS] XYZMOVE 로드 완료")
(princ)
