This document provides comprehensive guidance for AI assistants (GitHub Copilot, Claude, ChatGPT, and others) working with the Open CASCADE Technology (OCCT) C++17+ 3D CAD/CAM/CAE library.
IMPORTANT: These are the most critical rules. Follow them strictly.
Memory Management is Paramount:
occ::handle<ClassName> for any class inheriting from Standard_Transient (e.g., Geom_*, Poly_*, AIS_*, V3d_*). This is for reference-counted objects.ClassName*) for these types, as it will cause memory leaks.occ::handle<Geom_Circle> aCircle = new Geom_Circle(...);Geom_Circle* aCircle = new Geom_Circle(...);Handle(ClassName) macro still exists but occ::handle<> is preferred in new code.Check Operation Status:
BRepAlgoAPI_Fuse, BRepBuilderAPI_MakeEdge), ALWAYS check if the operation was successful using the IsDone() method before accessing the result.BRepAlgoAPI_Fuse aFuser(theShape1, theShape2); if (aFuser.IsDone()) { const TopoDS_Shape& aResult = aFuser.Shape(); } else { // Handle error }
Strict Naming and File Conventions:
Package_ClassName convention.src/Module/Toolkit/Package/.src/Module/Toolkit/Package/FILES.cmake file.Use Modern C++ Idioms:
for loops and structured bindings where applicable.TopExp_Explorer constructor style.for (TopExp_Explorer anExp(theShape, TopAbs_FACE); anExp.More(); anExp.Next()) { ... }for (TopExp_Explorer anExp; anExp.Init(theShape, TopAbs_FACE); anExp.More(); anExp.Next()) { ... }Safe Type Casting:
TopoDS helper functions to avoid errors.const TopoDS_Face& aFace = TopoDS::Face(anExp.Current());const TopoDS_Face& aFace = (const TopoDS_Face&)anExp.Current();Handle Downcasting:
occ::down_cast<DerivedClass>(BaseHandle) to safely downcast handles.const occ::handle<Geom_Circle> aCircle = occ::down_cast<Geom_Circle>(aCurveHandle); // Alternative (legacy): occ::handle<Geom_Circle>::DownCast(aCurveHandle)
// Do not use C-style casts on handles Geom_Circle* aCircle = (Geom_Circle*)aHandle.Get();
Validate Handles for Null Safety:
occ::handle<ClassName> is not null before dereferencing it:if (!theHandle.IsNull()) { // use theHandle }
Open CASCADE Technology (OCCT) is a comprehensive C++ software development platform for 3D surface and solid modeling, CAD data exchange, and visualization. It's a modern C++17+ library providing services for CAD/CAM/CAE applications.
src/: Source code, organized by a Module/Toolkit/Package hierarchy.tests/: Draw Harness test files, organized by functionality.adm/: Administrative and build configuration files.samples/: Example applications.NEVER use non-ASCII symbols in code or comments.
| Element Type | Pattern | Example |
|---|---|---|
| Classes | Package_ClassName | TopoDS_Shape, BRep_Builder |
| Public Methods | MethodName | IsDone(), Shape() |
| Private Methods | methodName | myInternalMethod() |
| Method Parameters | theParameterName | theShape, theTolerance |
| Local Variables | aVariableName | aBox, anExplorer |
| Class Member Fields | myFieldName | myShape, myIsDone |
| Struct Member Fields | FieldVariableName | Point, Value |
| Global Variables | THE_GLOBAL_VARIABLE | THE_DEFAULT_PRECISION |
Use standard C++ primitive types in all code. The old Standard_* typedefs are deprecated and must not be used:
| Use This | Instead of (Deprecated) | Usage |
|---|---|---|
int | Integer values | |
double | Floating-point numbers | |
bool | Boolean values | |
float | Single-precision floats | |
char | Character values | |
uint8_t | Byte values | |
size_t | Size values | |
void* | Generic pointers | |
char16_t | Unicode characters | |
const char* | C-style strings | |
true/false | Boolean literals |
WARNING: All
Standard_*type aliases inStandard_TypeDef.hxxare markedStandard_DEPRECATEDand will be removed in future versions. Always use native C++ types directly.
ALWAYS use OCCT collection classes instead of STL containers:
| OCCT Type | Instead of | Description |
|---|---|---|
TCollection_AsciiString | std::string | ASCII string |
TCollection_ExtendedString | std::wstring | Unicode string |
NCollection_Array1<T> | std::vector<T> | Fixed-size array (1-based) |
NCollection_DynamicArray<T> | std::vector<T> | Dynamic array |
NCollection_List<T> | std::list<T> | Doubly-linked list |
NCollection_Sequence<T> | std::deque<T> | Indexed sequence |
NCollection_Map<K> | std::unordered_set<K> | Hash set |
NCollection_DataMap<K,V> | std::unordered_map<K,V> | Hash map |
NCollection_IndexedMap<K> | - | Indexed hash set |
NCollection_IndexedDataMap<K,V> | - | Indexed hash map |
IMPORTANT: Package-Specific Type Aliases Removed
Old package-specific type aliases have been removed from OCCT. You must use
NCollection_*templates directly with explicit types:
Removed Alias (Do Not Use) Use Instead TColStd_ListOfIntegerNCollection_List<int>TColStd_Array1OfRealNCollection_Array1<double>TColStd_SequenceOfIntegerNCollection_Sequence<int>TColStd_MapOfIntegerNCollection_Map<int>TColStd_DataMapOfIntegerRealNCollection_DataMap<int, double>TopTools_ListOfShapeNCollection_List<TopoDS_Shape>TopTools_MapOfShapeNCollection_Map<TopoDS_Shape>TColgp_Array1OfPntNCollection_Array1<gp_Pnt>TColgp_SequenceOfPntNCollection_Sequence<gp_Pnt>Exception:
TColStd_PackedMapOfIntegerstill exists as it has a specialized implementation.
If STL containers are absolutely necessary, use OCCT's allocators:
#include <NCollection_Allocator.hxx> #include <NCollection_OccAllocator.hxx> #include <NCollection_IncAllocator.hxx> // Option 1: NCollection_Allocator - uses standard OCCT memory allocation std::vector<gp_Pnt, NCollection_Allocator<gp_Pnt>> aPoints; std::list<TopoDS_Shape, NCollection_Allocator<TopoDS_Shape>> aShapes; // Option 2: NCollection_OccAllocator - with custom memory pool (preferred for performance) occ::handle<NCollection_IncAllocator> anIncAlloc = new NCollection_IncAllocator(); NCollection_OccAllocator<gp_Pnt> anAllocator(anIncAlloc); std::vector<gp_Pnt, NCollection_OccAllocator<gp_Pnt>> aPooledPoints(anAllocator);
This is a C++17+ codebase. Use modern features where appropriate:
for loopsfor (const auto& [aKey, aValue] : aMap)std::optional for optional return valuesstd::variant for type-safe unionsif constexpr for compile-time conditions[[nodiscard]], [[maybe_unused]] attributes where appropriateauto KeywordUse auto only in the following cases:
for loopsauto anIter = aContainer.begin()Avoid auto in these cases:
Readability is more important than brevity. Always prefer explicit types.
Use const for variables that will not be modified after initialization:
const double aTolerance = 0.001; const TopoDS_Shape aShape = aBuilder.Shape();
Use constexpr for values that can be computed at compile time:
constexpr int THE_MAX_ITERATIONS = 100; constexpr double THE_PI = 3.14159265358979323846;
Prefer const references to avoid unnecessary copies:
void ProcessShape(const TopoDS_Shape& theShape); for (const TopoDS_Face& aFace : aFaces) { // ... }
This example demonstrates adding a new class BRepLib_MyNewClass to the BRepLib package in the TKTopAlgo toolkit.
1. Create Header and Source Files:
cd src/ModelingAlgorithms/TKTopAlgo/BRepLib touch BRepLib_MyNewClass.hxx BRepLib_MyNewClass.cxx
2. Implement the Class: Add content following all code conventions (see sections 3 and 7).
3. Add Files to Package CMake: Edit src/ModelingAlgorithms/TKTopAlgo/BRepLib/FILES.cmake:
set(OCCT_BRepLib_FILES ... BRepLib_MyNewClass.hxx BRepLib_MyNewClass.cxx )
4. Create a GTest:
cd src/ModelingAlgorithms/TKTopAlgo/GTests touch BRepLib_MyNewClass_Test.cxx
5. Add GTest to CMake: Edit src/ModelingAlgorithms/TKTopAlgo/GTests/FILES.cmake:
set(OCCT_TKTopAlgo_GTests_FILES ... BRepLib_MyNewClass_Test.cxx )
6. Build and Run:
cd build cmake .. -DBUILD_GTEST=ON cmake --build . --config Release ./bin/OpenCascadeGTest --gtest_filter="*MyNewClass*"
build/)mkdir -p build && cd build cmake .. -DCMAKE_BUILD_TYPE=Release -DBUILD_GTEST=ON cmake --build . --config Release --parallel
source build/env.shbuild\env.battests/. Run with DRAWEXE.src/.../GTests/. Enable with -DBUILD_GTEST=ON.BRepPrimAPI_MakeBox, BRepPrimAPI_MakeCylinderBRepAlgoAPI_Fuse, BRepAlgoAPI_Cut, BRepAlgoAPI_CommonTopExp_Explorergp_Trsf with BRepBuilderAPI_Transform| Package | Purpose | Module |
|---|---|---|
gp | Geometric Primitives (Points, Vecs) | FoundationClasses |
Geom | Geometric entities (Curves, Surfaces) | ModelingData |
TopoDS | Topological Data Structures | ModelingData |
TopExp | Exploring topological shapes | ModelingData |
BRepAlgoAPI | High-level modeling algorithms | ModelingAlgorithms |
BRepPrimAPI | Geometric primitives creation | ModelingAlgorithms |
AIS | Application Interactive Services | Visualization |
#include <Standard_Handle.hxx> // occ::handle, occ::down_cast #include <gp_Pnt.hxx> #include <gp_Trsf.hxx> #include <Geom_Circle.hxx> #include <TopoDS.hxx> #include <TopoDS_Shape.hxx> #include <TopoDS_Face.hxx> #include <TopExp_Explorer.hxx> #include <BRep_Builder.hxx> #include <BRepAlgoAPI_Fuse.hxx> #include <BRepBuilderAPI_Transform.hxx> #include <BRepPrimAPI_MakeBox.hxx> #include <Standard_Failure.hxx> #include <NCollection_List.hxx> // NCollection_List<T> #include <NCollection_DataMap.hxx> // NCollection_DataMap<K,V> #include <NCollection_IndexedDataMap.hxx>// NCollection_IndexedDataMap<K,V>
Use Doxygen-style comments with //! prefix:
//! Brief description of the method functionality. //! Additional details if needed. //! @param[in] theInputParam description of input parameter //! @param[out] theOutputParam description of output parameter //! @param[in,out] theInOutParam description of in/out parameter //! @return description of return value Standard_EXPORT bool MethodName(const InputType& theInputParam, OutputType& theOutputParam);
Rules:
@param[in] for input parameters@param[out] for output parameters@param[in,out] for bidirectional parameters@return for return value descriptionEach method MUST be preceded by:
// followed by 98 = signs//================================================================================================= void MyClass::MyMethod(const TopoDS_Shape& theShape) { // Implementation } //================================================================================================= bool MyClass::AnotherMethod() { // Implementation }
DO NOT use old-style function guards:
// WRONG - Do not use this style: //================================================================================================= // purpose: Description of what the method does // function: MyClass::MyMethod //=================================================================================================
Place implementation notes inside the method body:
//================================================================================================= void MyClass::ComplexMethod(const TopoDS_Shape& theShape) { // Using iterative approach for better performance with large shape hierarchies. for (TopExp_Explorer anExp(theShape, TopAbs_FACE); anExp.More(); anExp.Next()) { // Handle degenerate faces separately const TopoDS_Face& aFace = TopoDS::Face(anExp.Current()); // ... } }
src/Module/Toolkit/GTests/ClassName_Test.cxx or PackageName_Test.cxx#include <gtest/gtest.h> #include <MyClass.hxx> // Test fixture (optional) class MyClassTest : public testing::Test { protected: void SetUp() override { // Setup code } }; // Test with fixture TEST_F(MyClassTest, MethodName_Scenario) { // Arrange MyClass anObject; // Act const bool isSuccess = anObject.SomeMethod(); // Assert EXPECT_TRUE(isSuccess); } // Standalone test TEST(MyClassTest, BasicFunctionality) { // Test implementation }
Pattern: TestFixture.MethodOrFeature_Scenario_ExpectedBehavior
Examples:
DE_WrapperTest.Read_ValidSTEPFile_ReturnsTrueBRepAlgoAPI_FuseTest.TwoBoxes_ProducesValidShapegp_PntTest.Distance_SamePoint_ReturnsZeroEXPECT_* - non-fatal (test continues)ASSERT_* - fatal (test stops)Common assertions:
EXPECT_TRUE(condition) / EXPECT_FALSE(condition)EXPECT_EQ(actual, expected) / EXPECT_NE(actual, expected)EXPECT_NEAR(actual, expected, tolerance) - for floating-pointEXPECT_THROW(statement, exception_type) - for exceptions# Build cmake .. cmake --build . # Run all ./bin/OpenCascadeGTest # Run filtered ./bin/OpenCascadeGTest --gtest_filter="*MyClass*" # List tests ./bin/OpenCascadeGTest --gtest_list_tests
| File | Purpose |
|---|---|
src/MODULES.cmake | Defines all modules |
src/Module/TOOLKITS.cmake | Defines toolkits within a module |
src/Module/Toolkit/PACKAGES.cmake | Defines packages within a toolkit |
src/Module/Toolkit/Package/FILES.cmake | Lists source/header files (edit when adding files) |
src/Module/Toolkit/GTests/FILES.cmake | Lists GTest source files |
src/Module/Toolkit/EXTERNLIB.cmake | External library dependencies |
build/env.sh / build/env.bat | Environment setup script |