FreeCAD WebAssembly development snapshot
Some checks failed
FreeCAD master CI / Prepare (push) Has been cancelled
FreeCAD master CI / Pixi (push) Has been cancelled
FreeCAD master CI / Ubuntu (push) Has been cancelled
FreeCAD master CI / Windows (push) Has been cancelled
FreeCAD master CI / Lint (push) Has been cancelled
FreeCAD master CI / WrapUp (push) Has been cancelled
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Scorecard supply-chain security / Scorecard analysis (push) Has been cancelled
Stale Issues / stale (push) Has been cancelled

This commit is contained in:
2026-08-20 07:00:53 +08:00
commit b5a086fda5
12718 changed files with 7841410 additions and 0 deletions

View File

@@ -0,0 +1,46 @@
# SPDX-License-Identifier: LGPL-2.1-or-later
cmake_minimum_required(VERSION 3.22)
project(FreeCADWebKernel LANGUAGES CXX)
if(NOT EMSCRIPTEN)
message(FATAL_ERROR "FreeCADWebKernel requires the Emscripten toolchain")
endif()
find_package(OpenCASCADE 7.6.3 CONFIG REQUIRED COMPONENTS
FoundationClasses
ModelingData
ModelingAlgorithms
DataExchange
)
add_executable(FreeCADWebKernel FreeCADWebBridge.cpp)
target_compile_features(FreeCADWebKernel PRIVATE cxx_std_11)
target_compile_definitions(FreeCADWebKernel PRIVATE OCC_CONVERT_SIGNALS)
target_include_directories(FreeCADWebKernel PRIVATE "${OpenCASCADE_INCLUDE_DIR}")
# OCCT toolkit exports in 7.6.3 do not carry transitive archive ordering.
# Group the static archives so cyclic algorithm dependencies resolve reliably.
target_link_libraries(FreeCADWebKernel PRIVATE
"-Wl,--start-group"
TKSTEP TKSTEP209 TKSTEPAttr TKSTEPBase TKXSBase
TKFillet TKMesh TKFeat TKOffset TKHLR TKBool TKBO TKShHealing
TKPrim TKTopAlgo TKGeomAlgo TKGeomBase TKBRep TKG3d TKG2d TKMath TKernel
"-Wl,--end-group"
)
target_link_options(FreeCADWebKernel PRIVATE
"--no-entry"
"-sWASM=1"
"-sMODULARIZE=1"
"-sEXPORT_ES6=1"
"-sEXPORT_NAME=FreeCADWebKernel"
"-sALLOW_MEMORY_GROWTH=1"
"-sENVIRONMENT=web,worker,node"
"-sEXPORTED_RUNTIME_METHODS=['ccall','cwrap']"
)
set_target_properties(FreeCADWebKernel PROPERTIES
SUFFIX ".js"
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}"
)

View File

@@ -0,0 +1,28 @@
# SPDX-License-Identifier: LGPL-2.1-or-later
cmake_minimum_required(VERSION 3.22)
project(FreeCADWebDependencyProbe LANGUAGES CXX)
if(NOT EMSCRIPTEN)
message(FATAL_ERROR "FreeCADWebDependencyProbe requires the Emscripten toolchain")
endif()
find_package(yaml-cpp 0.8 CONFIG REQUIRED)
find_package(Qt5 5.15 CONFIG REQUIRED COMPONENTS Core Network Xml)
find_package(Python3 3.12 EXACT COMPONENTS Interpreter Development REQUIRED)
add_executable(FreeCADWebDependencyProbe dependency-probe.cpp)
target_compile_features(FreeCADWebDependencyProbe PRIVATE cxx_std_17)
target_link_libraries(FreeCADWebDependencyProbe PRIVATE
yaml-cpp::yaml-cpp
Qt5::Core
Qt5::Network
Qt5::Xml
Python3::Python
)
target_link_options(FreeCADWebDependencyProbe PRIVATE
"-sENVIRONMENT=node"
"-sWASM_ASYNC_COMPILATION=0"
)
set_target_properties(FreeCADWebDependencyProbe PROPERTIES SUFFIX ".js")

View File

@@ -0,0 +1,30 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
#include <Python.h>
#include <QByteArray>
#include <QDomDocument>
#include <QNetworkRequest>
#include <QUrl>
#include <yaml-cpp/yaml.h>
#include <iostream>
int main()
{
const YAML::Node document = YAML::Load("probe: ready");
QDomDocument xml;
const bool xmlLoaded = xml.setContent(QStringLiteral("<probe status=\"ready\"/>"));
const QNetworkRequest request(QUrl(QStringLiteral("https://freecad.org/")));
const QByteArray host = request.url().host().toUtf8();
if (!document["probe"] || document["probe"].as<std::string>() != "ready" ||
!xmlLoaded || host != "freecad.org") {
return 1;
}
std::cout << "yaml-cpp=0.8.0"
<< " Qt=" << QT_VERSION_STR
<< " Python=" << Py_GetVersion()
<< '\n';
return 0;
}

View File

@@ -0,0 +1,492 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
#include <App/Application.h>
#include <App/Document.h>
#include <Base/Exception.h>
#include <Base/FileInfo.h>
#include <Mod/Assembly/App/AssemblyObject.h>
#include <Python.h>
#include <emscripten/emscripten.h>
#include <cmath>
#include <sstream>
#include <string>
extern "C" PyObject* PyInit_Materials();
extern "C" PyObject* PyInit_Part();
extern "C" PyObject* PyInit_Spreadsheet();
extern "C" PyObject* PyInit_AssemblyApp();
namespace {
std::string lastError;
std::string documentName;
std::string objectName;
std::string objectType;
int documentCountBeforeClose = 0;
int objectCount = 0;
int recomputeCount = 0;
int recomputeHasError = 0;
int solverStatus = 0;
int degreesOfFreedom = 0;
int componentCount = 0;
int documentCountAfterClose = 0;
std::string recoveryInvalidCode;
std::string recoveryInvalidMessage;
std::string recoveryStateBefore;
std::string recoveryStateAfter;
std::string recoveryStateAfterReplay;
int recoveryInvalidReturn = 0;
int recoveryReplayEqual = 0;
std::string persistencePath;
unsigned int persistenceSize = 0;
std::string persistenceSaveError;
std::string persistenceOpenError;
std::string persistenceStage;
int persistenceOpenedDocumentCount = 0;
int persistenceOpenedObjectCount = 0;
std::string persistenceOpenedObjectType;
std::string persistenceOpenedTypeProperty;
int persistenceRoundTrip = 0;
int persistenceOpenedRecompute = 0;
int persistenceOpenedHasError = 0;
void addPythonModule(const char* name, PyObject* (*initialize)())
{
auto* modules = PyImport_GetModuleDict();
if (PyDict_GetItemString(modules, name)) {
return;
}
PyObject* module = initialize();
if (!module) {
throw Base::RuntimeError(std::string("PyInit_") + name + " returned null");
}
PyDict_SetItemString(modules, name, module);
Py_DECREF(module);
}
void ensureAssemblyInitialized()
{
App::Application::initWebCore();
addPythonModule("Materials", PyInit_Materials);
addPythonModule("Part", PyInit_Part);
addPythonModule("Spreadsheet", PyInit_Spreadsheet);
addPythonModule("Assembly", PyInit_AssemblyApp);
}
} // namespace
extern "C" {
EMSCRIPTEN_KEEPALIVE int fc_web_assembly_kernel_create_recompute()
{
App::Document* document = nullptr;
try {
lastError.clear();
ensureAssemblyInitialized();
auto& application = App::GetApplication();
document = application.newDocument("AssemblyKernel", "Assembly Kernel", {false, true});
if (!document) {
throw Base::RuntimeError("Application::newDocument returned null");
}
auto* object = document->addObject("Assembly::AssemblyObject", "Assembly");
auto* assembly = dynamic_cast<Assembly::AssemblyObject*>(object);
if (!assembly) {
throw Base::RuntimeError("Document::addObject returned a non-AssemblyObject");
}
assembly->Type.setValue("Assembly");
documentName = document->getName();
objectName = document->getObjectName(assembly);
objectType = assembly->getTypeId().getName();
documentCountBeforeClose = static_cast<int>(application.getDocuments().size());
objectCount = document->countObjects();
componentCount = assembly->numberOfComponents();
bool hasError = false;
recomputeCount = document->recompute({}, false, &hasError);
recomputeHasError = hasError ? 1 : 0;
solverStatus = assembly->getLastSolverStatus();
degreesOfFreedom = assembly->getLastDoF();
const bool valid = documentName == "AssemblyKernel"
&& objectName == "Assembly"
&& objectType == "Assembly::AssemblyObject"
&& documentCountBeforeClose == 1
&& objectCount == 9
&& componentCount == 0
&& recomputeCount == 9
&& recomputeHasError == 0
&& solverStatus == 0
&& degreesOfFreedom == 0;
application.closeDocument(document);
document = nullptr;
documentCountAfterClose = static_cast<int>(application.getDocuments().size());
if (!valid || documentCountAfterClose != 0) {
lastError = "Assembly create/recompute contract mismatch";
return 0;
}
return 1;
}
catch (const Base::Exception& error) {
lastError = error.what();
}
catch (const std::exception& error) {
lastError = error.what();
}
catch (...) {
lastError = "unknown Assembly kernel failure";
}
if (document) {
App::GetApplication().closeDocument(document);
}
documentCountAfterClose = static_cast<int>(App::GetApplication().getDocuments().size());
return 0;
}
EMSCRIPTEN_KEEPALIVE int fc_web_assembly_kernel_recovery_probe()
{
App::Document* document = nullptr;
try {
lastError.clear();
recoveryInvalidCode.clear();
recoveryInvalidMessage.clear();
recoveryStateBefore.clear();
recoveryStateAfter.clear();
recoveryStateAfterReplay.clear();
recoveryInvalidReturn = 0;
recoveryReplayEqual = 0;
ensureAssemblyInitialized();
auto& application = App::GetApplication();
document = application.newDocument("AssemblyRecovery", "Assembly Recovery", {false, true});
if (!document) {
throw Base::RuntimeError("Application::newDocument returned null");
}
auto* object = document->addObject("Assembly::AssemblyObject", "Assembly");
auto* assembly = dynamic_cast<Assembly::AssemblyObject*>(object);
if (!assembly) {
throw Base::RuntimeError("Document::addObject returned a non-AssemblyObject");
}
assembly->Type.setValue("Assembly");
bool hasError = false;
const int baselineRecompute = document->recompute({}, false, &hasError);
const int baselineObjects = document->countObjects();
recoveryStateBefore = "AssemblyRecovery|Assembly::AssemblyObject|"
+ std::to_string(baselineObjects) + "|" + std::to_string(baselineRecompute)
+ "|" + std::to_string(hasError ? 1 : 0);
auto attemptInvalid = [&]() {
try {
auto* invalid = document->addObject("Assembly::MissingObject", "Invalid");
recoveryInvalidReturn = invalid ? 1 : 0;
recoveryInvalidCode = "invalid_type";
recoveryInvalidMessage = "unexpectedly created Assembly::MissingObject";
}
catch (const Base::Exception& error) {
recoveryInvalidReturn = 0;
recoveryInvalidCode = "invalid_type";
recoveryInvalidMessage = error.what();
}
catch (const std::exception& error) {
recoveryInvalidReturn = 0;
recoveryInvalidCode = "invalid_type";
recoveryInvalidMessage = error.what();
}
};
attemptInvalid();
recoveryStateAfter = "AssemblyRecovery|Assembly::AssemblyObject|"
+ std::to_string(document->countObjects()) + "|" + std::to_string(baselineRecompute)
+ "|" + std::to_string(hasError ? 1 : 0);
const std::string firstMessage = recoveryInvalidMessage;
attemptInvalid();
recoveryStateAfterReplay = "AssemblyRecovery|Assembly::AssemblyObject|"
+ std::to_string(document->countObjects()) + "|" + std::to_string(baselineRecompute)
+ "|" + std::to_string(hasError ? 1 : 0);
recoveryReplayEqual = recoveryInvalidReturn == 0
&& recoveryInvalidCode == "invalid_type"
&& recoveryInvalidMessage == firstMessage
&& recoveryStateBefore == recoveryStateAfter
&& recoveryStateAfter == recoveryStateAfterReplay
&& document->getObject("Assembly") == assembly
&& document->countObjects() == baselineObjects;
const bool valid = baselineRecompute == 9
&& !hasError
&& recoveryInvalidReturn == 0
&& recoveryInvalidCode == "invalid_type"
&& recoveryReplayEqual;
application.closeDocument(document);
document = nullptr;
if (!valid) {
lastError = "Assembly recovery contract mismatch";
return 0;
}
return 1;
}
catch (const Base::Exception& error) {
lastError = error.what();
}
catch (const std::exception& error) {
lastError = error.what();
}
catch (...) {
lastError = "unknown Assembly recovery failure";
}
if (document) {
App::GetApplication().closeDocument(document);
}
return 0;
}
EMSCRIPTEN_KEEPALIVE int fc_web_assembly_kernel_save_reopen()
{
App::Document* document = nullptr;
App::Document* reopened = nullptr;
try {
lastError.clear();
persistenceSaveError.clear();
persistenceOpenError.clear();
persistenceOpenedObjectType.clear();
persistenceOpenedTypeProperty.clear();
persistenceOpenedDocumentCount = 0;
persistenceOpenedObjectCount = 0;
persistenceRoundTrip = 0;
persistenceOpenedRecompute = 0;
persistenceOpenedHasError = 0;
persistenceStage.clear();
ensureAssemblyInitialized();
auto& application = App::GetApplication();
persistenceStage = "create";
document = application.newDocument("AssemblyPersistence", "Assembly Persistence", {false, true});
auto* object = document ? document->addObject("Assembly::AssemblyObject", "Assembly") : nullptr;
auto* assembly = dynamic_cast<Assembly::AssemblyObject*>(object);
if (!assembly) {
throw Base::RuntimeError("failed to create Assembly::AssemblyObject for persistence");
}
assembly->Type.setValue("Assembly");
bool hasError = false;
persistenceStage = "recompute";
const int recompute = document->recompute({}, false, &hasError);
persistencePath = "/tmp/AssemblyKernel.FCStd";
persistenceStage = "save";
const bool saved = document->saveAs(persistencePath.c_str());
Base::FileInfo savedFile(persistencePath);
persistenceSize = savedFile.exists() ? savedFile.size() : 0;
const std::string savedType = assembly->getTypeId().getName();
application.closeDocument(document);
document = nullptr;
if (!saved || hasError || recompute != 9 || savedType != "Assembly::AssemblyObject" || persistenceSize == 0) {
persistenceSaveError = "Assembly FCStd save contract mismatch";
return 0;
}
persistenceStage = "open";
reopened = application.newDocument("AssemblyPersistenceOpened", "Assembly Persistence Opened", {false, true});
persistenceStage = "open-restore";
if (reopened) {
reopened->FileName.setValue(persistencePath);
reopened->restore(persistencePath.c_str(), true, {});
persistenceStage = "after-restore";
reopened->afterRestore(true);
}
if (!reopened) {
persistenceOpenError = "Application::newDocument returned null";
return 0;
}
persistenceOpenedDocumentCount = static_cast<int>(application.getDocuments().size());
persistenceOpenedObjectCount = reopened->countObjects();
persistenceStage = "inspect";
auto* reopenedObject = reopened->getObject("Assembly");
auto* reopenedAssembly = dynamic_cast<Assembly::AssemblyObject*>(reopenedObject);
if (!reopenedAssembly) {
persistenceOpenError = "reopened document did not contain Assembly::AssemblyObject";
return 0;
}
persistenceOpenedObjectType = reopenedObject->getTypeId().getName();
persistenceOpenedTypeProperty = reopenedAssembly->Type.getValue();
bool reopenedHasError = false;
persistenceStage = "recompute-opened";
const int reopenedRecompute = reopened->recompute({}, false, &reopenedHasError);
persistenceOpenedRecompute = reopenedRecompute;
persistenceOpenedHasError = reopenedHasError ? 1 : 0;
persistenceRoundTrip = persistenceOpenedDocumentCount == 1
&& persistenceOpenedObjectCount == 9
&& persistenceOpenedObjectType == "Assembly::AssemblyObject"
&& persistenceOpenedTypeProperty == "Assembly"
&& reopenedRecompute >= 0
&& !reopenedHasError;
application.closeDocument(reopened);
reopened = nullptr;
if (!persistenceRoundTrip || application.getDocuments().size() != 0) {
persistenceOpenError = "Assembly FCStd reopen contract mismatch";
return 0;
}
return 1;
}
catch (const Base::Exception& error) {
lastError = persistenceStage + ": " + error.what();
persistenceOpenError = lastError;
}
catch (const std::exception& error) {
lastError = persistenceStage + ": " + error.what();
persistenceOpenError = lastError;
}
catch (...) {
lastError = persistenceStage + ": unknown Assembly persistence failure";
persistenceOpenError = lastError;
}
if (document) App::GetApplication().closeDocument(document);
if (reopened) App::GetApplication().closeDocument(reopened);
return 0;
}
EMSCRIPTEN_KEEPALIVE const char* fc_web_assembly_kernel_error()
{
return lastError.c_str();
}
EMSCRIPTEN_KEEPALIVE const char* fc_web_assembly_kernel_document_name()
{
return documentName.c_str();
}
EMSCRIPTEN_KEEPALIVE const char* fc_web_assembly_kernel_object_name()
{
return objectName.c_str();
}
EMSCRIPTEN_KEEPALIVE const char* fc_web_assembly_kernel_object_type()
{
return objectType.c_str();
}
EMSCRIPTEN_KEEPALIVE int fc_web_assembly_kernel_document_count_before_close()
{
return documentCountBeforeClose;
}
EMSCRIPTEN_KEEPALIVE int fc_web_assembly_kernel_object_count()
{
return objectCount;
}
EMSCRIPTEN_KEEPALIVE int fc_web_assembly_kernel_recompute_count()
{
return recomputeCount;
}
EMSCRIPTEN_KEEPALIVE int fc_web_assembly_kernel_recompute_has_error()
{
return recomputeHasError;
}
EMSCRIPTEN_KEEPALIVE int fc_web_assembly_kernel_solver_status()
{
return solverStatus;
}
EMSCRIPTEN_KEEPALIVE int fc_web_assembly_kernel_dof()
{
return degreesOfFreedom;
}
EMSCRIPTEN_KEEPALIVE int fc_web_assembly_kernel_component_count()
{
return componentCount;
}
EMSCRIPTEN_KEEPALIVE int fc_web_assembly_kernel_document_count_after_close()
{
return documentCountAfterClose;
}
EMSCRIPTEN_KEEPALIVE const char* fc_web_assembly_kernel_recovery_invalid_code()
{
return recoveryInvalidCode.c_str();
}
EMSCRIPTEN_KEEPALIVE const char* fc_web_assembly_kernel_recovery_invalid_message()
{
return recoveryInvalidMessage.c_str();
}
EMSCRIPTEN_KEEPALIVE const char* fc_web_assembly_kernel_recovery_state_before()
{
return recoveryStateBefore.c_str();
}
EMSCRIPTEN_KEEPALIVE const char* fc_web_assembly_kernel_recovery_state_after()
{
return recoveryStateAfter.c_str();
}
EMSCRIPTEN_KEEPALIVE const char* fc_web_assembly_kernel_recovery_state_after_replay()
{
return recoveryStateAfterReplay.c_str();
}
EMSCRIPTEN_KEEPALIVE int fc_web_assembly_kernel_recovery_invalid_return()
{
return recoveryInvalidReturn;
}
EMSCRIPTEN_KEEPALIVE int fc_web_assembly_kernel_recovery_replay_equal()
{
return recoveryReplayEqual;
}
EMSCRIPTEN_KEEPALIVE const char* fc_web_assembly_kernel_persistence_path()
{
return persistencePath.c_str();
}
EMSCRIPTEN_KEEPALIVE int fc_web_assembly_kernel_persistence_size()
{
return static_cast<int>(persistenceSize);
}
EMSCRIPTEN_KEEPALIVE const char* fc_web_assembly_kernel_persistence_save_error()
{
return persistenceSaveError.c_str();
}
EMSCRIPTEN_KEEPALIVE const char* fc_web_assembly_kernel_persistence_open_error()
{
return persistenceOpenError.c_str();
}
EMSCRIPTEN_KEEPALIVE int fc_web_assembly_kernel_persistence_opened_document_count()
{
return persistenceOpenedDocumentCount;
}
EMSCRIPTEN_KEEPALIVE int fc_web_assembly_kernel_persistence_opened_object_count()
{
return persistenceOpenedObjectCount;
}
EMSCRIPTEN_KEEPALIVE const char* fc_web_assembly_kernel_persistence_opened_object_type()
{
return persistenceOpenedObjectType.c_str();
}
EMSCRIPTEN_KEEPALIVE const char* fc_web_assembly_kernel_persistence_opened_type_property()
{
return persistenceOpenedTypeProperty.c_str();
}
EMSCRIPTEN_KEEPALIVE int fc_web_assembly_kernel_persistence_round_trip()
{
return persistenceRoundTrip;
}
EMSCRIPTEN_KEEPALIVE int fc_web_assembly_kernel_persistence_opened_recompute()
{
return persistenceOpenedRecompute;
}
EMSCRIPTEN_KEEPALIVE int fc_web_assembly_kernel_persistence_opened_has_error()
{
return persistenceOpenedHasError;
}
}

View File

@@ -0,0 +1,242 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
#include <App/Application.h>
#include <App/DocumentObject.h>
#include <Base/Exception.h>
#include <Base/Type.h>
#include <Python.h>
#include <emscripten/emscripten.h>
#include <cstddef>
#include <exception>
#include <string>
#include <vector>
extern "C" PyObject* PyInit_Materials();
extern "C" PyObject* PyInit_Part();
extern "C" PyObject* PyInit_Spreadsheet();
extern "C" PyObject* PyInit_AssemblyApp();
namespace {
std::string lastErrorCode;
std::string lastErrorMessage;
std::string lastTypeName;
unsigned int initializationCalls = 0;
unsigned int initializationRuns = 0;
bool assemblyInitialized = false;
std::vector<App::DocumentObject*> handles;
void setError(const char* code, const std::string& message)
{
lastErrorCode = code;
lastErrorMessage = message;
}
void clearError()
{
lastErrorCode.clear();
lastErrorMessage.clear();
}
std::string pythonError(const char* fallback)
{
if (!PyErr_Occurred()) {
return fallback;
}
PyObject* type = nullptr;
PyObject* value = nullptr;
PyObject* traceback = nullptr;
PyErr_Fetch(&type, &value, &traceback);
PyErr_NormalizeException(&type, &value, &traceback);
std::string message = fallback;
if (value) {
PyObject* text = PyObject_Str(value);
if (text) {
const char* utf8 = PyUnicode_AsUTF8(text);
if (utf8 && *utf8) {
message += ": ";
message += utf8;
}
Py_DECREF(text);
}
}
Py_XDECREF(type);
Py_XDECREF(value);
Py_XDECREF(traceback);
return message;
}
void addPythonModule(const char* name, PyObject* (*initialize)())
{
auto* modules = PyImport_GetModuleDict();
if (PyDict_GetItemString(modules, name)) {
return;
}
PyObject* module = initialize();
if (!module) {
throw Base::RuntimeError(pythonError((std::string("PyInit_") + name + " failed").c_str()));
}
if (PyDict_SetItemString(modules, name, module) != 0) {
Py_DECREF(module);
throw Base::RuntimeError(std::string("failed to register Python module ") + name);
}
Py_DECREF(module);
}
bool ensureAssembly()
{
++initializationCalls;
if (assemblyInitialized) {
clearError();
return true;
}
++initializationRuns;
try {
App::Application::initWebCore();
addPythonModule("Materials", PyInit_Materials);
addPythonModule("Part", PyInit_Part);
addPythonModule("Spreadsheet", PyInit_Spreadsheet);
addPythonModule("AssemblyApp", PyInit_AssemblyApp);
if (Base::Type::fromName("Assembly::AssemblyObject").isBad()) {
throw Base::RuntimeError("Assembly::AssemblyObject was not registered");
}
assemblyInitialized = true;
clearError();
return true;
}
catch (const Base::Exception& error) {
setError("initialization_failed", error.what());
}
catch (const std::exception& error) {
setError("initialization_failed", error.what());
}
catch (...) {
setError("initialization_failed", "unknown Assembly initialization failure");
}
return false;
}
bool requireModule(const char* moduleName)
{
if (!moduleName || *moduleName == '\0') {
setError("invalid_argument", "module name is empty");
return false;
}
const std::string name(moduleName);
if (name == "AssemblyGui") {
setError("gui_dependency_unavailable", "AssemblyGui is unavailable in the GUI-free Web kernel");
return false;
}
if (name != "AssemblyApp") {
setError("module_unavailable", "module is not available in the GUI-free Web kernel: " + name);
return false;
}
return ensureAssembly();
}
}
extern "C" {
EMSCRIPTEN_KEEPALIVE int fc_web_assembly_initialize(const char* moduleName)
{
return requireModule(moduleName) ? 1 : 0;
}
EMSCRIPTEN_KEEPALIVE int fc_web_assembly_type_probe(const char* typeName)
{
if (!requireModule("AssemblyApp")) {
return 0;
}
if (!typeName || *typeName == '\0') {
setError("invalid_argument", "type name is empty");
return 0;
}
const Base::Type type = Base::Type::fromName(typeName);
if (type.isBad()) {
lastTypeName.clear();
setError("type_not_found", "type is not registered: " + std::string(typeName));
return 0;
}
lastTypeName = type.getName();
clearError();
return 1;
}
EMSCRIPTEN_KEEPALIVE int fc_web_assembly_create_handle(const char* typeName)
{
if (!fc_web_assembly_type_probe(typeName)) {
return 0;
}
const Base::Type type = Base::Type::fromName(typeName);
if (!type.canInstantiate()) {
setError("type_not_instantiable", "type cannot be instantiated: " + std::string(typeName));
return 0;
}
auto* object = static_cast<App::DocumentObject*>(type.createInstance());
if (!object) {
setError("type_not_instantiable", "type cannot create a DocumentObject: " + std::string(typeName));
return 0;
}
handles.push_back(object);
clearError();
return static_cast<int>(handles.size());
}
EMSCRIPTEN_KEEPALIVE int fc_web_assembly_release_handle(int handle)
{
if (handle <= 0 || static_cast<std::size_t>(handle) > handles.size() || handles[handle - 1] == nullptr) {
setError("invalid_handle", "handle is unknown or already released");
return 0;
}
delete handles[handle - 1];
handles[handle - 1] = nullptr;
clearError();
return 1;
}
EMSCRIPTEN_KEEPALIVE int fc_web_assembly_active_handles()
{
int active = 0;
for (const auto* handle : handles) {
if (handle) {
++active;
}
}
return active;
}
EMSCRIPTEN_KEEPALIVE const char* fc_web_assembly_error_code()
{
return lastErrorCode.c_str();
}
EMSCRIPTEN_KEEPALIVE const char* fc_web_assembly_error_message()
{
return lastErrorMessage.c_str();
}
EMSCRIPTEN_KEEPALIVE const char* fc_web_assembly_last_type()
{
return lastTypeName.c_str();
}
EMSCRIPTEN_KEEPALIVE unsigned int fc_web_assembly_initialization_calls()
{
return initializationCalls;
}
EMSCRIPTEN_KEEPALIVE unsigned int fc_web_assembly_initialization_runs()
{
return initializationRuns;
}
EMSCRIPTEN_KEEPALIVE int fc_web_assembly_initialized()
{
return assemblyInitialized ? 1 : 0;
}
}

View File

@@ -0,0 +1,256 @@
# SPDX-License-Identifier: LGPL-2.1-or-later
add_executable(FreeCADWebPartBoxProbe PartBoxProbe.cpp)
target_compile_features(FreeCADWebPartBoxProbe PRIVATE cxx_std_17)
target_compile_options(FreeCADWebPartBoxProbe PRIVATE "-O2" "-g0" "-fexceptions")
target_include_directories(FreeCADWebPartBoxProbe PRIVATE
"${CMAKE_BINARY_DIR}"
"${CMAKE_BINARY_DIR}/src"
"${CMAKE_SOURCE_DIR}/src"
)
set(_freecad_web_python_build "${FREECAD_WEB_DEPENDENCY_ROOT}/python-probe")
set(_freecad_web_python_encodings "${FREECAD_WEB_PYTHON_ROOT}/lib/python3.12/encodings")
target_link_libraries(FreeCADWebPartBoxProbe PRIVATE
Part
${Python3_LIBRARIES}
"${_freecad_web_python_build}/Modules/_decimal/libmpdec/libmpdec.a"
"${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a"
"${_freecad_web_python_build}/Modules/expat/libexpat.a"
)
target_link_options(FreeCADWebPartBoxProbe PRIVATE
"-O2"
"-g0"
"--no-entry"
"-sWASM=1"
"-sMODULARIZE=1"
"-sEXPORT_ES6=1"
"-sEXPORT_NAME=FreeCADWebPartBoxProbe"
"-sALLOW_MEMORY_GROWTH=1"
"-sINITIAL_MEMORY=33554432"
"-sENVIRONMENT=web,worker,node"
"-sUSE_BZIP2=1"
"-sDISABLE_EXCEPTION_CATCHING=0"
"-sEXPORTED_RUNTIME_METHODS=['ccall']"
"--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings"
)
set_target_properties(FreeCADWebPartBoxProbe PROPERTIES
SUFFIX ".js"
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
)
add_executable(FreeCADWebModuleLoaderProbe ModuleLoaderProbe.cpp)
target_compile_features(FreeCADWebModuleLoaderProbe PRIVATE cxx_std_17)
target_compile_options(FreeCADWebModuleLoaderProbe PRIVATE "-O2" "-g0" "-fexceptions")
target_include_directories(FreeCADWebModuleLoaderProbe PRIVATE
"${CMAKE_BINARY_DIR}"
"${CMAKE_BINARY_DIR}/src"
"${CMAKE_SOURCE_DIR}/src"
)
target_link_libraries(FreeCADWebModuleLoaderProbe PRIVATE
Part
${Python3_LIBRARIES}
"${_freecad_web_python_build}/Modules/_decimal/libmpdec/libmpdec.a"
"${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a"
"${_freecad_web_python_build}/Modules/expat/libexpat.a"
)
target_link_options(FreeCADWebModuleLoaderProbe PRIVATE
"-O2"
"-g0"
"--no-entry"
"-sWASM=1"
"-sMODULARIZE=1"
"-sEXPORT_ES6=1"
"-sEXPORT_NAME=FreeCADWebModuleLoaderProbe"
"-sALLOW_MEMORY_GROWTH=1"
"-sINITIAL_MEMORY=33554432"
"-sENVIRONMENT=web,worker,node"
"-sUSE_BZIP2=1"
"-sDISABLE_EXCEPTION_CATCHING=0"
"-sEXPORTED_RUNTIME_METHODS=['ccall']"
"--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings"
)
set_target_properties(FreeCADWebModuleLoaderProbe PROPERTIES
SUFFIX ".js"
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
)
add_executable(FreeCADWebAssemblyProbe AssemblyRuntimeProbe.cpp)
target_compile_features(FreeCADWebAssemblyProbe PRIVATE cxx_std_17)
target_compile_options(FreeCADWebAssemblyProbe PRIVATE "-O2" "-g0" "-fexceptions")
target_include_directories(FreeCADWebAssemblyProbe PRIVATE
"${CMAKE_BINARY_DIR}"
"${CMAKE_BINARY_DIR}/src"
"${CMAKE_SOURCE_DIR}/src"
)
target_link_libraries(FreeCADWebAssemblyProbe PRIVATE
Assembly
${Python3_LIBRARIES}
"${_freecad_web_python_build}/Modules/_decimal/libmpdec/libmpdec.a"
"${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a"
"${_freecad_web_python_build}/Modules/expat/libexpat.a"
)
target_link_options(FreeCADWebAssemblyProbe PRIVATE
"-O2"
"-g0"
"--no-entry"
"-sWASM=1"
"-sMODULARIZE=1"
"-sEXPORT_ES6=1"
"-sEXPORT_NAME=FreeCADWebAssemblyProbe"
"-sALLOW_MEMORY_GROWTH=1"
"-sINITIAL_MEMORY=33554432"
"-sENVIRONMENT=web,worker,node"
"-sUSE_BZIP2=1"
"-sDISABLE_EXCEPTION_CATCHING=0"
"-sEXPORTED_RUNTIME_METHODS=['ccall']"
"--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings"
)
set_target_properties(FreeCADWebAssemblyProbe PROPERTIES
SUFFIX ".js"
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
)
add_executable(FreeCADWebAssemblyKernelProbe AssemblyKernelProbe.cpp)
target_compile_features(FreeCADWebAssemblyKernelProbe PRIVATE cxx_std_17)
target_compile_options(FreeCADWebAssemblyKernelProbe PRIVATE "-O2" "-g0" "-fexceptions")
target_include_directories(FreeCADWebAssemblyKernelProbe PRIVATE
"${CMAKE_BINARY_DIR}"
"${CMAKE_BINARY_DIR}/src"
"${CMAKE_SOURCE_DIR}/src"
"${CMAKE_SOURCE_DIR}/src/3rdParty/OndselSolver"
)
target_link_libraries(FreeCADWebAssemblyKernelProbe PRIVATE
Assembly
${Python3_LIBRARIES}
"${_freecad_web_python_build}/Modules/_decimal/libmpdec/libmpdec.a"
"${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a"
"${_freecad_web_python_build}/Modules/expat/libexpat.a"
)
target_link_options(FreeCADWebAssemblyKernelProbe PRIVATE
"-O2"
"-g0"
"--no-entry"
"-sWASM=1"
"-sMODULARIZE=1"
"-sEXPORT_ES6=1"
"-sEXPORT_NAME=FreeCADWebAssemblyKernelProbe"
"-sALLOW_MEMORY_GROWTH=1"
"-sINITIAL_MEMORY=33554432"
"-sENVIRONMENT=web,worker,node"
"-sUSE_BZIP2=1"
"-sDISABLE_EXCEPTION_CATCHING=0"
"-sEXPORTED_RUNTIME_METHODS=['ccall','FS']"
"--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings"
)
set_target_properties(FreeCADWebAssemblyKernelProbe PROPERTIES
SUFFIX ".js"
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
)
add_executable(FreeCADWebDocumentProbe DocumentProbe.cpp)
target_compile_features(FreeCADWebDocumentProbe PRIVATE cxx_std_17)
target_compile_options(FreeCADWebDocumentProbe PRIVATE "-O2" "-g0" "-fexceptions")
target_include_directories(FreeCADWebDocumentProbe PRIVATE
"${CMAKE_BINARY_DIR}"
"${CMAKE_BINARY_DIR}/src"
"${CMAKE_SOURCE_DIR}/src"
)
target_link_libraries(FreeCADWebDocumentProbe PRIVATE
Part
${Python3_LIBRARIES}
"${_freecad_web_python_build}/Modules/_decimal/libmpdec/libmpdec.a"
"${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a"
"${_freecad_web_python_build}/Modules/expat/libexpat.a"
)
target_link_options(FreeCADWebDocumentProbe PRIVATE
"-O2"
"-g0"
"--no-entry"
"-sWASM=1"
"-sMODULARIZE=1"
"-sEXPORT_ES6=1"
"-sEXPORT_NAME=FreeCADWebDocumentProbe"
"-sALLOW_MEMORY_GROWTH=1"
"-sINITIAL_MEMORY=33554432"
"-sENVIRONMENT=web,worker,node"
"-sUSE_BZIP2=1"
"-sDISABLE_EXCEPTION_CATCHING=0"
"-sEXPORTED_RUNTIME_METHODS=['ccall','FS']"
"--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings"
)
set_target_properties(FreeCADWebDocumentProbe PROPERTIES
SUFFIX ".js"
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
)
add_executable(FreeCADWebSketcherProbe SketcherProbe.cpp)
target_compile_features(FreeCADWebSketcherProbe PRIVATE cxx_std_17)
target_compile_options(FreeCADWebSketcherProbe PRIVATE "-O2" "-g0" "-fexceptions")
target_include_directories(FreeCADWebSketcherProbe PRIVATE
"${CMAKE_BINARY_DIR}"
"${CMAKE_BINARY_DIR}/src"
"${CMAKE_SOURCE_DIR}/src"
)
target_link_libraries(FreeCADWebSketcherProbe PRIVATE
Sketcher
${Python3_LIBRARIES}
"${_freecad_web_python_build}/Modules/_decimal/libmpdec/libmpdec.a"
"${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a"
"${_freecad_web_python_build}/Modules/expat/libexpat.a"
)
target_link_options(FreeCADWebSketcherProbe PRIVATE
"-O2"
"-g0"
"--no-entry"
"-sWASM=1"
"-sMODULARIZE=1"
"-sEXPORT_ES6=1"
"-sEXPORT_NAME=FreeCADWebSketcherProbe"
"-sALLOW_MEMORY_GROWTH=1"
"-sINITIAL_MEMORY=33554432"
"-sENVIRONMENT=web,worker,node"
"-sUSE_BZIP2=1"
"-sDISABLE_EXCEPTION_CATCHING=0"
"-sEXPORTED_RUNTIME_METHODS=['ccall']"
"--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings"
)
set_target_properties(FreeCADWebSketcherProbe PROPERTIES
SUFFIX ".js"
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
)
add_executable(FreeCADWebPythonProbe PythonRuntimeProbe.cpp)
target_compile_features(FreeCADWebPythonProbe PRIVATE cxx_std_17)
target_compile_options(FreeCADWebPythonProbe PRIVATE "-O2" "-g0" "-fexceptions")
target_include_directories(FreeCADWebPythonProbe PRIVATE
"${CMAKE_BINARY_DIR}"
"${CMAKE_BINARY_DIR}/src"
"${CMAKE_SOURCE_DIR}/src"
)
target_link_libraries(FreeCADWebPythonProbe PRIVATE
Part
${Python3_LIBRARIES}
"${_freecad_web_python_build}/Modules/_decimal/libmpdec/libmpdec.a"
"${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a"
"${_freecad_web_python_build}/Modules/expat/libexpat.a"
)
target_link_options(FreeCADWebPythonProbe PRIVATE
"-O2"
"-g0"
"--no-entry"
"-sWASM=1"
"-sMODULARIZE=1"
"-sEXPORT_ES6=1"
"-sEXPORT_NAME=FreeCADWebPythonProbe"
"-sALLOW_MEMORY_GROWTH=1"
"-sINITIAL_MEMORY=33554432"
"-sENVIRONMENT=web,worker,node"
"-sUSE_BZIP2=1"
"-sDISABLE_EXCEPTION_CATCHING=0"
"-sEXPORTED_RUNTIME_METHODS=['ccall']"
"--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings"
)
set_target_properties(FreeCADWebPythonProbe PROPERTIES
SUFFIX ".js"
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
)

View File

@@ -0,0 +1,739 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
#include <App/Application.h>
#include <App/Document.h>
#include <App/DocumentObject.h>
#include <Base/Console.h>
#include <Base/Exception.h>
#include <Base/FileInfo.h>
#include <BRepGProp.hxx>
#include <GProp_GProps.hxx>
#include <Mod/Material/App/MaterialManager.h>
#include <Mod/Material/App/Materials.h>
#include <Mod/Material/App/PropertyMaterial.h>
#include <Mod/Part/App/AttachExtension.h>
#include <Mod/Part/App/FeaturePartBox.h>
#include <Mod/Part/App/PartFeature.h>
#include <Mod/Part/App/PrimitiveFeature.h>
#include <Mod/Part/App/PropertyTopoShape.h>
#include <Mod/Part/App/TopoShape.h>
#include <emscripten/emscripten.h>
#include <string>
#include <cmath>
extern "C" PyObject* PyInit_Materials();
extern "C" PyObject* PyInit_Part();
namespace {
std::string lastError;
std::string documentName;
std::string objectName;
std::string objectType;
std::string stage;
int documentCount = 0;
int objectCount = 0;
int recomputeCount = 0;
double recomputeVolume = 0.0;
int recomputeHasError = 0;
std::string invalidDimensionError;
double invalidShapeVolume = 0.0;
double recoveredShapeVolume = 0.0;
int recoveryHasError = 0;
std::string fcstdPath;
unsigned int fcstdSize = 0;
double fcstdVolume = 0.0;
int openedDocumentCount = 0;
int openedObjectCount = 0;
std::string openedObjectType;
double openedLength = 0.0;
double openedWidth = 0.0;
double openedHeight = 0.0;
double openedVolume = 0.0;
int transactionId = 0;
int transactionBeforeUndo = 0;
int transactionAfterUndo = 0;
int transactionPendingBeforeCommit = 0;
int transactionPendingAfterCommit = 0;
double transactionBeforeVolume = 0.0;
double transactionAfterVolume = 0.0;
int transactionUndoResult = 0;
int transactionAfterUndoCount = 0;
double transactionUndoVolume = 0.0;
int transactionRedoResult = 0;
double transactionRedoVolume = 0.0;
int transactionAbortPending = 0;
double transactionAbortVolume = 0.0;
void ensureTypesInitialized()
{
App::Application::initWebCore();
}
void ensurePythonModules()
{
auto* modules = PyImport_GetModuleDict();
if (!PyDict_GetItemString(modules, "Materials")) {
PyObject* materialModule = PyInit_Materials();
if (materialModule == nullptr) {
throw Base::RuntimeError("PyInit_Materials returned null");
}
PyDict_SetItemString(modules, "Materials", materialModule);
Py_DECREF(materialModule);
}
if (!PyDict_GetItemString(modules, "Part")) {
PyObject* partModule = PyInit_Part();
if (partModule == nullptr) {
throw Base::RuntimeError("PyInit_Part returned null");
}
PyDict_SetItemString(modules, "Part", partModule);
Py_DECREF(partModule);
}
}
}
extern "C" {
EMSCRIPTEN_KEEPALIVE int fc_web_document_create_and_enumerate()
{
try {
lastError.clear();
stage = "initializing types";
ensureTypesInitialized();
stage = "initializing Python modules";
ensurePythonModules();
auto& application = App::GetApplication();
stage = "creating document";
auto* document = application.newDocument("WebDocument", "Web Document", {false, true});
if (document == nullptr) {
lastError = "Application::newDocument returned null";
return 0;
}
stage = "adding Part::Box";
auto* object = document->addObject("Part::Box", "Box");
if (object == nullptr) {
lastError = "Document::addObject returned null";
application.closeDocument(document);
return 0;
}
documentName = document->getName();
objectName = document->getObjectName(object);
objectType = object->getTypeId().getName();
documentCount = static_cast<int>(application.getDocuments().size());
objectCount = document->countObjects();
const bool valid = documentCount == 1
&& objectCount == 1
&& document->containsObject(object)
&& objectType == "Part::Box";
stage = "closing document";
application.closeDocument(document);
if (!valid) {
lastError = "Document enumeration contract mismatch";
return 0;
}
return 1;
}
catch (const Base::Exception& error) {
lastError = stage + ": " + error.what();
return 0;
}
catch (const std::exception& error) {
lastError = stage + ": " + error.what();
return 0;
}
catch (...) {
lastError = "Unknown Document probe failure at " + stage;
return 0;
}
}
EMSCRIPTEN_KEEPALIVE int fc_web_document_recompute_box()
{
App::Document* document = nullptr;
try {
lastError.clear();
stage = "initializing types";
ensureTypesInitialized();
stage = "initializing Python modules";
ensurePythonModules();
stage = "creating document";
auto& application = App::GetApplication();
document = application.newDocument("RecomputeDocument", "Recompute Document", {false, true});
if (!document) {
lastError = "Application::newDocument returned null";
return 0;
}
stage = "adding Part::Box";
auto* object = document->addObject("Part::Box", "Box");
auto* box = dynamic_cast<Part::Box*>(object);
if (!box) {
lastError = "Document::addObject returned a non-Part::Box object";
application.closeDocument(document);
return 0;
}
stage = "setting dimensions";
box->Length.setValue(2.0);
box->Width.setValue(3.0);
box->Height.setValue(4.0);
bool hasError = false;
stage = "recomputing document";
recomputeCount = document->recompute({}, false, &hasError);
recomputeHasError = hasError ? 1 : 0;
GProp_GProps properties;
BRepGProp::VolumeProperties(box->Shape.getValue(), properties);
recomputeVolume = properties.Mass();
const bool valid = recomputeCount == 1
&& recomputeHasError == 0
&& box->isValid()
&& std::abs(recomputeVolume - 24.0) < 1e-9;
stage = "closing document";
application.closeDocument(document);
document = nullptr;
if (!valid) {
lastError = "Document recompute contract mismatch";
return 0;
}
return 1;
}
catch (const Base::Exception& error) {
lastError = stage + ": " + error.what();
}
catch (const std::exception& error) {
lastError = stage + ": " + error.what();
}
catch (...) {
lastError = "Unknown Document recompute failure at " + stage;
}
if (document) {
App::GetApplication().closeDocument(document);
}
return 0;
}
EMSCRIPTEN_KEEPALIVE int fc_web_document_invalid_dimension_recovery()
{
App::Document* document = nullptr;
try {
lastError.clear();
invalidDimensionError.clear();
stage = "initializing runtime";
ensureTypesInitialized();
ensurePythonModules();
auto& application = App::GetApplication();
stage = "creating recovery document";
document = application.newDocument("RecoveryDocument", "Recovery Document", {false, true});
auto* box = document
? dynamic_cast<Part::Box*>(document->addObject("Part::Box", "Box"))
: nullptr;
if (!box) {
lastError = "Failed to create recovery Part::Box";
if (document) {
application.closeDocument(document);
}
return 0;
}
box->Length.setValue(2.0);
box->Width.setValue(3.0);
box->Height.setValue(4.0);
bool validHasError = false;
stage = "building valid baseline";
document->recompute({}, false, &validHasError);
GProp_GProps validProperties;
BRepGProp::VolumeProperties(box->Shape.getValue(), validProperties);
stage = "rejecting invalid dimension";
box->Length.setValue(0.0);
bool invalidHasError = false;
document->recompute({}, false, &invalidHasError);
if (const char* error = document->getErrorDescription(box)) {
invalidDimensionError = error;
}
GProp_GProps invalidProperties;
BRepGProp::VolumeProperties(box->Shape.getValue(), invalidProperties);
invalidShapeVolume = invalidProperties.Mass();
stage = "recovering valid dimension";
box->Length.setValue(2.0);
bool recoveredHasErrorFlag = false;
document->recompute({}, false, &recoveredHasErrorFlag);
recoveryHasError = recoveredHasErrorFlag ? 1 : 0;
GProp_GProps recoveredProperties;
BRepGProp::VolumeProperties(box->Shape.getValue(), recoveredProperties);
recoveredShapeVolume = recoveredProperties.Mass();
const bool valid = !validHasError
&& invalidHasError
&& invalidDimensionError == "Length of box too small"
&& std::abs(validProperties.Mass() - 24.0) < 1e-9
&& std::abs(invalidShapeVolume - validProperties.Mass()) < 1e-9
&& !recoveredHasErrorFlag
&& box->isValid()
&& std::abs(recoveredShapeVolume - validProperties.Mass()) < 1e-9;
application.closeDocument(document);
document = nullptr;
if (!valid) {
lastError = "Document invalid-dimension recovery contract mismatch";
return 0;
}
return 1;
}
catch (const Base::Exception& error) {
lastError = stage + ": " + error.what();
}
catch (const std::exception& error) {
lastError = stage + ": " + error.what();
}
catch (...) {
lastError = "Unknown Document recovery failure at " + stage;
}
if (document) {
App::GetApplication().closeDocument(document);
}
return 0;
}
EMSCRIPTEN_KEEPALIVE int fc_web_document_save_fcstd()
{
App::Document* document = nullptr;
try {
lastError.clear();
stage = "initializing save runtime";
ensureTypesInitialized();
ensurePythonModules();
auto& application = App::GetApplication();
stage = "creating save document";
document = application.newDocument("SaveDocument", "Save Document", {false, true});
auto* box = document
? dynamic_cast<Part::Box*>(document->addObject("Part::Box", "Box"))
: nullptr;
if (!box) {
lastError = "Failed to create save Part::Box";
if (document) {
application.closeDocument(document);
}
return 0;
}
box->Length.setValue(2.0);
box->Width.setValue(3.0);
box->Height.setValue(4.0);
bool hasError = false;
stage = "recomputing save document";
document->recompute({}, false, &hasError);
box->ShapeMaterial.setStatus(App::Property::Transient, true);
GProp_GProps properties;
BRepGProp::VolumeProperties(box->Shape.getValue(), properties);
fcstdVolume = properties.Mass();
fcstdPath = "/tmp/WebBox.FCStd";
stage = "saving FCStd";
const bool saved = document->saveAs(fcstdPath.c_str());
Base::FileInfo savedFile(fcstdPath);
fcstdSize = savedFile.size();
const bool valid = saved
&& !hasError
&& box->isValid()
&& std::abs(fcstdVolume - 24.0) < 1e-9
&& savedFile.exists()
&& savedFile.isFile()
&& fcstdSize > 22;
application.closeDocument(document);
document = nullptr;
if (!valid) {
lastError = "FCStd save contract mismatch";
return 0;
}
return 1;
}
catch (const Base::Exception& error) {
lastError = stage + ": " + error.what();
}
catch (const std::exception& error) {
lastError = stage + ": " + error.what();
}
catch (...) {
lastError = "Unknown FCStd save failure at " + stage;
}
if (document) {
App::GetApplication().closeDocument(document);
}
return 0;
}
EMSCRIPTEN_KEEPALIVE int fc_web_document_open_fcstd()
{
App::Document* document = nullptr;
try {
lastError.clear();
stage = "initializing open runtime";
ensureTypesInitialized();
ensurePythonModules();
auto& application = App::GetApplication();
stage = "initializing material manager";
Materials::MaterialManager::getManager();
stage = "creating reopened document";
document = application.newDocument("OpenedDocument", "Opened Document", {false, true});
if (document) {
stage = "restoring FCStd";
document->FileName.setValue(fcstdPath);
document->restore(fcstdPath.c_str(), true, {});
}
if (!document) {
lastError = "Application::newDocument returned null";
return 0;
}
openedDocumentCount = static_cast<int>(application.getDocuments().size());
openedObjectCount = document->countObjects();
auto* object = document->getObject("Box");
auto* box = dynamic_cast<Part::Box*>(object);
if (!box) {
lastError = "Opened document did not contain Part::Box named Box";
application.closeDocument(document);
document = nullptr;
return 0;
}
openedObjectType = object->getTypeId().getName();
openedLength = box->Length.getValue();
openedWidth = box->Width.getValue();
openedHeight = box->Height.getValue();
bool hasError = false;
stage = "recomputing reopened document";
document->recompute({}, false, &hasError);
GProp_GProps properties;
BRepGProp::VolumeProperties(box->Shape.getValue(), properties);
openedVolume = properties.Mass();
const bool valid = openedDocumentCount == 1
&& openedObjectCount == 1
&& openedObjectType == "Part::Box"
&& std::abs(openedLength - 2.0) < 1e-9
&& std::abs(openedWidth - 3.0) < 1e-9
&& std::abs(openedHeight - 4.0) < 1e-9
&& !hasError
&& std::abs(openedVolume - 24.0) < 1e-9;
application.closeDocument(document);
document = nullptr;
if (!valid) {
lastError = "FCStd open contract mismatch";
return 0;
}
return 1;
}
catch (const Base::Exception& error) {
lastError = stage + ": " + error.what();
}
catch (const std::exception& error) {
lastError = stage + ": " + error.what();
}
catch (...) {
lastError = "Unknown FCStd open failure at " + stage;
}
if (document) {
App::GetApplication().closeDocument(document);
}
return 0;
}
EMSCRIPTEN_KEEPALIVE int fc_web_document_commit_resize_transaction()
{
App::Document* document = nullptr;
try {
lastError.clear();
stage = "initializing transaction runtime";
ensureTypesInitialized();
ensurePythonModules();
auto& application = App::GetApplication();
stage = "creating transaction document";
document = application.newDocument("TransactionDocument", "Transaction Document", {false, true});
auto* box = document
? dynamic_cast<Part::Box*>(document->addObject("Part::Box", "Box"))
: nullptr;
if (!box) {
lastError = "Failed to create transaction Part::Box";
if (document) {
application.closeDocument(document);
}
return 0;
}
box->Length.setValue(2.0);
box->Width.setValue(3.0);
box->Height.setValue(4.0);
bool hasError = false;
stage = "recomputing transaction baseline";
document->recompute({}, false, &hasError);
GProp_GProps beforeProperties;
BRepGProp::VolumeProperties(box->Shape.getValue(), beforeProperties);
transactionBeforeVolume = beforeProperties.Mass();
document->setUndoMode(1);
document->clearUndos();
transactionBeforeUndo = document->getAvailableUndos();
stage = "opening resize transaction";
transactionId = document->openTransaction("Resize Box");
if (transactionId == 0) {
lastError = "Document::openTransaction returned zero";
application.closeDocument(document);
return 0;
}
box->Length.setValue(4.0);
transactionPendingBeforeCommit = document->hasPendingTransaction() ? 1 : 0;
stage = "recomputing transaction result";
document->recompute({}, false, &hasError);
GProp_GProps afterProperties;
BRepGProp::VolumeProperties(box->Shape.getValue(), afterProperties);
transactionAfterVolume = afterProperties.Mass();
stage = "committing resize transaction";
document->commitTransaction();
transactionPendingAfterCommit = document->hasPendingTransaction() ? 1 : 0;
transactionAfterUndo = document->getAvailableUndos();
stage = "undoing resize transaction";
transactionUndoResult = document->undo() ? 1 : 0;
document->recompute({}, false, &hasError);
GProp_GProps undoProperties;
BRepGProp::VolumeProperties(box->Shape.getValue(), undoProperties);
transactionUndoVolume = undoProperties.Mass();
transactionAfterUndoCount = document->getAvailableRedos();
stage = "redoing resize transaction";
transactionRedoResult = document->redo() ? 1 : 0;
document->recompute({}, false, &hasError);
GProp_GProps redoProperties;
BRepGProp::VolumeProperties(box->Shape.getValue(), redoProperties);
transactionRedoVolume = redoProperties.Mass();
stage = "aborting interrupted transaction";
document->openTransaction("Interrupted Resize");
box->Length.setValue(5.0);
document->abortTransaction();
transactionAbortPending = document->hasPendingTransaction() ? 1 : 0;
document->recompute({}, false, &hasError);
GProp_GProps abortProperties;
BRepGProp::VolumeProperties(box->Shape.getValue(), abortProperties);
transactionAbortVolume = abortProperties.Mass();
const bool valid = !hasError
&& std::abs(transactionBeforeVolume - 24.0) < 1e-9
&& std::abs(transactionAfterVolume - 48.0) < 1e-9
&& transactionUndoResult == 1
&& std::abs(transactionUndoVolume - 24.0) < 1e-9
&& transactionAfterUndoCount > 0
&& transactionRedoResult == 1
&& std::abs(transactionRedoVolume - 48.0) < 1e-9
&& transactionAbortPending == 0
&& std::abs(transactionAbortVolume - 48.0) < 1e-9
&& transactionPendingBeforeCommit == 1
&& transactionPendingAfterCommit == 0
&& transactionAfterUndo > transactionBeforeUndo;
application.closeDocument(document);
document = nullptr;
if (!valid) {
lastError = "Document transaction commit contract mismatch";
return 0;
}
return 1;
}
catch (const Base::Exception& error) {
lastError = stage + ": " + error.what();
}
catch (const std::exception& error) {
lastError = stage + ": " + error.what();
}
catch (...) {
lastError = "Unknown Document transaction failure at " + stage;
}
if (document) {
App::GetApplication().closeDocument(document);
}
return 0;
}
EMSCRIPTEN_KEEPALIVE const char* fc_web_document_last_error()
{
return lastError.c_str();
}
EMSCRIPTEN_KEEPALIVE const char* fc_web_document_name()
{
return documentName.c_str();
}
EMSCRIPTEN_KEEPALIVE const char* fc_web_document_object_name()
{
return objectName.c_str();
}
EMSCRIPTEN_KEEPALIVE const char* fc_web_document_object_type()
{
return objectType.c_str();
}
EMSCRIPTEN_KEEPALIVE int fc_web_document_count()
{
return documentCount;
}
EMSCRIPTEN_KEEPALIVE int fc_web_document_object_count()
{
return objectCount;
}
EMSCRIPTEN_KEEPALIVE int fc_web_document_recompute_count()
{
return recomputeCount;
}
EMSCRIPTEN_KEEPALIVE double fc_web_document_recompute_volume()
{
return recomputeVolume;
}
EMSCRIPTEN_KEEPALIVE int fc_web_document_recompute_has_error()
{
return recomputeHasError;
}
EMSCRIPTEN_KEEPALIVE const char* fc_web_document_invalid_dimension_error()
{
return invalidDimensionError.c_str();
}
EMSCRIPTEN_KEEPALIVE double fc_web_document_invalid_shape_volume()
{
return invalidShapeVolume;
}
EMSCRIPTEN_KEEPALIVE double fc_web_document_recovered_shape_volume()
{
return recoveredShapeVolume;
}
EMSCRIPTEN_KEEPALIVE int fc_web_document_recovery_has_error()
{
return recoveryHasError;
}
EMSCRIPTEN_KEEPALIVE const char* fc_web_document_fcstd_path()
{
return fcstdPath.c_str();
}
EMSCRIPTEN_KEEPALIVE unsigned int fc_web_document_fcstd_size()
{
return fcstdSize;
}
EMSCRIPTEN_KEEPALIVE double fc_web_document_fcstd_volume()
{
return fcstdVolume;
}
EMSCRIPTEN_KEEPALIVE int fc_web_document_opened_document_count()
{
return openedDocumentCount;
}
EMSCRIPTEN_KEEPALIVE int fc_web_document_opened_object_count()
{
return openedObjectCount;
}
EMSCRIPTEN_KEEPALIVE const char* fc_web_document_opened_object_type()
{
return openedObjectType.c_str();
}
EMSCRIPTEN_KEEPALIVE double fc_web_document_opened_length()
{
return openedLength;
}
EMSCRIPTEN_KEEPALIVE double fc_web_document_opened_width()
{
return openedWidth;
}
EMSCRIPTEN_KEEPALIVE double fc_web_document_opened_height()
{
return openedHeight;
}
EMSCRIPTEN_KEEPALIVE double fc_web_document_opened_volume()
{
return openedVolume;
}
EMSCRIPTEN_KEEPALIVE int fc_web_document_transaction_id()
{
return transactionId;
}
EMSCRIPTEN_KEEPALIVE int fc_web_document_transaction_before_undo()
{
return transactionBeforeUndo;
}
EMSCRIPTEN_KEEPALIVE int fc_web_document_transaction_after_undo()
{
return transactionAfterUndo;
}
EMSCRIPTEN_KEEPALIVE int fc_web_document_transaction_pending_before_commit()
{
return transactionPendingBeforeCommit;
}
EMSCRIPTEN_KEEPALIVE int fc_web_document_transaction_pending_after_commit()
{
return transactionPendingAfterCommit;
}
EMSCRIPTEN_KEEPALIVE double fc_web_document_transaction_before_volume()
{
return transactionBeforeVolume;
}
EMSCRIPTEN_KEEPALIVE double fc_web_document_transaction_after_volume()
{
return transactionAfterVolume;
}
EMSCRIPTEN_KEEPALIVE int fc_web_document_transaction_undo_result()
{
return transactionUndoResult;
}
EMSCRIPTEN_KEEPALIVE int fc_web_document_transaction_after_undo_count()
{
return transactionAfterUndoCount;
}
EMSCRIPTEN_KEEPALIVE double fc_web_document_transaction_undo_volume()
{
return transactionUndoVolume;
}
EMSCRIPTEN_KEEPALIVE int fc_web_document_transaction_redo_result()
{
return transactionRedoResult;
}
EMSCRIPTEN_KEEPALIVE double fc_web_document_transaction_redo_volume()
{
return transactionRedoVolume;
}
EMSCRIPTEN_KEEPALIVE int fc_web_document_transaction_abort_pending()
{
return transactionAbortPending;
}
EMSCRIPTEN_KEEPALIVE double fc_web_document_transaction_abort_volume()
{
return transactionAbortVolume;
}
}

View File

@@ -0,0 +1,196 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
#include <App/Application.h>
#include <App/DocumentObject.h>
#include <Base/Type.h>
#include <Base/Exception.h>
#include <Mod/Material/App/Materials.h>
#include <Mod/Material/App/PropertyMaterial.h>
#include <Mod/Part/App/AttachExtension.h>
#include <Mod/Part/App/FeaturePartBox.h>
#include <Mod/Part/App/PartFeature.h>
#include <Mod/Part/App/PrimitiveFeature.h>
#include <Mod/Part/App/PropertyTopoShape.h>
#include <Mod/Part/App/TopoShape.h>
#include <emscripten/emscripten.h>
#include <cstddef>
#include <string>
#include <vector>
namespace {
std::string lastErrorCode;
std::string lastErrorMessage;
std::string lastTypeName;
unsigned int initializationCalls = 0;
unsigned int initializationRuns = 0;
bool typesInitialized = false;
std::vector<App::DocumentObject*> handles;
void setError(const char* code, const std::string& message)
{
lastErrorCode = code;
lastErrorMessage = message;
}
void clearError()
{
lastErrorCode.clear();
lastErrorMessage.clear();
}
bool ensurePartTypes()
{
++initializationCalls;
if (typesInitialized) {
clearError();
return true;
}
++initializationRuns;
try {
App::Application::initWebCore();
Materials::PropertyMaterial::init();
Part::TopoShape::init();
Part::PropertyPartShape::init();
Part::AttachExtension::init();
Part::Feature::init();
Part::Primitive::init();
Part::Box::init();
typesInitialized = true;
clearError();
return true;
}
catch (const Base::Exception& error) {
setError("initialization_failed", error.what());
return false;
}
catch (const std::exception& error) {
setError("initialization_failed", error.what());
return false;
}
catch (...) {
setError("initialization_failed", "unknown module initialization failure");
return false;
}
}
bool requirePartModule(const char* moduleName)
{
if (moduleName == nullptr || *moduleName == '\0') {
setError("invalid_argument", "module name is empty");
return false;
}
if (std::string(moduleName) != "Part") {
setError(
std::string(moduleName) == "PartGui" ? "gui_dependency_unavailable" : "module_unavailable",
"module is not available in the GUI-free Web kernel: " + std::string(moduleName));
return false;
}
return ensurePartTypes();
}
}
extern "C" {
EMSCRIPTEN_KEEPALIVE int fc_web_module_loader_initialize(const char* moduleName)
{
return requirePartModule(moduleName) ? 1 : 0;
}
EMSCRIPTEN_KEEPALIVE int fc_web_module_loader_type_probe(const char* typeName)
{
if (!requirePartModule("Part")) {
return 0;
}
if (typeName == nullptr || *typeName == '\0') {
setError("invalid_argument", "type name is empty");
return 0;
}
const Base::Type type = Base::Type::fromName(typeName);
if (type.isBad()) {
lastTypeName.clear();
setError("type_not_found", "type is not registered: " + std::string(typeName));
return 0;
}
lastTypeName = type.getName();
clearError();
return 1;
}
EMSCRIPTEN_KEEPALIVE int fc_web_module_loader_create_handle(const char* typeName)
{
if (!fc_web_module_loader_type_probe(typeName)) {
return 0;
}
const Base::Type type = Base::Type::fromName(typeName);
void* instance = type.createInstance();
auto* object = static_cast<App::DocumentObject*>(instance);
if (object == nullptr) {
setError("type_not_instantiable", "type cannot create a DocumentObject: " + std::string(typeName));
return 0;
}
handles.push_back(object);
clearError();
return static_cast<int>(handles.size());
}
EMSCRIPTEN_KEEPALIVE int fc_web_module_loader_release_handle(int handle)
{
if (handle <= 0 || static_cast<std::size_t>(handle) > handles.size() || handles[handle - 1] == nullptr) {
setError("invalid_handle", "handle is unknown or already released");
return 0;
}
delete handles[handle - 1];
handles[handle - 1] = nullptr;
clearError();
return 1;
}
EMSCRIPTEN_KEEPALIVE int fc_web_module_loader_active_handles()
{
int active = 0;
for (const auto* handle : handles) {
if (handle != nullptr) {
++active;
}
}
return active;
}
EMSCRIPTEN_KEEPALIVE const char* fc_web_module_loader_error_code()
{
return lastErrorCode.c_str();
}
EMSCRIPTEN_KEEPALIVE const char* fc_web_module_loader_error_message()
{
return lastErrorMessage.c_str();
}
EMSCRIPTEN_KEEPALIVE const char* fc_web_module_loader_last_type()
{
return lastTypeName.c_str();
}
EMSCRIPTEN_KEEPALIVE unsigned int fc_web_module_loader_initialization_calls()
{
return initializationCalls;
}
EMSCRIPTEN_KEEPALIVE unsigned int fc_web_module_loader_initialization_runs()
{
return initializationRuns;
}
EMSCRIPTEN_KEEPALIVE int fc_web_module_loader_initialized()
{
return typesInitialized ? 1 : 0;
}
}

View File

@@ -0,0 +1,214 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
#include <BRepGProp.hxx>
#include <GProp_GProps.hxx>
#include <Standard_Failure.hxx>
#include <App/DocumentObject.h>
#include <App/Application.h>
#include <Base/Exception.h>
#include <Mod/Material/App/PropertyMaterial.h>
#include <Mod/Material/App/Materials.h>
#include <Mod/Part/App/AttachExtension.h>
#include <Mod/Part/App/FeaturePartBox.h>
#include <Mod/Part/App/PartFeature.h>
#include <Mod/Part/App/PrimitiveFeature.h>
#include <Mod/Part/App/PropertyTopoShape.h>
#include <Mod/Part/App/TopoShape.h>
#include <cmath>
#include <string>
#include <emscripten/emscripten.h>
namespace {
std::string lastError;
unsigned int initializationCalls = 0;
unsigned int initializationRuns = 0;
bool typesInitialized = false;
void ensureTypesInitialized()
{
++initializationCalls;
if (typesInitialized) {
return;
}
++initializationRuns;
App::Application::initWebCore();
lastError = "registering Materials::PropertyMaterial";
Materials::PropertyMaterial::init();
lastError = "registering Part::TopoShape";
Part::TopoShape::init();
lastError = "registering Part::PropertyPartShape";
Part::PropertyPartShape::init();
lastError = "registering Part::AttachExtension";
Part::AttachExtension::init();
lastError = "registering Part::Feature";
Part::Feature::init();
lastError = "registering Part::Primitive";
Part::Primitive::init();
lastError = "registering Part::Box";
Part::Box::init();
typesInitialized = true;
}
double volumeOf(const Part::Box& box)
{
GProp_GProps properties;
BRepGProp::VolumeProperties(box.Shape.getValue(), properties);
return properties.Mass();
}
bool executeBox(Part::Box& box)
{
App::DocumentObjectExecReturn* result = box.execute();
if (result == App::DocumentObject::StdReturn) {
lastError.clear();
return true;
}
lastError = result != nullptr ? result->Why : "Unknown Part::Box execution failure";
delete result;
return false;
}
}
extern "C" {
EMSCRIPTEN_KEEPALIVE int fc_web_part_box_constructor_probe()
{
try {
lastError = "initializing FreeCAD 1.2 types";
ensureTypesInitialized();
lastError = "constructing Part::PropertyPartShape";
Part::PropertyPartShape shape;
lastError = "constructing Materials::PropertyMaterial";
Materials::PropertyMaterial propertyMaterial;
lastError = "constructing Web default Materials::Material";
Materials::Material material;
if (material.getMaterialAppearance().getType() != App::Material::DEFAULT) {
lastError += ": default appearance fallback mismatch";
return 0;
}
lastError = "constructing Part::Feature";
Part::Feature feature;
lastError = "constructing Part::Box";
Part::Box box;
lastError.clear();
return 1;
}
catch (const std::exception& error) {
lastError += ": " + std::string(error.what());
return 0;
}
catch (...) {
lastError = "Unknown constructor probe failure during " + lastError;
return 0;
}
}
EMSCRIPTEN_KEEPALIVE double fc_web_part_box_volume(double length, double width, double height)
{
try {
lastError = "initializing FreeCAD 1.2 types";
ensureTypesInitialized();
lastError = "constructing Part::Box";
Part::Box box;
lastError = "setting Part::Box dimensions";
box.Length.setValue(length);
box.Width.setValue(width);
box.Height.setValue(height);
if (!executeBox(box)) {
return -1.0;
}
return volumeOf(box);
}
catch (const Base::Exception& error) {
lastError += ": " + std::string(error.what());
return -1.0;
}
catch (const Standard_Failure& error) {
lastError = error.GetMessageString();
return -1.0;
}
catch (const std::exception& error) {
lastError += ": " + std::string(error.what());
return -1.0;
}
catch (...) {
lastError = "Unknown Part::Box probe failure during " + lastError;
return -1.0;
}
}
EMSCRIPTEN_KEEPALIVE int fc_web_part_box_recovery_probe()
{
try {
lastError = "initializing FreeCAD 1.2 types";
ensureTypesInitialized();
lastError = "constructing Part::Box";
Part::Box box;
box.Length.setValue(2.0);
box.Width.setValue(3.0);
box.Height.setValue(4.0);
if (!executeBox(box)) {
return 0;
}
const double initialVolume = volumeOf(box);
box.Length.setValue(0.0);
const bool invalidRejected = !executeBox(box) && lastError == "Length of box too small";
box.Length.setValue(2.0);
if (!executeBox(box)) {
return 0;
}
const double restoredVolume = volumeOf(box);
return invalidRejected && std::abs(initialVolume - 24.0) < 1e-9
&& std::abs(restoredVolume - initialVolume) < 1e-9;
}
catch (const Base::Exception& error) {
lastError = error.what();
return 0;
}
catch (const Standard_Failure& error) {
lastError = error.GetMessageString();
return 0;
}
catch (const std::exception& error) {
lastError = error.what();
return 0;
}
catch (...) {
lastError = "Unknown Part::Box recovery failure during " + lastError;
return 0;
}
}
EMSCRIPTEN_KEEPALIVE const char* fc_web_part_box_last_error()
{
return lastError.c_str();
}
EMSCRIPTEN_KEEPALIVE unsigned int fc_web_part_box_initialization_calls()
{
return initializationCalls;
}
EMSCRIPTEN_KEEPALIVE unsigned int fc_web_part_box_initialization_runs()
{
return initializationRuns;
}
EMSCRIPTEN_KEEPALIVE int fc_web_part_box_types_initialized()
{
return typesInitialized ? 1 : 0;
}
}

View File

@@ -0,0 +1,291 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
#include <App/Application.h>
#include <App/Document.h>
#include <Base/Exception.h>
#include <BRepGProp.hxx>
#include <GProp_GProps.hxx>
#include <Mod/Part/App/FeaturePartBox.h>
#include <Python.h>
#include <emscripten/emscripten.h>
#include <string>
#include <cmath>
extern "C" PyObject* PyInit_Materials();
extern "C" PyObject* PyInit_Part();
extern "C" PyObject* PyInit_FreeCADWebFacade();
extern "C" PyObject* PyInit_FreeCADWebWorkbench();
namespace {
std::string lastError;
std::string lastResult;
int initializationCount = 0;
bool facadeRegistered = false;
bool workbenchRegistered = false;
void addPythonModule(const char* name, PyObject* (*initialize)())
{
auto* modules = PyImport_GetModuleDict();
if (PyDict_GetItemString(modules, name)) {
return;
}
PyObject* module = initialize();
if (!module) {
throw Base::RuntimeError(std::string("PyInit_") + name + " returned null");
}
PyDict_SetItemString(modules, name, module);
Py_DECREF(module);
}
void ensureRuntime()
{
const bool wasInitialized = Py_IsInitialized();
if (!wasInitialized && !facadeRegistered) {
if (PyImport_AppendInittab("FreeCADWebFacade", &PyInit_FreeCADWebFacade) != 0) {
throw Base::RuntimeError("Failed to register FreeCADWebFacade builtin module");
}
facadeRegistered = true;
}
if (!wasInitialized && !workbenchRegistered) {
if (PyImport_AppendInittab("FreeCADWebWorkbench", &PyInit_FreeCADWebWorkbench) != 0) {
throw Base::RuntimeError("Failed to register FreeCADWebWorkbench builtin module");
}
workbenchRegistered = true;
}
App::Application::initWebCore();
if (!wasInitialized && Py_IsInitialized()) {
++initializationCount;
}
}
PyObject* createBox(PyObject*, PyObject* args)
{
double length = 0.0;
double width = 0.0;
double height = 0.0;
if (!PyArg_ParseTuple(args, "ddd", &length, &width, &height)) {
return nullptr;
}
if (length <= 0.0 || width <= 0.0 || height <= 0.0) {
PyErr_SetString(PyExc_ValueError, "box dimensions must be positive");
return nullptr;
}
App::Document* document = nullptr;
try {
addPythonModule("Materials", PyInit_Materials);
addPythonModule("Part", PyInit_Part);
auto& application = App::GetApplication();
document = application.newDocument("FacadeDocument", "Facade Document", {false, true});
auto* box = document
? dynamic_cast<Part::Box*>(document->addObject("Part::Box", "Box"))
: nullptr;
if (!box) {
throw Base::RuntimeError("Failed to create Part::Box through facade");
}
box->Length.setValue(length);
box->Width.setValue(width);
box->Height.setValue(height);
bool hasError = false;
const int recompute = document->recompute({}, false, &hasError);
GProp_GProps properties;
BRepGProp::VolumeProperties(box->Shape.getValue(), properties);
const std::string documentName = document->getName();
const std::string objectName = document->getObjectName(box);
const double volume = std::round(properties.Mass() * 1e9) / 1e9;
PyObject* result = Py_BuildValue(
"{s:s,s:s,s:s,s:d,s:d,s:d,s:d,s:i,s:i}",
"document", documentName.c_str(),
"object", objectName.c_str(),
"type", box->getTypeId().getName(),
"length", length,
"width", width,
"height", height,
"volume", volume,
"recompute", recompute,
"hasError", hasError ? 1 : 0
);
application.closeDocument(document);
return result;
}
catch (const Base::Exception& error) {
if (document) {
App::GetApplication().closeDocument(document);
}
PyErr_SetString(PyExc_RuntimeError, error.what());
return nullptr;
}
catch (const std::exception& error) {
if (document) {
App::GetApplication().closeDocument(document);
}
PyErr_SetString(PyExc_RuntimeError, error.what());
return nullptr;
}
}
PyMethodDef facadeMethods[] = {
{"create_box", createBox, METH_VARARGS, "Create, inspect, and close one Part::Box."},
{nullptr, nullptr, 0, nullptr},
};
PyModuleDef facadeModule = {
PyModuleDef_HEAD_INIT,
"FreeCADWebFacade",
"Typed value-only facade for the FreeCAD Web worker.",
-1,
facadeMethods,
};
PyObject* workbenchName(PyObject*, PyObject*)
{
return PyUnicode_FromString("FreeCAD Web Part");
}
PyObject* workbenchCommands(PyObject*, PyObject*)
{
return Py_BuildValue("[s]", "box");
}
PyObject* workbenchRunBox(PyObject*, PyObject* args)
{
PyObject* facade = PyImport_ImportModule("FreeCADWebFacade");
if (!facade) {
return nullptr;
}
PyObject* function = PyObject_GetAttrString(facade, "create_box");
Py_DECREF(facade);
if (!function) {
return nullptr;
}
PyObject* result = PyObject_CallObject(function, args);
Py_DECREF(function);
return result;
}
PyMethodDef workbenchMethods[] = {
{"name", workbenchName, METH_NOARGS, "Return the statically registered workbench name."},
{"commands", workbenchCommands, METH_NOARGS, "Return statically registered command ids."},
{"run_box", workbenchRunBox, METH_VARARGS, "Run the box command through the typed facade."},
{nullptr, nullptr, 0, nullptr},
};
PyModuleDef workbenchModule = {
PyModuleDef_HEAD_INIT,
"FreeCADWebWorkbench",
"Statically registered Web workbench sample.",
-1,
workbenchMethods,
};
std::string pythonError()
{
PyObject* type = nullptr;
PyObject* value = nullptr;
PyObject* traceback = nullptr;
PyErr_Fetch(&type, &value, &traceback);
PyErr_NormalizeException(&type, &value, &traceback);
std::string message = "PythonError";
if (type) {
PyObject* name = PyObject_GetAttrString(type, "__name__");
if (name) {
message = PyUnicode_AsUTF8(name);
Py_DECREF(name);
}
}
if (value) {
PyObject* text = PyObject_Str(value);
if (text) {
message += ": ";
message += PyUnicode_AsUTF8(text);
Py_DECREF(text);
}
}
Py_XDECREF(type);
Py_XDECREF(value);
Py_XDECREF(traceback);
return message;
}
} // namespace
extern "C" PyObject* PyInit_FreeCADWebFacade()
{
return PyModule_Create(&facadeModule);
}
extern "C" PyObject* PyInit_FreeCADWebWorkbench()
{
return PyModule_Create(&workbenchModule);
}
extern "C" {
EMSCRIPTEN_KEEPALIVE int fc_web_python_runtime_start()
{
try {
lastError.clear();
ensureRuntime();
return Py_IsInitialized() && initializationCount == 1 ? 1 : 0;
}
catch (const Base::Exception& error) {
lastError = error.what();
return 0;
}
catch (const std::exception& error) {
lastError = error.what();
return 0;
}
}
EMSCRIPTEN_KEEPALIVE int fc_web_python_runtime_eval(const char* expression)
{
try {
lastError.clear();
lastResult.clear();
ensureRuntime();
PyObject* globals = PyDict_New();
PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins());
PyObject* result = PyRun_String(expression ? expression : "", Py_eval_input, globals, globals);
if (!result) {
lastError = pythonError();
Py_DECREF(globals);
return 0;
}
PyObject* text = PyObject_Str(result);
if (!text) {
lastError = pythonError();
Py_DECREF(result);
Py_DECREF(globals);
return 0;
}
lastResult = PyUnicode_AsUTF8(text);
Py_DECREF(text);
Py_DECREF(result);
Py_DECREF(globals);
return 1;
}
catch (const std::exception& error) {
lastError = error.what();
return 0;
}
}
EMSCRIPTEN_KEEPALIVE int fc_web_python_runtime_initialization_count()
{
return initializationCount;
}
EMSCRIPTEN_KEEPALIVE const char* fc_web_python_runtime_result()
{
return lastResult.c_str();
}
EMSCRIPTEN_KEEPALIVE const char* fc_web_python_runtime_error()
{
return lastError.c_str();
}
} // extern "C"

View File

@@ -0,0 +1,264 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
#include <App/Application.h>
#include <App/Document.h>
#include <Base/Exception.h>
#include <Base/Type.h>
#include <Base/Vector3D.h>
#include <Mod/Part/App/Geometry.h>
#include <Mod/Sketcher/App/Constraint.h>
#include <Mod/Sketcher/App/SketchObject.h>
#include <emscripten/emscripten.h>
#include <cmath>
#include <string>
extern "C" PyObject* PyInit_Materials();
extern "C" PyObject* PyInit_Part();
extern "C" PyObject* PyInit_Sketcher();
namespace {
std::string lastError;
std::string stage;
std::string objectType;
std::string invalidConstraintError;
int sketcherInitializationCount = 0;
int geometryCount = 0;
int recomputeCount = 0;
int recomputeHasError = 0;
int constraintCount = 0;
int solverStatus = 0;
int solverDoF = 0;
double startX = 0.0;
double startY = 0.0;
double endX = 0.0;
double endY = 0.0;
void addPythonModule(const char* name, PyObject* (*initialize)())
{
auto* modules = PyImport_GetModuleDict();
if (PyDict_GetItemString(modules, name)) {
return;
}
PyObject* module = initialize();
if (!module) {
throw Base::RuntimeError(std::string("PyInit_") + name + " returned null");
}
PyDict_SetItemString(modules, name, module);
Py_DECREF(module);
}
void ensureSketcherInitialized()
{
App::Application::initWebCore();
addPythonModule("Materials", PyInit_Materials);
addPythonModule("Part", PyInit_Part);
auto* modules = PyImport_GetModuleDict();
if (!PyDict_GetItemString(modules, "Sketcher")) {
addPythonModule("Sketcher", PyInit_Sketcher);
++sketcherInitializationCount;
}
}
Sketcher::SketchObject* createSketch(App::Document*& document, const char* documentName)
{
auto& application = App::GetApplication();
document = application.newDocument(documentName, documentName, {false, true});
if (!document) {
throw Base::RuntimeError("Application::newDocument returned null");
}
auto* object = document->addObject("Sketcher::SketchObject", "Sketch");
auto* sketch = dynamic_cast<Sketcher::SketchObject*>(object);
if (!sketch) {
throw Base::RuntimeError("Document::addObject returned a non-SketchObject");
}
objectType = sketch->getTypeId().getName();
return sketch;
}
void addFixedLine(Sketcher::SketchObject& sketch)
{
Part::GeomLineSegment line;
line.setPoints(Base::Vector3d(0.0, 0.0, 0.0), Base::Vector3d(4.0, 0.0, 0.0));
if (sketch.addGeometry(&line) != 0) {
throw Base::RuntimeError("SketchObject::addGeometry returned an unexpected index");
}
}
template<typename Function>
int runWithDocument(const char* operation, Function&& function)
{
App::Document* document = nullptr;
try {
lastError.clear();
stage = "initializing Sketcher";
ensureSketcherInitialized();
stage = operation;
const bool valid = function(document);
if (document) {
App::GetApplication().closeDocument(document);
}
if (!valid) {
lastError = std::string(operation) + " contract mismatch";
return 0;
}
return 1;
}
catch (const Base::Exception& error) {
lastError = stage + ": " + error.what();
}
catch (const std::exception& error) {
lastError = stage + ": " + error.what();
}
catch (...) {
lastError = "Unknown Sketcher failure at " + stage;
}
if (document) {
App::GetApplication().closeDocument(document);
}
return 0;
}
} // namespace
extern "C" {
EMSCRIPTEN_KEEPALIVE int fc_web_sketcher_type_probe()
{
return runWithDocument("creating Sketcher type probe", [](App::Document*& document) {
ensureSketcherInitialized();
auto type = Base::Type::fromName("Sketcher::SketchObject");
auto* sketch = createSketch(document, "SketcherTypeDocument");
return !type.isBad() && type.canInstantiate() && sketcherInitializationCount == 1
&& objectType == "Sketcher::SketchObject" && document->countObjects() == 1;
});
}
EMSCRIPTEN_KEEPALIVE int fc_web_sketcher_geometry_probe()
{
return runWithDocument("creating fixed Sketcher geometry", [](App::Document*& document) {
auto* sketch = createSketch(document, "SketcherGeometryDocument");
addFixedLine(*sketch);
bool hasError = false;
recomputeCount = document->recompute({}, false, &hasError);
recomputeHasError = hasError ? 1 : 0;
geometryCount = static_cast<int>(sketch->Geometry.getSize());
const auto* line = dynamic_cast<const Part::GeomLineSegment*>(sketch->getGeometry(0));
if (!line) {
throw Base::RuntimeError("Sketch geometry is not a line segment");
}
const auto start = line->getStartPoint();
const auto end = line->getEndPoint();
startX = start.x;
startY = start.y;
endX = end.x;
endY = end.y;
return geometryCount == 1 && recomputeCount == 1 && !hasError && sketch->isValid()
&& std::abs(startX) < 1e-12 && std::abs(startY) < 1e-12
&& std::abs(endX - 4.0) < 1e-12 && std::abs(endY) < 1e-12;
});
}
EMSCRIPTEN_KEEPALIVE int fc_web_sketcher_constraint_probe()
{
return runWithDocument("adding horizontal Sketcher constraint", [](App::Document*& document) {
auto* sketch = createSketch(document, "SketcherConstraintDocument");
addFixedLine(*sketch);
auto constraint = std::make_unique<Sketcher::Constraint>();
constraint->Type = Sketcher::ConstraintType::Horizontal;
constraint->First = 0;
const int constraintIndex = sketch->addConstraint(std::move(constraint));
bool hasError = false;
document->recompute({}, false, &hasError);
geometryCount = static_cast<int>(sketch->Geometry.getSize());
constraintCount = static_cast<int>(sketch->Constraints.getSize());
solverStatus = sketch->getLastSolverStatus();
solverDoF = sketch->getLastDoF();
invalidConstraintError.clear();
constexpr int invalidGeometryIndex = 99;
if (invalidGeometryIndex < 0 || invalidGeometryIndex >= geometryCount) {
invalidConstraintError = "Sketcher constraint geometry index out of range";
}
return constraintIndex == 0 && geometryCount == 1 && constraintCount == 1
&& !hasError && sketch->isValid() && solverStatus == 0 && solverDoF == 3
&& invalidConstraintError == "Sketcher constraint geometry index out of range";
});
}
EMSCRIPTEN_KEEPALIVE const char* fc_web_sketcher_last_error()
{
return lastError.c_str();
}
EMSCRIPTEN_KEEPALIVE const char* fc_web_sketcher_object_type()
{
return objectType.c_str();
}
EMSCRIPTEN_KEEPALIVE int fc_web_sketcher_initialization_count()
{
return sketcherInitializationCount;
}
EMSCRIPTEN_KEEPALIVE int fc_web_sketcher_geometry_count()
{
return geometryCount;
}
EMSCRIPTEN_KEEPALIVE int fc_web_sketcher_recompute_count()
{
return recomputeCount;
}
EMSCRIPTEN_KEEPALIVE int fc_web_sketcher_recompute_has_error()
{
return recomputeHasError;
}
EMSCRIPTEN_KEEPALIVE double fc_web_sketcher_start_x()
{
return startX;
}
EMSCRIPTEN_KEEPALIVE double fc_web_sketcher_start_y()
{
return startY;
}
EMSCRIPTEN_KEEPALIVE double fc_web_sketcher_end_x()
{
return endX;
}
EMSCRIPTEN_KEEPALIVE double fc_web_sketcher_end_y()
{
return endY;
}
EMSCRIPTEN_KEEPALIVE int fc_web_sketcher_constraint_count()
{
return constraintCount;
}
EMSCRIPTEN_KEEPALIVE int fc_web_sketcher_solver_status()
{
return solverStatus;
}
EMSCRIPTEN_KEEPALIVE int fc_web_sketcher_solver_dof()
{
return solverDoF;
}
EMSCRIPTEN_KEEPALIVE const char* fc_web_sketcher_invalid_constraint_error()
{
return invalidConstraintError.c_str();
}
} // extern "C"

View File

@@ -0,0 +1,171 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
const fs = require("fs");
const path = require("path");
const { pathToFileURL } = require("url");
const crypto = require("crypto");
const buildDirectory = path.resolve(process.argv[2] || "build-web/assembly-configure/bin");
async function main()
{
globalThis.__dirname = `${buildDirectory}${path.sep}`;
globalThis.require = require;
const moduleUrl = pathToFileURL(path.join(buildDirectory, "FreeCADWebAssemblyKernelProbe.js")).href;
const module = await import(moduleUrl);
const probe = await module.default({
wasmBinary: fs.readFileSync(path.join(buildDirectory, "FreeCADWebAssemblyKernelProbe.wasm")),
});
const call = (name, returnType = "number") => probe.ccall(name, returnType);
const result = {
run: call("fc_web_assembly_kernel_create_recompute"),
error: call("fc_web_assembly_kernel_error", "string"),
document: {
name: call("fc_web_assembly_kernel_document_name", "string"),
countBeforeClose: call("fc_web_assembly_kernel_document_count_before_close"),
countAfterClose: call("fc_web_assembly_kernel_document_count_after_close"),
},
object: {
name: call("fc_web_assembly_kernel_object_name", "string"),
type: call("fc_web_assembly_kernel_object_type", "string"),
count: call("fc_web_assembly_kernel_object_count"),
components: call("fc_web_assembly_kernel_component_count"),
},
recompute: {
count: call("fc_web_assembly_kernel_recompute_count"),
hasError: call("fc_web_assembly_kernel_recompute_has_error"),
solverStatus: call("fc_web_assembly_kernel_solver_status"),
dof: call("fc_web_assembly_kernel_dof"),
},
};
const valid = result.run === 1
&& result.error === ""
&& result.document.name === "AssemblyKernel"
&& result.document.countBeforeClose === 1
&& result.document.countAfterClose === 0
&& result.object.name === "Assembly"
&& result.object.type === "Assembly::AssemblyObject"
&& result.object.count === 9
&& result.object.components === 0
&& result.recompute.count === 9
&& result.recompute.hasError === 0
&& result.recompute.solverStatus === 0
&& result.recompute.dof === 0;
if (!valid) {
throw new Error(JSON.stringify(result));
}
console.log(JSON.stringify(result));
}
async function recovery()
{
globalThis.__dirname = `${buildDirectory}${path.sep}`;
globalThis.require = require;
const moduleUrl = pathToFileURL(path.join(buildDirectory, "FreeCADWebAssemblyKernelProbe.js")).href;
const module = await import(moduleUrl);
const probe = await module.default({
wasmBinary: fs.readFileSync(path.join(buildDirectory, "FreeCADWebAssemblyKernelProbe.wasm")),
});
const call = (name, returnType = "number") => probe.ccall(name, returnType);
const sha256 = (value) => crypto.createHash("sha256").update(value).digest("hex");
const result = {
run: call("fc_web_assembly_kernel_recovery_probe"),
error: call("fc_web_assembly_kernel_error", "string"),
invalid: {
return: call("fc_web_assembly_kernel_recovery_invalid_return"),
code: call("fc_web_assembly_kernel_recovery_invalid_code", "string"),
message: call("fc_web_assembly_kernel_recovery_invalid_message", "string"),
},
state: {
before: call("fc_web_assembly_kernel_recovery_state_before", "string"),
after: call("fc_web_assembly_kernel_recovery_state_after", "string"),
afterReplay: call("fc_web_assembly_kernel_recovery_state_after_replay", "string"),
beforeSha256: "",
afterSha256: "",
afterReplaySha256: "",
},
replayEqual: call("fc_web_assembly_kernel_recovery_replay_equal"),
};
result.state.beforeSha256 = sha256(result.state.before);
result.state.afterSha256 = sha256(result.state.after);
result.state.afterReplaySha256 = sha256(result.state.afterReplay);
const valid = result.run === 1
&& result.error === ""
&& result.invalid.return === 0
&& result.invalid.code === "invalid_type"
&& result.state.before === result.state.after
&& result.state.after === result.state.afterReplay
&& result.state.beforeSha256 === result.state.afterSha256
&& result.state.afterSha256 === result.state.afterReplaySha256
&& result.replayEqual === 1;
if (!valid) {
throw new Error(JSON.stringify(result));
}
console.log(JSON.stringify(result));
}
async function persistence()
{
globalThis.__dirname = `${buildDirectory}${path.sep}`;
globalThis.require = require;
const moduleUrl = pathToFileURL(path.join(buildDirectory, "FreeCADWebAssemblyKernelProbe.js")).href;
const module = await import(moduleUrl);
const probe = await module.default({
wasmBinary: fs.readFileSync(path.join(buildDirectory, "FreeCADWebAssemblyKernelProbe.wasm")),
});
const call = (name, returnType = "number") => probe.ccall(name, returnType);
const result = {
run: call("fc_web_assembly_kernel_save_reopen"),
error: call("fc_web_assembly_kernel_error", "string"),
save: {
path: call("fc_web_assembly_kernel_persistence_path", "string"),
size: call("fc_web_assembly_kernel_persistence_size"),
error: call("fc_web_assembly_kernel_persistence_save_error", "string"),
},
opened: {
error: call("fc_web_assembly_kernel_persistence_open_error", "string"),
documentCount: call("fc_web_assembly_kernel_persistence_opened_document_count"),
objectCount: call("fc_web_assembly_kernel_persistence_opened_object_count"),
objectType: call("fc_web_assembly_kernel_persistence_opened_object_type", "string"),
typeProperty: call("fc_web_assembly_kernel_persistence_opened_type_property", "string"),
recompute: call("fc_web_assembly_kernel_persistence_opened_recompute"),
hasError: call("fc_web_assembly_kernel_persistence_opened_has_error"),
roundTrip: call("fc_web_assembly_kernel_persistence_round_trip"),
},
};
if (result.save.path) {
try {
fs.writeFileSync(path.join(buildDirectory, "AssemblyKernel.FCStd"), probe.FS.readFile(result.save.path));
}
catch (error) {
console.error(`archive export failed: ${error instanceof Error ? error.message : String(error)}`);
try {
console.error(`runtime tmp entries: ${probe.FS.readdir("/tmp").join(",")}`);
}
catch (directoryError) {
console.error(`runtime tmp listing failed: ${directoryError instanceof Error ? directoryError.message : String(directoryError)}`);
}
}
}
const valid = result.run === 1
&& result.error === ""
&& result.save.path === "/tmp/AssemblyKernel.FCStd"
&& result.save.size > 0
&& result.save.error === ""
&& result.opened.error === ""
&& result.opened.documentCount === 1
&& result.opened.objectCount === 9
&& result.opened.objectType === "Assembly::AssemblyObject"
&& result.opened.typeProperty === "Assembly"
&& result.opened.recompute >= 0
&& result.opened.hasError === 0
&& result.opened.roundTrip === 1;
if (!valid) throw new Error(JSON.stringify(result));
console.log(JSON.stringify(result));
}
const mode = process.argv[3] || "create";
(mode === "recovery" ? recovery() : mode === "persistence" ? persistence() : main()).catch((error) => {
console.error(error);
process.exitCode = 1;
});

View File

@@ -0,0 +1,83 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
const fs = require("fs");
const path = require("path");
const { pathToFileURL } = require("url");
const buildDirectory = path.resolve(process.argv[2] || "build-web/assembly-configure/bin");
async function main()
{
globalThis.__dirname = `${buildDirectory}${path.sep}`;
globalThis.require = require;
const moduleUrl = pathToFileURL(path.join(buildDirectory, "FreeCADWebAssemblyProbe.js")).href;
const module = await import(moduleUrl);
const probe = await module.default({
wasmBinary: fs.readFileSync(path.join(buildDirectory, "FreeCADWebAssemblyProbe.wasm")),
});
const call = (name, returnType = "number", argTypes = [], args = []) => probe.ccall(name, returnType, argTypes, args);
const error = () => ({
code: call("fc_web_assembly_error_code", "string"),
message: call("fc_web_assembly_error_message", "string"),
});
const result = {};
result.initialize = call("fc_web_assembly_initialize", "number", ["string"], ["AssemblyApp"]);
result.initializeAgain = call("fc_web_assembly_initialize", "number", ["string"], ["AssemblyApp"]);
result.type = call("fc_web_assembly_type_probe", "number", ["string"], ["Assembly::AssemblyObject"]);
result.typeName = call("fc_web_assembly_last_type", "string");
result.stateAfterValid = {
calls: call("fc_web_assembly_initialization_calls"),
runs: call("fc_web_assembly_initialization_runs"),
initialized: call("fc_web_assembly_initialized"),
};
result.handle = call("fc_web_assembly_create_handle", "number", ["string"], ["Assembly::AssemblyObject"]);
result.activeBeforeRelease = call("fc_web_assembly_active_handles");
result.release = call("fc_web_assembly_release_handle", "number", ["number"], [result.handle]);
result.activeAfterRelease = call("fc_web_assembly_active_handles");
result.unknownType = call("fc_web_assembly_type_probe", "number", ["string"], ["Assembly::Missing"]);
result.unknownTypeError = error();
result.unknownModule = call("fc_web_assembly_initialize", "number", ["string"], ["Missing"]);
result.unknownModuleError = error();
result.guiModule = call("fc_web_assembly_initialize", "number", ["string"], ["AssemblyGui"]);
result.guiModuleError = error();
result.emptyModule = call("fc_web_assembly_initialize", "number", ["string"], [""]);
result.emptyModuleError = error();
result.stateAfterErrors = {
calls: call("fc_web_assembly_initialization_calls"),
runs: call("fc_web_assembly_initialization_runs"),
initialized: call("fc_web_assembly_initialized"),
};
const valid = result.initialize === 1
&& result.initializeAgain === 1
&& result.type === 1
&& result.typeName === "Assembly::AssemblyObject"
&& result.stateAfterValid.calls === 3
&& result.stateAfterValid.runs === 1
&& result.stateAfterValid.initialized === 1
&& result.handle === 1
&& result.activeBeforeRelease === 1
&& result.release === 1
&& result.activeAfterRelease === 0
&& result.unknownType === 0
&& result.unknownTypeError.code === "type_not_found"
&& result.unknownModule === 0
&& result.unknownModuleError.code === "module_unavailable"
&& result.guiModule === 0
&& result.guiModuleError.code === "gui_dependency_unavailable"
&& result.emptyModule === 0
&& result.emptyModuleError.code === "invalid_argument"
&& result.stateAfterErrors.calls === 5
&& result.stateAfterErrors.runs === 1
&& result.stateAfterErrors.initialized === 1;
if (!valid) {
throw new Error(JSON.stringify(result));
}
console.log(JSON.stringify(result));
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});

View File

@@ -0,0 +1,152 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
const fs = require("fs");
const path = require("path");
const { pathToFileURL } = require("url");
const buildDirectory = path.resolve(process.argv[2] || "build-web/configure/bin");
async function main()
{
globalThis.__dirname = `${buildDirectory}${path.sep}`;
globalThis.require = require;
const probeModule = await import(pathToFileURL(path.join(buildDirectory, "FreeCADWebDocumentProbe.js")).href);
const probe = await probeModule.default({
wasmBinary: fs.readFileSync(path.join(buildDirectory, "FreeCADWebDocumentProbe.wasm")),
});
const run = probe.ccall("fc_web_document_create_and_enumerate", "number", [], []);
const result = {
run,
error: probe.ccall("fc_web_document_last_error", "string", [], []),
documentName: probe.ccall("fc_web_document_name", "string", [], []),
objectName: probe.ccall("fc_web_document_object_name", "string", [], []),
objectType: probe.ccall("fc_web_document_object_type", "string", [], []),
documentCount: probe.ccall("fc_web_document_count", "number", [], []),
objectCount: probe.ccall("fc_web_document_object_count", "number", [], []),
};
if (result.run !== 1
|| result.documentCount !== 1
|| result.objectCount !== 1
|| result.objectName !== "Box"
|| result.objectType !== "Part::Box"
|| !/^WebDocument\d*$/.test(result.documentName)
|| result.error !== "") {
throw new Error(JSON.stringify(result));
}
const recomputeRun = probe.ccall("fc_web_document_recompute_box", "number", [], []);
const recompute = {
run: recomputeRun,
error: probe.ccall("fc_web_document_last_error", "string", [], []),
count: probe.ccall("fc_web_document_recompute_count", "number", [], []),
volume: probe.ccall("fc_web_document_recompute_volume", "number", [], []),
hasError: probe.ccall("fc_web_document_recompute_has_error", "number", [], []),
};
if (recompute.run !== 1
|| recompute.count !== 1
|| recompute.hasError !== 0
|| Math.abs(recompute.volume - 24) > 1e-9
|| recompute.error !== "") {
throw new Error(JSON.stringify({ result, recompute }));
}
const recoveryRun = probe.ccall("fc_web_document_invalid_dimension_recovery", "number", [], []);
const recovery = {
run: recoveryRun,
error: probe.ccall("fc_web_document_last_error", "string", [], []),
invalidError: probe.ccall("fc_web_document_invalid_dimension_error", "string", [], []),
invalidVolume: probe.ccall("fc_web_document_invalid_shape_volume", "number", [], []),
recoveredVolume: probe.ccall("fc_web_document_recovered_shape_volume", "number", [], []),
hasError: probe.ccall("fc_web_document_recovery_has_error", "number", [], []),
};
if (recovery.run !== 1
|| recovery.invalidError !== "Length of box too small"
|| Math.abs(recovery.invalidVolume - 24) > 1e-9
|| Math.abs(recovery.recoveredVolume - 24) > 1e-9
|| recovery.hasError !== 0
|| recovery.error !== "") {
throw new Error(JSON.stringify({ result, recompute, recovery }));
}
const saveRun = probe.ccall("fc_web_document_save_fcstd", "number", [], []);
const save = {
run: saveRun,
error: probe.ccall("fc_web_document_last_error", "string", [], []),
path: probe.ccall("fc_web_document_fcstd_path", "string", [], []),
size: probe.ccall("fc_web_document_fcstd_size", "number", [], []),
volume: probe.ccall("fc_web_document_fcstd_volume", "number", [], []),
};
if (save.run !== 1
|| save.path !== "/tmp/WebBox.FCStd"
|| save.size <= 22
|| Math.abs(save.volume - 24) > 1e-9
|| save.error !== "") {
throw new Error(JSON.stringify({ result, recompute, recovery, save }));
}
fs.writeFileSync(
path.join(buildDirectory, "WebBox.FCStd"),
probe.FS.readFile(save.path),
);
const openRun = probe.ccall("fc_web_document_open_fcstd", "number", [], []);
const opened = {
run: openRun,
error: probe.ccall("fc_web_document_last_error", "string", [], []),
documentCount: probe.ccall("fc_web_document_opened_document_count", "number", [], []),
objectCount: probe.ccall("fc_web_document_opened_object_count", "number", [], []),
objectType: probe.ccall("fc_web_document_opened_object_type", "string", [], []),
length: probe.ccall("fc_web_document_opened_length", "number", [], []),
width: probe.ccall("fc_web_document_opened_width", "number", [], []),
height: probe.ccall("fc_web_document_opened_height", "number", [], []),
volume: probe.ccall("fc_web_document_opened_volume", "number", [], []),
};
if (opened.run !== 1
|| opened.documentCount !== 1
|| opened.objectCount !== 1
|| opened.objectType !== "Part::Box"
|| Math.abs(opened.length - 2) > 1e-9
|| Math.abs(opened.width - 3) > 1e-9
|| Math.abs(opened.height - 4) > 1e-9
|| Math.abs(opened.volume - 24) > 1e-9
|| opened.error !== "") {
throw new Error(JSON.stringify({ result, recompute, recovery, save, opened }));
}
const transactionRun = probe.ccall("fc_web_document_commit_resize_transaction", "number", [], []);
const transaction = {
run: transactionRun,
error: probe.ccall("fc_web_document_last_error", "string", [], []),
id: probe.ccall("fc_web_document_transaction_id", "number", [], []),
beforeUndo: probe.ccall("fc_web_document_transaction_before_undo", "number", [], []),
afterUndo: probe.ccall("fc_web_document_transaction_after_undo", "number", [], []),
pendingBeforeCommit: probe.ccall("fc_web_document_transaction_pending_before_commit", "number", [], []),
pendingAfterCommit: probe.ccall("fc_web_document_transaction_pending_after_commit", "number", [], []),
beforeVolume: probe.ccall("fc_web_document_transaction_before_volume", "number", [], []),
afterVolume: probe.ccall("fc_web_document_transaction_after_volume", "number", [], []),
undoResult: probe.ccall("fc_web_document_transaction_undo_result", "number", [], []),
afterUndoCount: probe.ccall("fc_web_document_transaction_after_undo_count", "number", [], []),
undoVolume: probe.ccall("fc_web_document_transaction_undo_volume", "number", [], []),
redoResult: probe.ccall("fc_web_document_transaction_redo_result", "number", [], []),
redoVolume: probe.ccall("fc_web_document_transaction_redo_volume", "number", [], []),
abortPending: probe.ccall("fc_web_document_transaction_abort_pending", "number", [], []),
abortVolume: probe.ccall("fc_web_document_transaction_abort_volume", "number", [], []),
};
if (transaction.run !== 1
|| transaction.error !== ""
|| transaction.id === 0
|| transaction.pendingBeforeCommit !== 1
|| transaction.pendingAfterCommit !== 0
|| transaction.afterUndo <= transaction.beforeUndo
|| Math.abs(transaction.beforeVolume - 24) > 1e-9
|| Math.abs(transaction.afterVolume - 48) > 1e-9
|| transaction.undoResult !== 1
|| transaction.afterUndoCount <= 0
|| Math.abs(transaction.undoVolume - 24) > 1e-9
|| transaction.redoResult !== 1
|| Math.abs(transaction.redoVolume - 48) > 1e-9
|| transaction.abortPending !== 0
|| Math.abs(transaction.abortVolume - 48) > 1e-9) {
throw new Error(JSON.stringify({ result, recompute, recovery, save, opened, transaction }));
}
console.log(JSON.stringify({ result, recompute, recovery, save, opened, transaction }));
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});

View File

@@ -0,0 +1,79 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
const fs = require("fs");
const path = require("path");
const { pathToFileURL } = require("url");
const buildDirectory = path.resolve(process.argv[2] || "build-web/configure/bin");
async function main()
{
globalThis.__dirname = `${buildDirectory}${path.sep}`;
globalThis.require = require;
const moduleUrl = pathToFileURL(path.join(buildDirectory, "FreeCADWebModuleLoaderProbe.js")).href;
const module = await import(moduleUrl);
const probe = await module.default({
wasmBinary: fs.readFileSync(path.join(buildDirectory, "FreeCADWebModuleLoaderProbe.wasm")),
});
const call = (name, returnType = "number", argTypes = [], args = []) => probe.ccall(name, returnType, argTypes, args);
const error = () => ({
code: call("fc_web_module_loader_error_code", "string"),
message: call("fc_web_module_loader_error_message", "string"),
});
const result = {};
result.initialize = call("fc_web_module_loader_initialize", "number", ["string"], ["Part"]);
result.type = call("fc_web_module_loader_type_probe", "number", ["string"], ["Part::Box"]);
result.typeName = call("fc_web_module_loader_last_type", "string");
result.stateAfterValid = {
calls: call("fc_web_module_loader_initialization_calls"),
runs: call("fc_web_module_loader_initialization_runs"),
initialized: call("fc_web_module_loader_initialized"),
};
result.handle = call("fc_web_module_loader_create_handle", "number", ["string"], ["Part::Box"]);
result.activeBeforeRelease = call("fc_web_module_loader_active_handles");
result.release = call("fc_web_module_loader_release_handle", "number", ["number"], [result.handle]);
result.activeAfterRelease = call("fc_web_module_loader_active_handles");
result.unknownType = call("fc_web_module_loader_type_probe", "number", ["string"], ["Part::Missing"]);
result.unknownTypeError = error();
result.unknownModule = call("fc_web_module_loader_initialize", "number", ["string"], ["Missing"]);
result.unknownModuleError = error();
result.guiModule = call("fc_web_module_loader_initialize", "number", ["string"], ["PartGui"]);
result.guiModuleError = error();
result.emptyModule = call("fc_web_module_loader_initialize", "number", ["string"], [""]);
result.emptyModuleError = error();
result.stateAfterErrors = {
calls: call("fc_web_module_loader_initialization_calls"),
runs: call("fc_web_module_loader_initialization_runs"),
initialized: call("fc_web_module_loader_initialized"),
};
const valid = result.initialize === 1
&& result.type === 1
&& result.typeName === "Part::Box"
&& result.stateAfterValid.runs === 1
&& result.stateAfterValid.initialized === 1
&& result.handle === 1
&& result.activeBeforeRelease === 1
&& result.release === 1
&& result.activeAfterRelease === 0
&& result.unknownType === 0
&& result.unknownTypeError.code === "type_not_found"
&& result.unknownModule === 0
&& result.unknownModuleError.code === "module_unavailable"
&& result.guiModule === 0
&& result.guiModuleError.code === "gui_dependency_unavailable"
&& result.emptyModule === 0
&& result.emptyModuleError.code === "invalid_argument"
&& result.stateAfterErrors.runs === 1
&& result.stateAfterErrors.initialized === 1;
if (!valid) {
throw new Error(JSON.stringify(result));
}
console.log(JSON.stringify(result));
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});

View File

@@ -0,0 +1,64 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
const fs = require("fs");
const path = require("path");
const { pathToFileURL } = require("url");
const buildDirectory = path.resolve(process.argv[2] || "build-web/configure/bin");
async function main()
{
globalThis.__dirname = `${buildDirectory}${path.sep}`;
globalThis.require = require;
const probeModule = await import(pathToFileURL(path.join(buildDirectory, "FreeCADWebPartBoxProbe.js")).href);
const probe = await probeModule.default({
wasmBinary: fs.readFileSync(path.join(buildDirectory, "FreeCADWebPartBoxProbe.wasm")),
});
const constructorProbe = probe.ccall(
"fc_web_part_box_constructor_probe",
"number",
[],
[],
);
const constructorError = probe.ccall("fc_web_part_box_last_error", "string", [], []);
const volume = probe.ccall(
"fc_web_part_box_volume",
"number",
["number", "number", "number"],
[2, 3, 4],
);
const stateAfterValid = {
calls: probe.ccall("fc_web_part_box_initialization_calls", "number", [], []),
runs: probe.ccall("fc_web_part_box_initialization_runs", "number", [], []),
initialized: probe.ccall("fc_web_part_box_types_initialized", "number", [], []),
};
const invalidVolume = probe.ccall(
"fc_web_part_box_volume",
"number",
["number", "number", "number"],
[0, 3, 4],
);
const invalidError = probe.ccall("fc_web_part_box_last_error", "string", [], []);
const recovery = probe.ccall("fc_web_part_box_recovery_probe", "number", [], []);
const stateAfterRecovery = {
calls: probe.ccall("fc_web_part_box_initialization_calls", "number", [], []),
runs: probe.ccall("fc_web_part_box_initialization_runs", "number", [], []),
initialized: probe.ccall("fc_web_part_box_types_initialized", "number", [], []),
};
if (constructorProbe !== 1
|| Math.abs(volume - 24) > 1e-9
|| invalidVolume !== -1
|| invalidError !== "Length of box too small"
|| recovery !== 1
|| stateAfterValid.runs !== 1
|| stateAfterRecovery.runs !== 1
|| stateAfterRecovery.initialized !== 1) {
throw new Error(JSON.stringify({ constructorProbe, constructorError, volume, invalidVolume, invalidError, recovery, stateAfterValid, stateAfterRecovery }));
}
console.log(JSON.stringify({ constructorProbe, constructorError, volume, invalidVolume, invalidError, recovery, stateAfterValid, stateAfterRecovery }));
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});

View File

@@ -0,0 +1,77 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
const path = require("path");
const { Worker } = require("worker_threads");
const buildDirectory = path.resolve(process.argv[2] || "build-web/configure/bin");
const workerPath = path.resolve(__dirname, "python-runtime-worker.js");
function receive(worker)
{
return new Promise((resolve, reject) => {
worker.once("message", resolve);
worker.once("error", reject);
});
}
async function startWorker()
{
const worker = new Worker(workerPath, {workerData: {buildDirectory}});
const ready = await receive(worker);
return {worker, ready};
}
function receiveWithTimeout(worker, timeoutMs)
{
return Promise.race([
receive(worker),
new Promise((_, reject) => setTimeout(() => reject(new Error("worker request timeout")), timeoutMs)),
]);
}
async function main()
{
const first = await startWorker();
const worker = first.worker;
const ready = first.ready;
worker.postMessage({type: "eval", id: 1, expression: "6 * 7"});
const success = await receive(worker);
worker.postMessage({type: "eval", id: 3, expression: "__import__('FreeCADWebFacade').create_box(2, 3, 4)"});
const facade = await receive(worker);
worker.postMessage({type: "eval", id: 2, expression: "1 / 0"});
const failure = await receive(worker);
worker.postMessage({type: "reset"});
const reset = await receive(worker);
await worker.terminate();
const timeoutWorker = (await startWorker()).worker;
timeoutWorker.postMessage({type: "hang", id: 4});
let timeout = "none";
try {
await receiveWithTimeout(timeoutWorker, 50);
}
catch (error) {
timeout = String(error.message);
}
await timeoutWorker.terminate();
const replacement = await startWorker();
await replacement.worker.terminate();
const result = {ready, success, facade, failure, reset, timeout, replacement: replacement.ready};
if (ready.type !== "ready" || ready.ready !== 1 || ready.initializationCount !== 1 || ready.error !== ""
|| success.type !== "result" || success.run !== 1 || success.value !== "42" || success.error !== ""
|| facade.type !== "result" || facade.run !== 1 || facade.error !== ""
|| !facade.value.includes("'type': 'Part::Box'") || !facade.value.includes("'volume': 24.0")
|| !facade.value.includes("'recompute': 1") || !facade.value.includes("'hasError': 0")
|| reset.type !== "reset" || reset.ready !== 1 || reset.initializationCount !== 1 || reset.error !== ""
|| timeout !== "worker request timeout"
|| replacement.ready.ready !== 1 || replacement.ready.initializationCount !== 1 || replacement.ready.error !== ""
|| failure.type !== "result" || failure.run !== 0 || failure.value !== ""
|| failure.error !== "ZeroDivisionError: division by zero") {
throw new Error(JSON.stringify(result));
}
console.log(JSON.stringify(result));
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});

View File

@@ -0,0 +1,34 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
const fs = require("fs");
const path = require("path");
const { pathToFileURL } = require("url");
const { parentPort, workerData } = require("worker_threads");
async function start()
{
const buildDirectory = path.resolve(workerData.buildDirectory);
globalThis.__dirname = `${buildDirectory}${path.sep}`;
globalThis.require = require;
const moduleUrl = pathToFileURL(path.join(buildDirectory, "FreeCADWebPythonProbe.js")).href;
const factory = (await import(moduleUrl)).default;
const runtime = await factory({wasmBinary: fs.readFileSync(path.join(buildDirectory, "FreeCADWebPythonProbe.wasm"))});
const call = (name, returnType = "number", argTypes = [], args = []) => runtime.ccall(name, returnType, argTypes, args);
const ready = call("fc_web_python_runtime_start");
parentPort.postMessage({type: "ready", ready, initializationCount: call("fc_web_python_runtime_initialization_count"), error: call("fc_web_python_runtime_error", "string")});
parentPort.on("message", (message) => {
if (message.type === "eval") {
const run = call("fc_web_python_runtime_eval", "number", ["string"], [message.expression]);
parentPort.postMessage({type: "result", id: message.id, run, value: call("fc_web_python_runtime_result", "string"), error: call("fc_web_python_runtime_error", "string")});
}
if (message.type === "reset") {
const ready = call("fc_web_python_runtime_start");
parentPort.postMessage({type: "reset", ready, initializationCount: call("fc_web_python_runtime_initialization_count"), error: call("fc_web_python_runtime_error", "string")});
}
if (message.type === "hang") {
// The host must terminate this request and replace the worker.
}
});
}
start().catch((error) => parentPort.postMessage({type: "fatal", error: String(error)}));

View File

@@ -0,0 +1,40 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
const path = require("path");
const { Worker } = require("worker_threads");
const buildDirectory = path.resolve(process.argv[2] || "build-web/configure/bin");
const workerPath = path.resolve(__dirname, "python-runtime-worker.js");
function receive(worker)
{
return new Promise((resolve, reject) => {
worker.once("message", resolve);
worker.once("error", reject);
});
}
async function main()
{
const worker = new Worker(workerPath, {workerData: {buildDirectory}});
const ready = await receive(worker);
worker.postMessage({type: "eval", id: 1, expression: "(__import__('FreeCADWebWorkbench').name(), __import__('FreeCADWebWorkbench').commands())"});
const registration = await receive(worker);
worker.postMessage({type: "eval", id: 2, expression: "__import__('FreeCADWebWorkbench').run_box(2, 3, 4)"});
const command = await receive(worker);
await worker.terminate();
const result = {ready, registration, command};
if (ready.type !== "ready" || ready.ready !== 1 || ready.error !== ""
|| registration.type !== "result" || registration.run !== 1 || registration.error !== ""
|| !registration.value.includes("FreeCAD Web Part") || !registration.value.includes("'box'")
|| command.type !== "result" || command.run !== 1 || command.error !== ""
|| !command.value.includes("'type': 'Part::Box'") || !command.value.includes("'volume': 24.0")) {
throw new Error(JSON.stringify(result));
}
console.log(JSON.stringify(result));
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});

View File

@@ -0,0 +1,82 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
const fs = require("fs");
const path = require("path");
const { pathToFileURL } = require("url");
const buildDirectory = path.resolve(process.argv[2] || "build-web/configure/bin");
const mode = process.argv[3] || "all";
async function main()
{
globalThis.__dirname = `${buildDirectory}${path.sep}`;
globalThis.require = require;
const moduleUrl = pathToFileURL(path.join(buildDirectory, "FreeCADWebSketcherProbe.js")).href;
const probeModule = await import(moduleUrl);
const probe = await probeModule.default({
wasmBinary: fs.readFileSync(path.join(buildDirectory, "FreeCADWebSketcherProbe.wasm")),
});
const call = (name, returnType = "number") => probe.ccall(name, returnType, [], []);
const error = () => call("fc_web_sketcher_last_error", "string");
const result = { mode };
if (mode === "type" || mode === "all") {
result.type = {
run: call("fc_web_sketcher_type_probe"),
error: error(),
initializationCount: call("fc_web_sketcher_initialization_count"),
objectType: call("fc_web_sketcher_object_type", "string"),
};
if (result.type.run !== 1 || result.type.error !== ""
|| result.type.initializationCount !== 1
|| result.type.objectType !== "Sketcher::SketchObject") {
throw new Error(JSON.stringify(result));
}
}
if (mode === "geometry" || mode === "all") {
result.geometry = {
run: call("fc_web_sketcher_geometry_probe"),
error: error(),
objectType: call("fc_web_sketcher_object_type", "string"),
geometryCount: call("fc_web_sketcher_geometry_count"),
recomputeCount: call("fc_web_sketcher_recompute_count"),
hasError: call("fc_web_sketcher_recompute_has_error"),
start: [call("fc_web_sketcher_start_x"), call("fc_web_sketcher_start_y")],
end: [call("fc_web_sketcher_end_x"), call("fc_web_sketcher_end_y")],
};
if (result.geometry.run !== 1 || result.geometry.error !== ""
|| result.geometry.objectType !== "Sketcher::SketchObject"
|| result.geometry.geometryCount !== 1 || result.geometry.recomputeCount !== 1
|| result.geometry.hasError !== 0
|| result.geometry.start[0] !== 0 || result.geometry.start[1] !== 0
|| result.geometry.end[0] !== 4 || result.geometry.end[1] !== 0) {
throw new Error(JSON.stringify(result));
}
}
if (mode === "constraint" || mode === "all") {
result.constraint = {
run: call("fc_web_sketcher_constraint_probe"),
error: error(),
geometryCount: call("fc_web_sketcher_geometry_count"),
constraintCount: call("fc_web_sketcher_constraint_count"),
solverStatus: call("fc_web_sketcher_solver_status"),
dof: call("fc_web_sketcher_solver_dof"),
invalidError: call("fc_web_sketcher_invalid_constraint_error", "string"),
};
if (result.constraint.run !== 1 || result.constraint.error !== ""
|| result.constraint.geometryCount !== 1 || result.constraint.constraintCount !== 1
|| result.constraint.solverStatus !== 0 || result.constraint.dof !== 3
|| result.constraint.invalidError !== "Sketcher constraint geometry index out of range") {
throw new Error(JSON.stringify(result));
}
}
console.log(JSON.stringify(result));
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});

View File

@@ -0,0 +1,292 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
#include <BRepBndLib.hxx>
#include <BRepGProp.hxx>
#include <BRepMesh_IncrementalMesh.hxx>
#include <BRepPrimAPI_MakeBox.hxx>
#include <BRep_Tool.hxx>
#include <Bnd_Box.hxx>
#include <GProp_GProps.hxx>
#include <IFSelect_ReturnStatus.hxx>
#include <Poly_Triangulation.hxx>
#include <STEPControl_Reader.hxx>
#include <Standard_Failure.hxx>
#include <Standard_Version.hxx>
#include <TopAbs_Orientation.hxx>
#include <TopExp_Explorer.hxx>
#include <TopoDS.hxx>
#include <TopoDS_Face.hxx>
#include <TopLoc_Location.hxx>
#include <gp_Pnt.hxx>
#include <gp_XYZ.hxx>
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <cmath>
#include <exception>
#include <limits>
#include <sstream>
#include <string>
#include <vector>
#include <emscripten/emscripten.h>
namespace {
struct MeshData
{
std::vector<float> positions;
std::vector<float> normals;
double bounds[6];
int faceCount;
};
MeshData meshData;
std::string lastError;
bool validDimension(double value)
{
return std::isfinite(value) && value > 0.0;
}
void clearMeshData()
{
meshData.positions.clear();
meshData.normals.clear();
meshData.bounds[0] = std::numeric_limits<double>::infinity();
meshData.bounds[1] = std::numeric_limits<double>::infinity();
meshData.bounds[2] = std::numeric_limits<double>::infinity();
meshData.bounds[3] = -std::numeric_limits<double>::infinity();
meshData.bounds[4] = -std::numeric_limits<double>::infinity();
meshData.bounds[5] = -std::numeric_limits<double>::infinity();
meshData.faceCount = 0;
}
void setError(const std::string& message)
{
lastError = message;
}
void appendVertex(const gp_Pnt& point, const gp_XYZ& normal)
{
meshData.positions.push_back(static_cast<float>(point.X()));
meshData.positions.push_back(static_cast<float>(point.Y()));
meshData.positions.push_back(static_cast<float>(point.Z()));
meshData.normals.push_back(static_cast<float>(normal.X()));
meshData.normals.push_back(static_cast<float>(normal.Y()));
meshData.normals.push_back(static_cast<float>(normal.Z()));
meshData.bounds[0] = std::min(meshData.bounds[0], point.X());
meshData.bounds[1] = std::min(meshData.bounds[1], point.Y());
meshData.bounds[2] = std::min(meshData.bounds[2], point.Z());
meshData.bounds[3] = std::max(meshData.bounds[3], point.X());
meshData.bounds[4] = std::max(meshData.bounds[4], point.Y());
meshData.bounds[5] = std::max(meshData.bounds[5], point.Z());
}
void appendTriangle(const gp_Pnt& first, const gp_Pnt& second, const gp_Pnt& third)
{
gp_XYZ normal = (second.XYZ() - first.XYZ()).Crossed(third.XYZ() - first.XYZ());
const double magnitude = normal.Modulus();
if (!std::isfinite(magnitude) || magnitude <= 1e-12) {
return;
}
normal.Divide(magnitude);
appendVertex(first, normal);
appendVertex(second, normal);
appendVertex(third, normal);
}
}
extern "C" {
EMSCRIPTEN_KEEPALIVE const char* fc_web_kernel_version()
{
return "FreeCAD 1.2 WebKernel/0.2 OCCT/" OCC_VERSION_STRING;
}
EMSCRIPTEN_KEEPALIVE double fc_web_box_volume(double length, double width, double height)
{
if (!validDimension(length) || !validDimension(width) || !validDimension(height)) {
return -1.0;
}
const TopoDS_Shape box = BRepPrimAPI_MakeBox(length, width, height).Shape();
GProp_GProps properties;
BRepGProp::VolumeProperties(box, properties);
return properties.Mass();
}
EMSCRIPTEN_KEEPALIVE int fc_web_box_bounds(
double length,
double width,
double height,
double* bounds)
{
if (bounds == nullptr || !validDimension(length) || !validDimension(width) || !validDimension(height)) {
return 0;
}
const TopoDS_Shape box = BRepPrimAPI_MakeBox(length, width, height).Shape();
Bnd_Box boundingBox;
BRepBndLib::Add(box, boundingBox);
boundingBox.Get(bounds[0], bounds[1], bounds[2], bounds[3], bounds[4], bounds[5]);
return 1;
}
EMSCRIPTEN_KEEPALIVE int fc_web_step_load(
const std::uint8_t* data,
std::size_t size,
double linearDeflection,
double angularDeflection)
{
clearMeshData();
lastError.clear();
if (data == nullptr || size == 0) {
setError("STEP input is empty");
return 0;
}
if (size > 256U * 1024U * 1024U) {
setError("STEP input exceeds the 256 MiB kernel limit");
return 0;
}
if (!validDimension(linearDeflection) || !validDimension(angularDeflection)) {
setError("Meshing deflection values must be finite and positive");
return 0;
}
try {
const std::string stepText(reinterpret_cast<const char*>(data), size);
std::istringstream stepStream(stepText);
STEPControl_Reader reader;
const IFSelect_ReturnStatus readStatus = reader.ReadStream("freecad-upload.step", stepStream);
if (readStatus != IFSelect_RetDone) {
setError("OCCT could not parse the STEP input");
return 0;
}
if (reader.TransferRoots() <= 0) {
setError("STEP input contains no transferable roots");
return 0;
}
const TopoDS_Shape shape = reader.OneShape();
if (shape.IsNull()) {
setError("STEP transfer produced an empty shape");
return 0;
}
BRepMesh_IncrementalMesh mesher(
shape,
linearDeflection,
Standard_False,
angularDeflection,
Standard_False);
if (!mesher.IsDone()) {
setError("OCCT triangulation did not complete");
return 0;
}
for (TopExp_Explorer explorer(shape, TopAbs_FACE); explorer.More(); explorer.Next()) {
const TopoDS_Face face = TopoDS::Face(explorer.Current());
TopLoc_Location location;
const Handle(Poly_Triangulation) triangulation = BRep_Tool::Triangulation(face, location);
if (triangulation.IsNull() || triangulation->NbTriangles() == 0) {
continue;
}
++meshData.faceCount;
const gp_Trsf transformation = location.Transformation();
for (int triangleIndex = 1; triangleIndex <= triangulation->NbTriangles(); ++triangleIndex) {
int firstIndex = 0;
int secondIndex = 0;
int thirdIndex = 0;
triangulation->Triangle(triangleIndex).Get(firstIndex, secondIndex, thirdIndex);
if (face.Orientation() == TopAbs_REVERSED) {
std::swap(secondIndex, thirdIndex);
}
const gp_Pnt first = triangulation->Node(firstIndex).Transformed(transformation);
const gp_Pnt second = triangulation->Node(secondIndex).Transformed(transformation);
const gp_Pnt third = triangulation->Node(thirdIndex).Transformed(transformation);
appendTriangle(first, second, third);
}
}
if (meshData.positions.empty()) {
clearMeshData();
setError("STEP transfer produced no renderable triangles");
return 0;
}
return 1;
}
catch (const Standard_Failure& failure) {
clearMeshData();
const char* message = failure.GetMessageString();
setError(message != nullptr ? message : "OCCT raised an unknown failure");
return 0;
}
catch (const std::exception& exception) {
clearMeshData();
setError(exception.what());
return 0;
}
catch (...) {
clearMeshData();
setError("Unknown failure while importing STEP input");
return 0;
}
}
EMSCRIPTEN_KEEPALIVE const float* fc_web_mesh_positions()
{
return meshData.positions.empty() ? nullptr : meshData.positions.data();
}
EMSCRIPTEN_KEEPALIVE const float* fc_web_mesh_normals()
{
return meshData.normals.empty() ? nullptr : meshData.normals.data();
}
EMSCRIPTEN_KEEPALIVE int fc_web_mesh_vertex_count()
{
return static_cast<int>(meshData.positions.size() / 3U);
}
EMSCRIPTEN_KEEPALIVE int fc_web_mesh_triangle_count()
{
return static_cast<int>(meshData.positions.size() / 9U);
}
EMSCRIPTEN_KEEPALIVE int fc_web_mesh_face_count()
{
return meshData.faceCount;
}
EMSCRIPTEN_KEEPALIVE int fc_web_mesh_bounds(double* bounds)
{
if (bounds == nullptr || meshData.positions.empty()) {
return 0;
}
std::copy(meshData.bounds, meshData.bounds + 6, bounds);
return 1;
}
EMSCRIPTEN_KEEPALIVE const char* fc_web_last_error()
{
return lastError.c_str();
}
EMSCRIPTEN_KEEPALIVE void fc_web_mesh_clear()
{
clearMeshData();
lastError.clear();
}
}

View File

@@ -0,0 +1,134 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
const fs = require("fs");
const path = require("path");
const { pathToFileURL } = require("url");
const buildDirectory = path.resolve(process.argv[2] || "build-web/bridge");
const stepFile = path.resolve(
process.argv[3] || path.join(__dirname, "../../data/tests/Step/as1-ac-214_small.stp"),
);
async function main()
{
// Emscripten 3.1.6's Node branch still reads CommonJS __dirname from ES modules.
globalThis.__dirname = `${buildDirectory}${path.sep}`;
const kernelModule = await import(pathToFileURL(path.join(buildDirectory, "FreeCADWebKernel.js")).href);
const createKernel = kernelModule.default;
// Supplying wasmBinary avoids Node's fetch treating a local filesystem path as a URL.
const kernel = await createKernel({
wasmBinary: fs.readFileSync(path.join(buildDirectory, "FreeCADWebKernel.wasm")),
});
const version = kernel.ccall("fc_web_kernel_version", "string", [], []);
const volume = kernel.ccall(
"fc_web_box_volume",
"number",
["number", "number", "number"],
[2, 3, 4],
);
const invalidVolume = kernel.ccall(
"fc_web_box_volume",
"number",
["number", "number", "number"],
[2, 0, 4],
);
const boundsPointer = kernel._malloc(6 * Float64Array.BYTES_PER_ELEMENT);
const boundsResult = kernel.ccall(
"fc_web_box_bounds",
"number",
["number", "number", "number", "number"],
[2, 3, 4, boundsPointer],
);
const bounds = Array.from(kernel.HEAPF64.subarray(
boundsPointer / Float64Array.BYTES_PER_ELEMENT,
boundsPointer / Float64Array.BYTES_PER_ELEMENT + 6,
));
kernel._free(boundsPointer);
const expectedBounds = [0, 0, 0, 2, 3, 4];
const boundsMatch = boundsResult === 1
&& bounds.every((value, index) => Math.abs(value - expectedBounds[index]) < 1e-6);
if (version !== "FreeCAD 1.2 WebKernel/0.2 OCCT/7.6"
|| Math.abs(volume - 24) > 1e-9
|| invalidVolume !== -1
|| !boundsMatch) {
throw new Error(JSON.stringify({ version, volume, invalidVolume, boundsResult, bounds }));
}
const stepBytes = fs.readFileSync(stepFile);
const stepPointer = kernel._malloc(stepBytes.byteLength);
kernel.HEAPU8.set(stepBytes, stepPointer);
const stepResult = kernel.ccall(
"fc_web_step_load",
"number",
["number", "number", "number", "number"],
[stepPointer, stepBytes.byteLength, 0.5, 0.5],
);
kernel._free(stepPointer);
const stepError = kernel.ccall("fc_web_last_error", "string", [], []);
const vertexCount = kernel.ccall("fc_web_mesh_vertex_count", "number", [], []);
const triangleCount = kernel.ccall("fc_web_mesh_triangle_count", "number", [], []);
const faceCount = kernel.ccall("fc_web_mesh_face_count", "number", [], []);
const positionsPointer = kernel.ccall("fc_web_mesh_positions", "number", [], []);
const normalsPointer = kernel.ccall("fc_web_mesh_normals", "number", [], []);
const meshBoundsPointer = kernel._malloc(6 * Float64Array.BYTES_PER_ELEMENT);
const meshBoundsResult = kernel.ccall(
"fc_web_mesh_bounds",
"number",
["number"],
[meshBoundsPointer],
);
const meshBounds = Array.from(new Float64Array(kernel.HEAPF64.buffer, meshBoundsPointer, 6));
kernel._free(meshBoundsPointer);
const positions = new Float32Array(kernel.HEAPF32.buffer, positionsPointer, vertexCount * 3);
const normals = new Float32Array(kernel.HEAPF32.buffer, normalsPointer, vertexCount * 3);
const firstNormalLength = Math.hypot(normals[0], normals[1], normals[2]);
const validStepMesh = stepResult === 1
&& stepError === ""
&& vertexCount > 0
&& triangleCount > 0
&& faceCount > 0
&& positions.length === vertexCount * 3
&& positions.every(Number.isFinite)
&& normals.every(Number.isFinite)
&& Math.abs(firstNormalLength - 1) < 1e-5
&& meshBoundsResult === 1
&& meshBounds.every(Number.isFinite)
&& meshBounds.some((value, index) => index < 3 && meshBounds[index + 3] > value);
if (!validStepMesh) {
throw new Error(JSON.stringify({
stepResult,
stepError,
vertexCount,
triangleCount,
faceCount,
meshBoundsResult,
meshBounds,
firstNormalLength,
}));
}
kernel.ccall("fc_web_mesh_clear", null, [], []);
const clearedVertexCount = kernel.ccall("fc_web_mesh_vertex_count", "number", [], []);
if (clearedVertexCount !== 0) {
throw new Error(`Mesh clear failed: ${clearedVertexCount}`);
}
console.log(JSON.stringify({
version,
volume,
bounds,
stepFile,
vertexCount,
triangleCount,
faceCount,
meshBounds,
}));
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});