diff --git a/SourceCode/Code2026/cad_mcp_frame/cmakelists.txt b/SourceCode/Code2026/cad_mcp_frame/cmakelists.txt index f7df56f..213f719 100644 --- a/SourceCode/Code2026/cad_mcp_frame/cmakelists.txt +++ b/SourceCode/Code2026/cad_mcp_frame/cmakelists.txt @@ -22,8 +22,8 @@ target_set_name_and_suffix(CadMcpFrame "cad_mcp_frame" ".arx") target_link_objectarx(CadMcpFrame CADMCPFRAME_EXPORT) -# 模块自己的头目录(mcp_plugin_api.h 等插件接口) -target_include_directories(CadMcpFrame PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/inc") +# mcp_plugin_api.h 已上移到 SourceCode/Code2026/inc(frame 与 plugins 共用), +# 由 target_link_objectarx 引入的 ShsGlobalIncludes 自动可见 target_compile_definitions(CadMcpFrame PRIVATE AECRXBASE_EXPORT diff --git a/SourceCode/Code2026/cad_mcp_frame/mcp_ConfigParser.cpp b/SourceCode/Code2026/cad_mcp_frame/mcp_ConfigParser.cpp index d864fef..e1eb573 100644 --- a/SourceCode/Code2026/cad_mcp_frame/mcp_ConfigParser.cpp +++ b/SourceCode/Code2026/cad_mcp_frame/mcp_ConfigParser.cpp @@ -92,7 +92,11 @@ void mcp_ConfigParser::LoadDllTool(const nlohmann::json &toolConfig, const std:: // 1. 定义版本校验函数指针 typedef int (*GetApiVersionFunc)(); +#ifdef ZWCAD + GetApiVersionFunc getVerFn = (GetApiVersionFunc)GetProcAddress(hMod, "zcrxGetApiVersion"); +#else GetApiVersionFunc getVerFn = (GetApiVersionFunc)GetProcAddress(hMod, "acrxGetApiVersion"); +#endif // 2. 核心拦截逻辑 if (!getVerFn) diff --git a/SourceCode/Code2026/cad_mcp_plugins/StdAfx.cpp b/SourceCode/Code2026/cad_mcp_plugins/StdAfx.cpp new file mode 100644 index 0000000..3743d0c --- /dev/null +++ b/SourceCode/Code2026/cad_mcp_plugins/StdAfx.cpp @@ -0,0 +1,6 @@ +// StdAfx.cpp : source file that includes just the standard includes +// StdAfx.pch will be the pre-compiled header +// StdAfx.obj will contain the pre-compiled type information + +#include "StdAfx.h" + diff --git a/SourceCode/Code2026/cad_mcp_plugins/StdAfx.h b/SourceCode/Code2026/cad_mcp_plugins/StdAfx.h new file mode 100644 index 0000000..3fb8896 --- /dev/null +++ b/SourceCode/Code2026/cad_mcp_plugins/StdAfx.h @@ -0,0 +1,50 @@ +#pragma once + +#if _MSC_VER > 1000 +#pragma once +#endif // _MSC_VER > 1000 + +#define WINVER 0x0600 + +#pragma warning(disable: 4786) + +//- 'DEBUG workaround' below prevents the MFC or ATL #include-s from pulling +//- in "Afx.h" that would force the debug CRT through #pragma-s. +#if defined(_DEBUG) && !defined(AC_FULL_DEBUG) +#define _DEBUG_WAS_DEFINED +#undef _DEBUG +#pragma message ("Compiling MFC / STL / ATL header files in release mode.") +#endif + +#pragma pack (push, 8) +#pragma warning(disable: 4786 4996) + +#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers + +#include // MFC core and standard components +#include // MFC extensions + +#ifndef _AFX_NO_OLE_SUPPORT +#include // MFC OLE classes +#include // MFC OLE dialog classes +#include // MFC Automation classes +#endif + +#include // MFC support for Internet Explorer 4 Common Controls +#ifndef _AFX_NO_AFXCMN_SUPPORT +#include // MFC support for Windows Common Controls +#endif + +#include +#include +#include +#include +#include + +extern HINSTANCE _hdllInstance; + +#ifdef _DEBUG_WAS_DEFINED +#define _DEBUG +#undef _DEBUG_WAS_DEFINED +#endif + diff --git a/SourceCode/Code2026/cad_mcp_plugins/cmakelists.txt b/SourceCode/Code2026/cad_mcp_plugins/cmakelists.txt new file mode 100644 index 0000000..9175ca5 --- /dev/null +++ b/SourceCode/Code2026/cad_mcp_plugins/cmakelists.txt @@ -0,0 +1,38 @@ +cmake_minimum_required(VERSION 3.16) + +project(CadMcpPlugins) + +set(SOURCES + "mcp_plugins.cpp" + "dwg_review_common.cpp" + "dwg_review_overview.cpp" + "dwg_review_query.cpp" + "dwg_review_frame.cpp" + "dwg_review_check.cpp" + "dwg_review_view.cpp" + "StdAfx.cpp" +) + +add_library(CadMcpPlugins SHARED ${SOURCES}) + +target_precompile_headers(CadMcpPlugins PRIVATE StdAfx.h) + +# 插件是普通 DLL(由 cad_mcp_frame 在运行时 LoadLibrary),不是 .arx +target_set_name_and_suffix(CadMcpPlugins "cad_mcp_plugins" ".dll") + +target_link_objectarx(CadMcpPlugins CADMCPPLUGINS_EXPORT) + +target_compile_definitions(CadMcpPlugins PRIVATE + AECRXBASE_EXPORT + EARTHWORM_EXPORT +) + +# 与 cad_mcp_frame 相同:原工程由 CadProject 的 cmake 注入 SUB_ARX(中望没有子版本) +if (IS_ZWCAD) + target_compile_definitions(CadMcpPlugins PRIVATE SUB_ARX=0) +else() + target_compile_definitions(CadMcpPlugins PRIVATE SUB_ARX=${CAD_SDK_SUBVERSION}) +endif() + +# nlohmann/json 通过 DEP_INC_ROOT 可见;插件不需要链接 AecRxBase +set_debug_post_build(CadMcpPlugins "cad_mcp_plugins" ".dll") diff --git a/SourceCode/Code2026/cad_mcp_plugins/dwg_review_check.cpp b/SourceCode/Code2026/cad_mcp_plugins/dwg_review_check.cpp new file mode 100644 index 0000000..13fd5f9 --- /dev/null +++ b/SourceCode/Code2026/cad_mcp_plugins/dwg_review_check.cpp @@ -0,0 +1,234 @@ +// ============================================================================ +// dwg_review_check.cpp +// 图纸审查 - 确定性检查工具(均为 c++_dll 后端) +// find_duplicate_entities : 几何重复 / 重叠实体 +// find_zero_length : 零长度 / 退化实体 +// ============================================================================ + +#include "KTCad.h" +#include "dwg_review_common.h" +#include "mcp_plugin_api.h" + +#include +#include +#include +#include +#include + +using namespace dwg_review; + +namespace +{ + const double kPi = 3.14159265358979323846; + + bool typeMatches(const std::string& type, const nlohmann::json& filter) + { + if (!filter.is_array() || filter.empty()) return true; + for (size_t i = 0; i < filter.size(); ++i) + if (filter[i].is_string() && filter[i].get() == type) return true; + return false; + } + + // 把坐标量化到 tolerance 网格,得到可比较的字符串 + std::string quant(double v, double tol) + { + long long k = (long long)::llround(v / (tol > 1e-12 ? tol : 1e-12)); + return std::to_string(k); + } + + std::string q3(double x, double y, double z, double tol) + { + return quant(x, tol) + "," + quant(y, tol) + "," + quant(z, tol); + } + + // 计算多段线总长度 + double polyLength(AcDbPolyline* p) + { + if (!p) return 0.0; + double len = 0.0; + const int n = p->numVerts(); + for (int i = 0; i + 1 < n; ++i) + { + AcGePoint2d a, b; + if (p->getPointAt(i, a) == Acad::eOk && p->getPointAt(i + 1, b) == Acad::eOk) + len += a.distanceTo(b); + } + if (p->isClosed() && n > 1) + { + AcGePoint2d a, b; + if (p->getPointAt(n - 1, a) == Acad::eOk && p->getPointAt(0, b) == Acad::eOk) + len += a.distanceTo(b); + } + return len; + } + + // 构造几何签名(仅对支持的类型返回 true) + bool buildSignature(AcDbEntity* pEnt, double tol, + const nlohmann::json& typeFilter, + std::string& sig, std::string& type) + { + type = entityTypeName(pEnt); + if (!typeMatches(type, typeFilter)) return false; + + if (AcDbLine* p = AcDbLine::cast(pEnt)) + { + double ax = p->startPoint().x, ay = p->startPoint().y, az = p->startPoint().z; + double bx = p->endPoint().x, by = p->endPoint().y, bz = p->endPoint().z; + // 端点顺序无关 + if (ax > bx || (ax == bx && ay > by) || (ax == bx && ay == by && az > bz)) + { + std::swap(ax, bx); std::swap(ay, by); std::swap(az, bz); + } + sig = "LINE:" + q3(ax, ay, az, tol) + ";" + q3(bx, by, bz, tol); + return true; + } + if (AcDbArc* p = AcDbArc::cast(pEnt)) + { + sig = "ARC:" + q3(p->center().x, p->center().y, p->center().z, tol) + + ";r" + quant(p->radius(), tol) + + ";a" + quant(p->startAngle(), tol) + ";" + quant(p->endAngle(), tol); + return true; + } + if (AcDbCircle* p = AcDbCircle::cast(pEnt)) + { + sig = "CIRCLE:" + q3(p->center().x, p->center().y, p->center().z, tol) + + ";r" + quant(p->radius(), tol); + return true; + } + if (AcDbPoint* p = AcDbPoint::cast(pEnt)) + { + sig = "POINT:" + q3(p->position().x, p->position().y, p->position().z, tol); + return true; + } + if (AcDbPolyline* p = AcDbPolyline::cast(pEnt)) + { + std::string s = "LWPOLYLINE:"; + const int n = p->numVerts(); + for (int i = 0; i < n; ++i) + { + AcGePoint2d pt; + if (p->getPointAt(i, pt) != Acad::eOk) return false; + s += q3(pt.x, pt.y, 0.0, tol) + "|"; + } + s += (p->isClosed() ? "C" : "O"); + sig = s; + return true; + } + return false; + } +} + +// =========================================================================== +// find_duplicate_entities +// =========================================================================== +class mcp_Tool_FindDuplicateEntities : public mcp_Tool +{ +public: + nlohmann::json Execute(const nlohmann::json& args) override + { + const CommonQuery q = parseCommonQuery(args); + const double tol = args.value("tolerance", 0.001); + const nlohmann::json typeFilter = + args.contains("type_filter") ? args["type_filter"] : nlohmann::json(); + const int groupLimit = args.value("limit", 200); + + std::map > buckets; + std::map bucketType; + + forEachEntity(q, [&](AcDbEntity* pEnt) -> bool + { + std::string sig, type; + if (buildSignature(pEnt, tol, typeFilter, sig, type)) + { + buckets[sig].push_back(handleOf(pEnt)); + bucketType[sig] = type; + } + return true; + }); + + nlohmann::json groups = nlohmann::json::array(); + int count = 0; + for (std::map >::iterator it = buckets.begin(); + it != buckets.end(); ++it) + { + if (it->second.size() < 2) continue; // 只保留重复组 + if (count >= groupLimit) break; + + nlohmann::json g; + g["reason"] = "identical_geometry"; + g["type"] = bucketType[it->first]; + nlohmann::json hs = nlohmann::json::array(); + for (size_t i = 0; i < it->second.size(); ++i) hs.push_back(it->second[i]); + g["handles"] = hs; + groups.push_back(g); + ++count; + } + + nlohmann::json r; + r["count"] = count; + r["groups"] = groups; + return makeJsonResult(r); + } +}; +EXPORT_MCP_TOOL(mcp_Tool_FindDuplicateEntities, CreateFindDuplicateEntitiesTool) + +// =========================================================================== +// find_zero_length +// =========================================================================== +class mcp_Tool_FindZeroLength : public mcp_Tool +{ +public: + nlohmann::json Execute(const nlohmann::json& args) override + { + const CommonQuery q = parseCommonQuery(args); + const double tol = args.value("tolerance", 0.001); + + int total = 0, returned = 0; + nlohmann::json items = nlohmann::json::array(); + + forEachEntity(q, [&](AcDbEntity* pEnt) -> bool + { + double len = -1.0; + const std::string type = entityTypeName(pEnt); + + if (AcDbLine* p = AcDbLine::cast(pEnt)) + { + len = p->startPoint().distanceTo(p->endPoint()); + } + else if (AcDbArc* p = AcDbArc::cast(pEnt)) + { + double span = p->endAngle() - p->startAngle(); + while (span < 0.0) span += 2.0 * kPi; + while (span > 2.0 * kPi) span -= 2.0 * kPi; + len = p->radius() * span; + } + else if (AcDbPolyline* p = AcDbPolyline::cast(pEnt)) + { + len = polyLength(p); + } + else + { + return true; + } + + if (len >= 0.0 && len < tol) + { + if (total >= q.offset && returned < q.limit) + { + nlohmann::json o; + o["handle"] = handleOf(pEnt); + o["type"] = type; + o["layer"] = layerOf(pEnt); + o["length"] = len; + items.push_back(o); + ++returned; + } + ++total; + } + return true; + }); + + return makeJsonResult(pageResult(total, returned, q.offset, items)); + } +}; +EXPORT_MCP_TOOL(mcp_Tool_FindZeroLength, CreateFindZeroLengthTool) diff --git a/SourceCode/Code2026/cad_mcp_plugins/dwg_review_common.cpp b/SourceCode/Code2026/cad_mcp_plugins/dwg_review_common.cpp new file mode 100644 index 0000000..9df63c8 --- /dev/null +++ b/SourceCode/Code2026/cad_mcp_plugins/dwg_review_common.cpp @@ -0,0 +1,319 @@ +#include "KTCad.h" +#include "dwg_review_common.h" +#include "mcp_plugin_api.h" // 复用 mcp_Tool_Utility 构造 MCP 结果信封 + +#include +#include + +namespace dwg_review +{ + +// =========================================================================== +// 字符串 / 实体基础读取 +// =========================================================================== + +std::string wstrToUtf8(const std::wstring& w) +{ + if (w.empty()) return std::string(); + int len = ::WideCharToMultiByte(CP_UTF8, 0, w.c_str(), (int)w.size(), NULL, 0, NULL, NULL); + if (len <= 0) return std::string(); + std::string out((size_t)len, '\0'); + ::WideCharToMultiByte(CP_UTF8, 0, w.c_str(), (int)w.size(), &out[0], len, NULL, NULL); + return out; +} + +std::string acharToUtf8(const ACHAR* s) +{ + if (!s) return std::string(); +#ifdef _UNICODE + return wstrToUtf8(std::wstring(s)); +#else + return std::string(s); +#endif +} + +std::string handleOf(AcDbEntity* pEnt) +{ + if (!pEnt) return std::string(); + AcDbHandle h; + pEnt->getAcDbHandle(h); + ACHAR buf[64] = { 0 }; + h.getIntoAsciiBuffer(buf, 64); + return acharToUtf8(buf); +} + +std::string layerOf(AcDbEntity* pEnt) +{ + if (!pEnt) return std::string(); + return acharToUtf8(pEnt->layer()); +} + +std::string entityTypeName(AcDbEntity* pEnt) +{ + if (!pEnt) return std::string(); + + // 注意判定顺序:派生类必须先于基类 + if (AcDbBlockReference::cast(pEnt)) return "INSERT"; + if (AcDbAttribute::cast(pEnt)) return "ATTRIB"; + if (AcDbAttributeDefinition::cast(pEnt)) return "ATTDEF"; + if (AcDbMText::cast(pEnt)) return "MTEXT"; + if (AcDbText::cast(pEnt)) return "TEXT"; + if (AcDbArc::cast(pEnt)) return "ARC"; // Arc 派生自 Circle + if (AcDbCircle::cast(pEnt)) return "CIRCLE"; + if (AcDbLine::cast(pEnt)) return "LINE"; + if (AcDbPolyline::cast(pEnt)) return "LWPOLYLINE"; + if (AcDb2dPolyline::cast(pEnt)) return "POLYLINE"; + if (AcDbDimension::cast(pEnt)) return "DIMENSION"; + if (AcDbEllipse::cast(pEnt)) return "ELLIPSE"; + if (AcDbSpline::cast(pEnt)) return "SPLINE"; + if (AcDbPoint::cast(pEnt)) return "POINT"; + + // 兜底:取类名去掉 AcDb 前缀并大写 + std::string n = acharToUtf8(pEnt->isA()->name()); + if (n.rfind("AcDb", 0) == 0) n = n.substr(4); + for (size_t i = 0; i < n.size(); ++i) + n[i] = (char)::toupper((unsigned char)n[i]); + return n; +} + +bool entityBBox(AcDbEntity* pEnt, BBox& out) +{ + out = BBox(); + if (!pEnt) return false; + try + { + AcDbExtents ext; + if (pEnt->getGeomExtents(ext) != Acad::eOk) return false; + out.minX = ext.minPoint().x; + out.minY = ext.minPoint().y; + out.maxX = ext.maxPoint().x; + out.maxY = ext.maxPoint().y; + out.valid = true; + return true; + } + catch (...) + { + return false; // 部分实体(如空块、特殊动态块)取范围会抛异常 + } +} + +std::string blockNameOf(AcDbBlockReference* pRef) +{ + if (!pRef) return std::string(); + AcDbBlockTableRecord* pRec = nullptr; + std::string name; + if (acdbOpenObject(pRec, pRef->blockTableRecord(), AcDb::kForRead) == Acad::eOk && pRec) + { + const ACHAR* nm = NULL; + if (pRec->getName(nm) == Acad::eOk && nm) name = acharToUtf8(nm); + pRec->close(); + } + return name; +} + +bool objectIdFromHandle(const std::string& handleStr, AcDbObjectId& out) +{ + AcDbDatabase* pDb = acdbHostApplicationServices()->workingDatabase(); + if (!pDb) return false; + std::wstring ws(handleStr.begin(), handleStr.end()); + AcDbHandle h(ws.c_str()); // AcDbHandle(const ACHAR*) + return pDb->getAcDbObjectId(out, false, h) == Acad::eOk; +} + +// =========================================================================== +// 匹配 / 过滤 +// =========================================================================== + +bool wildcardMatch(const std::string& name, const std::string& pattern) +{ + if (pattern.empty()) return true; // 空模式 = 全部匹配 + + size_t n = name.size(), m = pattern.size(); + size_t i = 0, j = 0, star = (size_t)-1, mark = 0; + while (i < n) + { + if (j < m && (pattern[j] == '?' || + ::tolower((unsigned char)pattern[j]) == ::tolower((unsigned char)name[i]))) + { + ++i; ++j; + } + else if (j < m && pattern[j] == '*') + { + star = j++; mark = i; + } + else if (star != (size_t)-1) + { + j = star + 1; i = ++mark; + } + else + { + return false; + } + } + while (j < m && pattern[j] == '*') ++j; + return j == m; +} + +bool bboxInWindow(const BBox& b, const CommonQuery& q) +{ + if (!q.useWindow) return true; + if (!b.valid) return false; + if (b.maxX < q.minX || b.minX > q.maxX) return false; + if (b.maxY < q.minY || b.minY > q.maxY) return false; + return true; +} + +bool layerAccepted(AcDbEntity* pEnt, const CommonQuery& q) +{ + return wildcardMatch(layerOf(pEnt), q.layerFilter); +} + +// =========================================================================== +// 空间定位 / 遍历 +// =========================================================================== + +AcDbBlockTableRecord* openSpace(AcDbDatabase* pDb, const std::string& space) +{ + if (!pDb) return nullptr; + + AcDbBlockTable* pBT = nullptr; + if (pDb->getBlockTable(pBT, AcDb::kForRead) != Acad::eOk) return nullptr; + + AcDbBlockTableRecord* pRec = nullptr; + if (space.empty() || space == "Model" || space == "model") + { + pBT->getAt(ACDB_MODEL_SPACE, pRec, AcDb::kForRead); + } + else + { + AcDbObjectId id; + std::wstring ws(space.begin(), space.end()); + if (pBT->getAt(ws.c_str(), id) == Acad::eOk) + acdbOpenObject(pRec, id, AcDb::kForRead); + } + pBT->close(); + return pRec; +} + +void forEachEntity(const CommonQuery& q, const EntityVisitor& visitor) +{ + AcDbDatabase* pDb = acdbHostApplicationServices()->workingDatabase(); + if (!pDb) return; + + AcDbBlockTableRecord* pSpace = openSpace(pDb, q.space); + if (!pSpace) return; + + AcDbBlockTableRecordIterator* pIter = nullptr; + if (pSpace->newIterator(pIter) != Acad::eOk || !pIter) + { + pSpace->close(); + return; + } + + for (pIter->start(); !pIter->done(); pIter->step()) + { + AcDbEntity* pEnt = nullptr; + if (pIter->getEntity(pEnt, AcDb::kForRead) != Acad::eOk || !pEnt) continue; + + bool cont = true; + if (layerAccepted(pEnt, q)) + { + if (q.useWindow) + { + BBox b; + if (entityBBox(pEnt, b) && bboxInWindow(b, q)) + cont = visitor(pEnt); + } + else + { + cont = visitor(pEnt); + } + } + pEnt->close(); + if (!cont) break; + } + + delete pIter; + pSpace->close(); +} + +// =========================================================================== +// 通用查询参数解析 +// =========================================================================== + +CommonQuery parseCommonQuery(const nlohmann::json& args) +{ + CommonQuery q; + + if (args.contains("space") && args["space"].is_string()) + q.space = args["space"].get(); + if (args.contains("layer_filter") && args["layer_filter"].is_string()) + q.layerFilter = args["layer_filter"].get(); + if (args.contains("limit") && args["limit"].is_number_integer()) + q.limit = args["limit"].get(); + if (args.contains("offset") && args["offset"].is_number_integer()) + q.offset = args["offset"].get(); + + if (q.limit <= 0) q.limit = 200; + if (q.limit > 1000) q.limit = 1000; + if (q.offset < 0) q.offset = 0; + + if (args.contains("window") && args["window"].is_object()) + { + const nlohmann::json& w = args["window"]; + if (w.contains("min_x") && w.contains("min_y") && + w.contains("max_x") && w.contains("max_y")) + { + q.useWindow = true; + q.minX = w["min_x"].get(); + q.minY = w["min_y"].get(); + q.maxX = w["max_x"].get(); + q.maxY = w["max_y"].get(); + } + } + return q; +} + +// =========================================================================== +// 结果封装 +// =========================================================================== + +nlohmann::json pageResult(int total, int returned, int offset, const nlohmann::json& items) +{ + nlohmann::json j; + j["total"] = total; + j["returned"] = returned; + j["offset"] = offset; + j["items"] = items; + return j; +} + +nlohmann::json makeError(int code, const std::string& msg) +{ + nlohmann::json j; + j["error"] = { { "code", code }, { "message", msg } }; + return j; +} + +nlohmann::json makeJsonResult(const nlohmann::json& data) +{ + std::wstring w = mcp_Tool_Utility::utf8ToWString(data.dump()); + return mcp_Tool_Utility::make_text_result(w); +} + +nlohmann::json point2Json(double x, double y) +{ + return nlohmann::json::array({ x, y }); +} + +nlohmann::json point3Json(double x, double y, double z) +{ + return nlohmann::json::array({ x, y, z }); +} + +nlohmann::json bboxJson(const BBox& b) +{ + return nlohmann::json::array({ b.minX, b.minY, b.maxX, b.maxY }); +} + +} // namespace dwg_review diff --git a/SourceCode/Code2026/cad_mcp_plugins/dwg_review_common.h b/SourceCode/Code2026/cad_mcp_plugins/dwg_review_common.h new file mode 100644 index 0000000..2a234a5 --- /dev/null +++ b/SourceCode/Code2026/cad_mcp_plugins/dwg_review_common.h @@ -0,0 +1,90 @@ +#pragma once +// ============================================================================ +// dwg_review_common.h +// 图纸审查工具集 - 公共辅助层 +// +// 供 dwg_review_overview / dwg_review_query / dwg_review_frame / +// dwg_review_check / dwg_review_view 共用,避免各工具重复实现: +// - 字符串/句柄/图层/实体类型/包围盒 等基础读取 +// - 通配符匹配、扫描范围过滤 +// - 通用查询参数解析 (space / layer_filter / window / limit / offset) +// - 空间定位与统一实体遍历 forEachEntity +// - 分页信封、错误体、坐标序列化 +// ============================================================================ + +#include "KTCad.h" +#include +#include +#include +#include + +namespace dwg_review +{ + +// 审查工具统一错误码区间 +enum ReviewErrorCode +{ + kErrBadParam = -32001, // 参数非法 + kErrNotFound = -32002, // 实体/图层等未找到 + kErrNoDocument = -32003, // 无活动文档 + kErrInternal = -32603 // 内部错误 +}; + +// 通用查询参数(所有"读"类工具共用) +struct CommonQuery +{ + std::string space = "Model"; // "Model" 或布局名 + std::string layerFilter; // 图层通配符,空 = 不过滤 + bool useWindow = false; // 是否限定扫描范围 + double minX = 0.0, minY = 0.0, maxX = 0.0, maxY = 0.0; + int limit = 200; // 单次最大返回,上限 1000 + int offset = 0; // 分页偏移 +}; + +// 包围盒 +struct BBox +{ + double minX = 0.0, minY = 0.0, maxX = 0.0, maxY = 0.0; + bool valid = false; +}; + +// 解析通用查询参数 +CommonQuery parseCommonQuery(const nlohmann::json& args); + +// ---------- 基础读取 ---------- +std::string wstrToUtf8(const std::wstring& w); +std::string acharToUtf8(const ACHAR* s); +std::string handleOf(AcDbEntity* pEnt); // 实体句柄(大写十六进制) +std::string layerOf(AcDbEntity* pEnt); // 实体所在图层名 +std::string entityTypeName(AcDbEntity* pEnt); // DXF 风格类型名,如 "LINE" +bool entityBBox(AcDbEntity* pEnt, BBox& out); // 取几何包围盒(含异常保护) +std::string blockNameOf(AcDbBlockReference* pRef); // 取块参照的块名(经块表记录) +bool objectIdFromHandle(const std::string& handleStr, AcDbObjectId& out); // 句柄字符串 -> ObjectId + +// ---------- 匹配 / 过滤 ---------- +bool wildcardMatch(const std::string& name, const std::string& pattern); +bool bboxInWindow(const BBox& b, const CommonQuery& q); +bool layerAccepted(AcDbEntity* pEnt, const CommonQuery& q); + +// ---------- 遍历 ---------- +// 打开指定空间的块表记录(成功返回的对象需调用者 close) +AcDbBlockTableRecord* openSpace(AcDbDatabase* pDb, const std::string& space); + +// 实体访问器:返回 false 可提前终止遍历 +typedef std::function EntityVisitor; + +// 遍历指定空间实体:自动处理图层过滤、范围过滤、对象关闭。 +// 注意:实体以 kForRead 打开,visitor 内只做读取;需要写操作请自行按句柄重开。 +void forEachEntity(const CommonQuery& q, const EntityVisitor& visitor); + +// ---------- 结果封装 ---------- +nlohmann::json pageResult(int total, int returned, int offset, const nlohmann::json& items); +nlohmann::json makeError(int code, const std::string& msg); +// 把数据包装为 MCP 文本结果信封:{"result":{"content":[{"type":"text","text":}]}} +// 与既有截图工具返回结构保持一致,便于标准 MCP 客户端 / agent 统一读取 result.content。 +nlohmann::json makeJsonResult(const nlohmann::json& data); +nlohmann::json point2Json(double x, double y); +nlohmann::json point3Json(double x, double y, double z); +nlohmann::json bboxJson(const BBox& b); + +} // namespace dwg_review diff --git a/SourceCode/Code2026/cad_mcp_plugins/dwg_review_frame.cpp b/SourceCode/Code2026/cad_mcp_plugins/dwg_review_frame.cpp new file mode 100644 index 0000000..743b0dd --- /dev/null +++ b/SourceCode/Code2026/cad_mcp_plugins/dwg_review_frame.cpp @@ -0,0 +1,419 @@ +// ============================================================================ +// dwg_review_frame.cpp +// 图纸审查 - 图框识别实现 +// 同时导出 detect_drawing_frames 工具。 +// ============================================================================ + +#include "KTCad.h" +#include "dwg_review_common.h" +#include "dwg_review_frame.h" +#include "mcp_plugin_api.h" + +#include +#include +#include + +using namespace dwg_review; + +namespace +{ + // ---------- 基础 ---------- + bool approxEq(double a, double b, double tol) { return fabs(a - b) <= tol; } + + std::string toLower(const std::string& s) + { + std::string r = s; + for (size_t i = 0; i < r.size(); ++i) + r[i] = (char)::tolower((unsigned char)r[i]); + return r; + } + + bool containsCI(const std::string& hay, const std::string& needle) + { + if (needle.empty()) return false; + return toLower(hay).find(toLower(needle)) != std::string::npos; + } + + // ---------- 标准图幅 ---------- + struct SheetDef { const char* name; double w; double h; }; + static const SheetDef kSheets[] = { + { "A0", 1189.0, 841.0 }, + { "A1", 841.0, 594.0 }, + { "A2", 594.0, 420.0 }, + { "A3", 420.0, 297.0 }, + { "A4", 297.0, 210.0 } + }; + static const int kSheetCount = 5; + static const double kBaseAspect = 1.41421356; // √2 + static const double kScales[] = { 1.0, 2.0, 2.5, 5.0, 10.0, 20.0, 25.0, 30.0, + 40.0, 50.0, 100.0, 150.0, 200.0, 250.0, 300.0, + 400.0, 500.0 }; + static const int kScaleCount = 17; + + // 长宽比是否命中 A 系列(含加长图:长边按短边的 1/4 或 1/8 递增) + bool ratioMatches(double ratio, double tol, bool& extended) + { + extended = false; + if (fabs(ratio - kBaseAspect) <= tol) return true; + for (int n = 1; n <= 8; ++n) + { + if (fabs(ratio - (kBaseAspect + n / 8.0)) <= tol) { extended = true; return true; } + if (fabs(ratio - (kBaseAspect + n / 4.0)) <= tol) { extended = true; return true; } + } + return false; + } + + // 图框关键词 + bool isFrameKeyword(const std::string& s) + { + static const char* kw[] = { "图框", "图签", "标题栏", "边框", + "FRAME", "BORDER", "TITLE", "SHEET", "TK", + "A0", "A1", "A2", "A3", "A4" }; + for (int i = 0; i < (int)(sizeof(kw) / sizeof(kw[0])); ++i) + if (containsCI(s, kw[i])) return true; + return false; + } + + // 推测图幅:先看名称/图层线索,再按常见比例反推 + void guessSheet(double L, double S, const std::string& hint, double ratioTol, + std::string& outSheet, double& outScale) + { + outSheet.clear(); + outScale = 0.0; + + // 1) 名称/图层线索(如块名含 "A3") + for (int i = 0; i < kSheetCount; ++i) + if (containsCI(hint, kSheets[i].name)) { outSheet = kSheets[i].name; return; } + + // 2) 比例反推:把 L/S 与 标准幅面 × 常见比例 比较,取相对误差最小者 + double bestErr = 1e18; + int bestSheet = -1; + double bestScale = 0.0; + for (int i = 0; i < kSheetCount; ++i) + { + for (int j = 0; j < kScaleCount; ++j) + { + double ew = kSheets[i].w * kScales[j]; + double eh = kSheets[i].h * kScales[j]; + double e = fabs(L - ew) / (L > 1e-9 ? L : 1.0) + + fabs(S - eh) / (S > 1e-9 ? S : 1.0); + if (e < bestErr) { bestErr = e; bestSheet = i; bestScale = kScales[j]; } + } + } + if (bestSheet >= 0 && bestErr < 0.02) + { + outSheet = kSheets[bestSheet].name; + outScale = bestScale; + return; + } + + // 3) 只能判断是否加长图 + bool ext = false; + if (ratioMatches(L / (S > 1e-9 ? S : 1.0), ratioTol, ext) && ext) + outSheet = "A?-加长"; + } + + // 填充尺寸 / 方向 / 图幅 / 置信度 + void finalizeFrame(DrawingFrame& f, const FrameDetectOptions& opt, bool nameHint) + { + f.width = f.maxX - f.minX; + f.height = f.maxY - f.minY; + f.longSide = (std::max)(f.width, f.height); + f.shortSide = (std::min)(f.width, f.height); + f.orientation = (f.width >= f.height) ? 0 : 1; + + const std::string hint = f.blockName + " " + f.layer; + guessSheet(f.longSide, f.shortSide, hint, opt.ratioTol, f.sheetSize, f.sheetScale); + + double conf = 0.0; + if (f.kind == FrameKind::Block && nameHint) conf += 0.4; + if (isFrameKeyword(hint)) conf += 0.3; + if (!f.sheetSize.empty()) conf += 0.2; + if (f.sheetScale > 0.0) conf += 0.1; + if (opt.minSide > 0.0 && f.shortSide >= opt.minSide) conf += 0.1; + f.confidence = (conf > 1.0) ? 1.0 : conf; + } + + // 是否采纳为图框 + bool acceptable(const DrawingFrame& f, const FrameDetectOptions& opt, bool blockFilterMatched) + { + if (f.shortSide < opt.minSide) return false; + if (f.confidence < opt.minConfidence) return false; + if (blockFilterMatched) return true; // 用户显式指定块名,信任 + + const double ratio = (f.shortSide > 1e-9) ? f.longSide / f.shortSide : 0.0; + bool ext = false; + if (!ratioMatches(ratio, opt.ratioTol, ext)) + { + // 比例不符时,仅当名称/图层命中图框关键词才放行 + const std::string hint = f.blockName + " " + f.layer; + if (!isFrameKeyword(hint)) return false; + } + return true; + } + + // 闭合轴对齐矩形判定(允许 4 或 5 个顶点,5 为闭合重复首点) + bool isClosedRect(AcDbPolyline* p, double tol) + { + if (!p || !p->isClosed()) return false; + const int n = p->numVerts(); + if (n < 4 || n > 5) return false; + + double mnx = 1e308, mny = 1e308, mxx = -1e308, mxy = -1e308; + std::vector pts; + pts.reserve(n); + for (int i = 0; i < n; ++i) + { + AcGePoint2d pt; + if (p->getPointAt(i, pt) != Acad::eOk) return false; + pts.push_back(pt); + if (pt.x < mnx) mnx = pt.x; + if (pt.x > mxx) mxx = pt.x; + if (pt.y < mny) mny = pt.y; + if (pt.y > mxy) mxy = pt.y; + } + for (size_t i = 0; i < pts.size(); ++i) + { + const bool cx = approxEq(pts[i].x, mnx, tol) || approxEq(pts[i].x, mxx, tol); + const bool cy = approxEq(pts[i].y, mny, tol) || approxEq(pts[i].y, mxy, tol); + if (!cx || !cy) return false; + } + return true; + } + + // ---------- 直线组配对 ---------- + struct Seg { double x1, y1, x2, y2; std::string layer, handle; }; + + bool segCoversX(const Seg& s, double xL, double xR, double tol) + { + double a = (std::min)(s.x1, s.x2), b = (std::max)(s.x1, s.x2); + return a <= xL + tol && b >= xR - tol; + } + bool segCoversY(const Seg& s, double yB, double yT, double tol) + { + double a = (std::min)(s.y1, s.y2), b = (std::max)(s.y1, s.y2); + return a <= yB + tol && b >= yT - tol; + } + + void collectLineLoops(std::vector& segs, const FrameDetectOptions& opt, + std::vector& out) + { + std::vector h, v; + for (size_t i = 0; i < segs.size(); ++i) + { + const Seg& s = segs[i]; + if (fabs(s.y1 - s.y2) <= opt.axisTol) h.push_back(s); + else if (fabs(s.x1 - s.x2) <= opt.axisTol) v.push_back(s); + } + if (h.size() > 64) h.resize(64); // 防止组合爆炸 + if (v.size() > 64) v.resize(64); + + for (size_t i = 0; i < h.size(); ++i) + for (size_t j = i + 1; j < h.size(); ++j) + { + if (fabs(h[i].y1 - h[j].y1) <= opt.axisTol) continue; + const double yTop = (std::max)(h[i].y1, h[j].y1); + const double yBot = (std::min)(h[i].y1, h[j].y1); + + for (size_t k = 0; k < v.size(); ++k) + for (size_t l = k + 1; l < v.size(); ++l) + { + if (fabs(v[k].x1 - v[l].x1) <= opt.axisTol) continue; + const double xL = (std::min)(v[k].x1, v[l].x1); + const double xR = (std::max)(v[k].x1, v[l].x1); + + if (segCoversX(h[i], xL, xR, opt.axisTol) && + segCoversX(h[j], xL, xR, opt.axisTol) && + segCoversY(v[k], yBot, yTop, opt.axisTol) && + segCoversY(v[l], yBot, yTop, opt.axisTol)) + { + DrawingFrame f; + f.kind = FrameKind::LineLoop; + f.handle = h[i].handle; + f.layer = h[i].layer; + f.minX = xL; f.minY = yBot; f.maxX = xR; f.maxY = yTop; + f.lineCount = 4; + finalizeFrame(f, opt, false); + if (acceptable(f, opt, false)) out.push_back(f); + } + } + } + } + + // 排序:置信度降序 → 上→下 → 左→右 + bool frameLess(const DrawingFrame& a, const DrawingFrame& b) + { + if (fabs(a.confidence - b.confidence) > 1e-6) return a.confidence > b.confidence; + if (fabs(a.maxY - b.maxY) > 1e-6) return a.maxY > b.maxY; + return a.minX < b.minX; + } +} + +namespace dwg_review +{ + +const char* frameKindName(FrameKind k) +{ + switch (k) + { + case FrameKind::Block: return "block"; + case FrameKind::Polyline: return "polyline"; + case FrameKind::LineLoop: return "line_loop"; + } + return "unknown"; +} + +std::vector detectFrames(const FrameDetectOptions& opt) +{ + std::vector frames; + + // 复用公共层的遍历(图层 / 范围过滤已内含) + CommonQuery q; + q.space = opt.space; + q.layerFilter = opt.layerFilter; + q.useWindow = opt.useWindow; + q.minX = opt.winMinX; q.minY = opt.winMinY; + q.maxX = opt.winMaxX; q.maxY = opt.winMaxY; + + std::vector segs; + + forEachEntity(q, [&](AcDbEntity* pEnt) -> bool + { + BBox b; + if (!entityBBox(pEnt, b)) return true; + + // 1) 块参照图框 + if (AcDbBlockReference* pRef = AcDbBlockReference::cast(pEnt)) + { + const std::string blk = blockNameOf(pRef); + bool matched = false; + if (!opt.blockNameFilter.empty()) + { + if (!wildcardMatch(blk, opt.blockNameFilter)) return true; + matched = true; + } + DrawingFrame f; + f.kind = FrameKind::Block; + f.handle = handleOf(pEnt); + f.layer = layerOf(pEnt); + f.blockName = blk; + f.minX = b.minX; f.minY = b.minY; f.maxX = b.maxX; f.maxY = b.maxY; + finalizeFrame(f, opt, matched); + if (acceptable(f, opt, matched)) frames.push_back(f); + return true; + } + + // 2) 闭合矩形多段线 + if (AcDbPolyline* pPoly = AcDbPolyline::cast(pEnt)) + { + if (isClosedRect(pPoly, opt.axisTol)) + { + DrawingFrame f; + f.kind = FrameKind::Polyline; + f.handle = handleOf(pEnt); + f.layer = layerOf(pEnt); + f.minX = b.minX; f.minY = b.minY; f.maxX = b.maxX; f.maxY = b.maxY; + finalizeFrame(f, opt, false); + if (acceptable(f, opt, false)) frames.push_back(f); + } + return true; + } + + // 3) 直线(暂存,稍后配对) + if (opt.detectLineLoops) + { + if (AcDbLine* pLine = AcDbLine::cast(pEnt)) + { + Seg s; + s.x1 = pLine->startPoint().x; s.y1 = pLine->startPoint().y; + s.x2 = pLine->endPoint().x; s.y2 = pLine->endPoint().y; + s.layer = layerOf(pEnt); + s.handle = handleOf(pEnt); + segs.push_back(s); + } + } + return true; + }); + + if (opt.detectLineLoops && !segs.empty()) + collectLineLoops(segs, opt, frames); + + std::sort(frames.begin(), frames.end(), frameLess); + return frames; +} + +nlohmann::json framesToJson(const std::vector& frames) +{ + nlohmann::json arr = nlohmann::json::array(); + for (size_t i = 0; i < frames.size(); ++i) + { + const DrawingFrame& f = frames[i]; + nlohmann::json o; + o["handle"] = f.handle; + o["kind"] = frameKindName(f.kind); + o["layer"] = f.layer; + if (!f.blockName.empty()) o["block_name"] = f.blockName; + o["bbox"] = nlohmann::json::array({ f.minX, f.minY, f.maxX, f.maxY }); + o["width"] = f.width; + o["height"] = f.height; + o["orientation"] = (f.orientation == 0) ? "landscape" : "portrait"; + o["sheet_size"] = f.sheetSize; + o["sheet_scale"] = f.sheetScale; + o["confidence"] = f.confidence; + if (f.kind == FrameKind::LineLoop) o["line_count"] = f.lineCount; + arr.push_back(o); + } + + nlohmann::json r; + r["count"] = (int)frames.size(); + r["items"] = arr; + return r; +} + +} // namespace dwg_review + +// =========================================================================== +// detect_drawing_frames 工具 +// =========================================================================== +class mcp_Tool_DetectDrawingFrames : public mcp_Tool +{ +public: + nlohmann::json Execute(const nlohmann::json& args) override + { + FrameDetectOptions opt; + if (args.contains("space") && args["space"].is_string()) + opt.space = args["space"].get(); + if (args.contains("layer_filter") && args["layer_filter"].is_string()) + opt.layerFilter = args["layer_filter"].get(); + if (args.contains("block_name_filter") && args["block_name_filter"].is_string()) + opt.blockNameFilter = args["block_name_filter"].get(); + if (args.contains("detect_line_loops") && args["detect_line_loops"].is_boolean()) + opt.detectLineLoops = args["detect_line_loops"].get(); + if (args.contains("min_side") && args["min_side"].is_number()) + opt.minSide = args["min_side"].get(); + if (args.contains("ratio_tol") && args["ratio_tol"].is_number()) + opt.ratioTol = args["ratio_tol"].get(); + if (args.contains("axis_tol") && args["axis_tol"].is_number()) + opt.axisTol = args["axis_tol"].get(); + if (args.contains("min_confidence") && args["min_confidence"].is_number()) + opt.minConfidence = args["min_confidence"].get(); + + if (args.contains("window") && args["window"].is_object()) + { + const nlohmann::json& w = args["window"]; + if (w.contains("min_x") && w.contains("min_y") && + w.contains("max_x") && w.contains("max_y")) + { + opt.useWindow = true; + opt.winMinX = w["min_x"].get(); + opt.winMinY = w["min_y"].get(); + opt.winMaxX = w["max_x"].get(); + opt.winMaxY = w["max_y"].get(); + } + } + + std::vector frames = detectFrames(opt); + return makeJsonResult(framesToJson(frames)); + } +}; +EXPORT_MCP_TOOL(mcp_Tool_DetectDrawingFrames, CreateDetectDrawingFramesTool) diff --git a/SourceCode/Code2026/cad_mcp_plugins/dwg_review_frame.h b/SourceCode/Code2026/cad_mcp_plugins/dwg_review_frame.h new file mode 100644 index 0000000..3cc0d09 --- /dev/null +++ b/SourceCode/Code2026/cad_mcp_plugins/dwg_review_frame.h @@ -0,0 +1,78 @@ +#pragma once +// ============================================================================ +// dwg_review_frame.h +// 图纸审查 - 图框识别模块 +// +// 目标:从 DWG 中识别出"图框"(图纸边界),为后续「按图框逐张审查 / 分图」 +// 提供基准。图框在 DWG 中通常以三种形态存在(参考主流分图软件做法): +// 1) 块参照 (Block Reference) —— 最常见,图框被封装为块 +// 2) 闭合多段线 (Closed Polyline) —— 独立图层上的闭合矩形 +// 3) 直线组 (Line Loop) —— 四条直线围成的矩形(老旧图纸) +// +// 识别特征:轴对齐矩形 + 长宽比接近 ISO A 系列(√2≈1.414,含加长图) +// + 可选的图层/块名关键词(图框/TK/FRAME/BORDER/TITLE/A0-A4)。 +// ============================================================================ + +#include +#include +#include + +namespace dwg_review +{ + +// 图框的几何来源形态 +enum class FrameKind +{ + Block, // 块参照 + Polyline, // 闭合多段线 + LineLoop // 直线组 +}; + +// 一个被识别出的图框 +struct DrawingFrame +{ + std::string handle; // 代表图元句柄(块 INSERT / 多段线 / 首条线) + FrameKind kind = FrameKind::Polyline; + std::string layer; // 所在图层 + std::string blockName; // 仅 Block 有值 + + // 外框范围(WCS 坐标) + double minX = 0.0, minY = 0.0, maxX = 0.0, maxY = 0.0; + + // 外框尺寸(图纸单位) + double width = 0.0, height = 0.0; + double longSide = 0.0, shortSide = 0.0; + + int orientation = 0; // 0 = 横向(宽>=高),1 = 纵向 + std::string sheetSize; // 推测图幅 "A0".."A4" / "A?-加长";无法判定为空串 + double sheetScale = 0.0; // 由比例反推命中的出图比例(如 100.0),未命中为 0 + double confidence = 0.0; // 置信度 0~1 + int lineCount = 0; // LineLoop 时的线段数 +}; + +// 识别选项 +struct FrameDetectOptions +{ + std::string space = "Model"; // "Model" 或布局名 + std::string layerFilter; // 图层通配符,空 = 不过滤 + std::string blockNameFilter; // 块名通配符,空 = 自动启发式判定 + bool useWindow = false; // 是否限定扫描范围 + double winMinX = 0.0, winMinY = 0.0, winMaxX = 0.0, winMaxY = 0.0; + + double minSide = 0.0; // 最小短边过滤(图纸单位),过滤小方块 + double ratioTol = 0.06; // 长宽比容差 + double axisTol = 1.0; // 轴对齐 / 矩形顶点判定容差(图纸单位) + bool detectLineLoops = false;// 是否做直线组配对(成本较高,默认关闭) + double minConfidence = 0.0; // 最低置信度过滤 +}; + +// 主入口:识别当前文档指定空间中的图框 +std::vector detectFrames(const FrameDetectOptions& opt); + +// 转为 JSON(供 MCP 工具直接返回给 LLM) +nlohmann::json framesToJson(const std::vector& frames); + +// 形态名("block" / "polyline" / "line_loop") +const char* frameKindName(FrameKind k); + +} // namespace dwg_review diff --git a/SourceCode/Code2026/cad_mcp_plugins/dwg_review_overview.cpp b/SourceCode/Code2026/cad_mcp_plugins/dwg_review_overview.cpp new file mode 100644 index 0000000..a1654ec --- /dev/null +++ b/SourceCode/Code2026/cad_mcp_plugins/dwg_review_overview.cpp @@ -0,0 +1,351 @@ +// ============================================================================ +// dwg_review_overview.cpp +// 图纸审查 - 概览层工具(均为 c++_dll 后端) +// get_drawing_info : 图纸元数据(文件名/单位/布局数/各空间实体数) +// get_layers : 图层清单(开关/冻结/锁定/颜色/线型/可选实体计数) +// get_layouts : 布局清单(模型空间 + 图纸空间布局 + 视口) +// ============================================================================ + +#include "KTCad.h" +#include "dwg_review_common.h" +#include "mcp_plugin_api.h" + +#include "dbcolor.h" // AcCmColor(图层颜色);AcDbViewport 在 dbents.h(已由 cadsdk 引入) + +#include + +using namespace dwg_review; + +namespace +{ + // 图纸单位代码 -> 名称 + std::string insUnitsName(int u) + { + switch (u) + { + case 0: return "Unitless"; + case 1: return "Inches"; + case 2: return "Feet"; + case 3: return "Miles"; + case 4: return "Millimeters"; + case 5: return "Centimeters"; + case 6: return "Meters"; + case 7: return "Kilometers"; + case 8: return "Microinches"; + case 9: return "Mils"; + case 10: return "Yards"; + case 11: return "Angstroms"; + case 12: return "Nanometers"; + case 13: return "Microns"; + case 14: return "Decimeters"; + case 15: return "Decameters"; + case 16: return "Hectometers"; + case 17: return "Gigameters"; + case 18: return "AstronomicalUnits"; + case 19: return "LightYears"; + case 20: return "Parsecs"; + default: return "Unknown"; + } + } + + // 取块表记录名 + std::string recordName(AcDbBlockTableRecord* pRec) + { + const ACHAR* nm = NULL; + if (pRec && pRec->getName(nm) == Acad::eOk && nm) return acharToUtf8(nm); + return std::string(); + } + + // 统计某空间内的实体总数 + int countEntitiesIn(AcDbBlockTableRecord* pRec) + { + if (!pRec) return 0; + int n = 0; + AcDbBlockTableRecordIterator* it = nullptr; + if (pRec->newIterator(it) != Acad::eOk || !it) return 0; + for (it->start(); !it->done(); it->step()) ++n; + delete it; + return n; + } + + // 取线型名 + std::string linetypeName(AcDbObjectId id) + { + AcDbLinetypeTableRecord* pRec = nullptr; + if (acdbOpenObject(pRec, id, AcDb::kForRead) == Acad::eOk && pRec) + { + const ACHAR* nm = NULL; + std::string s; + if (pRec->getName(nm) == Acad::eOk && nm) s = acharToUtf8(nm); + pRec->close(); + return s; + } + return std::string(); + } + + // 统计各图层实体数(遍历模型空间 + 所有图纸布局) + void countByLayer(AcDbDatabase* pDb, std::map& out) + { + AcDbBlockTable* pBT = nullptr; + if (pDb->getBlockTable(pBT, AcDb::kForRead) != Acad::eOk || !pBT) return; + + AcDbBlockTableIterator* it = nullptr; + if (pBT->newIterator(it) == Acad::eOk && it) + { + for (it->start(); !it->done(); it->step()) + { + AcDbBlockTableRecord* pRec = nullptr; + if (it->getRecord(pRec, AcDb::kForRead) != Acad::eOk || !pRec) continue; + + const std::string nm = recordName(pRec); + static const std::string kModelSpace = acharToUtf8(ACDB_MODEL_SPACE); + const bool isModel = (nm == kModelSpace); + if (isModel || pRec->isLayout()) + { + AcDbBlockTableRecordIterator* eit = nullptr; + if (pRec->newIterator(eit) == Acad::eOk && eit) + { + for (eit->start(); !eit->done(); eit->step()) + { + AcDbEntity* pEnt = nullptr; + if (eit->getEntity(pEnt, AcDb::kForRead) == Acad::eOk && pEnt) + { + out[layerOf(pEnt)]++; + pEnt->close(); + } + } + delete eit; + } + } + pRec->close(); + } + delete it; + } + pBT->close(); + } + + // 收集某布局内的视口 + nlohmann::json collectViewports(AcDbBlockTableRecord* pRec) + { + nlohmann::json arr = nlohmann::json::array(); + if (!pRec) return arr; + + AcDbBlockTableRecordIterator* it = nullptr; + if (pRec->newIterator(it) != Acad::eOk || !it) return arr; + + for (it->start(); !it->done(); it->step()) + { + AcDbEntity* pEnt = nullptr; + if (it->getEntity(pEnt, AcDb::kForRead) != Acad::eOk || !pEnt) continue; + + AcDbViewport* pVp = AcDbViewport::cast(pEnt); + if (pVp) + { + nlohmann::json v; + v["handle"] = handleOf(pEnt); + v["center"] = point2Json(pVp->centerPoint().x, pVp->centerPoint().y); + v["width"] = pVp->width(); + v["height"] = pVp->height(); + v["scale"] = pVp->customScale(); + arr.push_back(v); + } + pEnt->close(); + } + delete it; + return arr; + } +} + +// =========================================================================== +// get_drawing_info +// =========================================================================== +class mcp_Tool_GetDrawingInfo : public mcp_Tool +{ +public: + nlohmann::json Execute(const nlohmann::json&) override + { + AcDbDatabase* pDb = acdbHostApplicationServices()->workingDatabase(); + if (!pDb) return makeError(kErrNoDocument, "no active document"); + + nlohmann::json r; + const ACHAR* fn = NULL; + pDb->getFilename(fn); + r["file_name"] = acharToUtf8(fn); + r["insunits"] = (int)pDb->insunits(); + r["insunits_name"] = insUnitsName((int)pDb->insunits()); + + nlohmann::json counts = nlohmann::json::object(); + int layoutCount = 0; + int total = 0; + + AcDbBlockTable* pBT = nullptr; + if (pDb->getBlockTable(pBT, AcDb::kForRead) == Acad::eOk && pBT) + { + AcDbBlockTableRecord* pModel = nullptr; + if (pBT->getAt(ACDB_MODEL_SPACE, pModel, AcDb::kForRead) == Acad::eOk && pModel) + { + int c = countEntitiesIn(pModel); + counts["Model"] = c; total += c; + pModel->close(); + } + + AcDbBlockTableIterator* it = nullptr; + if (pBT->newIterator(it) == Acad::eOk && it) + { + for (it->start(); !it->done(); it->step()) + { + AcDbBlockTableRecord* pRec = nullptr; + if (it->getRecord(pRec, AcDb::kForRead) != Acad::eOk || !pRec) continue; + if (pRec->isLayout()) + { + ++layoutCount; + int c = countEntitiesIn(pRec); + counts[recordName(pRec)] = c; total += c; + } + pRec->close(); + } + delete it; + } + pBT->close(); + } + + r["layout_count"] = layoutCount + 1; // 含 Model + r["entity_count"] = counts; + r["entity_count_total"] = total; + return makeJsonResult(r); + } +}; +EXPORT_MCP_TOOL(mcp_Tool_GetDrawingInfo, CreateGetDrawingInfoTool) + +// =========================================================================== +// get_layers +// =========================================================================== +class mcp_Tool_GetLayers : public mcp_Tool +{ +public: + nlohmann::json Execute(const nlohmann::json& args) override + { + AcDbDatabase* pDb = acdbHostApplicationServices()->workingDatabase(); + if (!pDb) return makeError(kErrNoDocument, "no active document"); + + const std::string nameFilter = args.value("name_filter", std::string()); + const bool includeEmpty = args.value("include_empty", false); + const bool needCount = args.value("count_entities", false); + + std::map layerCounts; + if (needCount) countByLayer(pDb, layerCounts); + + nlohmann::json items = nlohmann::json::array(); + AcDbLayerTable* pLT = nullptr; + if (pDb->getLayerTable(pLT, AcDb::kForRead) == Acad::eOk && pLT) + { + AcDbLayerTableIterator* it = nullptr; + if (pLT->newIterator(it) == Acad::eOk && it) + { + for (it->start(); !it->done(); it->step()) + { + AcDbLayerTableRecord* pRec = nullptr; + if (it->getRecord(pRec, AcDb::kForRead) != Acad::eOk || !pRec) continue; + + const ACHAR* nm = NULL; + pRec->getName(nm); + const std::string name = acharToUtf8(nm); + + const int cnt = needCount + ? (layerCounts.count(name) ? layerCounts[name] : 0) : -1; + + if (!wildcardMatch(name, nameFilter) || + (needCount && !includeEmpty && cnt == 0)) + { + pRec->close(); + continue; + } + + nlohmann::json o; + o["name"] = name; + o["on"] = !pRec->isOff(); + o["frozen"] = pRec->isFrozen(); + o["locked"] = pRec->isLocked(); + o["plot"] = pRec->isPlottable(); + + AcCmColor col = pRec->color(); + o["color_index"] = (int)col.colorIndex(); + o["linetype"] = linetypeName(pRec->linetypeObjectId()); + if (cnt >= 0) o["entity_count"] = cnt; + + items.push_back(o); + pRec->close(); + } + delete it; + } + pLT->close(); + } + + nlohmann::json r; + r["count"] = (int)items.size(); + r["items"] = items; + return makeJsonResult(r); + } +}; +EXPORT_MCP_TOOL(mcp_Tool_GetLayers, CreateGetLayersTool) + +// =========================================================================== +// get_layouts +// =========================================================================== +class mcp_Tool_GetLayouts : public mcp_Tool +{ +public: + nlohmann::json Execute(const nlohmann::json&) override + { + AcDbDatabase* pDb = acdbHostApplicationServices()->workingDatabase(); + if (!pDb) return makeError(kErrNoDocument, "no active document"); + + nlohmann::json items = nlohmann::json::array(); + + AcDbBlockTable* pBT = nullptr; + if (pDb->getBlockTable(pBT, AcDb::kForRead) == Acad::eOk && pBT) + { + // 模型空间 + AcDbBlockTableRecord* pModel = nullptr; + if (pBT->getAt(ACDB_MODEL_SPACE, pModel, AcDb::kForRead) == Acad::eOk && pModel) + { + nlohmann::json o; + o["name"] = "Model"; + o["is_model"] = true; + o["entity_count"] = countEntitiesIn(pModel); + o["viewports"] = nlohmann::json::array(); + items.push_back(o); + pModel->close(); + } + + // 图纸空间布局 + AcDbBlockTableIterator* it = nullptr; + if (pBT->newIterator(it) == Acad::eOk && it) + { + for (it->start(); !it->done(); it->step()) + { + AcDbBlockTableRecord* pRec = nullptr; + if (it->getRecord(pRec, AcDb::kForRead) != Acad::eOk || !pRec) continue; + if (pRec->isLayout()) + { + nlohmann::json o; + o["name"] = recordName(pRec); + o["is_model"] = false; + o["entity_count"] = countEntitiesIn(pRec); + o["viewports"] = collectViewports(pRec); + items.push_back(o); + } + pRec->close(); + } + delete it; + } + pBT->close(); + } + + nlohmann::json r; + r["count"] = (int)items.size(); + r["items"] = items; + return makeJsonResult(r); + } +}; +EXPORT_MCP_TOOL(mcp_Tool_GetLayouts, CreateGetLayoutsTool) diff --git a/SourceCode/Code2026/cad_mcp_plugins/dwg_review_query.cpp b/SourceCode/Code2026/cad_mcp_plugins/dwg_review_query.cpp new file mode 100644 index 0000000..bdf1772 --- /dev/null +++ b/SourceCode/Code2026/cad_mcp_plugins/dwg_review_query.cpp @@ -0,0 +1,440 @@ +// ============================================================================ +// dwg_review_query.cpp +// 图纸审查 - 数据提取层工具(均为 c++_dll 后端,统一分页返回) +// query_entities : 按图层/类型/范围查询图元摘要 +// get_text_content : 提取 TEXT / MTEXT / ATTRIB 文字 +// get_dimensions : 提取标注 +// get_block_references : 提取块参照及其属性 +// get_polylines_info : 多段线闭合性 / 面积 / 长度 +// get_entity_detail : 按 handle 取单个实体完整属性 +// +// 返回统一分页信封:{ total, returned, offset, items:[...] } +// 实体 ID 统一使用 handle。 +// ============================================================================ + +#include "KTCad.h" +#include "dwg_review_common.h" +#include "mcp_plugin_api.h" + +#include "dbdim.h" // AcDbDimension(cadsdk 未包含) + +#include + +using namespace dwg_review; + +namespace +{ + // 类型过滤:filter 为空数组/非数组时全部通过 + bool typeMatches(const std::string& type, const nlohmann::json& filter) + { + if (!filter.is_array() || filter.empty()) return true; + for (size_t i = 0; i < filter.size(); ++i) + { + if (filter[i].is_string() && filter[i].get() == type) + return true; + } + return false; + } + + // 取类名(去掉 AcDb 前缀),如 "RotatedDimension" + std::string rawClassName(AcRxObject* pObj) + { + if (!pObj) return std::string(); + std::string n = acharToUtf8(pObj->isA()->name()); + if (n.rfind("AcDb", 0) == 0) n = n.substr(4); + return n; + } + + // 取标注样式名 + std::string dimStyleName(AcDbObjectId id) + { + AcDbDimStyleTableRecord* pRec = nullptr; + if (acdbOpenObject(pRec, id, AcDb::kForRead) == Acad::eOk && pRec) + { + const ACHAR* nm = NULL; + std::string s; + if (pRec->getName(nm) == Acad::eOk && nm) s = acharToUtf8(nm); + pRec->close(); + return s; + } + return std::string(); + } + + // 计算多段线总长度 + double polyLength(AcDbPolyline* p) + { + if (!p) return 0.0; + double len = 0.0; + const int n = p->numVerts(); + for (int i = 0; i + 1 < n; ++i) + { + AcGePoint2d a, b; + if (p->getPointAt(i, a) == Acad::eOk && p->getPointAt(i + 1, b) == Acad::eOk) + len += a.distanceTo(b); + } + if (p->isClosed() && n > 1) + { + AcGePoint2d a, b; + if (p->getPointAt(n - 1, a) == Acad::eOk && p->getPointAt(0, b) == Acad::eOk) + len += a.distanceTo(b); + } + return len; + } + + // 通用摘要:handle / type / layer / bbox + 类型相关 properties + nlohmann::json buildEntitySummary(AcDbEntity* pEnt) + { + nlohmann::json o; + o["handle"] = handleOf(pEnt); + o["type"] = entityTypeName(pEnt); + o["layer"] = layerOf(pEnt); + + BBox b; + if (entityBBox(pEnt, b)) o["bbox"] = bboxJson(b); + + nlohmann::json props = nlohmann::json::object(); + + if (AcDbLine* p = AcDbLine::cast(pEnt)) + { + props["start"] = point3Json(p->startPoint().x, p->startPoint().y, p->startPoint().z); + props["end"] = point3Json(p->endPoint().x, p->endPoint().y, p->endPoint().z); + } + else if (AcDbArc* p = AcDbArc::cast(pEnt)) + { + props["center"] = point3Json(p->center().x, p->center().y, p->center().z); + props["radius"] = p->radius(); + props["start_angle"] = p->startAngle(); + props["end_angle"] = p->endAngle(); + } + else if (AcDbCircle* p = AcDbCircle::cast(pEnt)) + { + props["center"] = point3Json(p->center().x, p->center().y, p->center().z); + props["radius"] = p->radius(); + } + else if (AcDbPolyline* p = AcDbPolyline::cast(pEnt)) + { + props["vertex_count"] = p->numVerts(); + props["closed"] = p->isClosed(); + } + else if (AcDbPoint* p = AcDbPoint::cast(pEnt)) + { + props["position"] = point3Json(p->position().x, p->position().y, p->position().z); + } + else if (AcDbBlockReference* p = AcDbBlockReference::cast(pEnt)) + { + props["block_name"] = blockNameOf(p); + } + + o["properties"] = props; + return o; + } +} + +// =========================================================================== +// query_entities +// =========================================================================== +class mcp_Tool_QueryEntities : public mcp_Tool +{ +public: + nlohmann::json Execute(const nlohmann::json& args) override + { + const CommonQuery q = parseCommonQuery(args); + const nlohmann::json typeFilter = + args.contains("type_filter") ? args["type_filter"] : nlohmann::json(); + + int total = 0, returned = 0; + nlohmann::json items = nlohmann::json::array(); + + forEachEntity(q, [&](AcDbEntity* pEnt) -> bool + { + if (!typeMatches(entityTypeName(pEnt), typeFilter)) return true; + if (total >= q.offset && returned < q.limit) + { + items.push_back(buildEntitySummary(pEnt)); + ++returned; + } + ++total; + return true; + }); + + return makeJsonResult(pageResult(total, returned, q.offset, items)); + } +}; +EXPORT_MCP_TOOL(mcp_Tool_QueryEntities, CreateQueryEntitiesTool) + +// =========================================================================== +// get_text_content +// =========================================================================== +class mcp_Tool_GetTextContent : public mcp_Tool +{ +public: + nlohmann::json Execute(const nlohmann::json& args) override + { + const CommonQuery q = parseCommonQuery(args); + const std::string contentFilter = args.value("content_filter", std::string()); + + int total = 0, returned = 0; + nlohmann::json items = nlohmann::json::array(); + + forEachEntity(q, [&](AcDbEntity* pEnt) -> bool + { + const std::string type = entityTypeName(pEnt); + if (type != "TEXT" && type != "MTEXT" && type != "ATTRIB") return true; + + std::string content; + double height = 0.0; + nlohmann::json o; + o["handle"] = handleOf(pEnt); + o["type"] = type; + o["layer"] = layerOf(pEnt); + + if (AcDbMText* p = AcDbMText::cast(pEnt)) + { + content = acharToUtf8(p->contents()); + height = p->textHeight(); + o["insert"] = point3Json(p->location().x, p->location().y, p->location().z); + } + else if (AcDbAttribute* p = AcDbAttribute::cast(pEnt)) + { + content = acharToUtf8(p->textString()); + height = p->height(); + o["insert"] = point3Json(p->position().x, p->position().y, p->position().z); + } + else if (AcDbText* p = AcDbText::cast(pEnt)) + { + content = acharToUtf8(p->textString()); + height = p->height(); + o["rotation"] = p->rotation(); + o["insert"] = point3Json(p->position().x, p->position().y, p->position().z); + } + else + { + return true; + } + + // 可选内容过滤(子串,大小写敏感) + if (!contentFilter.empty() && content.find(contentFilter) == std::string::npos) + return true; + + o["content"] = content; + o["height"] = height; + BBox b; + if (entityBBox(pEnt, b)) o["bbox"] = bboxJson(b); + + if (total >= q.offset && returned < q.limit) + { + items.push_back(o); + ++returned; + } + ++total; + return true; + }); + + return makeJsonResult(pageResult(total, returned, q.offset, items)); + } +}; +EXPORT_MCP_TOOL(mcp_Tool_GetTextContent, CreateGetTextContentTool) + +// =========================================================================== +// get_dimensions +// =========================================================================== +class mcp_Tool_GetDimensions : public mcp_Tool +{ +public: + nlohmann::json Execute(const nlohmann::json& args) override + { + const CommonQuery q = parseCommonQuery(args); + + int total = 0, returned = 0; + nlohmann::json items = nlohmann::json::array(); + + forEachEntity(q, [&](AcDbEntity* pEnt) -> bool + { + AcDbDimension* pDim = AcDbDimension::cast(pEnt); + if (!pDim) return true; + + if (total >= q.offset && returned < q.limit) + { + nlohmann::json o; + o["handle"] = handleOf(pEnt); + o["type"] = rawClassName(pDim); + o["layer"] = layerOf(pEnt); + double meas = 0.0; + pDim->measurement(meas); + o["measurement"] = meas; + o["text_override"] = acharToUtf8(pDim->dimensionText()); + o["dim_style"] = dimStyleName(pDim->dimensionStyle()); + items.push_back(o); + ++returned; + } + ++total; + return true; + }); + + return makeJsonResult(pageResult(total, returned, q.offset, items)); + } +}; +EXPORT_MCP_TOOL(mcp_Tool_GetDimensions, CreateGetDimensionsTool) + +// =========================================================================== +// get_block_references +// =========================================================================== +class mcp_Tool_GetBlockReferences : public mcp_Tool +{ +public: + nlohmann::json Execute(const nlohmann::json& args) override + { + const CommonQuery q = parseCommonQuery(args); + const std::string blockFilter = args.value("block_name_filter", std::string()); + + int total = 0, returned = 0; + nlohmann::json items = nlohmann::json::array(); + + forEachEntity(q, [&](AcDbEntity* pEnt) -> bool + { + AcDbBlockReference* pRef = AcDbBlockReference::cast(pEnt); + if (!pRef) return true; + + const std::string blk = blockNameOf(pRef); + if (!blockFilter.empty() && !wildcardMatch(blk, blockFilter)) return true; + + if (total >= q.offset && returned < q.limit) + { + nlohmann::json o; + o["handle"] = handleOf(pEnt); + o["type"] = "INSERT"; + o["layer"] = layerOf(pEnt); + o["block_name"] = blk; + o["insert"] = point3Json(pRef->position().x, pRef->position().y, pRef->position().z); + o["rotation"] = pRef->rotation(); + AcGeScale3d sc = pRef->scaleFactors(); + o["scale"] = nlohmann::json::array({ sc.sx, sc.sy, sc.sz }); + + // 属性 + nlohmann::json atts = nlohmann::json::array(); + AcDbObjectIterator* ait = pRef->attributeIterator(); + if (ait) + { + for (; !ait->done(); ait->step()) + { + AcDbAttribute* pAtt = nullptr; + if (acdbOpenObject(pAtt, ait->objectId(), AcDb::kForRead) == Acad::eOk && pAtt) + { + nlohmann::json a; + a["tag"] = acharToUtf8(pAtt->tag()); + a["value"] = acharToUtf8(pAtt->textString()); + atts.push_back(a); + pAtt->close(); + } + } + delete ait; + } + o["attributes"] = atts; + + BBox b; + if (entityBBox(pEnt, b)) o["bbox"] = bboxJson(b); + + items.push_back(o); + ++returned; + } + ++total; + return true; + }); + + return makeJsonResult(pageResult(total, returned, q.offset, items)); + } +}; +EXPORT_MCP_TOOL(mcp_Tool_GetBlockReferences, CreateGetBlockReferencesTool) + +// =========================================================================== +// get_polylines_info +// =========================================================================== +class mcp_Tool_GetPolylinesInfo : public mcp_Tool +{ +public: + nlohmann::json Execute(const nlohmann::json& args) override + { + const CommonQuery q = parseCommonQuery(args); + + int total = 0, returned = 0; + nlohmann::json items = nlohmann::json::array(); + + forEachEntity(q, [&](AcDbEntity* pEnt) -> bool + { + AcDbPolyline* p = AcDbPolyline::cast(pEnt); + if (!p) return true; + + if (total >= q.offset && returned < q.limit) + { + nlohmann::json o; + o["handle"] = handleOf(pEnt); + o["type"] = "LWPOLYLINE"; + o["layer"] = layerOf(pEnt); + o["vertex_count"] = p->numVerts(); + o["closed"] = p->isClosed(); + o["length"] = polyLength(p); + double area = 0.0; + if (p->getArea(area) == Acad::eOk) o["area"] = area; + BBox b; + if (entityBBox(pEnt, b)) o["bbox"] = bboxJson(b); + items.push_back(o); + ++returned; + } + ++total; + return true; + }); + + return makeJsonResult(pageResult(total, returned, q.offset, items)); + } +}; +EXPORT_MCP_TOOL(mcp_Tool_GetPolylinesInfo, CreateGetPolylinesInfoTool) + +// =========================================================================== +// get_entity_detail +// =========================================================================== +class mcp_Tool_GetEntityDetail : public mcp_Tool +{ +public: + nlohmann::json Execute(const nlohmann::json& args) override + { + if (!args.contains("handle") || !args["handle"].is_string()) + return makeError(kErrBadParam, "handle is required"); + + const std::string hs = args["handle"].get(); + + AcDbObjectId id; + if (!objectIdFromHandle(hs, id)) + return makeError(kErrNotFound, "invalid handle: " + hs); + + AcDbEntity* pEnt = nullptr; + if (acdbOpenObject(pEnt, id, AcDb::kForRead) != Acad::eOk || !pEnt) + return makeError(kErrNotFound, "entity not found: " + hs); + + nlohmann::json o = buildEntitySummary(pEnt); + + // 补充文字 / 标注 / 块 等细节 + if (AcDbText* p = AcDbText::cast(pEnt)) + { + o["text"] = acharToUtf8(p->textString()); + o["height"] = p->height(); + o["rotation"] = p->rotation(); + } + else if (AcDbMText* p = AcDbMText::cast(pEnt)) + { + o["text"] = acharToUtf8(p->contents()); + o["height"] = p->textHeight(); + } + else if (AcDbDimension* p = AcDbDimension::cast(pEnt)) + { + double meas = 0.0; + p->measurement(meas); + o["measurement"] = meas; + o["text_override"] = acharToUtf8(p->dimensionText()); + o["dim_style"] = dimStyleName(p->dimensionStyle()); + } + + pEnt->close(); + return makeJsonResult(o); + } +}; +EXPORT_MCP_TOOL(mcp_Tool_GetEntityDetail, CreateGetEntityDetailTool) diff --git a/SourceCode/Code2026/cad_mcp_plugins/dwg_review_view.cpp b/SourceCode/Code2026/cad_mcp_plugins/dwg_review_view.cpp new file mode 100644 index 0000000..e488f60 --- /dev/null +++ b/SourceCode/Code2026/cad_mcp_plugins/dwg_review_view.cpp @@ -0,0 +1,194 @@ +// ============================================================================ +// dwg_review_view.cpp +// 图纸审查 - 视图 / 行动层工具(均为 c++_dll 后端) +// zoom_to_entity : 缩放到指定 handle(或 handle 列表)实体 +// zoom_to_window : 缩放到指定 WCS 范围(逐图框审查用;对直线组图框尤其实用) +// highlight_entities : 按 handle 列表临时高亮(改色) +// ============================================================================ + +#include "KTCad.h" +#include "dwg_review_common.h" +#include "mcp_plugin_api.h" + +#include +#include +#include + +using namespace dwg_review; + +namespace +{ + // 数字格式化为命令行可用的定点字符串(避免科学计数法) + std::wstring fmt(double v) + { + wchar_t buf[64]; + swprintf_s(buf, 64, L"%.6f", v); + return std::wstring(buf); + } + + // 缩放到 WCS 范围(四周按 marginFrac 留边),outView 回传实际使用范围 + void zoomToBox(double x1, double y1, double x2, double y2, + double marginFrac, double outView[4]) + { + double w = x2 - x1; + double h = y2 - y1; + if (w < 1e-6) w = 1.0; + if (h < 1e-6) h = 1.0; + const double mx = w * marginFrac, my = h * marginFrac; + + outView[0] = x1 - mx; outView[1] = y1 - my; + outView[2] = x2 + mx; outView[3] = y2 + my; + + std::wstring cmd = L"_.ZOOM _W "; + cmd += fmt(outView[0]) + L"," + fmt(outView[1]) + L" "; + cmd += fmt(outView[2]) + L"," + fmt(outView[3]) + L" "; + acDocManager->sendStringToExecute(acDocManager->curDocument(), cmd.c_str()); + } + + // 按句柄打开实体并取包围盒 + bool bboxByHandle(const std::string& hs, BBox& out) + { + AcDbObjectId id; + if (!objectIdFromHandle(hs, id)) return false; + AcDbEntity* pEnt = nullptr; + if (acdbOpenObject(pEnt, id, AcDb::kForRead) != Acad::eOk || !pEnt) return false; + const bool ok = entityBBox(pEnt, out); + pEnt->close(); + return ok; + } + + // 从 args 里取句柄列表(支持 "handle" 或 "handles") + std::vector collectHandles(const nlohmann::json& args) + { + std::vector hs; + if (args.contains("handle") && args["handle"].is_string()) + hs.push_back(args["handle"].get()); + if (args.contains("handles") && args["handles"].is_array()) + { + for (size_t i = 0; i < args["handles"].size(); ++i) + if (args["handles"][i].is_string()) + hs.push_back(args["handles"][i].get()); + } + return hs; + } +} + +// =========================================================================== +// zoom_to_entity +// =========================================================================== +class mcp_Tool_ZoomToEntity : public mcp_Tool +{ +public: + nlohmann::json Execute(const nlohmann::json& args) override + { + const std::vector hs = collectHandles(args); + if (hs.empty()) return makeError(kErrBadParam, "handle or handles is required"); + + // 合并所有目标实体的包围盒 + BBox box; + bool first = true; + for (size_t i = 0; i < hs.size(); ++i) + { + BBox b; + if (!bboxByHandle(hs[i], b)) continue; + if (first) { box = b; first = false; } + else + { + if (b.minX < box.minX) box.minX = b.minX; + if (b.minY < box.minY) box.minY = b.minY; + if (b.maxX > box.maxX) box.maxX = b.maxX; + if (b.maxY > box.maxY) box.maxY = b.maxY; + } + } + if (first) return makeError(kErrNotFound, "no valid entity for the given handle(s)"); + + double view[4]; + zoomToBox(box.minX, box.minY, box.maxX, box.maxY, 0.05, view); + + nlohmann::json r; + r["ok"] = true; + r["view"] = nlohmann::json::array({ view[0], view[1], view[2], view[3] }); + return makeJsonResult(r); + } +}; +EXPORT_MCP_TOOL(mcp_Tool_ZoomToEntity, CreateZoomToEntityTool) + +// =========================================================================== +// zoom_to_window +// =========================================================================== +class mcp_Tool_ZoomToWindow : public mcp_Tool +{ +public: + nlohmann::json Execute(const nlohmann::json& args) override + { + double x1, y1, x2, y2; + if (args.contains("window") && args["window"].is_object()) + { + const nlohmann::json& w = args["window"]; + if (!w.contains("min_x") || !w.contains("min_y") || + !w.contains("max_x") || !w.contains("max_y")) + return makeError(kErrBadParam, "window requires min_x/min_y/max_x/max_y"); + x1 = w["min_x"].get(); y1 = w["min_y"].get(); + x2 = w["max_x"].get(); y2 = w["max_y"].get(); + } + else if (args.contains("min_x") && args.contains("min_y") && + args.contains("max_x") && args.contains("max_y")) + { + x1 = args["min_x"].get(); y1 = args["min_y"].get(); + x2 = args["max_x"].get(); y2 = args["max_y"].get(); + } + else + { + return makeError(kErrBadParam, "min_x/min_y/max_x/max_y (or window) is required"); + } + + const double margin = args.value("margin", 0.02); + + double view[4]; + zoomToBox(x1, y1, x2, y2, margin, view); + + nlohmann::json r; + r["ok"] = true; + r["view"] = nlohmann::json::array({ view[0], view[1], view[2], view[3] }); + return makeJsonResult(r); + } +}; +EXPORT_MCP_TOOL(mcp_Tool_ZoomToWindow, CreateZoomToWindowTool) + +// =========================================================================== +// highlight_entities +// =========================================================================== +class mcp_Tool_HighlightEntities : public mcp_Tool +{ +public: + nlohmann::json Execute(const nlohmann::json& args) override + { + const std::vector hs = collectHandles(args); + if (hs.empty()) return makeError(kErrBadParam, "handle or handles is required"); + + // restore=true 时把颜色复位为 ByLayer(256) + const bool restore = args.value("restore", false); + const int color = restore ? 256 : args.value("color", 1); // 默认红色 + + int count = 0; + for (size_t i = 0; i < hs.size(); ++i) + { + AcDbObjectId id; + if (!objectIdFromHandle(hs[i], id)) continue; + + AcDbEntity* pEnt = nullptr; + if (acdbOpenObject(pEnt, id, AcDb::kForWrite) != Acad::eOk || !pEnt) continue; + + pEnt->setColorIndex((Adesk::UInt16)color); + pEnt->draw(); + pEnt->close(); + ++count; + } + + nlohmann::json r; + r["ok"] = true; + r["count"] = count; + return makeJsonResult(r); + } +}; +EXPORT_MCP_TOOL(mcp_Tool_HighlightEntities, CreateHighlightEntitiesTool) diff --git a/SourceCode/Code2026/cad_mcp_plugins/mcp_plugins.cpp b/SourceCode/Code2026/cad_mcp_plugins/mcp_plugins.cpp new file mode 100644 index 0000000..248881b --- /dev/null +++ b/SourceCode/Code2026/cad_mcp_plugins/mcp_plugins.cpp @@ -0,0 +1,165 @@ +#include "KTCad.h" +#include "mcp_plugin_api.h" +#include +#include "tchar.h" +#include "rxregsvc.h" +#include +#pragma comment(lib, "gdiplus.lib") + +#ifdef ZWCAD + // 中望的库是 ZwRx.lib,符号也换成了 zcrx 家族(acrxEntryPoint 会被 SDK 宏改名, + // 但显式写出来的 GetApiVersion 不会,所以这里按平台分开)。 + #pragma comment(linker, "/export:zcrxGetApiVersion,PRIVATE") +#else + #pragma comment(lib, "rxapi.lib") + #pragma comment(linker, "/export:acrxGetApiVersion,PRIVATE") +#endif + +namespace +{ + // 辅助函数:Base64 编码 + std::string Base64Encode(const unsigned char *data, size_t length) + { + static const char encoding_table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + size_t out_len = 4 * ((length + 2) / 3); + std::string ret(out_len, '\0'); + size_t i; + char *p = const_cast(ret.c_str()); + + for (i = 0; i < length - 2; i += 3) + { + *p++ = encoding_table[(data[i] >> 2) & 0x3F]; + *p++ = encoding_table[((data[i] & 0x3) << 4) | ((int)(data[i + 1] & 0xF0) >> 4)]; + *p++ = encoding_table[((data[i + 1] & 0xF) << 2) | ((int)(data[i + 2] & 0xC0) >> 6)]; + *p++ = encoding_table[data[i + 2] & 0x3F]; + } + if (i < length) + { + *p++ = encoding_table[(data[i] >> 2) & 0x3F]; + if (i == (length - 1)) + { + *p++ = encoding_table[((data[i] & 0x3) << 4)]; + *p++ = '='; + } + else + { + *p++ = encoding_table[((data[i] & 0x3) << 4) | ((int)(data[i + 1] & 0xF0) >> 4)]; + *p++ = encoding_table[((data[i + 1] & 0xF) << 2)]; + } + *p++ = '='; + } + return ret; + } + + // 辅助函数:获取 GDI+ 图像编码器的 Clsid (用于转 PNG) + int GetEncoderClsid(const WCHAR *format, CLSID *pClsid) + { + UINT num = 0, size = 0; + Gdiplus::GetImageEncodersSize(&num, &size); + if (size == 0) return -1; + Gdiplus::ImageCodecInfo *pImageCodecInfo = (Gdiplus::ImageCodecInfo *)(malloc(size)); + if (pImageCodecInfo == NULL) return -1; + Gdiplus::GetImageEncoders(num, size, pImageCodecInfo); + for (UINT j = 0; j < num; ++j) + { + if (_tcscmp(pImageCodecInfo[j].MimeType, format) == 0) + { + *pClsid = pImageCodecInfo[j].Clsid; + free(pImageCodecInfo); + return j; + } + } + free(pImageCodecInfo); + return -1; + } +} + +class mcp_Tool_ViewportScreenshot: public mcp_Tool +{ +public: + virtual nlohmann::json Execute(const nlohmann::json &args) override + { + // 1. 获取 AutoCAD 当前文档的绘图区句柄 + HWND hWnd = adsw_acadDocWnd(); + if (!hWnd) + return mcp_Tool_Utility::make_error(-32000, L"无法获取CAD绘图区窗口句柄"); + + // 2. 初始化 GDI+ + Gdiplus::GdiplusStartupInput gdiplusStartupInput; + ULONG_PTR gdiplusToken; + Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL); + + std::string base64Result; + bool success = false; + + // 3. 开始 Windows GDI 抓屏逻辑 (使用花括号限定生命周期) + { + RECT rc; + GetClientRect(hWnd, &rc); + int width = rc.right - rc.left; + int height = rc.bottom - rc.top; + + HDC hdcScreen = GetDC(hWnd); + HDC hdcMem = CreateCompatibleDC(hdcScreen); + HBITMAP hBitmap = CreateCompatibleBitmap(hdcScreen, width, height); + HBITMAP hOldBitmap = (HBITMAP)SelectObject(hdcMem, hBitmap); + + // 将屏幕内容块拷贝到内存位图中 + BitBlt(hdcMem, 0, 0, width, height, hdcScreen, 0, 0, SRCCOPY); + + // 将 GDI 位图转换为 GDI+ 位图 + Gdiplus::Bitmap bmp(hBitmap, NULL); + + // 创建内存流,将位图以 PNG 格式保存到内存,而非硬盘 + IStream *pStream = nullptr; + if (CreateStreamOnHGlobal(NULL, TRUE, &pStream) == S_OK) + { + CLSID pngClsid; + GetEncoderClsid(L"image/png", &pngClsid); + + if (bmp.Save(pStream, &pngClsid, NULL) == Gdiplus::Ok) + { + // 从内存流中读取二进制数据 + STATSTG stat; + pStream->Stat(&stat, STATFLAG_NONAME); + ULONG size = stat.cbSize.LowPart; + + std::vector buffer(size); + LARGE_INTEGER liZero = {}; + pStream->Seek(liZero, STREAM_SEEK_SET, NULL); + + ULONG bytesRead; + pStream->Read(buffer.data(), size, &bytesRead); + + // 转换为 Base64 + base64Result = Base64Encode(buffer.data(), size); + success = true; + } + pStream->Release(); + } + + // 清理 GDI 资源 + SelectObject(hdcMem, hOldBitmap); + DeleteObject(hBitmap); + DeleteDC(hdcMem); + ReleaseDC(hWnd, hdcScreen); + } + + // 4. 关闭 GDI+ + Gdiplus::GdiplusShutdown(gdiplusToken); + + // 5. 按照 MCP 多模态协议返回数据 + if (success) + { + return mcp_Tool_Utility::make_mixed_result(L"已成功截取 AutoCAD 当前视口画面。", base64Result, "image/png"); + } + else + { + return mcp_Tool_Utility::make_error(-32001, L"截图或图像编码失败"); + } + } +}; + +EXPORT_MCP_TOOL(mcp_Tool_ViewportScreenshot, CreateViewportScreenshotTool) + + diff --git a/SourceCode/Code2026/cmakelists.txt b/SourceCode/Code2026/cmakelists.txt index 6cf08a6..65235b4 100644 --- a/SourceCode/Code2026/cmakelists.txt +++ b/SourceCode/Code2026/cmakelists.txt @@ -130,6 +130,7 @@ add_custom_module(SPLDCmd "SH/Structures") # R180/R190 是 C++98,跳过;中望的现代 SDK 都是 C++14,可以编 if (IS_ZWCAD OR CAD_SDK_VERSION GREATER_EQUAL 20) add_custom_module_2(cad_mcp_frame CadMcpFrame "SH/Other") + add_custom_module_2(cad_mcp_plugins CadMcpPlugins "SH/Other") else() message(STATUS ">>> 跳过 cad_mcp_frame:需要 C++11+(当前 preset 为 C++98)") endif() diff --git a/SourceCode/Code2026/cad_mcp_frame/inc/mcp_plugin_api.h b/SourceCode/Code2026/inc/mcp_plugin_api.h similarity index 100% rename from SourceCode/Code2026/cad_mcp_frame/inc/mcp_plugin_api.h rename to SourceCode/Code2026/inc/mcp_plugin_api.h diff --git a/cad_mcp_frame-review.md b/cad_mcp_frame-review.md index 1016ee2..4e428d7 100644 --- a/cad_mcp_frame-review.md +++ b/cad_mcp_frame-review.md @@ -9,6 +9,8 @@ | 项 | 处理 | | --- | --- | | 源码 | 12 个 cpp/h + `.def` + `.rc` + `res/` + `cad-mcp-frame.json` 拷到 `SourceCode/Code2026/cad_mcp_frame/` | +| 插件工程 | `CadProject/src/cad_mcp_plugins`(8 个 cpp/h)拷到 `SourceCode/Code2026/cad_mcp_plugins/`;输出是普通 DLL(`cad_mcp_plugins.dll`),由 frame 运行时 `LoadLibrary` | +| 插件接口头 | `mcp_plugin_api.h` 从 frame 目录**上移到 `SourceCode/Code2026/inc/`**(frame 与 plugins 共用;在 `ShsGlobalIncludes` 的 include 路径里,两边都自动可见) | | 插件接口头 | `mcp_plugin_api.h`(原在 `CadProject/inc/`)放到 `cad_mcp_frame/inc/` | | `cadsdk.h` | 改为 `#include "KTCad.h"`(两者除尾部 4 个 include 与 `using namespace MemOper` 外完全一致) | | `nlohmann/json` | 单头下载后放 `SourceCode/dep_inc/nlohmann/json.hpp`(仓库已跟踪 `dep_inc/`,与 `rapidjson` 同级) | @@ -19,6 +21,7 @@ | 顶层挂载 | `add_custom_module_2(cad_mcp_frame CadMcpFrame "SH/Other")` | | ZRX `.def` | 中望要导出 `zcrxEntryPoint` / `zcrxGetApiVersion`(ARX 下 `acrxEntryPoint` 被 SDK 宏改名,`def` 里必须写 zcrx 名) | | ZRX 版本号函数 | 代码里显式声明的 `acrxGetApiVersion()` 不会被宏改名,中望下未解析。改为按平台取 `zcrxGetApiVersion()`(`#ifdef ZWCAD`) | +| 插件的中望链接 | 源码里有 `#pragma comment(lib,"rxapi.lib")`,中望的库叫 `ZwRx.lib` → 该 pragma 与导出名都按 `#ifdef ZWCAD` 分开(中望导出 `zcrxGetApiVersion`);frame 里查插件版本号的函数名同样按平台分 | | 编码 | 全部 `.cpp/.h` 规整为 UTF-8 with BOM(仓库红线) | ## 2. 一个必须知道的限制:C++11+ @@ -41,8 +44,9 @@ endif() | preset | 结果 | | --- | --- | -| **R230**(AutoCAD 2020,C++14) | ✅ 编译通过,`cad_mcp_frame.arx` 818 KB,已自动部署 | -| **Z2026**(中望 2026,C++14) | ✅ 编译通过,`cad_mcp_frame.zrx` 818 KB,已自动部署 | +| **R230**(AutoCAD 2020,C++14) | ✅ 编译通过,`cad_mcp_frame.arx` + `cad_mcp_plugins.dll`,已自动部署 | +| **Z2026**(中望 2026,C++14) | ✅ 编译通过,`cad_mcp_frame.zrx` + `cad_mcp_plugins.dll`,已自动部署 | +| **插件**(R230 / Z2026) | ✅ `cad_mcp_plugins.dll` 866 KB / 864 KB;配置里 16 个 `c++_dll` 工具的工厂函数(`CreateXxxTool`)全部在导出表里 | | R190 / R180(C++98) | ⏭ 按条件跳过(见上) | ## 3. 工程结构与架构 @@ -183,8 +187,12 @@ return mcp_Tool_Utility::make_text_result(L"LISP inline command issued for execu 1. **配置文件名**:把 `cad-mcp-frame.json` 改成代码里找的 `mcp_config.json` (或把代码改成读 `cad-mcp-frame.json`)——现在是"能编译但一加载就自关"的状态。 -2. **插件工程未移植**:18 个工具里 16 个是 `c++_dll`,指到 `cad_mcp_plugins` 生成的 ARX; - 该工程还在 `CadProject` 下,没进 code2026。工具要真正可用,插件也得按同样方式移植。 +2. **插件已移植,但运行时文件没装配**:`cad_mcp_plugins.dll` 编译并部署到 + `c:\ShangHuaSoft\Envi3D-2026-M\<标签>\`,与 `cad_mcp_frame.arx` 同目录, + 而配置里 `plugin_directory` 是 `"."`、`dll_name` 是 `cad_mcp_plugins.dll` —— 位置对得上。 + 但**配置文件本身没有部署**(`set_debug_post_build` 只拷构建产物): + 需要把 `cad-mcp-frame.json`(或改名成 `mcp_config.json`)和 LISP 目录手工放到部署目录, + 否则 frame 起来后 `LoadAndRegister` 失败、直接自关。 3. **LISP 目录**:`global_settings.lisp_directory` 指向的脚本目录需要随部署带上。 4. **实测**:本次只验证"编译 + 部署",没有在 CAD 里加载验证(`NETLOAD`/启动自动加载后 看命令行是否打印 `[MCP Server] ... started`,以及能否 `tools/list`)。